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