sched, smp: Trace IPIs sent via send_call_function_single_ipi()
[linux-block.git] / kernel / smp.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Generic helpers for smp ipi calls
4  *
5  * (C) Jens Axboe <jens.axboe@oracle.com> 2008
6  */
7
8 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
9
10 #include <linux/irq_work.h>
11 #include <linux/rcupdate.h>
12 #include <linux/rculist.h>
13 #include <linux/kernel.h>
14 #include <linux/export.h>
15 #include <linux/percpu.h>
16 #include <linux/init.h>
17 #include <linux/interrupt.h>
18 #include <linux/gfp.h>
19 #include <linux/smp.h>
20 #include <linux/cpu.h>
21 #include <linux/sched.h>
22 #include <linux/sched/idle.h>
23 #include <linux/hypervisor.h>
24 #include <linux/sched/clock.h>
25 #include <linux/nmi.h>
26 #include <linux/sched/debug.h>
27 #include <linux/jump_label.h>
28
29 #include <trace/events/ipi.h>
30
31 #include "smpboot.h"
32 #include "sched/smp.h"
33
34 #define CSD_TYPE(_csd)  ((_csd)->node.u_flags & CSD_FLAG_TYPE_MASK)
35
36 struct call_function_data {
37         call_single_data_t      __percpu *csd;
38         cpumask_var_t           cpumask;
39         cpumask_var_t           cpumask_ipi;
40 };
41
42 static DEFINE_PER_CPU_ALIGNED(struct call_function_data, cfd_data);
43
44 static DEFINE_PER_CPU_SHARED_ALIGNED(struct llist_head, call_single_queue);
45
46 static void __flush_smp_call_function_queue(bool warn_cpu_offline);
47
48 int smpcfd_prepare_cpu(unsigned int cpu)
49 {
50         struct call_function_data *cfd = &per_cpu(cfd_data, cpu);
51
52         if (!zalloc_cpumask_var_node(&cfd->cpumask, GFP_KERNEL,
53                                      cpu_to_node(cpu)))
54                 return -ENOMEM;
55         if (!zalloc_cpumask_var_node(&cfd->cpumask_ipi, GFP_KERNEL,
56                                      cpu_to_node(cpu))) {
57                 free_cpumask_var(cfd->cpumask);
58                 return -ENOMEM;
59         }
60         cfd->csd = alloc_percpu(call_single_data_t);
61         if (!cfd->csd) {
62                 free_cpumask_var(cfd->cpumask);
63                 free_cpumask_var(cfd->cpumask_ipi);
64                 return -ENOMEM;
65         }
66
67         return 0;
68 }
69
70 int smpcfd_dead_cpu(unsigned int cpu)
71 {
72         struct call_function_data *cfd = &per_cpu(cfd_data, cpu);
73
74         free_cpumask_var(cfd->cpumask);
75         free_cpumask_var(cfd->cpumask_ipi);
76         free_percpu(cfd->csd);
77         return 0;
78 }
79
80 int smpcfd_dying_cpu(unsigned int cpu)
81 {
82         /*
83          * The IPIs for the smp-call-function callbacks queued by other
84          * CPUs might arrive late, either due to hardware latencies or
85          * because this CPU disabled interrupts (inside stop-machine)
86          * before the IPIs were sent. So flush out any pending callbacks
87          * explicitly (without waiting for the IPIs to arrive), to
88          * ensure that the outgoing CPU doesn't go offline with work
89          * still pending.
90          */
91         __flush_smp_call_function_queue(false);
92         irq_work_run();
93         return 0;
94 }
95
96 void __init call_function_init(void)
97 {
98         int i;
99
100         for_each_possible_cpu(i)
101                 init_llist_head(&per_cpu(call_single_queue, i));
102
103         smpcfd_prepare_cpu(smp_processor_id());
104 }
105
106 #ifdef CONFIG_CSD_LOCK_WAIT_DEBUG
107
108 static DEFINE_STATIC_KEY_MAYBE(CONFIG_CSD_LOCK_WAIT_DEBUG_DEFAULT, csdlock_debug_enabled);
109
110 /*
111  * Parse the csdlock_debug= kernel boot parameter.
112  *
113  * If you need to restore the old "ext" value that once provided
114  * additional debugging information, reapply the following commits:
115  *
116  * de7b09ef658d ("locking/csd_lock: Prepare more CSD lock debugging")
117  * a5aabace5fb8 ("locking/csd_lock: Add more data to CSD lock debugging")
118  */
119 static int __init csdlock_debug(char *str)
120 {
121         int ret;
122         unsigned int val = 0;
123
124         ret = get_option(&str, &val);
125         if (ret) {
126                 if (val)
127                         static_branch_enable(&csdlock_debug_enabled);
128                 else
129                         static_branch_disable(&csdlock_debug_enabled);
130         }
131
132         return 1;
133 }
134 __setup("csdlock_debug=", csdlock_debug);
135
136 static DEFINE_PER_CPU(call_single_data_t *, cur_csd);
137 static DEFINE_PER_CPU(smp_call_func_t, cur_csd_func);
138 static DEFINE_PER_CPU(void *, cur_csd_info);
139
140 static ulong csd_lock_timeout = 5000;  /* CSD lock timeout in milliseconds. */
141 module_param(csd_lock_timeout, ulong, 0444);
142
143 static atomic_t csd_bug_count = ATOMIC_INIT(0);
144
145 /* Record current CSD work for current CPU, NULL to erase. */
146 static void __csd_lock_record(struct __call_single_data *csd)
147 {
148         if (!csd) {
149                 smp_mb(); /* NULL cur_csd after unlock. */
150                 __this_cpu_write(cur_csd, NULL);
151                 return;
152         }
153         __this_cpu_write(cur_csd_func, csd->func);
154         __this_cpu_write(cur_csd_info, csd->info);
155         smp_wmb(); /* func and info before csd. */
156         __this_cpu_write(cur_csd, csd);
157         smp_mb(); /* Update cur_csd before function call. */
158                   /* Or before unlock, as the case may be. */
159 }
160
161 static __always_inline void csd_lock_record(struct __call_single_data *csd)
162 {
163         if (static_branch_unlikely(&csdlock_debug_enabled))
164                 __csd_lock_record(csd);
165 }
166
167 static int csd_lock_wait_getcpu(struct __call_single_data *csd)
168 {
169         unsigned int csd_type;
170
171         csd_type = CSD_TYPE(csd);
172         if (csd_type == CSD_TYPE_ASYNC || csd_type == CSD_TYPE_SYNC)
173                 return csd->node.dst; /* Other CSD_TYPE_ values might not have ->dst. */
174         return -1;
175 }
176
177 /*
178  * Complain if too much time spent waiting.  Note that only
179  * the CSD_TYPE_SYNC/ASYNC types provide the destination CPU,
180  * so waiting on other types gets much less information.
181  */
182 static bool csd_lock_wait_toolong(struct __call_single_data *csd, u64 ts0, u64 *ts1, int *bug_id)
183 {
184         int cpu = -1;
185         int cpux;
186         bool firsttime;
187         u64 ts2, ts_delta;
188         call_single_data_t *cpu_cur_csd;
189         unsigned int flags = READ_ONCE(csd->node.u_flags);
190         unsigned long long csd_lock_timeout_ns = csd_lock_timeout * NSEC_PER_MSEC;
191
192         if (!(flags & CSD_FLAG_LOCK)) {
193                 if (!unlikely(*bug_id))
194                         return true;
195                 cpu = csd_lock_wait_getcpu(csd);
196                 pr_alert("csd: CSD lock (#%d) got unstuck on CPU#%02d, CPU#%02d released the lock.\n",
197                          *bug_id, raw_smp_processor_id(), cpu);
198                 return true;
199         }
200
201         ts2 = sched_clock();
202         ts_delta = ts2 - *ts1;
203         if (likely(ts_delta <= csd_lock_timeout_ns || csd_lock_timeout_ns == 0))
204                 return false;
205
206         firsttime = !*bug_id;
207         if (firsttime)
208                 *bug_id = atomic_inc_return(&csd_bug_count);
209         cpu = csd_lock_wait_getcpu(csd);
210         if (WARN_ONCE(cpu < 0 || cpu >= nr_cpu_ids, "%s: cpu = %d\n", __func__, cpu))
211                 cpux = 0;
212         else
213                 cpux = cpu;
214         cpu_cur_csd = smp_load_acquire(&per_cpu(cur_csd, cpux)); /* Before func and info. */
215         pr_alert("csd: %s non-responsive CSD lock (#%d) on CPU#%d, waiting %llu ns for CPU#%02d %pS(%ps).\n",
216                  firsttime ? "Detected" : "Continued", *bug_id, raw_smp_processor_id(), ts2 - ts0,
217                  cpu, csd->func, csd->info);
218         if (cpu_cur_csd && csd != cpu_cur_csd) {
219                 pr_alert("\tcsd: CSD lock (#%d) handling prior %pS(%ps) request.\n",
220                          *bug_id, READ_ONCE(per_cpu(cur_csd_func, cpux)),
221                          READ_ONCE(per_cpu(cur_csd_info, cpux)));
222         } else {
223                 pr_alert("\tcsd: CSD lock (#%d) %s.\n",
224                          *bug_id, !cpu_cur_csd ? "unresponsive" : "handling this request");
225         }
226         if (cpu >= 0) {
227                 dump_cpu_task(cpu);
228                 if (!cpu_cur_csd) {
229                         pr_alert("csd: Re-sending CSD lock (#%d) IPI from CPU#%02d to CPU#%02d\n", *bug_id, raw_smp_processor_id(), cpu);
230                         arch_send_call_function_single_ipi(cpu);
231                 }
232         }
233         dump_stack();
234         *ts1 = ts2;
235
236         return false;
237 }
238
239 /*
240  * csd_lock/csd_unlock used to serialize access to per-cpu csd resources
241  *
242  * For non-synchronous ipi calls the csd can still be in use by the
243  * previous function call. For multi-cpu calls its even more interesting
244  * as we'll have to ensure no other cpu is observing our csd.
245  */
246 static void __csd_lock_wait(struct __call_single_data *csd)
247 {
248         int bug_id = 0;
249         u64 ts0, ts1;
250
251         ts1 = ts0 = sched_clock();
252         for (;;) {
253                 if (csd_lock_wait_toolong(csd, ts0, &ts1, &bug_id))
254                         break;
255                 cpu_relax();
256         }
257         smp_acquire__after_ctrl_dep();
258 }
259
260 static __always_inline void csd_lock_wait(struct __call_single_data *csd)
261 {
262         if (static_branch_unlikely(&csdlock_debug_enabled)) {
263                 __csd_lock_wait(csd);
264                 return;
265         }
266
267         smp_cond_load_acquire(&csd->node.u_flags, !(VAL & CSD_FLAG_LOCK));
268 }
269 #else
270 static void csd_lock_record(struct __call_single_data *csd)
271 {
272 }
273
274 static __always_inline void csd_lock_wait(struct __call_single_data *csd)
275 {
276         smp_cond_load_acquire(&csd->node.u_flags, !(VAL & CSD_FLAG_LOCK));
277 }
278 #endif
279
280 static __always_inline void csd_lock(struct __call_single_data *csd)
281 {
282         csd_lock_wait(csd);
283         csd->node.u_flags |= CSD_FLAG_LOCK;
284
285         /*
286          * prevent CPU from reordering the above assignment
287          * to ->flags with any subsequent assignments to other
288          * fields of the specified call_single_data_t structure:
289          */
290         smp_wmb();
291 }
292
293 static __always_inline void csd_unlock(struct __call_single_data *csd)
294 {
295         WARN_ON(!(csd->node.u_flags & CSD_FLAG_LOCK));
296
297         /*
298          * ensure we're all done before releasing data:
299          */
300         smp_store_release(&csd->node.u_flags, 0);
301 }
302
303 static DEFINE_PER_CPU_SHARED_ALIGNED(call_single_data_t, csd_data);
304
305 void __smp_call_single_queue(int cpu, struct llist_node *node)
306 {
307         /*
308          * The list addition should be visible before sending the IPI
309          * handler locks the list to pull the entry off it because of
310          * normal cache coherency rules implied by spinlocks.
311          *
312          * If IPIs can go out of order to the cache coherency protocol
313          * in an architecture, sufficient synchronisation should be added
314          * to arch code to make it appear to obey cache coherency WRT
315          * locking and barrier primitives. Generic code isn't really
316          * equipped to do the right thing...
317          */
318         if (llist_add(node, &per_cpu(call_single_queue, cpu)))
319                 send_call_function_single_ipi(cpu);
320 }
321
322 /*
323  * Insert a previously allocated call_single_data_t element
324  * for execution on the given CPU. data must already have
325  * ->func, ->info, and ->flags set.
326  */
327 static int generic_exec_single(int cpu, struct __call_single_data *csd)
328 {
329         if (cpu == smp_processor_id()) {
330                 smp_call_func_t func = csd->func;
331                 void *info = csd->info;
332                 unsigned long flags;
333
334                 /*
335                  * We can unlock early even for the synchronous on-stack case,
336                  * since we're doing this from the same CPU..
337                  */
338                 csd_lock_record(csd);
339                 csd_unlock(csd);
340                 local_irq_save(flags);
341                 func(info);
342                 csd_lock_record(NULL);
343                 local_irq_restore(flags);
344                 return 0;
345         }
346
347         if ((unsigned)cpu >= nr_cpu_ids || !cpu_online(cpu)) {
348                 csd_unlock(csd);
349                 return -ENXIO;
350         }
351
352         __smp_call_single_queue(cpu, &csd->node.llist);
353
354         return 0;
355 }
356
357 /**
358  * generic_smp_call_function_single_interrupt - Execute SMP IPI callbacks
359  *
360  * Invoked by arch to handle an IPI for call function single.
361  * Must be called with interrupts disabled.
362  */
363 void generic_smp_call_function_single_interrupt(void)
364 {
365         __flush_smp_call_function_queue(true);
366 }
367
368 /**
369  * __flush_smp_call_function_queue - Flush pending smp-call-function callbacks
370  *
371  * @warn_cpu_offline: If set to 'true', warn if callbacks were queued on an
372  *                    offline CPU. Skip this check if set to 'false'.
373  *
374  * Flush any pending smp-call-function callbacks queued on this CPU. This is
375  * invoked by the generic IPI handler, as well as by a CPU about to go offline,
376  * to ensure that all pending IPI callbacks are run before it goes completely
377  * offline.
378  *
379  * Loop through the call_single_queue and run all the queued callbacks.
380  * Must be called with interrupts disabled.
381  */
382 static void __flush_smp_call_function_queue(bool warn_cpu_offline)
383 {
384         call_single_data_t *csd, *csd_next;
385         struct llist_node *entry, *prev;
386         struct llist_head *head;
387         static bool warned;
388
389         lockdep_assert_irqs_disabled();
390
391         head = this_cpu_ptr(&call_single_queue);
392         entry = llist_del_all(head);
393         entry = llist_reverse_order(entry);
394
395         /* There shouldn't be any pending callbacks on an offline CPU. */
396         if (unlikely(warn_cpu_offline && !cpu_online(smp_processor_id()) &&
397                      !warned && entry != NULL)) {
398                 warned = true;
399                 WARN(1, "IPI on offline CPU %d\n", smp_processor_id());
400
401                 /*
402                  * We don't have to use the _safe() variant here
403                  * because we are not invoking the IPI handlers yet.
404                  */
405                 llist_for_each_entry(csd, entry, node.llist) {
406                         switch (CSD_TYPE(csd)) {
407                         case CSD_TYPE_ASYNC:
408                         case CSD_TYPE_SYNC:
409                         case CSD_TYPE_IRQ_WORK:
410                                 pr_warn("IPI callback %pS sent to offline CPU\n",
411                                         csd->func);
412                                 break;
413
414                         case CSD_TYPE_TTWU:
415                                 pr_warn("IPI task-wakeup sent to offline CPU\n");
416                                 break;
417
418                         default:
419                                 pr_warn("IPI callback, unknown type %d, sent to offline CPU\n",
420                                         CSD_TYPE(csd));
421                                 break;
422                         }
423                 }
424         }
425
426         /*
427          * First; run all SYNC callbacks, people are waiting for us.
428          */
429         prev = NULL;
430         llist_for_each_entry_safe(csd, csd_next, entry, node.llist) {
431                 /* Do we wait until *after* callback? */
432                 if (CSD_TYPE(csd) == CSD_TYPE_SYNC) {
433                         smp_call_func_t func = csd->func;
434                         void *info = csd->info;
435
436                         if (prev) {
437                                 prev->next = &csd_next->node.llist;
438                         } else {
439                                 entry = &csd_next->node.llist;
440                         }
441
442                         csd_lock_record(csd);
443                         func(info);
444                         csd_unlock(csd);
445                         csd_lock_record(NULL);
446                 } else {
447                         prev = &csd->node.llist;
448                 }
449         }
450
451         if (!entry)
452                 return;
453
454         /*
455          * Second; run all !SYNC callbacks.
456          */
457         prev = NULL;
458         llist_for_each_entry_safe(csd, csd_next, entry, node.llist) {
459                 int type = CSD_TYPE(csd);
460
461                 if (type != CSD_TYPE_TTWU) {
462                         if (prev) {
463                                 prev->next = &csd_next->node.llist;
464                         } else {
465                                 entry = &csd_next->node.llist;
466                         }
467
468                         if (type == CSD_TYPE_ASYNC) {
469                                 smp_call_func_t func = csd->func;
470                                 void *info = csd->info;
471
472                                 csd_lock_record(csd);
473                                 csd_unlock(csd);
474                                 func(info);
475                                 csd_lock_record(NULL);
476                         } else if (type == CSD_TYPE_IRQ_WORK) {
477                                 irq_work_single(csd);
478                         }
479
480                 } else {
481                         prev = &csd->node.llist;
482                 }
483         }
484
485         /*
486          * Third; only CSD_TYPE_TTWU is left, issue those.
487          */
488         if (entry)
489                 sched_ttwu_pending(entry);
490 }
491
492
493 /**
494  * flush_smp_call_function_queue - Flush pending smp-call-function callbacks
495  *                                 from task context (idle, migration thread)
496  *
497  * When TIF_POLLING_NRFLAG is supported and a CPU is in idle and has it
498  * set, then remote CPUs can avoid sending IPIs and wake the idle CPU by
499  * setting TIF_NEED_RESCHED. The idle task on the woken up CPU has to
500  * handle queued SMP function calls before scheduling.
501  *
502  * The migration thread has to ensure that an eventually pending wakeup has
503  * been handled before it migrates a task.
504  */
505 void flush_smp_call_function_queue(void)
506 {
507         unsigned int was_pending;
508         unsigned long flags;
509
510         if (llist_empty(this_cpu_ptr(&call_single_queue)))
511                 return;
512
513         local_irq_save(flags);
514         /* Get the already pending soft interrupts for RT enabled kernels */
515         was_pending = local_softirq_pending();
516         __flush_smp_call_function_queue(true);
517         if (local_softirq_pending())
518                 do_softirq_post_smp_call_flush(was_pending);
519
520         local_irq_restore(flags);
521 }
522
523 /*
524  * smp_call_function_single - Run a function on a specific CPU
525  * @func: The function to run. This must be fast and non-blocking.
526  * @info: An arbitrary pointer to pass to the function.
527  * @wait: If true, wait until function has completed on other CPUs.
528  *
529  * Returns 0 on success, else a negative status code.
530  */
531 int smp_call_function_single(int cpu, smp_call_func_t func, void *info,
532                              int wait)
533 {
534         call_single_data_t *csd;
535         call_single_data_t csd_stack = {
536                 .node = { .u_flags = CSD_FLAG_LOCK | CSD_TYPE_SYNC, },
537         };
538         int this_cpu;
539         int err;
540
541         /*
542          * prevent preemption and reschedule on another processor,
543          * as well as CPU removal
544          */
545         this_cpu = get_cpu();
546
547         /*
548          * Can deadlock when called with interrupts disabled.
549          * We allow cpu's that are not yet online though, as no one else can
550          * send smp call function interrupt to this cpu and as such deadlocks
551          * can't happen.
552          */
553         WARN_ON_ONCE(cpu_online(this_cpu) && irqs_disabled()
554                      && !oops_in_progress);
555
556         /*
557          * When @wait we can deadlock when we interrupt between llist_add() and
558          * arch_send_call_function_ipi*(); when !@wait we can deadlock due to
559          * csd_lock() on because the interrupt context uses the same csd
560          * storage.
561          */
562         WARN_ON_ONCE(!in_task());
563
564         csd = &csd_stack;
565         if (!wait) {
566                 csd = this_cpu_ptr(&csd_data);
567                 csd_lock(csd);
568         }
569
570         csd->func = func;
571         csd->info = info;
572 #ifdef CONFIG_CSD_LOCK_WAIT_DEBUG
573         csd->node.src = smp_processor_id();
574         csd->node.dst = cpu;
575 #endif
576
577         err = generic_exec_single(cpu, csd);
578
579         if (wait)
580                 csd_lock_wait(csd);
581
582         put_cpu();
583
584         return err;
585 }
586 EXPORT_SYMBOL(smp_call_function_single);
587
588 /**
589  * smp_call_function_single_async() - Run an asynchronous function on a
590  *                               specific CPU.
591  * @cpu: The CPU to run on.
592  * @csd: Pre-allocated and setup data structure
593  *
594  * Like smp_call_function_single(), but the call is asynchonous and
595  * can thus be done from contexts with disabled interrupts.
596  *
597  * The caller passes his own pre-allocated data structure
598  * (ie: embedded in an object) and is responsible for synchronizing it
599  * such that the IPIs performed on the @csd are strictly serialized.
600  *
601  * If the function is called with one csd which has not yet been
602  * processed by previous call to smp_call_function_single_async(), the
603  * function will return immediately with -EBUSY showing that the csd
604  * object is still in progress.
605  *
606  * NOTE: Be careful, there is unfortunately no current debugging facility to
607  * validate the correctness of this serialization.
608  *
609  * Return: %0 on success or negative errno value on error
610  */
611 int smp_call_function_single_async(int cpu, struct __call_single_data *csd)
612 {
613         int err = 0;
614
615         preempt_disable();
616
617         if (csd->node.u_flags & CSD_FLAG_LOCK) {
618                 err = -EBUSY;
619                 goto out;
620         }
621
622         csd->node.u_flags = CSD_FLAG_LOCK;
623         smp_wmb();
624
625         err = generic_exec_single(cpu, csd);
626
627 out:
628         preempt_enable();
629
630         return err;
631 }
632 EXPORT_SYMBOL_GPL(smp_call_function_single_async);
633
634 /*
635  * smp_call_function_any - Run a function on any of the given cpus
636  * @mask: The mask of cpus it can run on.
637  * @func: The function to run. This must be fast and non-blocking.
638  * @info: An arbitrary pointer to pass to the function.
639  * @wait: If true, wait until function has completed.
640  *
641  * Returns 0 on success, else a negative status code (if no cpus were online).
642  *
643  * Selection preference:
644  *      1) current cpu if in @mask
645  *      2) any cpu of current node if in @mask
646  *      3) any other online cpu in @mask
647  */
648 int smp_call_function_any(const struct cpumask *mask,
649                           smp_call_func_t func, void *info, int wait)
650 {
651         unsigned int cpu;
652         const struct cpumask *nodemask;
653         int ret;
654
655         /* Try for same CPU (cheapest) */
656         cpu = get_cpu();
657         if (cpumask_test_cpu(cpu, mask))
658                 goto call;
659
660         /* Try for same node. */
661         nodemask = cpumask_of_node(cpu_to_node(cpu));
662         for (cpu = cpumask_first_and(nodemask, mask); cpu < nr_cpu_ids;
663              cpu = cpumask_next_and(cpu, nodemask, mask)) {
664                 if (cpu_online(cpu))
665                         goto call;
666         }
667
668         /* Any online will do: smp_call_function_single handles nr_cpu_ids. */
669         cpu = cpumask_any_and(mask, cpu_online_mask);
670 call:
671         ret = smp_call_function_single(cpu, func, info, wait);
672         put_cpu();
673         return ret;
674 }
675 EXPORT_SYMBOL_GPL(smp_call_function_any);
676
677 /*
678  * Flags to be used as scf_flags argument of smp_call_function_many_cond().
679  *
680  * %SCF_WAIT:           Wait until function execution is completed
681  * %SCF_RUN_LOCAL:      Run also locally if local cpu is set in cpumask
682  */
683 #define SCF_WAIT        (1U << 0)
684 #define SCF_RUN_LOCAL   (1U << 1)
685
686 static void smp_call_function_many_cond(const struct cpumask *mask,
687                                         smp_call_func_t func, void *info,
688                                         unsigned int scf_flags,
689                                         smp_cond_func_t cond_func)
690 {
691         int cpu, last_cpu, this_cpu = smp_processor_id();
692         struct call_function_data *cfd;
693         bool wait = scf_flags & SCF_WAIT;
694         bool run_remote = false;
695         bool run_local = false;
696         int nr_cpus = 0;
697
698         lockdep_assert_preemption_disabled();
699
700         /*
701          * Can deadlock when called with interrupts disabled.
702          * We allow cpu's that are not yet online though, as no one else can
703          * send smp call function interrupt to this cpu and as such deadlocks
704          * can't happen.
705          */
706         if (cpu_online(this_cpu) && !oops_in_progress &&
707             !early_boot_irqs_disabled)
708                 lockdep_assert_irqs_enabled();
709
710         /*
711          * When @wait we can deadlock when we interrupt between llist_add() and
712          * arch_send_call_function_ipi*(); when !@wait we can deadlock due to
713          * csd_lock() on because the interrupt context uses the same csd
714          * storage.
715          */
716         WARN_ON_ONCE(!in_task());
717
718         /* Check if we need local execution. */
719         if ((scf_flags & SCF_RUN_LOCAL) && cpumask_test_cpu(this_cpu, mask))
720                 run_local = true;
721
722         /* Check if we need remote execution, i.e., any CPU excluding this one. */
723         cpu = cpumask_first_and(mask, cpu_online_mask);
724         if (cpu == this_cpu)
725                 cpu = cpumask_next_and(cpu, mask, cpu_online_mask);
726         if (cpu < nr_cpu_ids)
727                 run_remote = true;
728
729         if (run_remote) {
730                 cfd = this_cpu_ptr(&cfd_data);
731                 cpumask_and(cfd->cpumask, mask, cpu_online_mask);
732                 __cpumask_clear_cpu(this_cpu, cfd->cpumask);
733
734                 cpumask_clear(cfd->cpumask_ipi);
735                 for_each_cpu(cpu, cfd->cpumask) {
736                         call_single_data_t *csd = per_cpu_ptr(cfd->csd, cpu);
737
738                         if (cond_func && !cond_func(cpu, info))
739                                 continue;
740
741                         csd_lock(csd);
742                         if (wait)
743                                 csd->node.u_flags |= CSD_TYPE_SYNC;
744                         csd->func = func;
745                         csd->info = info;
746 #ifdef CONFIG_CSD_LOCK_WAIT_DEBUG
747                         csd->node.src = smp_processor_id();
748                         csd->node.dst = cpu;
749 #endif
750                         if (llist_add(&csd->node.llist, &per_cpu(call_single_queue, cpu))) {
751                                 __cpumask_set_cpu(cpu, cfd->cpumask_ipi);
752                                 nr_cpus++;
753                                 last_cpu = cpu;
754                         }
755                 }
756
757                 /*
758                  * Choose the most efficient way to send an IPI. Note that the
759                  * number of CPUs might be zero due to concurrent changes to the
760                  * provided mask.
761                  */
762                 if (nr_cpus == 1)
763                         send_call_function_single_ipi(last_cpu);
764                 else if (likely(nr_cpus > 1))
765                         arch_send_call_function_ipi_mask(cfd->cpumask_ipi);
766         }
767
768         if (run_local && (!cond_func || cond_func(this_cpu, info))) {
769                 unsigned long flags;
770
771                 local_irq_save(flags);
772                 func(info);
773                 local_irq_restore(flags);
774         }
775
776         if (run_remote && wait) {
777                 for_each_cpu(cpu, cfd->cpumask) {
778                         call_single_data_t *csd;
779
780                         csd = per_cpu_ptr(cfd->csd, cpu);
781                         csd_lock_wait(csd);
782                 }
783         }
784 }
785
786 /**
787  * smp_call_function_many(): Run a function on a set of CPUs.
788  * @mask: The set of cpus to run on (only runs on online subset).
789  * @func: The function to run. This must be fast and non-blocking.
790  * @info: An arbitrary pointer to pass to the function.
791  * @wait: Bitmask that controls the operation. If %SCF_WAIT is set, wait
792  *        (atomically) until function has completed on other CPUs. If
793  *        %SCF_RUN_LOCAL is set, the function will also be run locally
794  *        if the local CPU is set in the @cpumask.
795  *
796  * If @wait is true, then returns once @func has returned.
797  *
798  * You must not call this function with disabled interrupts or from a
799  * hardware interrupt handler or from a bottom half handler. Preemption
800  * must be disabled when calling this function.
801  */
802 void smp_call_function_many(const struct cpumask *mask,
803                             smp_call_func_t func, void *info, bool wait)
804 {
805         smp_call_function_many_cond(mask, func, info, wait * SCF_WAIT, NULL);
806 }
807 EXPORT_SYMBOL(smp_call_function_many);
808
809 /**
810  * smp_call_function(): Run a function on all other CPUs.
811  * @func: The function to run. This must be fast and non-blocking.
812  * @info: An arbitrary pointer to pass to the function.
813  * @wait: If true, wait (atomically) until function has completed
814  *        on other CPUs.
815  *
816  * Returns 0.
817  *
818  * If @wait is true, then returns once @func has returned; otherwise
819  * it returns just before the target cpu calls @func.
820  *
821  * You must not call this function with disabled interrupts or from a
822  * hardware interrupt handler or from a bottom half handler.
823  */
824 void smp_call_function(smp_call_func_t func, void *info, int wait)
825 {
826         preempt_disable();
827         smp_call_function_many(cpu_online_mask, func, info, wait);
828         preempt_enable();
829 }
830 EXPORT_SYMBOL(smp_call_function);
831
832 /* Setup configured maximum number of CPUs to activate */
833 unsigned int setup_max_cpus = NR_CPUS;
834 EXPORT_SYMBOL(setup_max_cpus);
835
836
837 /*
838  * Setup routine for controlling SMP activation
839  *
840  * Command-line option of "nosmp" or "maxcpus=0" will disable SMP
841  * activation entirely (the MPS table probe still happens, though).
842  *
843  * Command-line option of "maxcpus=<NUM>", where <NUM> is an integer
844  * greater than 0, limits the maximum number of CPUs activated in
845  * SMP mode to <NUM>.
846  */
847
848 void __weak arch_disable_smp_support(void) { }
849
850 static int __init nosmp(char *str)
851 {
852         setup_max_cpus = 0;
853         arch_disable_smp_support();
854
855         return 0;
856 }
857
858 early_param("nosmp", nosmp);
859
860 /* this is hard limit */
861 static int __init nrcpus(char *str)
862 {
863         int nr_cpus;
864
865         if (get_option(&str, &nr_cpus) && nr_cpus > 0 && nr_cpus < nr_cpu_ids)
866                 set_nr_cpu_ids(nr_cpus);
867
868         return 0;
869 }
870
871 early_param("nr_cpus", nrcpus);
872
873 static int __init maxcpus(char *str)
874 {
875         get_option(&str, &setup_max_cpus);
876         if (setup_max_cpus == 0)
877                 arch_disable_smp_support();
878
879         return 0;
880 }
881
882 early_param("maxcpus", maxcpus);
883
884 #if (NR_CPUS > 1) && !defined(CONFIG_FORCE_NR_CPUS)
885 /* Setup number of possible processor ids */
886 unsigned int nr_cpu_ids __read_mostly = NR_CPUS;
887 EXPORT_SYMBOL(nr_cpu_ids);
888 #endif
889
890 /* An arch may set nr_cpu_ids earlier if needed, so this would be redundant */
891 void __init setup_nr_cpu_ids(void)
892 {
893         set_nr_cpu_ids(find_last_bit(cpumask_bits(cpu_possible_mask), NR_CPUS) + 1);
894 }
895
896 /* Called by boot processor to activate the rest. */
897 void __init smp_init(void)
898 {
899         int num_nodes, num_cpus;
900
901         idle_threads_init();
902         cpuhp_threads_init();
903
904         pr_info("Bringing up secondary CPUs ...\n");
905
906         bringup_nonboot_cpus(setup_max_cpus);
907
908         num_nodes = num_online_nodes();
909         num_cpus  = num_online_cpus();
910         pr_info("Brought up %d node%s, %d CPU%s\n",
911                 num_nodes, (num_nodes > 1 ? "s" : ""),
912                 num_cpus,  (num_cpus  > 1 ? "s" : ""));
913
914         /* Any cleanup work */
915         smp_cpus_done(setup_max_cpus);
916 }
917
918 /*
919  * on_each_cpu_cond(): Call a function on each processor for which
920  * the supplied function cond_func returns true, optionally waiting
921  * for all the required CPUs to finish. This may include the local
922  * processor.
923  * @cond_func:  A callback function that is passed a cpu id and
924  *              the info parameter. The function is called
925  *              with preemption disabled. The function should
926  *              return a blooean value indicating whether to IPI
927  *              the specified CPU.
928  * @func:       The function to run on all applicable CPUs.
929  *              This must be fast and non-blocking.
930  * @info:       An arbitrary pointer to pass to both functions.
931  * @wait:       If true, wait (atomically) until function has
932  *              completed on other CPUs.
933  *
934  * Preemption is disabled to protect against CPUs going offline but not online.
935  * CPUs going online during the call will not be seen or sent an IPI.
936  *
937  * You must not call this function with disabled interrupts or
938  * from a hardware interrupt handler or from a bottom half handler.
939  */
940 void on_each_cpu_cond_mask(smp_cond_func_t cond_func, smp_call_func_t func,
941                            void *info, bool wait, const struct cpumask *mask)
942 {
943         unsigned int scf_flags = SCF_RUN_LOCAL;
944
945         if (wait)
946                 scf_flags |= SCF_WAIT;
947
948         preempt_disable();
949         smp_call_function_many_cond(mask, func, info, scf_flags, cond_func);
950         preempt_enable();
951 }
952 EXPORT_SYMBOL(on_each_cpu_cond_mask);
953
954 static void do_nothing(void *unused)
955 {
956 }
957
958 /**
959  * kick_all_cpus_sync - Force all cpus out of idle
960  *
961  * Used to synchronize the update of pm_idle function pointer. It's
962  * called after the pointer is updated and returns after the dummy
963  * callback function has been executed on all cpus. The execution of
964  * the function can only happen on the remote cpus after they have
965  * left the idle function which had been called via pm_idle function
966  * pointer. So it's guaranteed that nothing uses the previous pointer
967  * anymore.
968  */
969 void kick_all_cpus_sync(void)
970 {
971         /* Make sure the change is visible before we kick the cpus */
972         smp_mb();
973         smp_call_function(do_nothing, NULL, 1);
974 }
975 EXPORT_SYMBOL_GPL(kick_all_cpus_sync);
976
977 /**
978  * wake_up_all_idle_cpus - break all cpus out of idle
979  * wake_up_all_idle_cpus try to break all cpus which is in idle state even
980  * including idle polling cpus, for non-idle cpus, we will do nothing
981  * for them.
982  */
983 void wake_up_all_idle_cpus(void)
984 {
985         int cpu;
986
987         for_each_possible_cpu(cpu) {
988                 preempt_disable();
989                 if (cpu != smp_processor_id() && cpu_online(cpu))
990                         wake_up_if_idle(cpu);
991                 preempt_enable();
992         }
993 }
994 EXPORT_SYMBOL_GPL(wake_up_all_idle_cpus);
995
996 /**
997  * struct smp_call_on_cpu_struct - Call a function on a specific CPU
998  * @work: &work_struct
999  * @done: &completion to signal
1000  * @func: function to call
1001  * @data: function's data argument
1002  * @ret: return value from @func
1003  * @cpu: target CPU (%-1 for any CPU)
1004  *
1005  * Used to call a function on a specific cpu and wait for it to return.
1006  * Optionally make sure the call is done on a specified physical cpu via vcpu
1007  * pinning in order to support virtualized environments.
1008  */
1009 struct smp_call_on_cpu_struct {
1010         struct work_struct      work;
1011         struct completion       done;
1012         int                     (*func)(void *);
1013         void                    *data;
1014         int                     ret;
1015         int                     cpu;
1016 };
1017
1018 static void smp_call_on_cpu_callback(struct work_struct *work)
1019 {
1020         struct smp_call_on_cpu_struct *sscs;
1021
1022         sscs = container_of(work, struct smp_call_on_cpu_struct, work);
1023         if (sscs->cpu >= 0)
1024                 hypervisor_pin_vcpu(sscs->cpu);
1025         sscs->ret = sscs->func(sscs->data);
1026         if (sscs->cpu >= 0)
1027                 hypervisor_pin_vcpu(-1);
1028
1029         complete(&sscs->done);
1030 }
1031
1032 int smp_call_on_cpu(unsigned int cpu, int (*func)(void *), void *par, bool phys)
1033 {
1034         struct smp_call_on_cpu_struct sscs = {
1035                 .done = COMPLETION_INITIALIZER_ONSTACK(sscs.done),
1036                 .func = func,
1037                 .data = par,
1038                 .cpu  = phys ? cpu : -1,
1039         };
1040
1041         INIT_WORK_ONSTACK(&sscs.work, smp_call_on_cpu_callback);
1042
1043         if (cpu >= nr_cpu_ids || !cpu_online(cpu))
1044                 return -ENXIO;
1045
1046         queue_work_on(cpu, system_wq, &sscs.work);
1047         wait_for_completion(&sscs.done);
1048
1049         return sscs.ret;
1050 }
1051 EXPORT_SYMBOL_GPL(smp_call_on_cpu);