refcount_c11.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /* Copyright (c) 2015, Google Inc.
  2. *
  3. * Permission to use, copy, modify, and/or distribute this software for any
  4. * purpose with or without fee is hereby granted, provided that the above
  5. * copyright notice and this permission notice appear in all copies.
  6. *
  7. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  10. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  12. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
  14. #include "internal.h"
  15. #if defined(OPENSSL_C11_ATOMIC)
  16. #include <assert.h>
  17. #include <stdalign.h>
  18. #include <stdatomic.h>
  19. #include <stdlib.h>
  20. #include <openssl/type_check.h>
  21. // See comment above the typedef of CRYPTO_refcount_t about these tests.
  22. static_assert(alignof(CRYPTO_refcount_t) == alignof(_Atomic CRYPTO_refcount_t),
  23. "_Atomic alters the needed alignment of a reference count");
  24. static_assert(sizeof(CRYPTO_refcount_t) == sizeof(_Atomic CRYPTO_refcount_t),
  25. "_Atomic alters the size of a reference count");
  26. static_assert((CRYPTO_refcount_t)-1 == CRYPTO_REFCOUNT_MAX,
  27. "CRYPTO_REFCOUNT_MAX is incorrect");
  28. void CRYPTO_refcount_inc(CRYPTO_refcount_t *in_count) {
  29. _Atomic CRYPTO_refcount_t *count = (_Atomic CRYPTO_refcount_t *) in_count;
  30. uint32_t expected = atomic_load(count);
  31. while (expected != CRYPTO_REFCOUNT_MAX) {
  32. uint32_t new_value = expected + 1;
  33. if (atomic_compare_exchange_weak(count, &expected, new_value)) {
  34. break;
  35. }
  36. }
  37. }
  38. int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *in_count) {
  39. _Atomic CRYPTO_refcount_t *count = (_Atomic CRYPTO_refcount_t *)in_count;
  40. uint32_t expected = atomic_load(count);
  41. for (;;) {
  42. if (expected == 0) {
  43. abort();
  44. } else if (expected == CRYPTO_REFCOUNT_MAX) {
  45. return 0;
  46. } else {
  47. const uint32_t new_value = expected - 1;
  48. if (atomic_compare_exchange_weak(count, &expected, new_value)) {
  49. return new_value == 0;
  50. }
  51. }
  52. }
  53. }
  54. #endif // OPENSSL_C11_ATOMIC