threads_win.c 15 KB

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