2
0

qemu-coroutine-lock.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /*
  2. * coroutine queues and locks
  3. *
  4. * Copyright (c) 2011 Kevin Wolf <kwolf@redhat.com>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. *
  24. * The lock-free mutex implementation is based on OSv
  25. * (core/lfmutex.cc, include/lockfree/mutex.hh).
  26. * Copyright (C) 2013 Cloudius Systems, Ltd.
  27. */
  28. #include "qemu/osdep.h"
  29. #include "qemu/coroutine_int.h"
  30. #include "qemu/processor.h"
  31. #include "qemu/queue.h"
  32. #include "block/aio.h"
  33. #include "trace.h"
  34. void qemu_co_queue_init(CoQueue *queue)
  35. {
  36. QSIMPLEQ_INIT(&queue->entries);
  37. }
  38. void coroutine_fn qemu_co_queue_wait_impl(CoQueue *queue, QemuLockable *lock,
  39. CoQueueWaitFlags flags)
  40. {
  41. Coroutine *self = qemu_coroutine_self();
  42. if (flags & CO_QUEUE_WAIT_FRONT) {
  43. QSIMPLEQ_INSERT_HEAD(&queue->entries, self, co_queue_next);
  44. } else {
  45. QSIMPLEQ_INSERT_TAIL(&queue->entries, self, co_queue_next);
  46. }
  47. if (lock) {
  48. qemu_lockable_unlock(lock);
  49. }
  50. /* There is no race condition here. Other threads will call
  51. * aio_co_schedule on our AioContext, which can reenter this
  52. * coroutine but only after this yield and after the main loop
  53. * has gone through the next iteration.
  54. */
  55. qemu_coroutine_yield();
  56. assert(qemu_in_coroutine());
  57. /* TODO: OSv implements wait morphing here, where the wakeup
  58. * primitive automatically places the woken coroutine on the
  59. * mutex's queue. This avoids the thundering herd effect.
  60. * This could be implemented for CoMutexes, but not really for
  61. * other cases of QemuLockable.
  62. */
  63. if (lock) {
  64. qemu_lockable_lock(lock);
  65. }
  66. }
  67. bool qemu_co_enter_next_impl(CoQueue *queue, QemuLockable *lock)
  68. {
  69. Coroutine *next;
  70. next = QSIMPLEQ_FIRST(&queue->entries);
  71. if (!next) {
  72. return false;
  73. }
  74. QSIMPLEQ_REMOVE_HEAD(&queue->entries, co_queue_next);
  75. if (lock) {
  76. qemu_lockable_unlock(lock);
  77. }
  78. aio_co_wake(next);
  79. if (lock) {
  80. qemu_lockable_lock(lock);
  81. }
  82. return true;
  83. }
  84. bool coroutine_fn qemu_co_queue_next(CoQueue *queue)
  85. {
  86. /* No unlock/lock needed in coroutine context. */
  87. return qemu_co_enter_next_impl(queue, NULL);
  88. }
  89. void qemu_co_enter_all_impl(CoQueue *queue, QemuLockable *lock)
  90. {
  91. while (qemu_co_enter_next_impl(queue, lock)) {
  92. /* just loop */
  93. }
  94. }
  95. void coroutine_fn qemu_co_queue_restart_all(CoQueue *queue)
  96. {
  97. /* No unlock/lock needed in coroutine context. */
  98. qemu_co_enter_all_impl(queue, NULL);
  99. }
  100. bool qemu_co_queue_empty(CoQueue *queue)
  101. {
  102. return QSIMPLEQ_FIRST(&queue->entries) == NULL;
  103. }
  104. /* The wait records are handled with a multiple-producer, single-consumer
  105. * lock-free queue. There cannot be two concurrent pop_waiter() calls
  106. * because pop_waiter() can only be called while mutex->handoff is zero.
  107. * This can happen in three cases:
  108. * - in qemu_co_mutex_unlock, before the hand-off protocol has started.
  109. * In this case, qemu_co_mutex_lock will see mutex->handoff == 0 and
  110. * not take part in the handoff.
  111. * - in qemu_co_mutex_lock, if it steals the hand-off responsibility from
  112. * qemu_co_mutex_unlock. In this case, qemu_co_mutex_unlock will fail
  113. * the cmpxchg (it will see either 0 or the next sequence value) and
  114. * exit. The next hand-off cannot begin until qemu_co_mutex_lock has
  115. * woken up someone.
  116. * - in qemu_co_mutex_unlock, if it takes the hand-off token itself.
  117. * In this case another iteration starts with mutex->handoff == 0;
  118. * a concurrent qemu_co_mutex_lock will fail the cmpxchg, and
  119. * qemu_co_mutex_unlock will go back to case (1).
  120. *
  121. * The following functions manage this queue.
  122. */
  123. typedef struct CoWaitRecord {
  124. Coroutine *co;
  125. QSLIST_ENTRY(CoWaitRecord) next;
  126. } CoWaitRecord;
  127. static void coroutine_fn push_waiter(CoMutex *mutex, CoWaitRecord *w)
  128. {
  129. w->co = qemu_coroutine_self();
  130. QSLIST_INSERT_HEAD_ATOMIC(&mutex->from_push, w, next);
  131. }
  132. static void move_waiters(CoMutex *mutex)
  133. {
  134. QSLIST_HEAD(, CoWaitRecord) reversed;
  135. QSLIST_MOVE_ATOMIC(&reversed, &mutex->from_push);
  136. while (!QSLIST_EMPTY(&reversed)) {
  137. CoWaitRecord *w = QSLIST_FIRST(&reversed);
  138. QSLIST_REMOVE_HEAD(&reversed, next);
  139. QSLIST_INSERT_HEAD(&mutex->to_pop, w, next);
  140. }
  141. }
  142. static CoWaitRecord *pop_waiter(CoMutex *mutex)
  143. {
  144. CoWaitRecord *w;
  145. if (QSLIST_EMPTY(&mutex->to_pop)) {
  146. move_waiters(mutex);
  147. if (QSLIST_EMPTY(&mutex->to_pop)) {
  148. return NULL;
  149. }
  150. }
  151. w = QSLIST_FIRST(&mutex->to_pop);
  152. QSLIST_REMOVE_HEAD(&mutex->to_pop, next);
  153. return w;
  154. }
  155. static bool has_waiters(CoMutex *mutex)
  156. {
  157. return QSLIST_EMPTY(&mutex->to_pop) || QSLIST_EMPTY(&mutex->from_push);
  158. }
  159. void qemu_co_mutex_init(CoMutex *mutex)
  160. {
  161. memset(mutex, 0, sizeof(*mutex));
  162. }
  163. static void coroutine_fn qemu_co_mutex_wake(CoMutex *mutex, Coroutine *co)
  164. {
  165. /* Read co before co->ctx; pairs with smp_wmb() in
  166. * qemu_coroutine_enter().
  167. */
  168. smp_read_barrier_depends();
  169. mutex->ctx = co->ctx;
  170. aio_co_wake(co);
  171. }
  172. static void coroutine_fn qemu_co_mutex_lock_slowpath(AioContext *ctx,
  173. CoMutex *mutex)
  174. {
  175. Coroutine *self = qemu_coroutine_self();
  176. CoWaitRecord w;
  177. unsigned old_handoff;
  178. trace_qemu_co_mutex_lock_entry(mutex, self);
  179. push_waiter(mutex, &w);
  180. /*
  181. * Add waiter before reading mutex->handoff. Pairs with qatomic_mb_set
  182. * in qemu_co_mutex_unlock.
  183. */
  184. smp_mb__after_rmw();
  185. /* This is the "Responsibility Hand-Off" protocol; a lock() picks from
  186. * a concurrent unlock() the responsibility of waking somebody up.
  187. */
  188. old_handoff = qatomic_read(&mutex->handoff);
  189. if (old_handoff &&
  190. has_waiters(mutex) &&
  191. qatomic_cmpxchg(&mutex->handoff, old_handoff, 0) == old_handoff) {
  192. /* There can be no concurrent pops, because there can be only
  193. * one active handoff at a time.
  194. */
  195. CoWaitRecord *to_wake = pop_waiter(mutex);
  196. Coroutine *co = to_wake->co;
  197. if (co == self) {
  198. /* We got the lock ourselves! */
  199. assert(to_wake == &w);
  200. mutex->ctx = ctx;
  201. return;
  202. }
  203. qemu_co_mutex_wake(mutex, co);
  204. }
  205. qemu_coroutine_yield();
  206. trace_qemu_co_mutex_lock_return(mutex, self);
  207. }
  208. void coroutine_fn qemu_co_mutex_lock(CoMutex *mutex)
  209. {
  210. AioContext *ctx = qemu_get_current_aio_context();
  211. Coroutine *self = qemu_coroutine_self();
  212. int waiters, i;
  213. /* Running a very small critical section on pthread_mutex_t and CoMutex
  214. * shows that pthread_mutex_t is much faster because it doesn't actually
  215. * go to sleep. What happens is that the critical section is shorter
  216. * than the latency of entering the kernel and thus FUTEX_WAIT always
  217. * fails. With CoMutex there is no such latency but you still want to
  218. * avoid wait and wakeup. So introduce it artificially.
  219. */
  220. i = 0;
  221. retry_fast_path:
  222. waiters = qatomic_cmpxchg(&mutex->locked, 0, 1);
  223. if (waiters != 0) {
  224. while (waiters == 1 && ++i < 1000) {
  225. if (qatomic_read(&mutex->ctx) == ctx) {
  226. break;
  227. }
  228. if (qatomic_read(&mutex->locked) == 0) {
  229. goto retry_fast_path;
  230. }
  231. cpu_relax();
  232. }
  233. waiters = qatomic_fetch_inc(&mutex->locked);
  234. }
  235. if (waiters == 0) {
  236. /* Uncontended. */
  237. trace_qemu_co_mutex_lock_uncontended(mutex, self);
  238. mutex->ctx = ctx;
  239. } else {
  240. qemu_co_mutex_lock_slowpath(ctx, mutex);
  241. }
  242. mutex->holder = self;
  243. self->locks_held++;
  244. }
  245. void coroutine_fn qemu_co_mutex_unlock(CoMutex *mutex)
  246. {
  247. Coroutine *self = qemu_coroutine_self();
  248. trace_qemu_co_mutex_unlock_entry(mutex, self);
  249. assert(mutex->locked);
  250. assert(mutex->holder == self);
  251. assert(qemu_in_coroutine());
  252. mutex->ctx = NULL;
  253. mutex->holder = NULL;
  254. self->locks_held--;
  255. if (qatomic_fetch_dec(&mutex->locked) == 1) {
  256. /* No waiting qemu_co_mutex_lock(). Pfew, that was easy! */
  257. return;
  258. }
  259. for (;;) {
  260. CoWaitRecord *to_wake = pop_waiter(mutex);
  261. unsigned our_handoff;
  262. if (to_wake) {
  263. qemu_co_mutex_wake(mutex, to_wake->co);
  264. break;
  265. }
  266. /* Some concurrent lock() is in progress (we know this because
  267. * mutex->locked was >1) but it hasn't yet put itself on the wait
  268. * queue. Pick a sequence number for the handoff protocol (not 0).
  269. */
  270. if (++mutex->sequence == 0) {
  271. mutex->sequence = 1;
  272. }
  273. our_handoff = mutex->sequence;
  274. /* Set handoff before checking for waiters. */
  275. qatomic_mb_set(&mutex->handoff, our_handoff);
  276. if (!has_waiters(mutex)) {
  277. /* The concurrent lock has not added itself yet, so it
  278. * will be able to pick our handoff.
  279. */
  280. break;
  281. }
  282. /* Try to do the handoff protocol ourselves; if somebody else has
  283. * already taken it, however, we're done and they're responsible.
  284. */
  285. if (qatomic_cmpxchg(&mutex->handoff, our_handoff, 0) != our_handoff) {
  286. break;
  287. }
  288. }
  289. trace_qemu_co_mutex_unlock_return(mutex, self);
  290. }
  291. struct CoRwTicket {
  292. bool read;
  293. Coroutine *co;
  294. QSIMPLEQ_ENTRY(CoRwTicket) next;
  295. };
  296. void qemu_co_rwlock_init(CoRwlock *lock)
  297. {
  298. qemu_co_mutex_init(&lock->mutex);
  299. lock->owners = 0;
  300. QSIMPLEQ_INIT(&lock->tickets);
  301. }
  302. /* Releases the internal CoMutex. */
  303. static void coroutine_fn qemu_co_rwlock_maybe_wake_one(CoRwlock *lock)
  304. {
  305. CoRwTicket *tkt = QSIMPLEQ_FIRST(&lock->tickets);
  306. Coroutine *co = NULL;
  307. /*
  308. * Setting lock->owners here prevents rdlock and wrlock from
  309. * sneaking in between unlock and wake.
  310. */
  311. if (tkt) {
  312. if (tkt->read) {
  313. if (lock->owners >= 0) {
  314. lock->owners++;
  315. co = tkt->co;
  316. }
  317. } else {
  318. if (lock->owners == 0) {
  319. lock->owners = -1;
  320. co = tkt->co;
  321. }
  322. }
  323. }
  324. if (co) {
  325. QSIMPLEQ_REMOVE_HEAD(&lock->tickets, next);
  326. qemu_co_mutex_unlock(&lock->mutex);
  327. aio_co_wake(co);
  328. } else {
  329. qemu_co_mutex_unlock(&lock->mutex);
  330. }
  331. }
  332. void coroutine_fn qemu_co_rwlock_rdlock(CoRwlock *lock)
  333. {
  334. Coroutine *self = qemu_coroutine_self();
  335. qemu_co_mutex_lock(&lock->mutex);
  336. /* For fairness, wait if a writer is in line. */
  337. if (lock->owners == 0 || (lock->owners > 0 && QSIMPLEQ_EMPTY(&lock->tickets))) {
  338. lock->owners++;
  339. qemu_co_mutex_unlock(&lock->mutex);
  340. } else {
  341. CoRwTicket my_ticket = { true, self };
  342. QSIMPLEQ_INSERT_TAIL(&lock->tickets, &my_ticket, next);
  343. qemu_co_mutex_unlock(&lock->mutex);
  344. qemu_coroutine_yield();
  345. assert(lock->owners >= 1);
  346. /* Possibly wake another reader, which will wake the next in line. */
  347. qemu_co_mutex_lock(&lock->mutex);
  348. qemu_co_rwlock_maybe_wake_one(lock);
  349. }
  350. self->locks_held++;
  351. }
  352. void coroutine_fn qemu_co_rwlock_unlock(CoRwlock *lock)
  353. {
  354. Coroutine *self = qemu_coroutine_self();
  355. assert(qemu_in_coroutine());
  356. self->locks_held--;
  357. qemu_co_mutex_lock(&lock->mutex);
  358. if (lock->owners > 0) {
  359. lock->owners--;
  360. } else {
  361. assert(lock->owners == -1);
  362. lock->owners = 0;
  363. }
  364. qemu_co_rwlock_maybe_wake_one(lock);
  365. }
  366. void coroutine_fn qemu_co_rwlock_downgrade(CoRwlock *lock)
  367. {
  368. qemu_co_mutex_lock(&lock->mutex);
  369. assert(lock->owners == -1);
  370. lock->owners = 1;
  371. /* Possibly wake another reader, which will wake the next in line. */
  372. qemu_co_rwlock_maybe_wake_one(lock);
  373. }
  374. void coroutine_fn qemu_co_rwlock_wrlock(CoRwlock *lock)
  375. {
  376. Coroutine *self = qemu_coroutine_self();
  377. qemu_co_mutex_lock(&lock->mutex);
  378. if (lock->owners == 0) {
  379. lock->owners = -1;
  380. qemu_co_mutex_unlock(&lock->mutex);
  381. } else {
  382. CoRwTicket my_ticket = { false, qemu_coroutine_self() };
  383. QSIMPLEQ_INSERT_TAIL(&lock->tickets, &my_ticket, next);
  384. qemu_co_mutex_unlock(&lock->mutex);
  385. qemu_coroutine_yield();
  386. assert(lock->owners == -1);
  387. }
  388. self->locks_held++;
  389. }
  390. void coroutine_fn qemu_co_rwlock_upgrade(CoRwlock *lock)
  391. {
  392. qemu_co_mutex_lock(&lock->mutex);
  393. assert(lock->owners > 0);
  394. /* For fairness, wait if a writer is in line. */
  395. if (lock->owners == 1 && QSIMPLEQ_EMPTY(&lock->tickets)) {
  396. lock->owners = -1;
  397. qemu_co_mutex_unlock(&lock->mutex);
  398. } else {
  399. CoRwTicket my_ticket = { false, qemu_coroutine_self() };
  400. lock->owners--;
  401. QSIMPLEQ_INSERT_TAIL(&lock->tickets, &my_ticket, next);
  402. qemu_co_rwlock_maybe_wake_one(lock);
  403. qemu_coroutine_yield();
  404. assert(lock->owners == -1);
  405. }
  406. }