rcutorture: Use DEFINE_STATIC_SRCU()
[platform/adaptation/renesas_rcar/renesas_kernel.git] / kernel / srcu.c
1 /*
2  * Sleepable Read-Copy Update mechanism for mutual exclusion.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17  *
18  * Copyright (C) IBM Corporation, 2006
19  * Copyright (C) Fujitsu, 2012
20  *
21  * Author: Paul McKenney <paulmck@us.ibm.com>
22  *         Lai Jiangshan <laijs@cn.fujitsu.com>
23  *
24  * For detailed explanation of Read-Copy Update mechanism see -
25  *              Documentation/RCU/ *.txt
26  *
27  */
28
29 #include <linux/export.h>
30 #include <linux/mutex.h>
31 #include <linux/percpu.h>
32 #include <linux/preempt.h>
33 #include <linux/rcupdate.h>
34 #include <linux/sched.h>
35 #include <linux/smp.h>
36 #include <linux/delay.h>
37 #include <linux/srcu.h>
38
39 /*
40  * Initialize an rcu_batch structure to empty.
41  */
42 static inline void rcu_batch_init(struct rcu_batch *b)
43 {
44         b->head = NULL;
45         b->tail = &b->head;
46 }
47
48 /*
49  * Enqueue a callback onto the tail of the specified rcu_batch structure.
50  */
51 static inline void rcu_batch_queue(struct rcu_batch *b, struct rcu_head *head)
52 {
53         *b->tail = head;
54         b->tail = &head->next;
55 }
56
57 /*
58  * Is the specified rcu_batch structure empty?
59  */
60 static inline bool rcu_batch_empty(struct rcu_batch *b)
61 {
62         return b->tail == &b->head;
63 }
64
65 /*
66  * Remove the callback at the head of the specified rcu_batch structure
67  * and return a pointer to it, or return NULL if the structure is empty.
68  */
69 static inline struct rcu_head *rcu_batch_dequeue(struct rcu_batch *b)
70 {
71         struct rcu_head *head;
72
73         if (rcu_batch_empty(b))
74                 return NULL;
75
76         head = b->head;
77         b->head = head->next;
78         if (b->tail == &head->next)
79                 rcu_batch_init(b);
80
81         return head;
82 }
83
84 /*
85  * Move all callbacks from the rcu_batch structure specified by "from" to
86  * the structure specified by "to".
87  */
88 static inline void rcu_batch_move(struct rcu_batch *to, struct rcu_batch *from)
89 {
90         if (!rcu_batch_empty(from)) {
91                 *to->tail = from->head;
92                 to->tail = from->tail;
93                 rcu_batch_init(from);
94         }
95 }
96
97 static int init_srcu_struct_fields(struct srcu_struct *sp)
98 {
99         sp->completed = 0;
100         spin_lock_init(&sp->queue_lock);
101         sp->running = false;
102         rcu_batch_init(&sp->batch_queue);
103         rcu_batch_init(&sp->batch_check0);
104         rcu_batch_init(&sp->batch_check1);
105         rcu_batch_init(&sp->batch_done);
106         INIT_DELAYED_WORK(&sp->work, process_srcu);
107         sp->per_cpu_ref = alloc_percpu(struct srcu_struct_array);
108         return sp->per_cpu_ref ? 0 : -ENOMEM;
109 }
110
111 #ifdef CONFIG_DEBUG_LOCK_ALLOC
112
113 int __init_srcu_struct(struct srcu_struct *sp, const char *name,
114                        struct lock_class_key *key)
115 {
116         /* Don't re-initialize a lock while it is held. */
117         debug_check_no_locks_freed((void *)sp, sizeof(*sp));
118         lockdep_init_map(&sp->dep_map, name, key, 0);
119         return init_srcu_struct_fields(sp);
120 }
121 EXPORT_SYMBOL_GPL(__init_srcu_struct);
122
123 #else /* #ifdef CONFIG_DEBUG_LOCK_ALLOC */
124
125 /**
126  * init_srcu_struct - initialize a sleep-RCU structure
127  * @sp: structure to initialize.
128  *
129  * Must invoke this on a given srcu_struct before passing that srcu_struct
130  * to any other function.  Each srcu_struct represents a separate domain
131  * of SRCU protection.
132  */
133 int init_srcu_struct(struct srcu_struct *sp)
134 {
135         return init_srcu_struct_fields(sp);
136 }
137 EXPORT_SYMBOL_GPL(init_srcu_struct);
138
139 #endif /* #else #ifdef CONFIG_DEBUG_LOCK_ALLOC */
140
141 /*
142  * Returns approximate total of the readers' ->seq[] values for the
143  * rank of per-CPU counters specified by idx.
144  */
145 static unsigned long srcu_readers_seq_idx(struct srcu_struct *sp, int idx)
146 {
147         int cpu;
148         unsigned long sum = 0;
149         unsigned long t;
150
151         for_each_possible_cpu(cpu) {
152                 t = ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->seq[idx]);
153                 sum += t;
154         }
155         return sum;
156 }
157
158 /*
159  * Returns approximate number of readers active on the specified rank
160  * of the per-CPU ->c[] counters.
161  */
162 static unsigned long srcu_readers_active_idx(struct srcu_struct *sp, int idx)
163 {
164         int cpu;
165         unsigned long sum = 0;
166         unsigned long t;
167
168         for_each_possible_cpu(cpu) {
169                 t = ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[idx]);
170                 sum += t;
171         }
172         return sum;
173 }
174
175 /*
176  * Return true if the number of pre-existing readers is determined to
177  * be stably zero.  An example unstable zero can occur if the call
178  * to srcu_readers_active_idx() misses an __srcu_read_lock() increment,
179  * but due to task migration, sees the corresponding __srcu_read_unlock()
180  * decrement.  This can happen because srcu_readers_active_idx() takes
181  * time to sum the array, and might in fact be interrupted or preempted
182  * partway through the summation.
183  */
184 static bool srcu_readers_active_idx_check(struct srcu_struct *sp, int idx)
185 {
186         unsigned long seq;
187
188         seq = srcu_readers_seq_idx(sp, idx);
189
190         /*
191          * The following smp_mb() A pairs with the smp_mb() B located in
192          * __srcu_read_lock().  This pairing ensures that if an
193          * __srcu_read_lock() increments its counter after the summation
194          * in srcu_readers_active_idx(), then the corresponding SRCU read-side
195          * critical section will see any changes made prior to the start
196          * of the current SRCU grace period.
197          *
198          * Also, if the above call to srcu_readers_seq_idx() saw the
199          * increment of ->seq[], then the call to srcu_readers_active_idx()
200          * must see the increment of ->c[].
201          */
202         smp_mb(); /* A */
203
204         /*
205          * Note that srcu_readers_active_idx() can incorrectly return
206          * zero even though there is a pre-existing reader throughout.
207          * To see this, suppose that task A is in a very long SRCU
208          * read-side critical section that started on CPU 0, and that
209          * no other reader exists, so that the sum of the counters
210          * is equal to one.  Then suppose that task B starts executing
211          * srcu_readers_active_idx(), summing up to CPU 1, and then that
212          * task C starts reading on CPU 0, so that its increment is not
213          * summed, but finishes reading on CPU 2, so that its decrement
214          * -is- summed.  Then when task B completes its sum, it will
215          * incorrectly get zero, despite the fact that task A has been
216          * in its SRCU read-side critical section the whole time.
217          *
218          * We therefore do a validation step should srcu_readers_active_idx()
219          * return zero.
220          */
221         if (srcu_readers_active_idx(sp, idx) != 0)
222                 return false;
223
224         /*
225          * The remainder of this function is the validation step.
226          * The following smp_mb() D pairs with the smp_mb() C in
227          * __srcu_read_unlock().  If the __srcu_read_unlock() was seen
228          * by srcu_readers_active_idx() above, then any destructive
229          * operation performed after the grace period will happen after
230          * the corresponding SRCU read-side critical section.
231          *
232          * Note that there can be at most NR_CPUS worth of readers using
233          * the old index, which is not enough to overflow even a 32-bit
234          * integer.  (Yes, this does mean that systems having more than
235          * a billion or so CPUs need to be 64-bit systems.)  Therefore,
236          * the sum of the ->seq[] counters cannot possibly overflow.
237          * Therefore, the only way that the return values of the two
238          * calls to srcu_readers_seq_idx() can be equal is if there were
239          * no increments of the corresponding rank of ->seq[] counts
240          * in the interim.  But the missed-increment scenario laid out
241          * above includes an increment of the ->seq[] counter by
242          * the corresponding __srcu_read_lock().  Therefore, if this
243          * scenario occurs, the return values from the two calls to
244          * srcu_readers_seq_idx() will differ, and thus the validation
245          * step below suffices.
246          */
247         smp_mb(); /* D */
248
249         return srcu_readers_seq_idx(sp, idx) == seq;
250 }
251
252 /**
253  * srcu_readers_active - returns approximate number of readers.
254  * @sp: which srcu_struct to count active readers (holding srcu_read_lock).
255  *
256  * Note that this is not an atomic primitive, and can therefore suffer
257  * severe errors when invoked on an active srcu_struct.  That said, it
258  * can be useful as an error check at cleanup time.
259  */
260 static int srcu_readers_active(struct srcu_struct *sp)
261 {
262         int cpu;
263         unsigned long sum = 0;
264
265         for_each_possible_cpu(cpu) {
266                 sum += ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[0]);
267                 sum += ACCESS_ONCE(per_cpu_ptr(sp->per_cpu_ref, cpu)->c[1]);
268         }
269         return sum;
270 }
271
272 /**
273  * cleanup_srcu_struct - deconstruct a sleep-RCU structure
274  * @sp: structure to clean up.
275  *
276  * Must invoke this after you are finished using a given srcu_struct that
277  * was initialized via init_srcu_struct(), else you leak memory.
278  */
279 void cleanup_srcu_struct(struct srcu_struct *sp)
280 {
281         int sum;
282
283         sum = srcu_readers_active(sp);
284         WARN_ON(sum);  /* Leakage unless caller handles error. */
285         if (sum != 0)
286                 return;
287         free_percpu(sp->per_cpu_ref);
288         sp->per_cpu_ref = NULL;
289 }
290 EXPORT_SYMBOL_GPL(cleanup_srcu_struct);
291
292 /*
293  * Counts the new reader in the appropriate per-CPU element of the
294  * srcu_struct.  Must be called from process context.
295  * Returns an index that must be passed to the matching srcu_read_unlock().
296  */
297 int __srcu_read_lock(struct srcu_struct *sp)
298 {
299         int idx;
300
301         preempt_disable();
302         idx = rcu_dereference_index_check(sp->completed,
303                                           rcu_read_lock_sched_held()) & 0x1;
304         ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->c[idx]) += 1;
305         smp_mb(); /* B */  /* Avoid leaking the critical section. */
306         ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->seq[idx]) += 1;
307         preempt_enable();
308         return idx;
309 }
310 EXPORT_SYMBOL_GPL(__srcu_read_lock);
311
312 /*
313  * Removes the count for the old reader from the appropriate per-CPU
314  * element of the srcu_struct.  Note that this may well be a different
315  * CPU than that which was incremented by the corresponding srcu_read_lock().
316  * Must be called from process context.
317  */
318 void __srcu_read_unlock(struct srcu_struct *sp, int idx)
319 {
320         preempt_disable();
321         smp_mb(); /* C */  /* Avoid leaking the critical section. */
322         ACCESS_ONCE(this_cpu_ptr(sp->per_cpu_ref)->c[idx]) -= 1;
323         preempt_enable();
324 }
325 EXPORT_SYMBOL_GPL(__srcu_read_unlock);
326
327 /*
328  * We use an adaptive strategy for synchronize_srcu() and especially for
329  * synchronize_srcu_expedited().  We spin for a fixed time period
330  * (defined below) to allow SRCU readers to exit their read-side critical
331  * sections.  If there are still some readers after 10 microseconds,
332  * we repeatedly block for 1-millisecond time periods.  This approach
333  * has done well in testing, so there is no need for a config parameter.
334  */
335 #define SRCU_RETRY_CHECK_DELAY          5
336 #define SYNCHRONIZE_SRCU_TRYCOUNT       2
337 #define SYNCHRONIZE_SRCU_EXP_TRYCOUNT   12
338
339 /*
340  * @@@ Wait until all pre-existing readers complete.  Such readers
341  * will have used the index specified by "idx".
342  * the caller should ensures the ->completed is not changed while checking
343  * and idx = (->completed & 1) ^ 1
344  */
345 static bool try_check_zero(struct srcu_struct *sp, int idx, int trycount)
346 {
347         for (;;) {
348                 if (srcu_readers_active_idx_check(sp, idx))
349                         return true;
350                 if (--trycount <= 0)
351                         return false;
352                 udelay(SRCU_RETRY_CHECK_DELAY);
353         }
354 }
355
356 /*
357  * Increment the ->completed counter so that future SRCU readers will
358  * use the other rank of the ->c[] and ->seq[] arrays.  This allows
359  * us to wait for pre-existing readers in a starvation-free manner.
360  */
361 static void srcu_flip(struct srcu_struct *sp)
362 {
363         sp->completed++;
364 }
365
366 /*
367  * Enqueue an SRCU callback on the specified srcu_struct structure,
368  * initiating grace-period processing if it is not already running.
369  */
370 void call_srcu(struct srcu_struct *sp, struct rcu_head *head,
371                 void (*func)(struct rcu_head *head))
372 {
373         unsigned long flags;
374
375         head->next = NULL;
376         head->func = func;
377         spin_lock_irqsave(&sp->queue_lock, flags);
378         rcu_batch_queue(&sp->batch_queue, head);
379         if (!sp->running) {
380                 sp->running = true;
381                 schedule_delayed_work(&sp->work, 0);
382         }
383         spin_unlock_irqrestore(&sp->queue_lock, flags);
384 }
385 EXPORT_SYMBOL_GPL(call_srcu);
386
387 struct rcu_synchronize {
388         struct rcu_head head;
389         struct completion completion;
390 };
391
392 /*
393  * Awaken the corresponding synchronize_srcu() instance now that a
394  * grace period has elapsed.
395  */
396 static void wakeme_after_rcu(struct rcu_head *head)
397 {
398         struct rcu_synchronize *rcu;
399
400         rcu = container_of(head, struct rcu_synchronize, head);
401         complete(&rcu->completion);
402 }
403
404 static void srcu_advance_batches(struct srcu_struct *sp, int trycount);
405 static void srcu_reschedule(struct srcu_struct *sp);
406
407 /*
408  * Helper function for synchronize_srcu() and synchronize_srcu_expedited().
409  */
410 static void __synchronize_srcu(struct srcu_struct *sp, int trycount)
411 {
412         struct rcu_synchronize rcu;
413         struct rcu_head *head = &rcu.head;
414         bool done = false;
415
416         rcu_lockdep_assert(!lock_is_held(&sp->dep_map) &&
417                            !lock_is_held(&rcu_bh_lock_map) &&
418                            !lock_is_held(&rcu_lock_map) &&
419                            !lock_is_held(&rcu_sched_lock_map),
420                            "Illegal synchronize_srcu() in same-type SRCU (or RCU) read-side critical section");
421
422         init_completion(&rcu.completion);
423
424         head->next = NULL;
425         head->func = wakeme_after_rcu;
426         spin_lock_irq(&sp->queue_lock);
427         if (!sp->running) {
428                 /* steal the processing owner */
429                 sp->running = true;
430                 rcu_batch_queue(&sp->batch_check0, head);
431                 spin_unlock_irq(&sp->queue_lock);
432
433                 srcu_advance_batches(sp, trycount);
434                 if (!rcu_batch_empty(&sp->batch_done)) {
435                         BUG_ON(sp->batch_done.head != head);
436                         rcu_batch_dequeue(&sp->batch_done);
437                         done = true;
438                 }
439                 /* give the processing owner to work_struct */
440                 srcu_reschedule(sp);
441         } else {
442                 rcu_batch_queue(&sp->batch_queue, head);
443                 spin_unlock_irq(&sp->queue_lock);
444         }
445
446         if (!done)
447                 wait_for_completion(&rcu.completion);
448 }
449
450 /**
451  * synchronize_srcu - wait for prior SRCU read-side critical-section completion
452  * @sp: srcu_struct with which to synchronize.
453  *
454  * Flip the completed counter, and wait for the old count to drain to zero.
455  * As with classic RCU, the updater must use some separate means of
456  * synchronizing concurrent updates.  Can block; must be called from
457  * process context.
458  *
459  * Note that it is illegal to call synchronize_srcu() from the corresponding
460  * SRCU read-side critical section; doing so will result in deadlock.
461  * However, it is perfectly legal to call synchronize_srcu() on one
462  * srcu_struct from some other srcu_struct's read-side critical section.
463  */
464 void synchronize_srcu(struct srcu_struct *sp)
465 {
466         __synchronize_srcu(sp, SYNCHRONIZE_SRCU_TRYCOUNT);
467 }
468 EXPORT_SYMBOL_GPL(synchronize_srcu);
469
470 /**
471  * synchronize_srcu_expedited - Brute-force SRCU grace period
472  * @sp: srcu_struct with which to synchronize.
473  *
474  * Wait for an SRCU grace period to elapse, but be more aggressive about
475  * spinning rather than blocking when waiting.
476  *
477  * Note that it is illegal to call this function while holding any lock
478  * that is acquired by a CPU-hotplug notifier.  It is also illegal to call
479  * synchronize_srcu_expedited() from the corresponding SRCU read-side
480  * critical section; doing so will result in deadlock.  However, it is
481  * perfectly legal to call synchronize_srcu_expedited() on one srcu_struct
482  * from some other srcu_struct's read-side critical section, as long as
483  * the resulting graph of srcu_structs is acyclic.
484  */
485 void synchronize_srcu_expedited(struct srcu_struct *sp)
486 {
487         __synchronize_srcu(sp, SYNCHRONIZE_SRCU_EXP_TRYCOUNT);
488 }
489 EXPORT_SYMBOL_GPL(synchronize_srcu_expedited);
490
491 /**
492  * srcu_barrier - Wait until all in-flight call_srcu() callbacks complete.
493  */
494 void srcu_barrier(struct srcu_struct *sp)
495 {
496         synchronize_srcu(sp);
497 }
498 EXPORT_SYMBOL_GPL(srcu_barrier);
499
500 /**
501  * srcu_batches_completed - return batches completed.
502  * @sp: srcu_struct on which to report batch completion.
503  *
504  * Report the number of batches, correlated with, but not necessarily
505  * precisely the same as, the number of grace periods that have elapsed.
506  */
507 long srcu_batches_completed(struct srcu_struct *sp)
508 {
509         return sp->completed;
510 }
511 EXPORT_SYMBOL_GPL(srcu_batches_completed);
512
513 #define SRCU_CALLBACK_BATCH     10
514 #define SRCU_INTERVAL           1
515
516 /*
517  * Move any new SRCU callbacks to the first stage of the SRCU grace
518  * period pipeline.
519  */
520 static void srcu_collect_new(struct srcu_struct *sp)
521 {
522         if (!rcu_batch_empty(&sp->batch_queue)) {
523                 spin_lock_irq(&sp->queue_lock);
524                 rcu_batch_move(&sp->batch_check0, &sp->batch_queue);
525                 spin_unlock_irq(&sp->queue_lock);
526         }
527 }
528
529 /*
530  * Core SRCU state machine.  Advance callbacks from ->batch_check0 to
531  * ->batch_check1 and then to ->batch_done as readers drain.
532  */
533 static void srcu_advance_batches(struct srcu_struct *sp, int trycount)
534 {
535         int idx = 1 ^ (sp->completed & 1);
536
537         /*
538          * Because readers might be delayed for an extended period after
539          * fetching ->completed for their index, at any point in time there
540          * might well be readers using both idx=0 and idx=1.  We therefore
541          * need to wait for readers to clear from both index values before
542          * invoking a callback.
543          */
544
545         if (rcu_batch_empty(&sp->batch_check0) &&
546             rcu_batch_empty(&sp->batch_check1))
547                 return; /* no callbacks need to be advanced */
548
549         if (!try_check_zero(sp, idx, trycount))
550                 return; /* failed to advance, will try after SRCU_INTERVAL */
551
552         /*
553          * The callbacks in ->batch_check1 have already done with their
554          * first zero check and flip back when they were enqueued on
555          * ->batch_check0 in a previous invocation of srcu_advance_batches().
556          * (Presumably try_check_zero() returned false during that
557          * invocation, leaving the callbacks stranded on ->batch_check1.)
558          * They are therefore ready to invoke, so move them to ->batch_done.
559          */
560         rcu_batch_move(&sp->batch_done, &sp->batch_check1);
561
562         if (rcu_batch_empty(&sp->batch_check0))
563                 return; /* no callbacks need to be advanced */
564         srcu_flip(sp);
565
566         /*
567          * The callbacks in ->batch_check0 just finished their
568          * first check zero and flip, so move them to ->batch_check1
569          * for future checking on the other idx.
570          */
571         rcu_batch_move(&sp->batch_check1, &sp->batch_check0);
572
573         /*
574          * SRCU read-side critical sections are normally short, so check
575          * at least twice in quick succession after a flip.
576          */
577         trycount = trycount < 2 ? 2 : trycount;
578         if (!try_check_zero(sp, idx^1, trycount))
579                 return; /* failed to advance, will try after SRCU_INTERVAL */
580
581         /*
582          * The callbacks in ->batch_check1 have now waited for all
583          * pre-existing readers using both idx values.  They are therefore
584          * ready to invoke, so move them to ->batch_done.
585          */
586         rcu_batch_move(&sp->batch_done, &sp->batch_check1);
587 }
588
589 /*
590  * Invoke a limited number of SRCU callbacks that have passed through
591  * their grace period.  If there are more to do, SRCU will reschedule
592  * the workqueue.
593  */
594 static void srcu_invoke_callbacks(struct srcu_struct *sp)
595 {
596         int i;
597         struct rcu_head *head;
598
599         for (i = 0; i < SRCU_CALLBACK_BATCH; i++) {
600                 head = rcu_batch_dequeue(&sp->batch_done);
601                 if (!head)
602                         break;
603                 local_bh_disable();
604                 head->func(head);
605                 local_bh_enable();
606         }
607 }
608
609 /*
610  * Finished one round of SRCU grace period.  Start another if there are
611  * more SRCU callbacks queued, otherwise put SRCU into not-running state.
612  */
613 static void srcu_reschedule(struct srcu_struct *sp)
614 {
615         bool pending = true;
616
617         if (rcu_batch_empty(&sp->batch_done) &&
618             rcu_batch_empty(&sp->batch_check1) &&
619             rcu_batch_empty(&sp->batch_check0) &&
620             rcu_batch_empty(&sp->batch_queue)) {
621                 spin_lock_irq(&sp->queue_lock);
622                 if (rcu_batch_empty(&sp->batch_done) &&
623                     rcu_batch_empty(&sp->batch_check1) &&
624                     rcu_batch_empty(&sp->batch_check0) &&
625                     rcu_batch_empty(&sp->batch_queue)) {
626                         sp->running = false;
627                         pending = false;
628                 }
629                 spin_unlock_irq(&sp->queue_lock);
630         }
631
632         if (pending)
633                 schedule_delayed_work(&sp->work, SRCU_INTERVAL);
634 }
635
636 /*
637  * This is the work-queue function that handles SRCU grace periods.
638  */
639 void process_srcu(struct work_struct *work)
640 {
641         struct srcu_struct *sp;
642
643         sp = container_of(work, struct srcu_struct, work.work);
644
645         srcu_collect_new(sp);
646         srcu_advance_batches(sp, 1);
647         srcu_invoke_callbacks(sp);
648         srcu_reschedule(sp);
649 }
650 EXPORT_SYMBOL_GPL(process_srcu);