]> Git Repo - linux.git/blob - kernel/cpu.c
sched/topology: fix the issue groups don't span domain->span for NUMA diameter > 2
[linux.git] / kernel / cpu.c
1 /* CPU control.
2  * (C) 2001, 2002, 2003, 2004 Rusty Russell
3  *
4  * This code is licenced under the GPL.
5  */
6 #include <linux/sched/mm.h>
7 #include <linux/proc_fs.h>
8 #include <linux/smp.h>
9 #include <linux/init.h>
10 #include <linux/notifier.h>
11 #include <linux/sched/signal.h>
12 #include <linux/sched/hotplug.h>
13 #include <linux/sched/isolation.h>
14 #include <linux/sched/task.h>
15 #include <linux/sched/smt.h>
16 #include <linux/unistd.h>
17 #include <linux/cpu.h>
18 #include <linux/oom.h>
19 #include <linux/rcupdate.h>
20 #include <linux/export.h>
21 #include <linux/bug.h>
22 #include <linux/kthread.h>
23 #include <linux/stop_machine.h>
24 #include <linux/mutex.h>
25 #include <linux/gfp.h>
26 #include <linux/suspend.h>
27 #include <linux/lockdep.h>
28 #include <linux/tick.h>
29 #include <linux/irq.h>
30 #include <linux/nmi.h>
31 #include <linux/smpboot.h>
32 #include <linux/relay.h>
33 #include <linux/slab.h>
34 #include <linux/percpu-rwsem.h>
35
36 #include <trace/events/power.h>
37 #define CREATE_TRACE_POINTS
38 #include <trace/events/cpuhp.h>
39
40 #include "smpboot.h"
41
42 /**
43  * cpuhp_cpu_state - Per cpu hotplug state storage
44  * @state:      The current cpu state
45  * @target:     The target state
46  * @thread:     Pointer to the hotplug thread
47  * @should_run: Thread should execute
48  * @rollback:   Perform a rollback
49  * @single:     Single callback invocation
50  * @bringup:    Single callback bringup or teardown selector
51  * @cb_state:   The state for a single callback (install/uninstall)
52  * @result:     Result of the operation
53  * @done_up:    Signal completion to the issuer of the task for cpu-up
54  * @done_down:  Signal completion to the issuer of the task for cpu-down
55  */
56 struct cpuhp_cpu_state {
57         enum cpuhp_state        state;
58         enum cpuhp_state        target;
59         enum cpuhp_state        fail;
60 #ifdef CONFIG_SMP
61         struct task_struct      *thread;
62         bool                    should_run;
63         bool                    rollback;
64         bool                    single;
65         bool                    bringup;
66         struct hlist_node       *node;
67         struct hlist_node       *last;
68         enum cpuhp_state        cb_state;
69         int                     result;
70         struct completion       done_up;
71         struct completion       done_down;
72 #endif
73 };
74
75 static DEFINE_PER_CPU(struct cpuhp_cpu_state, cpuhp_state) = {
76         .fail = CPUHP_INVALID,
77 };
78
79 #ifdef CONFIG_SMP
80 cpumask_t cpus_booted_once_mask;
81 #endif
82
83 #if defined(CONFIG_LOCKDEP) && defined(CONFIG_SMP)
84 static struct lockdep_map cpuhp_state_up_map =
85         STATIC_LOCKDEP_MAP_INIT("cpuhp_state-up", &cpuhp_state_up_map);
86 static struct lockdep_map cpuhp_state_down_map =
87         STATIC_LOCKDEP_MAP_INIT("cpuhp_state-down", &cpuhp_state_down_map);
88
89
90 static inline void cpuhp_lock_acquire(bool bringup)
91 {
92         lock_map_acquire(bringup ? &cpuhp_state_up_map : &cpuhp_state_down_map);
93 }
94
95 static inline void cpuhp_lock_release(bool bringup)
96 {
97         lock_map_release(bringup ? &cpuhp_state_up_map : &cpuhp_state_down_map);
98 }
99 #else
100
101 static inline void cpuhp_lock_acquire(bool bringup) { }
102 static inline void cpuhp_lock_release(bool bringup) { }
103
104 #endif
105
106 /**
107  * cpuhp_step - Hotplug state machine step
108  * @name:       Name of the step
109  * @startup:    Startup function of the step
110  * @teardown:   Teardown function of the step
111  * @cant_stop:  Bringup/teardown can't be stopped at this step
112  */
113 struct cpuhp_step {
114         const char              *name;
115         union {
116                 int             (*single)(unsigned int cpu);
117                 int             (*multi)(unsigned int cpu,
118                                          struct hlist_node *node);
119         } startup;
120         union {
121                 int             (*single)(unsigned int cpu);
122                 int             (*multi)(unsigned int cpu,
123                                          struct hlist_node *node);
124         } teardown;
125         struct hlist_head       list;
126         bool                    cant_stop;
127         bool                    multi_instance;
128 };
129
130 static DEFINE_MUTEX(cpuhp_state_mutex);
131 static struct cpuhp_step cpuhp_hp_states[];
132
133 static struct cpuhp_step *cpuhp_get_step(enum cpuhp_state state)
134 {
135         return cpuhp_hp_states + state;
136 }
137
138 static bool cpuhp_step_empty(bool bringup, struct cpuhp_step *step)
139 {
140         return bringup ? !step->startup.single : !step->teardown.single;
141 }
142
143 /**
144  * cpuhp_invoke_callback _ Invoke the callbacks for a given state
145  * @cpu:        The cpu for which the callback should be invoked
146  * @state:      The state to do callbacks for
147  * @bringup:    True if the bringup callback should be invoked
148  * @node:       For multi-instance, do a single entry callback for install/remove
149  * @lastp:      For multi-instance rollback, remember how far we got
150  *
151  * Called from cpu hotplug and from the state register machinery.
152  */
153 static int cpuhp_invoke_callback(unsigned int cpu, enum cpuhp_state state,
154                                  bool bringup, struct hlist_node *node,
155                                  struct hlist_node **lastp)
156 {
157         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
158         struct cpuhp_step *step = cpuhp_get_step(state);
159         int (*cbm)(unsigned int cpu, struct hlist_node *node);
160         int (*cb)(unsigned int cpu);
161         int ret, cnt;
162
163         if (st->fail == state) {
164                 st->fail = CPUHP_INVALID;
165                 return -EAGAIN;
166         }
167
168         if (cpuhp_step_empty(bringup, step)) {
169                 WARN_ON_ONCE(1);
170                 return 0;
171         }
172
173         if (!step->multi_instance) {
174                 WARN_ON_ONCE(lastp && *lastp);
175                 cb = bringup ? step->startup.single : step->teardown.single;
176
177                 trace_cpuhp_enter(cpu, st->target, state, cb);
178                 ret = cb(cpu);
179                 trace_cpuhp_exit(cpu, st->state, state, ret);
180                 return ret;
181         }
182         cbm = bringup ? step->startup.multi : step->teardown.multi;
183
184         /* Single invocation for instance add/remove */
185         if (node) {
186                 WARN_ON_ONCE(lastp && *lastp);
187                 trace_cpuhp_multi_enter(cpu, st->target, state, cbm, node);
188                 ret = cbm(cpu, node);
189                 trace_cpuhp_exit(cpu, st->state, state, ret);
190                 return ret;
191         }
192
193         /* State transition. Invoke on all instances */
194         cnt = 0;
195         hlist_for_each(node, &step->list) {
196                 if (lastp && node == *lastp)
197                         break;
198
199                 trace_cpuhp_multi_enter(cpu, st->target, state, cbm, node);
200                 ret = cbm(cpu, node);
201                 trace_cpuhp_exit(cpu, st->state, state, ret);
202                 if (ret) {
203                         if (!lastp)
204                                 goto err;
205
206                         *lastp = node;
207                         return ret;
208                 }
209                 cnt++;
210         }
211         if (lastp)
212                 *lastp = NULL;
213         return 0;
214 err:
215         /* Rollback the instances if one failed */
216         cbm = !bringup ? step->startup.multi : step->teardown.multi;
217         if (!cbm)
218                 return ret;
219
220         hlist_for_each(node, &step->list) {
221                 if (!cnt--)
222                         break;
223
224                 trace_cpuhp_multi_enter(cpu, st->target, state, cbm, node);
225                 ret = cbm(cpu, node);
226                 trace_cpuhp_exit(cpu, st->state, state, ret);
227                 /*
228                  * Rollback must not fail,
229                  */
230                 WARN_ON_ONCE(ret);
231         }
232         return ret;
233 }
234
235 #ifdef CONFIG_SMP
236 static bool cpuhp_is_ap_state(enum cpuhp_state state)
237 {
238         /*
239          * The extra check for CPUHP_TEARDOWN_CPU is only for documentation
240          * purposes as that state is handled explicitly in cpu_down.
241          */
242         return state > CPUHP_BRINGUP_CPU && state != CPUHP_TEARDOWN_CPU;
243 }
244
245 static inline void wait_for_ap_thread(struct cpuhp_cpu_state *st, bool bringup)
246 {
247         struct completion *done = bringup ? &st->done_up : &st->done_down;
248         wait_for_completion(done);
249 }
250
251 static inline void complete_ap_thread(struct cpuhp_cpu_state *st, bool bringup)
252 {
253         struct completion *done = bringup ? &st->done_up : &st->done_down;
254         complete(done);
255 }
256
257 /*
258  * The former STARTING/DYING states, ran with IRQs disabled and must not fail.
259  */
260 static bool cpuhp_is_atomic_state(enum cpuhp_state state)
261 {
262         return CPUHP_AP_IDLE_DEAD <= state && state < CPUHP_AP_ONLINE;
263 }
264
265 /* Serializes the updates to cpu_online_mask, cpu_present_mask */
266 static DEFINE_MUTEX(cpu_add_remove_lock);
267 bool cpuhp_tasks_frozen;
268 EXPORT_SYMBOL_GPL(cpuhp_tasks_frozen);
269
270 /*
271  * The following two APIs (cpu_maps_update_begin/done) must be used when
272  * attempting to serialize the updates to cpu_online_mask & cpu_present_mask.
273  */
274 void cpu_maps_update_begin(void)
275 {
276         mutex_lock(&cpu_add_remove_lock);
277 }
278
279 void cpu_maps_update_done(void)
280 {
281         mutex_unlock(&cpu_add_remove_lock);
282 }
283
284 /*
285  * If set, cpu_up and cpu_down will return -EBUSY and do nothing.
286  * Should always be manipulated under cpu_add_remove_lock
287  */
288 static int cpu_hotplug_disabled;
289
290 #ifdef CONFIG_HOTPLUG_CPU
291
292 DEFINE_STATIC_PERCPU_RWSEM(cpu_hotplug_lock);
293
294 void cpus_read_lock(void)
295 {
296         percpu_down_read(&cpu_hotplug_lock);
297 }
298 EXPORT_SYMBOL_GPL(cpus_read_lock);
299
300 int cpus_read_trylock(void)
301 {
302         return percpu_down_read_trylock(&cpu_hotplug_lock);
303 }
304 EXPORT_SYMBOL_GPL(cpus_read_trylock);
305
306 void cpus_read_unlock(void)
307 {
308         percpu_up_read(&cpu_hotplug_lock);
309 }
310 EXPORT_SYMBOL_GPL(cpus_read_unlock);
311
312 void cpus_write_lock(void)
313 {
314         percpu_down_write(&cpu_hotplug_lock);
315 }
316
317 void cpus_write_unlock(void)
318 {
319         percpu_up_write(&cpu_hotplug_lock);
320 }
321
322 void lockdep_assert_cpus_held(void)
323 {
324         /*
325          * We can't have hotplug operations before userspace starts running,
326          * and some init codepaths will knowingly not take the hotplug lock.
327          * This is all valid, so mute lockdep until it makes sense to report
328          * unheld locks.
329          */
330         if (system_state < SYSTEM_RUNNING)
331                 return;
332
333         percpu_rwsem_assert_held(&cpu_hotplug_lock);
334 }
335
336 #ifdef CONFIG_LOCKDEP
337 int lockdep_is_cpus_held(void)
338 {
339         return percpu_rwsem_is_held(&cpu_hotplug_lock);
340 }
341 #endif
342
343 static void lockdep_acquire_cpus_lock(void)
344 {
345         rwsem_acquire(&cpu_hotplug_lock.dep_map, 0, 0, _THIS_IP_);
346 }
347
348 static void lockdep_release_cpus_lock(void)
349 {
350         rwsem_release(&cpu_hotplug_lock.dep_map, _THIS_IP_);
351 }
352
353 /*
354  * Wait for currently running CPU hotplug operations to complete (if any) and
355  * disable future CPU hotplug (from sysfs). The 'cpu_add_remove_lock' protects
356  * the 'cpu_hotplug_disabled' flag. The same lock is also acquired by the
357  * hotplug path before performing hotplug operations. So acquiring that lock
358  * guarantees mutual exclusion from any currently running hotplug operations.
359  */
360 void cpu_hotplug_disable(void)
361 {
362         cpu_maps_update_begin();
363         cpu_hotplug_disabled++;
364         cpu_maps_update_done();
365 }
366 EXPORT_SYMBOL_GPL(cpu_hotplug_disable);
367
368 static void __cpu_hotplug_enable(void)
369 {
370         if (WARN_ONCE(!cpu_hotplug_disabled, "Unbalanced cpu hotplug enable\n"))
371                 return;
372         cpu_hotplug_disabled--;
373 }
374
375 void cpu_hotplug_enable(void)
376 {
377         cpu_maps_update_begin();
378         __cpu_hotplug_enable();
379         cpu_maps_update_done();
380 }
381 EXPORT_SYMBOL_GPL(cpu_hotplug_enable);
382
383 #else
384
385 static void lockdep_acquire_cpus_lock(void)
386 {
387 }
388
389 static void lockdep_release_cpus_lock(void)
390 {
391 }
392
393 #endif  /* CONFIG_HOTPLUG_CPU */
394
395 /*
396  * Architectures that need SMT-specific errata handling during SMT hotplug
397  * should override this.
398  */
399 void __weak arch_smt_update(void) { }
400
401 #ifdef CONFIG_HOTPLUG_SMT
402 enum cpuhp_smt_control cpu_smt_control __read_mostly = CPU_SMT_ENABLED;
403
404 void __init cpu_smt_disable(bool force)
405 {
406         if (!cpu_smt_possible())
407                 return;
408
409         if (force) {
410                 pr_info("SMT: Force disabled\n");
411                 cpu_smt_control = CPU_SMT_FORCE_DISABLED;
412         } else {
413                 pr_info("SMT: disabled\n");
414                 cpu_smt_control = CPU_SMT_DISABLED;
415         }
416 }
417
418 /*
419  * The decision whether SMT is supported can only be done after the full
420  * CPU identification. Called from architecture code.
421  */
422 void __init cpu_smt_check_topology(void)
423 {
424         if (!topology_smt_supported())
425                 cpu_smt_control = CPU_SMT_NOT_SUPPORTED;
426 }
427
428 static int __init smt_cmdline_disable(char *str)
429 {
430         cpu_smt_disable(str && !strcmp(str, "force"));
431         return 0;
432 }
433 early_param("nosmt", smt_cmdline_disable);
434
435 static inline bool cpu_smt_allowed(unsigned int cpu)
436 {
437         if (cpu_smt_control == CPU_SMT_ENABLED)
438                 return true;
439
440         if (topology_is_primary_thread(cpu))
441                 return true;
442
443         /*
444          * On x86 it's required to boot all logical CPUs at least once so
445          * that the init code can get a chance to set CR4.MCE on each
446          * CPU. Otherwise, a broadcasted MCE observing CR4.MCE=0b on any
447          * core will shutdown the machine.
448          */
449         return !cpumask_test_cpu(cpu, &cpus_booted_once_mask);
450 }
451
452 /* Returns true if SMT is not supported of forcefully (irreversibly) disabled */
453 bool cpu_smt_possible(void)
454 {
455         return cpu_smt_control != CPU_SMT_FORCE_DISABLED &&
456                 cpu_smt_control != CPU_SMT_NOT_SUPPORTED;
457 }
458 EXPORT_SYMBOL_GPL(cpu_smt_possible);
459 #else
460 static inline bool cpu_smt_allowed(unsigned int cpu) { return true; }
461 #endif
462
463 static inline enum cpuhp_state
464 cpuhp_set_state(struct cpuhp_cpu_state *st, enum cpuhp_state target)
465 {
466         enum cpuhp_state prev_state = st->state;
467
468         st->rollback = false;
469         st->last = NULL;
470
471         st->target = target;
472         st->single = false;
473         st->bringup = st->state < target;
474
475         return prev_state;
476 }
477
478 static inline void
479 cpuhp_reset_state(struct cpuhp_cpu_state *st, enum cpuhp_state prev_state)
480 {
481         st->target = prev_state;
482
483         /*
484          * Already rolling back. No need invert the bringup value or to change
485          * the current state.
486          */
487         if (st->rollback)
488                 return;
489
490         st->rollback = true;
491
492         /*
493          * If we have st->last we need to undo partial multi_instance of this
494          * state first. Otherwise start undo at the previous state.
495          */
496         if (!st->last) {
497                 if (st->bringup)
498                         st->state--;
499                 else
500                         st->state++;
501         }
502
503         st->bringup = !st->bringup;
504 }
505
506 /* Regular hotplug invocation of the AP hotplug thread */
507 static void __cpuhp_kick_ap(struct cpuhp_cpu_state *st)
508 {
509         if (!st->single && st->state == st->target)
510                 return;
511
512         st->result = 0;
513         /*
514          * Make sure the above stores are visible before should_run becomes
515          * true. Paired with the mb() above in cpuhp_thread_fun()
516          */
517         smp_mb();
518         st->should_run = true;
519         wake_up_process(st->thread);
520         wait_for_ap_thread(st, st->bringup);
521 }
522
523 static int cpuhp_kick_ap(struct cpuhp_cpu_state *st, enum cpuhp_state target)
524 {
525         enum cpuhp_state prev_state;
526         int ret;
527
528         prev_state = cpuhp_set_state(st, target);
529         __cpuhp_kick_ap(st);
530         if ((ret = st->result)) {
531                 cpuhp_reset_state(st, prev_state);
532                 __cpuhp_kick_ap(st);
533         }
534
535         return ret;
536 }
537
538 static int bringup_wait_for_ap(unsigned int cpu)
539 {
540         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
541
542         /* Wait for the CPU to reach CPUHP_AP_ONLINE_IDLE */
543         wait_for_ap_thread(st, true);
544         if (WARN_ON_ONCE((!cpu_online(cpu))))
545                 return -ECANCELED;
546
547         /* Unpark the hotplug thread of the target cpu */
548         kthread_unpark(st->thread);
549
550         /*
551          * SMT soft disabling on X86 requires to bring the CPU out of the
552          * BIOS 'wait for SIPI' state in order to set the CR4.MCE bit.  The
553          * CPU marked itself as booted_once in notify_cpu_starting() so the
554          * cpu_smt_allowed() check will now return false if this is not the
555          * primary sibling.
556          */
557         if (!cpu_smt_allowed(cpu))
558                 return -ECANCELED;
559
560         if (st->target <= CPUHP_AP_ONLINE_IDLE)
561                 return 0;
562
563         return cpuhp_kick_ap(st, st->target);
564 }
565
566 static int bringup_cpu(unsigned int cpu)
567 {
568         struct task_struct *idle = idle_thread_get(cpu);
569         int ret;
570
571         /*
572          * Some architectures have to walk the irq descriptors to
573          * setup the vector space for the cpu which comes online.
574          * Prevent irq alloc/free across the bringup.
575          */
576         irq_lock_sparse();
577
578         /* Arch-specific enabling code. */
579         ret = __cpu_up(cpu, idle);
580         irq_unlock_sparse();
581         if (ret)
582                 return ret;
583         return bringup_wait_for_ap(cpu);
584 }
585
586 static int finish_cpu(unsigned int cpu)
587 {
588         struct task_struct *idle = idle_thread_get(cpu);
589         struct mm_struct *mm = idle->active_mm;
590
591         /*
592          * idle_task_exit() will have switched to &init_mm, now
593          * clean up any remaining active_mm state.
594          */
595         if (mm != &init_mm)
596                 idle->active_mm = &init_mm;
597         mmdrop(mm);
598         return 0;
599 }
600
601 /*
602  * Hotplug state machine related functions
603  */
604
605 /*
606  * Get the next state to run. Empty ones will be skipped. Returns true if a
607  * state must be run.
608  *
609  * st->state will be modified ahead of time, to match state_to_run, as if it
610  * has already ran.
611  */
612 static bool cpuhp_next_state(bool bringup,
613                              enum cpuhp_state *state_to_run,
614                              struct cpuhp_cpu_state *st,
615                              enum cpuhp_state target)
616 {
617         do {
618                 if (bringup) {
619                         if (st->state >= target)
620                                 return false;
621
622                         *state_to_run = ++st->state;
623                 } else {
624                         if (st->state <= target)
625                                 return false;
626
627                         *state_to_run = st->state--;
628                 }
629
630                 if (!cpuhp_step_empty(bringup, cpuhp_get_step(*state_to_run)))
631                         break;
632         } while (true);
633
634         return true;
635 }
636
637 static int cpuhp_invoke_callback_range(bool bringup,
638                                        unsigned int cpu,
639                                        struct cpuhp_cpu_state *st,
640                                        enum cpuhp_state target)
641 {
642         enum cpuhp_state state;
643         int err = 0;
644
645         while (cpuhp_next_state(bringup, &state, st, target)) {
646                 err = cpuhp_invoke_callback(cpu, state, bringup, NULL, NULL);
647                 if (err)
648                         break;
649         }
650
651         return err;
652 }
653
654 static inline bool can_rollback_cpu(struct cpuhp_cpu_state *st)
655 {
656         if (IS_ENABLED(CONFIG_HOTPLUG_CPU))
657                 return true;
658         /*
659          * When CPU hotplug is disabled, then taking the CPU down is not
660          * possible because takedown_cpu() and the architecture and
661          * subsystem specific mechanisms are not available. So the CPU
662          * which would be completely unplugged again needs to stay around
663          * in the current state.
664          */
665         return st->state <= CPUHP_BRINGUP_CPU;
666 }
667
668 static int cpuhp_up_callbacks(unsigned int cpu, struct cpuhp_cpu_state *st,
669                               enum cpuhp_state target)
670 {
671         enum cpuhp_state prev_state = st->state;
672         int ret = 0;
673
674         ret = cpuhp_invoke_callback_range(true, cpu, st, target);
675         if (ret) {
676                 cpuhp_reset_state(st, prev_state);
677                 if (can_rollback_cpu(st))
678                         WARN_ON(cpuhp_invoke_callback_range(false, cpu, st,
679                                                             prev_state));
680         }
681         return ret;
682 }
683
684 /*
685  * The cpu hotplug threads manage the bringup and teardown of the cpus
686  */
687 static void cpuhp_create(unsigned int cpu)
688 {
689         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
690
691         init_completion(&st->done_up);
692         init_completion(&st->done_down);
693 }
694
695 static int cpuhp_should_run(unsigned int cpu)
696 {
697         struct cpuhp_cpu_state *st = this_cpu_ptr(&cpuhp_state);
698
699         return st->should_run;
700 }
701
702 /*
703  * Execute teardown/startup callbacks on the plugged cpu. Also used to invoke
704  * callbacks when a state gets [un]installed at runtime.
705  *
706  * Each invocation of this function by the smpboot thread does a single AP
707  * state callback.
708  *
709  * It has 3 modes of operation:
710  *  - single: runs st->cb_state
711  *  - up:     runs ++st->state, while st->state < st->target
712  *  - down:   runs st->state--, while st->state > st->target
713  *
714  * When complete or on error, should_run is cleared and the completion is fired.
715  */
716 static void cpuhp_thread_fun(unsigned int cpu)
717 {
718         struct cpuhp_cpu_state *st = this_cpu_ptr(&cpuhp_state);
719         bool bringup = st->bringup;
720         enum cpuhp_state state;
721
722         if (WARN_ON_ONCE(!st->should_run))
723                 return;
724
725         /*
726          * ACQUIRE for the cpuhp_should_run() load of ->should_run. Ensures
727          * that if we see ->should_run we also see the rest of the state.
728          */
729         smp_mb();
730
731         /*
732          * The BP holds the hotplug lock, but we're now running on the AP,
733          * ensure that anybody asserting the lock is held, will actually find
734          * it so.
735          */
736         lockdep_acquire_cpus_lock();
737         cpuhp_lock_acquire(bringup);
738
739         if (st->single) {
740                 state = st->cb_state;
741                 st->should_run = false;
742         } else {
743                 st->should_run = cpuhp_next_state(bringup, &state, st, st->target);
744                 if (!st->should_run)
745                         goto end;
746         }
747
748         WARN_ON_ONCE(!cpuhp_is_ap_state(state));
749
750         if (cpuhp_is_atomic_state(state)) {
751                 local_irq_disable();
752                 st->result = cpuhp_invoke_callback(cpu, state, bringup, st->node, &st->last);
753                 local_irq_enable();
754
755                 /*
756                  * STARTING/DYING must not fail!
757                  */
758                 WARN_ON_ONCE(st->result);
759         } else {
760                 st->result = cpuhp_invoke_callback(cpu, state, bringup, st->node, &st->last);
761         }
762
763         if (st->result) {
764                 /*
765                  * If we fail on a rollback, we're up a creek without no
766                  * paddle, no way forward, no way back. We loose, thanks for
767                  * playing.
768                  */
769                 WARN_ON_ONCE(st->rollback);
770                 st->should_run = false;
771         }
772
773 end:
774         cpuhp_lock_release(bringup);
775         lockdep_release_cpus_lock();
776
777         if (!st->should_run)
778                 complete_ap_thread(st, bringup);
779 }
780
781 /* Invoke a single callback on a remote cpu */
782 static int
783 cpuhp_invoke_ap_callback(int cpu, enum cpuhp_state state, bool bringup,
784                          struct hlist_node *node)
785 {
786         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
787         int ret;
788
789         if (!cpu_online(cpu))
790                 return 0;
791
792         cpuhp_lock_acquire(false);
793         cpuhp_lock_release(false);
794
795         cpuhp_lock_acquire(true);
796         cpuhp_lock_release(true);
797
798         /*
799          * If we are up and running, use the hotplug thread. For early calls
800          * we invoke the thread function directly.
801          */
802         if (!st->thread)
803                 return cpuhp_invoke_callback(cpu, state, bringup, node, NULL);
804
805         st->rollback = false;
806         st->last = NULL;
807
808         st->node = node;
809         st->bringup = bringup;
810         st->cb_state = state;
811         st->single = true;
812
813         __cpuhp_kick_ap(st);
814
815         /*
816          * If we failed and did a partial, do a rollback.
817          */
818         if ((ret = st->result) && st->last) {
819                 st->rollback = true;
820                 st->bringup = !bringup;
821
822                 __cpuhp_kick_ap(st);
823         }
824
825         /*
826          * Clean up the leftovers so the next hotplug operation wont use stale
827          * data.
828          */
829         st->node = st->last = NULL;
830         return ret;
831 }
832
833 static int cpuhp_kick_ap_work(unsigned int cpu)
834 {
835         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
836         enum cpuhp_state prev_state = st->state;
837         int ret;
838
839         cpuhp_lock_acquire(false);
840         cpuhp_lock_release(false);
841
842         cpuhp_lock_acquire(true);
843         cpuhp_lock_release(true);
844
845         trace_cpuhp_enter(cpu, st->target, prev_state, cpuhp_kick_ap_work);
846         ret = cpuhp_kick_ap(st, st->target);
847         trace_cpuhp_exit(cpu, st->state, prev_state, ret);
848
849         return ret;
850 }
851
852 static struct smp_hotplug_thread cpuhp_threads = {
853         .store                  = &cpuhp_state.thread,
854         .create                 = &cpuhp_create,
855         .thread_should_run      = cpuhp_should_run,
856         .thread_fn              = cpuhp_thread_fun,
857         .thread_comm            = "cpuhp/%u",
858         .selfparking            = true,
859 };
860
861 void __init cpuhp_threads_init(void)
862 {
863         BUG_ON(smpboot_register_percpu_thread(&cpuhp_threads));
864         kthread_unpark(this_cpu_read(cpuhp_state.thread));
865 }
866
867 #ifdef CONFIG_HOTPLUG_CPU
868 #ifndef arch_clear_mm_cpumask_cpu
869 #define arch_clear_mm_cpumask_cpu(cpu, mm) cpumask_clear_cpu(cpu, mm_cpumask(mm))
870 #endif
871
872 /**
873  * clear_tasks_mm_cpumask - Safely clear tasks' mm_cpumask for a CPU
874  * @cpu: a CPU id
875  *
876  * This function walks all processes, finds a valid mm struct for each one and
877  * then clears a corresponding bit in mm's cpumask.  While this all sounds
878  * trivial, there are various non-obvious corner cases, which this function
879  * tries to solve in a safe manner.
880  *
881  * Also note that the function uses a somewhat relaxed locking scheme, so it may
882  * be called only for an already offlined CPU.
883  */
884 void clear_tasks_mm_cpumask(int cpu)
885 {
886         struct task_struct *p;
887
888         /*
889          * This function is called after the cpu is taken down and marked
890          * offline, so its not like new tasks will ever get this cpu set in
891          * their mm mask. -- Peter Zijlstra
892          * Thus, we may use rcu_read_lock() here, instead of grabbing
893          * full-fledged tasklist_lock.
894          */
895         WARN_ON(cpu_online(cpu));
896         rcu_read_lock();
897         for_each_process(p) {
898                 struct task_struct *t;
899
900                 /*
901                  * Main thread might exit, but other threads may still have
902                  * a valid mm. Find one.
903                  */
904                 t = find_lock_task_mm(p);
905                 if (!t)
906                         continue;
907                 arch_clear_mm_cpumask_cpu(cpu, t->mm);
908                 task_unlock(t);
909         }
910         rcu_read_unlock();
911 }
912
913 /* Take this CPU down. */
914 static int take_cpu_down(void *_param)
915 {
916         struct cpuhp_cpu_state *st = this_cpu_ptr(&cpuhp_state);
917         enum cpuhp_state target = max((int)st->target, CPUHP_AP_OFFLINE);
918         int err, cpu = smp_processor_id();
919         int ret;
920
921         /* Ensure this CPU doesn't handle any more interrupts. */
922         err = __cpu_disable();
923         if (err < 0)
924                 return err;
925
926         /*
927          * Must be called from CPUHP_TEARDOWN_CPU, which means, as we are going
928          * down, that the current state is CPUHP_TEARDOWN_CPU - 1.
929          */
930         WARN_ON(st->state != (CPUHP_TEARDOWN_CPU - 1));
931
932         /* Invoke the former CPU_DYING callbacks */
933         ret = cpuhp_invoke_callback_range(false, cpu, st, target);
934
935         /*
936          * DYING must not fail!
937          */
938         WARN_ON_ONCE(ret);
939
940         /* Give up timekeeping duties */
941         tick_handover_do_timer();
942         /* Remove CPU from timer broadcasting */
943         tick_offline_cpu(cpu);
944         /* Park the stopper thread */
945         stop_machine_park(cpu);
946         return 0;
947 }
948
949 static int takedown_cpu(unsigned int cpu)
950 {
951         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
952         int err;
953
954         /* Park the smpboot threads */
955         kthread_park(per_cpu_ptr(&cpuhp_state, cpu)->thread);
956
957         /*
958          * Prevent irq alloc/free while the dying cpu reorganizes the
959          * interrupt affinities.
960          */
961         irq_lock_sparse();
962
963         /*
964          * So now all preempt/rcu users must observe !cpu_active().
965          */
966         err = stop_machine_cpuslocked(take_cpu_down, NULL, cpumask_of(cpu));
967         if (err) {
968                 /* CPU refused to die */
969                 irq_unlock_sparse();
970                 /* Unpark the hotplug thread so we can rollback there */
971                 kthread_unpark(per_cpu_ptr(&cpuhp_state, cpu)->thread);
972                 return err;
973         }
974         BUG_ON(cpu_online(cpu));
975
976         /*
977          * The teardown callback for CPUHP_AP_SCHED_STARTING will have removed
978          * all runnable tasks from the CPU, there's only the idle task left now
979          * that the migration thread is done doing the stop_machine thing.
980          *
981          * Wait for the stop thread to go away.
982          */
983         wait_for_ap_thread(st, false);
984         BUG_ON(st->state != CPUHP_AP_IDLE_DEAD);
985
986         /* Interrupts are moved away from the dying cpu, reenable alloc/free */
987         irq_unlock_sparse();
988
989         hotplug_cpu__broadcast_tick_pull(cpu);
990         /* This actually kills the CPU. */
991         __cpu_die(cpu);
992
993         tick_cleanup_dead_cpu(cpu);
994         rcutree_migrate_callbacks(cpu);
995         return 0;
996 }
997
998 static void cpuhp_complete_idle_dead(void *arg)
999 {
1000         struct cpuhp_cpu_state *st = arg;
1001
1002         complete_ap_thread(st, false);
1003 }
1004
1005 void cpuhp_report_idle_dead(void)
1006 {
1007         struct cpuhp_cpu_state *st = this_cpu_ptr(&cpuhp_state);
1008
1009         BUG_ON(st->state != CPUHP_AP_OFFLINE);
1010         rcu_report_dead(smp_processor_id());
1011         st->state = CPUHP_AP_IDLE_DEAD;
1012         /*
1013          * We cannot call complete after rcu_report_dead() so we delegate it
1014          * to an online cpu.
1015          */
1016         smp_call_function_single(cpumask_first(cpu_online_mask),
1017                                  cpuhp_complete_idle_dead, st, 0);
1018 }
1019
1020 static int cpuhp_down_callbacks(unsigned int cpu, struct cpuhp_cpu_state *st,
1021                                 enum cpuhp_state target)
1022 {
1023         enum cpuhp_state prev_state = st->state;
1024         int ret = 0;
1025
1026         ret = cpuhp_invoke_callback_range(false, cpu, st, target);
1027         if (ret) {
1028
1029                 cpuhp_reset_state(st, prev_state);
1030
1031                 if (st->state < prev_state)
1032                         WARN_ON(cpuhp_invoke_callback_range(true, cpu, st,
1033                                                             prev_state));
1034         }
1035
1036         return ret;
1037 }
1038
1039 /* Requires cpu_add_remove_lock to be held */
1040 static int __ref _cpu_down(unsigned int cpu, int tasks_frozen,
1041                            enum cpuhp_state target)
1042 {
1043         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1044         int prev_state, ret = 0;
1045
1046         if (num_online_cpus() == 1)
1047                 return -EBUSY;
1048
1049         if (!cpu_present(cpu))
1050                 return -EINVAL;
1051
1052         cpus_write_lock();
1053
1054         cpuhp_tasks_frozen = tasks_frozen;
1055
1056         prev_state = cpuhp_set_state(st, target);
1057         /*
1058          * If the current CPU state is in the range of the AP hotplug thread,
1059          * then we need to kick the thread.
1060          */
1061         if (st->state > CPUHP_TEARDOWN_CPU) {
1062                 st->target = max((int)target, CPUHP_TEARDOWN_CPU);
1063                 ret = cpuhp_kick_ap_work(cpu);
1064                 /*
1065                  * The AP side has done the error rollback already. Just
1066                  * return the error code..
1067                  */
1068                 if (ret)
1069                         goto out;
1070
1071                 /*
1072                  * We might have stopped still in the range of the AP hotplug
1073                  * thread. Nothing to do anymore.
1074                  */
1075                 if (st->state > CPUHP_TEARDOWN_CPU)
1076                         goto out;
1077
1078                 st->target = target;
1079         }
1080         /*
1081          * The AP brought itself down to CPUHP_TEARDOWN_CPU. So we need
1082          * to do the further cleanups.
1083          */
1084         ret = cpuhp_down_callbacks(cpu, st, target);
1085         if (ret && st->state < prev_state) {
1086                 if (st->state == CPUHP_TEARDOWN_CPU) {
1087                         cpuhp_reset_state(st, prev_state);
1088                         __cpuhp_kick_ap(st);
1089                 } else {
1090                         WARN(1, "DEAD callback error for CPU%d", cpu);
1091                 }
1092         }
1093
1094 out:
1095         cpus_write_unlock();
1096         /*
1097          * Do post unplug cleanup. This is still protected against
1098          * concurrent CPU hotplug via cpu_add_remove_lock.
1099          */
1100         lockup_detector_cleanup();
1101         arch_smt_update();
1102         return ret;
1103 }
1104
1105 static int cpu_down_maps_locked(unsigned int cpu, enum cpuhp_state target)
1106 {
1107         if (cpu_hotplug_disabled)
1108                 return -EBUSY;
1109         return _cpu_down(cpu, 0, target);
1110 }
1111
1112 static int cpu_down(unsigned int cpu, enum cpuhp_state target)
1113 {
1114         int err;
1115
1116         cpu_maps_update_begin();
1117         err = cpu_down_maps_locked(cpu, target);
1118         cpu_maps_update_done();
1119         return err;
1120 }
1121
1122 /**
1123  * cpu_device_down - Bring down a cpu device
1124  * @dev: Pointer to the cpu device to offline
1125  *
1126  * This function is meant to be used by device core cpu subsystem only.
1127  *
1128  * Other subsystems should use remove_cpu() instead.
1129  */
1130 int cpu_device_down(struct device *dev)
1131 {
1132         return cpu_down(dev->id, CPUHP_OFFLINE);
1133 }
1134
1135 int remove_cpu(unsigned int cpu)
1136 {
1137         int ret;
1138
1139         lock_device_hotplug();
1140         ret = device_offline(get_cpu_device(cpu));
1141         unlock_device_hotplug();
1142
1143         return ret;
1144 }
1145 EXPORT_SYMBOL_GPL(remove_cpu);
1146
1147 void smp_shutdown_nonboot_cpus(unsigned int primary_cpu)
1148 {
1149         unsigned int cpu;
1150         int error;
1151
1152         cpu_maps_update_begin();
1153
1154         /*
1155          * Make certain the cpu I'm about to reboot on is online.
1156          *
1157          * This is inline to what migrate_to_reboot_cpu() already do.
1158          */
1159         if (!cpu_online(primary_cpu))
1160                 primary_cpu = cpumask_first(cpu_online_mask);
1161
1162         for_each_online_cpu(cpu) {
1163                 if (cpu == primary_cpu)
1164                         continue;
1165
1166                 error = cpu_down_maps_locked(cpu, CPUHP_OFFLINE);
1167                 if (error) {
1168                         pr_err("Failed to offline CPU%d - error=%d",
1169                                 cpu, error);
1170                         break;
1171                 }
1172         }
1173
1174         /*
1175          * Ensure all but the reboot CPU are offline.
1176          */
1177         BUG_ON(num_online_cpus() > 1);
1178
1179         /*
1180          * Make sure the CPUs won't be enabled by someone else after this
1181          * point. Kexec will reboot to a new kernel shortly resetting
1182          * everything along the way.
1183          */
1184         cpu_hotplug_disabled++;
1185
1186         cpu_maps_update_done();
1187 }
1188
1189 #else
1190 #define takedown_cpu            NULL
1191 #endif /*CONFIG_HOTPLUG_CPU*/
1192
1193 /**
1194  * notify_cpu_starting(cpu) - Invoke the callbacks on the starting CPU
1195  * @cpu: cpu that just started
1196  *
1197  * It must be called by the arch code on the new cpu, before the new cpu
1198  * enables interrupts and before the "boot" cpu returns from __cpu_up().
1199  */
1200 void notify_cpu_starting(unsigned int cpu)
1201 {
1202         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1203         enum cpuhp_state target = min((int)st->target, CPUHP_AP_ONLINE);
1204         int ret;
1205
1206         rcu_cpu_starting(cpu);  /* Enables RCU usage on this CPU. */
1207         cpumask_set_cpu(cpu, &cpus_booted_once_mask);
1208         ret = cpuhp_invoke_callback_range(true, cpu, st, target);
1209
1210         /*
1211          * STARTING must not fail!
1212          */
1213         WARN_ON_ONCE(ret);
1214 }
1215
1216 /*
1217  * Called from the idle task. Wake up the controlling task which brings the
1218  * hotplug thread of the upcoming CPU up and then delegates the rest of the
1219  * online bringup to the hotplug thread.
1220  */
1221 void cpuhp_online_idle(enum cpuhp_state state)
1222 {
1223         struct cpuhp_cpu_state *st = this_cpu_ptr(&cpuhp_state);
1224
1225         /* Happens for the boot cpu */
1226         if (state != CPUHP_AP_ONLINE_IDLE)
1227                 return;
1228
1229         /*
1230          * Unpart the stopper thread before we start the idle loop (and start
1231          * scheduling); this ensures the stopper task is always available.
1232          */
1233         stop_machine_unpark(smp_processor_id());
1234
1235         st->state = CPUHP_AP_ONLINE_IDLE;
1236         complete_ap_thread(st, true);
1237 }
1238
1239 /* Requires cpu_add_remove_lock to be held */
1240 static int _cpu_up(unsigned int cpu, int tasks_frozen, enum cpuhp_state target)
1241 {
1242         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1243         struct task_struct *idle;
1244         int ret = 0;
1245
1246         cpus_write_lock();
1247
1248         if (!cpu_present(cpu)) {
1249                 ret = -EINVAL;
1250                 goto out;
1251         }
1252
1253         /*
1254          * The caller of cpu_up() might have raced with another
1255          * caller. Nothing to do.
1256          */
1257         if (st->state >= target)
1258                 goto out;
1259
1260         if (st->state == CPUHP_OFFLINE) {
1261                 /* Let it fail before we try to bring the cpu up */
1262                 idle = idle_thread_get(cpu);
1263                 if (IS_ERR(idle)) {
1264                         ret = PTR_ERR(idle);
1265                         goto out;
1266                 }
1267         }
1268
1269         cpuhp_tasks_frozen = tasks_frozen;
1270
1271         cpuhp_set_state(st, target);
1272         /*
1273          * If the current CPU state is in the range of the AP hotplug thread,
1274          * then we need to kick the thread once more.
1275          */
1276         if (st->state > CPUHP_BRINGUP_CPU) {
1277                 ret = cpuhp_kick_ap_work(cpu);
1278                 /*
1279                  * The AP side has done the error rollback already. Just
1280                  * return the error code..
1281                  */
1282                 if (ret)
1283                         goto out;
1284         }
1285
1286         /*
1287          * Try to reach the target state. We max out on the BP at
1288          * CPUHP_BRINGUP_CPU. After that the AP hotplug thread is
1289          * responsible for bringing it up to the target state.
1290          */
1291         target = min((int)target, CPUHP_BRINGUP_CPU);
1292         ret = cpuhp_up_callbacks(cpu, st, target);
1293 out:
1294         cpus_write_unlock();
1295         arch_smt_update();
1296         return ret;
1297 }
1298
1299 static int cpu_up(unsigned int cpu, enum cpuhp_state target)
1300 {
1301         int err = 0;
1302
1303         if (!cpu_possible(cpu)) {
1304                 pr_err("can't online cpu %d because it is not configured as may-hotadd at boot time\n",
1305                        cpu);
1306 #if defined(CONFIG_IA64)
1307                 pr_err("please check additional_cpus= boot parameter\n");
1308 #endif
1309                 return -EINVAL;
1310         }
1311
1312         err = try_online_node(cpu_to_node(cpu));
1313         if (err)
1314                 return err;
1315
1316         cpu_maps_update_begin();
1317
1318         if (cpu_hotplug_disabled) {
1319                 err = -EBUSY;
1320                 goto out;
1321         }
1322         if (!cpu_smt_allowed(cpu)) {
1323                 err = -EPERM;
1324                 goto out;
1325         }
1326
1327         err = _cpu_up(cpu, 0, target);
1328 out:
1329         cpu_maps_update_done();
1330         return err;
1331 }
1332
1333 /**
1334  * cpu_device_up - Bring up a cpu device
1335  * @dev: Pointer to the cpu device to online
1336  *
1337  * This function is meant to be used by device core cpu subsystem only.
1338  *
1339  * Other subsystems should use add_cpu() instead.
1340  */
1341 int cpu_device_up(struct device *dev)
1342 {
1343         return cpu_up(dev->id, CPUHP_ONLINE);
1344 }
1345
1346 int add_cpu(unsigned int cpu)
1347 {
1348         int ret;
1349
1350         lock_device_hotplug();
1351         ret = device_online(get_cpu_device(cpu));
1352         unlock_device_hotplug();
1353
1354         return ret;
1355 }
1356 EXPORT_SYMBOL_GPL(add_cpu);
1357
1358 /**
1359  * bringup_hibernate_cpu - Bring up the CPU that we hibernated on
1360  * @sleep_cpu: The cpu we hibernated on and should be brought up.
1361  *
1362  * On some architectures like arm64, we can hibernate on any CPU, but on
1363  * wake up the CPU we hibernated on might be offline as a side effect of
1364  * using maxcpus= for example.
1365  */
1366 int bringup_hibernate_cpu(unsigned int sleep_cpu)
1367 {
1368         int ret;
1369
1370         if (!cpu_online(sleep_cpu)) {
1371                 pr_info("Hibernated on a CPU that is offline! Bringing CPU up.\n");
1372                 ret = cpu_up(sleep_cpu, CPUHP_ONLINE);
1373                 if (ret) {
1374                         pr_err("Failed to bring hibernate-CPU up!\n");
1375                         return ret;
1376                 }
1377         }
1378         return 0;
1379 }
1380
1381 void bringup_nonboot_cpus(unsigned int setup_max_cpus)
1382 {
1383         unsigned int cpu;
1384
1385         for_each_present_cpu(cpu) {
1386                 if (num_online_cpus() >= setup_max_cpus)
1387                         break;
1388                 if (!cpu_online(cpu))
1389                         cpu_up(cpu, CPUHP_ONLINE);
1390         }
1391 }
1392
1393 #ifdef CONFIG_PM_SLEEP_SMP
1394 static cpumask_var_t frozen_cpus;
1395
1396 int freeze_secondary_cpus(int primary)
1397 {
1398         int cpu, error = 0;
1399
1400         cpu_maps_update_begin();
1401         if (primary == -1) {
1402                 primary = cpumask_first(cpu_online_mask);
1403                 if (!housekeeping_cpu(primary, HK_FLAG_TIMER))
1404                         primary = housekeeping_any_cpu(HK_FLAG_TIMER);
1405         } else {
1406                 if (!cpu_online(primary))
1407                         primary = cpumask_first(cpu_online_mask);
1408         }
1409
1410         /*
1411          * We take down all of the non-boot CPUs in one shot to avoid races
1412          * with the userspace trying to use the CPU hotplug at the same time
1413          */
1414         cpumask_clear(frozen_cpus);
1415
1416         pr_info("Disabling non-boot CPUs ...\n");
1417         for_each_online_cpu(cpu) {
1418                 if (cpu == primary)
1419                         continue;
1420
1421                 if (pm_wakeup_pending()) {
1422                         pr_info("Wakeup pending. Abort CPU freeze\n");
1423                         error = -EBUSY;
1424                         break;
1425                 }
1426
1427                 trace_suspend_resume(TPS("CPU_OFF"), cpu, true);
1428                 error = _cpu_down(cpu, 1, CPUHP_OFFLINE);
1429                 trace_suspend_resume(TPS("CPU_OFF"), cpu, false);
1430                 if (!error)
1431                         cpumask_set_cpu(cpu, frozen_cpus);
1432                 else {
1433                         pr_err("Error taking CPU%d down: %d\n", cpu, error);
1434                         break;
1435                 }
1436         }
1437
1438         if (!error)
1439                 BUG_ON(num_online_cpus() > 1);
1440         else
1441                 pr_err("Non-boot CPUs are not disabled\n");
1442
1443         /*
1444          * Make sure the CPUs won't be enabled by someone else. We need to do
1445          * this even in case of failure as all freeze_secondary_cpus() users are
1446          * supposed to do thaw_secondary_cpus() on the failure path.
1447          */
1448         cpu_hotplug_disabled++;
1449
1450         cpu_maps_update_done();
1451         return error;
1452 }
1453
1454 void __weak arch_thaw_secondary_cpus_begin(void)
1455 {
1456 }
1457
1458 void __weak arch_thaw_secondary_cpus_end(void)
1459 {
1460 }
1461
1462 void thaw_secondary_cpus(void)
1463 {
1464         int cpu, error;
1465
1466         /* Allow everyone to use the CPU hotplug again */
1467         cpu_maps_update_begin();
1468         __cpu_hotplug_enable();
1469         if (cpumask_empty(frozen_cpus))
1470                 goto out;
1471
1472         pr_info("Enabling non-boot CPUs ...\n");
1473
1474         arch_thaw_secondary_cpus_begin();
1475
1476         for_each_cpu(cpu, frozen_cpus) {
1477                 trace_suspend_resume(TPS("CPU_ON"), cpu, true);
1478                 error = _cpu_up(cpu, 1, CPUHP_ONLINE);
1479                 trace_suspend_resume(TPS("CPU_ON"), cpu, false);
1480                 if (!error) {
1481                         pr_info("CPU%d is up\n", cpu);
1482                         continue;
1483                 }
1484                 pr_warn("Error taking CPU%d up: %d\n", cpu, error);
1485         }
1486
1487         arch_thaw_secondary_cpus_end();
1488
1489         cpumask_clear(frozen_cpus);
1490 out:
1491         cpu_maps_update_done();
1492 }
1493
1494 static int __init alloc_frozen_cpus(void)
1495 {
1496         if (!alloc_cpumask_var(&frozen_cpus, GFP_KERNEL|__GFP_ZERO))
1497                 return -ENOMEM;
1498         return 0;
1499 }
1500 core_initcall(alloc_frozen_cpus);
1501
1502 /*
1503  * When callbacks for CPU hotplug notifications are being executed, we must
1504  * ensure that the state of the system with respect to the tasks being frozen
1505  * or not, as reported by the notification, remains unchanged *throughout the
1506  * duration* of the execution of the callbacks.
1507  * Hence we need to prevent the freezer from racing with regular CPU hotplug.
1508  *
1509  * This synchronization is implemented by mutually excluding regular CPU
1510  * hotplug and Suspend/Hibernate call paths by hooking onto the Suspend/
1511  * Hibernate notifications.
1512  */
1513 static int
1514 cpu_hotplug_pm_callback(struct notifier_block *nb,
1515                         unsigned long action, void *ptr)
1516 {
1517         switch (action) {
1518
1519         case PM_SUSPEND_PREPARE:
1520         case PM_HIBERNATION_PREPARE:
1521                 cpu_hotplug_disable();
1522                 break;
1523
1524         case PM_POST_SUSPEND:
1525         case PM_POST_HIBERNATION:
1526                 cpu_hotplug_enable();
1527                 break;
1528
1529         default:
1530                 return NOTIFY_DONE;
1531         }
1532
1533         return NOTIFY_OK;
1534 }
1535
1536
1537 static int __init cpu_hotplug_pm_sync_init(void)
1538 {
1539         /*
1540          * cpu_hotplug_pm_callback has higher priority than x86
1541          * bsp_pm_callback which depends on cpu_hotplug_pm_callback
1542          * to disable cpu hotplug to avoid cpu hotplug race.
1543          */
1544         pm_notifier(cpu_hotplug_pm_callback, 0);
1545         return 0;
1546 }
1547 core_initcall(cpu_hotplug_pm_sync_init);
1548
1549 #endif /* CONFIG_PM_SLEEP_SMP */
1550
1551 int __boot_cpu_id;
1552
1553 #endif /* CONFIG_SMP */
1554
1555 /* Boot processor state steps */
1556 static struct cpuhp_step cpuhp_hp_states[] = {
1557         [CPUHP_OFFLINE] = {
1558                 .name                   = "offline",
1559                 .startup.single         = NULL,
1560                 .teardown.single        = NULL,
1561         },
1562 #ifdef CONFIG_SMP
1563         [CPUHP_CREATE_THREADS]= {
1564                 .name                   = "threads:prepare",
1565                 .startup.single         = smpboot_create_threads,
1566                 .teardown.single        = NULL,
1567                 .cant_stop              = true,
1568         },
1569         [CPUHP_PERF_PREPARE] = {
1570                 .name                   = "perf:prepare",
1571                 .startup.single         = perf_event_init_cpu,
1572                 .teardown.single        = perf_event_exit_cpu,
1573         },
1574         [CPUHP_WORKQUEUE_PREP] = {
1575                 .name                   = "workqueue:prepare",
1576                 .startup.single         = workqueue_prepare_cpu,
1577                 .teardown.single        = NULL,
1578         },
1579         [CPUHP_HRTIMERS_PREPARE] = {
1580                 .name                   = "hrtimers:prepare",
1581                 .startup.single         = hrtimers_prepare_cpu,
1582                 .teardown.single        = hrtimers_dead_cpu,
1583         },
1584         [CPUHP_SMPCFD_PREPARE] = {
1585                 .name                   = "smpcfd:prepare",
1586                 .startup.single         = smpcfd_prepare_cpu,
1587                 .teardown.single        = smpcfd_dead_cpu,
1588         },
1589         [CPUHP_RELAY_PREPARE] = {
1590                 .name                   = "relay:prepare",
1591                 .startup.single         = relay_prepare_cpu,
1592                 .teardown.single        = NULL,
1593         },
1594         [CPUHP_SLAB_PREPARE] = {
1595                 .name                   = "slab:prepare",
1596                 .startup.single         = slab_prepare_cpu,
1597                 .teardown.single        = slab_dead_cpu,
1598         },
1599         [CPUHP_RCUTREE_PREP] = {
1600                 .name                   = "RCU/tree:prepare",
1601                 .startup.single         = rcutree_prepare_cpu,
1602                 .teardown.single        = rcutree_dead_cpu,
1603         },
1604         /*
1605          * On the tear-down path, timers_dead_cpu() must be invoked
1606          * before blk_mq_queue_reinit_notify() from notify_dead(),
1607          * otherwise a RCU stall occurs.
1608          */
1609         [CPUHP_TIMERS_PREPARE] = {
1610                 .name                   = "timers:prepare",
1611                 .startup.single         = timers_prepare_cpu,
1612                 .teardown.single        = timers_dead_cpu,
1613         },
1614         /* Kicks the plugged cpu into life */
1615         [CPUHP_BRINGUP_CPU] = {
1616                 .name                   = "cpu:bringup",
1617                 .startup.single         = bringup_cpu,
1618                 .teardown.single        = finish_cpu,
1619                 .cant_stop              = true,
1620         },
1621         /* Final state before CPU kills itself */
1622         [CPUHP_AP_IDLE_DEAD] = {
1623                 .name                   = "idle:dead",
1624         },
1625         /*
1626          * Last state before CPU enters the idle loop to die. Transient state
1627          * for synchronization.
1628          */
1629         [CPUHP_AP_OFFLINE] = {
1630                 .name                   = "ap:offline",
1631                 .cant_stop              = true,
1632         },
1633         /* First state is scheduler control. Interrupts are disabled */
1634         [CPUHP_AP_SCHED_STARTING] = {
1635                 .name                   = "sched:starting",
1636                 .startup.single         = sched_cpu_starting,
1637                 .teardown.single        = sched_cpu_dying,
1638         },
1639         [CPUHP_AP_RCUTREE_DYING] = {
1640                 .name                   = "RCU/tree:dying",
1641                 .startup.single         = NULL,
1642                 .teardown.single        = rcutree_dying_cpu,
1643         },
1644         [CPUHP_AP_SMPCFD_DYING] = {
1645                 .name                   = "smpcfd:dying",
1646                 .startup.single         = NULL,
1647                 .teardown.single        = smpcfd_dying_cpu,
1648         },
1649         /* Entry state on starting. Interrupts enabled from here on. Transient
1650          * state for synchronsization */
1651         [CPUHP_AP_ONLINE] = {
1652                 .name                   = "ap:online",
1653         },
1654         /*
1655          * Handled on control processor until the plugged processor manages
1656          * this itself.
1657          */
1658         [CPUHP_TEARDOWN_CPU] = {
1659                 .name                   = "cpu:teardown",
1660                 .startup.single         = NULL,
1661                 .teardown.single        = takedown_cpu,
1662                 .cant_stop              = true,
1663         },
1664
1665         [CPUHP_AP_SCHED_WAIT_EMPTY] = {
1666                 .name                   = "sched:waitempty",
1667                 .startup.single         = NULL,
1668                 .teardown.single        = sched_cpu_wait_empty,
1669         },
1670
1671         /* Handle smpboot threads park/unpark */
1672         [CPUHP_AP_SMPBOOT_THREADS] = {
1673                 .name                   = "smpboot/threads:online",
1674                 .startup.single         = smpboot_unpark_threads,
1675                 .teardown.single        = smpboot_park_threads,
1676         },
1677         [CPUHP_AP_IRQ_AFFINITY_ONLINE] = {
1678                 .name                   = "irq/affinity:online",
1679                 .startup.single         = irq_affinity_online_cpu,
1680                 .teardown.single        = NULL,
1681         },
1682         [CPUHP_AP_PERF_ONLINE] = {
1683                 .name                   = "perf:online",
1684                 .startup.single         = perf_event_init_cpu,
1685                 .teardown.single        = perf_event_exit_cpu,
1686         },
1687         [CPUHP_AP_WATCHDOG_ONLINE] = {
1688                 .name                   = "lockup_detector:online",
1689                 .startup.single         = lockup_detector_online_cpu,
1690                 .teardown.single        = lockup_detector_offline_cpu,
1691         },
1692         [CPUHP_AP_WORKQUEUE_ONLINE] = {
1693                 .name                   = "workqueue:online",
1694                 .startup.single         = workqueue_online_cpu,
1695                 .teardown.single        = workqueue_offline_cpu,
1696         },
1697         [CPUHP_AP_RCUTREE_ONLINE] = {
1698                 .name                   = "RCU/tree:online",
1699                 .startup.single         = rcutree_online_cpu,
1700                 .teardown.single        = rcutree_offline_cpu,
1701         },
1702 #endif
1703         /*
1704          * The dynamically registered state space is here
1705          */
1706
1707 #ifdef CONFIG_SMP
1708         /* Last state is scheduler control setting the cpu active */
1709         [CPUHP_AP_ACTIVE] = {
1710                 .name                   = "sched:active",
1711                 .startup.single         = sched_cpu_activate,
1712                 .teardown.single        = sched_cpu_deactivate,
1713         },
1714 #endif
1715
1716         /* CPU is fully up and running. */
1717         [CPUHP_ONLINE] = {
1718                 .name                   = "online",
1719                 .startup.single         = NULL,
1720                 .teardown.single        = NULL,
1721         },
1722 };
1723
1724 /* Sanity check for callbacks */
1725 static int cpuhp_cb_check(enum cpuhp_state state)
1726 {
1727         if (state <= CPUHP_OFFLINE || state >= CPUHP_ONLINE)
1728                 return -EINVAL;
1729         return 0;
1730 }
1731
1732 /*
1733  * Returns a free for dynamic slot assignment of the Online state. The states
1734  * are protected by the cpuhp_slot_states mutex and an empty slot is identified
1735  * by having no name assigned.
1736  */
1737 static int cpuhp_reserve_state(enum cpuhp_state state)
1738 {
1739         enum cpuhp_state i, end;
1740         struct cpuhp_step *step;
1741
1742         switch (state) {
1743         case CPUHP_AP_ONLINE_DYN:
1744                 step = cpuhp_hp_states + CPUHP_AP_ONLINE_DYN;
1745                 end = CPUHP_AP_ONLINE_DYN_END;
1746                 break;
1747         case CPUHP_BP_PREPARE_DYN:
1748                 step = cpuhp_hp_states + CPUHP_BP_PREPARE_DYN;
1749                 end = CPUHP_BP_PREPARE_DYN_END;
1750                 break;
1751         default:
1752                 return -EINVAL;
1753         }
1754
1755         for (i = state; i <= end; i++, step++) {
1756                 if (!step->name)
1757                         return i;
1758         }
1759         WARN(1, "No more dynamic states available for CPU hotplug\n");
1760         return -ENOSPC;
1761 }
1762
1763 static int cpuhp_store_callbacks(enum cpuhp_state state, const char *name,
1764                                  int (*startup)(unsigned int cpu),
1765                                  int (*teardown)(unsigned int cpu),
1766                                  bool multi_instance)
1767 {
1768         /* (Un)Install the callbacks for further cpu hotplug operations */
1769         struct cpuhp_step *sp;
1770         int ret = 0;
1771
1772         /*
1773          * If name is NULL, then the state gets removed.
1774          *
1775          * CPUHP_AP_ONLINE_DYN and CPUHP_BP_PREPARE_DYN are handed out on
1776          * the first allocation from these dynamic ranges, so the removal
1777          * would trigger a new allocation and clear the wrong (already
1778          * empty) state, leaving the callbacks of the to be cleared state
1779          * dangling, which causes wreckage on the next hotplug operation.
1780          */
1781         if (name && (state == CPUHP_AP_ONLINE_DYN ||
1782                      state == CPUHP_BP_PREPARE_DYN)) {
1783                 ret = cpuhp_reserve_state(state);
1784                 if (ret < 0)
1785                         return ret;
1786                 state = ret;
1787         }
1788         sp = cpuhp_get_step(state);
1789         if (name && sp->name)
1790                 return -EBUSY;
1791
1792         sp->startup.single = startup;
1793         sp->teardown.single = teardown;
1794         sp->name = name;
1795         sp->multi_instance = multi_instance;
1796         INIT_HLIST_HEAD(&sp->list);
1797         return ret;
1798 }
1799
1800 static void *cpuhp_get_teardown_cb(enum cpuhp_state state)
1801 {
1802         return cpuhp_get_step(state)->teardown.single;
1803 }
1804
1805 /*
1806  * Call the startup/teardown function for a step either on the AP or
1807  * on the current CPU.
1808  */
1809 static int cpuhp_issue_call(int cpu, enum cpuhp_state state, bool bringup,
1810                             struct hlist_node *node)
1811 {
1812         struct cpuhp_step *sp = cpuhp_get_step(state);
1813         int ret;
1814
1815         /*
1816          * If there's nothing to do, we done.
1817          * Relies on the union for multi_instance.
1818          */
1819         if (cpuhp_step_empty(bringup, sp))
1820                 return 0;
1821         /*
1822          * The non AP bound callbacks can fail on bringup. On teardown
1823          * e.g. module removal we crash for now.
1824          */
1825 #ifdef CONFIG_SMP
1826         if (cpuhp_is_ap_state(state))
1827                 ret = cpuhp_invoke_ap_callback(cpu, state, bringup, node);
1828         else
1829                 ret = cpuhp_invoke_callback(cpu, state, bringup, node, NULL);
1830 #else
1831         ret = cpuhp_invoke_callback(cpu, state, bringup, node, NULL);
1832 #endif
1833         BUG_ON(ret && !bringup);
1834         return ret;
1835 }
1836
1837 /*
1838  * Called from __cpuhp_setup_state on a recoverable failure.
1839  *
1840  * Note: The teardown callbacks for rollback are not allowed to fail!
1841  */
1842 static void cpuhp_rollback_install(int failedcpu, enum cpuhp_state state,
1843                                    struct hlist_node *node)
1844 {
1845         int cpu;
1846
1847         /* Roll back the already executed steps on the other cpus */
1848         for_each_present_cpu(cpu) {
1849                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1850                 int cpustate = st->state;
1851
1852                 if (cpu >= failedcpu)
1853                         break;
1854
1855                 /* Did we invoke the startup call on that cpu ? */
1856                 if (cpustate >= state)
1857                         cpuhp_issue_call(cpu, state, false, node);
1858         }
1859 }
1860
1861 int __cpuhp_state_add_instance_cpuslocked(enum cpuhp_state state,
1862                                           struct hlist_node *node,
1863                                           bool invoke)
1864 {
1865         struct cpuhp_step *sp;
1866         int cpu;
1867         int ret;
1868
1869         lockdep_assert_cpus_held();
1870
1871         sp = cpuhp_get_step(state);
1872         if (sp->multi_instance == false)
1873                 return -EINVAL;
1874
1875         mutex_lock(&cpuhp_state_mutex);
1876
1877         if (!invoke || !sp->startup.multi)
1878                 goto add_node;
1879
1880         /*
1881          * Try to call the startup callback for each present cpu
1882          * depending on the hotplug state of the cpu.
1883          */
1884         for_each_present_cpu(cpu) {
1885                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1886                 int cpustate = st->state;
1887
1888                 if (cpustate < state)
1889                         continue;
1890
1891                 ret = cpuhp_issue_call(cpu, state, true, node);
1892                 if (ret) {
1893                         if (sp->teardown.multi)
1894                                 cpuhp_rollback_install(cpu, state, node);
1895                         goto unlock;
1896                 }
1897         }
1898 add_node:
1899         ret = 0;
1900         hlist_add_head(node, &sp->list);
1901 unlock:
1902         mutex_unlock(&cpuhp_state_mutex);
1903         return ret;
1904 }
1905
1906 int __cpuhp_state_add_instance(enum cpuhp_state state, struct hlist_node *node,
1907                                bool invoke)
1908 {
1909         int ret;
1910
1911         cpus_read_lock();
1912         ret = __cpuhp_state_add_instance_cpuslocked(state, node, invoke);
1913         cpus_read_unlock();
1914         return ret;
1915 }
1916 EXPORT_SYMBOL_GPL(__cpuhp_state_add_instance);
1917
1918 /**
1919  * __cpuhp_setup_state_cpuslocked - Setup the callbacks for an hotplug machine state
1920  * @state:              The state to setup
1921  * @invoke:             If true, the startup function is invoked for cpus where
1922  *                      cpu state >= @state
1923  * @startup:            startup callback function
1924  * @teardown:           teardown callback function
1925  * @multi_instance:     State is set up for multiple instances which get
1926  *                      added afterwards.
1927  *
1928  * The caller needs to hold cpus read locked while calling this function.
1929  * Returns:
1930  *   On success:
1931  *      Positive state number if @state is CPUHP_AP_ONLINE_DYN
1932  *      0 for all other states
1933  *   On failure: proper (negative) error code
1934  */
1935 int __cpuhp_setup_state_cpuslocked(enum cpuhp_state state,
1936                                    const char *name, bool invoke,
1937                                    int (*startup)(unsigned int cpu),
1938                                    int (*teardown)(unsigned int cpu),
1939                                    bool multi_instance)
1940 {
1941         int cpu, ret = 0;
1942         bool dynstate;
1943
1944         lockdep_assert_cpus_held();
1945
1946         if (cpuhp_cb_check(state) || !name)
1947                 return -EINVAL;
1948
1949         mutex_lock(&cpuhp_state_mutex);
1950
1951         ret = cpuhp_store_callbacks(state, name, startup, teardown,
1952                                     multi_instance);
1953
1954         dynstate = state == CPUHP_AP_ONLINE_DYN;
1955         if (ret > 0 && dynstate) {
1956                 state = ret;
1957                 ret = 0;
1958         }
1959
1960         if (ret || !invoke || !startup)
1961                 goto out;
1962
1963         /*
1964          * Try to call the startup callback for each present cpu
1965          * depending on the hotplug state of the cpu.
1966          */
1967         for_each_present_cpu(cpu) {
1968                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1969                 int cpustate = st->state;
1970
1971                 if (cpustate < state)
1972                         continue;
1973
1974                 ret = cpuhp_issue_call(cpu, state, true, NULL);
1975                 if (ret) {
1976                         if (teardown)
1977                                 cpuhp_rollback_install(cpu, state, NULL);
1978                         cpuhp_store_callbacks(state, NULL, NULL, NULL, false);
1979                         goto out;
1980                 }
1981         }
1982 out:
1983         mutex_unlock(&cpuhp_state_mutex);
1984         /*
1985          * If the requested state is CPUHP_AP_ONLINE_DYN, return the
1986          * dynamically allocated state in case of success.
1987          */
1988         if (!ret && dynstate)
1989                 return state;
1990         return ret;
1991 }
1992 EXPORT_SYMBOL(__cpuhp_setup_state_cpuslocked);
1993
1994 int __cpuhp_setup_state(enum cpuhp_state state,
1995                         const char *name, bool invoke,
1996                         int (*startup)(unsigned int cpu),
1997                         int (*teardown)(unsigned int cpu),
1998                         bool multi_instance)
1999 {
2000         int ret;
2001
2002         cpus_read_lock();
2003         ret = __cpuhp_setup_state_cpuslocked(state, name, invoke, startup,
2004                                              teardown, multi_instance);
2005         cpus_read_unlock();
2006         return ret;
2007 }
2008 EXPORT_SYMBOL(__cpuhp_setup_state);
2009
2010 int __cpuhp_state_remove_instance(enum cpuhp_state state,
2011                                   struct hlist_node *node, bool invoke)
2012 {
2013         struct cpuhp_step *sp = cpuhp_get_step(state);
2014         int cpu;
2015
2016         BUG_ON(cpuhp_cb_check(state));
2017
2018         if (!sp->multi_instance)
2019                 return -EINVAL;
2020
2021         cpus_read_lock();
2022         mutex_lock(&cpuhp_state_mutex);
2023
2024         if (!invoke || !cpuhp_get_teardown_cb(state))
2025                 goto remove;
2026         /*
2027          * Call the teardown callback for each present cpu depending
2028          * on the hotplug state of the cpu. This function is not
2029          * allowed to fail currently!
2030          */
2031         for_each_present_cpu(cpu) {
2032                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
2033                 int cpustate = st->state;
2034
2035                 if (cpustate >= state)
2036                         cpuhp_issue_call(cpu, state, false, node);
2037         }
2038
2039 remove:
2040         hlist_del(node);
2041         mutex_unlock(&cpuhp_state_mutex);
2042         cpus_read_unlock();
2043
2044         return 0;
2045 }
2046 EXPORT_SYMBOL_GPL(__cpuhp_state_remove_instance);
2047
2048 /**
2049  * __cpuhp_remove_state_cpuslocked - Remove the callbacks for an hotplug machine state
2050  * @state:      The state to remove
2051  * @invoke:     If true, the teardown function is invoked for cpus where
2052  *              cpu state >= @state
2053  *
2054  * The caller needs to hold cpus read locked while calling this function.
2055  * The teardown callback is currently not allowed to fail. Think
2056  * about module removal!
2057  */
2058 void __cpuhp_remove_state_cpuslocked(enum cpuhp_state state, bool invoke)
2059 {
2060         struct cpuhp_step *sp = cpuhp_get_step(state);
2061         int cpu;
2062
2063         BUG_ON(cpuhp_cb_check(state));
2064
2065         lockdep_assert_cpus_held();
2066
2067         mutex_lock(&cpuhp_state_mutex);
2068         if (sp->multi_instance) {
2069                 WARN(!hlist_empty(&sp->list),
2070                      "Error: Removing state %d which has instances left.\n",
2071                      state);
2072                 goto remove;
2073         }
2074
2075         if (!invoke || !cpuhp_get_teardown_cb(state))
2076                 goto remove;
2077
2078         /*
2079          * Call the teardown callback for each present cpu depending
2080          * on the hotplug state of the cpu. This function is not
2081          * allowed to fail currently!
2082          */
2083         for_each_present_cpu(cpu) {
2084                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
2085                 int cpustate = st->state;
2086
2087                 if (cpustate >= state)
2088                         cpuhp_issue_call(cpu, state, false, NULL);
2089         }
2090 remove:
2091         cpuhp_store_callbacks(state, NULL, NULL, NULL, false);
2092         mutex_unlock(&cpuhp_state_mutex);
2093 }
2094 EXPORT_SYMBOL(__cpuhp_remove_state_cpuslocked);
2095
2096 void __cpuhp_remove_state(enum cpuhp_state state, bool invoke)
2097 {
2098         cpus_read_lock();
2099         __cpuhp_remove_state_cpuslocked(state, invoke);
2100         cpus_read_unlock();
2101 }
2102 EXPORT_SYMBOL(__cpuhp_remove_state);
2103
2104 #ifdef CONFIG_HOTPLUG_SMT
2105 static void cpuhp_offline_cpu_device(unsigned int cpu)
2106 {
2107         struct device *dev = get_cpu_device(cpu);
2108
2109         dev->offline = true;
2110         /* Tell user space about the state change */
2111         kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
2112 }
2113
2114 static void cpuhp_online_cpu_device(unsigned int cpu)
2115 {
2116         struct device *dev = get_cpu_device(cpu);
2117
2118         dev->offline = false;
2119         /* Tell user space about the state change */
2120         kobject_uevent(&dev->kobj, KOBJ_ONLINE);
2121 }
2122
2123 int cpuhp_smt_disable(enum cpuhp_smt_control ctrlval)
2124 {
2125         int cpu, ret = 0;
2126
2127         cpu_maps_update_begin();
2128         for_each_online_cpu(cpu) {
2129                 if (topology_is_primary_thread(cpu))
2130                         continue;
2131                 ret = cpu_down_maps_locked(cpu, CPUHP_OFFLINE);
2132                 if (ret)
2133                         break;
2134                 /*
2135                  * As this needs to hold the cpu maps lock it's impossible
2136                  * to call device_offline() because that ends up calling
2137                  * cpu_down() which takes cpu maps lock. cpu maps lock
2138                  * needs to be held as this might race against in kernel
2139                  * abusers of the hotplug machinery (thermal management).
2140                  *
2141                  * So nothing would update device:offline state. That would
2142                  * leave the sysfs entry stale and prevent onlining after
2143                  * smt control has been changed to 'off' again. This is
2144                  * called under the sysfs hotplug lock, so it is properly
2145                  * serialized against the regular offline usage.
2146                  */
2147                 cpuhp_offline_cpu_device(cpu);
2148         }
2149         if (!ret)
2150                 cpu_smt_control = ctrlval;
2151         cpu_maps_update_done();
2152         return ret;
2153 }
2154
2155 int cpuhp_smt_enable(void)
2156 {
2157         int cpu, ret = 0;
2158
2159         cpu_maps_update_begin();
2160         cpu_smt_control = CPU_SMT_ENABLED;
2161         for_each_present_cpu(cpu) {
2162                 /* Skip online CPUs and CPUs on offline nodes */
2163                 if (cpu_online(cpu) || !node_online(cpu_to_node(cpu)))
2164                         continue;
2165                 ret = _cpu_up(cpu, 0, CPUHP_ONLINE);
2166                 if (ret)
2167                         break;
2168                 /* See comment in cpuhp_smt_disable() */
2169                 cpuhp_online_cpu_device(cpu);
2170         }
2171         cpu_maps_update_done();
2172         return ret;
2173 }
2174 #endif
2175
2176 #if defined(CONFIG_SYSFS) && defined(CONFIG_HOTPLUG_CPU)
2177 static ssize_t show_cpuhp_state(struct device *dev,
2178                                 struct device_attribute *attr, char *buf)
2179 {
2180         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2181
2182         return sprintf(buf, "%d\n", st->state);
2183 }
2184 static DEVICE_ATTR(state, 0444, show_cpuhp_state, NULL);
2185
2186 static ssize_t write_cpuhp_target(struct device *dev,
2187                                   struct device_attribute *attr,
2188                                   const char *buf, size_t count)
2189 {
2190         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2191         struct cpuhp_step *sp;
2192         int target, ret;
2193
2194         ret = kstrtoint(buf, 10, &target);
2195         if (ret)
2196                 return ret;
2197
2198 #ifdef CONFIG_CPU_HOTPLUG_STATE_CONTROL
2199         if (target < CPUHP_OFFLINE || target > CPUHP_ONLINE)
2200                 return -EINVAL;
2201 #else
2202         if (target != CPUHP_OFFLINE && target != CPUHP_ONLINE)
2203                 return -EINVAL;
2204 #endif
2205
2206         ret = lock_device_hotplug_sysfs();
2207         if (ret)
2208                 return ret;
2209
2210         mutex_lock(&cpuhp_state_mutex);
2211         sp = cpuhp_get_step(target);
2212         ret = !sp->name || sp->cant_stop ? -EINVAL : 0;
2213         mutex_unlock(&cpuhp_state_mutex);
2214         if (ret)
2215                 goto out;
2216
2217         if (st->state < target)
2218                 ret = cpu_up(dev->id, target);
2219         else
2220                 ret = cpu_down(dev->id, target);
2221 out:
2222         unlock_device_hotplug();
2223         return ret ? ret : count;
2224 }
2225
2226 static ssize_t show_cpuhp_target(struct device *dev,
2227                                  struct device_attribute *attr, char *buf)
2228 {
2229         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2230
2231         return sprintf(buf, "%d\n", st->target);
2232 }
2233 static DEVICE_ATTR(target, 0644, show_cpuhp_target, write_cpuhp_target);
2234
2235
2236 static ssize_t write_cpuhp_fail(struct device *dev,
2237                                 struct device_attribute *attr,
2238                                 const char *buf, size_t count)
2239 {
2240         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2241         struct cpuhp_step *sp;
2242         int fail, ret;
2243
2244         ret = kstrtoint(buf, 10, &fail);
2245         if (ret)
2246                 return ret;
2247
2248         if (fail == CPUHP_INVALID) {
2249                 st->fail = fail;
2250                 return count;
2251         }
2252
2253         if (fail < CPUHP_OFFLINE || fail > CPUHP_ONLINE)
2254                 return -EINVAL;
2255
2256         /*
2257          * Cannot fail STARTING/DYING callbacks.
2258          */
2259         if (cpuhp_is_atomic_state(fail))
2260                 return -EINVAL;
2261
2262         /*
2263          * DEAD callbacks cannot fail...
2264          * ... neither can CPUHP_BRINGUP_CPU during hotunplug. The latter
2265          * triggering STARTING callbacks, a failure in this state would
2266          * hinder rollback.
2267          */
2268         if (fail <= CPUHP_BRINGUP_CPU && st->state > CPUHP_BRINGUP_CPU)
2269                 return -EINVAL;
2270
2271         /*
2272          * Cannot fail anything that doesn't have callbacks.
2273          */
2274         mutex_lock(&cpuhp_state_mutex);
2275         sp = cpuhp_get_step(fail);
2276         if (!sp->startup.single && !sp->teardown.single)
2277                 ret = -EINVAL;
2278         mutex_unlock(&cpuhp_state_mutex);
2279         if (ret)
2280                 return ret;
2281
2282         st->fail = fail;
2283
2284         return count;
2285 }
2286
2287 static ssize_t show_cpuhp_fail(struct device *dev,
2288                                struct device_attribute *attr, char *buf)
2289 {
2290         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2291
2292         return sprintf(buf, "%d\n", st->fail);
2293 }
2294
2295 static DEVICE_ATTR(fail, 0644, show_cpuhp_fail, write_cpuhp_fail);
2296
2297 static struct attribute *cpuhp_cpu_attrs[] = {
2298         &dev_attr_state.attr,
2299         &dev_attr_target.attr,
2300         &dev_attr_fail.attr,
2301         NULL
2302 };
2303
2304 static const struct attribute_group cpuhp_cpu_attr_group = {
2305         .attrs = cpuhp_cpu_attrs,
2306         .name = "hotplug",
2307         NULL
2308 };
2309
2310 static ssize_t show_cpuhp_states(struct device *dev,
2311                                  struct device_attribute *attr, char *buf)
2312 {
2313         ssize_t cur, res = 0;
2314         int i;
2315
2316         mutex_lock(&cpuhp_state_mutex);
2317         for (i = CPUHP_OFFLINE; i <= CPUHP_ONLINE; i++) {
2318                 struct cpuhp_step *sp = cpuhp_get_step(i);
2319
2320                 if (sp->name) {
2321                         cur = sprintf(buf, "%3d: %s\n", i, sp->name);
2322                         buf += cur;
2323                         res += cur;
2324                 }
2325         }
2326         mutex_unlock(&cpuhp_state_mutex);
2327         return res;
2328 }
2329 static DEVICE_ATTR(states, 0444, show_cpuhp_states, NULL);
2330
2331 static struct attribute *cpuhp_cpu_root_attrs[] = {
2332         &dev_attr_states.attr,
2333         NULL
2334 };
2335
2336 static const struct attribute_group cpuhp_cpu_root_attr_group = {
2337         .attrs = cpuhp_cpu_root_attrs,
2338         .name = "hotplug",
2339         NULL
2340 };
2341
2342 #ifdef CONFIG_HOTPLUG_SMT
2343
2344 static ssize_t
2345 __store_smt_control(struct device *dev, struct device_attribute *attr,
2346                     const char *buf, size_t count)
2347 {
2348         int ctrlval, ret;
2349
2350         if (sysfs_streq(buf, "on"))
2351                 ctrlval = CPU_SMT_ENABLED;
2352         else if (sysfs_streq(buf, "off"))
2353                 ctrlval = CPU_SMT_DISABLED;
2354         else if (sysfs_streq(buf, "forceoff"))
2355                 ctrlval = CPU_SMT_FORCE_DISABLED;
2356         else
2357                 return -EINVAL;
2358
2359         if (cpu_smt_control == CPU_SMT_FORCE_DISABLED)
2360                 return -EPERM;
2361
2362         if (cpu_smt_control == CPU_SMT_NOT_SUPPORTED)
2363                 return -ENODEV;
2364
2365         ret = lock_device_hotplug_sysfs();
2366         if (ret)
2367                 return ret;
2368
2369         if (ctrlval != cpu_smt_control) {
2370                 switch (ctrlval) {
2371                 case CPU_SMT_ENABLED:
2372                         ret = cpuhp_smt_enable();
2373                         break;
2374                 case CPU_SMT_DISABLED:
2375                 case CPU_SMT_FORCE_DISABLED:
2376                         ret = cpuhp_smt_disable(ctrlval);
2377                         break;
2378                 }
2379         }
2380
2381         unlock_device_hotplug();
2382         return ret ? ret : count;
2383 }
2384
2385 #else /* !CONFIG_HOTPLUG_SMT */
2386 static ssize_t
2387 __store_smt_control(struct device *dev, struct device_attribute *attr,
2388                     const char *buf, size_t count)
2389 {
2390         return -ENODEV;
2391 }
2392 #endif /* CONFIG_HOTPLUG_SMT */
2393
2394 static const char *smt_states[] = {
2395         [CPU_SMT_ENABLED]               = "on",
2396         [CPU_SMT_DISABLED]              = "off",
2397         [CPU_SMT_FORCE_DISABLED]        = "forceoff",
2398         [CPU_SMT_NOT_SUPPORTED]         = "notsupported",
2399         [CPU_SMT_NOT_IMPLEMENTED]       = "notimplemented",
2400 };
2401
2402 static ssize_t
2403 show_smt_control(struct device *dev, struct device_attribute *attr, char *buf)
2404 {
2405         const char *state = smt_states[cpu_smt_control];
2406
2407         return snprintf(buf, PAGE_SIZE - 2, "%s\n", state);
2408 }
2409
2410 static ssize_t
2411 store_smt_control(struct device *dev, struct device_attribute *attr,
2412                   const char *buf, size_t count)
2413 {
2414         return __store_smt_control(dev, attr, buf, count);
2415 }
2416 static DEVICE_ATTR(control, 0644, show_smt_control, store_smt_control);
2417
2418 static ssize_t
2419 show_smt_active(struct device *dev, struct device_attribute *attr, char *buf)
2420 {
2421         return snprintf(buf, PAGE_SIZE - 2, "%d\n", sched_smt_active());
2422 }
2423 static DEVICE_ATTR(active, 0444, show_smt_active, NULL);
2424
2425 static struct attribute *cpuhp_smt_attrs[] = {
2426         &dev_attr_control.attr,
2427         &dev_attr_active.attr,
2428         NULL
2429 };
2430
2431 static const struct attribute_group cpuhp_smt_attr_group = {
2432         .attrs = cpuhp_smt_attrs,
2433         .name = "smt",
2434         NULL
2435 };
2436
2437 static int __init cpu_smt_sysfs_init(void)
2438 {
2439         return sysfs_create_group(&cpu_subsys.dev_root->kobj,
2440                                   &cpuhp_smt_attr_group);
2441 }
2442
2443 static int __init cpuhp_sysfs_init(void)
2444 {
2445         int cpu, ret;
2446
2447         ret = cpu_smt_sysfs_init();
2448         if (ret)
2449                 return ret;
2450
2451         ret = sysfs_create_group(&cpu_subsys.dev_root->kobj,
2452                                  &cpuhp_cpu_root_attr_group);
2453         if (ret)
2454                 return ret;
2455
2456         for_each_possible_cpu(cpu) {
2457                 struct device *dev = get_cpu_device(cpu);
2458
2459                 if (!dev)
2460                         continue;
2461                 ret = sysfs_create_group(&dev->kobj, &cpuhp_cpu_attr_group);
2462                 if (ret)
2463                         return ret;
2464         }
2465         return 0;
2466 }
2467 device_initcall(cpuhp_sysfs_init);
2468 #endif /* CONFIG_SYSFS && CONFIG_HOTPLUG_CPU */
2469
2470 /*
2471  * cpu_bit_bitmap[] is a special, "compressed" data structure that
2472  * represents all NR_CPUS bits binary values of 1<<nr.
2473  *
2474  * It is used by cpumask_of() to get a constant address to a CPU
2475  * mask value that has a single bit set only.
2476  */
2477
2478 /* cpu_bit_bitmap[0] is empty - so we can back into it */
2479 #define MASK_DECLARE_1(x)       [x+1][0] = (1UL << (x))
2480 #define MASK_DECLARE_2(x)       MASK_DECLARE_1(x), MASK_DECLARE_1(x+1)
2481 #define MASK_DECLARE_4(x)       MASK_DECLARE_2(x), MASK_DECLARE_2(x+2)
2482 #define MASK_DECLARE_8(x)       MASK_DECLARE_4(x), MASK_DECLARE_4(x+4)
2483
2484 const unsigned long cpu_bit_bitmap[BITS_PER_LONG+1][BITS_TO_LONGS(NR_CPUS)] = {
2485
2486         MASK_DECLARE_8(0),      MASK_DECLARE_8(8),
2487         MASK_DECLARE_8(16),     MASK_DECLARE_8(24),
2488 #if BITS_PER_LONG > 32
2489         MASK_DECLARE_8(32),     MASK_DECLARE_8(40),
2490         MASK_DECLARE_8(48),     MASK_DECLARE_8(56),
2491 #endif
2492 };
2493 EXPORT_SYMBOL_GPL(cpu_bit_bitmap);
2494
2495 const DECLARE_BITMAP(cpu_all_bits, NR_CPUS) = CPU_BITS_ALL;
2496 EXPORT_SYMBOL(cpu_all_bits);
2497
2498 #ifdef CONFIG_INIT_ALL_POSSIBLE
2499 struct cpumask __cpu_possible_mask __read_mostly
2500         = {CPU_BITS_ALL};
2501 #else
2502 struct cpumask __cpu_possible_mask __read_mostly;
2503 #endif
2504 EXPORT_SYMBOL(__cpu_possible_mask);
2505
2506 struct cpumask __cpu_online_mask __read_mostly;
2507 EXPORT_SYMBOL(__cpu_online_mask);
2508
2509 struct cpumask __cpu_present_mask __read_mostly;
2510 EXPORT_SYMBOL(__cpu_present_mask);
2511
2512 struct cpumask __cpu_active_mask __read_mostly;
2513 EXPORT_SYMBOL(__cpu_active_mask);
2514
2515 atomic_t __num_online_cpus __read_mostly;
2516 EXPORT_SYMBOL(__num_online_cpus);
2517
2518 void init_cpu_present(const struct cpumask *src)
2519 {
2520         cpumask_copy(&__cpu_present_mask, src);
2521 }
2522
2523 void init_cpu_possible(const struct cpumask *src)
2524 {
2525         cpumask_copy(&__cpu_possible_mask, src);
2526 }
2527
2528 void init_cpu_online(const struct cpumask *src)
2529 {
2530         cpumask_copy(&__cpu_online_mask, src);
2531 }
2532
2533 void set_cpu_online(unsigned int cpu, bool online)
2534 {
2535         /*
2536          * atomic_inc/dec() is required to handle the horrid abuse of this
2537          * function by the reboot and kexec code which invoke it from
2538          * IPI/NMI broadcasts when shutting down CPUs. Invocation from
2539          * regular CPU hotplug is properly serialized.
2540          *
2541          * Note, that the fact that __num_online_cpus is of type atomic_t
2542          * does not protect readers which are not serialized against
2543          * concurrent hotplug operations.
2544          */
2545         if (online) {
2546                 if (!cpumask_test_and_set_cpu(cpu, &__cpu_online_mask))
2547                         atomic_inc(&__num_online_cpus);
2548         } else {
2549                 if (cpumask_test_and_clear_cpu(cpu, &__cpu_online_mask))
2550                         atomic_dec(&__num_online_cpus);
2551         }
2552 }
2553
2554 /*
2555  * Activate the first processor.
2556  */
2557 void __init boot_cpu_init(void)
2558 {
2559         int cpu = smp_processor_id();
2560
2561         /* Mark the boot cpu "present", "online" etc for SMP and UP case */
2562         set_cpu_online(cpu, true);
2563         set_cpu_active(cpu, true);
2564         set_cpu_present(cpu, true);
2565         set_cpu_possible(cpu, true);
2566
2567 #ifdef CONFIG_SMP
2568         __boot_cpu_id = cpu;
2569 #endif
2570 }
2571
2572 /*
2573  * Must be called _AFTER_ setting up the per_cpu areas
2574  */
2575 void __init boot_cpu_hotplug_init(void)
2576 {
2577 #ifdef CONFIG_SMP
2578         cpumask_set_cpu(smp_processor_id(), &cpus_booted_once_mask);
2579 #endif
2580         this_cpu_write(cpuhp_state.state, CPUHP_ONLINE);
2581 }
2582
2583 /*
2584  * These are used for a global "mitigations=" cmdline option for toggling
2585  * optional CPU mitigations.
2586  */
2587 enum cpu_mitigations {
2588         CPU_MITIGATIONS_OFF,
2589         CPU_MITIGATIONS_AUTO,
2590         CPU_MITIGATIONS_AUTO_NOSMT,
2591 };
2592
2593 static enum cpu_mitigations cpu_mitigations __ro_after_init =
2594         CPU_MITIGATIONS_AUTO;
2595
2596 static int __init mitigations_parse_cmdline(char *arg)
2597 {
2598         if (!strcmp(arg, "off"))
2599                 cpu_mitigations = CPU_MITIGATIONS_OFF;
2600         else if (!strcmp(arg, "auto"))
2601                 cpu_mitigations = CPU_MITIGATIONS_AUTO;
2602         else if (!strcmp(arg, "auto,nosmt"))
2603                 cpu_mitigations = CPU_MITIGATIONS_AUTO_NOSMT;
2604         else
2605                 pr_crit("Unsupported mitigations=%s, system may still be vulnerable\n",
2606                         arg);
2607
2608         return 0;
2609 }
2610 early_param("mitigations", mitigations_parse_cmdline);
2611
2612 /* mitigations=off */
2613 bool cpu_mitigations_off(void)
2614 {
2615         return cpu_mitigations == CPU_MITIGATIONS_OFF;
2616 }
2617 EXPORT_SYMBOL_GPL(cpu_mitigations_off);
2618
2619 /* mitigations=auto,nosmt */
2620 bool cpu_mitigations_auto_nosmt(void)
2621 {
2622         return cpu_mitigations == CPU_MITIGATIONS_AUTO_NOSMT;
2623 }
2624 EXPORT_SYMBOL_GPL(cpu_mitigations_auto_nosmt);
This page took 0.171098 seconds and 4 git commands to generate.