요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
=========================
CPU hotplug in the Kernel
=========================
:Date: September, 2021
:Author: Sebastian Andrzej Siewior <[email protected]>,
Rusty Russell <[email protected]>,
Srivatsa Vaddagiri <[email protected]>,
Ashok Raj <[email protected]>,
Joel Schopp <[email protected]>,
Thomas Gleixner <[email protected]>
Introduction
============
Modern advances in system architectures have introduced advanced error
reporting and correction capabilities in processors. There are couple OEMS that
support NUMA hardware which are hot pluggable as well, where physical node
insertion and removal require support for CPU hotplug.
Such advances require CPUs available to a kernel to be removed either for
provisioning reasons, or for RAS purposes to keep an offending CPU off
system execution path. Hence the need for CPU hotplug support in the
Linux kernel.
A more novel use of CPU-hotplug support is its use today in suspend resume
support for SMP. Dual-core and HT support makes even a laptop run SMP kernels
which didn't support these methods.
Command Line Switches
=====================
``maxcpus=n``
Restrict boot time CPUs to *n*. Say if you have four CPUs, using
``maxcpus=2`` will only boot two. You can choose to bring the
other CPUs later online.
``nr_cpus=n``
Restrict the total amount of CPUs the kernel will support. If the number
supplied here is lower than the number of physically available CPUs, then
those CPUs can not be brought online later.
``possible_cpus=n``
This option sets ``possible_cpus`` bits in ``cpu_possible_mask``.
This option is limited to the X86 and S390 architecture.
``cpu0_hotplug``
Allow to shutdown CPU0.
This option is limited to the X86 architecture.
CPU maps
========
``cpu_possible_mask``
Bitmap of possible CPUs that can ever be available in the
system. This is used to allocate some boot time memory for per_cpu variables
that aren't designed to grow/shrink as CPUs are made available or removed.
Once set during boot time discovery phase, the map is static, i.e no bits
are added or removed anytime. Trimming it accurately for your system needs
upfront can save some boot time memory.
``cpu_online_mask``
Bitmap of all CPUs currently online. Its set in ``__cpu_up()``
after a CPU is available for kernel scheduling and ready to receive
interrupts from devices. Its cleared when a CPU is brought down using
``__cpu_disable()``, before which all OS services including interrupts are
migrated to another target CPU.
``cpu_present_mask``
Bitmap of CPUs currently present in the system. Not all
of them may be online. When physical hotplug is processed by the relevant
subsystem (e.g ACPI) can change and new bit either be added or removed
from the map depending on the event is hot-add/hot-remove. There are currently
no locking rules as of now. Typical usage is to init topology during boot,
at which time hotplug is disabled.
You really don't need to manipulate any of the system CPU maps. They should
be read-only for most use. When setting up per-cpu resources almost always use
``cpu_possible_mask`` or ``for_each_possible_cpu()`` to iterate. To macro
``for_each_cpu()`` can be used to iterate over a custom CPU mask.
Never use anything other than ``cpumask_t`` to represent bitmap of CPUs.
Using CPU hotplug
=================
The kernel option *CONFIG_HOTPLUG_CPU* needs to be enabled. It is currently
available on multiple architectures including ARM, MIPS, PowerPC and X86. The
configuration is done via the sysfs interface::
$ ls -lh /sys/devices/system/cpu
total 0
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu0
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu1
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu2
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu3
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu4
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu5
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu6
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu7
drwxr-xr-x 2 root root 0 Dec 21 16:33 hotplug
-r--r--r-- 1 root root 4.0K Dec 21 16:33 offline
-r--r--r-- 1 root root 4.0K Dec 21 16:33 online
-r--r--r-- 1 root root 4.0K Dec 21 16:33 possible
-r--r--r-- 1 root root 4.0K Dec 21 16:33 present
The files *offline*, *online*, *possible*, *present* represent the CPU masks.
Each CPU folder contains an *online* file which controls the logical on (1) and
off (0) state. To logically shutdown CPU4::
$ echo 0 > /sys/devices/system/cpu/cpu4/online
smpboot: CPU 4 is now offline
Once the CPU is shutdown, it will be removed from */proc/interrupts*,
*/proc/cpuinfo* and should also not be shown visible by the *top* command. To
bring CPU4 back online::
$ echo 1 > /sys/devices/system/cpu/cpu4/online
smpboot: Booting Node 0 Processor 4 APIC 0x1
The CPU is usable again. This should work on all CPUs, but CPU0 is often special
and excluded from CPU hotplug.
The CPU hotplug coordination
============================
The offline case
----------------
Once a CPU has been logically shutdown the teardown callbacks of registered
hotplug states will be invoked, starting with ``CPUHP_ONLINE`` and terminating
at state ``CPUHP_OFFLINE``. This includes:
* If tasks are frozen due to a suspend operation then *cpuhp_tasks_frozen*
will be set to true.
* All processes are migrated away from this outgoing CPU to new CPUs.
The new CPU is chosen from each process' current cpuset, which may be
a subset of all online CPUs.
* All interrupts targeted to this CPU are migrated to a new CPU
* timers are also migrated to a new CPU
* Once all services are migrated, kernel calls an arch specific routine
``__cpu_disable()`` to perform arch specific cleanup.
The CPU hotplug API
===================
CPU hotplug state machine
-------------------------
CPU hotplug uses a trivial state machine with a linear state space from
CPUHP_OFFLINE to CPUHP_ONLINE. Each state has a startup and a teardown
callback.
When a CPU is onlined, the startup callbacks are invoked sequentially until
the state CPUHP_ONLINE is reached. They can also be invoked when the
callbacks of a state are set up or an instance is added to a multi-instance
state.
When a CPU is offlined the teardown callbacks are invoked in the reverse
order sequentially until the state CPUHP_OFFLINE is reached. They can also
be invoked when the callbacks of a state are removed or an instance is
removed from a multi-instance state.
If a usage site requires only a callback in one direction of the hotplug
operations (CPU online or CPU offline) then the other not-required callback
can be set to NULL when the state is set up.
The state space is divided into three sections:
* The PREPARE section
The PREPARE section covers the state space from CPUHP_OFFLINE to
CPUHP_BRINGUP_CPU.
The startup callbacks in this section are invoked before the CPU is
started during a CPU online operation. The teardown callbacks are invoked
after the CPU has become dysfunctional during a CPU offline operation.
The callbacks are invoked on a control CPU as they can't obviously run on
the hotplugged CPU which is either not yet started or has become
dysfunctional already.
The startup callbacks are used to setup resources which are required to
bring a CPU successfully online. The teardown callbacks are used to free
resources or to move pending work to an online CPU after the hotplugged
CPU became dysfunctional.
The startup callbacks are allowed to fail. If a callback fails, the CPU
online operation is aborted and the CPU is brought down to the previous
state (usually CPUHP_OFFLINE) again.
The teardown callbacks in this section are not allowed to fail.
* The STARTING section
The STARTING section covers the state space between CPUHP_BRINGUP_CPU + 1
and CPUHP_AP_ONLINE.
The startup callbacks in this section are invoked on the hotplugged CPU
with interrupts disabled during a CPU online operation in the early CPU
setup code. The teardown callbacks are invoked with interrupts disabled
on the hotplugged CPU during a CPU offline operation shortly before the
CPU is completely shut down.
The callbacks in this section are not allowed to fail.
The callbacks are used for low level hardware initialization/shutdown and
for core subsystems.
* The ONLINE section
The ONLINE section covers the state space between CPUHP_AP_ONLINE + 1 and
CPUHP_ONLINE.
The startup callbacks in this section are invoked on the hotplugged CPU
during a CPU online operation. The teardown callbacks are invoked on the
hotplugged CPU during a CPU offline operation.
The callbacks are invoked in the context of the per CPU hotplug thread,
which is pinned on the hotplugged CPU. The callbacks are invoked with
interrupts and preemption enabled.
The callbacks are allowed to fail. When a callback fails the hotplug
operation is aborted and the CPU is brought back to the previous state.
CPU online/offline operations
-----------------------------
A successful online operation looks like this::
[CPUHP_OFFLINE]
[CPUHP_OFFLINE + 1]->startup() -> success
[CPUHP_OFFLINE + 2]->startup() -> success
[CPUHP_OFFLINE + 3] -> skipped because startup == NULL
...
[CPUHP_BRINGUP_CPU]->startup() -> success
=== End of PREPARE section
[CPUHP_BRINGUP_CPU + 1]->startup() -> success
...
[CPUHP_AP_ONLINE]->startup() -> success
=== End of STARTUP section
[CPUHP_AP_ONLINE + 1]->startup() -> success
...
[CPUHP_ONLINE - 1]->startup() -> success
[CPUHP_ONLINE]
A successful offline operation looks like this::
[CPUHP_ONLINE]
[CPUHP_ONLINE - 1]->teardown() -> success
...
[CPUHP_AP_ONLINE + 1]->teardown() -> success
=== Start of STARTUP section
[CPUHP_AP_ONLINE]->teardown() -> success
...
[CPUHP_BRINGUP_ONLINE - 1]->teardown()
...
=== Start of PREPARE section
[CPUHP_BRINGUP_CPU]->teardown()
[CPUHP_OFFLINE + 3]->teardown()
[CPUHP_OFFLINE + 2] -> skipped because teardown == NULL
[CPUHP_OFFLINE + 1]->teardown()
[CPUHP_OFFLINE]
A failed online operation looks like this::
[CPUHP_OFFLINE]
[CPUHP_OFFLINE + 1]->startup() -> success
[CPUHP_OFFLINE + 2]->startup() -> success
[CPUHP_OFFLINE + 3] -> skipped because startup == NULL
...
[CPUHP_BRINGUP_CPU]->startup() -> success
=== End of PREPARE section
[CPUHP_BRINGUP_CPU + 1]->startup() -> success
...
[CPUHP_AP_ONLINE]->startup() -> success
=== End of STARTUP section
[CPUHP_AP_ONLINE + 1]->startup() -> success
---
[CPUHP_AP_ONLINE + N]->startup() -> fail
[CPUHP_AP_ONLINE + (N - 1)]->teardown()
...
[CPUHP_AP_ONLINE + 1]->teardown()
=== Start of STARTUP section
[CPUHP_AP_ONLINE]->teardown()
...
[CPUHP_BRINGUP_ONLINE - 1]->teardown()
...
=== Start of PREPARE section
[CPUHP_BRINGUP_CPU]->teardown()
[CPUHP_OFFLINE + 3]->teardown()
[CPUHP_OFFLINE + 2] -> skipped because teardown == NULL
[CPUHP_OFFLINE + 1]->teardown()
[CPUHP_OFFLINE]
A failed offline operation looks like this::
[CPUHP_ONLINE]
[CPUHP_ONLINE - 1]->teardown() -> success
...
[CPUHP_ONLINE - N]->teardown() -> fail
[CPUHP_ONLINE - (N - 1)]->startup()
...
[CPUHP_ONLINE - 1]->startup()
[CPUHP_ONLINE]
Recursive failures cannot be handled sensibly. Look at the following
example of a recursive fail due to a failed offline operation: ::
[CPUHP_ONLINE]
[CPUHP_ONLINE - 1]->teardown() -> success
...
[CPUHP_ONLINE - N]->teardown() -> fail
[CPUHP_ONLINE - (N - 1)]->startup() -> success
[CPUHP_ONLINE - (N - 2)]->startup() -> fail
The CPU hotplug state machine stops right here and does not try to go back
down again because that would likely result in an endless loop::
[CPUHP_ONLINE - (N - 1)]->teardown() -> success
[CPUHP_ONLINE - N]->teardown() -> fail
[CPUHP_ONLINE - (N - 1)]->startup() -> success
[CPUHP_ONLINE - (N - 2)]->startup() -> fail
[CPUHP_ONLINE - (N - 1)]->teardown() -> success
[CPUHP_ONLINE - N]->teardown() -> fail
Lather, rinse and repeat. In this case the CPU left in state::
[CPUHP_ONLINE - (N - 1)]
which at least lets the system make progress and gives the user a chance to
debug or even resolve the situation.
Allocating a state
------------------
There are two ways to allocate a CPU hotplug state:
* Static allocation
Static allocation has to be used when the subsystem or driver has
ordering requirements versus other CPU hotplug states. E.g. the PERF core
startup callback has to be invoked before the PERF driver startup
callbacks during a CPU online operation. During a CPU offline operation
the driver teardown callbacks have to be invoked before the core teardown
callback. The statically allocated states are described by constants in
the cpuhp_state enum which can be found in include/linux/cpuhotplug.h.
Insert the state into the enum at the proper place so the ordering
requirements are fulfilled. The state constant has to be used for state
setup and removal.
Static allocation is also required when the state callbacks are not set
up at runtime and are part of the initializer of the CPU hotplug state
array in kernel/cpu.c.
* Dynamic allocation
When there are no ordering requirements for the state callbacks then
dynamic allocation is the preferred method. The state number is allocated
by the setup function and returned to the caller on success.
Only the PREPARE and ONLINE sections provide a dynamic allocation
range. The STARTING section does not as most of the callbacks in that
section have explicit ordering requirements.
Setup of a CPU hotplug state
----------------------------
The core code provides the following functions to setup a state:
* cpuhp_setup_state(state, name, startup, teardown)
* cpuhp_setup_state_nocalls(state, name, startup, teardown)
* cpuhp_setup_state_cpuslocked(state, name, startup, teardown)
* cpuhp_setup_state_nocalls_cpuslocked(state, name, startup, teardown)
For cases where a driver or a subsystem has multiple instances and the same
CPU hotplug state callbacks need to be invoked for each instance, the CPU
hotplug core provides multi-instance support. The advantage over driver
specific instance lists is that the instance related functions are fully
serialized against CPU hotplug operations and provide the automatic
invocations of the state callbacks on add and removal. To set up such a
multi-instance state the following function is available:
* cpuhp_setup_state_multi(state, name, startup, teardown)
The @state argument is either a statically allocated state or one of the
constants for dynamically allocated states - CPUHP_BP_PREPARE_DYN,
CPUHP_AP_ONLINE_DYN - depending on the state section (PREPARE, ONLINE) for
which a dynamic state should be allocated.
The @name argument is used for sysfs output and for instrumentation. The
naming convention is "subsys:mode" or "subsys/driver:mode",
e.g. "perf:mode" or "perf/x86:mode". The common mode names are:
======== =======================================================
prepare For states in the PREPARE section
dead For states in the PREPARE section which do not provide
a startup callback
starting For states in the STARTING section
dying For states in the STARTING section which do not provide
a startup callback
online For states in the ONLINE section
offline For states in the ONLINE section which do not provide
a startup callback
======== =======================================================
As the @name argument is only used for sysfs and instrumentation other mode
descriptors can be used as well if they describe the nature of the state
better than the common ones.
Examples for @name arguments: "perf/online", "perf/x86:prepare",
"RCU/tree:dying", "sched/waitempty"
The @startup argument is a function pointer to the callback which should be
invoked during a CPU online operation. If the usage site does not require a
startup callback set the pointer to NULL.
The @teardown argument is a function pointer to the callback which should
be invoked during a CPU offline operation. If the usage site does not
require a teardown callback set the pointer to NULL.
The functions differ in the way how the installed callbacks are treated:
* cpuhp_setup_state_nocalls(), cpuhp_setup_state_nocalls_cpuslocked()
and cpuhp_setup_state_multi() only install the callbacks
* cpuhp_setup_state() and cpuhp_setup_state_cpuslocked() install the
callbacks and invoke the @startup callback (if not NULL) for all online
CPUs which have currently a state greater than the newly installed
state. Depending on the state section the callback is either invoked on
the current CPU (PREPARE section) or on each online CPU (ONLINE
section) in the context of the CPU's hotplug thread.
If a callback fails for CPU N then the teardown callback for CPU
0 .. N-1 is invoked to rollback the operation. The state setup fails,
the callbacks for the state are not installed and in case of dynamic
allocation the allocated state is freed.
The state setup and the callback invocations are serialized against CPU
hotplug operations. If the setup function has to be called from a CPU
hotplug read locked region, then the _cpuslocked() variants have to be
used. These functions cannot be used from within CPU hotplug callbacks.
The function return values:
======== ===================================================================
0 Statically allocated state was successfully set up
>0 Dynamically allocated state was successfully set up.
The returned number is the state number which was allocated. If
the state callbacks have to be removed later, e.g. module
removal, then this number has to be saved by the caller and used
as @state argument for the state remove function. For
multi-instance states the dynamically allocated state number is
also required as @state argument for the instance add/remove
operations.
<0 Operation failed
======== ===================================================================
Removal of a CPU hotplug state
------------------------------
To remove a previously set up state, the following functions are provided:
* cpuhp_remove_state(state)
* cpuhp_remove_state_nocalls(state)
* cpuhp_remove_state_nocalls_cpuslocked(state)
* cpuhp_remove_multi_state(state)
The @state argument is either a statically allocated state or the state
number which was allocated in the dynamic range by cpuhp_setup_state*(). If
the state is in the dynamic range, then the state number is freed and
available for dynamic allocation again.
The functions differ in the way how the installed callbacks are treated:
* cpuhp_remove_state_nocalls(), cpuhp_remove_state_nocalls_cpuslocked()
and cpuhp_remove_multi_state() only remove the callbacks.
* cpuhp_remove_state() removes the callbacks and invokes the teardown
callback (if not NULL) for all online CPUs which have currently a state
greater than the removed state. Depending on the state section the
callback is either invoked on the current CPU (PREPARE section) or on
each online CPU (ONLINE section) in the context of the CPU's hotplug
thread.
In order to complete the removal, the teardown callback should not fail.
The state removal and the callback invocations are serialized against CPU
hotplug operations. If the remove function has to be called from a CPU
hotplug read locked region, then the _cpuslocked() variants have to be
used. These functions cannot be used from within CPU hotplug callbacks.
If a multi-instance state is removed then the caller has to remove all
instances first.
Multi-Instance state instance management
----------------------------------------
Once the multi-instance state is set up, instances can be added to the
state:
* cpuhp_state_add_instance(state, node)
* cpuhp_state_add_instance_nocalls(state, node)
The @state argument is either a statically allocated state or the state
number which was allocated in the dynamic range by cpuhp_setup_state_multi().
The @node argument is a pointer to an hlist_node which is embedded in the
instance's data structure. The pointer is handed to the multi-instance
state callbacks and can be used by the callback to retrieve the instance
via container_of().
The functions differ in the way how the installed callbacks are treated:
* cpuhp_state_add_instance_nocalls() and only adds the instance to the
multi-instance state's node list.
* cpuhp_state_add_instance() adds the instance and invokes the startup
callback (if not NULL) associated with @state for all online CPUs which
have currently a state greater than @state. The callback is only
invoked for the to be added instance. Depending on the state section
the callback is either invoked on the current CPU (PREPARE section) or
on each online CPU (ONLINE section) in the context of the CPU's hotplug
thread.
If a callback fails for CPU N then the teardown callback for CPU
0 .. N-1 is invoked to rollback the operation, the function fails and
the instance is not added to the node list of the multi-instance state.
To remove an instance from the state's node list these functions are
available:
* cpuhp_state_remove_instance(state, node)
* cpuhp_state_remove_instance_nocalls(state, node)
The arguments are the same as for the cpuhp_state_add_instance*()
variants above.
The functions differ in the way how the installed callbacks are treated:
* cpuhp_state_remove_instance_nocalls() only removes the instance from the
state's node list.
* cpuhp_state_remove_instance() removes the instance and invokes the
teardown callback (if not NULL) associated with @state for all online
CPUs which have currently a state greater than @state. The callback is
only invoked for the to be removed instance. Depending on the state
section the callback is either invoked on the current CPU (PREPARE
section) or on each online CPU (ONLINE section) in the context of the
CPU's hotplug thread.
In order to complete the removal, the teardown callback should not fail.
The node list add/remove operations and the callback invocations are
serialized against CPU hotplug operations. These functions cannot be used
from within CPU hotplug callbacks and CPU hotplug read locked regions.
Examples
--------
Setup and teardown a statically allocated state in the STARTING section for
notifications on online and offline operations::
ret = cpuhp_setup_state(CPUHP_SUBSYS_STARTING, "subsys:starting", subsys_cpu_starting, subsys_cpu_dying);
if (ret < 0)
return ret;
....
cpuhp_remove_state(CPUHP_SUBSYS_STARTING);
Setup and teardown a dynamically allocated state in the ONLINE section
for notifications on offline operations::
state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "subsys:offline", NULL, subsys_cpu_offline);
if (state < 0)
return state;
....
cpuhp_remove_state(state);
Setup and teardown a dynamically allocated state in the ONLINE section
for notifications on online operations without invoking the callbacks::
state = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "subsys:online", subsys_cpu_online, NULL);
if (state < 0)
return state;
....
cpuhp_remove_state_nocalls(state);
Setup, use and teardown a dynamically allocated multi-instance state in the
ONLINE section for notifications on online and offline operation::
state = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "subsys:online", subsys_cpu_online, subsys_cpu_offline);
if (state < 0)
return state;
....
ret = cpuhp_state_add_instance(state, &inst1->node);
if (ret)
return ret;
....
ret = cpuhp_state_add_instance(state, &inst2->node);
if (ret)
return ret;
....
cpuhp_remove_instance(state, &inst1->node);
....
cpuhp_remove_instance(state, &inst2->node);
....
cpuhp_remove_multi_state(state);
Testing of hotplug states
=========================
One way to verify whether a custom state is working as expected or not is to
shutdown a CPU and then put it online again. It is also possible to put the CPU
to certain state (for instance *CPUHP_AP_ONLINE*) and then go back to
*CPUHP_ONLINE*. This would simulate an error one state after *CPUHP_AP_ONLINE*
which would lead to rollback to the online state.
All registered states are enumerated in ``/sys/devices/system/cpu/hotplug/states`` ::
$ tail /sys/devices/system/cpu/hotplug/states
138: mm/vmscan:online
139: mm/vmstat:online
140: lib/percpu_cnt:online
141: acpi/cpu-drv:online
142: base/cacheinfo:online
143: virtio/net:online
144: x86/mce:online
145: printk:online
168: sched:active
169: online
To rollback CPU4 to ``lib/percpu_cnt:online`` and back online just issue::
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
169
$ echo 140 > /sys/devices/system/cpu/cpu4/hotplug/target
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
140
It is important to note that the teardown callback of state 140 have been
invoked. And now get back online::
$ echo 169 > /sys/devices/system/cpu/cpu4/hotplug/target
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
169
With trace events enabled, the individual steps are visible, too::
# TASK-PID CPU# TIMESTAMP FUNCTION
# | | | | |
bash-394 [001] 22.976: cpuhp_enter: cpu: 0004 target: 140 step: 169 (cpuhp_kick_ap_work)
cpuhp/4-31 [004] 22.977: cpuhp_enter: cpu: 0004 target: 140 step: 168 (sched_cpu_deactivate)
cpuhp/4-31 [004] 22.990: cpuhp_exit: cpu: 0004 state: 168 step: 168 ret: 0
cpuhp/4-31 [004] 22.991: cpuhp_enter: cpu: 0004 target: 140 step: 144 (mce_cpu_pre_down)
cpuhp/4-31 [004] 22.992: cpuhp_exit: cpu: 0004 state: 144 step: 144 ret: 0
cpuhp/4-31 [004] 22.993: cpuhp_multi_enter: cpu: 0004 target: 140 step: 143 (virtnet_cpu_down_prep)
cpuhp/4-31 [004] 22.994: cpuhp_exit: cpu: 0004 state: 143 step: 143 ret: 0
cpuhp/4-31 [004] 22.995: cpuhp_enter: cpu: 0004 target: 140 step: 142 (cacheinfo_cpu_pre_down)
cpuhp/4-31 [004] 22.996: cpuhp_exit: cpu: 0004 state: 142 step: 142 ret: 0
bash-394 [001] 22.997: cpuhp_exit: cpu: 0004 state: 140 step: 169 ret: 0
bash-394 [005] 95.540: cpuhp_enter: cpu: 0004 target: 169 step: 140 (cpuhp_kick_ap_work)
cpuhp/4-31 [004] 95.541: cpuhp_enter: cpu: 0004 target: 169 step: 141 (acpi_soft_cpu_online)
cpuhp/4-31 [004] 95.542: cpuhp_exit: cpu: 0004 state: 141 step: 141 ret: 0
cpuhp/4-31 [004] 95.543: cpuhp_enter: cpu: 0004 target: 169 step: 142 (cacheinfo_cpu_online)
cpuhp/4-31 [004] 95.544: cpuhp_exit: cpu: 0004 state: 142 step: 142 ret: 0
cpuhp/4-31 [004] 95.545: cpuhp_multi_enter: cpu: 0004 target: 169 step: 143 (virtnet_cpu_online)
cpuhp/4-31 [004] 95.546: cpuhp_exit: cpu: 0004 state: 143 step: 143 ret: 0
cpuhp/4-31 [004] 95.547: cpuhp_enter: cpu: 0004 target: 169 step: 144 (mce_cpu_online)
cpuhp/4-31 [004] 95.548: cpuhp_exit: cpu: 0004 state: 144 step: 144 ret: 0
cpuhp/4-31 [004] 95.549: cpuhp_enter: cpu: 0004 target: 169 step: 145 (console_cpu_notify)
cpuhp/4-31 [004] 95.550: cpuhp_exit: cpu: 0004 state: 145 step: 145 ret: 0
cpuhp/4-31 [004] 95.551: cpuhp_enter: cpu: 0004 target: 169 step: 168 (sched_cpu_activate)
cpuhp/4-31 [004] 95.552: cpuhp_exit: cpu: 0004 state: 168 step: 168 ret: 0
bash-394 [005] 95.553: cpuhp_exit: cpu: 0004 state: 169 step: 140 ret: 0
As it an be seen, CPU4 went down until timestamp 22.996 and then back up until
95.552. All invoked callbacks including their return codes are visible in the
trace.
Architecture's requirements
===========================
The following functions and configurations are required:
``CONFIG_HOTPLUG_CPU``
This entry needs to be enabled in Kconfig
``__cpu_up()``
Arch interface to bring up a CPU
``__cpu_disable()``
Arch interface to shutdown a CPU, no more interrupts can be handled by the
kernel after the routine returns. This includes the shutdown of the timer.
``__cpu_die()``
This actually supposed to ensure death of the CPU. Actually look at some
example code in other arch that implement CPU hotplug. The processor is taken
down from the ``idle()`` loop for that specific architecture. ``__cpu_die()``
typically waits for some per_cpu state to be set, to ensure the processor dead
routine is called to be sure positively.
User Space Notification
=======================
After CPU successfully onlined or offline udev events are sent. A udev rule like::
SUBSYSTEM=="cpu", DRIVERS=="processor", DEVPATH=="/devices/system/cpu/*", RUN+="the_hotplug_receiver.sh"
will receive all events. A script like::
#!/bin/sh
if [ "${ACTION}" = "offline" ]
then
echo "CPU ${DEVPATH##*/} offline"
elif [ "${ACTION}" = "online" ]
then
echo "CPU ${DEVPATH##*/} online"
fi
can process the event further.
When changes to the CPUs in the system occur, the sysfs file
/sys/devices/system/cpu/crash_hotplug contains '1' if the kernel
updates the kdump capture kernel list of CPUs itself (via elfcorehdr and
other relevant kexec segment), or '0' if userspace must update the kdump
capture kernel list of CPUs.
The availability depends on the CONFIG_HOTPLUG_CPU kernel configuration
option.
To skip userspace processing of CPU hot un/plug events for kdump
(i.e. the unload-then-reload to obtain a current list of CPUs), this sysfs
file can be used in a udev rule as follows:
SUBSYSTEM=="cpu", ATTRS{crash_hotplug}=="1", GOTO="kdump_reload_end"
For a CPU hot un/plug event, if the architecture supports kernel updates
of the elfcorehdr (which contains the list of CPUs) and other relevant
kexec segments, then the rule skips the unload-then-reload of the kdump
capture kernel.
Kernel Inline Documentations Reference
======================================
.. kernel-doc:: include/linux/cpuhotplug.h
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
CPU hotplug in the Kernel
1-30이 문서는 2021년 9월 기준이며 Sebastian Andrzej Siewior, Rusty Russell, Srivatsa Vaddagiri, Ashok Raj, Joel Schopp, Thomas Gleixner가 작성했습니다.
현대 processor는 고급 error reporting 및 correction 기능을 제공하며, 일부 OEM의 NUMA hardware는 physical node 자체를 hot-plug할 수 있습니다. 이런 node를 삽입하거나 제거하려면 CPU hotplug 지원이 필요합니다.
Kernel이 사용할 수 있는 CPU를 provisioning 목적으로 제거하거나, RAS 목적으로 문제가 있는 CPU를 system execution path에서 제외해야 하므로 Linux kernel에 CPU hotplug가 필요합니다.
CPU hotplug는 SMP suspend/resume에도 사용됩니다. Dual-core와 HT 때문에 과거 이 방식을 지원하지 않던 laptop도 SMP kernel로 동작하기 때문입니다.
Command Line Switches
31-52| Option | 효과 | 제한 |
|---|---|---|
| maxcpus=n | Boot 시 online으로 시작할 CPU를 n개로 제한합니다. 예를 들어 4개 중 maxcpus=2이면 2개만 boot하고 나머지는 나중에 online으로 전환할 수 있습니다. | 후속 online 가능 |
| nr_cpus=n | Kernel이 지원할 CPU 총수를 제한합니다. 물리 CPU 수보다 작게 지정하면 초과 CPU는 나중에도 online으로 만들 수 없습니다. | 지원 상한 |
| possible_cpus=n | cpu_possible_mask의 possible_cpus bit를 설정합니다. | X86, S390 전용 |
| cpu0_hotplug | CPU0 shutdown을 허용합니다. | X86 전용 |
CPU maps
53-86| Mask | 의미 | 변경 시점 |
|---|---|---|
| cpu_possible_mask | 시스템에서 언젠가 사용 가능할 수 있는 CPU의 bitmap입니다. CPU 증감에 맞춰 크기를 바꿀 수 없는 per_cpu variable의 boot-time memory를 할당하는 데 사용합니다. | Boot discovery에서 한 번 정해지며 이후 bit를 추가하거나 제거하지 않습니다. 정확히 줄이면 boot memory를 절약합니다. |
| cpu_online_mask | 현재 online인 모든 CPU의 bitmap입니다. | CPU가 scheduling과 device interrupt를 받을 준비가 된 뒤 __cpu_up()에서 set하고, OS service와 interrupt를 다른 CPU로 옮긴 뒤 __cpu_disable()에서 clear합니다. |
| cpu_present_mask | 현재 물리적으로 존재하는 CPU의 bitmap이며 모두 online일 필요는 없습니다. | ACPI 같은 subsystem이 physical hot-add/hot-remove를 처리할 때 bit가 추가 또는 제거될 수 있습니다. 현재 명확한 locking rule은 없고, 보통 hotplug가 disabled인 boot 중 topology 초기화에 사용합니다. |
대부분의 code는 system CPU map을 직접 조작할 필요가 없으며 read-only로 취급해야 합니다. Per-CPU resource를 설정할 때는 거의 항상 `cpu_possible_mask` 또는 `for_each_possible_cpu()`로 순회하고, custom mask는 `for_each_cpu()`로 순회합니다.
CPU bitmap은 반드시 `cpumask_t`로 표현해야 합니다.
sysfs로 CPU hotplug 사용하기
87-126Kernel option `CONFIG_HOTPLUG_CPU`를 enable해야 합니다. ARM, MIPS, PowerPC, X86을 비롯한 여러 architecture가 지원하며 sysfs interface로 구성합니다.
$ ls -lh /sys/devices/system/cpu
total 0
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu0
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu1
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu2
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu3
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu4
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu5
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu6
drwxr-xr-x 9 root root 0 Dec 21 16:33 cpu7
drwxr-xr-x 2 root root 0 Dec 21 16:33 hotplug
-r--r--r-- 1 root root 4.0K Dec 21 16:33 offline
-r--r--r-- 1 root root 4.0K Dec 21 16:33 online
-r--r--r-- 1 root root 4.0K Dec 21 16:33 possible
-r--r--r-- 1 root root 4.0K Dec 21 16:33 present
`offline`, `online`, `possible`, `present` file은 각각 CPU mask를 나타냅니다. 각 CPU directory의 `online` file은 logical on(1)과 off(0) 상태를 제어합니다. CPU4를 logical shutdown하려면 다음을 실행합니다.
$ echo 0 > /sys/devices/system/cpu/cpu4/online
smpboot: CPU 4 is now offline
Shutdown된 CPU는 `/proc/interrupts`와 `/proc/cpuinfo`에서 제거되고 `top`에도 나타나지 않아야 합니다. CPU4를 다시 online으로 만들려면 다음을 실행합니다.
$ echo 1 > /sys/devices/system/cpu/cpu4/online
smpboot: Booting Node 0 Processor 4 APIC 0x1
이제 CPU를 다시 사용할 수 있습니다. 모든 CPU에서 동작해야 하지만 CPU0은 특별하게 취급되어 CPU hotplug 대상에서 제외되는 경우가 많습니다.
CPU offline coordination
127-147CPU를 logical shutdown하면 등록된 hotplug state의 teardown callback을 `CPUHP_ONLINE`에서 시작해 `CPUHP_OFFLINE`까지 호출합니다.
- Suspend로 task가 frozen 상태이면 `cpuhp_tasks_frozen`을 true로 설정합니다.
- 나가는 CPU의 모든 process를 새 CPU로 migration합니다. 각 process의 현재 cpuset에서 대상 CPU를 고르므로 전체 online CPU의 subset일 수 있습니다.
- 해당 CPU를 대상으로 한 모든 interrupt를 새 CPU로 migration합니다.
- Timer도 새 CPU로 migration합니다.
- 모든 service를 옮긴 뒤 architecture-specific cleanup을 위해 `__cpu_disable()`을 호출합니다.
CPU hotplug state machine
148-171CPU hotplug는 `CPUHP_OFFLINE`부터 `CPUHP_ONLINE`까지 선형 state space를 갖는 단순한 state machine을 사용하며, 각 state에는 startup callback과 teardown callback이 있습니다.
CPU를 online으로 만들 때는 `CPUHP_ONLINE`에 도달할 때까지 startup callback을 순서대로 호출합니다. State callback을 설치하거나 multi-instance state에 instance를 추가할 때도 호출될 수 있습니다.
CPU를 offline으로 만들 때는 `CPUHP_OFFLINE`에 도달할 때까지 teardown callback을 역순으로 호출합니다. State callback을 제거하거나 multi-instance state에서 instance를 제거할 때도 호출될 수 있습니다.
사용 지점이 online 또는 offline 한 방향의 callback만 필요로 한다면 state를 설정할 때 필요 없는 다른 callback을 `NULL`로 지정할 수 있습니다.
PREPARE, STARTING, ONLINE section
172-229| Section | State 범위 | 실행 context | 실패 규칙과 용도 |
|---|---|---|---|
| PREPARE | CPUHP_OFFLINE부터 CPUHP_BRINGUP_CPU | Online 전 또는 CPU가 이미 dysfunctional해진 offline 후이므로 control CPU에서 실행 | Online에 필요한 resource를 준비하거나 offline 뒤 resource를 해제하고 pending work를 online CPU로 옮깁니다. Startup은 실패할 수 있고 실패하면 이전 state로 rollback합니다. Teardown은 실패할 수 없습니다. |
| STARTING | CPUHP_BRINGUP_CPU + 1부터 CPUHP_AP_ONLINE | Hotplugged CPU에서 interrupt disabled 상태로 early setup 또는 완전 shutdown 직전에 실행 | Low-level hardware와 core subsystem의 초기화 및 shutdown에 사용하며 callback은 실패할 수 없습니다. |
| ONLINE | CPUHP_AP_ONLINE + 1부터 CPUHP_ONLINE | Hotplugged CPU에 pin된 per-CPU hotplug thread context에서 interrupt와 preemption enabled 상태로 실행 | Callback은 실패할 수 있으며, 실패하면 hotplug operation을 중단하고 CPU를 이전 state로 되돌립니다. |
CPU online/offline state transition
230-337성공한 online operation은 startup callback을 state 오름차순으로 실행합니다.
NULL startup state는 건너뛰며 PREPARE, STARTING, ONLINE 순서로 진행합니다.
성공한 offline operation은 teardown callback을 state 내림차순으로 실행합니다.
ONLINE에서 STARTING과 PREPARE를 역순으로 지나 OFFLINE에 도달합니다.
Online 중 `CPUHP_AP_ONLINE + N`의 startup이 실패하면 이미 성공한 state의 teardown을 역순으로 호출하여 `CPUHP_OFFLINE`까지 rollback합니다.
실패 지점 직전부터 teardown을 역순으로 실행합니다.
Offline 중 `CPUHP_ONLINE - N`의 teardown이 실패하면 이미 내려간 state의 startup을 다시 호출하여 `CPUHP_ONLINE`으로 복구합니다.
실패한 teardown 위쪽 state를 startup으로 복원합니다.
Rollback callback까지 실패하는 recursive failure는 합리적으로 처리할 수 없습니다. 다시 아래로 내려가려 하면 같은 teardown 실패와 startup 실패를 반복하는 endless loop가 되기 때문입니다.
State machine은 반복을 막기 위해 두 번째 startup failure에서 정지합니다.
다시 teardown을 시작하면 같은 두 failure 사이를 끝없이 순환합니다.
이 경우 CPU는 `CPUHP_ONLINE - (N - 1)` state에 남습니다. 적어도 system이 계속 진행하고 user가 상황을 debug하거나 해결할 기회를 제공합니다.
Hotplug state 할당
338-370CPU hotplug state 할당 방식은 두 가지입니다.
- Static allocation: subsystem 또는 driver가 다른 hotplug state와의 ordering을 요구할 때 사용합니다. 예를 들어 online에서는 PERF core startup이 PERF driver startup보다 먼저, offline에서는 driver teardown이 core teardown보다 먼저여야 합니다. `include/linux/cpuhotplug.h`의 `cpuhp_state` enum에서 올바른 위치에 state를 삽입하고 그 상수를 setup 및 removal에 사용합니다. Callback이 runtime에 설치되지 않고 `kernel/cpu.c`의 state array initializer에 포함될 때도 static allocation이 필요합니다.
- Dynamic allocation: ordering requirement가 없을 때 선호합니다. Setup function이 state number를 할당해 성공 시 caller에게 반환합니다. Dynamic range는 PREPARE와 ONLINE에만 있고, 명시적인 ordering이 필요한 callback이 많은 STARTING에는 없습니다.
CPU hotplug state setup
371-423Core code는 state setup을 위해 다음 function을 제공합니다.
- cpuhp_setup_state(state, name, startup, teardown)
- cpuhp_setup_state_nocalls(state, name, startup, teardown)
- cpuhp_setup_state_cpuslocked(state, name, startup, teardown)
- cpuhp_setup_state_nocalls_cpuslocked(state, name, startup, teardown)
Driver 또는 subsystem에 instance가 여러 개이고 각 instance마다 같은 callback을 호출해야 하면 hotplug core의 multi-instance 지원을 사용합니다. Driver별 instance list와 달리 instance function은 CPU hotplug operation과 완전히 serialize되고 add/remove 때 callback을 자동으로 호출합니다.
- cpuhp_setup_state_multi(state, name, startup, teardown)
`@state`는 statically allocated state이거나 dynamic state 상수 `CPUHP_BP_PREPARE_DYN`, `CPUHP_AP_ONLINE_DYN` 가운데 section에 맞는 값입니다.
`@name`은 sysfs output과 instrumentation에 사용합니다. Naming convention은 `subsys:mode` 또는 `subsys/driver:mode`이며 `perf:mode`, `perf/x86:mode`가 예입니다.
| Mode | 대상 state |
|---|---|
| prepare | PREPARE section |
| dead | Startup callback이 없는 PREPARE state |
| starting | STARTING section |
| dying | Startup callback이 없는 STARTING state |
| online | ONLINE section |
| offline | Startup callback이 없는 ONLINE state |
`@name`은 sysfs와 instrumentation에만 쓰이므로 state 성격을 더 잘 설명한다면 다른 mode descriptor도 사용할 수 있습니다. 예는 `perf/online`, `perf/x86:prepare`, `RCU/tree:dying`, `sched/waitempty`입니다.
Setup callback 처리와 반환값
424-470`@startup`은 CPU online operation에서 호출할 callback function pointer이고, 필요 없으면 `NULL`로 둡니다. `@teardown`은 CPU offline operation에서 호출할 callback pointer이며 역시 필요 없으면 `NULL`로 둡니다.
- `cpuhp_setup_state_nocalls()`, `cpuhp_setup_state_nocalls_cpuslocked()`, `cpuhp_setup_state_multi()`는 callback만 설치합니다.
- `cpuhp_setup_state()`와 `cpuhp_setup_state_cpuslocked()`는 callback을 설치하고 현재 state가 새 state보다 높은 모든 online CPU에 non-NULL startup을 호출합니다. PREPARE에서는 current CPU, ONLINE에서는 각 CPU의 hotplug thread context에서 해당 online CPU에 호출합니다.
CPU N의 callback이 실패하면 CPU 0부터 N-1까지 teardown callback을 호출해 rollback합니다. Setup은 실패하고 callback은 설치되지 않으며 dynamic allocation이면 state도 해제됩니다.
State setup과 callback 호출은 CPU hotplug operation과 serialize됩니다. CPU hotplug read lock 영역에서 setup을 호출해야 하면 `_cpuslocked()` variant를 사용해야 하며, 이 function들은 CPU hotplug callback 내부에서 사용할 수 없습니다.
| Return | 의미 |
|---|---|
| 0 | Statically allocated state setup 성공 |
| >0 | Dynamically allocated state setup 성공. 반환된 state number를 저장하여 module removal의 remove function과 multi-instance add/remove의 @state로 사용해야 합니다. |
| <0 | Operation 실패 |
CPU hotplug state removal
471-507설치한 state를 제거하는 function은 다음과 같습니다.
- cpuhp_remove_state(state)
- cpuhp_remove_state_nocalls(state)
- cpuhp_remove_state_nocalls_cpuslocked(state)
- cpuhp_remove_multi_state(state)
`@state`는 static state 또는 `cpuhp_setup_state*()`가 dynamic range에서 할당한 state number입니다. Dynamic state를 제거하면 number도 해제되어 다시 할당할 수 있습니다.
- `cpuhp_remove_state_nocalls()`, `cpuhp_remove_state_nocalls_cpuslocked()`, `cpuhp_remove_multi_state()`는 callback만 제거합니다.
- `cpuhp_remove_state()`는 callback을 제거하고 현재 state가 제거된 state보다 높은 모든 online CPU에 non-NULL teardown을 호출합니다. PREPARE에서는 current CPU, ONLINE에서는 각 CPU hotplug thread context에서 호출합니다.
Removal을 완료하려면 teardown callback이 실패하지 않아야 합니다. Removal과 callback 호출은 hotplug operation과 serialize되며, read-locked 영역에서는 `_cpuslocked()` variant를 사용합니다. Hotplug callback 내부에서는 사용할 수 없습니다.
Multi-instance state를 제거하기 전에 caller가 모든 instance를 먼저 제거해야 합니다.
Multi-instance state 관리
508-569Multi-instance state를 설치한 뒤 다음 function으로 instance를 추가합니다.
- cpuhp_state_add_instance(state, node)
- cpuhp_state_add_instance_nocalls(state, node)
`@state`는 static state 또는 `cpuhp_setup_state_multi()`가 dynamic range에서 할당한 number입니다. `@node`는 instance data structure에 embedded된 `hlist_node` pointer이며 callback은 이를 받아 `container_of()`로 instance를 찾습니다.
- `cpuhp_state_add_instance_nocalls()`는 multi-instance state의 node list에 instance만 추가합니다.
- `cpuhp_state_add_instance()`는 instance를 추가하고 현재 state가 @state보다 높은 모든 online CPU에 해당 instance의 startup callback을 호출합니다. CPU N에서 실패하면 CPU 0부터 N-1까지 teardown으로 rollback하고 instance를 list에 추가하지 않습니다.
Instance를 제거하는 function은 다음과 같습니다.
- cpuhp_state_remove_instance(state, node)
- cpuhp_state_remove_instance_nocalls(state, node)
Argument는 위의 `cpuhp_state_add_instance*()` variant와 같습니다.
- `cpuhp_state_remove_instance_nocalls()`는 state node list에서 instance만 제거합니다.
- `cpuhp_state_remove_instance()`는 instance를 제거하고 현재 state가 @state보다 높은 모든 online CPU에 해당 instance의 non-NULL teardown callback을 호출합니다. Removal을 완료하려면 teardown이 실패하지 않아야 합니다.
Node list add/remove와 callback 호출은 CPU hotplug operation과 serialize됩니다. 이 function들은 CPU hotplug callback 내부나 CPU hotplug read-locked 영역에서 사용할 수 없습니다.
State setup 및 teardown 예제
570-621STARTING section의 statically allocated state를 online/offline notification용으로 설치하고 제거하는 예입니다.
ret = cpuhp_setup_state(CPUHP_SUBSYS_STARTING, "subsys:starting", subsys_cpu_starting, subsys_cpu_dying);
if (ret < 0)
return ret;
....
cpuhp_remove_state(CPUHP_SUBSYS_STARTING);
ONLINE section의 dynamically allocated state를 offline notification용으로 설치하고 제거하는 예입니다.
state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "subsys:offline", NULL, subsys_cpu_offline);
if (state < 0)
return state;
....
cpuhp_remove_state(state);
Callback을 즉시 호출하지 않고 ONLINE section의 dynamic state를 online notification용으로 설치하고 제거하는 예입니다.
state = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN, "subsys:online", subsys_cpu_online, NULL);
if (state < 0)
return state;
....
cpuhp_remove_state_nocalls(state);
ONLINE section의 dynamically allocated multi-instance state를 설치하고 두 instance를 추가한 뒤 제거하는 예입니다.
state = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN, "subsys:online", subsys_cpu_online, subsys_cpu_offline);
if (state < 0)
return state;
....
ret = cpuhp_state_add_instance(state, &inst1->node);
if (ret)
return ret;
....
ret = cpuhp_state_add_instance(state, &inst2->node);
if (ret)
return ret;
....
cpuhp_remove_instance(state, &inst1->node);
....
cpuhp_remove_instance(state, &inst2->node);
....
cpuhp_remove_multi_state(state);
Hotplug state 시험
622-692Custom state가 예상대로 동작하는지는 CPU를 shutdown했다가 다시 online으로 만들거나, CPU를 `CPUHP_AP_ONLINE` 같은 특정 state로 내렸다가 `CPUHP_ONLINE`으로 되돌려 확인할 수 있습니다. 후자는 AP_ONLINE 다음 state의 error와 online state로의 rollback을 simulate합니다.
등록된 모든 state는 `/sys/devices/system/cpu/hotplug/states`에 열거됩니다.
$ tail /sys/devices/system/cpu/hotplug/states
138: mm/vmscan:online
139: mm/vmstat:online
140: lib/percpu_cnt:online
141: acpi/cpu-drv:online
142: base/cacheinfo:online
143: virtio/net:online
144: x86/mce:online
145: printk:online
168: sched:active
169: online
CPU4를 `lib/percpu_cnt:online` state 140까지 rollback하는 예입니다.
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
169
$ echo 140 > /sys/devices/system/cpu/cpu4/hotplug/target
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
140
이 과정에서 state 140의 teardown callback도 호출됩니다. 다시 online으로 전환합니다.
$ echo 169 > /sys/devices/system/cpu/cpu4/hotplug/target
$ cat /sys/devices/system/cpu/cpu4/hotplug/state
169
Trace event를 enable하면 각 단계와 callback return code를 볼 수 있습니다.
# TASK-PID CPU# TIMESTAMP FUNCTION
# | | | | |
bash-394 [001] 22.976: cpuhp_enter: cpu: 0004 target: 140 step: 169 (cpuhp_kick_ap_work)
cpuhp/4-31 [004] 22.977: cpuhp_enter: cpu: 0004 target: 140 step: 168 (sched_cpu_deactivate)
cpuhp/4-31 [004] 22.990: cpuhp_exit: cpu: 0004 state: 168 step: 168 ret: 0
cpuhp/4-31 [004] 22.991: cpuhp_enter: cpu: 0004 target: 140 step: 144 (mce_cpu_pre_down)
cpuhp/4-31 [004] 22.992: cpuhp_exit: cpu: 0004 state: 144 step: 144 ret: 0
cpuhp/4-31 [004] 22.993: cpuhp_multi_enter: cpu: 0004 target: 140 step: 143 (virtnet_cpu_down_prep)
cpuhp/4-31 [004] 22.994: cpuhp_exit: cpu: 0004 state: 143 step: 143 ret: 0
cpuhp/4-31 [004] 22.995: cpuhp_enter: cpu: 0004 target: 140 step: 142 (cacheinfo_cpu_pre_down)
cpuhp/4-31 [004] 22.996: cpuhp_exit: cpu: 0004 state: 142 step: 142 ret: 0
bash-394 [001] 22.997: cpuhp_exit: cpu: 0004 state: 140 step: 169 ret: 0
bash-394 [005] 95.540: cpuhp_enter: cpu: 0004 target: 169 step: 140 (cpuhp_kick_ap_work)
cpuhp/4-31 [004] 95.541: cpuhp_enter: cpu: 0004 target: 169 step: 141 (acpi_soft_cpu_online)
cpuhp/4-31 [004] 95.542: cpuhp_exit: cpu: 0004 state: 141 step: 141 ret: 0
cpuhp/4-31 [004] 95.543: cpuhp_enter: cpu: 0004 target: 169 step: 142 (cacheinfo_cpu_online)
cpuhp/4-31 [004] 95.544: cpuhp_exit: cpu: 0004 state: 142 step: 142 ret: 0
cpuhp/4-31 [004] 95.545: cpuhp_multi_enter: cpu: 0004 target: 169 step: 143 (virtnet_cpu_online)
cpuhp/4-31 [004] 95.546: cpuhp_exit: cpu: 0004 state: 143 step: 143 ret: 0
cpuhp/4-31 [004] 95.547: cpuhp_enter: cpu: 0004 target: 169 step: 144 (mce_cpu_online)
cpuhp/4-31 [004] 95.548: cpuhp_exit: cpu: 0004 state: 144 step: 144 ret: 0
cpuhp/4-31 [004] 95.549: cpuhp_enter: cpu: 0004 target: 169 step: 145 (console_cpu_notify)
cpuhp/4-31 [004] 95.550: cpuhp_exit: cpu: 0004 state: 145 step: 145 ret: 0
cpuhp/4-31 [004] 95.551: cpuhp_enter: cpu: 0004 target: 169 step: 168 (sched_cpu_activate)
cpuhp/4-31 [004] 95.552: cpuhp_exit: cpu: 0004 state: 168 step: 168 ret: 0
bash-394 [005] 95.553: cpuhp_exit: cpu: 0004 state: 169 step: 140 ret: 0
Trace에서 CPU4는 timestamp 22.996까지 내려갔다가 95.552까지 다시 올라왔으며, 호출된 모든 callback과 return code가 표시됩니다.
Architecture requirements
693-714| 항목 | 요구 사항 |
|---|---|
| CONFIG_HOTPLUG_CPU | Kconfig에서 enable해야 합니다. |
| __cpu_up() | CPU를 기동하는 architecture interface입니다. |
| __cpu_disable() | CPU를 shutdown하는 architecture interface입니다. 반환 뒤에는 timer shutdown을 포함해 kernel이 더 이상 interrupt를 처리할 수 없어야 합니다. |
| __cpu_die() | CPU가 실제로 죽었음을 보장해야 합니다. Architecture별 idle() loop에서 processor를 내리며, 보통 CPU dead routine이 호출되었음을 확실히 하기 위해 특정 per_cpu state가 set되기를 기다립니다. |
User Space Notification
715-757CPU가 성공적으로 online 또는 offline이 되면 udev event를 보냅니다. 다음 rule로 모든 event를 받을 수 있습니다.
SUBSYSTEM=="cpu", DRIVERS=="processor", DEVPATH=="/devices/system/cpu/*", RUN+="the_hotplug_receiver.sh"
Event를 처리하는 script 예입니다.
#!/bin/sh
if [ "${ACTION}" = "offline" ]
then
echo "CPU ${DEVPATH##*/} offline"
elif [ "${ACTION}" = "online" ]
then
echo "CPU ${DEVPATH##*/} online"
fi
System CPU가 바뀔 때 `/sys/devices/system/cpu/crash_hotplug`는 kernel이 `elfcorehdr`와 관련 kexec segment를 통해 kdump capture kernel의 CPU list를 직접 갱신하면 `1`, userspace가 갱신해야 하면 `0`을 담습니다. 사용 가능 여부는 `CONFIG_HOTPLUG_CPU`에 달려 있습니다.
Kdump의 최신 CPU list를 얻기 위한 unload 후 reload를 생략하려면 다음 udev rule을 사용할 수 있습니다.
SUBSYSTEM=="cpu", ATTRS{crash_hotplug}=="1", GOTO="kdump_reload_end"
Architecture가 CPU list를 담은 `elfcorehdr`와 관련 kexec segment를 kernel에서 갱신할 수 있다면 이 rule은 CPU hot un/plug event에서 kdump capture kernel의 unload/reload를 건너뜁니다.
Kernel Inline Documentations Reference
758-761CPU hotplug API의 inline kernel-doc reference는 `include/linux/cpuhotplug.h`에서 가져옵니다.
.. kernel-doc:: include/linux/cpuhotplug.h
요약과 해설
cpu_hotplug.rst:1-761CPU hotplug는 CPU를 scheduler와 interrupt 처리에서 안전하게 빼거나 다시 합류시키기 위해 task, interrupt, timer를 migration하고 architecture callback과 subsystem callback을 순서대로 실행합니다.
State machine은 control CPU에서 실행되는 PREPARE, hotplug 대상 CPU에서 interrupt disabled로 실행되는 STARTING, per-CPU hotplug thread에서 실행되는 ONLINE section으로 나뉩니다. Callback 실패 시 완료된 단계를 역순으로 rollback합니다.
Subsystem은 ordering requirement에 따라 static 또는 dynamic state를 선택하고, setup/remove 및 multi-instance API를 CPU hotplug operation과 serialize하여 사용해야 합니다. Sysfs target과 trace event로 개별 state 전환도 시험할 수 있습니다.