4 * Copyright Red Hat, Inc. 2013
7 * Stefan Hajnoczi <stefanha@redhat.com>
9 * This work is licensed under the terms of the GNU LGPL, version 2 or later.
10 * See the COPYING.LIB file in the top-level directory.
15 #include "qemu/rfifolock.h"
17 void rfifolock_init(RFifoLock
*r
, void (*cb
)(void *), void *opaque
)
19 qemu_mutex_init(&r
->lock
);
22 qemu_cond_init(&r
->cond
);
25 r
->cb_opaque
= opaque
;
28 void rfifolock_destroy(RFifoLock
*r
)
30 qemu_cond_destroy(&r
->cond
);
31 qemu_mutex_destroy(&r
->lock
);
35 * Theory of operation:
37 * In order to ensure FIFO ordering, implement a ticketlock. Threads acquiring
38 * the lock enqueue themselves by incrementing the tail index. When the lock
39 * is unlocked, the head is incremented and waiting threads are notified.
41 * Recursive locking does not take a ticket since the head is only incremented
42 * when the outermost recursive caller unlocks.
44 void rfifolock_lock(RFifoLock
*r
)
46 qemu_mutex_lock(&r
->lock
);
49 unsigned int ticket
= r
->tail
++;
51 if (r
->nesting
> 0 && qemu_thread_is_self(&r
->owner_thread
)) {
52 r
->tail
--; /* put ticket back, we're nesting */
54 while (ticket
!= r
->head
) {
55 /* Invoke optional contention callback */
59 qemu_cond_wait(&r
->cond
, &r
->lock
);
63 qemu_thread_get_self(&r
->owner_thread
);
65 qemu_mutex_unlock(&r
->lock
);
68 void rfifolock_unlock(RFifoLock
*r
)
70 qemu_mutex_lock(&r
->lock
);
71 assert(r
->nesting
> 0);
72 assert(qemu_thread_is_self(&r
->owner_thread
));
73 if (--r
->nesting
== 0) {
75 qemu_cond_broadcast(&r
->cond
);
77 qemu_mutex_unlock(&r
->lock
);