threads_win.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. /*
  2. * Copyright 2016-2025 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. #if defined(_WIN32)
  10. # include <windows.h>
  11. # if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600
  12. # define USE_RWLOCK
  13. # endif
  14. #endif
  15. #include <assert.h>
  16. /*
  17. * VC++ 2008 or earlier x86 compilers do not have an inline implementation
  18. * of InterlockedOr64 for 32bit and will fail to run on Windows XP 32bit.
  19. * https://docs.microsoft.com/en-us/cpp/intrinsics/interlockedor-intrinsic-functions#requirements
  20. * To work around this problem, we implement a manual locking mechanism for
  21. * only VC++ 2008 or earlier x86 compilers.
  22. */
  23. #if (defined(_MSC_VER) && defined(_M_IX86) && _MSC_VER <= 1600)
  24. # define NO_INTERLOCKEDOR64
  25. #endif
  26. #include <openssl/crypto.h>
  27. #include <crypto/cryptlib.h>
  28. #include "internal/common.h"
  29. #include "internal/thread_arch.h"
  30. #include "internal/rcu.h"
  31. #include "rcu_internal.h"
  32. #if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG) && defined(OPENSSL_SYS_WINDOWS)
  33. # ifdef USE_RWLOCK
  34. typedef struct {
  35. SRWLOCK lock;
  36. int exclusive;
  37. } CRYPTO_win_rwlock;
  38. # endif
  39. /*
  40. * This defines a quescent point (qp)
  41. * This is the barrier beyond which a writer
  42. * must wait before freeing data that was
  43. * atomically updated
  44. */
  45. struct rcu_qp {
  46. volatile LONG64 users;
  47. };
  48. struct thread_qp {
  49. struct rcu_qp *qp;
  50. unsigned int depth;
  51. CRYPTO_RCU_LOCK *lock;
  52. };
  53. #define MAX_QPS 10
  54. /*
  55. * This is the per thread tracking data
  56. * that is assigned to each thread participating
  57. * in an rcu qp
  58. *
  59. * qp points to the qp that it last acquired
  60. *
  61. */
  62. struct rcu_thr_data {
  63. struct thread_qp thread_qps[MAX_QPS];
  64. };
  65. /*
  66. * This is the internal version of a CRYPTO_RCU_LOCK
  67. * it is cast from CRYPTO_RCU_LOCK
  68. */
  69. struct rcu_lock_st {
  70. struct rcu_cb_item *cb_items;
  71. OSSL_LIB_CTX *ctx;
  72. /* Array of quiescent points for synchronization */
  73. struct rcu_qp *qp_group;
  74. /* rcu generation counter for in-order retirement */
  75. uint32_t id_ctr;
  76. /* Number of elements in qp_group array */
  77. uint32_t group_count;
  78. uint32_t next_to_retire;
  79. volatile long int reader_idx;
  80. uint32_t current_alloc_idx;
  81. uint32_t writers_alloced;
  82. CRYPTO_MUTEX *write_lock;
  83. CRYPTO_MUTEX *alloc_lock;
  84. CRYPTO_CONDVAR *alloc_signal;
  85. CRYPTO_MUTEX *prior_lock;
  86. CRYPTO_CONDVAR *prior_signal;
  87. };
  88. static struct rcu_qp *allocate_new_qp_group(struct rcu_lock_st *lock,
  89. uint32_t count)
  90. {
  91. struct rcu_qp *new =
  92. OPENSSL_zalloc(sizeof(*new) * count);
  93. lock->group_count = count;
  94. return new;
  95. }
  96. CRYPTO_RCU_LOCK *ossl_rcu_lock_new(int num_writers, OSSL_LIB_CTX *ctx)
  97. {
  98. struct rcu_lock_st *new;
  99. /*
  100. * We need a minimum of 2 qps
  101. */
  102. if (num_writers < 2)
  103. num_writers = 2;
  104. ctx = ossl_lib_ctx_get_concrete(ctx);
  105. if (ctx == NULL)
  106. return 0;
  107. new = OPENSSL_zalloc(sizeof(*new));
  108. if (new == NULL)
  109. return NULL;
  110. new->ctx = ctx;
  111. new->write_lock = ossl_crypto_mutex_new();
  112. new->alloc_signal = ossl_crypto_condvar_new();
  113. new->prior_signal = ossl_crypto_condvar_new();
  114. new->alloc_lock = ossl_crypto_mutex_new();
  115. new->prior_lock = ossl_crypto_mutex_new();
  116. new->qp_group = allocate_new_qp_group(new, num_writers);
  117. if (new->qp_group == NULL
  118. || new->alloc_signal == NULL
  119. || new->prior_signal == NULL
  120. || new->write_lock == NULL
  121. || new->alloc_lock == NULL
  122. || new->prior_lock == NULL) {
  123. OPENSSL_free(new->qp_group);
  124. ossl_crypto_condvar_free(&new->alloc_signal);
  125. ossl_crypto_condvar_free(&new->prior_signal);
  126. ossl_crypto_mutex_free(&new->alloc_lock);
  127. ossl_crypto_mutex_free(&new->prior_lock);
  128. ossl_crypto_mutex_free(&new->write_lock);
  129. OPENSSL_free(new);
  130. new = NULL;
  131. }
  132. return new;
  133. }
  134. void ossl_rcu_lock_free(CRYPTO_RCU_LOCK *lock)
  135. {
  136. OPENSSL_free(lock->qp_group);
  137. ossl_crypto_condvar_free(&lock->alloc_signal);
  138. ossl_crypto_condvar_free(&lock->prior_signal);
  139. ossl_crypto_mutex_free(&lock->alloc_lock);
  140. ossl_crypto_mutex_free(&lock->prior_lock);
  141. ossl_crypto_mutex_free(&lock->write_lock);
  142. OPENSSL_free(lock);
  143. }
  144. static ossl_inline struct rcu_qp *get_hold_current_qp(CRYPTO_RCU_LOCK *lock)
  145. {
  146. uint32_t qp_idx;
  147. /* get the current qp index */
  148. for (;;) {
  149. qp_idx = InterlockedOr(&lock->reader_idx, 0);
  150. InterlockedAdd64(&lock->qp_group[qp_idx].users, (LONG64)1);
  151. if (qp_idx == InterlockedOr(&lock->reader_idx, 0))
  152. break;
  153. InterlockedAdd64(&lock->qp_group[qp_idx].users, (LONG64)-1);
  154. }
  155. return &lock->qp_group[qp_idx];
  156. }
  157. static void ossl_rcu_free_local_data(void *arg)
  158. {
  159. OSSL_LIB_CTX *ctx = arg;
  160. CRYPTO_THREAD_LOCAL *lkey = ossl_lib_ctx_get_rcukey(ctx);
  161. struct rcu_thr_data *data = CRYPTO_THREAD_get_local(lkey);
  162. OPENSSL_free(data);
  163. CRYPTO_THREAD_set_local(lkey, NULL);
  164. }
  165. void ossl_rcu_read_lock(CRYPTO_RCU_LOCK *lock)
  166. {
  167. struct rcu_thr_data *data;
  168. int i;
  169. int available_qp = -1;
  170. CRYPTO_THREAD_LOCAL *lkey = ossl_lib_ctx_get_rcukey(lock->ctx);
  171. /*
  172. * we're going to access current_qp here so ask the
  173. * processor to fetch it
  174. */
  175. data = CRYPTO_THREAD_get_local(lkey);
  176. if (data == NULL) {
  177. data = OPENSSL_zalloc(sizeof(*data));
  178. OPENSSL_assert(data != NULL);
  179. CRYPTO_THREAD_set_local(lkey, data);
  180. ossl_init_thread_start(NULL, lock->ctx, ossl_rcu_free_local_data);
  181. }
  182. for (i = 0; i < MAX_QPS; i++) {
  183. if (data->thread_qps[i].qp == NULL && available_qp == -1)
  184. available_qp = i;
  185. /* If we have a hold on this lock already, we're good */
  186. if (data->thread_qps[i].lock == lock)
  187. return;
  188. }
  189. /*
  190. * if we get here, then we don't have a hold on this lock yet
  191. */
  192. assert(available_qp != -1);
  193. data->thread_qps[available_qp].qp = get_hold_current_qp(lock);
  194. data->thread_qps[available_qp].depth = 1;
  195. data->thread_qps[available_qp].lock = lock;
  196. }
  197. void ossl_rcu_write_lock(CRYPTO_RCU_LOCK *lock)
  198. {
  199. ossl_crypto_mutex_lock(lock->write_lock);
  200. }
  201. void ossl_rcu_write_unlock(CRYPTO_RCU_LOCK *lock)
  202. {
  203. ossl_crypto_mutex_unlock(lock->write_lock);
  204. }
  205. void ossl_rcu_read_unlock(CRYPTO_RCU_LOCK *lock)
  206. {
  207. CRYPTO_THREAD_LOCAL *lkey = ossl_lib_ctx_get_rcukey(lock->ctx);
  208. struct rcu_thr_data *data = CRYPTO_THREAD_get_local(lkey);
  209. int i;
  210. LONG64 ret;
  211. assert(data != NULL);
  212. for (i = 0; i < MAX_QPS; i++) {
  213. if (data->thread_qps[i].lock == lock) {
  214. data->thread_qps[i].depth--;
  215. if (data->thread_qps[i].depth == 0) {
  216. ret = InterlockedAdd64(&data->thread_qps[i].qp->users, (LONG64)-1);
  217. OPENSSL_assert(ret >= 0);
  218. data->thread_qps[i].qp = NULL;
  219. data->thread_qps[i].lock = NULL;
  220. }
  221. return;
  222. }
  223. }
  224. }
  225. static struct rcu_qp *update_qp(CRYPTO_RCU_LOCK *lock, uint32_t *curr_id)
  226. {
  227. uint32_t current_idx;
  228. uint32_t tmp;
  229. ossl_crypto_mutex_lock(lock->alloc_lock);
  230. /*
  231. * we need at least one qp to be available with one
  232. * left over, so that readers can start working on
  233. * one that isn't yet being waited on
  234. */
  235. while (lock->group_count - lock->writers_alloced < 2)
  236. ossl_crypto_condvar_wait(lock->alloc_signal, lock->alloc_lock);
  237. current_idx = lock->current_alloc_idx;
  238. /* Allocate the qp */
  239. lock->writers_alloced++;
  240. /* increment the allocation index */
  241. lock->current_alloc_idx =
  242. (lock->current_alloc_idx + 1) % lock->group_count;
  243. /* get and insert a new id */
  244. *curr_id = lock->id_ctr;
  245. lock->id_ctr++;
  246. /* update the reader index to be the prior qp */
  247. tmp = lock->current_alloc_idx;
  248. InterlockedExchange(&lock->reader_idx, tmp);
  249. /* wake up any waiters */
  250. ossl_crypto_condvar_broadcast(lock->alloc_signal);
  251. ossl_crypto_mutex_unlock(lock->alloc_lock);
  252. return &lock->qp_group[current_idx];
  253. }
  254. static void retire_qp(CRYPTO_RCU_LOCK *lock,
  255. struct rcu_qp *qp)
  256. {
  257. ossl_crypto_mutex_lock(lock->alloc_lock);
  258. lock->writers_alloced--;
  259. ossl_crypto_condvar_broadcast(lock->alloc_signal);
  260. ossl_crypto_mutex_unlock(lock->alloc_lock);
  261. }
  262. void ossl_synchronize_rcu(CRYPTO_RCU_LOCK *lock)
  263. {
  264. struct rcu_qp *qp;
  265. uint64_t count;
  266. uint32_t curr_id;
  267. struct rcu_cb_item *cb_items, *tmpcb;
  268. /* before we do anything else, lets grab the cb list */
  269. ossl_crypto_mutex_lock(lock->write_lock);
  270. cb_items = lock->cb_items;
  271. lock->cb_items = NULL;
  272. ossl_crypto_mutex_unlock(lock->write_lock);
  273. qp = update_qp(lock, &curr_id);
  274. /* retire in order */
  275. ossl_crypto_mutex_lock(lock->prior_lock);
  276. while (lock->next_to_retire != curr_id)
  277. ossl_crypto_condvar_wait(lock->prior_signal, lock->prior_lock);
  278. /* wait for the reader count to reach zero */
  279. do {
  280. count = InterlockedOr64(&qp->users, 0);
  281. } while (count != (uint64_t)0);
  282. lock->next_to_retire++;
  283. ossl_crypto_condvar_broadcast(lock->prior_signal);
  284. ossl_crypto_mutex_unlock(lock->prior_lock);
  285. retire_qp(lock, qp);
  286. /* handle any callbacks that we have */
  287. while (cb_items != NULL) {
  288. tmpcb = cb_items;
  289. cb_items = cb_items->next;
  290. tmpcb->fn(tmpcb->data);
  291. OPENSSL_free(tmpcb);
  292. }
  293. /* and we're done */
  294. return;
  295. }
  296. /*
  297. * Note, must be called under the protection of ossl_rcu_write_lock
  298. */
  299. int ossl_rcu_call(CRYPTO_RCU_LOCK *lock, rcu_cb_fn cb, void *data)
  300. {
  301. struct rcu_cb_item *new;
  302. new = OPENSSL_zalloc(sizeof(struct rcu_cb_item));
  303. if (new == NULL)
  304. return 0;
  305. new->data = data;
  306. new->fn = cb;
  307. new->next = lock->cb_items;
  308. lock->cb_items = new;
  309. return 1;
  310. }
  311. void *ossl_rcu_uptr_deref(void **p)
  312. {
  313. return (void *)*p;
  314. }
  315. void ossl_rcu_assign_uptr(void **p, void **v)
  316. {
  317. InterlockedExchangePointer((void * volatile *)p, (void *)*v);
  318. }
  319. CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void)
  320. {
  321. CRYPTO_RWLOCK *lock;
  322. # ifdef USE_RWLOCK
  323. CRYPTO_win_rwlock *rwlock;
  324. if ((lock = OPENSSL_zalloc(sizeof(CRYPTO_win_rwlock))) == NULL)
  325. /* Don't set error, to avoid recursion blowup. */
  326. return NULL;
  327. rwlock = lock;
  328. InitializeSRWLock(&rwlock->lock);
  329. # else
  330. if ((lock = OPENSSL_zalloc(sizeof(CRITICAL_SECTION))) == NULL)
  331. /* Don't set error, to avoid recursion blowup. */
  332. return NULL;
  333. # if !defined(_WIN32_WCE)
  334. /* 0x400 is the spin count value suggested in the documentation */
  335. if (!InitializeCriticalSectionAndSpinCount(lock, 0x400)) {
  336. OPENSSL_free(lock);
  337. return NULL;
  338. }
  339. # else
  340. InitializeCriticalSection(lock);
  341. # endif
  342. # endif
  343. return lock;
  344. }
  345. __owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock)
  346. {
  347. # ifdef USE_RWLOCK
  348. CRYPTO_win_rwlock *rwlock = lock;
  349. AcquireSRWLockShared(&rwlock->lock);
  350. # else
  351. EnterCriticalSection(lock);
  352. # endif
  353. return 1;
  354. }
  355. __owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock)
  356. {
  357. # ifdef USE_RWLOCK
  358. CRYPTO_win_rwlock *rwlock = lock;
  359. AcquireSRWLockExclusive(&rwlock->lock);
  360. rwlock->exclusive = 1;
  361. # else
  362. EnterCriticalSection(lock);
  363. # endif
  364. return 1;
  365. }
  366. int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock)
  367. {
  368. # ifdef USE_RWLOCK
  369. CRYPTO_win_rwlock *rwlock = lock;
  370. if (rwlock->exclusive) {
  371. rwlock->exclusive = 0;
  372. ReleaseSRWLockExclusive(&rwlock->lock);
  373. } else {
  374. ReleaseSRWLockShared(&rwlock->lock);
  375. }
  376. # else
  377. LeaveCriticalSection(lock);
  378. # endif
  379. return 1;
  380. }
  381. void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock)
  382. {
  383. if (lock == NULL)
  384. return;
  385. # ifndef USE_RWLOCK
  386. DeleteCriticalSection(lock);
  387. # endif
  388. OPENSSL_free(lock);
  389. return;
  390. }
  391. # define ONCE_UNINITED 0
  392. # define ONCE_ININIT 1
  393. # define ONCE_DONE 2
  394. /*
  395. * We don't use InitOnceExecuteOnce because that isn't available in WinXP which
  396. * we still have to support.
  397. */
  398. int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void))
  399. {
  400. LONG volatile *lock = (LONG *)once;
  401. LONG result;
  402. if (*lock == ONCE_DONE)
  403. return 1;
  404. do {
  405. result = InterlockedCompareExchange(lock, ONCE_ININIT, ONCE_UNINITED);
  406. if (result == ONCE_UNINITED) {
  407. init();
  408. *lock = ONCE_DONE;
  409. return 1;
  410. }
  411. } while (result == ONCE_ININIT);
  412. return (*lock == ONCE_DONE);
  413. }
  414. int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *))
  415. {
  416. *key = TlsAlloc();
  417. if (*key == TLS_OUT_OF_INDEXES)
  418. return 0;
  419. return 1;
  420. }
  421. void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key)
  422. {
  423. DWORD last_error;
  424. void *ret;
  425. /*
  426. * TlsGetValue clears the last error even on success, so that callers may
  427. * distinguish it successfully returning NULL or failing. It is documented
  428. * to never fail if the argument is a valid index from TlsAlloc, so we do
  429. * not need to handle this.
  430. *
  431. * However, this error-mangling behavior interferes with the caller's use of
  432. * GetLastError. In particular SSL_get_error queries the error queue to
  433. * determine whether the caller should look at the OS's errors. To avoid
  434. * destroying state, save and restore the Windows error.
  435. *
  436. * https://msdn.microsoft.com/en-us/library/windows/desktop/ms686812(v=vs.85).aspx
  437. */
  438. last_error = GetLastError();
  439. ret = TlsGetValue(*key);
  440. SetLastError(last_error);
  441. return ret;
  442. }
  443. int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val)
  444. {
  445. if (TlsSetValue(*key, val) == 0)
  446. return 0;
  447. return 1;
  448. }
  449. int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key)
  450. {
  451. if (TlsFree(*key) == 0)
  452. return 0;
  453. return 1;
  454. }
  455. CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void)
  456. {
  457. return GetCurrentThreadId();
  458. }
  459. int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b)
  460. {
  461. return (a == b);
  462. }
  463. int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock)
  464. {
  465. *ret = (int)InterlockedExchangeAdd((LONG volatile *)val, (LONG)amount)
  466. + amount;
  467. return 1;
  468. }
  469. int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret,
  470. CRYPTO_RWLOCK *lock)
  471. {
  472. #if (defined(NO_INTERLOCKEDOR64))
  473. if (lock == NULL || !CRYPTO_THREAD_write_lock(lock))
  474. return 0;
  475. *val |= op;
  476. *ret = *val;
  477. if (!CRYPTO_THREAD_unlock(lock))
  478. return 0;
  479. return 1;
  480. #else
  481. *ret = (uint64_t)InterlockedOr64((LONG64 volatile *)val, (LONG64)op) | op;
  482. return 1;
  483. #endif
  484. }
  485. int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock)
  486. {
  487. #if (defined(NO_INTERLOCKEDOR64))
  488. if (lock == NULL || !CRYPTO_THREAD_read_lock(lock))
  489. return 0;
  490. *ret = *val;
  491. if (!CRYPTO_THREAD_unlock(lock))
  492. return 0;
  493. return 1;
  494. #else
  495. *ret = (uint64_t)InterlockedOr64((LONG64 volatile *)val, 0);
  496. return 1;
  497. #endif
  498. }
  499. int CRYPTO_atomic_load_int(int *val, int *ret, CRYPTO_RWLOCK *lock)
  500. {
  501. #if (defined(NO_INTERLOCKEDOR64))
  502. if (lock == NULL || !CRYPTO_THREAD_read_lock(lock))
  503. return 0;
  504. *ret = *val;
  505. if (!CRYPTO_THREAD_unlock(lock))
  506. return 0;
  507. return 1;
  508. #else
  509. /* On Windows, LONG is always the same size as int. */
  510. *ret = (int)InterlockedOr((LONG volatile *)val, 0);
  511. return 1;
  512. #endif
  513. }
  514. int openssl_init_fork_handlers(void)
  515. {
  516. return 0;
  517. }
  518. int openssl_get_fork_id(void)
  519. {
  520. return 0;
  521. }
  522. #endif