refcount.h 2.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
/*
 * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
 *
 * Licensed under the OpenSSL license (the "License").  You may not use
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */
#ifndef HEADER_INTERNAL_REFCOUNT_H
# define HEADER_INTERNAL_REFCOUNT_H

12 13
# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
     && !defined(__STDC_NO_ATOMICS__)
14 15 16 17
# include <stdatomic.h>
# define HAVE_C11_ATOMICS
# endif

18 19
# if defined(HAVE_C11_ATOMICS) && defined(ATOMIC_INT_LOCK_FREE) \
     && ATOMIC_INT_LOCK_FREE > 0
20 21 22 23 24

# define HAVE_ATOMICS 1

typedef _Atomic int CRYPTO_REF_COUNT;

25 26 27 28 29 30
static ossl_inline int CRYPTO_GET_REF(_Atomic int *val, int *ret, void *lock)
{
    *ret = atomic_fetch_add_explicit(val, 0, memory_order_relaxed);
    return 1;
}

31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
static ossl_inline int CRYPTO_UP_REF(_Atomic int *val, int *ret, void *lock)
{
    *ret = atomic_fetch_add_explicit(val, 1, memory_order_relaxed) + 1;
    return 1;
}

static ossl_inline int CRYPTO_DOWN_REF(_Atomic int *val, int *ret, void *lock)
{
    *ret = atomic_fetch_sub_explicit(val, 1, memory_order_release) - 1;
    if (*ret == 0)
        atomic_thread_fence(memory_order_acquire);
    return 1;
}

# elif defined(__GNUC__) && defined(__ATOMIC_RELAXED) && __GCC_ATOMIC_INT_LOCK_FREE > 0

# define HAVE_ATOMICS 1

typedef int CRYPTO_REF_COUNT;

51
static ossl_inline int CRYPTO_GET_REF(int *val, int *ret, void *lock)
52 53 54 55 56
{
    *ret = __atomic_fetch_add(val, 0, __ATOMIC_RELAXED);
    return 1;
}

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
static ossl_inline int CRYPTO_UP_REF(int *val, int *ret, void *lock)
{
    *ret = __atomic_fetch_add(val, 1, __ATOMIC_RELAXED) + 1;
    return 1;
}

static ossl_inline int CRYPTO_DOWN_REF(int *val, int *ret, void *lock)
{
    *ret = __atomic_fetch_sub(val, 1, __ATOMIC_RELEASE) - 1;
    if (*ret == 0)
        __atomic_thread_fence(__ATOMIC_ACQUIRE);
    return 1;
}

# else

typedef int CRYPTO_REF_COUNT;

75
# define CRYPTO_GET_REF(val, ret, lock) CRYPTO_atomic_add(val, 0, ret, lock)
76 77 78 79 80
# define CRYPTO_UP_REF(val, ret, lock) CRYPTO_atomic_add(val, 1, ret, lock)
# define CRYPTO_DOWN_REF(val, ret, lock) CRYPTO_atomic_add(val, -1, ret, lock)

# endif
#endif