spinlock.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. /* Linuxthreads - a simple clone()-based implementation of Posix */
  2. /* threads for Linux. */
  3. /* Copyright (C) 1998 Xavier Leroy (Xavier.Leroy@inria.fr) */
  4. /* */
  5. /* This program is free software; you can redistribute it and/or */
  6. /* modify it under the terms of the GNU Library General Public License */
  7. /* as published by the Free Software Foundation; either version 2 */
  8. /* of the License, or (at your option) any later version. */
  9. /* */
  10. /* This program is distributed in the hope that it will be useful, */
  11. /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
  12. /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
  13. /* GNU Library General Public License for more details. */
  14. /* Internal locks */
  15. #define __FORCE_GLIBC
  16. #include <features.h>
  17. #include <errno.h>
  18. #include <sched.h>
  19. #include <time.h>
  20. #include <stdlib.h>
  21. #include <limits.h>
  22. #include "pthread.h"
  23. #include "internals.h"
  24. #include "spinlock.h"
  25. #include "restart.h"
  26. static void __pthread_acquire(int * spinlock);
  27. static inline void __pthread_release(int * spinlock)
  28. {
  29. WRITE_MEMORY_BARRIER();
  30. *spinlock = __LT_SPINLOCK_INIT;
  31. __asm __volatile ("" : "=m" (*spinlock) : "0" (*spinlock));
  32. }
  33. /* The status field of a spinlock is a pointer whose least significant
  34. bit is a locked flag.
  35. Thus the field values have the following meanings:
  36. status == 0: spinlock is free
  37. status == 1: spinlock is taken; no thread is waiting on it
  38. (status & 1) == 1: spinlock is taken and (status & ~1L) is a
  39. pointer to the first waiting thread; other
  40. waiting threads are linked via the p_nextlock
  41. field.
  42. (status & 1) == 0: same as above, but spinlock is not taken.
  43. The waiting list is not sorted by priority order.
  44. Actually, we always insert at top of list (sole insertion mode
  45. that can be performed without locking).
  46. For __pthread_unlock, we perform a linear search in the list
  47. to find the highest-priority, oldest waiting thread.
  48. This is safe because there are no concurrent __pthread_unlock
  49. operations -- only the thread that locked the mutex can unlock it. */
  50. void internal_function __pthread_lock(struct _pthread_fastlock * lock,
  51. pthread_descr self)
  52. {
  53. #if defined HAS_COMPARE_AND_SWAP
  54. long oldstatus, newstatus;
  55. int successful_seizure, spurious_wakeup_count;
  56. int spin_count;
  57. #endif
  58. #if defined TEST_FOR_COMPARE_AND_SWAP
  59. if (!__pthread_has_cas)
  60. #endif
  61. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  62. {
  63. __pthread_acquire(&lock->__spinlock);
  64. return;
  65. }
  66. #endif
  67. #if defined HAS_COMPARE_AND_SWAP
  68. /* First try it without preparation. Maybe it's a completely
  69. uncontested lock. */
  70. if (lock->__status == 0 && __compare_and_swap (&lock->__status, 0, 1))
  71. return;
  72. spurious_wakeup_count = 0;
  73. spin_count = 0;
  74. /* On SMP, try spinning to get the lock. */
  75. #if 0
  76. if (__pthread_smp_kernel) {
  77. int max_count = lock->__spinlock * 2 + 10;
  78. if (max_count > MAX_ADAPTIVE_SPIN_COUNT)
  79. max_count = MAX_ADAPTIVE_SPIN_COUNT;
  80. for (spin_count = 0; spin_count < max_count; spin_count++) {
  81. if (((oldstatus = lock->__status) & 1) == 0) {
  82. if(__compare_and_swap(&lock->__status, oldstatus, oldstatus | 1))
  83. {
  84. if (spin_count)
  85. lock->__spinlock += (spin_count - lock->__spinlock) / 8;
  86. READ_MEMORY_BARRIER();
  87. return;
  88. }
  89. }
  90. #ifdef BUSY_WAIT_NOP
  91. BUSY_WAIT_NOP;
  92. #endif
  93. __asm __volatile ("" : "=m" (lock->__status) : "0" (lock->__status));
  94. }
  95. lock->__spinlock += (spin_count - lock->__spinlock) / 8;
  96. }
  97. #endif
  98. again:
  99. /* No luck, try once more or suspend. */
  100. do {
  101. oldstatus = lock->__status;
  102. successful_seizure = 0;
  103. if ((oldstatus & 1) == 0) {
  104. newstatus = oldstatus | 1;
  105. successful_seizure = 1;
  106. } else {
  107. if (self == NULL)
  108. self = thread_self();
  109. newstatus = (long) self | 1;
  110. }
  111. if (self != NULL) {
  112. THREAD_SETMEM(self, p_nextlock, (pthread_descr) (oldstatus));
  113. /* Make sure the store in p_nextlock completes before performing
  114. the compare-and-swap */
  115. MEMORY_BARRIER();
  116. }
  117. } while(! __compare_and_swap(&lock->__status, oldstatus, newstatus));
  118. /* Suspend with guard against spurious wakeup.
  119. This can happen in pthread_cond_timedwait_relative, when the thread
  120. wakes up due to timeout and is still on the condvar queue, and then
  121. locks the queue to remove itself. At that point it may still be on the
  122. queue, and may be resumed by a condition signal. */
  123. if (!successful_seizure) {
  124. for (;;) {
  125. suspend(self);
  126. if (self->p_nextlock != NULL) {
  127. /* Count resumes that don't belong to us. */
  128. spurious_wakeup_count++;
  129. continue;
  130. }
  131. break;
  132. }
  133. goto again;
  134. }
  135. /* Put back any resumes we caught that don't belong to us. */
  136. while (spurious_wakeup_count--)
  137. restart(self);
  138. READ_MEMORY_BARRIER();
  139. #endif
  140. }
  141. int __pthread_unlock(struct _pthread_fastlock * lock)
  142. {
  143. #if defined HAS_COMPARE_AND_SWAP
  144. long oldstatus;
  145. pthread_descr thr, * ptr, * maxptr;
  146. int maxprio;
  147. #endif
  148. #if defined TEST_FOR_COMPARE_AND_SWAP
  149. if (!__pthread_has_cas)
  150. #endif
  151. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  152. {
  153. __pthread_release(&lock->__spinlock);
  154. return 0;
  155. }
  156. #endif
  157. #if defined HAS_COMPARE_AND_SWAP
  158. WRITE_MEMORY_BARRIER();
  159. again:
  160. while ((oldstatus = lock->__status) == 1) {
  161. if (__compare_and_swap_with_release_semantics(&lock->__status,
  162. oldstatus, 0))
  163. return 0;
  164. }
  165. /* Find thread in waiting queue with maximal priority */
  166. ptr = (pthread_descr *) &lock->__status;
  167. thr = (pthread_descr) (oldstatus & ~1L);
  168. maxprio = 0;
  169. maxptr = ptr;
  170. /* Before we iterate over the wait queue, we need to execute
  171. a read barrier, otherwise we may read stale contents of nodes that may
  172. just have been inserted by other processors. One read barrier is enough to
  173. ensure we have a stable list; we don't need one for each pointer chase
  174. through the list, because we are the owner of the lock; other threads
  175. can only add nodes at the front; if a front node is consistent,
  176. the ones behind it must also be. */
  177. READ_MEMORY_BARRIER();
  178. while (thr != 0) {
  179. if (thr->p_priority >= maxprio) {
  180. maxptr = ptr;
  181. maxprio = thr->p_priority;
  182. }
  183. ptr = &(thr->p_nextlock);
  184. thr = (pthread_descr)((long)(thr->p_nextlock) & ~1L);
  185. }
  186. /* Remove max prio thread from waiting list. */
  187. if (maxptr == (pthread_descr *) &lock->__status) {
  188. /* If max prio thread is at head, remove it with compare-and-swap
  189. to guard against concurrent lock operation. This removal
  190. also has the side effect of marking the lock as released
  191. because the new status comes from thr->p_nextlock whose
  192. least significant bit is clear. */
  193. thr = (pthread_descr) (oldstatus & ~1L);
  194. if (! __compare_and_swap_with_release_semantics
  195. (&lock->__status, oldstatus, (long)(thr->p_nextlock) & ~1L))
  196. goto again;
  197. } else {
  198. /* No risk of concurrent access, remove max prio thread normally.
  199. But in this case we must also flip the least significant bit
  200. of the status to mark the lock as released. */
  201. thr = (pthread_descr)((long)*maxptr & ~1L);
  202. *maxptr = thr->p_nextlock;
  203. /* Ensure deletion from linked list completes before we
  204. release the lock. */
  205. WRITE_MEMORY_BARRIER();
  206. do {
  207. oldstatus = lock->__status;
  208. } while (!__compare_and_swap_with_release_semantics(&lock->__status,
  209. oldstatus, oldstatus & ~1L));
  210. }
  211. /* Wake up the selected waiting thread. Woken thread can check
  212. its own p_nextlock field for NULL to detect that it has been removed. No
  213. barrier is needed here, since restart() and suspend() take
  214. care of memory synchronization. */
  215. thr->p_nextlock = NULL;
  216. restart(thr);
  217. return 0;
  218. #endif
  219. }
  220. /*
  221. * Alternate fastlocks do not queue threads directly. Instead, they queue
  222. * these wait queue node structures. When a timed wait wakes up due to
  223. * a timeout, it can leave its wait node in the queue (because there
  224. * is no safe way to remove from the quue). Some other thread will
  225. * deallocate the abandoned node.
  226. */
  227. struct wait_node {
  228. struct wait_node *next; /* Next node in null terminated linked list */
  229. pthread_descr thr; /* The thread waiting with this node */
  230. int abandoned; /* Atomic flag */
  231. };
  232. static long wait_node_free_list;
  233. static int wait_node_free_list_spinlock;
  234. /* Allocate a new node from the head of the free list using an atomic
  235. operation, or else using malloc if that list is empty. A fundamental
  236. assumption here is that we can safely access wait_node_free_list->next.
  237. That's because we never free nodes once we allocate them, so a pointer to a
  238. node remains valid indefinitely. */
  239. static struct wait_node *wait_node_alloc(void)
  240. {
  241. struct wait_node *new_node = 0;
  242. __pthread_acquire(&wait_node_free_list_spinlock);
  243. if (wait_node_free_list != 0) {
  244. new_node = (struct wait_node *) wait_node_free_list;
  245. wait_node_free_list = (long) new_node->next;
  246. }
  247. WRITE_MEMORY_BARRIER();
  248. __pthread_release(&wait_node_free_list_spinlock);
  249. if (new_node == 0)
  250. return malloc(sizeof *wait_node_alloc());
  251. return new_node;
  252. }
  253. /* Return a node to the head of the free list using an atomic
  254. operation. */
  255. static void wait_node_free(struct wait_node *wn)
  256. {
  257. __pthread_acquire(&wait_node_free_list_spinlock);
  258. wn->next = (struct wait_node *) wait_node_free_list;
  259. wait_node_free_list = (long) wn;
  260. WRITE_MEMORY_BARRIER();
  261. __pthread_release(&wait_node_free_list_spinlock);
  262. return;
  263. }
  264. #if defined HAS_COMPARE_AND_SWAP
  265. /* Remove a wait node from the specified queue. It is assumed
  266. that the removal takes place concurrently with only atomic insertions at the
  267. head of the queue. */
  268. static void wait_node_dequeue(struct wait_node **pp_head,
  269. struct wait_node **pp_node,
  270. struct wait_node *p_node)
  271. {
  272. /* If the node is being deleted from the head of the
  273. list, it must be deleted using atomic compare-and-swap.
  274. Otherwise it can be deleted in the straightforward way. */
  275. if (pp_node == pp_head) {
  276. /* We don't need a read barrier between these next two loads,
  277. because it is assumed that the caller has already ensured
  278. the stability of *p_node with respect to p_node. */
  279. long oldvalue = (long) p_node;
  280. long newvalue = (long) p_node->next;
  281. if (__compare_and_swap((long *) pp_node, oldvalue, newvalue))
  282. return;
  283. /* Oops! Compare and swap failed, which means the node is
  284. no longer first. We delete it using the ordinary method. But we don't
  285. know the identity of the node which now holds the pointer to the node
  286. being deleted, so we must search from the beginning. */
  287. for (pp_node = pp_head; p_node != *pp_node; ) {
  288. pp_node = &(*pp_node)->next;
  289. READ_MEMORY_BARRIER(); /* Stabilize *pp_node for next iteration. */
  290. }
  291. }
  292. *pp_node = p_node->next;
  293. return;
  294. }
  295. #endif
  296. void __pthread_alt_lock(struct _pthread_fastlock * lock,
  297. pthread_descr self)
  298. {
  299. #if defined HAS_COMPARE_AND_SWAP
  300. long oldstatus, newstatus;
  301. #endif
  302. struct wait_node wait_node;
  303. #if defined TEST_FOR_COMPARE_AND_SWAP
  304. if (!__pthread_has_cas)
  305. #endif
  306. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  307. {
  308. int suspend_needed = 0;
  309. __pthread_acquire(&lock->__spinlock);
  310. if (lock->__status == 0)
  311. lock->__status = 1;
  312. else {
  313. if (self == NULL)
  314. self = thread_self();
  315. wait_node.abandoned = 0;
  316. wait_node.next = (struct wait_node *) lock->__status;
  317. wait_node.thr = self;
  318. lock->__status = (long) &wait_node;
  319. suspend_needed = 1;
  320. }
  321. __pthread_release(&lock->__spinlock);
  322. if (suspend_needed)
  323. suspend (self);
  324. return;
  325. }
  326. #endif
  327. #if defined HAS_COMPARE_AND_SWAP
  328. do {
  329. oldstatus = lock->__status;
  330. if (oldstatus == 0) {
  331. newstatus = 1;
  332. } else {
  333. if (self == NULL)
  334. self = thread_self();
  335. wait_node.thr = self;
  336. newstatus = (long) &wait_node;
  337. }
  338. wait_node.abandoned = 0;
  339. wait_node.next = (struct wait_node *) oldstatus;
  340. /* Make sure the store in wait_node.next completes before performing
  341. the compare-and-swap */
  342. MEMORY_BARRIER();
  343. } while(! __compare_and_swap(&lock->__status, oldstatus, newstatus));
  344. /* Suspend. Note that unlike in __pthread_lock, we don't worry
  345. here about spurious wakeup. That's because this lock is not
  346. used in situations where that can happen; the restart can
  347. only come from the previous lock owner. */
  348. if (oldstatus != 0)
  349. suspend(self);
  350. READ_MEMORY_BARRIER();
  351. #endif
  352. }
  353. /* Timed-out lock operation; returns 0 to indicate timeout. */
  354. int __pthread_alt_timedlock(struct _pthread_fastlock * lock,
  355. pthread_descr self, const struct timespec *abstime)
  356. {
  357. long oldstatus = 0;
  358. #if defined HAS_COMPARE_AND_SWAP
  359. long newstatus;
  360. #endif
  361. struct wait_node *p_wait_node = wait_node_alloc();
  362. /* Out of memory, just give up and do ordinary lock. */
  363. if (p_wait_node == 0) {
  364. __pthread_alt_lock(lock, self);
  365. return 1;
  366. }
  367. #if defined TEST_FOR_COMPARE_AND_SWAP
  368. if (!__pthread_has_cas)
  369. #endif
  370. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  371. {
  372. __pthread_acquire(&lock->__spinlock);
  373. if (lock->__status == 0)
  374. lock->__status = 1;
  375. else {
  376. if (self == NULL)
  377. self = thread_self();
  378. p_wait_node->abandoned = 0;
  379. p_wait_node->next = (struct wait_node *) lock->__status;
  380. p_wait_node->thr = self;
  381. lock->__status = (long) p_wait_node;
  382. oldstatus = 1; /* force suspend */
  383. }
  384. __pthread_release(&lock->__spinlock);
  385. goto suspend;
  386. }
  387. #endif
  388. #if defined HAS_COMPARE_AND_SWAP
  389. do {
  390. oldstatus = lock->__status;
  391. if (oldstatus == 0) {
  392. newstatus = 1;
  393. } else {
  394. if (self == NULL)
  395. self = thread_self();
  396. p_wait_node->thr = self;
  397. newstatus = (long) p_wait_node;
  398. }
  399. p_wait_node->abandoned = 0;
  400. p_wait_node->next = (struct wait_node *) oldstatus;
  401. /* Make sure the store in wait_node.next completes before performing
  402. the compare-and-swap */
  403. MEMORY_BARRIER();
  404. } while(! __compare_and_swap(&lock->__status, oldstatus, newstatus));
  405. #endif
  406. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  407. suspend:
  408. #endif
  409. /* If we did not get the lock, do a timed suspend. If we wake up due
  410. to a timeout, then there is a race; the old lock owner may try
  411. to remove us from the queue. This race is resolved by us and the owner
  412. doing an atomic testandset() to change the state of the wait node from 0
  413. to 1. If we succeed, then it's a timeout and we abandon the node in the
  414. queue. If we fail, it means the owner gave us the lock. */
  415. if (oldstatus != 0) {
  416. if (timedsuspend(self, abstime) == 0) {
  417. if (!testandset(&p_wait_node->abandoned))
  418. return 0; /* Timeout! */
  419. /* Eat oustanding resume from owner, otherwise wait_node_free() below
  420. will race with owner's wait_node_dequeue(). */
  421. suspend(self);
  422. }
  423. }
  424. wait_node_free(p_wait_node);
  425. READ_MEMORY_BARRIER();
  426. return 1; /* Got the lock! */
  427. }
  428. void __pthread_alt_unlock(struct _pthread_fastlock *lock)
  429. {
  430. struct wait_node *p_node, **pp_node, *p_max_prio, **pp_max_prio;
  431. struct wait_node ** const pp_head = (struct wait_node **) &lock->__status;
  432. int maxprio;
  433. WRITE_MEMORY_BARRIER();
  434. #if defined TEST_FOR_COMPARE_AND_SWAP
  435. if (!__pthread_has_cas)
  436. #endif
  437. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  438. {
  439. __pthread_acquire(&lock->__spinlock);
  440. }
  441. #endif
  442. while (1) {
  443. /* If no threads are waiting for this lock, try to just
  444. atomically release it. */
  445. #if defined TEST_FOR_COMPARE_AND_SWAP
  446. if (!__pthread_has_cas)
  447. #endif
  448. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  449. {
  450. if (lock->__status == 0 || lock->__status == 1) {
  451. lock->__status = 0;
  452. break;
  453. }
  454. }
  455. #endif
  456. #if defined TEST_FOR_COMPARE_AND_SWAP
  457. else
  458. #endif
  459. #if defined HAS_COMPARE_AND_SWAP
  460. {
  461. long oldstatus = lock->__status;
  462. if (oldstatus == 0 || oldstatus == 1) {
  463. if (__compare_and_swap_with_release_semantics (&lock->__status, oldstatus, 0))
  464. break;
  465. else
  466. continue;
  467. }
  468. }
  469. #endif
  470. /* Process the entire queue of wait nodes. Remove all abandoned
  471. wait nodes and put them into the global free queue, and
  472. remember the one unabandoned node which refers to the thread
  473. having the highest priority. */
  474. pp_max_prio = pp_node = pp_head;
  475. p_max_prio = p_node = *pp_head;
  476. maxprio = INT_MIN;
  477. READ_MEMORY_BARRIER(); /* Prevent access to stale data through p_node */
  478. while (p_node != (struct wait_node *) 1) {
  479. int prio;
  480. if (p_node->abandoned) {
  481. /* Remove abandoned node. */
  482. #if defined TEST_FOR_COMPARE_AND_SWAP
  483. if (!__pthread_has_cas)
  484. #endif
  485. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  486. *pp_node = p_node->next;
  487. #endif
  488. #if defined TEST_FOR_COMPARE_AND_SWAP
  489. else
  490. #endif
  491. #if defined HAS_COMPARE_AND_SWAP
  492. wait_node_dequeue(pp_head, pp_node, p_node);
  493. #endif
  494. wait_node_free(p_node);
  495. /* Note that the next assignment may take us to the beginning
  496. of the queue, to newly inserted nodes, if pp_node == pp_head.
  497. In that case we need a memory barrier to stabilize the first of
  498. these new nodes. */
  499. p_node = *pp_node;
  500. if (pp_node == pp_head)
  501. READ_MEMORY_BARRIER(); /* No stale reads through p_node */
  502. continue;
  503. } else if ((prio = p_node->thr->p_priority) >= maxprio) {
  504. /* Otherwise remember it if its thread has a higher or equal priority
  505. compared to that of any node seen thus far. */
  506. maxprio = prio;
  507. pp_max_prio = pp_node;
  508. p_max_prio = p_node;
  509. }
  510. /* This canno6 jump backward in the list, so no further read
  511. barrier is needed. */
  512. pp_node = &p_node->next;
  513. p_node = *pp_node;
  514. }
  515. /* If all threads abandoned, go back to top */
  516. if (maxprio == INT_MIN)
  517. continue;
  518. ASSERT (p_max_prio != (struct wait_node *) 1);
  519. /* Now we want to to remove the max priority thread's wait node from
  520. the list. Before we can do this, we must atomically try to change the
  521. node's abandon state from zero to nonzero. If we succeed, that means we
  522. have the node that we will wake up. If we failed, then it means the
  523. thread timed out and abandoned the node in which case we repeat the
  524. whole unlock operation. */
  525. if (!testandset(&p_max_prio->abandoned)) {
  526. #if defined TEST_FOR_COMPARE_AND_SWAP
  527. if (!__pthread_has_cas)
  528. #endif
  529. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  530. *pp_max_prio = p_max_prio->next;
  531. #endif
  532. #if defined TEST_FOR_COMPARE_AND_SWAP
  533. else
  534. #endif
  535. #if defined HAS_COMPARE_AND_SWAP
  536. wait_node_dequeue(pp_head, pp_max_prio, p_max_prio);
  537. #endif
  538. restart(p_max_prio->thr);
  539. break;
  540. }
  541. }
  542. #if defined TEST_FOR_COMPARE_AND_SWAP
  543. if (!__pthread_has_cas)
  544. #endif
  545. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  546. {
  547. __pthread_release(&lock->__spinlock);
  548. }
  549. #endif
  550. }
  551. /* Compare-and-swap emulation with a spinlock */
  552. #ifdef TEST_FOR_COMPARE_AND_SWAP
  553. int __pthread_has_cas = 0;
  554. #endif
  555. #if !defined HAS_COMPARE_AND_SWAP || defined TEST_FOR_COMPARE_AND_SWAP
  556. int __pthread_compare_and_swap(long * ptr, long oldval, long newval,
  557. int * spinlock)
  558. {
  559. int res;
  560. __pthread_acquire(spinlock);
  561. if (*ptr == oldval) {
  562. *ptr = newval; res = 1;
  563. } else {
  564. res = 0;
  565. }
  566. __pthread_release(spinlock);
  567. return res;
  568. }
  569. #endif
  570. /* The retry strategy is as follows:
  571. - We test and set the spinlock MAX_SPIN_COUNT times, calling
  572. sched_yield() each time. This gives ample opportunity for other
  573. threads with priority >= our priority to make progress and
  574. release the spinlock.
  575. - If a thread with priority < our priority owns the spinlock,
  576. calling sched_yield() repeatedly is useless, since we're preventing
  577. the owning thread from making progress and releasing the spinlock.
  578. So, after MAX_SPIN_LOCK attemps, we suspend the calling thread
  579. using nanosleep(). This again should give time to the owning thread
  580. for releasing the spinlock.
  581. Notice that the nanosleep() interval must not be too small,
  582. since the kernel does busy-waiting for short intervals in a realtime
  583. process (!). The smallest duration that guarantees thread
  584. suspension is currently 2ms.
  585. - When nanosleep() returns, we try again, doing MAX_SPIN_COUNT
  586. sched_yield(), then sleeping again if needed. */
  587. static void __pthread_acquire(int * spinlock)
  588. {
  589. int cnt = 0;
  590. struct timespec tm;
  591. READ_MEMORY_BARRIER();
  592. while (testandset(spinlock)) {
  593. if (cnt < MAX_SPIN_COUNT) {
  594. sched_yield();
  595. cnt++;
  596. } else {
  597. tm.tv_sec = 0;
  598. tm.tv_nsec = SPIN_SLEEP_DURATION;
  599. nanosleep(&tm, NULL);
  600. cnt = 0;
  601. }
  602. }
  603. }