요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. SPDX-License-Identifier: GPL-2.0
=======================================
The padata parallel execution mechanism
=======================================
:Date: May 2020
Padata is a mechanism by which the kernel can farm jobs out to be done in
parallel on multiple CPUs while optionally retaining their ordering.
It was originally developed for IPsec, which needs to perform encryption and
decryption on large numbers of packets without reordering those packets. This
is currently the sole consumer of padata's serialized job support.
Padata also supports multithreaded jobs, splitting up the job evenly while load
balancing and coordinating between threads.
Running Serialized Jobs
=======================
Initializing
------------
The first step in using padata to run serialized jobs is to set up a
padata_instance structure for overall control of how jobs are to be run::
#include <linux/padata.h>
struct padata_instance *padata_alloc(const char *name);
'name' simply identifies the instance.
Then, complete padata initialization by allocating a padata_shell::
struct padata_shell *padata_alloc_shell(struct padata_instance *pinst);
A padata_shell is used to submit a job to padata and allows a series of such
jobs to be serialized independently. A padata_instance may have one or more
padata_shells associated with it, each allowing a separate series of jobs.
Modifying cpumasks
------------------
The CPUs used to run jobs can be changed in two ways, programmatically with
padata_set_cpumask() or via sysfs. The former is defined::
int padata_set_cpumask(struct padata_instance *pinst, int cpumask_type,
cpumask_var_t cpumask);
Here cpumask_type is one of PADATA_CPU_PARALLEL or PADATA_CPU_SERIAL, where a
parallel cpumask describes which processors will be used to execute jobs
submitted to this instance in parallel and a serial cpumask defines which
processors are allowed to be used as the serialization callback processor.
cpumask specifies the new cpumask to use.
There may be sysfs files for an instance's cpumasks. For example, pcrypt's
live in /sys/kernel/pcrypt/<instance-name>. Within an instance's directory
there are two files, parallel_cpumask and serial_cpumask, and either cpumask
may be changed by echoing a bitmask into the file, for example::
echo f > /sys/kernel/pcrypt/pencrypt/parallel_cpumask
Reading one of these files shows the user-supplied cpumask, which may be
different from the 'usable' cpumask.
Padata maintains two pairs of cpumasks internally, the user-supplied cpumasks
and the 'usable' cpumasks. (Each pair consists of a parallel and a serial
cpumask.) The user-supplied cpumasks default to all possible CPUs on instance
allocation and may be changed as above. The usable cpumasks are always a
subset of the user-supplied cpumasks and contain only the online CPUs in the
user-supplied masks; these are the cpumasks padata actually uses. So it is
legal to supply a cpumask to padata that contains offline CPUs. Once an
offline CPU in the user-supplied cpumask comes online, padata is going to use
it.
Changing the CPU masks are expensive operations, so it should not be done with
great frequency.
Running A Job
-------------
Actually submitting work to the padata instance requires the creation of a
padata_priv structure, which represents one job::
struct padata_priv {
/* Other stuff here... */
void (*parallel)(struct padata_priv *padata);
void (*serial)(struct padata_priv *padata);
};
This structure will almost certainly be embedded within some larger
structure specific to the work to be done. Most of its fields are private to
padata, but the structure should be zeroed at initialisation time, and the
parallel() and serial() functions should be provided. Those functions will
be called in the process of getting the work done as we will see
momentarily.
The submission of the job is done with::
int padata_do_parallel(struct padata_shell *ps,
struct padata_priv *padata, int *cb_cpu);
The ps and padata structures must be set up as described above; cb_cpu
points to the preferred CPU to be used for the final callback when the job is
done; it must be in the current instance's CPU mask (if not the cb_cpu pointer
is updated to point to the CPU actually chosen). The return value from
padata_do_parallel() is zero on success, indicating that the job is in
progress. -EBUSY means that somebody, somewhere else is messing with the
instance's CPU mask, while -EINVAL is a complaint about cb_cpu not being in the
serial cpumask, no online CPUs in the parallel or serial cpumasks, or a stopped
instance.
Each job submitted to padata_do_parallel() will, in turn, be passed to
exactly one call to the above-mentioned parallel() function, on one CPU, so
true parallelism is achieved by submitting multiple jobs. parallel() runs with
software interrupts disabled and thus cannot sleep. The parallel()
function gets the padata_priv structure pointer as its lone parameter;
information about the actual work to be done is probably obtained by using
container_of() to find the enclosing structure.
Note that parallel() has no return value; the padata subsystem assumes that
parallel() will take responsibility for the job from this point. The job
need not be completed during this call, but, if parallel() leaves work
outstanding, it should be prepared to be called again with a new job before
the previous one completes.
Serializing Jobs
----------------
When a job does complete, parallel() (or whatever function actually finishes
the work) should inform padata of the fact with a call to::
void padata_do_serial(struct padata_priv *padata);
At some point in the future, padata_do_serial() will trigger a call to the
serial() function in the padata_priv structure. That call will happen on
the CPU requested in the initial call to padata_do_parallel(); it, too, is
run with local software interrupts disabled.
Note that this call may be deferred for a while since the padata code takes
pains to ensure that jobs are completed in the order in which they were
submitted.
Destroying
----------
Cleaning up a padata instance predictably involves calling the two free
functions that correspond to the allocation in reverse::
void padata_free_shell(struct padata_shell *ps);
void padata_free(struct padata_instance *pinst);
It is the user's responsibility to ensure all outstanding jobs are complete
before any of the above are called.
Running Multithreaded Jobs
==========================
A multithreaded job has a main thread and zero or more helper threads, with the
main thread participating in the job and then waiting until all helpers have
finished. padata splits the job into units called chunks, where a chunk is a
piece of the job that one thread completes in one call to the thread function.
A user has to do three things to run a multithreaded job. First, describe the
job by defining a padata_mt_job structure, which is explained in the Interface
section. This includes a pointer to the thread function, which padata will
call each time it assigns a job chunk to a thread. Then, define the thread
function, which accepts three arguments, ``start``, ``end``, and ``arg``, where
the first two delimit the range that the thread operates on and the last is a
pointer to the job's shared state, if any. Prepare the shared state, which is
typically allocated on the main thread's stack. Last, call
padata_do_multithreaded(), which will return once the job is finished.
Interface
=========
.. kernel-doc:: include/linux/padata.h
.. kernel-doc:: kernel/padata.c
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
padata 병렬 실행 메커니즘 개요
1-18SPDX 라이선스 식별자는 GPL-2.0입니다.
padata 병렬 실행 메커니즘
작성 시점: 2020년 5월
Padata는 커널이 작업을 여러 CPU에 나누어 병렬로 수행하게 하면서, 선택적으로 작업 순서를 유지할 수 있도록 하는 메커니즘입니다.
원래는 많은 패킷의 순서를 바꾸지 않고 암호화와 복호화를 수행해야 하는 IPsec을 위해 개발되었습니다. 현재 padata의 직렬화 작업 지원을 사용하는 유일한 소비자도 IPsec입니다.
Padata는 작업을 고르게 나누고 스레드 사이의 부하 분산과 조정을 담당하는 다중 스레드 작업도 지원합니다.
직렬화 작업 실행
19-23직렬화 작업 실행 (Running Serialized Jobs)
초기화 (Initializing)
인스턴스와 셸 초기화
24-41Padata로 직렬화 작업을 실행하는 첫 단계는 작업 실행 방식을 전체적으로 제어할 `padata_instance` 구조체를 준비하는 것입니다.
#include <linux/padata.h>
struct padata_instance *padata_alloc(const char *name);
`name`은 해당 인스턴스를 식별하는 이름일 뿐입니다.
그다음 `padata_shell`을 할당하여 padata 초기화를 마칩니다.
struct padata_shell *padata_alloc_shell(struct padata_instance *pinst);
`padata_shell`은 작업을 padata에 제출하는 데 사용되며, 일련의 작업을 다른 작업열과 독립적으로 직렬화할 수 있게 합니다. 하나의 `padata_instance`에는 하나 이상의 `padata_shell`이 연결될 수 있고, 각 셸은 서로 별개의 작업열을 제공합니다.
CPU 마스크 변경
42-79CPU 마스크 변경 (Modifying cpumasks)
작업 실행에 사용할 CPU는 두 가지 방법으로 바꿀 수 있습니다. 프로그램에서 `padata_set_cpumask()`를 호출하거나 sysfs를 사용할 수 있습니다. 함수 원형은 다음과 같습니다.
int padata_set_cpumask(struct padata_instance *pinst, int cpumask_type,
cpumask_var_t cpumask);
`cpumask_type`은 `PADATA_CPU_PARALLEL` 또는 `PADATA_CPU_SERIAL`입니다. 병렬 CPU 마스크는 이 인스턴스에 제출된 작업을 병렬로 실행할 프로세서를 나타냅니다. 직렬 CPU 마스크는 직렬화 콜백 프로세서로 사용할 수 있는 프로세서를 정의합니다. `cpumask`는 새로 적용할 CPU 마스크입니다.
인스턴스의 CPU 마스크를 다루는 sysfs 파일이 존재할 수도 있습니다. 예를 들어 pcrypt의 파일은 `/sys/kernel/pcrypt/<instance-name>`에 있습니다. 인스턴스 디렉터리에는 `parallel_cpumask`와 `serial_cpumask`라는 두 파일이 있으며, 다음처럼 비트마스크를 파일에 쓰면 어느 마스크든 변경할 수 있습니다.
echo f > /sys/kernel/pcrypt/pencrypt/parallel_cpumask
이 파일 중 하나를 읽으면 사용자가 제공한 CPU 마스크가 표시됩니다. 이 값은 실제로 사용할 수 있는 'usable' CPU 마스크와 다를 수 있습니다.
Padata는 내부적으로 두 쌍의 CPU 마스크를 유지합니다. 하나는 사용자가 제공한 마스크이고 다른 하나는 'usable' 마스크이며, 각 쌍은 병렬 마스크와 직렬 마스크로 구성됩니다. 인스턴스를 할당할 때 사용자 제공 마스크의 기본값은 가능한 모든 CPU이고, 앞에서 설명한 방법으로 바꿀 수 있습니다.
Usable 마스크는 언제나 사용자 제공 마스크의 부분집합이며, 사용자 제공 마스크에 포함된 CPU 중 온라인 상태인 CPU만 담습니다. Padata가 실제로 사용하는 것은 이 usable 마스크입니다. 따라서 오프라인 CPU를 포함한 CPU 마스크를 padata에 제공해도 적법합니다. 사용자 제공 마스크에 포함된 오프라인 CPU가 온라인 상태가 되면 padata가 그 CPU를 사용하기 시작합니다.
CPU 마스크 변경은 비용이 큰 작업이므로 지나치게 자주 수행해서는 안 됩니다.
작업 구조체 준비
80-98작업 실행 (Running A Job)
Padata 인스턴스에 실제 작업을 제출하려면 작업 하나를 나타내는 `padata_priv` 구조체를 만들어야 합니다.
struct padata_priv {
/* Other stuff here... */
void (*parallel)(struct padata_priv *padata);
void (*serial)(struct padata_priv *padata);
};
이 구조체는 수행할 작업에 특화된 더 큰 구조체 안에 포함되는 경우가 거의 확실합니다. 대부분의 필드는 padata 내부 전용이지만, 초기화할 때 구조체 전체를 0으로 채우고 `parallel()`과 `serial()` 함수를 제공해야 합니다. 다음 절에서 설명하듯 작업 처리 과정에서 이 두 함수가 호출됩니다.
작업 제출과 반환값
99-113작업 제출은 다음 함수로 수행합니다.
int padata_do_parallel(struct padata_shell *ps,
struct padata_priv *padata, int *cb_cpu);
`ps`와 `padata` 구조체는 앞서 설명한 대로 설정되어 있어야 합니다. `cb_cpu`는 작업 완료 뒤 최종 콜백을 실행할 선호 CPU를 가리킵니다. 이 CPU는 현재 인스턴스의 CPU 마스크 안에 있어야 하며, 그렇지 않으면 `cb_cpu` 포인터가 실제로 선택된 CPU를 가리키도록 갱신됩니다.
`padata_do_parallel()`이 0을 반환하면 제출에 성공했고 작업이 진행 중이라는 뜻입니다. `-EBUSY`는 다른 곳에서 인스턴스의 CPU 마스크를 변경하고 있음을 나타냅니다. `-EINVAL`은 `cb_cpu`가 직렬 CPU 마스크에 없거나, 병렬 또는 직렬 CPU 마스크에 온라인 CPU가 없거나, 인스턴스가 중지된 경우를 뜻합니다.
병렬 콜백 실행 규칙
114-127`padata_do_parallel()`에 제출한 각 작업은 정확히 한 번, 하나의 CPU에서 앞서 언급한 `parallel()` 함수로 전달됩니다. 따라서 진정한 병렬성은 여러 작업을 제출함으로써 얻습니다.
`parallel()`은 소프트웨어 인터럽트가 비활성화된 상태에서 실행되므로 잠들 수 없습니다. 이 함수가 받는 유일한 인자는 `padata_priv` 구조체 포인터입니다. 실제로 수행할 작업에 관한 정보는 대개 `container_of()`로 이를 감싸는 구조체를 찾아 얻습니다.
`parallel()`에는 반환값이 없습니다. Padata 하위 시스템은 이 시점부터 `parallel()`이 작업을 책임진다고 가정합니다. 이 호출 안에서 작업을 끝낼 필요는 없지만, 미완료 작업을 남긴다면 이전 작업이 끝나기 전에 새 작업과 함께 다시 호출될 수 있음을 고려해야 합니다.
작업 직렬화와 완료 순서
128-143작업 직렬화 (Serializing Jobs)
작업이 끝나면 `parallel()` 또는 실제로 작업을 완료한 함수가 다음 호출로 그 사실을 padata에 알려야 합니다.
void padata_do_serial(struct padata_priv *padata);
이후 어느 시점에 `padata_do_serial()`이 `padata_priv` 구조체의 `serial()` 함수를 호출합니다. 이 호출은 처음 `padata_do_parallel()`을 호출할 때 요청한 CPU에서 이루어지며, 역시 로컬 소프트웨어 인터럽트가 비활성화된 상태로 실행됩니다.
Padata 코드는 작업이 제출된 순서대로 완료되도록 세심하게 보장하므로 `serial()` 호출이 한동안 지연될 수 있습니다.
인스턴스 해제
144-155해제 (Destroying)
Padata 인스턴스를 정리할 때는 예상대로 할당 함수에 대응하는 두 해제 함수를 할당의 역순으로 호출합니다.
void padata_free_shell(struct padata_shell *ps);
void padata_free(struct padata_instance *pinst);
위 함수를 호출하기 전에 보류 중인 모든 작업이 완료되었는지 확인하는 책임은 사용자에게 있습니다.
다중 스레드 작업 실행
156-173다중 스레드 작업 실행 (Running Multithreaded Jobs)
다중 스레드 작업에는 주 스레드와 0개 이상의 도우미 스레드가 있습니다. 주 스레드도 작업에 참여한 뒤 모든 도우미가 끝날 때까지 기다립니다. Padata는 작업을 청크라는 단위로 나누며, 청크는 한 스레드가 스레드 함수를 한 번 호출하여 완료하는 작업 조각입니다.
사용자가 다중 스레드 작업을 실행하려면 세 가지를 해야 합니다. 먼저 인터페이스 절에서 설명하는 `padata_mt_job` 구조체를 정의하여 작업을 기술합니다. 여기에는 padata가 스레드에 작업 청크를 할당할 때마다 호출할 스레드 함수 포인터도 포함됩니다.
다음으로 `start`, `end`, `arg`라는 세 인자를 받는 스레드 함수를 정의합니다. 앞의 두 인자는 스레드가 처리할 범위를 정하고, 마지막 인자는 존재하는 경우 작업의 공유 상태를 가리킵니다. 공유 상태는 일반적으로 주 스레드의 스택에 할당하여 준비합니다.
마지막으로 `padata_do_multithreaded()`를 호출합니다. 이 함수는 작업이 완료된 뒤 반환합니다.
커널 문서 인터페이스
174-178인터페이스 (Interface)
공개 인터페이스는 `include/linux/padata.h`에서, 구현 함수의 커널 문서는 `kernel/padata.c`에서 추출합니다.
요약과 해설
padata.rst:1-178Padata는 여러 CPU에서 작업을 병렬로 처리하면서 필요할 때 제출 순서를 보존하는 커널 메커니즘입니다. 직렬화 작업에서는 `padata_instance`가 전체 실행 정책과 CPU 마스크를 관리하고, 각 `padata_shell`이 서로 독립적인 작업 순서를 형성합니다.
각 `padata_priv` 작업은 잠들 수 없는 `parallel()` 콜백에서 처리되고, 완료 시 `padata_do_serial()`을 거쳐 요청한 CPU의 `serial()` 콜백으로 전달됩니다. 직렬 콜백은 제출 순서를 지키기 위해 지연될 수 있으며, 객체를 해제하기 전에는 모든 미완료 작업을 끝내야 합니다.
다중 스레드 모드는 주 스레드와 도우미 스레드가 청크 단위로 작업을 나눠 수행합니다. `padata_mt_job`과 범위 기반 스레드 함수를 준비한 뒤 `padata_do_multithreaded()`를 호출하면 완료 시점까지 동기적으로 기다립니다.