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