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