GNU Linux-libre 4.19.295-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        = hrtimers_dead_cpu,
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         /* Entry state on starting. Interrupts enabled from here on. Transient
1489          * state for synchronsization */
1490         [CPUHP_AP_ONLINE] = {
1491                 .name                   = "ap:online",
1492         },
1493         /*
1494          * Handled on controll processor until the plugged processor manages
1495          * this itself.
1496          */
1497         [CPUHP_TEARDOWN_CPU] = {
1498                 .name                   = "cpu:teardown",
1499                 .startup.single         = NULL,
1500                 .teardown.single        = takedown_cpu,
1501                 .cant_stop              = true,
1502         },
1503         /* Handle smpboot threads park/unpark */
1504         [CPUHP_AP_SMPBOOT_THREADS] = {
1505                 .name                   = "smpboot/threads:online",
1506                 .startup.single         = smpboot_unpark_threads,
1507                 .teardown.single        = smpboot_park_threads,
1508         },
1509         [CPUHP_AP_IRQ_AFFINITY_ONLINE] = {
1510                 .name                   = "irq/affinity:online",
1511                 .startup.single         = irq_affinity_online_cpu,
1512                 .teardown.single        = NULL,
1513         },
1514         [CPUHP_AP_PERF_ONLINE] = {
1515                 .name                   = "perf:online",
1516                 .startup.single         = perf_event_init_cpu,
1517                 .teardown.single        = perf_event_exit_cpu,
1518         },
1519         [CPUHP_AP_WATCHDOG_ONLINE] = {
1520                 .name                   = "lockup_detector:online",
1521                 .startup.single         = lockup_detector_online_cpu,
1522                 .teardown.single        = lockup_detector_offline_cpu,
1523         },
1524         [CPUHP_AP_WORKQUEUE_ONLINE] = {
1525                 .name                   = "workqueue:online",
1526                 .startup.single         = workqueue_online_cpu,
1527                 .teardown.single        = workqueue_offline_cpu,
1528         },
1529         [CPUHP_AP_RANDOM_ONLINE] = {
1530                 .name                   = "random:online",
1531                 .startup.single         = random_online_cpu,
1532                 .teardown.single        = NULL,
1533         },
1534         [CPUHP_AP_RCUTREE_ONLINE] = {
1535                 .name                   = "RCU/tree:online",
1536                 .startup.single         = rcutree_online_cpu,
1537                 .teardown.single        = rcutree_offline_cpu,
1538         },
1539 #endif
1540         /*
1541          * The dynamically registered state space is here
1542          */
1543
1544 #ifdef CONFIG_SMP
1545         /* Last state is scheduler control setting the cpu active */
1546         [CPUHP_AP_ACTIVE] = {
1547                 .name                   = "sched:active",
1548                 .startup.single         = sched_cpu_activate,
1549                 .teardown.single        = sched_cpu_deactivate,
1550         },
1551 #endif
1552
1553         /* CPU is fully up and running. */
1554         [CPUHP_ONLINE] = {
1555                 .name                   = "online",
1556                 .startup.single         = NULL,
1557                 .teardown.single        = NULL,
1558         },
1559 };
1560
1561 /* Sanity check for callbacks */
1562 static int cpuhp_cb_check(enum cpuhp_state state)
1563 {
1564         if (state <= CPUHP_OFFLINE || state >= CPUHP_ONLINE)
1565                 return -EINVAL;
1566         return 0;
1567 }
1568
1569 /*
1570  * Returns a free for dynamic slot assignment of the Online state. The states
1571  * are protected by the cpuhp_slot_states mutex and an empty slot is identified
1572  * by having no name assigned.
1573  */
1574 static int cpuhp_reserve_state(enum cpuhp_state state)
1575 {
1576         enum cpuhp_state i, end;
1577         struct cpuhp_step *step;
1578
1579         switch (state) {
1580         case CPUHP_AP_ONLINE_DYN:
1581                 step = cpuhp_hp_states + CPUHP_AP_ONLINE_DYN;
1582                 end = CPUHP_AP_ONLINE_DYN_END;
1583                 break;
1584         case CPUHP_BP_PREPARE_DYN:
1585                 step = cpuhp_hp_states + CPUHP_BP_PREPARE_DYN;
1586                 end = CPUHP_BP_PREPARE_DYN_END;
1587                 break;
1588         default:
1589                 return -EINVAL;
1590         }
1591
1592         for (i = state; i <= end; i++, step++) {
1593                 if (!step->name)
1594                         return i;
1595         }
1596         WARN(1, "No more dynamic states available for CPU hotplug\n");
1597         return -ENOSPC;
1598 }
1599
1600 static int cpuhp_store_callbacks(enum cpuhp_state state, const char *name,
1601                                  int (*startup)(unsigned int cpu),
1602                                  int (*teardown)(unsigned int cpu),
1603                                  bool multi_instance)
1604 {
1605         /* (Un)Install the callbacks for further cpu hotplug operations */
1606         struct cpuhp_step *sp;
1607         int ret = 0;
1608
1609         /*
1610          * If name is NULL, then the state gets removed.
1611          *
1612          * CPUHP_AP_ONLINE_DYN and CPUHP_BP_PREPARE_DYN are handed out on
1613          * the first allocation from these dynamic ranges, so the removal
1614          * would trigger a new allocation and clear the wrong (already
1615          * empty) state, leaving the callbacks of the to be cleared state
1616          * dangling, which causes wreckage on the next hotplug operation.
1617          */
1618         if (name && (state == CPUHP_AP_ONLINE_DYN ||
1619                      state == CPUHP_BP_PREPARE_DYN)) {
1620                 ret = cpuhp_reserve_state(state);
1621                 if (ret < 0)
1622                         return ret;
1623                 state = ret;
1624         }
1625         sp = cpuhp_get_step(state);
1626         if (name && sp->name)
1627                 return -EBUSY;
1628
1629         sp->startup.single = startup;
1630         sp->teardown.single = teardown;
1631         sp->name = name;
1632         sp->multi_instance = multi_instance;
1633         INIT_HLIST_HEAD(&sp->list);
1634         return ret;
1635 }
1636
1637 static void *cpuhp_get_teardown_cb(enum cpuhp_state state)
1638 {
1639         return cpuhp_get_step(state)->teardown.single;
1640 }
1641
1642 /*
1643  * Call the startup/teardown function for a step either on the AP or
1644  * on the current CPU.
1645  */
1646 static int cpuhp_issue_call(int cpu, enum cpuhp_state state, bool bringup,
1647                             struct hlist_node *node)
1648 {
1649         struct cpuhp_step *sp = cpuhp_get_step(state);
1650         int ret;
1651
1652         /*
1653          * If there's nothing to do, we done.
1654          * Relies on the union for multi_instance.
1655          */
1656         if ((bringup && !sp->startup.single) ||
1657             (!bringup && !sp->teardown.single))
1658                 return 0;
1659         /*
1660          * The non AP bound callbacks can fail on bringup. On teardown
1661          * e.g. module removal we crash for now.
1662          */
1663 #ifdef CONFIG_SMP
1664         if (cpuhp_is_ap_state(state))
1665                 ret = cpuhp_invoke_ap_callback(cpu, state, bringup, node);
1666         else
1667                 ret = cpuhp_invoke_callback(cpu, state, bringup, node, NULL);
1668 #else
1669         ret = cpuhp_invoke_callback(cpu, state, bringup, node, NULL);
1670 #endif
1671         BUG_ON(ret && !bringup);
1672         return ret;
1673 }
1674
1675 /*
1676  * Called from __cpuhp_setup_state on a recoverable failure.
1677  *
1678  * Note: The teardown callbacks for rollback are not allowed to fail!
1679  */
1680 static void cpuhp_rollback_install(int failedcpu, enum cpuhp_state state,
1681                                    struct hlist_node *node)
1682 {
1683         int cpu;
1684
1685         /* Roll back the already executed steps on the other cpus */
1686         for_each_present_cpu(cpu) {
1687                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1688                 int cpustate = st->state;
1689
1690                 if (cpu >= failedcpu)
1691                         break;
1692
1693                 /* Did we invoke the startup call on that cpu ? */
1694                 if (cpustate >= state)
1695                         cpuhp_issue_call(cpu, state, false, node);
1696         }
1697 }
1698
1699 int __cpuhp_state_add_instance_cpuslocked(enum cpuhp_state state,
1700                                           struct hlist_node *node,
1701                                           bool invoke)
1702 {
1703         struct cpuhp_step *sp;
1704         int cpu;
1705         int ret;
1706
1707         lockdep_assert_cpus_held();
1708
1709         sp = cpuhp_get_step(state);
1710         if (sp->multi_instance == false)
1711                 return -EINVAL;
1712
1713         mutex_lock(&cpuhp_state_mutex);
1714
1715         if (!invoke || !sp->startup.multi)
1716                 goto add_node;
1717
1718         /*
1719          * Try to call the startup callback for each present cpu
1720          * depending on the hotplug state of the cpu.
1721          */
1722         for_each_present_cpu(cpu) {
1723                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1724                 int cpustate = st->state;
1725
1726                 if (cpustate < state)
1727                         continue;
1728
1729                 ret = cpuhp_issue_call(cpu, state, true, node);
1730                 if (ret) {
1731                         if (sp->teardown.multi)
1732                                 cpuhp_rollback_install(cpu, state, node);
1733                         goto unlock;
1734                 }
1735         }
1736 add_node:
1737         ret = 0;
1738         hlist_add_head(node, &sp->list);
1739 unlock:
1740         mutex_unlock(&cpuhp_state_mutex);
1741         return ret;
1742 }
1743
1744 int __cpuhp_state_add_instance(enum cpuhp_state state, struct hlist_node *node,
1745                                bool invoke)
1746 {
1747         int ret;
1748
1749         cpus_read_lock();
1750         ret = __cpuhp_state_add_instance_cpuslocked(state, node, invoke);
1751         cpus_read_unlock();
1752         return ret;
1753 }
1754 EXPORT_SYMBOL_GPL(__cpuhp_state_add_instance);
1755
1756 /**
1757  * __cpuhp_setup_state_cpuslocked - Setup the callbacks for an hotplug machine state
1758  * @state:              The state to setup
1759  * @invoke:             If true, the startup function is invoked for cpus where
1760  *                      cpu state >= @state
1761  * @startup:            startup callback function
1762  * @teardown:           teardown callback function
1763  * @multi_instance:     State is set up for multiple instances which get
1764  *                      added afterwards.
1765  *
1766  * The caller needs to hold cpus read locked while calling this function.
1767  * Returns:
1768  *   On success:
1769  *      Positive state number if @state is CPUHP_AP_ONLINE_DYN
1770  *      0 for all other states
1771  *   On failure: proper (negative) error code
1772  */
1773 int __cpuhp_setup_state_cpuslocked(enum cpuhp_state state,
1774                                    const char *name, bool invoke,
1775                                    int (*startup)(unsigned int cpu),
1776                                    int (*teardown)(unsigned int cpu),
1777                                    bool multi_instance)
1778 {
1779         int cpu, ret = 0;
1780         bool dynstate;
1781
1782         lockdep_assert_cpus_held();
1783
1784         if (cpuhp_cb_check(state) || !name)
1785                 return -EINVAL;
1786
1787         mutex_lock(&cpuhp_state_mutex);
1788
1789         ret = cpuhp_store_callbacks(state, name, startup, teardown,
1790                                     multi_instance);
1791
1792         dynstate = state == CPUHP_AP_ONLINE_DYN;
1793         if (ret > 0 && dynstate) {
1794                 state = ret;
1795                 ret = 0;
1796         }
1797
1798         if (ret || !invoke || !startup)
1799                 goto out;
1800
1801         /*
1802          * Try to call the startup callback for each present cpu
1803          * depending on the hotplug state of the cpu.
1804          */
1805         for_each_present_cpu(cpu) {
1806                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1807                 int cpustate = st->state;
1808
1809                 if (cpustate < state)
1810                         continue;
1811
1812                 ret = cpuhp_issue_call(cpu, state, true, NULL);
1813                 if (ret) {
1814                         if (teardown)
1815                                 cpuhp_rollback_install(cpu, state, NULL);
1816                         cpuhp_store_callbacks(state, NULL, NULL, NULL, false);
1817                         goto out;
1818                 }
1819         }
1820 out:
1821         mutex_unlock(&cpuhp_state_mutex);
1822         /*
1823          * If the requested state is CPUHP_AP_ONLINE_DYN, return the
1824          * dynamically allocated state in case of success.
1825          */
1826         if (!ret && dynstate)
1827                 return state;
1828         return ret;
1829 }
1830 EXPORT_SYMBOL(__cpuhp_setup_state_cpuslocked);
1831
1832 int __cpuhp_setup_state(enum cpuhp_state state,
1833                         const char *name, bool invoke,
1834                         int (*startup)(unsigned int cpu),
1835                         int (*teardown)(unsigned int cpu),
1836                         bool multi_instance)
1837 {
1838         int ret;
1839
1840         cpus_read_lock();
1841         ret = __cpuhp_setup_state_cpuslocked(state, name, invoke, startup,
1842                                              teardown, multi_instance);
1843         cpus_read_unlock();
1844         return ret;
1845 }
1846 EXPORT_SYMBOL(__cpuhp_setup_state);
1847
1848 int __cpuhp_state_remove_instance(enum cpuhp_state state,
1849                                   struct hlist_node *node, bool invoke)
1850 {
1851         struct cpuhp_step *sp = cpuhp_get_step(state);
1852         int cpu;
1853
1854         BUG_ON(cpuhp_cb_check(state));
1855
1856         if (!sp->multi_instance)
1857                 return -EINVAL;
1858
1859         cpus_read_lock();
1860         mutex_lock(&cpuhp_state_mutex);
1861
1862         if (!invoke || !cpuhp_get_teardown_cb(state))
1863                 goto remove;
1864         /*
1865          * Call the teardown callback for each present cpu depending
1866          * on the hotplug state of the cpu. This function is not
1867          * allowed to fail currently!
1868          */
1869         for_each_present_cpu(cpu) {
1870                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1871                 int cpustate = st->state;
1872
1873                 if (cpustate >= state)
1874                         cpuhp_issue_call(cpu, state, false, node);
1875         }
1876
1877 remove:
1878         hlist_del(node);
1879         mutex_unlock(&cpuhp_state_mutex);
1880         cpus_read_unlock();
1881
1882         return 0;
1883 }
1884 EXPORT_SYMBOL_GPL(__cpuhp_state_remove_instance);
1885
1886 /**
1887  * __cpuhp_remove_state_cpuslocked - Remove the callbacks for an hotplug machine state
1888  * @state:      The state to remove
1889  * @invoke:     If true, the teardown function is invoked for cpus where
1890  *              cpu state >= @state
1891  *
1892  * The caller needs to hold cpus read locked while calling this function.
1893  * The teardown callback is currently not allowed to fail. Think
1894  * about module removal!
1895  */
1896 void __cpuhp_remove_state_cpuslocked(enum cpuhp_state state, bool invoke)
1897 {
1898         struct cpuhp_step *sp = cpuhp_get_step(state);
1899         int cpu;
1900
1901         BUG_ON(cpuhp_cb_check(state));
1902
1903         lockdep_assert_cpus_held();
1904
1905         mutex_lock(&cpuhp_state_mutex);
1906         if (sp->multi_instance) {
1907                 WARN(!hlist_empty(&sp->list),
1908                      "Error: Removing state %d which has instances left.\n",
1909                      state);
1910                 goto remove;
1911         }
1912
1913         if (!invoke || !cpuhp_get_teardown_cb(state))
1914                 goto remove;
1915
1916         /*
1917          * Call the teardown callback for each present cpu depending
1918          * on the hotplug state of the cpu. This function is not
1919          * allowed to fail currently!
1920          */
1921         for_each_present_cpu(cpu) {
1922                 struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1923                 int cpustate = st->state;
1924
1925                 if (cpustate >= state)
1926                         cpuhp_issue_call(cpu, state, false, NULL);
1927         }
1928 remove:
1929         cpuhp_store_callbacks(state, NULL, NULL, NULL, false);
1930         mutex_unlock(&cpuhp_state_mutex);
1931 }
1932 EXPORT_SYMBOL(__cpuhp_remove_state_cpuslocked);
1933
1934 void __cpuhp_remove_state(enum cpuhp_state state, bool invoke)
1935 {
1936         cpus_read_lock();
1937         __cpuhp_remove_state_cpuslocked(state, invoke);
1938         cpus_read_unlock();
1939 }
1940 EXPORT_SYMBOL(__cpuhp_remove_state);
1941
1942 #if defined(CONFIG_SYSFS) && defined(CONFIG_HOTPLUG_CPU)
1943 static ssize_t show_cpuhp_state(struct device *dev,
1944                                 struct device_attribute *attr, char *buf)
1945 {
1946         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
1947
1948         return sprintf(buf, "%d\n", st->state);
1949 }
1950 static DEVICE_ATTR(state, 0444, show_cpuhp_state, NULL);
1951
1952 static ssize_t write_cpuhp_target(struct device *dev,
1953                                   struct device_attribute *attr,
1954                                   const char *buf, size_t count)
1955 {
1956         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
1957         struct cpuhp_step *sp;
1958         int target, ret;
1959
1960         ret = kstrtoint(buf, 10, &target);
1961         if (ret)
1962                 return ret;
1963
1964 #ifdef CONFIG_CPU_HOTPLUG_STATE_CONTROL
1965         if (target < CPUHP_OFFLINE || target > CPUHP_ONLINE)
1966                 return -EINVAL;
1967 #else
1968         if (target != CPUHP_OFFLINE && target != CPUHP_ONLINE)
1969                 return -EINVAL;
1970 #endif
1971
1972         ret = lock_device_hotplug_sysfs();
1973         if (ret)
1974                 return ret;
1975
1976         mutex_lock(&cpuhp_state_mutex);
1977         sp = cpuhp_get_step(target);
1978         ret = !sp->name || sp->cant_stop ? -EINVAL : 0;
1979         mutex_unlock(&cpuhp_state_mutex);
1980         if (ret)
1981                 goto out;
1982
1983         if (st->state < target)
1984                 ret = do_cpu_up(dev->id, target);
1985         else
1986                 ret = do_cpu_down(dev->id, target);
1987 out:
1988         unlock_device_hotplug();
1989         return ret ? ret : count;
1990 }
1991
1992 static ssize_t show_cpuhp_target(struct device *dev,
1993                                  struct device_attribute *attr, char *buf)
1994 {
1995         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
1996
1997         return sprintf(buf, "%d\n", st->target);
1998 }
1999 static DEVICE_ATTR(target, 0644, show_cpuhp_target, write_cpuhp_target);
2000
2001
2002 static ssize_t write_cpuhp_fail(struct device *dev,
2003                                 struct device_attribute *attr,
2004                                 const char *buf, size_t count)
2005 {
2006         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2007         struct cpuhp_step *sp;
2008         int fail, ret;
2009
2010         ret = kstrtoint(buf, 10, &fail);
2011         if (ret)
2012                 return ret;
2013
2014         if (fail < CPUHP_OFFLINE || fail > CPUHP_ONLINE)
2015                 return -EINVAL;
2016
2017         /*
2018          * Cannot fail STARTING/DYING callbacks.
2019          */
2020         if (cpuhp_is_atomic_state(fail))
2021                 return -EINVAL;
2022
2023         /*
2024          * Cannot fail anything that doesn't have callbacks.
2025          */
2026         mutex_lock(&cpuhp_state_mutex);
2027         sp = cpuhp_get_step(fail);
2028         if (!sp->startup.single && !sp->teardown.single)
2029                 ret = -EINVAL;
2030         mutex_unlock(&cpuhp_state_mutex);
2031         if (ret)
2032                 return ret;
2033
2034         st->fail = fail;
2035
2036         return count;
2037 }
2038
2039 static ssize_t show_cpuhp_fail(struct device *dev,
2040                                struct device_attribute *attr, char *buf)
2041 {
2042         struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2043
2044         return sprintf(buf, "%d\n", st->fail);
2045 }
2046
2047 static DEVICE_ATTR(fail, 0644, show_cpuhp_fail, write_cpuhp_fail);
2048
2049 static struct attribute *cpuhp_cpu_attrs[] = {
2050         &dev_attr_state.attr,
2051         &dev_attr_target.attr,
2052         &dev_attr_fail.attr,
2053         NULL
2054 };
2055
2056 static const struct attribute_group cpuhp_cpu_attr_group = {
2057         .attrs = cpuhp_cpu_attrs,
2058         .name = "hotplug",
2059         NULL
2060 };
2061
2062 static ssize_t show_cpuhp_states(struct device *dev,
2063                                  struct device_attribute *attr, char *buf)
2064 {
2065         ssize_t cur, res = 0;
2066         int i;
2067
2068         mutex_lock(&cpuhp_state_mutex);
2069         for (i = CPUHP_OFFLINE; i <= CPUHP_ONLINE; i++) {
2070                 struct cpuhp_step *sp = cpuhp_get_step(i);
2071
2072                 if (sp->name) {
2073                         cur = sprintf(buf, "%3d: %s\n", i, sp->name);
2074                         buf += cur;
2075                         res += cur;
2076                 }
2077         }
2078         mutex_unlock(&cpuhp_state_mutex);
2079         return res;
2080 }
2081 static DEVICE_ATTR(states, 0444, show_cpuhp_states, NULL);
2082
2083 static struct attribute *cpuhp_cpu_root_attrs[] = {
2084         &dev_attr_states.attr,
2085         NULL
2086 };
2087
2088 static const struct attribute_group cpuhp_cpu_root_attr_group = {
2089         .attrs = cpuhp_cpu_root_attrs,
2090         .name = "hotplug",
2091         NULL
2092 };
2093
2094 #ifdef CONFIG_HOTPLUG_SMT
2095
2096 static const char *smt_states[] = {
2097         [CPU_SMT_ENABLED]               = "on",
2098         [CPU_SMT_DISABLED]              = "off",
2099         [CPU_SMT_FORCE_DISABLED]        = "forceoff",
2100         [CPU_SMT_NOT_SUPPORTED]         = "notsupported",
2101 };
2102
2103 static ssize_t
2104 show_smt_control(struct device *dev, struct device_attribute *attr, char *buf)
2105 {
2106         return snprintf(buf, PAGE_SIZE - 2, "%s\n", smt_states[cpu_smt_control]);
2107 }
2108
2109 static void cpuhp_offline_cpu_device(unsigned int cpu)
2110 {
2111         struct device *dev = get_cpu_device(cpu);
2112
2113         dev->offline = true;
2114         /* Tell user space about the state change */
2115         kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
2116 }
2117
2118 static void cpuhp_online_cpu_device(unsigned int cpu)
2119 {
2120         struct device *dev = get_cpu_device(cpu);
2121
2122         dev->offline = false;
2123         /* Tell user space about the state change */
2124         kobject_uevent(&dev->kobj, KOBJ_ONLINE);
2125 }
2126
2127 int cpuhp_smt_disable(enum cpuhp_smt_control ctrlval)
2128 {
2129         int cpu, ret = 0;
2130
2131         cpu_maps_update_begin();
2132         for_each_online_cpu(cpu) {
2133                 if (topology_is_primary_thread(cpu))
2134                         continue;
2135                 ret = cpu_down_maps_locked(cpu, CPUHP_OFFLINE);
2136                 if (ret)
2137                         break;
2138                 /*
2139                  * As this needs to hold the cpu maps lock it's impossible
2140                  * to call device_offline() because that ends up calling
2141                  * cpu_down() which takes cpu maps lock. cpu maps lock
2142                  * needs to be held as this might race against in kernel
2143                  * abusers of the hotplug machinery (thermal management).
2144                  *
2145                  * So nothing would update device:offline state. That would
2146                  * leave the sysfs entry stale and prevent onlining after
2147                  * smt control has been changed to 'off' again. This is
2148                  * called under the sysfs hotplug lock, so it is properly
2149                  * serialized against the regular offline usage.
2150                  */
2151                 cpuhp_offline_cpu_device(cpu);
2152         }
2153         if (!ret)
2154                 cpu_smt_control = ctrlval;
2155         cpu_maps_update_done();
2156         return ret;
2157 }
2158
2159 int cpuhp_smt_enable(void)
2160 {
2161         int cpu, ret = 0;
2162
2163         cpu_maps_update_begin();
2164         cpu_smt_control = CPU_SMT_ENABLED;
2165         for_each_present_cpu(cpu) {
2166                 /* Skip online CPUs and CPUs on offline nodes */
2167                 if (cpu_online(cpu) || !node_online(cpu_to_node(cpu)))
2168                         continue;
2169                 ret = _cpu_up(cpu, 0, CPUHP_ONLINE);
2170                 if (ret)
2171                         break;
2172                 /* See comment in cpuhp_smt_disable() */
2173                 cpuhp_online_cpu_device(cpu);
2174         }
2175         cpu_maps_update_done();
2176         return ret;
2177 }
2178
2179 static ssize_t
2180 store_smt_control(struct device *dev, struct device_attribute *attr,
2181                   const char *buf, size_t count)
2182 {
2183         int ctrlval, ret;
2184
2185         if (sysfs_streq(buf, "on"))
2186                 ctrlval = CPU_SMT_ENABLED;
2187         else if (sysfs_streq(buf, "off"))
2188                 ctrlval = CPU_SMT_DISABLED;
2189         else if (sysfs_streq(buf, "forceoff"))
2190                 ctrlval = CPU_SMT_FORCE_DISABLED;
2191         else
2192                 return -EINVAL;
2193
2194         if (cpu_smt_control == CPU_SMT_FORCE_DISABLED)
2195                 return -EPERM;
2196
2197         if (cpu_smt_control == CPU_SMT_NOT_SUPPORTED)
2198                 return -ENODEV;
2199
2200         ret = lock_device_hotplug_sysfs();
2201         if (ret)
2202                 return ret;
2203
2204         if (ctrlval != cpu_smt_control) {
2205                 switch (ctrlval) {
2206                 case CPU_SMT_ENABLED:
2207                         ret = cpuhp_smt_enable();
2208                         break;
2209                 case CPU_SMT_DISABLED:
2210                 case CPU_SMT_FORCE_DISABLED:
2211                         ret = cpuhp_smt_disable(ctrlval);
2212                         break;
2213                 }
2214         }
2215
2216         unlock_device_hotplug();
2217         return ret ? ret : count;
2218 }
2219 static DEVICE_ATTR(control, 0644, show_smt_control, store_smt_control);
2220
2221 static ssize_t
2222 show_smt_active(struct device *dev, struct device_attribute *attr, char *buf)
2223 {
2224         bool active = topology_max_smt_threads() > 1;
2225
2226         return snprintf(buf, PAGE_SIZE - 2, "%d\n", active);
2227 }
2228 static DEVICE_ATTR(active, 0444, show_smt_active, NULL);
2229
2230 static struct attribute *cpuhp_smt_attrs[] = {
2231         &dev_attr_control.attr,
2232         &dev_attr_active.attr,
2233         NULL
2234 };
2235
2236 static const struct attribute_group cpuhp_smt_attr_group = {
2237         .attrs = cpuhp_smt_attrs,
2238         .name = "smt",
2239         NULL
2240 };
2241
2242 static int __init cpu_smt_state_init(void)
2243 {
2244         return sysfs_create_group(&cpu_subsys.dev_root->kobj,
2245                                   &cpuhp_smt_attr_group);
2246 }
2247
2248 #else
2249 static inline int cpu_smt_state_init(void) { return 0; }
2250 #endif
2251
2252 static int __init cpuhp_sysfs_init(void)
2253 {
2254         int cpu, ret;
2255
2256         ret = cpu_smt_state_init();
2257         if (ret)
2258                 return ret;
2259
2260         ret = sysfs_create_group(&cpu_subsys.dev_root->kobj,
2261                                  &cpuhp_cpu_root_attr_group);
2262         if (ret)
2263                 return ret;
2264
2265         for_each_possible_cpu(cpu) {
2266                 struct device *dev = get_cpu_device(cpu);
2267
2268                 if (!dev)
2269                         continue;
2270                 ret = sysfs_create_group(&dev->kobj, &cpuhp_cpu_attr_group);
2271                 if (ret)
2272                         return ret;
2273         }
2274         return 0;
2275 }
2276 device_initcall(cpuhp_sysfs_init);
2277 #endif
2278
2279 /*
2280  * cpu_bit_bitmap[] is a special, "compressed" data structure that
2281  * represents all NR_CPUS bits binary values of 1<<nr.
2282  *
2283  * It is used by cpumask_of() to get a constant address to a CPU
2284  * mask value that has a single bit set only.
2285  */
2286
2287 /* cpu_bit_bitmap[0] is empty - so we can back into it */
2288 #define MASK_DECLARE_1(x)       [x+1][0] = (1UL << (x))
2289 #define MASK_DECLARE_2(x)       MASK_DECLARE_1(x), MASK_DECLARE_1(x+1)
2290 #define MASK_DECLARE_4(x)       MASK_DECLARE_2(x), MASK_DECLARE_2(x+2)
2291 #define MASK_DECLARE_8(x)       MASK_DECLARE_4(x), MASK_DECLARE_4(x+4)
2292
2293 const unsigned long cpu_bit_bitmap[BITS_PER_LONG+1][BITS_TO_LONGS(NR_CPUS)] = {
2294
2295         MASK_DECLARE_8(0),      MASK_DECLARE_8(8),
2296         MASK_DECLARE_8(16),     MASK_DECLARE_8(24),
2297 #if BITS_PER_LONG > 32
2298         MASK_DECLARE_8(32),     MASK_DECLARE_8(40),
2299         MASK_DECLARE_8(48),     MASK_DECLARE_8(56),
2300 #endif
2301 };
2302 EXPORT_SYMBOL_GPL(cpu_bit_bitmap);
2303
2304 const DECLARE_BITMAP(cpu_all_bits, NR_CPUS) = CPU_BITS_ALL;
2305 EXPORT_SYMBOL(cpu_all_bits);
2306
2307 #ifdef CONFIG_INIT_ALL_POSSIBLE
2308 struct cpumask __cpu_possible_mask __read_mostly
2309         = {CPU_BITS_ALL};
2310 #else
2311 struct cpumask __cpu_possible_mask __read_mostly;
2312 #endif
2313 EXPORT_SYMBOL(__cpu_possible_mask);
2314
2315 struct cpumask __cpu_online_mask __read_mostly;
2316 EXPORT_SYMBOL(__cpu_online_mask);
2317
2318 struct cpumask __cpu_present_mask __read_mostly;
2319 EXPORT_SYMBOL(__cpu_present_mask);
2320
2321 struct cpumask __cpu_active_mask __read_mostly;
2322 EXPORT_SYMBOL(__cpu_active_mask);
2323
2324 void init_cpu_present(const struct cpumask *src)
2325 {
2326         cpumask_copy(&__cpu_present_mask, src);
2327 }
2328
2329 void init_cpu_possible(const struct cpumask *src)
2330 {
2331         cpumask_copy(&__cpu_possible_mask, src);
2332 }
2333
2334 void init_cpu_online(const struct cpumask *src)
2335 {
2336         cpumask_copy(&__cpu_online_mask, src);
2337 }
2338
2339 /*
2340  * Activate the first processor.
2341  */
2342 void __init boot_cpu_init(void)
2343 {
2344         int cpu = smp_processor_id();
2345
2346         /* Mark the boot cpu "present", "online" etc for SMP and UP case */
2347         set_cpu_online(cpu, true);
2348         set_cpu_active(cpu, true);
2349         set_cpu_present(cpu, true);
2350         set_cpu_possible(cpu, true);
2351
2352 #ifdef CONFIG_SMP
2353         __boot_cpu_id = cpu;
2354 #endif
2355 }
2356
2357 /*
2358  * Must be called _AFTER_ setting up the per_cpu areas
2359  */
2360 void __init boot_cpu_hotplug_init(void)
2361 {
2362 #ifdef CONFIG_SMP
2363         this_cpu_write(cpuhp_state.booted_once, true);
2364 #endif
2365         this_cpu_write(cpuhp_state.state, CPUHP_ONLINE);
2366 }
2367
2368 /*
2369  * These are used for a global "mitigations=" cmdline option for toggling
2370  * optional CPU mitigations.
2371  */
2372 enum cpu_mitigations {
2373         CPU_MITIGATIONS_OFF,
2374         CPU_MITIGATIONS_AUTO,
2375         CPU_MITIGATIONS_AUTO_NOSMT,
2376 };
2377
2378 static enum cpu_mitigations cpu_mitigations __ro_after_init =
2379         CPU_MITIGATIONS_AUTO;
2380
2381 static int __init mitigations_parse_cmdline(char *arg)
2382 {
2383         if (!strcmp(arg, "off"))
2384                 cpu_mitigations = CPU_MITIGATIONS_OFF;
2385         else if (!strcmp(arg, "auto"))
2386                 cpu_mitigations = CPU_MITIGATIONS_AUTO;
2387         else if (!strcmp(arg, "auto,nosmt"))
2388                 cpu_mitigations = CPU_MITIGATIONS_AUTO_NOSMT;
2389         else
2390                 pr_crit("Unsupported mitigations=%s, system may still be vulnerable\n",
2391                         arg);
2392
2393         return 0;
2394 }
2395 early_param("mitigations", mitigations_parse_cmdline);
2396
2397 /* mitigations=off */
2398 bool cpu_mitigations_off(void)
2399 {
2400         return cpu_mitigations == CPU_MITIGATIONS_OFF;
2401 }
2402 EXPORT_SYMBOL_GPL(cpu_mitigations_off);
2403
2404 /* mitigations=auto,nosmt */
2405 bool cpu_mitigations_auto_nosmt(void)
2406 {
2407         return cpu_mitigations == CPU_MITIGATIONS_AUTO_NOSMT;
2408 }
2409 EXPORT_SYMBOL_GPL(cpu_mitigations_auto_nosmt);