seqcount: Compress SEQCNT_LOCKNAME_ZERO()
[linux-2.6-microblaze.git] / include / linux / seqlock.h
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef __LINUX_SEQLOCK_H
3 #define __LINUX_SEQLOCK_H
4
5 /*
6  * seqcount_t / seqlock_t - a reader-writer consistency mechanism with
7  * lockless readers (read-only retry loops), and no writer starvation.
8  *
9  * See Documentation/locking/seqlock.rst
10  *
11  * Copyrights:
12  * - Based on x86_64 vsyscall gettimeofday: Keith Owens, Andrea Arcangeli
13  * - Sequence counters with associated locks, (C) 2020 Linutronix GmbH
14  */
15
16 #include <linux/compiler.h>
17 #include <linux/kcsan-checks.h>
18 #include <linux/lockdep.h>
19 #include <linux/mutex.h>
20 #include <linux/preempt.h>
21 #include <linux/spinlock.h>
22 #include <linux/ww_mutex.h>
23
24 #include <asm/processor.h>
25
26 /*
27  * The seqlock seqcount_t interface does not prescribe a precise sequence of
28  * read begin/retry/end. For readers, typically there is a call to
29  * read_seqcount_begin() and read_seqcount_retry(), however, there are more
30  * esoteric cases which do not follow this pattern.
31  *
32  * As a consequence, we take the following best-effort approach for raw usage
33  * via seqcount_t under KCSAN: upon beginning a seq-reader critical section,
34  * pessimistically mark the next KCSAN_SEQLOCK_REGION_MAX memory accesses as
35  * atomics; if there is a matching read_seqcount_retry() call, no following
36  * memory operations are considered atomic. Usage of the seqlock_t interface
37  * is not affected.
38  */
39 #define KCSAN_SEQLOCK_REGION_MAX 1000
40
41 /*
42  * Sequence counters (seqcount_t)
43  *
44  * This is the raw counting mechanism, without any writer protection.
45  *
46  * Write side critical sections must be serialized and non-preemptible.
47  *
48  * If readers can be invoked from hardirq or softirq contexts,
49  * interrupts or bottom halves must also be respectively disabled before
50  * entering the write section.
51  *
52  * This mechanism can't be used if the protected data contains pointers,
53  * as the writer can invalidate a pointer that a reader is following.
54  *
55  * If the write serialization mechanism is one of the common kernel
56  * locking primitives, use a sequence counter with associated lock
57  * (seqcount_LOCKTYPE_t) instead.
58  *
59  * If it's desired to automatically handle the sequence counter writer
60  * serialization and non-preemptibility requirements, use a sequential
61  * lock (seqlock_t) instead.
62  *
63  * See Documentation/locking/seqlock.rst
64  */
65 typedef struct seqcount {
66         unsigned sequence;
67 #ifdef CONFIG_DEBUG_LOCK_ALLOC
68         struct lockdep_map dep_map;
69 #endif
70 } seqcount_t;
71
72 static inline void __seqcount_init(seqcount_t *s, const char *name,
73                                           struct lock_class_key *key)
74 {
75         /*
76          * Make sure we are not reinitializing a held lock:
77          */
78         lockdep_init_map(&s->dep_map, name, key, 0);
79         s->sequence = 0;
80 }
81
82 #ifdef CONFIG_DEBUG_LOCK_ALLOC
83
84 # define SEQCOUNT_DEP_MAP_INIT(lockname)                                \
85                 .dep_map = { .name = #lockname }
86
87 /**
88  * seqcount_init() - runtime initializer for seqcount_t
89  * @s: Pointer to the seqcount_t instance
90  */
91 # define seqcount_init(s)                                               \
92         do {                                                            \
93                 static struct lock_class_key __key;                     \
94                 __seqcount_init((s), #s, &__key);                       \
95         } while (0)
96
97 static inline void seqcount_lockdep_reader_access(const seqcount_t *s)
98 {
99         seqcount_t *l = (seqcount_t *)s;
100         unsigned long flags;
101
102         local_irq_save(flags);
103         seqcount_acquire_read(&l->dep_map, 0, 0, _RET_IP_);
104         seqcount_release(&l->dep_map, _RET_IP_);
105         local_irq_restore(flags);
106 }
107
108 #else
109 # define SEQCOUNT_DEP_MAP_INIT(lockname)
110 # define seqcount_init(s) __seqcount_init(s, NULL, NULL)
111 # define seqcount_lockdep_reader_access(x)
112 #endif
113
114 /**
115  * SEQCNT_ZERO() - static initializer for seqcount_t
116  * @name: Name of the seqcount_t instance
117  */
118 #define SEQCNT_ZERO(name) { .sequence = 0, SEQCOUNT_DEP_MAP_INIT(name) }
119
120 /*
121  * Sequence counters with associated locks (seqcount_LOCKTYPE_t)
122  *
123  * A sequence counter which associates the lock used for writer
124  * serialization at initialization time. This enables lockdep to validate
125  * that the write side critical section is properly serialized.
126  *
127  * For associated locks which do not implicitly disable preemption,
128  * preemption protection is enforced in the write side function.
129  *
130  * Lockdep is never used in any for the raw write variants.
131  *
132  * See Documentation/locking/seqlock.rst
133  */
134
135 #ifdef CONFIG_LOCKDEP
136 #define __SEQ_LOCK(expr)        expr
137 #else
138 #define __SEQ_LOCK(expr)
139 #endif
140
141 /**
142  * typedef seqcount_LOCKNAME_t - sequence counter with LOCKTYPR associated
143  * @seqcount:   The real sequence counter
144  * @lock:       Pointer to the associated spinlock
145  *
146  * A plain sequence counter with external writer synchronization by a
147  * spinlock. The spinlock is associated to the sequence count in the
148  * static initializer or init function. This enables lockdep to validate
149  * that the write side critical section is properly serialized.
150  */
151
152 /**
153  * seqcount_LOCKNAME_init() - runtime initializer for seqcount_LOCKNAME_t
154  * @s:          Pointer to the seqcount_LOCKNAME_t instance
155  * @lock:       Pointer to the associated LOCKTYPE
156  */
157
158 /*
159  * SEQCOUNT_LOCKTYPE() - Instantiate seqcount_LOCKNAME_t and helpers
160  * @locktype:           actual typename
161  * @lockname:           name
162  * @preemptible:        preemptibility of above locktype
163  * @lockmember:         argument for lockdep_assert_held()
164  */
165 #define SEQCOUNT_LOCKTYPE(locktype, lockname, preemptible, lockmember)  \
166 typedef struct seqcount_##lockname {                                    \
167         seqcount_t              seqcount;                               \
168         __SEQ_LOCK(locktype     *lock);                                 \
169 } seqcount_##lockname##_t;                                              \
170                                                                         \
171 static __always_inline void                                             \
172 seqcount_##lockname##_init(seqcount_##lockname##_t *s, locktype *lock)  \
173 {                                                                       \
174         seqcount_init(&s->seqcount);                                    \
175         __SEQ_LOCK(s->lock = lock);                                     \
176 }                                                                       \
177                                                                         \
178 static __always_inline seqcount_t *                                     \
179 __seqcount_##lockname##_ptr(seqcount_##lockname##_t *s)                 \
180 {                                                                       \
181         return &s->seqcount;                                            \
182 }                                                                       \
183                                                                         \
184 static __always_inline bool                                             \
185 __seqcount_##lockname##_preemptible(seqcount_##lockname##_t *s)         \
186 {                                                                       \
187         return preemptible;                                             \
188 }                                                                       \
189                                                                         \
190 static __always_inline void                                             \
191 __seqcount_##lockname##_assert(seqcount_##lockname##_t *s)              \
192 {                                                                       \
193         __SEQ_LOCK(lockdep_assert_held(lockmember));                    \
194 }
195
196 /*
197  * __seqprop() for seqcount_t
198  */
199
200 static inline seqcount_t *__seqcount_ptr(seqcount_t *s)
201 {
202         return s;
203 }
204
205 static inline bool __seqcount_preemptible(seqcount_t *s)
206 {
207         return false;
208 }
209
210 static inline void __seqcount_assert(seqcount_t *s)
211 {
212         lockdep_assert_preemption_disabled();
213 }
214
215 SEQCOUNT_LOCKTYPE(raw_spinlock_t,       raw_spinlock,   false,  s->lock)
216 SEQCOUNT_LOCKTYPE(spinlock_t,           spinlock,       false,  s->lock)
217 SEQCOUNT_LOCKTYPE(rwlock_t,             rwlock,         false,  s->lock)
218 SEQCOUNT_LOCKTYPE(struct mutex,         mutex,          true,   s->lock)
219 SEQCOUNT_LOCKTYPE(struct ww_mutex,      ww_mutex,       true,   &s->lock->base)
220
221 /**
222  * SEQCNT_LOCKNAME_ZERO - static initializer for seqcount_LOCKNAME_t
223  * @name:       Name of the seqcount_LOCKNAME_t instance
224  * @lock:       Pointer to the associated LOCKTYPE
225  */
226
227 #define SEQCOUNT_LOCKTYPE_ZERO(seq_name, assoc_lock) {                  \
228         .seqcount               = SEQCNT_ZERO(seq_name.seqcount),       \
229         __SEQ_LOCK(.lock        = (assoc_lock))                         \
230 }
231
232 #define SEQCNT_SPINLOCK_ZERO(name, lock)        SEQCOUNT_LOCKTYPE_ZERO(name, lock)
233 #define SEQCNT_RAW_SPINLOCK_ZERO(name, lock)    SEQCOUNT_LOCKTYPE_ZERO(name, lock)
234 #define SEQCNT_RWLOCK_ZERO(name, lock)          SEQCOUNT_LOCKTYPE_ZERO(name, lock)
235 #define SEQCNT_MUTEX_ZERO(name, lock)           SEQCOUNT_LOCKTYPE_ZERO(name, lock)
236 #define SEQCNT_WW_MUTEX_ZERO(name, lock)        SEQCOUNT_LOCKTYPE_ZERO(name, lock)
237
238
239 #define __seqprop_case(s, lockname, prop)                               \
240         seqcount_##lockname##_t: __seqcount_##lockname##_##prop((void *)(s))
241
242 #define __seqprop(s, prop) _Generic(*(s),                               \
243         seqcount_t:             __seqcount_##prop((void *)(s)),         \
244         __seqprop_case((s),     raw_spinlock,   prop),                  \
245         __seqprop_case((s),     spinlock,       prop),                  \
246         __seqprop_case((s),     rwlock,         prop),                  \
247         __seqprop_case((s),     mutex,          prop),                  \
248         __seqprop_case((s),     ww_mutex,       prop))
249
250 #define __to_seqcount_t(s)                              __seqprop(s, ptr)
251 #define __associated_lock_exists_and_is_preemptible(s)  __seqprop(s, preemptible)
252 #define __assert_write_section_is_protected(s)          __seqprop(s, assert)
253
254 /**
255  * __read_seqcount_begin() - begin a seqcount_t read section w/o barrier
256  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
257  *
258  * __read_seqcount_begin is like read_seqcount_begin, but has no smp_rmb()
259  * barrier. Callers should ensure that smp_rmb() or equivalent ordering is
260  * provided before actually loading any of the variables that are to be
261  * protected in this critical section.
262  *
263  * Use carefully, only in critical code, and comment how the barrier is
264  * provided.
265  *
266  * Return: count to be passed to read_seqcount_retry()
267  */
268 #define __read_seqcount_begin(s)                                        \
269         __read_seqcount_t_begin(__to_seqcount_t(s))
270
271 static inline unsigned __read_seqcount_t_begin(const seqcount_t *s)
272 {
273         unsigned ret;
274
275 repeat:
276         ret = READ_ONCE(s->sequence);
277         if (unlikely(ret & 1)) {
278                 cpu_relax();
279                 goto repeat;
280         }
281         kcsan_atomic_next(KCSAN_SEQLOCK_REGION_MAX);
282         return ret;
283 }
284
285 /**
286  * raw_read_seqcount_begin() - begin a seqcount_t read section w/o lockdep
287  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
288  *
289  * Return: count to be passed to read_seqcount_retry()
290  */
291 #define raw_read_seqcount_begin(s)                                      \
292         raw_read_seqcount_t_begin(__to_seqcount_t(s))
293
294 static inline unsigned raw_read_seqcount_t_begin(const seqcount_t *s)
295 {
296         unsigned ret = __read_seqcount_t_begin(s);
297         smp_rmb();
298         return ret;
299 }
300
301 /**
302  * read_seqcount_begin() - begin a seqcount_t read critical section
303  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
304  *
305  * Return: count to be passed to read_seqcount_retry()
306  */
307 #define read_seqcount_begin(s)                                          \
308         read_seqcount_t_begin(__to_seqcount_t(s))
309
310 static inline unsigned read_seqcount_t_begin(const seqcount_t *s)
311 {
312         seqcount_lockdep_reader_access(s);
313         return raw_read_seqcount_t_begin(s);
314 }
315
316 /**
317  * raw_read_seqcount() - read the raw seqcount_t counter value
318  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
319  *
320  * raw_read_seqcount opens a read critical section of the given
321  * seqcount_t, without any lockdep checking, and without checking or
322  * masking the sequence counter LSB. Calling code is responsible for
323  * handling that.
324  *
325  * Return: count to be passed to read_seqcount_retry()
326  */
327 #define raw_read_seqcount(s)                                            \
328         raw_read_seqcount_t(__to_seqcount_t(s))
329
330 static inline unsigned raw_read_seqcount_t(const seqcount_t *s)
331 {
332         unsigned ret = READ_ONCE(s->sequence);
333         smp_rmb();
334         kcsan_atomic_next(KCSAN_SEQLOCK_REGION_MAX);
335         return ret;
336 }
337
338 /**
339  * raw_seqcount_begin() - begin a seqcount_t read critical section w/o
340  *                        lockdep and w/o counter stabilization
341  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
342  *
343  * raw_seqcount_begin opens a read critical section of the given
344  * seqcount_t. Unlike read_seqcount_begin(), this function will not wait
345  * for the count to stabilize. If a writer is active when it begins, it
346  * will fail the read_seqcount_retry() at the end of the read critical
347  * section instead of stabilizing at the beginning of it.
348  *
349  * Use this only in special kernel hot paths where the read section is
350  * small and has a high probability of success through other external
351  * means. It will save a single branching instruction.
352  *
353  * Return: count to be passed to read_seqcount_retry()
354  */
355 #define raw_seqcount_begin(s)                                           \
356         raw_seqcount_t_begin(__to_seqcount_t(s))
357
358 static inline unsigned raw_seqcount_t_begin(const seqcount_t *s)
359 {
360         /*
361          * If the counter is odd, let read_seqcount_retry() fail
362          * by decrementing the counter.
363          */
364         return raw_read_seqcount_t(s) & ~1;
365 }
366
367 /**
368  * __read_seqcount_retry() - end a seqcount_t read section w/o barrier
369  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
370  * @start: count, from read_seqcount_begin()
371  *
372  * __read_seqcount_retry is like read_seqcount_retry, but has no smp_rmb()
373  * barrier. Callers should ensure that smp_rmb() or equivalent ordering is
374  * provided before actually loading any of the variables that are to be
375  * protected in this critical section.
376  *
377  * Use carefully, only in critical code, and comment how the barrier is
378  * provided.
379  *
380  * Return: true if a read section retry is required, else false
381  */
382 #define __read_seqcount_retry(s, start)                                 \
383         __read_seqcount_t_retry(__to_seqcount_t(s), start)
384
385 static inline int __read_seqcount_t_retry(const seqcount_t *s, unsigned start)
386 {
387         kcsan_atomic_next(0);
388         return unlikely(READ_ONCE(s->sequence) != start);
389 }
390
391 /**
392  * read_seqcount_retry() - end a seqcount_t read critical section
393  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
394  * @start: count, from read_seqcount_begin()
395  *
396  * read_seqcount_retry closes the read critical section of given
397  * seqcount_t.  If the critical section was invalid, it must be ignored
398  * (and typically retried).
399  *
400  * Return: true if a read section retry is required, else false
401  */
402 #define read_seqcount_retry(s, start)                                   \
403         read_seqcount_t_retry(__to_seqcount_t(s), start)
404
405 static inline int read_seqcount_t_retry(const seqcount_t *s, unsigned start)
406 {
407         smp_rmb();
408         return __read_seqcount_t_retry(s, start);
409 }
410
411 /**
412  * raw_write_seqcount_begin() - start a seqcount_t write section w/o lockdep
413  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
414  */
415 #define raw_write_seqcount_begin(s)                                     \
416 do {                                                                    \
417         if (__associated_lock_exists_and_is_preemptible(s))             \
418                 preempt_disable();                                      \
419                                                                         \
420         raw_write_seqcount_t_begin(__to_seqcount_t(s));                 \
421 } while (0)
422
423 static inline void raw_write_seqcount_t_begin(seqcount_t *s)
424 {
425         kcsan_nestable_atomic_begin();
426         s->sequence++;
427         smp_wmb();
428 }
429
430 /**
431  * raw_write_seqcount_end() - end a seqcount_t write section w/o lockdep
432  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
433  */
434 #define raw_write_seqcount_end(s)                                       \
435 do {                                                                    \
436         raw_write_seqcount_t_end(__to_seqcount_t(s));                   \
437                                                                         \
438         if (__associated_lock_exists_and_is_preemptible(s))             \
439                 preempt_enable();                                       \
440 } while (0)
441
442 static inline void raw_write_seqcount_t_end(seqcount_t *s)
443 {
444         smp_wmb();
445         s->sequence++;
446         kcsan_nestable_atomic_end();
447 }
448
449 /**
450  * write_seqcount_begin_nested() - start a seqcount_t write section with
451  *                                 custom lockdep nesting level
452  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
453  * @subclass: lockdep nesting level
454  *
455  * See Documentation/locking/lockdep-design.rst
456  */
457 #define write_seqcount_begin_nested(s, subclass)                        \
458 do {                                                                    \
459         __assert_write_section_is_protected(s);                         \
460                                                                         \
461         if (__associated_lock_exists_and_is_preemptible(s))             \
462                 preempt_disable();                                      \
463                                                                         \
464         write_seqcount_t_begin_nested(__to_seqcount_t(s), subclass);    \
465 } while (0)
466
467 static inline void write_seqcount_t_begin_nested(seqcount_t *s, int subclass)
468 {
469         raw_write_seqcount_t_begin(s);
470         seqcount_acquire(&s->dep_map, subclass, 0, _RET_IP_);
471 }
472
473 /**
474  * write_seqcount_begin() - start a seqcount_t write side critical section
475  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
476  *
477  * write_seqcount_begin opens a write side critical section of the given
478  * seqcount_t.
479  *
480  * Context: seqcount_t write side critical sections must be serialized and
481  * non-preemptible. If readers can be invoked from hardirq or softirq
482  * context, interrupts or bottom halves must be respectively disabled.
483  */
484 #define write_seqcount_begin(s)                                         \
485 do {                                                                    \
486         __assert_write_section_is_protected(s);                         \
487                                                                         \
488         if (__associated_lock_exists_and_is_preemptible(s))             \
489                 preempt_disable();                                      \
490                                                                         \
491         write_seqcount_t_begin(__to_seqcount_t(s));                     \
492 } while (0)
493
494 static inline void write_seqcount_t_begin(seqcount_t *s)
495 {
496         write_seqcount_t_begin_nested(s, 0);
497 }
498
499 /**
500  * write_seqcount_end() - end a seqcount_t write side critical section
501  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
502  *
503  * The write section must've been opened with write_seqcount_begin().
504  */
505 #define write_seqcount_end(s)                                           \
506 do {                                                                    \
507         write_seqcount_t_end(__to_seqcount_t(s));                       \
508                                                                         \
509         if (__associated_lock_exists_and_is_preemptible(s))             \
510                 preempt_enable();                                       \
511 } while (0)
512
513 static inline void write_seqcount_t_end(seqcount_t *s)
514 {
515         seqcount_release(&s->dep_map, _RET_IP_);
516         raw_write_seqcount_t_end(s);
517 }
518
519 /**
520  * raw_write_seqcount_barrier() - do a seqcount_t write barrier
521  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
522  *
523  * This can be used to provide an ordering guarantee instead of the usual
524  * consistency guarantee. It is one wmb cheaper, because it can collapse
525  * the two back-to-back wmb()s.
526  *
527  * Note that writes surrounding the barrier should be declared atomic (e.g.
528  * via WRITE_ONCE): a) to ensure the writes become visible to other threads
529  * atomically, avoiding compiler optimizations; b) to document which writes are
530  * meant to propagate to the reader critical section. This is necessary because
531  * neither writes before and after the barrier are enclosed in a seq-writer
532  * critical section that would ensure readers are aware of ongoing writes::
533  *
534  *      seqcount_t seq;
535  *      bool X = true, Y = false;
536  *
537  *      void read(void)
538  *      {
539  *              bool x, y;
540  *
541  *              do {
542  *                      int s = read_seqcount_begin(&seq);
543  *
544  *                      x = X; y = Y;
545  *
546  *              } while (read_seqcount_retry(&seq, s));
547  *
548  *              BUG_ON(!x && !y);
549  *      }
550  *
551  *      void write(void)
552  *      {
553  *              WRITE_ONCE(Y, true);
554  *
555  *              raw_write_seqcount_barrier(seq);
556  *
557  *              WRITE_ONCE(X, false);
558  *      }
559  */
560 #define raw_write_seqcount_barrier(s)                                   \
561         raw_write_seqcount_t_barrier(__to_seqcount_t(s))
562
563 static inline void raw_write_seqcount_t_barrier(seqcount_t *s)
564 {
565         kcsan_nestable_atomic_begin();
566         s->sequence++;
567         smp_wmb();
568         s->sequence++;
569         kcsan_nestable_atomic_end();
570 }
571
572 /**
573  * write_seqcount_invalidate() - invalidate in-progress seqcount_t read
574  *                               side operations
575  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
576  *
577  * After write_seqcount_invalidate, no seqcount_t read side operations
578  * will complete successfully and see data older than this.
579  */
580 #define write_seqcount_invalidate(s)                                    \
581         write_seqcount_t_invalidate(__to_seqcount_t(s))
582
583 static inline void write_seqcount_t_invalidate(seqcount_t *s)
584 {
585         smp_wmb();
586         kcsan_nestable_atomic_begin();
587         s->sequence+=2;
588         kcsan_nestable_atomic_end();
589 }
590
591 /**
592  * raw_read_seqcount_latch() - pick even/odd seqcount_t latch data copy
593  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
594  *
595  * Use seqcount_t latching to switch between two storage places protected
596  * by a sequence counter. Doing so allows having interruptible, preemptible,
597  * seqcount_t write side critical sections.
598  *
599  * Check raw_write_seqcount_latch() for more details and a full reader and
600  * writer usage example.
601  *
602  * Return: sequence counter raw value. Use the lowest bit as an index for
603  * picking which data copy to read. The full counter value must then be
604  * checked with read_seqcount_retry().
605  */
606 #define raw_read_seqcount_latch(s)                                      \
607         raw_read_seqcount_t_latch(__to_seqcount_t(s))
608
609 static inline int raw_read_seqcount_t_latch(seqcount_t *s)
610 {
611         /* Pairs with the first smp_wmb() in raw_write_seqcount_latch() */
612         int seq = READ_ONCE(s->sequence); /* ^^^ */
613         return seq;
614 }
615
616 /**
617  * raw_write_seqcount_latch() - redirect readers to even/odd copy
618  * @s: Pointer to seqcount_t or any of the seqcount_locktype_t variants
619  *
620  * The latch technique is a multiversion concurrency control method that allows
621  * queries during non-atomic modifications. If you can guarantee queries never
622  * interrupt the modification -- e.g. the concurrency is strictly between CPUs
623  * -- you most likely do not need this.
624  *
625  * Where the traditional RCU/lockless data structures rely on atomic
626  * modifications to ensure queries observe either the old or the new state the
627  * latch allows the same for non-atomic updates. The trade-off is doubling the
628  * cost of storage; we have to maintain two copies of the entire data
629  * structure.
630  *
631  * Very simply put: we first modify one copy and then the other. This ensures
632  * there is always one copy in a stable state, ready to give us an answer.
633  *
634  * The basic form is a data structure like::
635  *
636  *      struct latch_struct {
637  *              seqcount_t              seq;
638  *              struct data_struct      data[2];
639  *      };
640  *
641  * Where a modification, which is assumed to be externally serialized, does the
642  * following::
643  *
644  *      void latch_modify(struct latch_struct *latch, ...)
645  *      {
646  *              smp_wmb();      // Ensure that the last data[1] update is visible
647  *              latch->seq++;
648  *              smp_wmb();      // Ensure that the seqcount update is visible
649  *
650  *              modify(latch->data[0], ...);
651  *
652  *              smp_wmb();      // Ensure that the data[0] update is visible
653  *              latch->seq++;
654  *              smp_wmb();      // Ensure that the seqcount update is visible
655  *
656  *              modify(latch->data[1], ...);
657  *      }
658  *
659  * The query will have a form like::
660  *
661  *      struct entry *latch_query(struct latch_struct *latch, ...)
662  *      {
663  *              struct entry *entry;
664  *              unsigned seq, idx;
665  *
666  *              do {
667  *                      seq = raw_read_seqcount_latch(&latch->seq);
668  *
669  *                      idx = seq & 0x01;
670  *                      entry = data_query(latch->data[idx], ...);
671  *
672  *              // read_seqcount_retry() includes needed smp_rmb()
673  *              } while (read_seqcount_retry(&latch->seq, seq));
674  *
675  *              return entry;
676  *      }
677  *
678  * So during the modification, queries are first redirected to data[1]. Then we
679  * modify data[0]. When that is complete, we redirect queries back to data[0]
680  * and we can modify data[1].
681  *
682  * NOTE:
683  *
684  *      The non-requirement for atomic modifications does _NOT_ include
685  *      the publishing of new entries in the case where data is a dynamic
686  *      data structure.
687  *
688  *      An iteration might start in data[0] and get suspended long enough
689  *      to miss an entire modification sequence, once it resumes it might
690  *      observe the new entry.
691  *
692  * NOTE:
693  *
694  *      When data is a dynamic data structure; one should use regular RCU
695  *      patterns to manage the lifetimes of the objects within.
696  */
697 #define raw_write_seqcount_latch(s)                                     \
698         raw_write_seqcount_t_latch(__to_seqcount_t(s))
699
700 static inline void raw_write_seqcount_t_latch(seqcount_t *s)
701 {
702        smp_wmb();      /* prior stores before incrementing "sequence" */
703        s->sequence++;
704        smp_wmb();      /* increment "sequence" before following stores */
705 }
706
707 /*
708  * Sequential locks (seqlock_t)
709  *
710  * Sequence counters with an embedded spinlock for writer serialization
711  * and non-preemptibility.
712  *
713  * For more info, see:
714  *    - Comments on top of seqcount_t
715  *    - Documentation/locking/seqlock.rst
716  */
717 typedef struct {
718         struct seqcount seqcount;
719         spinlock_t lock;
720 } seqlock_t;
721
722 #define __SEQLOCK_UNLOCKED(lockname)                                    \
723         {                                                               \
724                 .seqcount = SEQCNT_ZERO(lockname),                      \
725                 .lock = __SPIN_LOCK_UNLOCKED(lockname)                  \
726         }
727
728 /**
729  * seqlock_init() - dynamic initializer for seqlock_t
730  * @sl: Pointer to the seqlock_t instance
731  */
732 #define seqlock_init(sl)                                                \
733         do {                                                            \
734                 seqcount_init(&(sl)->seqcount);                         \
735                 spin_lock_init(&(sl)->lock);                            \
736         } while (0)
737
738 /**
739  * DEFINE_SEQLOCK() - Define a statically allocated seqlock_t
740  * @sl: Name of the seqlock_t instance
741  */
742 #define DEFINE_SEQLOCK(sl) \
743                 seqlock_t sl = __SEQLOCK_UNLOCKED(sl)
744
745 /**
746  * read_seqbegin() - start a seqlock_t read side critical section
747  * @sl: Pointer to seqlock_t
748  *
749  * Return: count, to be passed to read_seqretry()
750  */
751 static inline unsigned read_seqbegin(const seqlock_t *sl)
752 {
753         unsigned ret = read_seqcount_begin(&sl->seqcount);
754
755         kcsan_atomic_next(0);  /* non-raw usage, assume closing read_seqretry() */
756         kcsan_flat_atomic_begin();
757         return ret;
758 }
759
760 /**
761  * read_seqretry() - end a seqlock_t read side section
762  * @sl: Pointer to seqlock_t
763  * @start: count, from read_seqbegin()
764  *
765  * read_seqretry closes the read side critical section of given seqlock_t.
766  * If the critical section was invalid, it must be ignored (and typically
767  * retried).
768  *
769  * Return: true if a read section retry is required, else false
770  */
771 static inline unsigned read_seqretry(const seqlock_t *sl, unsigned start)
772 {
773         /*
774          * Assume not nested: read_seqretry() may be called multiple times when
775          * completing read critical section.
776          */
777         kcsan_flat_atomic_end();
778
779         return read_seqcount_retry(&sl->seqcount, start);
780 }
781
782 /**
783  * write_seqlock() - start a seqlock_t write side critical section
784  * @sl: Pointer to seqlock_t
785  *
786  * write_seqlock opens a write side critical section for the given
787  * seqlock_t.  It also implicitly acquires the spinlock_t embedded inside
788  * that sequential lock. All seqlock_t write side sections are thus
789  * automatically serialized and non-preemptible.
790  *
791  * Context: if the seqlock_t read section, or other write side critical
792  * sections, can be invoked from hardirq or softirq contexts, use the
793  * _irqsave or _bh variants of this function instead.
794  */
795 static inline void write_seqlock(seqlock_t *sl)
796 {
797         spin_lock(&sl->lock);
798         write_seqcount_t_begin(&sl->seqcount);
799 }
800
801 /**
802  * write_sequnlock() - end a seqlock_t write side critical section
803  * @sl: Pointer to seqlock_t
804  *
805  * write_sequnlock closes the (serialized and non-preemptible) write side
806  * critical section of given seqlock_t.
807  */
808 static inline void write_sequnlock(seqlock_t *sl)
809 {
810         write_seqcount_t_end(&sl->seqcount);
811         spin_unlock(&sl->lock);
812 }
813
814 /**
815  * write_seqlock_bh() - start a softirqs-disabled seqlock_t write section
816  * @sl: Pointer to seqlock_t
817  *
818  * _bh variant of write_seqlock(). Use only if the read side section, or
819  * other write side sections, can be invoked from softirq contexts.
820  */
821 static inline void write_seqlock_bh(seqlock_t *sl)
822 {
823         spin_lock_bh(&sl->lock);
824         write_seqcount_t_begin(&sl->seqcount);
825 }
826
827 /**
828  * write_sequnlock_bh() - end a softirqs-disabled seqlock_t write section
829  * @sl: Pointer to seqlock_t
830  *
831  * write_sequnlock_bh closes the serialized, non-preemptible, and
832  * softirqs-disabled, seqlock_t write side critical section opened with
833  * write_seqlock_bh().
834  */
835 static inline void write_sequnlock_bh(seqlock_t *sl)
836 {
837         write_seqcount_t_end(&sl->seqcount);
838         spin_unlock_bh(&sl->lock);
839 }
840
841 /**
842  * write_seqlock_irq() - start a non-interruptible seqlock_t write section
843  * @sl: Pointer to seqlock_t
844  *
845  * _irq variant of write_seqlock(). Use only if the read side section, or
846  * other write sections, can be invoked from hardirq contexts.
847  */
848 static inline void write_seqlock_irq(seqlock_t *sl)
849 {
850         spin_lock_irq(&sl->lock);
851         write_seqcount_t_begin(&sl->seqcount);
852 }
853
854 /**
855  * write_sequnlock_irq() - end a non-interruptible seqlock_t write section
856  * @sl: Pointer to seqlock_t
857  *
858  * write_sequnlock_irq closes the serialized and non-interruptible
859  * seqlock_t write side section opened with write_seqlock_irq().
860  */
861 static inline void write_sequnlock_irq(seqlock_t *sl)
862 {
863         write_seqcount_t_end(&sl->seqcount);
864         spin_unlock_irq(&sl->lock);
865 }
866
867 static inline unsigned long __write_seqlock_irqsave(seqlock_t *sl)
868 {
869         unsigned long flags;
870
871         spin_lock_irqsave(&sl->lock, flags);
872         write_seqcount_t_begin(&sl->seqcount);
873         return flags;
874 }
875
876 /**
877  * write_seqlock_irqsave() - start a non-interruptible seqlock_t write
878  *                           section
879  * @lock:  Pointer to seqlock_t
880  * @flags: Stack-allocated storage for saving caller's local interrupt
881  *         state, to be passed to write_sequnlock_irqrestore().
882  *
883  * _irqsave variant of write_seqlock(). Use it only if the read side
884  * section, or other write sections, can be invoked from hardirq context.
885  */
886 #define write_seqlock_irqsave(lock, flags)                              \
887         do { flags = __write_seqlock_irqsave(lock); } while (0)
888
889 /**
890  * write_sequnlock_irqrestore() - end non-interruptible seqlock_t write
891  *                                section
892  * @sl:    Pointer to seqlock_t
893  * @flags: Caller's saved interrupt state, from write_seqlock_irqsave()
894  *
895  * write_sequnlock_irqrestore closes the serialized and non-interruptible
896  * seqlock_t write section previously opened with write_seqlock_irqsave().
897  */
898 static inline void
899 write_sequnlock_irqrestore(seqlock_t *sl, unsigned long flags)
900 {
901         write_seqcount_t_end(&sl->seqcount);
902         spin_unlock_irqrestore(&sl->lock, flags);
903 }
904
905 /**
906  * read_seqlock_excl() - begin a seqlock_t locking reader section
907  * @sl: Pointer to seqlock_t
908  *
909  * read_seqlock_excl opens a seqlock_t locking reader critical section.  A
910  * locking reader exclusively locks out *both* other writers *and* other
911  * locking readers, but it does not update the embedded sequence number.
912  *
913  * Locking readers act like a normal spin_lock()/spin_unlock().
914  *
915  * Context: if the seqlock_t write section, *or other read sections*, can
916  * be invoked from hardirq or softirq contexts, use the _irqsave or _bh
917  * variant of this function instead.
918  *
919  * The opened read section must be closed with read_sequnlock_excl().
920  */
921 static inline void read_seqlock_excl(seqlock_t *sl)
922 {
923         spin_lock(&sl->lock);
924 }
925
926 /**
927  * read_sequnlock_excl() - end a seqlock_t locking reader critical section
928  * @sl: Pointer to seqlock_t
929  */
930 static inline void read_sequnlock_excl(seqlock_t *sl)
931 {
932         spin_unlock(&sl->lock);
933 }
934
935 /**
936  * read_seqlock_excl_bh() - start a seqlock_t locking reader section with
937  *                          softirqs disabled
938  * @sl: Pointer to seqlock_t
939  *
940  * _bh variant of read_seqlock_excl(). Use this variant only if the
941  * seqlock_t write side section, *or other read sections*, can be invoked
942  * from softirq contexts.
943  */
944 static inline void read_seqlock_excl_bh(seqlock_t *sl)
945 {
946         spin_lock_bh(&sl->lock);
947 }
948
949 /**
950  * read_sequnlock_excl_bh() - stop a seqlock_t softirq-disabled locking
951  *                            reader section
952  * @sl: Pointer to seqlock_t
953  */
954 static inline void read_sequnlock_excl_bh(seqlock_t *sl)
955 {
956         spin_unlock_bh(&sl->lock);
957 }
958
959 /**
960  * read_seqlock_excl_irq() - start a non-interruptible seqlock_t locking
961  *                           reader section
962  * @sl: Pointer to seqlock_t
963  *
964  * _irq variant of read_seqlock_excl(). Use this only if the seqlock_t
965  * write side section, *or other read sections*, can be invoked from a
966  * hardirq context.
967  */
968 static inline void read_seqlock_excl_irq(seqlock_t *sl)
969 {
970         spin_lock_irq(&sl->lock);
971 }
972
973 /**
974  * read_sequnlock_excl_irq() - end an interrupts-disabled seqlock_t
975  *                             locking reader section
976  * @sl: Pointer to seqlock_t
977  */
978 static inline void read_sequnlock_excl_irq(seqlock_t *sl)
979 {
980         spin_unlock_irq(&sl->lock);
981 }
982
983 static inline unsigned long __read_seqlock_excl_irqsave(seqlock_t *sl)
984 {
985         unsigned long flags;
986
987         spin_lock_irqsave(&sl->lock, flags);
988         return flags;
989 }
990
991 /**
992  * read_seqlock_excl_irqsave() - start a non-interruptible seqlock_t
993  *                               locking reader section
994  * @lock:  Pointer to seqlock_t
995  * @flags: Stack-allocated storage for saving caller's local interrupt
996  *         state, to be passed to read_sequnlock_excl_irqrestore().
997  *
998  * _irqsave variant of read_seqlock_excl(). Use this only if the seqlock_t
999  * write side section, *or other read sections*, can be invoked from a
1000  * hardirq context.
1001  */
1002 #define read_seqlock_excl_irqsave(lock, flags)                          \
1003         do { flags = __read_seqlock_excl_irqsave(lock); } while (0)
1004
1005 /**
1006  * read_sequnlock_excl_irqrestore() - end non-interruptible seqlock_t
1007  *                                    locking reader section
1008  * @sl:    Pointer to seqlock_t
1009  * @flags: Caller saved interrupt state, from read_seqlock_excl_irqsave()
1010  */
1011 static inline void
1012 read_sequnlock_excl_irqrestore(seqlock_t *sl, unsigned long flags)
1013 {
1014         spin_unlock_irqrestore(&sl->lock, flags);
1015 }
1016
1017 /**
1018  * read_seqbegin_or_lock() - begin a seqlock_t lockless or locking reader
1019  * @lock: Pointer to seqlock_t
1020  * @seq : Marker and return parameter. If the passed value is even, the
1021  * reader will become a *lockless* seqlock_t reader as in read_seqbegin().
1022  * If the passed value is odd, the reader will become a *locking* reader
1023  * as in read_seqlock_excl().  In the first call to this function, the
1024  * caller *must* initialize and pass an even value to @seq; this way, a
1025  * lockless read can be optimistically tried first.
1026  *
1027  * read_seqbegin_or_lock is an API designed to optimistically try a normal
1028  * lockless seqlock_t read section first.  If an odd counter is found, the
1029  * lockless read trial has failed, and the next read iteration transforms
1030  * itself into a full seqlock_t locking reader.
1031  *
1032  * This is typically used to avoid seqlock_t lockless readers starvation
1033  * (too much retry loops) in the case of a sharp spike in write side
1034  * activity.
1035  *
1036  * Context: if the seqlock_t write section, *or other read sections*, can
1037  * be invoked from hardirq or softirq contexts, use the _irqsave or _bh
1038  * variant of this function instead.
1039  *
1040  * Check Documentation/locking/seqlock.rst for template example code.
1041  *
1042  * Return: the encountered sequence counter value, through the @seq
1043  * parameter, which is overloaded as a return parameter. This returned
1044  * value must be checked with need_seqretry(). If the read section need to
1045  * be retried, this returned value must also be passed as the @seq
1046  * parameter of the next read_seqbegin_or_lock() iteration.
1047  */
1048 static inline void read_seqbegin_or_lock(seqlock_t *lock, int *seq)
1049 {
1050         if (!(*seq & 1))        /* Even */
1051                 *seq = read_seqbegin(lock);
1052         else                    /* Odd */
1053                 read_seqlock_excl(lock);
1054 }
1055
1056 /**
1057  * need_seqretry() - validate seqlock_t "locking or lockless" read section
1058  * @lock: Pointer to seqlock_t
1059  * @seq: sequence count, from read_seqbegin_or_lock()
1060  *
1061  * Return: true if a read section retry is required, false otherwise
1062  */
1063 static inline int need_seqretry(seqlock_t *lock, int seq)
1064 {
1065         return !(seq & 1) && read_seqretry(lock, seq);
1066 }
1067
1068 /**
1069  * done_seqretry() - end seqlock_t "locking or lockless" reader section
1070  * @lock: Pointer to seqlock_t
1071  * @seq: count, from read_seqbegin_or_lock()
1072  *
1073  * done_seqretry finishes the seqlock_t read side critical section started
1074  * with read_seqbegin_or_lock() and validated by need_seqretry().
1075  */
1076 static inline void done_seqretry(seqlock_t *lock, int seq)
1077 {
1078         if (seq & 1)
1079                 read_sequnlock_excl(lock);
1080 }
1081
1082 /**
1083  * read_seqbegin_or_lock_irqsave() - begin a seqlock_t lockless reader, or
1084  *                                   a non-interruptible locking reader
1085  * @lock: Pointer to seqlock_t
1086  * @seq:  Marker and return parameter. Check read_seqbegin_or_lock().
1087  *
1088  * This is the _irqsave variant of read_seqbegin_or_lock(). Use it only if
1089  * the seqlock_t write section, *or other read sections*, can be invoked
1090  * from hardirq context.
1091  *
1092  * Note: Interrupts will be disabled only for "locking reader" mode.
1093  *
1094  * Return:
1095  *
1096  *   1. The saved local interrupts state in case of a locking reader, to
1097  *      be passed to done_seqretry_irqrestore().
1098  *
1099  *   2. The encountered sequence counter value, returned through @seq
1100  *      overloaded as a return parameter. Check read_seqbegin_or_lock().
1101  */
1102 static inline unsigned long
1103 read_seqbegin_or_lock_irqsave(seqlock_t *lock, int *seq)
1104 {
1105         unsigned long flags = 0;
1106
1107         if (!(*seq & 1))        /* Even */
1108                 *seq = read_seqbegin(lock);
1109         else                    /* Odd */
1110                 read_seqlock_excl_irqsave(lock, flags);
1111
1112         return flags;
1113 }
1114
1115 /**
1116  * done_seqretry_irqrestore() - end a seqlock_t lockless reader, or a
1117  *                              non-interruptible locking reader section
1118  * @lock:  Pointer to seqlock_t
1119  * @seq:   Count, from read_seqbegin_or_lock_irqsave()
1120  * @flags: Caller's saved local interrupt state in case of a locking
1121  *         reader, also from read_seqbegin_or_lock_irqsave()
1122  *
1123  * This is the _irqrestore variant of done_seqretry(). The read section
1124  * must've been opened with read_seqbegin_or_lock_irqsave(), and validated
1125  * by need_seqretry().
1126  */
1127 static inline void
1128 done_seqretry_irqrestore(seqlock_t *lock, int seq, unsigned long flags)
1129 {
1130         if (seq & 1)
1131                 read_sequnlock_excl_irqrestore(lock, flags);
1132 }
1133 #endif /* __LINUX_SEQLOCK_H */