Add internal functions to fetch a refcount
[openssl.git] / include / internal / refcount.h
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 #ifndef HEADER_INTERNAL_REFCOUNT_H
10 # define HEADER_INTERNAL_REFCOUNT_H
11
12 # if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
13      && !defined(__STDC_NO_ATOMICS__)
14 # include <stdatomic.h>
15 # define HAVE_C11_ATOMICS
16 # endif
17
18 # if defined(HAVE_C11_ATOMICS) && defined(ATOMIC_INT_LOCK_FREE) \
19      && ATOMIC_INT_LOCK_FREE > 0
20
21 # define HAVE_ATOMICS 1
22
23 typedef _Atomic int CRYPTO_REF_COUNT;
24
25 static ossl_inline int CRYPTO_GET_REF(_Atomic int *val, int *ret, void *lock)
26 {
27     *ret = atomic_fetch_add_explicit(val, 0, memory_order_relaxed);
28     return 1;
29 }
30
31 static ossl_inline int CRYPTO_UP_REF(_Atomic int *val, int *ret, void *lock)
32 {
33     *ret = atomic_fetch_add_explicit(val, 1, memory_order_relaxed) + 1;
34     return 1;
35 }
36
37 static ossl_inline int CRYPTO_DOWN_REF(_Atomic int *val, int *ret, void *lock)
38 {
39     *ret = atomic_fetch_sub_explicit(val, 1, memory_order_release) - 1;
40     if (*ret == 0)
41         atomic_thread_fence(memory_order_acquire);
42     return 1;
43 }
44
45 # elif defined(__GNUC__) && defined(__ATOMIC_RELAXED) && __GCC_ATOMIC_INT_LOCK_FREE > 0
46
47 # define HAVE_ATOMICS 1
48
49 typedef int CRYPTO_REF_COUNT;
50
51 static ossl_inline int CRYPTO_GET_REF(_Atomic int *val, int *ret, void *lock)
52 {
53     *ret = __atomic_fetch_add(val, 0, __ATOMIC_RELAXED);
54     return 1;
55 }
56
57 static ossl_inline int CRYPTO_UP_REF(int *val, int *ret, void *lock)
58 {
59     *ret = __atomic_fetch_add(val, 1, __ATOMIC_RELAXED) + 1;
60     return 1;
61 }
62
63 static ossl_inline int CRYPTO_DOWN_REF(int *val, int *ret, void *lock)
64 {
65     *ret = __atomic_fetch_sub(val, 1, __ATOMIC_RELEASE) - 1;
66     if (*ret == 0)
67         __atomic_thread_fence(__ATOMIC_ACQUIRE);
68     return 1;
69 }
70
71 # else
72
73 typedef int CRYPTO_REF_COUNT;
74
75 # define CRYPTO_GET_REF(val, ret, lock) CRYPTO_atomic_add(val, 0, ret, lock)
76 # define CRYPTO_UP_REF(val, ret, lock) CRYPTO_atomic_add(val, 1, ret, lock)
77 # define CRYPTO_DOWN_REF(val, ret, lock) CRYPTO_atomic_add(val, -1, ret, lock)
78
79 # endif
80 #endif