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