threads_win.c 16 KB

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