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