← Documents Documentation/core-api/padata.rst GitHub 원문 ↗

Linux 6.18.37 · Core API

padata 병렬 실행 메커니즘

Padata의 직렬화 작업 제출, CPU 마스크 관리, 병렬·직렬 콜백 계약, 인스턴스 수명 주기와 다중 스레드 작업 인터페이스를 설명합니다.

Source pathDocumentation/core-api/padata.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약과 해설

padata.rst:1-178

Padata는 여러 CPU에서 작업을 병렬로 처리하면서 필요할 때 제출 순서를 보존하는 커널 메커니즘입니다. 직렬화 작업에서는 `padata_instance`가 전체 실행 정책과 CPU 마스크를 관리하고, 각 `padata_shell`이 서로 독립적인 작업 순서를 형성합니다.

각 `padata_priv` 작업은 잠들 수 없는 `parallel()` 콜백에서 처리되고, 완료 시 `padata_do_serial()`을 거쳐 요청한 CPU의 `serial()` 콜백으로 전달됩니다. 직렬 콜백은 제출 순서를 지키기 위해 지연될 수 있으며, 객체를 해제하기 전에는 모든 미완료 작업을 끝내야 합니다.

다중 스레드 모드는 주 스레드와 도우미 스레드가 청크 단위로 작업을 나눠 수행합니다. `padata_mt_job`과 범위 기반 스레드 함수를 준비한 뒤 `padata_do_multithreaded()`를 호출하면 완료 시점까지 동기적으로 기다립니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 =======================================
4 The padata parallel execution mechanism
5 =======================================
6
7 :Date: May 2020
8
9 Padata is a mechanism by which the kernel can farm jobs out to be done in
10 parallel on multiple CPUs while optionally retaining their ordering.
11
12 It was originally developed for IPsec, which needs to perform encryption and
13 decryption on large numbers of packets without reordering those packets. This
14 is currently the sole consumer of padata's serialized job support.
15
16 Padata also supports multithreaded jobs, splitting up the job evenly while load
17 balancing and coordinating between threads.
18
19 Running Serialized Jobs
20 =======================
21
22 Initializing
23 ------------
24
25 The first step in using padata to run serialized jobs is to set up a
26 padata_instance structure for overall control of how jobs are to be run::
27
28 #include <linux/padata.h>
29
30 struct padata_instance *padata_alloc(const char *name);
31
32 'name' simply identifies the instance.
33
34 Then, complete padata initialization by allocating a padata_shell::
35
36 struct padata_shell *padata_alloc_shell(struct padata_instance *pinst);
37
38 A padata_shell is used to submit a job to padata and allows a series of such
39 jobs to be serialized independently. A padata_instance may have one or more
40 padata_shells associated with it, each allowing a separate series of jobs.
41
42 Modifying cpumasks
43 ------------------
44
45 The CPUs used to run jobs can be changed in two ways, programmatically with
46 padata_set_cpumask() or via sysfs. The former is defined::
47
48 int padata_set_cpumask(struct padata_instance *pinst, int cpumask_type,
49 cpumask_var_t cpumask);
50
51 Here cpumask_type is one of PADATA_CPU_PARALLEL or PADATA_CPU_SERIAL, where a
52 parallel cpumask describes which processors will be used to execute jobs
53 submitted to this instance in parallel and a serial cpumask defines which
54 processors are allowed to be used as the serialization callback processor.
55 cpumask specifies the new cpumask to use.
56
57 There may be sysfs files for an instance's cpumasks. For example, pcrypt's
58 live in /sys/kernel/pcrypt/<instance-name>. Within an instance's directory
59 there are two files, parallel_cpumask and serial_cpumask, and either cpumask
60 may be changed by echoing a bitmask into the file, for example::
61
62 echo f > /sys/kernel/pcrypt/pencrypt/parallel_cpumask
63
64 Reading one of these files shows the user-supplied cpumask, which may be
65 different from the 'usable' cpumask.
66
67 Padata maintains two pairs of cpumasks internally, the user-supplied cpumasks
68 and the 'usable' cpumasks. (Each pair consists of a parallel and a serial
69 cpumask.) The user-supplied cpumasks default to all possible CPUs on instance
70 allocation and may be changed as above. The usable cpumasks are always a
71 subset of the user-supplied cpumasks and contain only the online CPUs in the
72 user-supplied masks; these are the cpumasks padata actually uses. So it is
73 legal to supply a cpumask to padata that contains offline CPUs. Once an
74 offline CPU in the user-supplied cpumask comes online, padata is going to use
75 it.
76
77 Changing the CPU masks are expensive operations, so it should not be done with
78 great frequency.
79
80 Running A Job
81 -------------
82
83 Actually submitting work to the padata instance requires the creation of a
84 padata_priv structure, which represents one job::
85
86 struct padata_priv {
87 /* Other stuff here... */
88 void (*parallel)(struct padata_priv *padata);
89 void (*serial)(struct padata_priv *padata);
90 };
91
92 This structure will almost certainly be embedded within some larger
93 structure specific to the work to be done. Most of its fields are private to
94 padata, but the structure should be zeroed at initialisation time, and the
95 parallel() and serial() functions should be provided. Those functions will
96 be called in the process of getting the work done as we will see
97 momentarily.
98
99 The submission of the job is done with::
100
101 int padata_do_parallel(struct padata_shell *ps,
102 struct padata_priv *padata, int *cb_cpu);
103
104 The ps and padata structures must be set up as described above; cb_cpu
105 points to the preferred CPU to be used for the final callback when the job is
106 done; it must be in the current instance's CPU mask (if not the cb_cpu pointer
107 is updated to point to the CPU actually chosen). The return value from
108 padata_do_parallel() is zero on success, indicating that the job is in
109 progress. -EBUSY means that somebody, somewhere else is messing with the
110 instance's CPU mask, while -EINVAL is a complaint about cb_cpu not being in the
111 serial cpumask, no online CPUs in the parallel or serial cpumasks, or a stopped
112 instance.
113
114 Each job submitted to padata_do_parallel() will, in turn, be passed to
115 exactly one call to the above-mentioned parallel() function, on one CPU, so
116 true parallelism is achieved by submitting multiple jobs. parallel() runs with
117 software interrupts disabled and thus cannot sleep. The parallel()
118 function gets the padata_priv structure pointer as its lone parameter;
119 information about the actual work to be done is probably obtained by using
120 container_of() to find the enclosing structure.
121
122 Note that parallel() has no return value; the padata subsystem assumes that
123 parallel() will take responsibility for the job from this point. The job
124 need not be completed during this call, but, if parallel() leaves work
125 outstanding, it should be prepared to be called again with a new job before
126 the previous one completes.
127
128 Serializing Jobs
129 ----------------
130
131 When a job does complete, parallel() (or whatever function actually finishes
132 the work) should inform padata of the fact with a call to::
133
134 void padata_do_serial(struct padata_priv *padata);
135
136 At some point in the future, padata_do_serial() will trigger a call to the
137 serial() function in the padata_priv structure. That call will happen on
138 the CPU requested in the initial call to padata_do_parallel(); it, too, is
139 run with local software interrupts disabled.
140 Note that this call may be deferred for a while since the padata code takes
141 pains to ensure that jobs are completed in the order in which they were
142 submitted.
143
144 Destroying
145 ----------
146
147 Cleaning up a padata instance predictably involves calling the two free
148 functions that correspond to the allocation in reverse::
149
150 void padata_free_shell(struct padata_shell *ps);
151 void padata_free(struct padata_instance *pinst);
152
153 It is the user's responsibility to ensure all outstanding jobs are complete
154 before any of the above are called.
155
156 Running Multithreaded Jobs
157 ==========================
158
159 A multithreaded job has a main thread and zero or more helper threads, with the
160 main thread participating in the job and then waiting until all helpers have
161 finished. padata splits the job into units called chunks, where a chunk is a
162 piece of the job that one thread completes in one call to the thread function.
163
164 A user has to do three things to run a multithreaded job. First, describe the
165 job by defining a padata_mt_job structure, which is explained in the Interface
166 section. This includes a pointer to the thread function, which padata will
167 call each time it assigns a job chunk to a thread. Then, define the thread
168 function, which accepts three arguments, ``start``, ``end``, and ``arg``, where
169 the first two delimit the range that the thread operates on and the last is a
170 pointer to the job's shared state, if any. Prepare the shared state, which is
171 typically allocated on the main thread's stack. Last, call
172 padata_do_multithreaded(), which will return once the job is finished.
173
174 Interface
175 =========
176
177 .. kernel-doc:: include/linux/padata.h
178 .. kernel-doc:: kernel/padata.c
179

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

padata 병렬 실행 메커니즘 개요

1-18

SPDX 라이선스 식별자는 GPL-2.0입니다.

padata 병렬 실행 메커니즘

작성 시점: 2020년 5월

Padata는 커널이 작업을 여러 CPU에 나누어 병렬로 수행하게 하면서, 선택적으로 작업 순서를 유지할 수 있도록 하는 메커니즘입니다.

원래는 많은 패킷의 순서를 바꾸지 않고 암호화와 복호화를 수행해야 하는 IPsec을 위해 개발되었습니다. 현재 padata의 직렬화 작업 지원을 사용하는 유일한 소비자도 IPsec입니다.

Padata는 작업을 고르게 나누고 스레드 사이의 부하 분산과 조정을 담당하는 다중 스레드 작업도 지원합니다.

직렬화 작업 실행

19-23

직렬화 작업 실행 (Running Serialized Jobs)

초기화 (Initializing)

인스턴스와 셸 초기화

24-41

Padata로 직렬화 작업을 실행하는 첫 단계는 작업 실행 방식을 전체적으로 제어할 `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-79

CPU 마스크 변경 (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`에서 추출합니다.