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