• 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 "sched/sched.h"
49 #include "smpboot.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 	cpu_maps_update_begin();
1133 	err = cpu_down_maps_locked(cpu, target);
1134 	cpu_maps_update_done();
1135 	return err;
1136 }
1137 
1138 /**
1139  * cpu_device_down - Bring down a cpu device
1140  * @dev: Pointer to the cpu device to offline
1141  *
1142  * This function is meant to be used by device core cpu subsystem only.
1143  *
1144  * Other subsystems should use remove_cpu() instead.
1145  */
cpu_device_down(struct device * dev)1146 int cpu_device_down(struct device *dev)
1147 {
1148 	return cpu_down(dev->id, CPUHP_OFFLINE);
1149 }
1150 
remove_cpu(unsigned int cpu)1151 int remove_cpu(unsigned int cpu)
1152 {
1153 	int ret;
1154 
1155 	lock_device_hotplug();
1156 	ret = device_offline(get_cpu_device(cpu));
1157 	unlock_device_hotplug();
1158 
1159 	return ret;
1160 }
1161 EXPORT_SYMBOL_GPL(remove_cpu);
1162 
__pause_drain_rq(struct cpumask * cpus)1163 int __pause_drain_rq(struct cpumask *cpus)
1164 {
1165 	unsigned int cpu;
1166 	int err = 0;
1167 
1168 	/*
1169 	 * Disabling preemption avoids that one of the stopper, started from
1170 	 * sched_cpu_drain_rq(), blocks firing draining for the whole cpumask.
1171 	 */
1172 	preempt_disable();
1173 	for_each_cpu(cpu, cpus) {
1174 		err = sched_cpu_drain_rq(cpu);
1175 		if (err)
1176 			break;
1177 	}
1178 	preempt_enable();
1179 
1180 	return err;
1181 }
1182 
__wait_drain_rq(struct cpumask * cpus)1183 void __wait_drain_rq(struct cpumask *cpus)
1184 {
1185 	unsigned int cpu;
1186 
1187 	for_each_cpu(cpu, cpus)
1188 		sched_cpu_drain_rq_wait(cpu);
1189 }
1190 
1191 /* if rt task, set to cfs and return previous prio */
pause_reduce_prio(void)1192 static int pause_reduce_prio(void)
1193 {
1194 	int prev_prio = -1;
1195 
1196 	if (current->prio < MAX_RT_PRIO) {
1197 		struct sched_param param = { .sched_priority = 0 };
1198 
1199 		prev_prio = current->prio;
1200 		sched_setscheduler_nocheck(current, SCHED_NORMAL, &param);
1201 	}
1202 
1203 	return prev_prio;
1204 }
1205 
1206 /* if previous prio was set, restore */
pause_restore_prio(int prev_prio)1207 static void pause_restore_prio(int prev_prio)
1208 {
1209 	if (prev_prio >= 0 && prev_prio < MAX_RT_PRIO) {
1210 		struct sched_param param = { .sched_priority = MAX_RT_PRIO-1-prev_prio };
1211 
1212 		sched_setscheduler_nocheck(current, SCHED_FIFO, &param);
1213 	}
1214 }
1215 
pause_cpus(struct cpumask * cpus)1216 int pause_cpus(struct cpumask *cpus)
1217 {
1218 	int err = 0;
1219 	int cpu;
1220 	u64 start_time = 0;
1221 	int prev_prio;
1222 
1223 	start_time = sched_clock();
1224 
1225 	cpu_maps_update_begin();
1226 
1227 	if (cpu_hotplug_disabled) {
1228 		err = -EBUSY;
1229 		goto err_cpu_maps_update;
1230 	}
1231 
1232 	/* Pausing an already inactive CPU isn't an error */
1233 	cpumask_and(cpus, cpus, cpu_active_mask);
1234 
1235 	for_each_cpu(cpu, cpus) {
1236 		if (!cpu_online(cpu) || dl_bw_check_overflow(cpu) ||
1237 			get_cpu_device(cpu)->offline_disabled == true) {
1238 			err = -EBUSY;
1239 			goto err_cpu_maps_update;
1240 		}
1241 	}
1242 
1243 	if (cpumask_weight(cpus) >= num_active_cpus()) {
1244 		err = -EBUSY;
1245 		goto err_cpu_maps_update;
1246 	}
1247 
1248 	if (cpumask_empty(cpus))
1249 		goto err_cpu_maps_update;
1250 
1251 	/*
1252 	 * Lazy migration:
1253 	 *
1254 	 * We do care about how fast a CPU can go idle and stay this in this
1255 	 * state. If we try to take the cpus_write_lock() here, we would have
1256 	 * to wait for a few dozens of ms, as this function might schedule.
1257 	 * However, we can, as a first step, flip the active mask and migrate
1258 	 * anything currently on the run-queue, to give a chance to the paused
1259 	 * CPUs to reach quickly an idle state. There's a risk meanwhile for
1260 	 * another CPU to observe an out-of-date active_mask or to incompletely
1261 	 * update a cpuset. Both problems would be resolved later in the slow
1262 	 * path, which ensures active_mask synchronization, triggers a cpuset
1263 	 * rebuild and migrate any task that would have escaped the lazy
1264 	 * migration.
1265 	 */
1266 	for_each_cpu(cpu, cpus)
1267 		set_cpu_active(cpu, false);
1268 	err = __pause_drain_rq(cpus);
1269 	if (err) {
1270 		__wait_drain_rq(cpus);
1271 		for_each_cpu(cpu, cpus)
1272 			set_cpu_active(cpu, true);
1273 		goto err_cpu_maps_update;
1274 	}
1275 
1276 	prev_prio = pause_reduce_prio();
1277 
1278 	/*
1279 	 * Slow path deactivation:
1280 	 *
1281 	 * Now that paused CPUs are most likely idle, we can go through a
1282 	 * complete scheduler deactivation.
1283 	 *
1284 	 * The cpu_active_mask being already set and cpus_write_lock calling
1285 	 * synchronize_rcu(), we know that all preempt-disabled and RCU users
1286 	 * will observe the updated value.
1287 	 */
1288 	cpus_write_lock();
1289 
1290 	__wait_drain_rq(cpus);
1291 
1292 	cpuhp_tasks_frozen = 0;
1293 
1294 	if (sched_cpus_deactivate_nosync(cpus)) {
1295 		err = -EBUSY;
1296 		goto err_cpus_write_unlock;
1297 	}
1298 
1299 	err = __pause_drain_rq(cpus);
1300 	__wait_drain_rq(cpus);
1301 	if (err) {
1302 		for_each_cpu(cpu, cpus)
1303 			sched_cpu_activate(cpu);
1304 		goto err_cpus_write_unlock;
1305 	}
1306 
1307 	/*
1308 	 * Even if living on the side of the regular HP path, pause is using
1309 	 * one of the HP step (CPUHP_AP_ACTIVE). This should be reflected on the
1310 	 * current state of the CPU.
1311 	 */
1312 	for_each_cpu(cpu, cpus) {
1313 		struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1314 
1315 		st->state = CPUHP_AP_ACTIVE - 1;
1316 		st->target = st->state;
1317 	}
1318 
1319 err_cpus_write_unlock:
1320 	cpus_write_unlock();
1321 	pause_restore_prio(prev_prio);
1322 err_cpu_maps_update:
1323 	cpu_maps_update_done();
1324 
1325 	trace_cpuhp_pause(cpus, start_time, 1);
1326 
1327 	return err;
1328 }
1329 EXPORT_SYMBOL_GPL(pause_cpus);
1330 
resume_cpus(struct cpumask * cpus)1331 int resume_cpus(struct cpumask *cpus)
1332 {
1333 	unsigned int cpu;
1334 	int err = 0;
1335 	u64 start_time = 0;
1336 	int prev_prio;
1337 
1338 	start_time = sched_clock();
1339 
1340 	cpu_maps_update_begin();
1341 
1342 	if (cpu_hotplug_disabled) {
1343 		err = -EBUSY;
1344 		goto err_cpu_maps_update;
1345 	}
1346 
1347 	/* Resuming an already active CPU isn't an error */
1348 	cpumask_andnot(cpus, cpus, cpu_active_mask);
1349 
1350 	for_each_cpu(cpu, cpus) {
1351 		if (!cpu_online(cpu)) {
1352 			err = -EBUSY;
1353 			goto err_cpu_maps_update;
1354 		}
1355 	}
1356 
1357 	if (cpumask_empty(cpus))
1358 		goto err_cpu_maps_update;
1359 
1360 	for_each_cpu(cpu, cpus)
1361 		set_cpu_active(cpu, true);
1362 
1363 	trace_android_rvh_resume_cpus(cpus, &err);
1364 	if (err)
1365 		goto err_cpu_maps_update;
1366 
1367 	prev_prio = pause_reduce_prio();
1368 
1369 	/* Lazy Resume. Build domains through schedule a workqueue on
1370 	 * resuming cpu. This is so that the resuming cpu can work more
1371 	 * early, and cannot add additional load to other busy cpu.
1372 	 */
1373 	cpuset_update_active_cpus_affine(cpumask_first(cpus));
1374 
1375 	cpus_write_lock();
1376 
1377 	cpuhp_tasks_frozen = 0;
1378 
1379 	if (sched_cpus_activate(cpus)) {
1380 		err = -EBUSY;
1381 		goto err_cpus_write_unlock;
1382 	}
1383 
1384 	/*
1385 	 * see pause_cpus.
1386 	 */
1387 	for_each_cpu(cpu, cpus) {
1388 		struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1389 
1390 		st->state = CPUHP_ONLINE;
1391 		st->target = st->state;
1392 	}
1393 
1394 err_cpus_write_unlock:
1395 	cpus_write_unlock();
1396 	pause_restore_prio(prev_prio);
1397 err_cpu_maps_update:
1398 	cpu_maps_update_done();
1399 
1400 	trace_cpuhp_pause(cpus, start_time, 0);
1401 
1402 	return err;
1403 }
1404 EXPORT_SYMBOL_GPL(resume_cpus);
1405 
smp_shutdown_nonboot_cpus(unsigned int primary_cpu)1406 void smp_shutdown_nonboot_cpus(unsigned int primary_cpu)
1407 {
1408 	unsigned int cpu;
1409 	int error;
1410 
1411 	cpu_maps_update_begin();
1412 
1413 	/*
1414 	 * Make certain the cpu I'm about to reboot on is online.
1415 	 *
1416 	 * This is inline to what migrate_to_reboot_cpu() already do.
1417 	 */
1418 	if (!cpu_online(primary_cpu))
1419 		primary_cpu = cpumask_first(cpu_online_mask);
1420 
1421 	for_each_online_cpu(cpu) {
1422 		if (cpu == primary_cpu)
1423 			continue;
1424 
1425 		error = cpu_down_maps_locked(cpu, CPUHP_OFFLINE);
1426 		if (error) {
1427 			pr_err("Failed to offline CPU%d - error=%d",
1428 				cpu, error);
1429 			break;
1430 		}
1431 	}
1432 
1433 	/*
1434 	 * Ensure all but the reboot CPU are offline.
1435 	 */
1436 	BUG_ON(num_online_cpus() > 1);
1437 
1438 	/*
1439 	 * Make sure the CPUs won't be enabled by someone else after this
1440 	 * point. Kexec will reboot to a new kernel shortly resetting
1441 	 * everything along the way.
1442 	 */
1443 	cpu_hotplug_disabled++;
1444 
1445 	cpu_maps_update_done();
1446 }
1447 
1448 #else
1449 #define takedown_cpu		NULL
1450 #endif /*CONFIG_HOTPLUG_CPU*/
1451 
1452 /**
1453  * notify_cpu_starting(cpu) - Invoke the callbacks on the starting CPU
1454  * @cpu: cpu that just started
1455  *
1456  * It must be called by the arch code on the new cpu, before the new cpu
1457  * enables interrupts and before the "boot" cpu returns from __cpu_up().
1458  */
notify_cpu_starting(unsigned int cpu)1459 void notify_cpu_starting(unsigned int cpu)
1460 {
1461 	struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1462 	enum cpuhp_state target = min((int)st->target, CPUHP_AP_ONLINE);
1463 	int ret;
1464 
1465 	rcu_cpu_starting(cpu);	/* Enables RCU usage on this CPU. */
1466 	cpumask_set_cpu(cpu, &cpus_booted_once_mask);
1467 	while (st->state < target) {
1468 		st->state++;
1469 		ret = cpuhp_invoke_callback(cpu, st->state, true, NULL, NULL);
1470 		/*
1471 		 * STARTING must not fail!
1472 		 */
1473 		WARN_ON_ONCE(ret);
1474 	}
1475 }
1476 
1477 /*
1478  * Called from the idle task. Wake up the controlling task which brings the
1479  * hotplug thread of the upcoming CPU up and then delegates the rest of the
1480  * online bringup to the hotplug thread.
1481  */
cpuhp_online_idle(enum cpuhp_state state)1482 void cpuhp_online_idle(enum cpuhp_state state)
1483 {
1484 	struct cpuhp_cpu_state *st = this_cpu_ptr(&cpuhp_state);
1485 
1486 	/* Happens for the boot cpu */
1487 	if (state != CPUHP_AP_ONLINE_IDLE)
1488 		return;
1489 
1490 	/*
1491 	 * Unpart the stopper thread before we start the idle loop (and start
1492 	 * scheduling); this ensures the stopper task is always available.
1493 	 */
1494 	stop_machine_unpark(smp_processor_id());
1495 
1496 	st->state = CPUHP_AP_ONLINE_IDLE;
1497 	complete_ap_thread(st, true);
1498 }
1499 
switch_to_rt_policy(void)1500 static int switch_to_rt_policy(void)
1501 {
1502 	struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1503 	unsigned int policy = current->policy;
1504 
1505 	if (policy == SCHED_NORMAL)
1506 		/* Switch to SCHED_FIFO from SCHED_NORMAL. */
1507 		return sched_setscheduler_nocheck(current, SCHED_FIFO, &param);
1508 	else
1509 		return 1;
1510 }
1511 
switch_to_fair_policy(void)1512 static int switch_to_fair_policy(void)
1513 {
1514 	struct sched_param param = { .sched_priority = 0 };
1515 
1516 	return sched_setscheduler_nocheck(current, SCHED_NORMAL, &param);
1517 }
1518 
1519 /* Requires cpu_add_remove_lock to be held */
_cpu_up(unsigned int cpu,int tasks_frozen,enum cpuhp_state target)1520 static int _cpu_up(unsigned int cpu, int tasks_frozen, enum cpuhp_state target)
1521 {
1522 	struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
1523 	struct task_struct *idle;
1524 	int ret = 0;
1525 
1526 	cpus_write_lock();
1527 
1528 	if (!cpu_present(cpu)) {
1529 		ret = -EINVAL;
1530 		goto out;
1531 	}
1532 
1533 	/*
1534 	 * The caller of cpu_up() might have raced with another
1535 	 * caller. Nothing to do.
1536 	 */
1537 	if (st->state >= target)
1538 		goto out;
1539 
1540 	if (st->state == CPUHP_OFFLINE) {
1541 		/* Let it fail before we try to bring the cpu up */
1542 		idle = idle_thread_get(cpu);
1543 		if (IS_ERR(idle)) {
1544 			ret = PTR_ERR(idle);
1545 			goto out;
1546 		}
1547 	}
1548 
1549 	cpuhp_tasks_frozen = tasks_frozen;
1550 
1551 	cpuhp_set_state(st, target);
1552 	/*
1553 	 * If the current CPU state is in the range of the AP hotplug thread,
1554 	 * then we need to kick the thread once more.
1555 	 */
1556 	if (st->state > CPUHP_BRINGUP_CPU) {
1557 		ret = cpuhp_kick_ap_work(cpu);
1558 		/*
1559 		 * The AP side has done the error rollback already. Just
1560 		 * return the error code..
1561 		 */
1562 		if (ret)
1563 			goto out;
1564 	}
1565 
1566 	/*
1567 	 * Try to reach the target state. We max out on the BP at
1568 	 * CPUHP_BRINGUP_CPU. After that the AP hotplug thread is
1569 	 * responsible for bringing it up to the target state.
1570 	 */
1571 	target = min((int)target, CPUHP_BRINGUP_CPU);
1572 	ret = cpuhp_up_callbacks(cpu, st, target);
1573 out:
1574 	cpus_write_unlock();
1575 	arch_smt_update();
1576 	cpu_up_down_serialize_trainwrecks(tasks_frozen);
1577 	return ret;
1578 }
1579 
cpu_up(unsigned int cpu,enum cpuhp_state target)1580 static int cpu_up(unsigned int cpu, enum cpuhp_state target)
1581 {
1582 	int err = 0;
1583 	int switch_err;
1584 
1585 	if (!cpu_possible(cpu)) {
1586 		pr_err("can't online cpu %d because it is not configured as may-hotadd at boot time\n",
1587 		       cpu);
1588 #if defined(CONFIG_IA64)
1589 		pr_err("please check additional_cpus= boot parameter\n");
1590 #endif
1591 		return -EINVAL;
1592 	}
1593 
1594 	trace_android_vh_cpu_up(cpu);
1595 
1596 	/*
1597 	 * CPU hotplug operations consists of many steps and each step
1598 	 * calls a callback of core kernel subsystem. CPU hotplug-in
1599 	 * operation may get preempted by other CFS tasks and whole
1600 	 * operation of cpu hotplug in CPU gets delayed. Switch the
1601 	 * current task to SCHED_FIFO from SCHED_NORMAL, so that
1602 	 * hotplug in operation may complete quickly in heavy loaded
1603 	 * conditions and new CPU will start handle the workload.
1604 	 */
1605 
1606 	switch_err = switch_to_rt_policy();
1607 
1608 	err = try_online_node(cpu_to_node(cpu));
1609 	if (err)
1610 		goto switch_out;
1611 
1612 	cpu_maps_update_begin();
1613 
1614 	if (cpu_hotplug_disabled) {
1615 		err = -EBUSY;
1616 		goto out;
1617 	}
1618 	if (!cpu_smt_allowed(cpu)) {
1619 		err = -EPERM;
1620 		goto out;
1621 	}
1622 
1623 	err = _cpu_up(cpu, 0, target);
1624 out:
1625 	cpu_maps_update_done();
1626 switch_out:
1627 	if (!switch_err) {
1628 		switch_err = switch_to_fair_policy();
1629 		if (switch_err)
1630 			pr_err("Hotplug policy switch err=%d Task %s pid=%d\n",
1631 				switch_err, current->comm, current->pid);
1632 	}
1633 
1634 	return err;
1635 }
1636 
1637 /**
1638  * cpu_device_up - Bring up a cpu device
1639  * @dev: Pointer to the cpu device to online
1640  *
1641  * This function is meant to be used by device core cpu subsystem only.
1642  *
1643  * Other subsystems should use add_cpu() instead.
1644  */
cpu_device_up(struct device * dev)1645 int cpu_device_up(struct device *dev)
1646 {
1647 	return cpu_up(dev->id, CPUHP_ONLINE);
1648 }
1649 
add_cpu(unsigned int cpu)1650 int add_cpu(unsigned int cpu)
1651 {
1652 	int ret;
1653 
1654 	lock_device_hotplug();
1655 	ret = device_online(get_cpu_device(cpu));
1656 	unlock_device_hotplug();
1657 
1658 	return ret;
1659 }
1660 EXPORT_SYMBOL_GPL(add_cpu);
1661 
1662 /**
1663  * bringup_hibernate_cpu - Bring up the CPU that we hibernated on
1664  * @sleep_cpu: The cpu we hibernated on and should be brought up.
1665  *
1666  * On some architectures like arm64, we can hibernate on any CPU, but on
1667  * wake up the CPU we hibernated on might be offline as a side effect of
1668  * using maxcpus= for example.
1669  */
bringup_hibernate_cpu(unsigned int sleep_cpu)1670 int bringup_hibernate_cpu(unsigned int sleep_cpu)
1671 {
1672 	int ret;
1673 
1674 	if (!cpu_online(sleep_cpu)) {
1675 		pr_info("Hibernated on a CPU that is offline! Bringing CPU up.\n");
1676 		ret = cpu_up(sleep_cpu, CPUHP_ONLINE);
1677 		if (ret) {
1678 			pr_err("Failed to bring hibernate-CPU up!\n");
1679 			return ret;
1680 		}
1681 	}
1682 	return 0;
1683 }
1684 
bringup_nonboot_cpus(unsigned int setup_max_cpus)1685 void bringup_nonboot_cpus(unsigned int setup_max_cpus)
1686 {
1687 	unsigned int cpu;
1688 
1689 	for_each_present_cpu(cpu) {
1690 		if (num_online_cpus() >= setup_max_cpus)
1691 			break;
1692 		if (!cpu_online(cpu))
1693 			cpu_up(cpu, CPUHP_ONLINE);
1694 	}
1695 }
1696 
1697 #ifdef CONFIG_PM_SLEEP_SMP
1698 static cpumask_var_t frozen_cpus;
1699 
freeze_secondary_cpus(int primary)1700 int freeze_secondary_cpus(int primary)
1701 {
1702 	int cpu, error = 0;
1703 
1704 	cpu_maps_update_begin();
1705 	if (primary == -1) {
1706 		primary = cpumask_first(cpu_online_mask);
1707 		if (!housekeeping_cpu(primary, HK_FLAG_TIMER))
1708 			primary = housekeeping_any_cpu(HK_FLAG_TIMER);
1709 	} else {
1710 		if (!cpu_online(primary))
1711 			primary = cpumask_first(cpu_online_mask);
1712 	}
1713 
1714 	/*
1715 	 * We take down all of the non-boot CPUs in one shot to avoid races
1716 	 * with the userspace trying to use the CPU hotplug at the same time
1717 	 */
1718 	cpumask_clear(frozen_cpus);
1719 
1720 	pr_info("Disabling non-boot CPUs ...\n");
1721 	for_each_online_cpu(cpu) {
1722 		if (cpu == primary)
1723 			continue;
1724 
1725 		if (pm_wakeup_pending()) {
1726 			pr_info("Wakeup pending. Abort CPU freeze\n");
1727 			error = -EBUSY;
1728 			break;
1729 		}
1730 
1731 		trace_suspend_resume(TPS("CPU_OFF"), cpu, true);
1732 		error = _cpu_down(cpu, 1, CPUHP_OFFLINE);
1733 		trace_suspend_resume(TPS("CPU_OFF"), cpu, false);
1734 		if (!error)
1735 			cpumask_set_cpu(cpu, frozen_cpus);
1736 		else {
1737 			pr_err("Error taking CPU%d down: %d\n", cpu, error);
1738 			break;
1739 		}
1740 	}
1741 
1742 	if (!error)
1743 		BUG_ON(num_online_cpus() > 1);
1744 	else
1745 		pr_err("Non-boot CPUs are not disabled\n");
1746 
1747 	/*
1748 	 * Make sure the CPUs won't be enabled by someone else. We need to do
1749 	 * this even in case of failure as all freeze_secondary_cpus() users are
1750 	 * supposed to do thaw_secondary_cpus() on the failure path.
1751 	 */
1752 	cpu_hotplug_disabled++;
1753 
1754 	cpu_maps_update_done();
1755 	return error;
1756 }
1757 
arch_thaw_secondary_cpus_begin(void)1758 void __weak arch_thaw_secondary_cpus_begin(void)
1759 {
1760 }
1761 
arch_thaw_secondary_cpus_end(void)1762 void __weak arch_thaw_secondary_cpus_end(void)
1763 {
1764 }
1765 
thaw_secondary_cpus(void)1766 void thaw_secondary_cpus(void)
1767 {
1768 	int cpu, error;
1769 	struct device *cpu_device;
1770 
1771 	/* Allow everyone to use the CPU hotplug again */
1772 	cpu_maps_update_begin();
1773 	__cpu_hotplug_enable();
1774 	if (cpumask_empty(frozen_cpus))
1775 		goto out;
1776 
1777 	pr_info("Enabling non-boot CPUs ...\n");
1778 
1779 	arch_thaw_secondary_cpus_begin();
1780 
1781 	for_each_cpu(cpu, frozen_cpus) {
1782 		trace_suspend_resume(TPS("CPU_ON"), cpu, true);
1783 		error = _cpu_up(cpu, 1, CPUHP_ONLINE);
1784 		trace_suspend_resume(TPS("CPU_ON"), cpu, false);
1785 		if (!error) {
1786 			pr_info("CPU%d is up\n", cpu);
1787 			cpu_device = get_cpu_device(cpu);
1788 			if (!cpu_device)
1789 				pr_err("%s: failed to get cpu%d device\n",
1790 				       __func__, cpu);
1791 			else
1792 				kobject_uevent(&cpu_device->kobj, KOBJ_ONLINE);
1793 			continue;
1794 		}
1795 		pr_warn("Error taking CPU%d up: %d\n", cpu, error);
1796 	}
1797 
1798 	arch_thaw_secondary_cpus_end();
1799 
1800 	cpumask_clear(frozen_cpus);
1801 out:
1802 	cpu_maps_update_done();
1803 }
1804 
alloc_frozen_cpus(void)1805 static int __init alloc_frozen_cpus(void)
1806 {
1807 	if (!alloc_cpumask_var(&frozen_cpus, GFP_KERNEL|__GFP_ZERO))
1808 		return -ENOMEM;
1809 	return 0;
1810 }
1811 core_initcall(alloc_frozen_cpus);
1812 
1813 /*
1814  * When callbacks for CPU hotplug notifications are being executed, we must
1815  * ensure that the state of the system with respect to the tasks being frozen
1816  * or not, as reported by the notification, remains unchanged *throughout the
1817  * duration* of the execution of the callbacks.
1818  * Hence we need to prevent the freezer from racing with regular CPU hotplug.
1819  *
1820  * This synchronization is implemented by mutually excluding regular CPU
1821  * hotplug and Suspend/Hibernate call paths by hooking onto the Suspend/
1822  * Hibernate notifications.
1823  */
1824 static int
cpu_hotplug_pm_callback(struct notifier_block * nb,unsigned long action,void * ptr)1825 cpu_hotplug_pm_callback(struct notifier_block *nb,
1826 			unsigned long action, void *ptr)
1827 {
1828 	switch (action) {
1829 
1830 	case PM_SUSPEND_PREPARE:
1831 	case PM_HIBERNATION_PREPARE:
1832 		cpu_hotplug_disable();
1833 		break;
1834 
1835 	case PM_POST_SUSPEND:
1836 	case PM_POST_HIBERNATION:
1837 		cpu_hotplug_enable();
1838 		break;
1839 
1840 	default:
1841 		return NOTIFY_DONE;
1842 	}
1843 
1844 	return NOTIFY_OK;
1845 }
1846 
1847 
cpu_hotplug_pm_sync_init(void)1848 static int __init cpu_hotplug_pm_sync_init(void)
1849 {
1850 	/*
1851 	 * cpu_hotplug_pm_callback has higher priority than x86
1852 	 * bsp_pm_callback which depends on cpu_hotplug_pm_callback
1853 	 * to disable cpu hotplug to avoid cpu hotplug race.
1854 	 */
1855 	pm_notifier(cpu_hotplug_pm_callback, 0);
1856 	return 0;
1857 }
1858 core_initcall(cpu_hotplug_pm_sync_init);
1859 
1860 #endif /* CONFIG_PM_SLEEP_SMP */
1861 
1862 int __boot_cpu_id;
1863 
1864 /* Horrific hacks because we can't add more to cpuhp_hp_states. */
random_and_perf_prepare_fusion(unsigned int cpu)1865 static int random_and_perf_prepare_fusion(unsigned int cpu)
1866 {
1867 #ifdef CONFIG_PERF_EVENTS
1868 	perf_event_init_cpu(cpu);
1869 #endif
1870 	random_prepare_cpu(cpu);
1871 	return 0;
1872 }
random_and_workqueue_online_fusion(unsigned int cpu)1873 static int random_and_workqueue_online_fusion(unsigned int cpu)
1874 {
1875 	workqueue_online_cpu(cpu);
1876 	random_online_cpu(cpu);
1877 	return 0;
1878 }
1879 
1880 #endif /* CONFIG_SMP */
1881 
1882 /* Boot processor state steps */
1883 static struct cpuhp_step cpuhp_hp_states[] = {
1884 	[CPUHP_OFFLINE] = {
1885 		.name			= "offline",
1886 		.startup.single		= NULL,
1887 		.teardown.single	= NULL,
1888 	},
1889 #ifdef CONFIG_SMP
1890 	[CPUHP_CREATE_THREADS]= {
1891 		.name			= "threads:prepare",
1892 		.startup.single		= smpboot_create_threads,
1893 		.teardown.single	= NULL,
1894 		.cant_stop		= true,
1895 	},
1896 	[CPUHP_PERF_PREPARE] = {
1897 		.name			= "perf:prepare",
1898 		.startup.single		= random_and_perf_prepare_fusion,
1899 		.teardown.single	= perf_event_exit_cpu,
1900 	},
1901 	[CPUHP_WORKQUEUE_PREP] = {
1902 		.name			= "workqueue:prepare",
1903 		.startup.single		= workqueue_prepare_cpu,
1904 		.teardown.single	= NULL,
1905 	},
1906 	[CPUHP_HRTIMERS_PREPARE] = {
1907 		.name			= "hrtimers:prepare",
1908 		.startup.single		= hrtimers_prepare_cpu,
1909 		.teardown.single	= hrtimers_dead_cpu,
1910 	},
1911 	[CPUHP_SMPCFD_PREPARE] = {
1912 		.name			= "smpcfd:prepare",
1913 		.startup.single		= smpcfd_prepare_cpu,
1914 		.teardown.single	= smpcfd_dead_cpu,
1915 	},
1916 	[CPUHP_RELAY_PREPARE] = {
1917 		.name			= "relay:prepare",
1918 		.startup.single		= relay_prepare_cpu,
1919 		.teardown.single	= NULL,
1920 	},
1921 	[CPUHP_SLAB_PREPARE] = {
1922 		.name			= "slab:prepare",
1923 		.startup.single		= slab_prepare_cpu,
1924 		.teardown.single	= slab_dead_cpu,
1925 	},
1926 	[CPUHP_RCUTREE_PREP] = {
1927 		.name			= "RCU/tree:prepare",
1928 		.startup.single		= rcutree_prepare_cpu,
1929 		.teardown.single	= rcutree_dead_cpu,
1930 	},
1931 	/*
1932 	 * On the tear-down path, timers_dead_cpu() must be invoked
1933 	 * before blk_mq_queue_reinit_notify() from notify_dead(),
1934 	 * otherwise a RCU stall occurs.
1935 	 */
1936 	[CPUHP_TIMERS_PREPARE] = {
1937 		.name			= "timers:prepare",
1938 		.startup.single		= timers_prepare_cpu,
1939 		.teardown.single	= timers_dead_cpu,
1940 	},
1941 	/* Kicks the plugged cpu into life */
1942 	[CPUHP_BRINGUP_CPU] = {
1943 		.name			= "cpu:bringup",
1944 		.startup.single		= bringup_cpu,
1945 		.teardown.single	= finish_cpu,
1946 		.cant_stop		= true,
1947 	},
1948 	/* Final state before CPU kills itself */
1949 	[CPUHP_AP_IDLE_DEAD] = {
1950 		.name			= "idle:dead",
1951 	},
1952 	/*
1953 	 * Last state before CPU enters the idle loop to die. Transient state
1954 	 * for synchronization.
1955 	 */
1956 	[CPUHP_AP_OFFLINE] = {
1957 		.name			= "ap:offline",
1958 		.cant_stop		= true,
1959 	},
1960 	/* First state is scheduler control. Interrupts are disabled */
1961 	[CPUHP_AP_SCHED_STARTING] = {
1962 		.name			= "sched:starting",
1963 		.startup.single		= sched_cpu_starting,
1964 		.teardown.single	= sched_cpu_dying,
1965 	},
1966 	[CPUHP_AP_RCUTREE_DYING] = {
1967 		.name			= "RCU/tree:dying",
1968 		.startup.single		= NULL,
1969 		.teardown.single	= rcutree_dying_cpu,
1970 	},
1971 	[CPUHP_AP_SMPCFD_DYING] = {
1972 		.name			= "smpcfd:dying",
1973 		.startup.single		= NULL,
1974 		.teardown.single	= smpcfd_dying_cpu,
1975 	},
1976 	/* Entry state on starting. Interrupts enabled from here on. Transient
1977 	 * state for synchronsization */
1978 	[CPUHP_AP_ONLINE] = {
1979 		.name			= "ap:online",
1980 	},
1981 	/*
1982 	 * Handled on controll processor until the plugged processor manages
1983 	 * this itself.
1984 	 */
1985 	[CPUHP_TEARDOWN_CPU] = {
1986 		.name			= "cpu:teardown",
1987 		.startup.single		= NULL,
1988 		.teardown.single	= takedown_cpu,
1989 		.cant_stop		= true,
1990 	},
1991 	/* Handle smpboot threads park/unpark */
1992 	[CPUHP_AP_SMPBOOT_THREADS] = {
1993 		.name			= "smpboot/threads:online",
1994 		.startup.single		= smpboot_unpark_threads,
1995 		.teardown.single	= smpboot_park_threads,
1996 	},
1997 	[CPUHP_AP_IRQ_AFFINITY_ONLINE] = {
1998 		.name			= "irq/affinity:online",
1999 		.startup.single		= irq_affinity_online_cpu,
2000 		.teardown.single	= NULL,
2001 	},
2002 	[CPUHP_AP_PERF_ONLINE] = {
2003 		.name			= "perf:online",
2004 		.startup.single		= perf_event_init_cpu,
2005 		.teardown.single	= perf_event_exit_cpu,
2006 	},
2007 	[CPUHP_AP_WATCHDOG_ONLINE] = {
2008 		.name			= "lockup_detector:online",
2009 		.startup.single		= lockup_detector_online_cpu,
2010 		.teardown.single	= lockup_detector_offline_cpu,
2011 	},
2012 	[CPUHP_AP_WORKQUEUE_ONLINE] = {
2013 		.name			= "workqueue:online",
2014 		.startup.single		= random_and_workqueue_online_fusion,
2015 		.teardown.single	= workqueue_offline_cpu,
2016 	},
2017 	[CPUHP_AP_RCUTREE_ONLINE] = {
2018 		.name			= "RCU/tree:online",
2019 		.startup.single		= rcutree_online_cpu,
2020 		.teardown.single	= rcutree_offline_cpu,
2021 	},
2022 #endif
2023 	/*
2024 	 * The dynamically registered state space is here
2025 	 */
2026 
2027 #ifdef CONFIG_SMP
2028 	/* Last state is scheduler control setting the cpu active */
2029 	[CPUHP_AP_ACTIVE] = {
2030 		.name			= "sched:active",
2031 		.startup.single		= sched_cpu_activate,
2032 		.teardown.single	= sched_cpu_deactivate,
2033 	},
2034 #endif
2035 
2036 	/* CPU is fully up and running. */
2037 	[CPUHP_ONLINE] = {
2038 		.name			= "online",
2039 		.startup.single		= NULL,
2040 		.teardown.single	= NULL,
2041 	},
2042 };
2043 
2044 /* Sanity check for callbacks */
cpuhp_cb_check(enum cpuhp_state state)2045 static int cpuhp_cb_check(enum cpuhp_state state)
2046 {
2047 	if (state <= CPUHP_OFFLINE || state >= CPUHP_ONLINE)
2048 		return -EINVAL;
2049 	return 0;
2050 }
2051 
2052 /*
2053  * Returns a free for dynamic slot assignment of the Online state. The states
2054  * are protected by the cpuhp_slot_states mutex and an empty slot is identified
2055  * by having no name assigned.
2056  */
cpuhp_reserve_state(enum cpuhp_state state)2057 static int cpuhp_reserve_state(enum cpuhp_state state)
2058 {
2059 	enum cpuhp_state i, end;
2060 	struct cpuhp_step *step;
2061 
2062 	switch (state) {
2063 	case CPUHP_AP_ONLINE_DYN:
2064 		step = cpuhp_hp_states + CPUHP_AP_ONLINE_DYN;
2065 		end = CPUHP_AP_ONLINE_DYN_END;
2066 		break;
2067 	case CPUHP_BP_PREPARE_DYN:
2068 		step = cpuhp_hp_states + CPUHP_BP_PREPARE_DYN;
2069 		end = CPUHP_BP_PREPARE_DYN_END;
2070 		break;
2071 	default:
2072 		return -EINVAL;
2073 	}
2074 
2075 	for (i = state; i <= end; i++, step++) {
2076 		if (!step->name)
2077 			return i;
2078 	}
2079 	WARN(1, "No more dynamic states available for CPU hotplug\n");
2080 	return -ENOSPC;
2081 }
2082 
cpuhp_store_callbacks(enum cpuhp_state state,const char * name,int (* startup)(unsigned int cpu),int (* teardown)(unsigned int cpu),bool multi_instance)2083 static int cpuhp_store_callbacks(enum cpuhp_state state, const char *name,
2084 				 int (*startup)(unsigned int cpu),
2085 				 int (*teardown)(unsigned int cpu),
2086 				 bool multi_instance)
2087 {
2088 	/* (Un)Install the callbacks for further cpu hotplug operations */
2089 	struct cpuhp_step *sp;
2090 	int ret = 0;
2091 
2092 	/*
2093 	 * If name is NULL, then the state gets removed.
2094 	 *
2095 	 * CPUHP_AP_ONLINE_DYN and CPUHP_BP_PREPARE_DYN are handed out on
2096 	 * the first allocation from these dynamic ranges, so the removal
2097 	 * would trigger a new allocation and clear the wrong (already
2098 	 * empty) state, leaving the callbacks of the to be cleared state
2099 	 * dangling, which causes wreckage on the next hotplug operation.
2100 	 */
2101 	if (name && (state == CPUHP_AP_ONLINE_DYN ||
2102 		     state == CPUHP_BP_PREPARE_DYN)) {
2103 		ret = cpuhp_reserve_state(state);
2104 		if (ret < 0)
2105 			return ret;
2106 		state = ret;
2107 	}
2108 	sp = cpuhp_get_step(state);
2109 	if (name && sp->name)
2110 		return -EBUSY;
2111 
2112 	sp->startup.single = startup;
2113 	sp->teardown.single = teardown;
2114 	sp->name = name;
2115 	sp->multi_instance = multi_instance;
2116 	INIT_HLIST_HEAD(&sp->list);
2117 	return ret;
2118 }
2119 
cpuhp_get_teardown_cb(enum cpuhp_state state)2120 static void *cpuhp_get_teardown_cb(enum cpuhp_state state)
2121 {
2122 	return cpuhp_get_step(state)->teardown.single;
2123 }
2124 
2125 /*
2126  * Call the startup/teardown function for a step either on the AP or
2127  * on the current CPU.
2128  */
cpuhp_issue_call(int cpu,enum cpuhp_state state,bool bringup,struct hlist_node * node)2129 static int cpuhp_issue_call(int cpu, enum cpuhp_state state, bool bringup,
2130 			    struct hlist_node *node)
2131 {
2132 	struct cpuhp_step *sp = cpuhp_get_step(state);
2133 	int ret;
2134 
2135 	/*
2136 	 * If there's nothing to do, we done.
2137 	 * Relies on the union for multi_instance.
2138 	 */
2139 	if ((bringup && !sp->startup.single) ||
2140 	    (!bringup && !sp->teardown.single))
2141 		return 0;
2142 	/*
2143 	 * The non AP bound callbacks can fail on bringup. On teardown
2144 	 * e.g. module removal we crash for now.
2145 	 */
2146 #ifdef CONFIG_SMP
2147 	if (cpuhp_is_ap_state(state))
2148 		ret = cpuhp_invoke_ap_callback(cpu, state, bringup, node);
2149 	else
2150 		ret = cpuhp_invoke_callback(cpu, state, bringup, node, NULL);
2151 #else
2152 	ret = cpuhp_invoke_callback(cpu, state, bringup, node, NULL);
2153 #endif
2154 	BUG_ON(ret && !bringup);
2155 	return ret;
2156 }
2157 
2158 /*
2159  * Called from __cpuhp_setup_state on a recoverable failure.
2160  *
2161  * Note: The teardown callbacks for rollback are not allowed to fail!
2162  */
cpuhp_rollback_install(int failedcpu,enum cpuhp_state state,struct hlist_node * node)2163 static void cpuhp_rollback_install(int failedcpu, enum cpuhp_state state,
2164 				   struct hlist_node *node)
2165 {
2166 	int cpu;
2167 
2168 	/* Roll back the already executed steps on the other cpus */
2169 	for_each_present_cpu(cpu) {
2170 		struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
2171 		int cpustate = st->state;
2172 
2173 		if (cpu >= failedcpu)
2174 			break;
2175 
2176 		/* Did we invoke the startup call on that cpu ? */
2177 		if (cpustate >= state)
2178 			cpuhp_issue_call(cpu, state, false, node);
2179 	}
2180 }
2181 
__cpuhp_state_add_instance_cpuslocked(enum cpuhp_state state,struct hlist_node * node,bool invoke)2182 int __cpuhp_state_add_instance_cpuslocked(enum cpuhp_state state,
2183 					  struct hlist_node *node,
2184 					  bool invoke)
2185 {
2186 	struct cpuhp_step *sp;
2187 	int cpu;
2188 	int ret;
2189 
2190 	lockdep_assert_cpus_held();
2191 
2192 	sp = cpuhp_get_step(state);
2193 	if (sp->multi_instance == false)
2194 		return -EINVAL;
2195 
2196 	mutex_lock(&cpuhp_state_mutex);
2197 
2198 	if (!invoke || !sp->startup.multi)
2199 		goto add_node;
2200 
2201 	/*
2202 	 * Try to call the startup callback for each present cpu
2203 	 * depending on the hotplug state of the cpu.
2204 	 */
2205 	for_each_present_cpu(cpu) {
2206 		struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
2207 		int cpustate = st->state;
2208 
2209 		if (cpustate < state)
2210 			continue;
2211 
2212 		ret = cpuhp_issue_call(cpu, state, true, node);
2213 		if (ret) {
2214 			if (sp->teardown.multi)
2215 				cpuhp_rollback_install(cpu, state, node);
2216 			goto unlock;
2217 		}
2218 	}
2219 add_node:
2220 	ret = 0;
2221 	hlist_add_head(node, &sp->list);
2222 unlock:
2223 	mutex_unlock(&cpuhp_state_mutex);
2224 	return ret;
2225 }
2226 
__cpuhp_state_add_instance(enum cpuhp_state state,struct hlist_node * node,bool invoke)2227 int __cpuhp_state_add_instance(enum cpuhp_state state, struct hlist_node *node,
2228 			       bool invoke)
2229 {
2230 	int ret;
2231 
2232 	cpus_read_lock();
2233 	ret = __cpuhp_state_add_instance_cpuslocked(state, node, invoke);
2234 	cpus_read_unlock();
2235 	return ret;
2236 }
2237 EXPORT_SYMBOL_GPL(__cpuhp_state_add_instance);
2238 
2239 /**
2240  * __cpuhp_setup_state_cpuslocked - Setup the callbacks for an hotplug machine state
2241  * @state:		The state to setup
2242  * @invoke:		If true, the startup function is invoked for cpus where
2243  *			cpu state >= @state
2244  * @startup:		startup callback function
2245  * @teardown:		teardown callback function
2246  * @multi_instance:	State is set up for multiple instances which get
2247  *			added afterwards.
2248  *
2249  * The caller needs to hold cpus read locked while calling this function.
2250  * Returns:
2251  *   On success:
2252  *      Positive state number if @state is CPUHP_AP_ONLINE_DYN
2253  *      0 for all other states
2254  *   On failure: proper (negative) error code
2255  */
__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)2256 int __cpuhp_setup_state_cpuslocked(enum cpuhp_state state,
2257 				   const char *name, bool invoke,
2258 				   int (*startup)(unsigned int cpu),
2259 				   int (*teardown)(unsigned int cpu),
2260 				   bool multi_instance)
2261 {
2262 	int cpu, ret = 0;
2263 	bool dynstate;
2264 
2265 	lockdep_assert_cpus_held();
2266 
2267 	if (cpuhp_cb_check(state) || !name)
2268 		return -EINVAL;
2269 
2270 	mutex_lock(&cpuhp_state_mutex);
2271 
2272 	ret = cpuhp_store_callbacks(state, name, startup, teardown,
2273 				    multi_instance);
2274 
2275 	dynstate = state == CPUHP_AP_ONLINE_DYN;
2276 	if (ret > 0 && dynstate) {
2277 		state = ret;
2278 		ret = 0;
2279 	}
2280 
2281 	if (ret || !invoke || !startup)
2282 		goto out;
2283 
2284 	/*
2285 	 * Try to call the startup callback for each present cpu
2286 	 * depending on the hotplug state of the cpu.
2287 	 */
2288 	for_each_present_cpu(cpu) {
2289 		struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
2290 		int cpustate = st->state;
2291 
2292 		if (cpustate < state)
2293 			continue;
2294 
2295 		ret = cpuhp_issue_call(cpu, state, true, NULL);
2296 		if (ret) {
2297 			if (teardown)
2298 				cpuhp_rollback_install(cpu, state, NULL);
2299 			cpuhp_store_callbacks(state, NULL, NULL, NULL, false);
2300 			goto out;
2301 		}
2302 	}
2303 out:
2304 	mutex_unlock(&cpuhp_state_mutex);
2305 	/*
2306 	 * If the requested state is CPUHP_AP_ONLINE_DYN, return the
2307 	 * dynamically allocated state in case of success.
2308 	 */
2309 	if (!ret && dynstate)
2310 		return state;
2311 	return ret;
2312 }
2313 EXPORT_SYMBOL(__cpuhp_setup_state_cpuslocked);
2314 
__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)2315 int __cpuhp_setup_state(enum cpuhp_state state,
2316 			const char *name, bool invoke,
2317 			int (*startup)(unsigned int cpu),
2318 			int (*teardown)(unsigned int cpu),
2319 			bool multi_instance)
2320 {
2321 	int ret;
2322 
2323 	cpus_read_lock();
2324 	ret = __cpuhp_setup_state_cpuslocked(state, name, invoke, startup,
2325 					     teardown, multi_instance);
2326 	cpus_read_unlock();
2327 	return ret;
2328 }
2329 EXPORT_SYMBOL(__cpuhp_setup_state);
2330 
__cpuhp_state_remove_instance(enum cpuhp_state state,struct hlist_node * node,bool invoke)2331 int __cpuhp_state_remove_instance(enum cpuhp_state state,
2332 				  struct hlist_node *node, bool invoke)
2333 {
2334 	struct cpuhp_step *sp = cpuhp_get_step(state);
2335 	int cpu;
2336 
2337 	BUG_ON(cpuhp_cb_check(state));
2338 
2339 	if (!sp->multi_instance)
2340 		return -EINVAL;
2341 
2342 	cpus_read_lock();
2343 	mutex_lock(&cpuhp_state_mutex);
2344 
2345 	if (!invoke || !cpuhp_get_teardown_cb(state))
2346 		goto remove;
2347 	/*
2348 	 * Call the teardown callback for each present cpu depending
2349 	 * on the hotplug state of the cpu. This function is not
2350 	 * allowed to fail currently!
2351 	 */
2352 	for_each_present_cpu(cpu) {
2353 		struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
2354 		int cpustate = st->state;
2355 
2356 		if (cpustate >= state)
2357 			cpuhp_issue_call(cpu, state, false, node);
2358 	}
2359 
2360 remove:
2361 	hlist_del(node);
2362 	mutex_unlock(&cpuhp_state_mutex);
2363 	cpus_read_unlock();
2364 
2365 	return 0;
2366 }
2367 EXPORT_SYMBOL_GPL(__cpuhp_state_remove_instance);
2368 
2369 /**
2370  * __cpuhp_remove_state_cpuslocked - Remove the callbacks for an hotplug machine state
2371  * @state:	The state to remove
2372  * @invoke:	If true, the teardown function is invoked for cpus where
2373  *		cpu state >= @state
2374  *
2375  * The caller needs to hold cpus read locked while calling this function.
2376  * The teardown callback is currently not allowed to fail. Think
2377  * about module removal!
2378  */
__cpuhp_remove_state_cpuslocked(enum cpuhp_state state,bool invoke)2379 void __cpuhp_remove_state_cpuslocked(enum cpuhp_state state, bool invoke)
2380 {
2381 	struct cpuhp_step *sp = cpuhp_get_step(state);
2382 	int cpu;
2383 
2384 	BUG_ON(cpuhp_cb_check(state));
2385 
2386 	lockdep_assert_cpus_held();
2387 
2388 	mutex_lock(&cpuhp_state_mutex);
2389 	if (sp->multi_instance) {
2390 		WARN(!hlist_empty(&sp->list),
2391 		     "Error: Removing state %d which has instances left.\n",
2392 		     state);
2393 		goto remove;
2394 	}
2395 
2396 	if (!invoke || !cpuhp_get_teardown_cb(state))
2397 		goto remove;
2398 
2399 	/*
2400 	 * Call the teardown callback for each present cpu depending
2401 	 * on the hotplug state of the cpu. This function is not
2402 	 * allowed to fail currently!
2403 	 */
2404 	for_each_present_cpu(cpu) {
2405 		struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, cpu);
2406 		int cpustate = st->state;
2407 
2408 		if (cpustate >= state)
2409 			cpuhp_issue_call(cpu, state, false, NULL);
2410 	}
2411 remove:
2412 	cpuhp_store_callbacks(state, NULL, NULL, NULL, false);
2413 	mutex_unlock(&cpuhp_state_mutex);
2414 }
2415 EXPORT_SYMBOL(__cpuhp_remove_state_cpuslocked);
2416 
__cpuhp_remove_state(enum cpuhp_state state,bool invoke)2417 void __cpuhp_remove_state(enum cpuhp_state state, bool invoke)
2418 {
2419 	cpus_read_lock();
2420 	__cpuhp_remove_state_cpuslocked(state, invoke);
2421 	cpus_read_unlock();
2422 }
2423 EXPORT_SYMBOL(__cpuhp_remove_state);
2424 
2425 #ifdef CONFIG_HOTPLUG_SMT
cpuhp_offline_cpu_device(unsigned int cpu)2426 static void cpuhp_offline_cpu_device(unsigned int cpu)
2427 {
2428 	struct device *dev = get_cpu_device(cpu);
2429 
2430 	dev->offline = true;
2431 	/* Tell user space about the state change */
2432 	kobject_uevent(&dev->kobj, KOBJ_OFFLINE);
2433 }
2434 
cpuhp_online_cpu_device(unsigned int cpu)2435 static void cpuhp_online_cpu_device(unsigned int cpu)
2436 {
2437 	struct device *dev = get_cpu_device(cpu);
2438 
2439 	dev->offline = false;
2440 	/* Tell user space about the state change */
2441 	kobject_uevent(&dev->kobj, KOBJ_ONLINE);
2442 }
2443 
cpuhp_smt_disable(enum cpuhp_smt_control ctrlval)2444 int cpuhp_smt_disable(enum cpuhp_smt_control ctrlval)
2445 {
2446 	int cpu, ret = 0;
2447 
2448 	cpu_maps_update_begin();
2449 	for_each_online_cpu(cpu) {
2450 		if (topology_is_primary_thread(cpu))
2451 			continue;
2452 		ret = cpu_down_maps_locked(cpu, CPUHP_OFFLINE);
2453 		if (ret)
2454 			break;
2455 		/*
2456 		 * As this needs to hold the cpu maps lock it's impossible
2457 		 * to call device_offline() because that ends up calling
2458 		 * cpu_down() which takes cpu maps lock. cpu maps lock
2459 		 * needs to be held as this might race against in kernel
2460 		 * abusers of the hotplug machinery (thermal management).
2461 		 *
2462 		 * So nothing would update device:offline state. That would
2463 		 * leave the sysfs entry stale and prevent onlining after
2464 		 * smt control has been changed to 'off' again. This is
2465 		 * called under the sysfs hotplug lock, so it is properly
2466 		 * serialized against the regular offline usage.
2467 		 */
2468 		cpuhp_offline_cpu_device(cpu);
2469 	}
2470 	if (!ret)
2471 		cpu_smt_control = ctrlval;
2472 	cpu_maps_update_done();
2473 	return ret;
2474 }
2475 
cpuhp_smt_enable(void)2476 int cpuhp_smt_enable(void)
2477 {
2478 	int cpu, ret = 0;
2479 
2480 	cpu_maps_update_begin();
2481 	cpu_smt_control = CPU_SMT_ENABLED;
2482 	for_each_present_cpu(cpu) {
2483 		/* Skip online CPUs and CPUs on offline nodes */
2484 		if (cpu_online(cpu) || !node_online(cpu_to_node(cpu)))
2485 			continue;
2486 		ret = _cpu_up(cpu, 0, CPUHP_ONLINE);
2487 		if (ret)
2488 			break;
2489 		/* See comment in cpuhp_smt_disable() */
2490 		cpuhp_online_cpu_device(cpu);
2491 	}
2492 	cpu_maps_update_done();
2493 	return ret;
2494 }
2495 #endif
2496 
2497 #if defined(CONFIG_SYSFS) && defined(CONFIG_HOTPLUG_CPU)
show_cpuhp_state(struct device * dev,struct device_attribute * attr,char * buf)2498 static ssize_t show_cpuhp_state(struct device *dev,
2499 				struct device_attribute *attr, char *buf)
2500 {
2501 	struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2502 
2503 	return sprintf(buf, "%d\n", st->state);
2504 }
2505 static DEVICE_ATTR(state, 0444, show_cpuhp_state, NULL);
2506 
write_cpuhp_target(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2507 static ssize_t write_cpuhp_target(struct device *dev,
2508 				  struct device_attribute *attr,
2509 				  const char *buf, size_t count)
2510 {
2511 	struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2512 	struct cpuhp_step *sp;
2513 	int target, ret;
2514 
2515 	ret = kstrtoint(buf, 10, &target);
2516 	if (ret)
2517 		return ret;
2518 
2519 #ifdef CONFIG_CPU_HOTPLUG_STATE_CONTROL
2520 	if (target < CPUHP_OFFLINE || target > CPUHP_ONLINE)
2521 		return -EINVAL;
2522 #else
2523 	if (target != CPUHP_OFFLINE && target != CPUHP_ONLINE)
2524 		return -EINVAL;
2525 #endif
2526 
2527 	ret = lock_device_hotplug_sysfs();
2528 	if (ret)
2529 		return ret;
2530 
2531 	mutex_lock(&cpuhp_state_mutex);
2532 	sp = cpuhp_get_step(target);
2533 	ret = !sp->name || sp->cant_stop ? -EINVAL : 0;
2534 	mutex_unlock(&cpuhp_state_mutex);
2535 	if (ret)
2536 		goto out;
2537 
2538 	if (st->state < target)
2539 		ret = cpu_up(dev->id, target);
2540 	else if (st->state > target)
2541 		ret = cpu_down(dev->id, target);
2542 	else if (WARN_ON(st->target != target))
2543 		st->target = target;
2544 out:
2545 	unlock_device_hotplug();
2546 	return ret ? ret : count;
2547 }
2548 
show_cpuhp_target(struct device * dev,struct device_attribute * attr,char * buf)2549 static ssize_t show_cpuhp_target(struct device *dev,
2550 				 struct device_attribute *attr, char *buf)
2551 {
2552 	struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2553 
2554 	return sprintf(buf, "%d\n", st->target);
2555 }
2556 static DEVICE_ATTR(target, 0644, show_cpuhp_target, write_cpuhp_target);
2557 
2558 
write_cpuhp_fail(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2559 static ssize_t write_cpuhp_fail(struct device *dev,
2560 				struct device_attribute *attr,
2561 				const char *buf, size_t count)
2562 {
2563 	struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2564 	struct cpuhp_step *sp;
2565 	int fail, ret;
2566 
2567 	ret = kstrtoint(buf, 10, &fail);
2568 	if (ret)
2569 		return ret;
2570 
2571 	if (fail < CPUHP_OFFLINE || fail > CPUHP_ONLINE)
2572 		return -EINVAL;
2573 
2574 	/*
2575 	 * Cannot fail STARTING/DYING callbacks.
2576 	 */
2577 	if (cpuhp_is_atomic_state(fail))
2578 		return -EINVAL;
2579 
2580 	/*
2581 	 * Cannot fail anything that doesn't have callbacks.
2582 	 */
2583 	mutex_lock(&cpuhp_state_mutex);
2584 	sp = cpuhp_get_step(fail);
2585 	if (!sp->startup.single && !sp->teardown.single)
2586 		ret = -EINVAL;
2587 	mutex_unlock(&cpuhp_state_mutex);
2588 	if (ret)
2589 		return ret;
2590 
2591 	st->fail = fail;
2592 
2593 	return count;
2594 }
2595 
show_cpuhp_fail(struct device * dev,struct device_attribute * attr,char * buf)2596 static ssize_t show_cpuhp_fail(struct device *dev,
2597 			       struct device_attribute *attr, char *buf)
2598 {
2599 	struct cpuhp_cpu_state *st = per_cpu_ptr(&cpuhp_state, dev->id);
2600 
2601 	return sprintf(buf, "%d\n", st->fail);
2602 }
2603 
2604 static DEVICE_ATTR(fail, 0644, show_cpuhp_fail, write_cpuhp_fail);
2605 
2606 static struct attribute *cpuhp_cpu_attrs[] = {
2607 	&dev_attr_state.attr,
2608 	&dev_attr_target.attr,
2609 	&dev_attr_fail.attr,
2610 	NULL
2611 };
2612 
2613 static const struct attribute_group cpuhp_cpu_attr_group = {
2614 	.attrs = cpuhp_cpu_attrs,
2615 	.name = "hotplug",
2616 	NULL
2617 };
2618 
show_cpuhp_states(struct device * dev,struct device_attribute * attr,char * buf)2619 static ssize_t show_cpuhp_states(struct device *dev,
2620 				 struct device_attribute *attr, char *buf)
2621 {
2622 	ssize_t cur, res = 0;
2623 	int i;
2624 
2625 	mutex_lock(&cpuhp_state_mutex);
2626 	for (i = CPUHP_OFFLINE; i <= CPUHP_ONLINE; i++) {
2627 		struct cpuhp_step *sp = cpuhp_get_step(i);
2628 
2629 		if (sp->name) {
2630 			cur = sprintf(buf, "%3d: %s\n", i, sp->name);
2631 			buf += cur;
2632 			res += cur;
2633 		}
2634 	}
2635 	mutex_unlock(&cpuhp_state_mutex);
2636 	return res;
2637 }
2638 static DEVICE_ATTR(states, 0444, show_cpuhp_states, NULL);
2639 
2640 static struct attribute *cpuhp_cpu_root_attrs[] = {
2641 	&dev_attr_states.attr,
2642 	NULL
2643 };
2644 
2645 static const struct attribute_group cpuhp_cpu_root_attr_group = {
2646 	.attrs = cpuhp_cpu_root_attrs,
2647 	.name = "hotplug",
2648 	NULL
2649 };
2650 
2651 #ifdef CONFIG_HOTPLUG_SMT
2652 
2653 static ssize_t
__store_smt_control(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2654 __store_smt_control(struct device *dev, struct device_attribute *attr,
2655 		    const char *buf, size_t count)
2656 {
2657 	int ctrlval, ret;
2658 
2659 	if (sysfs_streq(buf, "on"))
2660 		ctrlval = CPU_SMT_ENABLED;
2661 	else if (sysfs_streq(buf, "off"))
2662 		ctrlval = CPU_SMT_DISABLED;
2663 	else if (sysfs_streq(buf, "forceoff"))
2664 		ctrlval = CPU_SMT_FORCE_DISABLED;
2665 	else
2666 		return -EINVAL;
2667 
2668 	if (cpu_smt_control == CPU_SMT_FORCE_DISABLED)
2669 		return -EPERM;
2670 
2671 	if (cpu_smt_control == CPU_SMT_NOT_SUPPORTED)
2672 		return -ENODEV;
2673 
2674 	ret = lock_device_hotplug_sysfs();
2675 	if (ret)
2676 		return ret;
2677 
2678 	if (ctrlval != cpu_smt_control) {
2679 		switch (ctrlval) {
2680 		case CPU_SMT_ENABLED:
2681 			ret = cpuhp_smt_enable();
2682 			break;
2683 		case CPU_SMT_DISABLED:
2684 		case CPU_SMT_FORCE_DISABLED:
2685 			ret = cpuhp_smt_disable(ctrlval);
2686 			break;
2687 		}
2688 	}
2689 
2690 	unlock_device_hotplug();
2691 	return ret ? ret : count;
2692 }
2693 
2694 #else /* !CONFIG_HOTPLUG_SMT */
2695 static ssize_t
__store_smt_control(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2696 __store_smt_control(struct device *dev, struct device_attribute *attr,
2697 		    const char *buf, size_t count)
2698 {
2699 	return -ENODEV;
2700 }
2701 #endif /* CONFIG_HOTPLUG_SMT */
2702 
2703 static const char *smt_states[] = {
2704 	[CPU_SMT_ENABLED]		= "on",
2705 	[CPU_SMT_DISABLED]		= "off",
2706 	[CPU_SMT_FORCE_DISABLED]	= "forceoff",
2707 	[CPU_SMT_NOT_SUPPORTED]		= "notsupported",
2708 	[CPU_SMT_NOT_IMPLEMENTED]	= "notimplemented",
2709 };
2710 
2711 static ssize_t
show_smt_control(struct device * dev,struct device_attribute * attr,char * buf)2712 show_smt_control(struct device *dev, struct device_attribute *attr, char *buf)
2713 {
2714 	const char *state = smt_states[cpu_smt_control];
2715 
2716 	return snprintf(buf, PAGE_SIZE - 2, "%s\n", state);
2717 }
2718 
2719 static ssize_t
store_smt_control(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)2720 store_smt_control(struct device *dev, struct device_attribute *attr,
2721 		  const char *buf, size_t count)
2722 {
2723 	return __store_smt_control(dev, attr, buf, count);
2724 }
2725 static DEVICE_ATTR(control, 0644, show_smt_control, store_smt_control);
2726 
2727 static ssize_t
show_smt_active(struct device * dev,struct device_attribute * attr,char * buf)2728 show_smt_active(struct device *dev, struct device_attribute *attr, char *buf)
2729 {
2730 	return snprintf(buf, PAGE_SIZE - 2, "%d\n", sched_smt_active());
2731 }
2732 static DEVICE_ATTR(active, 0444, show_smt_active, NULL);
2733 
2734 static struct attribute *cpuhp_smt_attrs[] = {
2735 	&dev_attr_control.attr,
2736 	&dev_attr_active.attr,
2737 	NULL
2738 };
2739 
2740 static const struct attribute_group cpuhp_smt_attr_group = {
2741 	.attrs = cpuhp_smt_attrs,
2742 	.name = "smt",
2743 	NULL
2744 };
2745 
cpu_smt_sysfs_init(void)2746 static int __init cpu_smt_sysfs_init(void)
2747 {
2748 	return sysfs_create_group(&cpu_subsys.dev_root->kobj,
2749 				  &cpuhp_smt_attr_group);
2750 }
2751 
cpuhp_sysfs_init(void)2752 static int __init cpuhp_sysfs_init(void)
2753 {
2754 	int cpu, ret;
2755 
2756 	ret = cpu_smt_sysfs_init();
2757 	if (ret)
2758 		return ret;
2759 
2760 	ret = sysfs_create_group(&cpu_subsys.dev_root->kobj,
2761 				 &cpuhp_cpu_root_attr_group);
2762 	if (ret)
2763 		return ret;
2764 
2765 	for_each_possible_cpu(cpu) {
2766 		struct device *dev = get_cpu_device(cpu);
2767 
2768 		if (!dev)
2769 			continue;
2770 		ret = sysfs_create_group(&dev->kobj, &cpuhp_cpu_attr_group);
2771 		if (ret)
2772 			return ret;
2773 	}
2774 	return 0;
2775 }
2776 device_initcall(cpuhp_sysfs_init);
2777 #endif /* CONFIG_SYSFS && CONFIG_HOTPLUG_CPU */
2778 
2779 /*
2780  * cpu_bit_bitmap[] is a special, "compressed" data structure that
2781  * represents all NR_CPUS bits binary values of 1<<nr.
2782  *
2783  * It is used by cpumask_of() to get a constant address to a CPU
2784  * mask value that has a single bit set only.
2785  */
2786 
2787 /* cpu_bit_bitmap[0] is empty - so we can back into it */
2788 #define MASK_DECLARE_1(x)	[x+1][0] = (1UL << (x))
2789 #define MASK_DECLARE_2(x)	MASK_DECLARE_1(x), MASK_DECLARE_1(x+1)
2790 #define MASK_DECLARE_4(x)	MASK_DECLARE_2(x), MASK_DECLARE_2(x+2)
2791 #define MASK_DECLARE_8(x)	MASK_DECLARE_4(x), MASK_DECLARE_4(x+4)
2792 
2793 const unsigned long cpu_bit_bitmap[BITS_PER_LONG+1][BITS_TO_LONGS(NR_CPUS)] = {
2794 
2795 	MASK_DECLARE_8(0),	MASK_DECLARE_8(8),
2796 	MASK_DECLARE_8(16),	MASK_DECLARE_8(24),
2797 #if BITS_PER_LONG > 32
2798 	MASK_DECLARE_8(32),	MASK_DECLARE_8(40),
2799 	MASK_DECLARE_8(48),	MASK_DECLARE_8(56),
2800 #endif
2801 };
2802 EXPORT_SYMBOL_GPL(cpu_bit_bitmap);
2803 
2804 const DECLARE_BITMAP(cpu_all_bits, NR_CPUS) = CPU_BITS_ALL;
2805 EXPORT_SYMBOL(cpu_all_bits);
2806 
2807 #ifdef CONFIG_INIT_ALL_POSSIBLE
2808 struct cpumask __cpu_possible_mask __read_mostly
2809 	= {CPU_BITS_ALL};
2810 #else
2811 struct cpumask __cpu_possible_mask __read_mostly;
2812 #endif
2813 EXPORT_SYMBOL(__cpu_possible_mask);
2814 
2815 struct cpumask __cpu_online_mask __read_mostly;
2816 EXPORT_SYMBOL(__cpu_online_mask);
2817 
2818 struct cpumask __cpu_present_mask __read_mostly;
2819 EXPORT_SYMBOL(__cpu_present_mask);
2820 
2821 struct cpumask __cpu_active_mask __read_mostly;
2822 EXPORT_SYMBOL(__cpu_active_mask);
2823 
2824 atomic_t __num_online_cpus __read_mostly;
2825 EXPORT_SYMBOL(__num_online_cpus);
2826 
init_cpu_present(const struct cpumask * src)2827 void init_cpu_present(const struct cpumask *src)
2828 {
2829 	cpumask_copy(&__cpu_present_mask, src);
2830 }
2831 
init_cpu_possible(const struct cpumask * src)2832 void init_cpu_possible(const struct cpumask *src)
2833 {
2834 	cpumask_copy(&__cpu_possible_mask, src);
2835 }
2836 
init_cpu_online(const struct cpumask * src)2837 void init_cpu_online(const struct cpumask *src)
2838 {
2839 	cpumask_copy(&__cpu_online_mask, src);
2840 }
2841 
set_cpu_online(unsigned int cpu,bool online)2842 void set_cpu_online(unsigned int cpu, bool online)
2843 {
2844 	/*
2845 	 * atomic_inc/dec() is required to handle the horrid abuse of this
2846 	 * function by the reboot and kexec code which invoke it from
2847 	 * IPI/NMI broadcasts when shutting down CPUs. Invocation from
2848 	 * regular CPU hotplug is properly serialized.
2849 	 *
2850 	 * Note, that the fact that __num_online_cpus is of type atomic_t
2851 	 * does not protect readers which are not serialized against
2852 	 * concurrent hotplug operations.
2853 	 */
2854 	if (online) {
2855 		if (!cpumask_test_and_set_cpu(cpu, &__cpu_online_mask))
2856 			atomic_inc(&__num_online_cpus);
2857 	} else {
2858 		if (cpumask_test_and_clear_cpu(cpu, &__cpu_online_mask))
2859 			atomic_dec(&__num_online_cpus);
2860 	}
2861 }
2862 
2863 /*
2864  * Activate the first processor.
2865  */
boot_cpu_init(void)2866 void __init boot_cpu_init(void)
2867 {
2868 	int cpu = smp_processor_id();
2869 
2870 	/* Mark the boot cpu "present", "online" etc for SMP and UP case */
2871 	set_cpu_online(cpu, true);
2872 	set_cpu_active(cpu, true);
2873 	set_cpu_present(cpu, true);
2874 	set_cpu_possible(cpu, true);
2875 
2876 #ifdef CONFIG_SMP
2877 	__boot_cpu_id = cpu;
2878 #endif
2879 }
2880 
2881 /*
2882  * Must be called _AFTER_ setting up the per_cpu areas
2883  */
boot_cpu_hotplug_init(void)2884 void __init boot_cpu_hotplug_init(void)
2885 {
2886 #ifdef CONFIG_SMP
2887 	cpumask_set_cpu(smp_processor_id(), &cpus_booted_once_mask);
2888 #endif
2889 	this_cpu_write(cpuhp_state.state, CPUHP_ONLINE);
2890 }
2891 
2892 /*
2893  * These are used for a global "mitigations=" cmdline option for toggling
2894  * optional CPU mitigations.
2895  */
2896 enum cpu_mitigations {
2897 	CPU_MITIGATIONS_OFF,
2898 	CPU_MITIGATIONS_AUTO,
2899 	CPU_MITIGATIONS_AUTO_NOSMT,
2900 };
2901 
2902 static enum cpu_mitigations cpu_mitigations __ro_after_init =
2903 	CPU_MITIGATIONS_AUTO;
2904 
mitigations_parse_cmdline(char * arg)2905 static int __init mitigations_parse_cmdline(char *arg)
2906 {
2907 	if (!strcmp(arg, "off"))
2908 		cpu_mitigations = CPU_MITIGATIONS_OFF;
2909 	else if (!strcmp(arg, "auto"))
2910 		cpu_mitigations = CPU_MITIGATIONS_AUTO;
2911 	else if (!strcmp(arg, "auto,nosmt"))
2912 		cpu_mitigations = CPU_MITIGATIONS_AUTO_NOSMT;
2913 	else
2914 		pr_crit("Unsupported mitigations=%s, system may still be vulnerable\n",
2915 			arg);
2916 
2917 	return 0;
2918 }
2919 early_param("mitigations", mitigations_parse_cmdline);
2920 
2921 /* mitigations=off */
cpu_mitigations_off(void)2922 bool cpu_mitigations_off(void)
2923 {
2924 	return cpu_mitigations == CPU_MITIGATIONS_OFF;
2925 }
2926 EXPORT_SYMBOL_GPL(cpu_mitigations_off);
2927 
2928 /* mitigations=auto,nosmt */
cpu_mitigations_auto_nosmt(void)2929 bool cpu_mitigations_auto_nosmt(void)
2930 {
2931 	return cpu_mitigations == CPU_MITIGATIONS_AUTO_NOSMT;
2932 }
2933 EXPORT_SYMBOL_GPL(cpu_mitigations_auto_nosmt);
2934