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