Debian Codegraph @

debian/rust-vendor/openssl-src/openssl/crypto/threads_pthread.c

raw
1 /*
2 * Copyright 2016-2026 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License 2.0 (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
10 /* We need to use the OPENSSL_fork_*() deprecated APIs */
11 #define OPENSSL_SUPPRESS_DEPRECATED
12
13 #if !defined(__GNUC__) || !defined(__ATOMIC_ACQ_REL) || defined(BROKEN_CLANG_ATOMICS) || defined(OPENSSL_NO_STDIO)
14 /*
15 * we only enable REPORT_RWLOCK_CONTENTION on clang/gcc when we have
16 * atomics available. We do this because we need to use an atomic to track
17 * when we can close the log file. We could use the CRYPTO_atomic_ api
18 * but that requires lock creation which gets us into a bad recursive loop
19 * when we try to initialize the file pointer
20 */
21 #ifdef REPORT_RWLOCK_CONTENTION
22 #warning "RWLOCK CONTENTION REPORTING NOT SUPPORTED, Disabling"
23 #undef REPORT_RWLOCK_CONTENTION
24 #endif
25 #endif
26
27 #ifdef REPORT_RWLOCK_CONTENTION
28 #define _GNU_SOURCE
29 #include <execinfo.h>
30 #include <unistd.h>
31 #endif
32
33 #include <openssl/crypto.h>
34 #include <crypto/cryptlib.h>
35 #include <crypto/sparse_array.h>
36 #include "internal/cryptlib.h"
37 #include "internal/threads_common.h"
38 #include "internal/rcu.h"
39 #ifdef REPORT_RWLOCK_CONTENTION
40 #include <fcntl.h>
41 #include <stdbool.h>
42 #include <sys/syscall.h>
43 #include <sys/uio.h>
44 #include "internal/time.h"
45 #endif
46 #include "rcu_internal.h"
47
48 #if defined(__clang__) && defined(__has_feature)
49 #if __has_feature(thread_sanitizer)
50 #define __SANITIZE_THREAD__
51 #endif
52 #endif
53
54 #if defined(__SANITIZE_THREAD__)
55 #include <sanitizer/tsan_interface.h>
56 #define TSAN_FAKE_UNLOCK(x) \
57 __tsan_mutex_pre_unlock((x), 0); \
58 __tsan_mutex_post_unlock((x), 0)
59
60 #define TSAN_FAKE_LOCK(x) \
61 __tsan_mutex_pre_lock((x), 0); \
62 __tsan_mutex_post_lock((x), 0, 0)
63 #else
64 #define TSAN_FAKE_UNLOCK(x)
65 #define TSAN_FAKE_LOCK(x)
66 #endif
67
68 #if defined(__sun)
69 #include <atomic.h>
70 #endif
71
72 #if defined(__apple_build_version__) && __apple_build_version__ < 6000000
73 /*
74 * OS/X 10.7 and 10.8 had a weird version of clang which has __ATOMIC_ACQUIRE and
75 * __ATOMIC_ACQ_REL but which expects only one parameter for __atomic_is_lock_free()
76 * rather than two which has signature __atomic_is_lock_free(sizeof(_Atomic(T))).
77 * All of this makes impossible to use __atomic_is_lock_free here.
78 *
79 * See: https://github.com/llvm/llvm-project/commit/a4c2602b714e6c6edb98164550a5ae829b2de760
80 */
81 #define BROKEN_CLANG_ATOMICS
82 #endif
83
84 #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && !defined(OPENSSL_SYS_WINDOWS)
85
86 #if defined(OPENSSL_SYS_UNIX)
87 #include <sys/types.h>
88 #include <unistd.h>
89 #endif
90
91 #include <assert.h>
92
93 /*
94 * The Non-Stop KLT thread model currently seems broken in its rwlock
95 * implementation
96 * Likewise is there a problem with the glibc implementation on riscv.
97 */
98 #if defined(PTHREAD_RWLOCK_INITIALIZER) && !defined(_KLT_MODEL_) && !defined(_PUT_MODEL_) \
99 && !defined(__riscv)
100 #define USE_RWLOCK
101 #endif
102
103 /*
104 * For all GNU/clang atomic builtins, we also need fallbacks, to cover all
105 * other compilers.
106
107 * Unfortunately, we can't do that with some "generic type", because there's no
108 * guarantee that the chosen generic type is large enough to cover all cases.
109 * Therefore, we implement fallbacks for each applicable type, with composed
110 * names that include the type they handle.
111 *
112 * (an anecdote: we previously tried to use |void *| as the generic type, with
113 * the thought that the pointer itself is the largest type. However, this is
114 * not true on 32-bit pointer platforms, as a |uint64_t| is twice as large)
115 *
116 * All applicable ATOMIC_ macros take the intended type as first parameter, so
117 * they can map to the correct fallback function. In the GNU/clang case, that
118 * parameter is simply ignored.
119 */
120
121 /*
122 * Internal types used with the ATOMIC_ macros, to make it possible to compose
123 * fallback function names.
124 */
125 typedef void *pvoid;
126
127 #if defined(__GNUC__) && defined(__ATOMIC_ACQUIRE) && !defined(BROKEN_CLANG_ATOMICS) \
128 && !defined(USE_ATOMIC_FALLBACKS)
129 #define ATOMIC_LOAD_N(t, p, o) __atomic_load_n(p, o)
130 #define ATOMIC_STORE_N(t, p, v, o) __atomic_store_n(p, v, o)
131 #define ATOMIC_STORE(t, p, v, o) __atomic_store(p, v, o)
132 #define ATOMIC_ADD_FETCH(p, v, o) __atomic_add_fetch(p, v, o)
133 #define ATOMIC_SUB_FETCH(p, v, o) __atomic_sub_fetch(p, v, o)
134 #else
135 static pthread_mutex_t atomic_sim_lock = PTHREAD_MUTEX_INITIALIZER;
136
137 #define IMPL_fallback_atomic_load_n(t) \
138 static ossl_inline t fallback_atomic_load_n_##t(t *p) \
139 { \
140 t ret; \
141 \
142 pthread_mutex_lock(&atomic_sim_lock); \
143 ret = *p; \
144 pthread_mutex_unlock(&atomic_sim_lock); \
145 return ret; \
146 }
147 IMPL_fallback_atomic_load_n(uint32_t)
148 IMPL_fallback_atomic_load_n(uint64_t)
149 IMPL_fallback_atomic_load_n(pvoid)
150
151 #define ATOMIC_LOAD_N(t, p, o) fallback_atomic_load_n_##t(p)
152
153 #define IMPL_fallback_atomic_store_n(t) \
154 static ossl_inline t fallback_atomic_store_n_##t(t *p, t v) \
155 { \
156 t ret; \
157 \
158 pthread_mutex_lock(&atomic_sim_lock); \
159 ret = *p; \
160 *p = v; \
161 pthread_mutex_unlock(&atomic_sim_lock); \
162 return ret; \
163 }
164 IMPL_fallback_atomic_store_n(uint32_t)
165
166 #define ATOMIC_STORE_N(t, p, v, o) fallback_atomic_store_n_##t(p, v)
167
168 #define IMPL_fallback_atomic_store(t) \
169 static ossl_inline void fallback_atomic_store_##t(t *p, t *v) \
170 { \
171 pthread_mutex_lock(&atomic_sim_lock); \
172 *p = *v; \
173 pthread_mutex_unlock(&atomic_sim_lock); \
174 }
175 IMPL_fallback_atomic_store(pvoid)
176
177 #define ATOMIC_STORE(t, p, v, o) fallback_atomic_store_##t(p, v)
178
179 /*
180 * The fallbacks that follow don't need any per type implementation, as
181 * they are designed for uint64_t only. If there comes a time when multiple
182 * types need to be covered, it's relatively easy to refactor them the same
183 * way as the fallbacks above.
184 */
185
186 static ossl_inline uint64_t fallback_atomic_add_fetch(uint64_t *p, uint64_t v)
187 {
188 uint64_t ret;
189
190 pthread_mutex_lock(&atomic_sim_lock);
191 *p += v;
192 ret = *p;
193 pthread_mutex_unlock(&atomic_sim_lock);
194 return ret;
195 }
196
197 #define ATOMIC_ADD_FETCH(p, v, o) fallback_atomic_add_fetch(p, v)
198
199 static ossl_inline uint64_t fallback_atomic_sub_fetch(uint64_t *p, uint64_t v)
200 {
201 uint64_t ret;
202
203 pthread_mutex_lock(&atomic_sim_lock);
204 *p -= v;
205 ret = *p;
206 pthread_mutex_unlock(&atomic_sim_lock);
207 return ret;
208 }
209
210 #define ATOMIC_SUB_FETCH(p, v, o) fallback_atomic_sub_fetch(p, v)
211 #endif
212
213 /*
214 * This is the core of an rcu lock. It tracks the readers and writers for the
215 * current quiescence point for a given lock. Users is the 64 bit value that
216 * stores the READERS/ID as defined above
217 *
218 */
219 struct rcu_qp {
220 uint64_t users;
221 };
222
223 struct thread_qp {
224 struct rcu_qp *qp;
225 unsigned int depth;
226 CRYPTO_RCU_LOCK *lock;
227 };
228
229 #define MAX_QPS 10
230 /*
231 * This is the per thread tracking data
232 * that is assigned to each thread participating
233 * in an rcu qp
234 *
235 * qp points to the qp that it last acquired
236 *
237 */
238 struct rcu_thr_data {
239 struct thread_qp thread_qps[MAX_QPS];
240 };
241
242 /*
243 * This is the internal version of a CRYPTO_RCU_LOCK
244 * it is cast from CRYPTO_RCU_LOCK
245 */
246 struct rcu_lock_st {
247 /* Callbacks to call for next ossl_synchronize_rcu */
248 struct rcu_cb_item *cb_items;
249
250 /* The context we are being created against */
251 OSSL_LIB_CTX *ctx;
252
253 /* Array of quiescent points for synchronization */
254 struct rcu_qp *qp_group;
255
256 /* rcu generation counter for in-order retirement */
257 uint32_t id_ctr;
258
259 /* Number of elements in qp_group array */
260 uint32_t group_count;
261
262 /* Index of the current qp in the qp_group array */
263 uint32_t reader_idx;
264
265 /* value of the next id_ctr value to be retired */
266 uint32_t next_to_retire;
267
268 /* index of the next free rcu_qp in the qp_group */
269 uint32_t current_alloc_idx;
270
271 /* number of qp's in qp_group array currently being retired */
272 uint32_t writers_alloced;
273
274 /* lock protecting write side operations */
275 pthread_mutex_t write_lock;
276
277 /* lock protecting updates to writers_alloced/current_alloc_idx */
278 pthread_mutex_t alloc_lock;
279
280 /* signal to wake threads waiting on alloc_lock */
281 pthread_cond_t alloc_signal;
282
283 /* lock to enforce in-order retirement */
284 pthread_mutex_t prior_lock;
285
286 /* signal to wake threads waiting on prior_lock */
287 pthread_cond_t prior_signal;
288 };
289
290 /* Read side acquisition of the current qp */
291 static struct rcu_qp *get_hold_current_qp(struct rcu_lock_st *lock)
292 {
293 uint32_t qp_idx;
294
295 /* get the current qp index */
296 for (;;) {
297 qp_idx = ATOMIC_LOAD_N(uint32_t, &lock->reader_idx, __ATOMIC_RELAXED);
298
299 /*
300 * Notes on use of __ATOMIC_ACQUIRE
301 * We need to ensure the following:
302 * 1) That subsequent operations aren't optimized by hoisting them above
303 * this operation. Specifically, we don't want the below re-load of
304 * qp_idx to get optimized away
305 * 2) We want to ensure that any updating of reader_idx on the write side
306 * of the lock is flushed from a local cpu cache so that we see any
307 * updates prior to the load. This is a non-issue on cache coherent
308 * systems like x86, but is relevant on other arches
309 */
310 ATOMIC_ADD_FETCH(&lock->qp_group[qp_idx].users, (uint64_t)1,
311 __ATOMIC_ACQUIRE);
312
313 /* if the idx hasn't changed, we're good, else try again */
314 if (qp_idx == ATOMIC_LOAD_N(uint32_t, &lock->reader_idx, __ATOMIC_ACQUIRE))
315 break;
316
317 ATOMIC_SUB_FETCH(&lock->qp_group[qp_idx].users, (uint64_t)1,
318 __ATOMIC_RELAXED);
319 }
320
321 return &lock->qp_group[qp_idx];
322 }
323
324 static void ossl_rcu_free_local_data(void *arg)
325 {
326 OSSL_LIB_CTX *ctx = arg;
327 struct rcu_thr_data *data = CRYPTO_THREAD_get_local_ex(CRYPTO_THREAD_LOCAL_RCU_KEY, ctx);
328
329 CRYPTO_THREAD_set_local_ex(CRYPTO_THREAD_LOCAL_RCU_KEY, ctx, NULL);
330 OPENSSL_free(data);
331 }
332
333 int ossl_rcu_read_lock(CRYPTO_RCU_LOCK *lock)
334 {
335 struct rcu_thr_data *data;
336 int i, available_qp = -1;
337
338 /*
339 * we're going to access current_qp here so ask the
340 * processor to fetch it
341 */
342 data = CRYPTO_THREAD_get_local_ex(CRYPTO_THREAD_LOCAL_RCU_KEY, lock->ctx);
343
344 if (data == NULL) {
345 data = OPENSSL_zalloc(sizeof(*data));
346 if (data == NULL)
347 return 0;
348
349 if (!CRYPTO_THREAD_set_local_ex(CRYPTO_THREAD_LOCAL_RCU_KEY, lock->ctx, data)) {
350 OPENSSL_free(data);
351 return 0;
352 }
353 if (!ossl_init_thread_start(NULL, lock->ctx, ossl_rcu_free_local_data)) {
354 OPENSSL_free(data);
355 CRYPTO_THREAD_set_local_ex(CRYPTO_THREAD_LOCAL_RCU_KEY, lock->ctx, NULL);
356 return 0;
357 }
358 }
359
360 for (i = 0; i < MAX_QPS; i++) {
361 if (data->thread_qps[i].qp == NULL && available_qp == -1)
362 available_qp = i;
363 /* If we have a hold on this lock already, we're good */
364 if (data->thread_qps[i].lock == lock) {
365 data->thread_qps[i].depth++;
366 return 1;
367 }
368 }
369
370 /*
371 * if we get here, then we don't have a hold on this lock yet
372 */
373 assert(available_qp != -1);
374
375 data->thread_qps[available_qp].qp = get_hold_current_qp(lock);
376 data->thread_qps[available_qp].depth = 1;
377 data->thread_qps[available_qp].lock = lock;
378 return 1;
379 }
380
381 void ossl_rcu_read_unlock(CRYPTO_RCU_LOCK *lock)
382 {
383 int i;
384 struct rcu_thr_data *data = CRYPTO_THREAD_get_local_ex(CRYPTO_THREAD_LOCAL_RCU_KEY, lock->ctx);
385 uint64_t ret;
386
387 assert(data != NULL);
388
389 for (i = 0; i < MAX_QPS; i++) {
390 if (data->thread_qps[i].lock == lock) {
391 /*
392 * we have to use __ATOMIC_RELEASE here
393 * to ensure that all preceding read instructions complete
394 * before the decrement is visible to ossl_synchronize_rcu
395 */
396 data->thread_qps[i].depth--;
397 if (data->thread_qps[i].depth == 0) {
398 ret = ATOMIC_SUB_FETCH(&data->thread_qps[i].qp->users,
399 (uint64_t)1, __ATOMIC_RELEASE);
400 OPENSSL_assert(ret != UINT64_MAX);
401 data->thread_qps[i].qp = NULL;
402 data->thread_qps[i].lock = NULL;
403 }
404 return;
405 }
406 }
407 /*
408 * If we get here, we're trying to unlock a lock that we never acquired -
409 * that's fatal.
410 */
411 assert(0);
412 }
413
414 /*
415 * Write side allocation routine to get the current qp
416 * and replace it with a new one
417 */
418 static struct rcu_qp *update_qp(CRYPTO_RCU_LOCK *lock, uint32_t *curr_id)
419 {
420 uint32_t current_idx;
421
422 pthread_mutex_lock(&lock->alloc_lock);
423
424 /*
425 * we need at least one qp to be available with one
426 * left over, so that readers can start working on
427 * one that isn't yet being waited on
428 */
429 while (lock->group_count - lock->writers_alloced < 2)
430 /* we have to wait for one to be free */
431 pthread_cond_wait(&lock->alloc_signal, &lock->alloc_lock);
432
433 current_idx = lock->current_alloc_idx;
434
435 /* Allocate the qp */
436 lock->writers_alloced++;
437
438 /* increment the allocation index */
439 lock->current_alloc_idx = (lock->current_alloc_idx + 1) % lock->group_count;
440
441 *curr_id = lock->id_ctr;
442 lock->id_ctr++;
443
444 /*
445 * make the current state of everything visible by this release
446 * when get_hold_current_qp acquires the next qp
447 */
448 ATOMIC_STORE_N(uint32_t, &lock->reader_idx, lock->current_alloc_idx,
449 __ATOMIC_RELEASE);
450
451 /*
452 * this should make sure that the new value of reader_idx is visible in
453 * get_hold_current_qp, directly after incrementing the users count
454 */
455 ATOMIC_ADD_FETCH(&lock->qp_group[current_idx].users, (uint64_t)0,
456 __ATOMIC_RELEASE);
457
458 /* wake up any waiters */
459 pthread_cond_signal(&lock->alloc_signal);
460 pthread_mutex_unlock(&lock->alloc_lock);
461 return &lock->qp_group[current_idx];
462 }
463
464 static void retire_qp(CRYPTO_RCU_LOCK *lock, struct rcu_qp *qp)
465 {
466 pthread_mutex_lock(&lock->alloc_lock);
467 lock->writers_alloced--;
468 pthread_cond_signal(&lock->alloc_signal);
469 pthread_mutex_unlock(&lock->alloc_lock);
470 }
471
472 static struct rcu_qp *allocate_new_qp_group(CRYPTO_RCU_LOCK *lock,
473 uint32_t count)
474 {
475 struct rcu_qp *new = OPENSSL_calloc(count, sizeof(*new));
476
477 lock->group_count = count;
478 return new;
479 }
480
481 void ossl_rcu_write_lock(CRYPTO_RCU_LOCK *lock)
482 {
483 pthread_mutex_lock(&lock->write_lock);
484 TSAN_FAKE_UNLOCK(&lock->write_lock);
485 }
486
487 void ossl_rcu_write_unlock(CRYPTO_RCU_LOCK *lock)
488 {
489 TSAN_FAKE_LOCK(&lock->write_lock);
490 pthread_mutex_unlock(&lock->write_lock);
491 }
492
493 void ossl_synchronize_rcu(CRYPTO_RCU_LOCK *lock)
494 {
495 struct rcu_qp *qp;
496 uint64_t count;
497 uint32_t curr_id;
498 struct rcu_cb_item *cb_items, *tmpcb;
499
500 pthread_mutex_lock(&lock->write_lock);
501 cb_items = lock->cb_items;
502 lock->cb_items = NULL;
503 pthread_mutex_unlock(&lock->write_lock);
504
505 qp = update_qp(lock, &curr_id);
506
507 /* retire in order */
508 pthread_mutex_lock(&lock->prior_lock);
509 while (lock->next_to_retire != curr_id)
510 pthread_cond_wait(&lock->prior_signal, &lock->prior_lock);
511
512 /*
513 * wait for the reader count to reach zero
514 * Note the use of __ATOMIC_ACQUIRE here to ensure that any
515 * prior __ATOMIC_RELEASE write operation in ossl_rcu_read_unlock
516 * is visible prior to our read
517 * however this is likely just necessary to silence a tsan warning
518 * because the read side should not do any write operation
519 * outside the atomic itself
520 */
521 do {
522 count = ATOMIC_LOAD_N(uint64_t, &qp->users, __ATOMIC_ACQUIRE);
523 } while (count != (uint64_t)0);
524
525 lock->next_to_retire++;
526 pthread_cond_broadcast(&lock->prior_signal);
527 pthread_mutex_unlock(&lock->prior_lock);
528
529 retire_qp(lock, qp);
530
531 /* handle any callbacks that we have */
532 while (cb_items != NULL) {
533 tmpcb = cb_items;
534 cb_items = cb_items->next;
535 tmpcb->fn(tmpcb->data);
536 OPENSSL_free(tmpcb);
537 }
538 }
539
540 CRYPTO_RCU_CB_ITEM *ossl_rcu_cb_item_new(void)
541 {
542 return OPENSSL_zalloc(sizeof(CRYPTO_RCU_CB_ITEM));
543 }
544
545 void ossl_rcu_cb_item_free(CRYPTO_RCU_CB_ITEM *item)
546 {
547 OPENSSL_free(item);
548 }
549
550 /*
551 * Note: This call assumes its made under the protection of
552 * ossl_rcu_write_lock
553 */
554 void ossl_rcu_call(CRYPTO_RCU_LOCK *lock, CRYPTO_RCU_CB_ITEM *item,
555 rcu_cb_fn cb, void *data)
556 {
557 item->fn = cb;
558 item->data = data;
559 item->next = lock->cb_items;
560 lock->cb_items = item;
561 }
562
563 void *ossl_rcu_uptr_deref(void **p)
564 {
565 return ATOMIC_LOAD_N(pvoid, p, __ATOMIC_ACQUIRE);
566 }
567
568 void ossl_rcu_assign_uptr(void **p, void **v)
569 {
570 ATOMIC_STORE(pvoid, p, v, __ATOMIC_RELEASE);
571 }
572
573 CRYPTO_RCU_LOCK *ossl_rcu_lock_new(int num_writers, OSSL_LIB_CTX *ctx)
574 {
575 struct rcu_lock_st *new;
576 pthread_mutex_t *mutexes[3] = { NULL };
577 pthread_cond_t *conds[2] = { NULL };
578 int i;
579
580 /*
581 * We need a minimum of 2 qp's
582 */
583 if (num_writers < 2)
584 num_writers = 2;
585
586 ctx = ossl_lib_ctx_get_concrete(ctx);
587 if (ctx == NULL)
588 return 0;
589
590 new = OPENSSL_zalloc(sizeof(*new));
591 if (new == NULL)
592 return NULL;
593
594 new->ctx = ctx;
595 i = 0;
596 mutexes[i] = pthread_mutex_init(&new->write_lock, NULL) == 0 ? &new->write_lock : NULL;
597 if (mutexes[i++] == NULL)
598 goto err;
599 mutexes[i] = pthread_mutex_init(&new->prior_lock, NULL) == 0 ? &new->prior_lock : NULL;
600 if (mutexes[i++] == NULL)
601 goto err;
602 mutexes[i] = pthread_mutex_init(&new->alloc_lock, NULL) == 0 ? &new->alloc_lock : NULL;
603 if (mutexes[i++] == NULL)
604 goto err;
605 conds[i - 3] = pthread_cond_init(&new->prior_signal, NULL) == 0 ? &new->prior_signal : NULL;
606 if (conds[i - 3] == NULL)
607 goto err;
608 i++;
609 conds[i - 3] = pthread_cond_init(&new->alloc_signal, NULL) == 0 ? &new->alloc_signal : NULL;
610 if (conds[i - 3] == NULL)
611 goto err;
612 i++;
613 new->qp_group = allocate_new_qp_group(new, num_writers);
614 if (new->qp_group == NULL)
615 goto err;
616
617 return new;
618
619 err:
620 for (i = 0; i < 3; i++)
621 if (mutexes[i] != NULL)
622 pthread_mutex_destroy(mutexes[i]);
623 for (i = 0; i < 2; i++)
624 if (conds[i] != NULL)
625 pthread_cond_destroy(conds[i]);
626 OPENSSL_free(new->qp_group);
627 OPENSSL_free(new);
628 return NULL;
629 }
630
631 void ossl_rcu_lock_free(CRYPTO_RCU_LOCK *lock)
632 {
633 struct rcu_lock_st *rlock = (struct rcu_lock_st *)lock;
634
635 if (lock == NULL)
636 return;
637
638 /* make sure we're synchronized */
639 ossl_synchronize_rcu(rlock);
640
641 OPENSSL_free(rlock->qp_group);
642 /*
643 * Some targets (BSD) allocate heap when initializing
644 * a mutex or condition, to prevent leaks, those need
645 * to be destroyed here
646 */
647 pthread_mutex_destroy(&rlock->write_lock);
648 pthread_mutex_destroy(&rlock->prior_lock);
649 pthread_mutex_destroy(&rlock->alloc_lock);
650 pthread_cond_destroy(&rlock->prior_signal);
651 pthread_cond_destroy(&rlock->alloc_signal);
652
653 /* There should only be a single qp left now */
654 OPENSSL_free(rlock);
655 }
656
657 #ifdef REPORT_RWLOCK_CONTENTION
658 /*
659 * Normally we would use a BIO here to do this, but we create locks during
660 * library initialization, and creating a bio too early, creates a recursive set
661 * of stack calls that leads us to call CRYPTO_thread_run_once while currently
662 * executing the init routine for various run_once functions, which leads to
663 * deadlock. Avoid that by just using a FILE pointer. Also note that we
664 * directly use a pthread_mutex_t to protect access from multiple threads
665 * to the contention log file. We do this because we want to avoid use
666 * of the CRYPTO_THREAD api so as to prevent recursive blocking reports.
667 */
668 static CRYPTO_ONCE init_contention_data_flag = CRYPTO_ONCE_STATIC_INIT;
669 pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
670 CRYPTO_THREAD_LOCAL thread_contention_data;
671
672 struct stack_info {
673 unsigned int nptrs;
674 int write;
675 OSSL_TIME start;
676 OSSL_TIME duration;
677 char **strings;
678 };
679
680 #define STACKS_COUNT 32
681 #define BT_BUF_SIZE 1024
682 struct stack_traces {
683 int fd;
684 int lock_depth;
685 size_t idx;
686 struct stack_info stacks[STACKS_COUNT];
687 };
688
689 /* The glibc gettid() definition presents only since 2.30. */
690 static ossl_inline pid_t get_tid(void)
691 {
692 return syscall(SYS_gettid);
693 }
694
695 #ifdef FIPS_MODULE
696 #define FIPS_SFX "-fips"
697 #else
698 #define FIPS_SFX ""
699 #endif
700 static void *init_contention_data(void)
701 {
702 struct stack_traces *traces;
703 char fname_fmt[] = "lock-contention-log" FIPS_SFX ".%d.txt";
704 char fname[sizeof(fname_fmt) + sizeof(int) * 3];
705
706 traces = OPENSSL_zalloc(sizeof(struct stack_traces));
707
708 snprintf(fname, sizeof(fname), fname_fmt, get_tid());
709
710 traces->fd = open(fname, O_WRONLY | O_APPEND | O_CLOEXEC | O_CREAT, 0600);
711
712 return traces;
713 }
714
715 static void destroy_contention_data(void *data)
716 {
717 struct stack_traces *st = data;
718
719 close(st->fd);
720 OPENSSL_free(data);
721 }
722
723 static void init_contention_data_once(void)
724 {
725 /*
726 * Create a thread local key here to store our list of stack traces
727 * to be printed when we unlock the lock we are holding
728 */
729 CRYPTO_THREAD_init_local(&thread_contention_data, destroy_contention_data);
730 return;
731 }
732
733 static struct stack_traces *get_stack_traces(bool init)
734 {
735 struct stack_traces *traces = CRYPTO_THREAD_get_local(&thread_contention_data);
736
737 if (!traces && init) {
738 traces = init_contention_data();
739 CRYPTO_THREAD_set_local(&thread_contention_data, traces);
740 }
741
742 return traces;
743 }
744
745 static void print_stack_traces(struct stack_traces *traces)
746 {
747 unsigned int j;
748 struct iovec *iov;
749 int iovcnt;
750
751 while (traces != NULL && traces->idx >= 1) {
752 traces->idx--;
753 dprintf(traces->fd,
754 "lock blocked on %s for %zu usec at time %zu tid %d\n",
755 traces->stacks[traces->idx].write == 1 ? "WRITE" : "READ",
756 ossl_time2us(traces->stacks[traces->idx].duration),
757 ossl_time2us(traces->stacks[traces->idx].start),
758 get_tid());
759 if (traces->stacks[traces->idx].strings != NULL) {
760 static const char lf = '\n';
761
762 iovcnt = traces->stacks[traces->idx].nptrs * 2 + 1;
763 iov = alloca(iovcnt * sizeof(*iov));
764 for (j = 0; j < traces->stacks[traces->idx].nptrs; j++) {
765 iov[2 * j].iov_base = traces->stacks[traces->idx].strings[j];
766 iov[2 * j].iov_len = strlen(traces->stacks[traces->idx].strings[j]);
767 iov[2 * j + 1].iov_base = (char *)&lf;
768 iov[2 * j + 1].iov_len = 1;
769 }
770 iov[traces->stacks[traces->idx].nptrs * 2].iov_base = (char *)&lf;
771 iov[traces->stacks[traces->idx].nptrs * 2].iov_len = 1;
772 } else {
773 static const char no_bt[] = "No stack trace available\n\n";
774
775 iovcnt = 1;
776 iov = alloca(iovcnt * sizeof(*iov));
777 iov[0].iov_base = (char *)no_bt;
778 iov[0].iov_len = sizeof(no_bt) - 1;
779 }
780 writev(traces->fd, iov, iovcnt);
781 free(traces->stacks[traces->idx].strings);
782 }
783 }
784
785 static ossl_inline void ossl_init_rwlock_contention_data(void)
786 {
787 CRYPTO_THREAD_run_once(&init_contention_data_flag, init_contention_data_once);
788 }
789
790 static int record_lock_contention(pthread_rwlock_t *lock,
791 struct stack_traces *traces, bool write)
792 {
793 void *buffer[BT_BUF_SIZE];
794 OSSL_TIME start, end;
795 int ret;
796
797 start = ossl_time_now();
798 ret = (write ? pthread_rwlock_wrlock : pthread_rwlock_rdlock)(lock);
799 if (ret)
800 return ret;
801 end = ossl_time_now();
802 traces->stacks[traces->idx].nptrs = backtrace(buffer, BT_BUF_SIZE);
803 traces->stacks[traces->idx].strings = backtrace_symbols(buffer,
804 traces->stacks[traces->idx].nptrs);
805 traces->stacks[traces->idx].duration = ossl_time_subtract(end, start);
806 traces->stacks[traces->idx].start = start;
807 traces->stacks[traces->idx].write = write;
808 traces->idx++;
809 if (traces->idx >= STACKS_COUNT) {
810 fprintf(stderr, "STACK RECORD OVERFLOW!\n");
811 print_stack_traces(traces);
812 }
813
814 return 0;
815 }
816
817 static ossl_inline int ossl_rwlock_rdlock(pthread_rwlock_t *lock)
818 {
819 struct stack_traces *traces = get_stack_traces(true);
820
821 if (ossl_unlikely(traces == NULL))
822 return ENOMEM;
823
824 traces->lock_depth++;
825 if (pthread_rwlock_tryrdlock(lock)) {
826 int ret = record_lock_contention(lock, traces, false);
827
828 if (ret)
829 traces->lock_depth--;
830
831 return ret;
832 }
833
834 return 0;
835 }
836
837 static ossl_inline int ossl_rwlock_wrlock(pthread_rwlock_t *lock)
838 {
839 struct stack_traces *traces = get_stack_traces(true);
840
841 if (ossl_unlikely(traces == NULL))
842 return ENOMEM;
843
844 traces->lock_depth++;
845 if (pthread_rwlock_trywrlock(lock)) {
846 int ret = record_lock_contention(lock, traces, true);
847
848 if (ret)
849 traces->lock_depth--;
850
851 return ret;
852 }
853
854 return 0;
855 }
856
857 static ossl_inline int ossl_rwlock_unlock(pthread_rwlock_t *lock)
858 {
859 int ret;
860
861 ret = pthread_rwlock_unlock(lock);
862 if (ret)
863 return ret;
864
865 {
866 struct stack_traces *traces = get_stack_traces(false);
867
868 if (traces != NULL) {
869 traces->lock_depth--;
870 assert(traces->lock_depth >= 0);
871 if (traces->lock_depth == 0)
872 print_stack_traces(traces);
873 }
874 }
875
876 return 0;
877 }
878
879 #else /* !REPORT_RWLOCK_CONTENTION */
880
881 #if defined(USE_RWLOCK)
882 static ossl_inline void ossl_init_rwlock_contention_data(void)
883 {
884 }
885
886 static ossl_inline int ossl_rwlock_rdlock(pthread_rwlock_t *rwlock)
887 {
888 return pthread_rwlock_rdlock(rwlock);
889 }
890
891 static ossl_inline int ossl_rwlock_wrlock(pthread_rwlock_t *rwlock)
892 {
893 return pthread_rwlock_wrlock(rwlock);
894 }
895
896 static ossl_inline int ossl_rwlock_unlock(pthread_rwlock_t *rwlock)
897 {
898 return pthread_rwlock_unlock(rwlock);
899 }
900 #endif /* USE_RWLOCK */
901 #endif /* REPORT_RWLOCK_CONTENTION */
902
903 CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void)
904 {
905 #ifdef USE_RWLOCK
906 CRYPTO_RWLOCK *lock;
907
908 ossl_init_rwlock_contention_data();
909
910 if ((lock = OPENSSL_zalloc(sizeof(pthread_rwlock_t))) == NULL)
911 /* Don't set error, to avoid recursion blowup. */
912 return NULL;
913
914 if (pthread_rwlock_init(lock, NULL) != 0) {
915 OPENSSL_free(lock);
916 return NULL;
917 }
918 #else
919 pthread_mutexattr_t attr;
920 CRYPTO_RWLOCK *lock;
921
922 if ((lock = OPENSSL_zalloc(sizeof(pthread_mutex_t))) == NULL)
923 /* Don't set error, to avoid recursion blowup. */
924 return NULL;
925
926 /*
927 * We don't use recursive mutexes, but try to catch errors if we do.
928 */
929 pthread_mutexattr_init(&attr);
930 #if !defined(__TANDEM) && !defined(_SPT_MODEL_)
931 #if !defined(NDEBUG) && !defined(OPENSSL_NO_MUTEX_ERRORCHECK)
932 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
933 #endif
934 #else
935 /* The SPT Thread Library does not define MUTEX attributes. */
936 #endif
937
938 if (pthread_mutex_init(lock, &attr) != 0) {
939 pthread_mutexattr_destroy(&attr);
940 OPENSSL_free(lock);
941 return NULL;
942 }
943
944 pthread_mutexattr_destroy(&attr);
945 #endif
946
947 return lock;
948 }
949
950 __owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock)
951 {
952 #ifdef USE_RWLOCK
953 if (!ossl_assert(ossl_rwlock_rdlock(lock) == 0))
954 return 0;
955 #else
956 if (pthread_mutex_lock(lock) != 0) {
957 assert(errno != EDEADLK && errno != EBUSY);
958 return 0;
959 }
960 #endif
961
962 return 1;
963 }
964
965 __owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock)
966 {
967 #ifdef USE_RWLOCK
968 if (!ossl_assert(ossl_rwlock_wrlock(lock) == 0))
969 return 0;
970 #else
971 if (pthread_mutex_lock(lock) != 0) {
972 assert(errno != EDEADLK && errno != EBUSY);
973 return 0;
974 }
975 #endif
976
977 return 1;
978 }
979
980 int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock)
981 {
982 #ifdef USE_RWLOCK
983 if (ossl_rwlock_unlock(lock) != 0)
984 return 0;
985 #else
986 if (pthread_mutex_unlock(lock) != 0) {
987 assert(errno != EPERM);
988 return 0;
989 }
990 #endif
991
992 return 1;
993 }
994
995 void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock)
996 {
997 if (lock == NULL)
998 return;
999
1000 #ifdef USE_RWLOCK
1001 pthread_rwlock_destroy(lock);
1002 #else
1003 pthread_mutex_destroy(lock);
1004 #endif
1005 OPENSSL_free(lock);
1006
1007 return;
1008 }
1009
1010 int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void))
1011 {
1012 if (ossl_unlikely(pthread_once(once, init) != 0))
1013 return 0;
1014
1015 return 1;
1016 }
1017
1018 int ossl_thread_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *))
1019 {
1020
1021 if (pthread_key_create(key, cleanup) != 0)
1022 return 0;
1023
1024 return 1;
1025 }
1026
1027 void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key)
1028 {
1029 return pthread_getspecific(*key);
1030 }
1031
1032 int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val)
1033 {
1034 if (pthread_setspecific(*key, val) != 0)
1035 return 0;
1036
1037 return 1;
1038 }
1039
1040 int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key)
1041 {
1042 if (pthread_key_delete(*key) != 0)
1043 return 0;
1044
1045 return 1;
1046 }
1047
1048 CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void)
1049 {
1050 return pthread_self();
1051 }
1052
1053 int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b)
1054 {
1055 return pthread_equal(a, b);
1056 }
1057
1058 int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock)
1059 {
1060 #if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
1061 if (__atomic_is_lock_free(sizeof(*val), val)) {
1062 *ret = __atomic_add_fetch(val, amount, __ATOMIC_ACQ_REL);
1063 return 1;
1064 }
1065 #elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
1066 /* This will work for all future Solaris versions. */
1067 if (ret != NULL) {
1068 *ret = atomic_add_int_nv((volatile unsigned int *)val, amount);
1069 return 1;
1070 }
1071 #endif
1072 if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
1073 return 0;
1074
1075 *val += amount;
1076 *ret = *val;
1077
1078 if (!CRYPTO_THREAD_unlock(lock))
1079 return 0;
1080
1081 return 1;
1082 }
1083
1084 int CRYPTO_atomic_add64(uint64_t *val, uint64_t op, uint64_t *ret,
1085 CRYPTO_RWLOCK *lock)
1086 {
1087 #if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
1088 if (__atomic_is_lock_free(sizeof(*val), val)) {
1089 *ret = __atomic_add_fetch(val, op, __ATOMIC_ACQ_REL);
1090 return 1;
1091 }
1092 #elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
1093 /* This will work for all future Solaris versions. */
1094 if (ret != NULL) {
1095 *ret = atomic_add_64_nv(val, op);
1096 return 1;
1097 }
1098 #endif
1099 if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
1100 return 0;
1101 *val += op;
1102 *ret = *val;
1103
1104 if (!CRYPTO_THREAD_unlock(lock))
1105 return 0;
1106
1107 return 1;
1108 }
1109
1110 int CRYPTO_atomic_and(uint64_t *val, uint64_t op, uint64_t *ret,
1111 CRYPTO_RWLOCK *lock)
1112 {
1113 #if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
1114 if (__atomic_is_lock_free(sizeof(*val), val)) {
1115 *ret = __atomic_and_fetch(val, op, __ATOMIC_ACQ_REL);
1116 return 1;
1117 }
1118 #elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
1119 /* This will work for all future Solaris versions. */
1120 if (ret != NULL) {
1121 *ret = atomic_and_64_nv(val, op);
1122 return 1;
1123 }
1124 #endif
1125 if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
1126 return 0;
1127 *val &= op;
1128 *ret = *val;
1129
1130 if (!CRYPTO_THREAD_unlock(lock))
1131 return 0;
1132
1133 return 1;
1134 }
1135
1136 int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret,
1137 CRYPTO_RWLOCK *lock)
1138 {
1139 #if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
1140 if (__atomic_is_lock_free(sizeof(*val), val)) {
1141 *ret = __atomic_or_fetch(val, op, __ATOMIC_ACQ_REL);
1142 return 1;
1143 }
1144 #elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
1145 /* This will work for all future Solaris versions. */
1146 if (ret != NULL) {
1147 *ret = atomic_or_64_nv(val, op);
1148 return 1;
1149 }
1150 #endif
1151 if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
1152 return 0;
1153 *val |= op;
1154 *ret = *val;
1155
1156 if (!CRYPTO_THREAD_unlock(lock))
1157 return 0;
1158
1159 return 1;
1160 }
1161
1162 int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock)
1163 {
1164 #if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
1165 if (__atomic_is_lock_free(sizeof(*val), val)) {
1166 __atomic_load(val, ret, __ATOMIC_ACQUIRE);
1167 return 1;
1168 }
1169 #elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
1170 /* This will work for all future Solaris versions. */
1171 if (ret != NULL) {
1172 *ret = atomic_or_64_nv(val, 0);
1173 return 1;
1174 }
1175 #endif
1176 if (lock == NULL || !CRYPTO_THREAD_read_lock(lock))
1177 return 0;
1178 *ret = *val;
1179 if (!CRYPTO_THREAD_unlock(lock))
1180 return 0;
1181
1182 return 1;
1183 }
1184
1185 int CRYPTO_atomic_store(uint64_t *dst, uint64_t val, CRYPTO_RWLOCK *lock)
1186 {
1187 #if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
1188 if (__atomic_is_lock_free(sizeof(*dst), dst)) {
1189 __atomic_store(dst, &val, __ATOMIC_RELEASE);
1190 return 1;
1191 }
1192 #elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
1193 /* This will work for all future Solaris versions. */
1194 if (dst != NULL) {
1195 atomic_swap_64(dst, val);
1196 return 1;
1197 }
1198 #endif
1199 if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
1200 return 0;
1201 *dst = val;
1202 if (!CRYPTO_THREAD_unlock(lock))
1203 return 0;
1204
1205 return 1;
1206 }
1207
1208 int CRYPTO_atomic_load_int(int *val, int *ret, CRYPTO_RWLOCK *lock)
1209 {
1210 #if defined(__GNUC__) && defined(__ATOMIC_ACQ_REL) && !defined(BROKEN_CLANG_ATOMICS)
1211 if (__atomic_is_lock_free(sizeof(*val), val)) {
1212 __atomic_load(val, ret, __ATOMIC_ACQUIRE);
1213 return 1;
1214 }
1215 #elif defined(__sun) && (defined(__SunOS_5_10) || defined(__SunOS_5_11))
1216 /* This will work for all future Solaris versions. */
1217 if (ret != NULL) {
1218 *ret = (int)atomic_or_uint_nv((unsigned int *)val, 0);
1219 return 1;
1220 }
1221 #endif
1222 if (lock == NULL || !CRYPTO_THREAD_read_lock(lock))
1223 return 0;
1224 *ret = *val;
1225 if (!CRYPTO_THREAD_unlock(lock))
1226 return 0;
1227
1228 return 1;
1229 }
1230
1231 #ifndef FIPS_MODULE
1232 int openssl_init_fork_handlers(void)
1233 {
1234 return 1;
1235 }
1236 #endif /* FIPS_MODULE */
1237
1238 int openssl_get_fork_id(void)
1239 {
1240 return getpid();
1241 }
1242 #endif