| 1 |
// Copyright (c) 2015, Google Inc. |
| 2 |
// SPDX-License-Identifier: ISC |
| 3 |
|
| 4 |
#include "internal.h" |
| 5 |
|
| 6 |
|
| 7 |
#if defined(OPENSSL_C11_ATOMIC) |
| 8 |
|
| 9 |
#include <assert.h> |
| 10 |
#include <stdalign.h> |
| 11 |
#include <stdatomic.h> |
| 12 |
#include <stdlib.h> |
| 13 |
|
| 14 |
#include <openssl/type_check.h> |
| 15 |
|
| 16 |
|
| 17 |
// See comment above the typedef of CRYPTO_refcount_t about these tests. |
| 18 |
OPENSSL_STATIC_ASSERT(alignof(CRYPTO_refcount_t) == alignof(_Atomic CRYPTO_refcount_t), |
| 19 |
_Atomic_alters_the_needed_alignment_of_a_reference_count) |
| 20 |
OPENSSL_STATIC_ASSERT(sizeof(CRYPTO_refcount_t) == sizeof(_Atomic CRYPTO_refcount_t), |
| 21 |
_Atomic_alters_the_size_of_a_reference_count) |
| 22 |
|
| 23 |
OPENSSL_STATIC_ASSERT((CRYPTO_refcount_t)-1 == CRYPTO_REFCOUNT_MAX, |
| 24 |
CRYPTO_REFCOUNT_MAX_is_incorrect) |
| 25 |
|
| 26 |
void CRYPTO_refcount_inc(CRYPTO_refcount_t *in_count) { |
| 27 |
_Atomic CRYPTO_refcount_t *count = (_Atomic CRYPTO_refcount_t *) in_count; |
| 28 |
uint32_t expected = atomic_load(count); |
| 29 |
|
| 30 |
while (expected != CRYPTO_REFCOUNT_MAX) { |
| 31 |
uint32_t new_value = expected + 1; |
| 32 |
if (atomic_compare_exchange_weak(count, &expected, new_value)) { |
| 33 |
break; |
| 34 |
} |
| 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 |
|
| 42 |
for (;;) { |
| 43 |
if (expected == 0) { |
| 44 |
abort(); |
| 45 |
} else if (expected == CRYPTO_REFCOUNT_MAX) { |
| 46 |
return 0; |
| 47 |
} else { |
| 48 |
const uint32_t new_value = expected - 1; |
| 49 |
if (atomic_compare_exchange_weak(count, &expected, new_value)) { |
| 50 |
return new_value == 0; |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
|
| 56 |
#endif // OPENSSL_C11_ATOMIC |