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