Skip to content

RW locks are bad for performance #20715

Closed

Description

@nicowilliams

OpenSSL uses read-write locks (e.g., pthread_rwlock_t on POSIX systems). Often these locks are used to protect data structures that should not change often, like providers lists.

Read-write locks are not a good thread synchronization mechanism. Readers can block when a writer gets the lock, and good rw lock implementations will not allow writer starvation, which means that if there are threads that want to write, then some threads that want to read will block.

For example, the code highlighted in the stack trace on #20698 takes a read-write lock for writing just in case it has to remove providers from the providers list, but this serializes all readers.

For global data such as configuration (e.g., trust anchors), providers lists, engines, a much better technique is read-copy-update (RCU), as is used in the Linux kernel. Then readers need never block due to writers. Writers are still serialized, but mostly not blocked by readers.

Until recently there were not a lot of RCU implementations for use in user-land, and I'm not sure if there is a portable one that is license-compatible with OpenSSL. I've been using a C library for years that I maintain and that has similar performance characteristics to user-land RCU, a compatible license, and a very simple API. RCU can be faster and better, but anything that is better than read-write locks is going to work well for OpenSSL.

With any RCU-like scheme it is critical to have values be immutable once published. Global configuration information, providers lists, etc. should all be amenable to being treated as immuntable once produced. Immutable values can be and must be destroyed when there are no references left to them, naturally, but must not be modified between publication and the last reference disappearing.

My "thread-safe variable" API is just init/destroy and get/release/set, where a get returns the current value of the "variable" and that value is then safe to use in the same thread until the next call to get/release/set in the same thread (or the thread exits), and no value is destructed until all references are gone, with no reader blocking any writer, and no writer blocking any reader (writers get serialized). get reads the variable and acquires a reference on its current value (doing both operations atomically), and it releases the reference on the previously-obtained value in the same thread, if one had been. There are similar mechanisms in Clojure, and in Haskell, etc., but the one I'm referring to is a C library with a permissive license.

Activity

  1. added
    issue: bug report
    on Apr 11, 2023
  2. changed the title [-]RW locks are bad[/-] [+]RW locks are bad for performance[/+] on Apr 11, 2023
  3. davidben commented on Apr 11, 2023

    @davidben
    Contributor

    In addition to rwlocks performing badly once you have any writers, reader-only workloads aren't free. Even a good rwlock implementation fundamentally has to write somewhere when taking a read lock. This means you still have some cacheline contention in heavily threaded servers.

    We didn't introduce the vast sea of global, mutable state that OpenSSL 3.x did, but even without that we see some impacts of this in BoringSSL and have plans to rework things. E.g., #5158 discussed a common pattern in OpenSSL that tends to cause this, which a better API would have avoided more naturally. And with OpenSSL 3.x levels of mutable state, I expect these kinds of problems would only compound.

  4. kroeckx commented on Apr 11, 2023

    @kroeckx
    Member
  5. paulidale commented on Apr 11, 2023

    @paulidale
    Contributor

    It's been mentioned before, but a call that effectively freezes the state of a libctx & it's store could avoid lots of locking.

    The 3.x provider design was too flexible in some areas...
    (over engineered is an apt description in some ways)

  6. nicowilliams commented on Apr 11, 2023

    @nicowilliams
    Author

    You can say no threading w/o atomics, and if you're not threading then the atomics are all stubs. And if you have threads but no atomics you can use mutexes to implement the atomics. That said, you're going to have atomics on any recent platform that has threads.

  7. nicowilliams commented on Apr 11, 2023

    @nicowilliams
    Author

    It's been mentioned before, but a call that effectively freezes the state of a libctx & it's store could avoid lots of locking.

    That's making it immutable. With RCU and RCU-like sync schemes you can have that cake and eat it too by allowing mutation to happen by installing new versions that once installed are immutable.

    This sort of thing would be great for, for example, dealing with having to reload certificates when they expire are are close to expiration (or when there's new ones to switch to). This could be done by apps or the library, either way, but the set of loaded certificates (and private keys) are immutable, and reloading consists of replacing the previous set with the new set without having to do anything special about threads using the old set. RCU-ish schemes make that easy.

  8. added
    triaged: feature
    and removed
    issue: bug report
    on Apr 12, 2023
  9. hlandau commented on Apr 12, 2023

    @hlandau
    Member

    These are interesting ideas. I would support requiring atomics for threaded builds in 4.x as all platforms I know of use atomics to implement higher level primitives anyway. The only issue I see is defining bindings for all supported platforms as there is no widely available standard API for atomics, but I see that as a readily surmountable problem.

    We have had serious performance issues with 3.0. Some of this is caused by cache line contention in locks, so the approaches discussed here are very interesting.

    Worth noting that recently we have introduced an internal mutex type, which uses pthread_mutex_t rather than pthread_rwlock_t. This has the advantage of being infallible unlike our CRYPTO_RWLOCK API. Since it's a private API, we can also revise it as needed. Where we do use mutexes in the future, we could consider replacing all internal, non-API visible usage of RWLOCK with our new mutex code.

  10. hlandau commented on Apr 12, 2023

    @hlandau
    Member

    Worth noting that the linked RCU implementation uses a pthread key per RCU item. This is a problem since OS implementations can impose a limit on the number of keys which can be created in a process. musl libc imposes a limit of 128 (and also takes a rwlock during key creation). This is both a problem in itself but we also need to consider any impacts on the application using OpenSSL — if we significantly increase our pthread key consumption, it could cause problems by causing an application to hit this limit.

    So if we adopt RCU in the future we will need a different implementation approach. We already have some platform abstraction code for thread locals but on *nix this just uses pthread keys.

  11. geofft commented on Apr 14, 2023

    @geofft

    It's been mentioned before, but a call that effectively freezes the state of a libctx & it's store could avoid lots of locking.

    I believe this is #15600.

    Until recently there were not a lot of RCU implementations for use in user-land, and I'm not sure if there is a portable one that is license-compatible with OpenSSL.

    https://paulmck.livejournal.com/69622.html discusses a few RCUish libraries in Rust, all of which are license-compatible (dual Apache 2/MIT) but not language-compatible. I mention it because they might be starting points if you're working on adapting Nico's library or writing your own, and also because that blog post is a good overview of what the various APIs and design choices might be. I'm going to guess they all assume atomics, though!

  12. nicowilliams commented on May 4, 2023

    @nicowilliams
    Author

    Worth noting that the linked RCU implementation uses a pthread key per RCU item. This is a problem since OS implementations can impose a limit on the number of keys which can be created in a process. musl libc imposes a limit of 128 (and also takes a rwlock during key creation). This is both a problem in itself but we also need to consider any impacts on the application using OpenSSL — if we significantly increase our pthread key consumption, it could cause problems by causing an application to hit this limit.

    The reason this uses a key per instance is just laziness, and my application needing only a handful of these thigns.

    if we significantly increase our pthread key consumption, it could cause problems by causing an application to hit this limit.

    I've also hit this limit in testing -- apparently glibc has up to 256, which is precious few.

    I will fix this. Just one pthread key should be sufficient -- its purpose is to drive destructor calling.

    I also need to add a function for calling from DllMain().

    FYI I recently made sure that ctp is thread-sanitizer- and Helgrind-clean. (There had been a bug in the thread_safe_var_init() functions that doesn't bite in production, and also two assert()s had races that also didn't bite in production because they were disabled.)

    Thanks for taking a look at this!

  13. nicowilliams commented on May 4, 2023

    @nicowilliams
    Author

    Also, there are other C RCU-like APIs and implementations out there. You don't have to adopt mine. Mine however has been in use in production since early 2016 without any problems.

  14. nicowilliams commented on May 4, 2023

    @nicowilliams
    Author

    https://paulmck.livejournal.com/69622.html discusses a few RCUish libraries in Rust, all of which are license-compatible (dual Apache 2/MIT) but not language-compatible. I mention it because they might be starting points if you're working on adapting Nico's library or writing your own, and also because that blog post is a good overview of what the various APIs and design choices might be. I'm going to guess they all assume atomics, though!

    Yes, they all need atomics / memory barriers.

    In kernel-land you can play games like the Linux kernel does where you can just make the writer wait long enough and disable preemption for readers executing in RCU critical sections. Solaris/Illumos has different scheme where the writer cross-calls all the other CPUs to update per-CPU (thread, if it were use-land) copies of the thing being written, also with readers blocking cross-calls while executing in critical sections. In user-land there's no way to disable preemption and also no way to guarantee that code in critical sections runs to completion within a "grace period".

    Thus user-land RCU APIs generally need memory barriers on the read side, which means that reads can't be remotely as fast as in kernel-land RCU, but they are still much much much faster than rw locks not least because RCU is non-blocking for readers. The non-blocking part is critical.

    Since one has to end up using memory barriers, one can end up having a much nicer API than kernel-land RCU. In the kernel-land case one has to declare critical sections on the reader side, and on the writer side one has to get a lock, write, then wait for a grace period -- compare to essentially two functions in my case (get and set).

  15. 135 remaining items

  16. nhorman commented on Oct 16, 2023

    @nhorman
    Contributor

    there seems to be alot of behavioral minutue in the provider code at the moment (lots of locking/unlocking to avoid recursive deadlocks when we init child providers for instance). I think this goes above and beyond just doing a lock replacement. This is going to be a significant work effort I think.

  17. nicowilliams commented on Oct 16, 2023

    @nicowilliams
    Author

    Yes, it's going to be a large effort, and for the moment RCU gets you a 20% break :)

  18. nicowilliams commented on Oct 16, 2023

    @nicowilliams
    Author

    (The hash tables need their own RCU critical section for reading due to their API implying that hash tables are atomic, though you could expose unprotected lower level hash table APIs that could be used under a common RCU critical section.)

    Replying to myself to emphasize this parenthetical. RCU composes very well, but only if one has "unlocked" versions of all the read APIs to be composed in one RCU critical section.

    The point is that it's pretty impressive to be getting a 20% performance improvement without having done the work to get the benefit of RCU critical section sharing! (Nor the work to reduce locking in the provider list code, for that matter.) It's true that I'd been hoping for much more than 20%, but this is 20% without doing the hard work that needs to be done [in the provider list code]!

  19. nhorman commented on Oct 20, 2023

    @nhorman
    Contributor

    more updates. Its still a bit of a mess, but I managed to convert the OSSL_PROVIDER list to a hash table, which enabled me to remove some of the refcounting and locking from that API (though not entirely). As a result, new performance data from the providerdoall perf test, which just iteratively runs OSSL_PROVIDER_do_all, couinting the number of providers found:
    providerdoall_performance

    its still not very parallelized, but its linear increase is smaller, and offers a consistent performance improvement (between 5% at low thread counts up to ~40% at higher thread counts)

  20. added
    triaged: performance
    on Nov 2, 2023
  21. nhorman commented on Nov 8, 2023

    @nhorman
    Contributor

    sorry, its been awhile since I updated here. I've been working on the windows implementation. Currently, its mostly working (tracking down an odd deadlock that I'm sure relates to my misunderstanding of how the windows Interlocked api works). Should have an update there soon

  22. nhorman commented on Feb 1, 2024

    @nhorman
    Contributor

    RCU has been merged! From here I'm going to start addressing individual code points that might benefit from RCU conversion. I think this can be closed.

  23. moved this from In progress to Done in Project Boardon Feb 1, 2024
  24. nicowilliams commented on Feb 1, 2024

    @nicowilliams
    Author

    @nhorman yay!

    Either need new issues to track the work of making the rest of the codebase use RCU, or this issue should be the one used as an umbrella for tracking that work. The title of this one being "RW locks are bad for performance", I can't quite tell whether the (my) intent was to say "implement RCU" or "implement RCU and use it" :) :)

  25. nicowilliams commented on Feb 1, 2024

    @nicowilliams
    Author

    Great work by the way!

  26. nicowilliams commented on Feb 1, 2024

    @nicowilliams
    Author

    I would suggest re-opening this issue and using it as an umbrella for the work of switching the codebase from RW locks to the new RCU APIs.

  27. nhorman commented on Feb 1, 2024

    @nhorman
    Contributor

    We have that currently:
    openssl/project#441

    There are also a myriad of other issues that need to be aggregated together I think

  28. mattcaswell commented on Feb 1, 2024

    @mattcaswell
    Member
  29. nicowilliams commented on Feb 1, 2024

    @nicowilliams
    Author

    @mattcaswell perfect! I'll track that. Thanks!

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

Metadata

Metadata

Assignees

Labels

help wantedtriaged: featuretriaged: performance

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions