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