Skip to content

Improved Avx2 + Scalar Base64 Encoding - #29178

Closed
Nick-Nuon wants to merge 19 commits into
openssl:masterfrom
Nick-Nuon:New_AVX2
Closed

Nick-Nuon wants to merge 19 commits into
openssl:masterfrom
Nick-Nuon:New_AVX2

Conversation

@Nick-Nuon

Copy link
Copy Markdown
Contributor

This is a suggested improvement to the base64 encoding kernel of OpenSSL following issue #11460 raised by @byronhe (Thanks to @nhorman for keeping the issue open). The objective is to improve base64 encoding speed on x64 systems with AVX support. Our approach is based on a similar function part of the simdutf C++ library which is widely deployed (e.g., in main browsers).

The following benchmarks were made using gcc, on Arch Linux with a Ryzen 5600 CPU. The benchmarking tools as well as the results are made available here:
https://github.com/Nick-Nuon/OpenSSL_B64_benchmarks.

API functions EVP_EncodeUpdate and EVP_EncodeFinal

Our first improvement affects these two API functions.

We benchmarked with three datasets:
-A subset of the Enron emails dataset
-A number of small images
-The .mobi version of 'Pride and Prejudice' (24.2 mb file)

Standard Alphabet

Dataset Original (GB/s) Ours (GB/s) Improvement ×
Email 2.01 17.28 8.597014925
Images 2.04 15.99 7.838235294
One "Big" file 2.31 11.31 4.896103896

Standard Alphabet / PEM mode

Dataset Original (GB/s) Ours (GB/s) Improvement ×
Email 1.9 14.59 7.678947368
Images 2.02 13.95 6.905940594
One "Big" file 2.09 10.57 5.057416268

SRP Alphabet

Dataset Original (GB/s) Ours (GB/s) Improvement ×
Email 2.02 10.12 5.00990099
Images 2.01 9.56 4.756218905
One "Big" file 2.09 9.15 4.377990431

SRP Alphabet/ PEM mode

Dataset Original (GB/s) Ours (GB/s) Improvement ×
Email 2.03 10.14 4.995073892
Images 2.01 9.59 4.771144279
One "Big" file 2.1 9.29 4.423809524

CLI

There are also improvements with respect to the CLI. Benchmarking against the "big" file we get:

Original:

Benchmark 1: ./apps/openssl enc -base64 -A -bufsize 65536 -in "/home/my_username/b64_workspace/OpenSSL_B64_benchmarks/benchmark_data/one_big_file/pg1342-images-kf8.mobi" > /dev/null
  Time (mean ± σ):      21.3 ms ±   1.2 ms    [User: 15.5 ms, System: 5.5 ms]
  Range (min … max):    18.6 ms …  25.9 ms    2000 runs

Ours:

Benchmark 1: ./apps/openssl enc -base64 -A -bufsize 65536 -in "/home/my_username/b64_workspace/OpenSSL_B64_benchmarks/benchmark_data/one_big_file/pg1342-images-kf8.mobi" > /dev/null
  Time (mean ± σ):       6.7 ms ±   0.4 ms    [User: 2.6 ms, System: 4.1 ms]
  Range (min … max):     5.6 ms …   8.9 ms    2000 runs

Taken from:
https://github.com/Nick-Nuon/OpenSSL_B64_benchmarks/tree/main/CLI_hyperfine_results
https://github.com/Nick-Nuon/OpenSSL_B64_benchmarks/tree/main/CLI_hyperfine_control

In order to test the effectiveness of this PR for CLI input of small sizes , we use a synthetic dataset of randomly generated files, increasing by intervals of 10000 bytes, we then use a linear regression to plot the performance of the old kernel vs our improved one.

✅ Main fit: y = 0.000000277739 * x + 0.935148975992
   - Slope (ms/byte):   0.000000277739
   - Slope (ms/MiB):    0.291230914693
✅ Control fit: y = 0.000000388180 * x + 0.987760805850
   - Slope (ms/MiB): 0.407035921818

Base64 small-size benchmark

Taken from:
https://github.com/Nick-Nuon/OpenSSL_B64_benchmarks/tree/main/CLI_smallsize_control
https://github.com/Nick-Nuon/OpenSSL_B64_benchmarks/tree/main/CLI_smallsize_results

Newline insertions at custom intervals

Originally, the OpenSSL base64 encoding kernel includes a buffer of ctx->length. It is possible by changing the ctx->length value to change the interval at which newlines are inserted.
When said value is a multiple of three, this translates to newline insertion at multiple of fours. Separate SIMD optimized branches were created to deals with different scenarios:

  • greater or equal than 32 ( excluding insertion at 64 bytes, which has its own branch)
  • greater or equal than 16
  • equal to 12
  • equal to 8
  • equal to 4

For the sake of brevity, we only post the graphs for the first case (which is overall also the best performing) to give a rough idea:

Base64 greater than equal 32 benchmark

Base64 greater than equal 32 benchmark

We briefly summarize the rest, as we deem them to be rare.

Amongst insertion at multiples of fours, the case where the insertion is done at 12 byte intervals is the worse at around 2x improvement over baselines, with the rest varying between the two extremes.

The cases where ctx->lengths isn't a multiple of threes corresponds to splitting the input into constant intervals(up to 80 bytes) and then calling the encode function on it.
These are not optimized and are about 30% slower than baseline in the worse cases.

For more details, we invite interested readers to delve deeper into the logs , or better yet, replicate them on their own hardware as they are small enough to inspect with the good old Mark I eyeball.

https://github.com/Nick-Nuon/OpenSSL_B64_benchmarks/tree/main/API_results
https://github.com/Nick-Nuon/OpenSSL_B64_benchmarks/tree/main/API_control
https://github.com/Nick-Nuon/OpenSSL_B64_benchmarks/tree/main/custom_interval_results

All tests pass locally with default build options. As I couldn't find a test that dealt specifically with custom newline insertions, I took the liberty to include one as to ensure a drop-in replacement.

@openssl-machine openssl-machine added the hold: cla required The contributor needs to submit a license agreement. label Nov 20, 2025
@t8m t8m added branch: master Applies to master branch triaged: feature The issue/pr requests/adds a feature labels Nov 20, 2025
Comment thread test/test_base64_simdutf.c Resolved
Comment thread test/test_base64_simdutf.c Resolved
@beldmit

beldmit commented Nov 21, 2025

Copy link
Copy Markdown
Member

Does it imply compile-time detection of AVX support?

@t8m

t8m commented Nov 21, 2025

Copy link
Copy Markdown
Member

To be able to accept this code we need CLA(s) signed by all the authors of the code. Is it just you @Nick-Nuon or are there multiple?

@t8m

t8m commented Nov 21, 2025

Copy link
Copy Markdown
Member

Does it imply compile-time detection of AVX support?

Yes, it looks like so. This needs to be able to fall back to non-AVX2 code if the instructions are not present.

@Nick-Nuon

Nick-Nuon commented Nov 21, 2025 •

Copy link
Copy Markdown
Contributor Author

To be able to accept this code we need CLA(s) signed by all the authors of the code. Is it just you @Nick-Nuon or are there multiple?

I would also include @lemire as large parts of the PR are adapted from his work/simdutf. Though only I appear in the commit history, I don't think this PR would have been possible without his feedback and encouragement (or at least it would have taken much longer).

@Nick-Nuon

Copy link
Copy Markdown
Contributor Author

Does it imply compile-time detection of AVX support?

Yes, it looks like so. This needs to be able to fall back to non-AVX2 code if the instructions are not present.

Gotcha, going out for a jog, but will take a look at it this morning.

@lemire

lemire commented Nov 21, 2025

Copy link
Copy Markdown

@Nick-Nuon I love getting credit, but no, I did not write a single line of code in this PR and I have no right to any of it.

@openssl-machine openssl-machine removed the hold: cla required The contributor needs to submit a license agreement. label Nov 22, 2025
Comment thread crypto/evp/encode.c Resolved
@Nick-Nuon

Copy link
Copy Markdown
Contributor Author

Does it imply compile-time detection of AVX support?

Yes, it looks like so. This needs to be able to fall back to non-AVX2 code if the instructions are not present.

@beldmit @t8m Thanks for taking the time to review. I might be reading too much into your comments , but after looking around a bit ,I added a check against OPENSSL_ia32cap_P just in case.

@slontis

slontis commented Nov 24, 2025

Copy link
Copy Markdown
Member

@beldmit @t8m Thanks for taking the time to review. I might be reading too much into your comments , but after looking around a bit ,I added a check against OPENSSL_ia32cap_P just in case.

You interpreted their comments correctly. In case something goes wrong on a particular platform, the platform can then
clear the related flag and bypass the assembler (and then not segfault :))

OpenSSL does not seem to use intrinsics anywhere else that I know of, are there likely to be any problems with alignment of in/out parameters?

@beldmit

beldmit commented Nov 24, 2025

Copy link
Copy Markdown
Member

Thank you for your efforts! Do I correctly understand, that now the code will compile when the compiler support AVX instructions, and there is no need to provide any explicit flags?

@t8m t8m left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As this removes lots of special handling in the Base64 BIO code, I'd like to ask @vdukhovni for a review as he was changing that code not so long ago.

@Nick-Nuon

Copy link
Copy Markdown
Contributor Author

@beldmit @t8m Thanks for taking the time to review. I might be reading too much into your comments , but after looking around a bit ,I added a check against OPENSSL_ia32cap_P just in case.

You interpreted their comments correctly. In case something goes wrong on a particular platform, the platform can then clear the related flag and bypass the assembler (and then not segfault :))

OpenSSL does not seem to use intrinsics anywhere else that I know of, are there likely to be any problems with alignment of in/out parameters?

AFAIK , not that I know of. I used _mm_loadu_si128 and _mm256_storeu_si256 intrinsics. There might be a small performance hit (that is IMO offset by development time and complexity), but if there are issues beyond this , they lie outside my current field of knowledge.

@Nick-Nuon

Nick-Nuon commented Nov 24, 2025 •

Copy link
Copy Markdown
Contributor Author

Thank you for your efforts! Do I correctly understand, that now the code will compile when the compiler support AVX instructions, and there is no need to provide any explicit flags?

You're welcome!

As of now, technically it will compile but for the AVX2 path to be activated, locally , I have to pass -mavx2 as compiler flag to CMake. I'll see what I can do about it.

Comment thread crypto/evp/enc_b64_avx2.c Outdated
@@ -0,0 +1,634 @@
#include <string.h>

#ifdef __AVX2__

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Nick-Nuon The __AVX2__ flag is set at compile time (not runtime). Often, openssl won't be build specifically with assumed AVX2 support at compile time. So __AVX2__ will just not be defined and this code won't built.

This may change in the future. Some distributions are planning x86_64_v3 ports such as Arch although it is slow going.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, CachyOS already supported x86-64-v3 and x86-64-v4.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you. Yes, so in that case, then some users would get openssl compiled for recent processors. But that's not very typical.

https://wiki.cachyos.org/cachyos_basic/why_cachyos/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For me, it's a chicken or egg question, as x86-64-v3 distributions are not widely available, and people generally choose to consider only runtime dispatch rather than compile-time dispatch (or both), which in turn leads to the performance benefits of x86-64-v3 not being perceived as significant enough to be worthwhile.

Since this PR seems to be OpenSSL's first attempt to use intrinsics for performance optimization, it would be nice to consider both runtime and compile-time dispatch, especially in conjunction with LTO and x86-64-v3, which may provide more inlining opportunities to maximize performance.

@lemire lemire Dec 1, 2025 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that if the OpenSSL community says 'no need for runtime dispatching, let us rely on compile-time' then @Nick-Nuon would be happy to simplify the code.

Alternatively, it is possible to modify the existing code so that the runtime dispatching is disabled when __AVX2__ is defined.

Since this PR seems to be OpenSSL's first attempt to use intrinsics for performance optimization

This is an important remark. Nick's PR should be viewed as a step forward in this direction. Once this PR is merged, it can serve as a model for future similar PRs.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OpenSSL's assembly typically does run time dispatching.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, it is possible to modify the existing code so that the runtime dispatching is disabled when __AVX2__ is defined.

That's exactly what I meant, support runtime dispatching but eliminate it when feasible to promote optimization.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OpenSSL's assembly typically does run time dispatching.

Yes, it's an OpenSSL tradition, but uninlineable asm needs to follow the calling convention anyway, in which case the runtime dispatching overhead is probably nothing in comparison. But intrinsics open up new possibilities, so I hope it's perfect from the start so that it can be a reference for future PR-like best practices.

Comment thread crypto/evp/encode.c Outdated
j = evp_encodeblock_int(ctx, out, in, inl - (inl % ctx->length),
&wrap_cnt);
} else {
#if defined(HAS_IA32CAP) && defined(__AVX2__)

This comment was marked as resolved.

This comment was marked as resolved.

Comment thread crypto/evp/encode.c Outdated
return evp_encodeblock_int(NULL, t, f, dlen);
int wrap_cnt = 0;

#if defined(HAS_IA32CAP) && defined(__AVX2__)

This comment was marked as resolved.

This comment was marked as resolved.

Comment thread crypto/evp/enc_b64_avx2.c Outdated
@@ -0,0 +1,634 @@
#include <string.h>

#ifdef __AVX2__

This comment was marked as resolved.

@Nick-Nuon

Nick-Nuon commented Dec 20, 2025 •

Copy link
Copy Markdown
Contributor Author

I still see 2 conflicts

They are gone now. Working on it, still taking care of the clang format/code style check.

@Nick-Nuon

Nick-Nuon commented Dec 21, 2025 •

Copy link
Copy Markdown
Contributor Author

Coding style test should be good to go!

@beldmit beldmit left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@paulidale paulidale added approval: done This pull request has the required number of approvals triaged: performance The issue/pr reports/fixes a performance concern and removed approval: review pending This pull request needs review by a committer labels Dec 22, 2025
@openssl-machine openssl-machine added approval: ready to merge The 24 hour grace period has passed, ready to merge and removed approval: done This pull request has the required number of approvals labels Dec 23, 2025
@openssl-machine

Copy link
Copy Markdown
Collaborator

This pull request is ready to merge

openssl-machine pushed a commit that referenced this pull request Dec 23, 2025
Reviewed-by: Dmitry Belyavskiy <[email protected]>
Reviewed-by: Paul Dale <[email protected]>
(Merged from #29178)
@paulidale

Copy link
Copy Markdown
Contributor

Squashed and merged. Thanks for persevering and getting this worthwhile improvement in.

@paulidale paulidale closed this Dec 23, 2025
@Nick-Nuon

Copy link
Copy Markdown
Contributor Author

Squashed and merged. Thanks for persevering and getting this worthwhile improvement in.

You welcome, it was a pleasure working on it.

Merry Christmas everyone.

@t8m t8m added the tests: present The PR has suitable tests present label Dec 29, 2025
nhorman added a commit to nhorman/openssl that referenced this pull request Jan 13, 2026
Recently, PR openssl#29178 introduced
some refactoring that sped up our base64 encoding, but in so doing
dropped the ability for our base64 BIO's to not include newlines on
write (the BIO_FLAG_BASE64_NO_NL flag).

Fix it by checking the BIO flags whenever the base64 bio starts a new
encoder, and, if set, sets the corresponding EVP_ENCODE_CTX_NO_NEWLINES
flags in the underlying encoder.

Fixes openssl#29618
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approval: ready to merge The 24 hour grace period has passed, ready to merge branch: master Applies to master branch tests: present The PR has suitable tests present triaged: feature The issue/pr requests/adds a feature triaged: performance The issue/pr reports/fixes a performance concern

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants