threads_win.c 16 KB

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