spinlock.c 21 KB

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