osdep: Introduce qemu_dup
[qemu.git] / include / qemu / seqlock.h
blob2e2be4c4f083e55acc8861021750d4f35a0fe6d5
1 /*
2 * Seqlock implementation for QEMU
4 * Copyright Red Hat, Inc. 2013
6 * Author:
7 * Paolo Bonzini <pbonzini@redhat.com>
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
14 #ifndef QEMU_SEQLOCK_H
15 #define QEMU_SEQLOCK_H
17 #include "qemu/atomic.h"
18 #include "qemu/thread.h"
20 typedef struct QemuSeqLock QemuSeqLock;
22 struct QemuSeqLock {
23 unsigned sequence;
26 static inline void seqlock_init(QemuSeqLock *sl)
28 sl->sequence = 0;
31 /* Lock out other writers and update the count. */
32 static inline void seqlock_write_begin(QemuSeqLock *sl)
34 ++sl->sequence;
36 /* Write sequence before updating other fields. */
37 smp_wmb();
40 static inline void seqlock_write_end(QemuSeqLock *sl)
42 /* Write other fields before finalizing sequence. */
43 smp_wmb();
45 ++sl->sequence;
48 static inline unsigned seqlock_read_begin(QemuSeqLock *sl)
50 /* Always fail if a write is in progress. */
51 unsigned ret = atomic_read(&sl->sequence);
53 /* Read sequence before reading other fields. */
54 smp_rmb();
55 return ret & ~1;
58 static inline int seqlock_read_retry(const QemuSeqLock *sl, unsigned start)
60 /* Read other fields before reading final sequence. */
61 smp_rmb();
62 return unlikely(atomic_read(&sl->sequence) != start);
65 #endif