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