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