xref: /linux/kernel/rcu/srcutiny.c (revision 12d5fc96ebbb3b948861805b32a4c3a96105ccd9)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Sleepable Read-Copy Update mechanism for mutual exclusion,
4  *	tiny version for non-preemptible single-CPU use.
5  *
6  * Copyright (C) IBM Corporation, 2017
7  *
8  * Author: Paul McKenney <paulmck@linux.ibm.com>
9  */
10 
11 #include <linux/export.h>
12 #include <linux/irq_work.h>
13 #include <linux/llist.h>
14 #include <linux/mutex.h>
15 #include <linux/preempt.h>
16 #include <linux/rcupdate_wait.h>
17 #include <linux/sched.h>
18 #include <linux/delay.h>
19 #include <linux/srcu.h>
20 
21 #include <linux/rcu_node_tree.h>
22 #include "rcu_segcblist.h"
23 #include "rcu.h"
24 
25 #ifndef CONFIG_TREE_RCU
26 int rcu_scheduler_active __read_mostly;
27 #else // #ifndef CONFIG_TREE_RCU
28 extern int rcu_scheduler_active;
29 #endif // #else // #ifndef CONFIG_TREE_RCU
30 static LIST_HEAD(srcu_boot_list);
31 static bool srcu_init_done;
32 
33 static void __srcu_defer_drain(struct srcu_struct *ssp);
34 
35 static int init_srcu_struct_fields(struct srcu_struct *ssp)
36 {
37 	ssp->srcu_lock_nesting[0] = 0;
38 	ssp->srcu_lock_nesting[1] = 0;
39 	init_swait_queue_head(&ssp->srcu_wq);
40 	ssp->srcu_cb_head = NULL;
41 	ssp->srcu_cb_tail = &ssp->srcu_cb_head;
42 	ssp->srcu_gp_running = false;
43 	ssp->srcu_gp_waiting = false;
44 	ssp->srcu_atomic_gp_flag = 0;
45 	ssp->srcu_idx = 0;
46 	ssp->srcu_idx_max = 0;
47 	INIT_WORK(&ssp->srcu_work, srcu_drive_gp);
48 	INIT_LIST_HEAD(&ssp->srcu_work.entry);
49 	init_irq_work(&ssp->srcu_irq_work, srcu_tiny_irq_work);
50 	init_llist_head(&ssp->defer_cbs);
51 	ssp->defer_iw = IRQ_WORK_INIT_HARD(srcu_defer_drain);
52 	return 0;
53 }
54 
55 #ifdef CONFIG_DEBUG_LOCK_ALLOC
56 
57 int init_srcu_struct_lockdep(struct srcu_struct *ssp, const char *name,
58 		     struct lock_class_key *key)
59 {
60 	/* Don't re-initialize a lock while it is held. */
61 	debug_check_no_locks_freed((void *)ssp, sizeof(*ssp));
62 	lockdep_init_map(&ssp->dep_map, name, key, 0);
63 	return init_srcu_struct_fields(ssp);
64 }
65 EXPORT_SYMBOL_GPL(init_srcu_struct_lockdep);
66 
67 #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
68 
69 /*
70  * init_srcu_struct_generic - initialize a sleep-RCU structure
71  * @ssp: structure to initialize.
72  *
73  * Must invoke this on a given srcu_struct before passing that srcu_struct
74  * to any other function.  Each srcu_struct represents a separate domain
75  * of SRCU protection.
76  */
77 int init_srcu_struct_generic(struct srcu_struct *ssp)
78 {
79 	return init_srcu_struct_fields(ssp);
80 }
81 EXPORT_SYMBOL_GPL(init_srcu_struct_generic);
82 
83 #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
84 
85 /*
86  * cleanup_srcu_struct - deconstruct a sleep-RCU structure
87  * @ssp: structure to clean up.
88  *
89  * Must invoke this after you are finished using a given srcu_struct that
90  * was initialized via init_srcu_struct(), else you leak memory.
91  */
92 void cleanup_srcu_struct(struct srcu_struct *ssp)
93 {
94 	WARN_ON(srcu_readers_active(ssp));
95 	/*
96 	 * Re-issue any deferred callbacks, then wait out ->defer_iw before it is
97 	 * freed.  Skipped entirely with CONFIG_RCU_DEFER=n: irq_work_sync() ends
98 	 * in an unconditional synchronize_rcu() wherever
99 	 * arch_irq_work_has_interrupt() is false, which is every !SMP target.
100 	 */
101 	if (IS_ENABLED(CONFIG_RCU_DEFER)) {
102 		__srcu_defer_drain(ssp);
103 		irq_work_sync(&ssp->defer_iw);
104 	}
105 	irq_work_sync(&ssp->srcu_irq_work);
106 	flush_work(&ssp->srcu_work);
107 	WARN_ON(ssp->srcu_gp_running);
108 	WARN_ON(ssp->srcu_gp_waiting);
109 	WARN_ON(ssp->srcu_cb_head);
110 	WARN_ON(&ssp->srcu_cb_head != ssp->srcu_cb_tail);
111 	WARN_ON(ssp->srcu_idx != ssp->srcu_idx_max);
112 	WARN_ON(ssp->srcu_idx & 0x1);
113 }
114 EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
115 
116 /*
117  * Removes the count for the old reader from the appropriate element of
118  * the srcu_struct.
119  */
120 void __srcu_read_unlock(struct srcu_struct *ssp, int idx)
121 {
122 	int newval;
123 
124 	preempt_disable();  // Needed for PREEMPT_LAZY
125 	newval = READ_ONCE(ssp->srcu_lock_nesting[idx]) - 1;
126 	WRITE_ONCE(ssp->srcu_lock_nesting[idx], newval);
127 	preempt_enable();
128 	if (!newval && READ_ONCE(ssp->srcu_gp_waiting) && in_task() && !irqs_disabled())
129 		swake_up_one(&ssp->srcu_wq);
130 }
131 EXPORT_SYMBOL_GPL(__srcu_read_unlock);
132 
133 /*
134  * Workqueue handler to drive one grace period and invoke any callbacks
135  * that become ready as a result.  Single-CPU operation and preemption
136  * disabling mean that we get away with murder on synchronization.  ;-)
137  */
138 void srcu_drive_gp(struct work_struct *wp)
139 {
140 	int idx;
141 	struct rcu_head *lh;
142 	struct rcu_head *rhp;
143 	struct srcu_struct *ssp;
144 
145 	ssp = container_of(wp, struct srcu_struct, srcu_work);
146 	preempt_disable();  // Needed for PREEMPT_LAZY
147 	if (ssp->srcu_gp_running || ULONG_CMP_GE(ssp->srcu_idx, READ_ONCE(ssp->srcu_idx_max))) {
148 		preempt_enable();
149 		return; /* Already running or nothing to do. */
150 	}
151 
152 	/* Remove recently arrived callbacks and wait for readers. */
153 	WRITE_ONCE(ssp->srcu_gp_running, true);
154 	local_irq_disable();
155 	lh = ssp->srcu_cb_head;
156 	ssp->srcu_cb_head = NULL;
157 	ssp->srcu_cb_tail = &ssp->srcu_cb_head;
158 	local_irq_enable();
159 	idx = (ssp->srcu_idx & 0x2) / 2;
160 	WRITE_ONCE(ssp->srcu_idx, ssp->srcu_idx + 1);
161 	WRITE_ONCE(ssp->srcu_gp_waiting, true);  /* srcu_read_unlock() wakes! */
162 	preempt_enable();
163 	if (IS_ENABLED(CONFIG_PREEMPTION))
164 		synchronize_rcu(); // Needed for RCU Tasks Trace to imply RCU grace period
165 	do {
166 		// Deadlock issues prevent __srcu_read_unlock() from
167 		// doing an unconditional wakeup, so polling is required.
168 		swait_event_timeout_exclusive(ssp->srcu_wq,
169 					      !READ_ONCE(ssp->srcu_lock_nesting[idx]), HZ / 10);
170 	} while (READ_ONCE(ssp->srcu_lock_nesting[idx]));
171 	preempt_disable();  // Needed for PREEMPT_LAZY
172 	WRITE_ONCE(ssp->srcu_gp_waiting, false); /* srcu_read_unlock() cheap. */
173 	WRITE_ONCE(ssp->srcu_idx, ssp->srcu_idx + 1);
174 	preempt_enable();
175 
176 	/* Invoke the callbacks we removed above. */
177 	while (lh) {
178 		rhp = lh;
179 		lh = lh->next;
180 		debug_rcu_head_callback(rhp);
181 		local_bh_disable();
182 		rhp->func(rhp);
183 		local_bh_enable();
184 	}
185 
186 	/*
187 	 * Enable rescheduling, and if there are more callbacks,
188 	 * reschedule ourselves.  This can race with a call_srcu()
189 	 * at interrupt level, but the ->srcu_gp_running checks will
190 	 * straighten that out.
191 	 */
192 	preempt_disable();  // Needed for PREEMPT_LAZY
193 	WRITE_ONCE(ssp->srcu_gp_running, false);
194 	idx = ULONG_CMP_LT(ssp->srcu_idx, READ_ONCE(ssp->srcu_idx_max));
195 	preempt_enable();
196 	if (idx)
197 		schedule_work(&ssp->srcu_work);
198 }
199 EXPORT_SYMBOL_GPL(srcu_drive_gp);
200 
201 /*
202  * Use an irq_work to defer schedule_work() to avoid acquiring the workqueue
203  * pool->lock while the caller might hold scheduler locks, causing lockdep
204  * splats due to workqueue_init() doing a wakeup.
205  */
206 void srcu_tiny_irq_work(struct irq_work *irq_work)
207 {
208 	struct srcu_struct *ssp;
209 
210 	ssp = container_of(irq_work, struct srcu_struct, srcu_irq_work);
211 	schedule_work(&ssp->srcu_work);
212 }
213 EXPORT_SYMBOL_GPL(srcu_tiny_irq_work);
214 
215 static void srcu_gp_start_if_needed(struct srcu_struct *ssp)
216 {
217 	unsigned long cookie;
218 
219 	lockdep_assert_preemption_disabled(); // Needed for PREEMPT_LAZY
220 	cookie = get_state_synchronize_srcu(ssp);
221 	if (ULONG_CMP_GE(READ_ONCE(ssp->srcu_idx_max), cookie)) {
222 		return;
223 	}
224 	WRITE_ONCE(ssp->srcu_idx_max, cookie);
225 	if (!READ_ONCE(ssp->srcu_gp_running)) {
226 		if (likely(srcu_init_done))
227 			irq_work_queue(&ssp->srcu_irq_work);
228 		else if (list_empty(&ssp->srcu_work.entry))
229 			list_add(&ssp->srcu_work.entry, &srcu_boot_list);
230 	}
231 }
232 
233 /*
234  * Also called by __srcu_defer_drain() to re-issue a deferred callback, so it
235  * must not re-check the deferral condition.
236  */
237 static void srcu_do_enqueue(struct srcu_struct *ssp, struct rcu_head *rhp,
238 			    rcu_callback_t func)
239 {
240 	unsigned long flags;
241 
242 	rhp->func = func;
243 	rhp->next = NULL;
244 	preempt_disable();  // Needed for PREEMPT_LAZY
245 	local_irq_save(flags);
246 	*ssp->srcu_cb_tail = rhp;
247 	ssp->srcu_cb_tail = &rhp->next;
248 	local_irq_restore(flags);
249 	srcu_gp_start_if_needed(ssp);
250 	preempt_enable();
251 }
252 
253 /*
254  * Set only by the irq_work drain, the one drain its own re-issue can re-feed;
255  * a callback staged during a direct drain is taken by ->defer_iw afterwards.
256  * Global rather than per-srcu_struct: a re-entrant call_srcu(B) inside a drain
257  * of A raises B's own ->defer_iw, whose drain can stage back onto A.
258  */
259 static bool srcu_defer_draining;
260 
261 static void __srcu_defer_drain(struct srcu_struct *ssp)
262 {
263 	struct llist_node *node, *next;
264 	unsigned long flags;
265 
266 	if (!IS_ENABLED(CONFIG_RCU_DEFER))
267 		return;
268 
269 	/* Re-issued newest-first; nothing depends on call_srcu() ordering. */
270 	local_irq_save(flags);
271 	llist_for_each_safe(node, next, llist_del_all(&ssp->defer_cbs)) {
272 		struct rcu_head *rhp = (struct rcu_head *)node;
273 
274 		srcu_do_enqueue(ssp, rhp, rhp->func);
275 	}
276 	local_irq_restore(flags);
277 }
278 
279 /* Only the irq_work drain can be re-fed by its own re-issue; see Tree SRCU. */
280 void srcu_defer_drain(struct irq_work *iw)
281 {
282 	struct srcu_struct *ssp = container_of(iw, struct srcu_struct, defer_iw);
283 
284 	WRITE_ONCE(srcu_defer_draining, true);
285 	__srcu_defer_drain(ssp);
286 	WRITE_ONCE(srcu_defer_draining, false);
287 }
288 EXPORT_SYMBOL_GPL(srcu_defer_drain);
289 
290 void call_srcu(struct srcu_struct *ssp, struct rcu_head *rhp,
291 	       rcu_callback_t func)
292 {
293 	if (should_rcu_defer()) {
294 		/* A re-entrant call_srcu() during the drain would livelock it. */
295 		if (READ_ONCE(srcu_defer_draining) && !in_nmi()) {
296 			WARN_ONCE(IS_ENABLED(CONFIG_PROVE_RCU),
297 				  "call_srcu() re-entered during callback drain; leaking callback\n");
298 			return;
299 		}
300 		rhp->func = func;
301 		if (llist_add((struct llist_node *)rhp, &ssp->defer_cbs))
302 			irq_work_queue(&ssp->defer_iw);
303 		return;
304 	}
305 
306 	/*
307 	 * Only reachable from an NMI when deferral is off: before the scheduler
308 	 * is up, or with CONFIG_RCU_DEFER=n.  The enqueue can then race.
309 	 */
310 	WARN_ON_ONCE(IS_ENABLED(CONFIG_PROVE_RCU) && in_nmi());
311 
312 	srcu_do_enqueue(ssp, rhp, func);
313 }
314 EXPORT_SYMBOL_GPL(call_srcu);
315 
316 /*
317  * synchronize_srcu - wait for prior SRCU read-side critical-section completion
318  */
319 void synchronize_srcu(struct srcu_struct *ssp)
320 {
321 	struct rcu_synchronize rs;
322 
323 	srcu_lock_sync(&ssp->dep_map);
324 
325 	RCU_LOCKDEP_WARN(lockdep_is_held(ssp) ||
326 			lock_is_held(&rcu_bh_lock_map) ||
327 			lock_is_held(&rcu_lock_map) ||
328 			lock_is_held(&rcu_sched_lock_map),
329 			"Illegal synchronize_srcu() in same-type SRCU (or in RCU) read-side critical section");
330 
331 	if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
332 		return;
333 
334 	might_sleep();
335 	init_rcu_head_on_stack(&rs.head);
336 	init_completion(&rs.completion);
337 	call_srcu(ssp, &rs.head, wakeme_after_rcu);
338 	wait_for_completion(&rs.completion);
339 	destroy_rcu_head_on_stack(&rs.head);
340 }
341 EXPORT_SYMBOL_GPL(synchronize_srcu);
342 
343 /*
344  * synchronize_srcu_atomic - spinning grace period for atomic-reader domains
345  * @ssp: srcu_struct with which to synchronize.
346  *
347  * On !SMP this cannot spin: a reader observed mid-section is preempted
348  * or interrupted-out, and can only finish if we yield the CPU. But it
349  * is also never needed: an atomic-flavor reader (preemption disabled)
350  * cannot be observed mid-section from process context on the sole CPU.
351  * So a reader observed here has broken the atomic-domain promise, and
352  * the only correct wait for it is a real grace period.
353  *
354  * (Actual kernel-doc header is in Tree SRCU.)
355  */
356 void synchronize_srcu_atomic(struct srcu_struct *ssp)
357 {
358 	int idx;
359 	bool ret;
360 	unsigned long srcu_state = get_state_synchronize_srcu(ssp);
361 
362 	srcu_lock_sync(&ssp->dep_map);
363 
364 	RCU_LOCKDEP_WARN(lockdep_is_held(ssp),
365 			 "Illegal synchronize_srcu_atomic() in same-type SRCU read-side critical section");
366 
367 	if (rcu_scheduler_active == RCU_SCHEDULER_INACTIVE)
368 		return;
369 
370 	if (IS_ENABLED(CONFIG_PREEMPTION))
371 		synchronize_rcu(); // Needed for RCU Tasks Trace to imply RCU grace period.
372 				   // And in Tiny RCU, it is near zero cost and doesn't block.
373 
374 	// Usually, there will be no readers.
375 	preempt_disable();  // Guard against lazy preemption and some other grace period.
376 	ret = !READ_ONCE(ssp->srcu_lock_nesting[0]) && !READ_ONCE(ssp->srcu_lock_nesting[1]);
377 	if (ret) {
378 		WRITE_ONCE(ssp->srcu_idx_max, ssp->srcu_idx + 2);
379 		WRITE_ONCE(ssp->srcu_idx, ssp->srcu_idx + 2);
380 		preempt_enable();
381 		return;
382 	}
383 
384 	// Because readers disable preemption, we should never get here.
385 	// However, a splat and some spinning is usually preferable to
386 	// memory corruption due to a too-short grace period.  There is
387 	// the possibility that this will hang if the preempted reader is
388 	// not looked upon favorably by the scheduler, but this is still
389 	// preferable to memory corruption.
390 	WARN_ON_ONCE(1);
391 
392 	// Wait to drive a grace period or for someone else to do it
393 	// for us while we are lazily preempted.
394 	while (ssp->srcu_atomic_gp_flag) {
395 		if (poll_state_synchronize_srcu(ssp, srcu_state)) {
396 			preempt_enable();
397 			return;
398 		}
399 		preempt_enable();
400 		cpu_relax();
401 		cond_resched_tasks_rcu_qs();
402 		preempt_disable();
403 	}
404 	ssp->srcu_atomic_gp_flag = 1;  // Acquire SRCU grace-period "lock".
405 	preempt_enable();
406 
407 	// We get here if a reader has been lazily preempted.
408 	// First, wait for old readers, which are quite unlikely.
409 	WRITE_ONCE(ssp->srcu_idx_max, get_state_synchronize_srcu(ssp));
410 	idx = !(((READ_ONCE(ssp->srcu_idx) + 1) & 0x2) >> 1);
411 	while (READ_ONCE(ssp->srcu_lock_nesting[idx])) {
412 		cond_resched_tasks_rcu_qs();
413 		cpu_relax();
414 	}
415 
416 	// Next, flip the index and wait for the other group of readers.
417 	WRITE_ONCE(ssp->srcu_idx, ssp->srcu_idx + 1);
418 	idx = !idx;
419 	while (READ_ONCE(ssp->srcu_lock_nesting[idx])) {
420 		cond_resched_tasks_rcu_qs();
421 		cpu_relax();
422 	}
423 
424 	// Finally, flip the index again for poll_state_synchronize_srcu().
425 	WRITE_ONCE(ssp->srcu_idx, ssp->srcu_idx + 1);
426 	WARN_ON_ONCE(!poll_state_synchronize_srcu(ssp, srcu_state));
427 	ssp->srcu_atomic_gp_flag = 0; // Release SRCU grace-period "lock".
428 }
429 EXPORT_SYMBOL_GPL(synchronize_srcu_atomic);
430 
431 /* Register any deferred callbacks, then wait for all in-flight ones. */
432 void srcu_barrier(struct srcu_struct *ssp)
433 {
434 	__srcu_defer_drain(ssp);
435 	synchronize_srcu(ssp);
436 }
437 EXPORT_SYMBOL_GPL(srcu_barrier);
438 
439 /*
440  * get_state_synchronize_srcu - Provide an end-of-grace-period cookie
441  */
442 unsigned long get_state_synchronize_srcu(struct srcu_struct *ssp)
443 {
444 	unsigned long ret;
445 
446 	barrier();
447 	ret = (READ_ONCE(ssp->srcu_idx) + 3) & ~0x1;
448 	barrier();
449 	return ret;
450 }
451 EXPORT_SYMBOL_GPL(get_state_synchronize_srcu);
452 
453 /*
454  * start_poll_synchronize_srcu - Provide cookie and start grace period
455  *
456  * The difference between this and get_state_synchronize_srcu() is that
457  * this function ensures that the poll_state_synchronize_srcu() will
458  * eventually return the value true.
459  *
460  * This function cannot be used with atomic SRCU, which only has
461  * atomic grace periods.  Doing so will silently corrupt internal
462  * SRCU state.  Tree SRCU has appropriate checking with splats,
463  * so please test with CONFIG_SMP=y as well as CONFIG_SMP=n.
464  */
465 unsigned long start_poll_synchronize_srcu(struct srcu_struct *ssp)
466 {
467 	unsigned long ret;
468 
469 	preempt_disable();  // Needed for PREEMPT_LAZY
470 	ret = get_state_synchronize_srcu(ssp);
471 	srcu_gp_start_if_needed(ssp);
472 	preempt_enable();
473 	return ret;
474 }
475 EXPORT_SYMBOL_GPL(start_poll_synchronize_srcu);
476 
477 /*
478  * poll_state_synchronize_srcu - Has cookie's grace period ended?
479  */
480 bool poll_state_synchronize_srcu(struct srcu_struct *ssp, unsigned long cookie)
481 {
482 	unsigned long cur_s = READ_ONCE(ssp->srcu_idx);
483 
484 	barrier();
485 	return cookie == SRCU_GET_STATE_COMPLETED ||
486 	       ULONG_CMP_GE(cur_s, cookie) || ULONG_CMP_LT(cur_s, cookie - 3);
487 }
488 EXPORT_SYMBOL_GPL(poll_state_synchronize_srcu);
489 
490 #ifndef CONFIG_TREE_RCU
491 /* Lockdep diagnostics.  */
492 void __init rcu_scheduler_starting(void)
493 {
494 	rcu_scheduler_active = RCU_SCHEDULER_RUNNING;
495 }
496 #endif // #ifndef CONFIG_TREE_RCU
497 
498 /*
499  * Queue work for srcu_struct structures with early boot callbacks.
500  * The work won't actually execute until the workqueue initialization
501  * phase that takes place after the scheduler starts.
502  */
503 void __init srcu_init(void)
504 {
505 	struct srcu_struct *ssp;
506 
507 	srcu_init_done = true;
508 	while (!list_empty(&srcu_boot_list)) {
509 		ssp = list_first_entry(&srcu_boot_list,
510 				      struct srcu_struct, srcu_work.entry);
511 		list_del_init(&ssp->srcu_work.entry);
512 		schedule_work(&ssp->srcu_work);
513 	}
514 }
515