threads_win.c 16 KB

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