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