| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | #include "internal.h" |
| 16 |
| 17 | #include <assert.h> |
| 18 | #include <stdlib.h> |
| 19 |
| 20 |
| 21 | // See comment above the typedef of CRYPTO_refcount_t about these tests. |
| 22 | static_assert(alignof(CRYPTO_refcount_t) == alignof(CRYPTO_atomic_u32), |
| 23 | "CRYPTO_refcount_t does not match CRYPTO_atomic_u32 alignment"); |
| 24 | static_assert(sizeof(CRYPTO_refcount_t) == sizeof(CRYPTO_atomic_u32), |
| 25 | "CRYPTO_refcount_t does not match CRYPTO_atomic_u32 size"); |
| 26 |
| 27 | static_assert((CRYPTO_refcount_t)-1 == CRYPTO_REFCOUNT_MAX, |
| 28 | "CRYPTO_REFCOUNT_MAX is incorrect"); |
| 29 |
| 30 | void CRYPTO_refcount_inc(CRYPTO_refcount_t *in_count) { |
| 31 | CRYPTO_atomic_u32 *count = (CRYPTO_atomic_u32 *)in_count; |
| 32 | uint32_t expected = CRYPTO_atomic_load_u32(count); |
| 33 |
| 34 | while (expected != CRYPTO_REFCOUNT_MAX) { |
| 35 | uint32_t new_value = expected + 1; |
| 36 | if (CRYPTO_atomic_compare_exchange_weak_u32(count, &expected, new_value)) { |
| 37 | break; |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 |
| 42 | int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *in_count) { |
| 43 | CRYPTO_atomic_u32 *count = (CRYPTO_atomic_u32 *)in_count; |
| 44 | uint32_t expected = CRYPTO_atomic_load_u32(count); |
| 45 |
| 46 | for (;;) { |
| 47 | if (expected == 0) { |
| 48 | abort(); |
| 49 | } else if (expected == CRYPTO_REFCOUNT_MAX) { |
| 50 | return 0; |
| 51 | } else { |
| 52 | const uint32_t new_value = expected - 1; |
| 53 | if (CRYPTO_atomic_compare_exchange_weak_u32(count, &expected, |
| 54 | new_value)) { |
| 55 | return new_value == 0; |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 |