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