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