blob: 173267e382b915df9d3b14a813f3157cd93ee34b [file] [log] [blame]
Adam Langley6f2e7332015-05-15 12:01:29 -07001/* 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
15#include "internal.h"
16
David Benjaminb7d63202022-07-26 13:25:02 -070017#include <assert.h>
Adam Langley6f2e7332015-05-15 12:01:29 -070018#include <stdlib.h>
19
Adam Langley6f2e7332015-05-15 12:01:29 -070020
21#if !defined(OPENSSL_C11_ATOMIC)
22
David Benjaminb7d63202022-07-26 13:25:02 -070023static_assert((CRYPTO_refcount_t)-1 == CRYPTO_REFCOUNT_MAX,
24 "CRYPTO_REFCOUNT_MAX is incorrect");
Adam Langley6f2e7332015-05-15 12:01:29 -070025
26static struct CRYPTO_STATIC_MUTEX g_refcount_lock = CRYPTO_STATIC_MUTEX_INIT;
27
28void CRYPTO_refcount_inc(CRYPTO_refcount_t *count) {
29 CRYPTO_STATIC_MUTEX_lock_write(&g_refcount_lock);
30 if (*count < CRYPTO_REFCOUNT_MAX) {
31 (*count)++;
32 }
David Benjamin29270de2016-05-24 15:28:36 +000033 CRYPTO_STATIC_MUTEX_unlock_write(&g_refcount_lock);
Adam Langley6f2e7332015-05-15 12:01:29 -070034}
35
36int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count) {
37 int ret;
38
39 CRYPTO_STATIC_MUTEX_lock_write(&g_refcount_lock);
40 if (*count == 0) {
41 abort();
42 }
43 if (*count < CRYPTO_REFCOUNT_MAX) {
44 (*count)--;
45 }
46 ret = (*count == 0);
David Benjamin29270de2016-05-24 15:28:36 +000047 CRYPTO_STATIC_MUTEX_unlock_write(&g_refcount_lock);
Adam Langley6f2e7332015-05-15 12:01:29 -070048
49 return ret;
50}
51
David Benjamin808f8322017-08-18 14:06:02 -040052#endif // OPENSSL_C11_ATOMIC