1 // Copyright 2015 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
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 
CRYPTO_refcount_inc(CRYPTO_refcount_t * count)21 void CRYPTO_refcount_inc(CRYPTO_refcount_t *count) {
22   uint32_t expected = CRYPTO_atomic_load_u32(count);
23 
24   while (expected != CRYPTO_REFCOUNT_MAX) {
25     uint32_t new_value = expected + 1;
26     if (CRYPTO_atomic_compare_exchange_weak_u32(count, &expected, new_value)) {
27       break;
28     }
29   }
30 }
31 
CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t * count)32 int CRYPTO_refcount_dec_and_test_zero(CRYPTO_refcount_t *count) {
33   uint32_t expected = CRYPTO_atomic_load_u32(count);
34 
35   for (;;) {
36     if (expected == 0) {
37       abort();
38     } else if (expected == CRYPTO_REFCOUNT_MAX) {
39       return 0;
40     } else {
41       const uint32_t new_value = expected - 1;
42       if (CRYPTO_atomic_compare_exchange_weak_u32(count, &expected,
43                                                   new_value)) {
44         return new_value == 0;
45       }
46     }
47   }
48 }
49