threads_win.c 16 KB

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