← Documents Documentation/bpf/cpumasks.rst GitHub 원문 ↗

Linux 6.18.37 · BPF

BPF cpumask kfuncs

BPF cpumask object의 lifecycle, RCU kptr 사용, mutation·query kfunc와 selftest 확장 절차를 설명합니다.

Source pathDocumentation/bpf/cpumasks.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약과 해설

cpumasks.rst:1-384

`struct bpf_cpumask *`는 BPF가 lifecycle을 관리하는 mutable·RCU-protected cpumask이며 map kptr로 저장할 수 있습니다. `create/acquire/release` ownership 규칙과 `bpf_kptr_xchg()`, RCU read-side protection을 지켜야 안전하게 공유할 수 있습니다.

mutating kfunc는 `struct bpf_cpumask *`를 받고 read-only query kfunc는 `struct cpumask *`를 받습니다. wrapper에서 base cpumask로의 cast만 안전하며 반대 방향 cast는 verifier가 거부합니다.

API는 CPU bit set/clear, atomic test-and-update, 전체 mask 변경, AND/OR/XOR/copy, first/weight/equal/subset/distribution query를 제공합니다. 새 kfunc를 추가할 때는 문서와 `cpumask_success.c` selftest도 함께 갱신해야 합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0
2
3 .. _cpumasks-header-label:
4
5 ==================
6 BPF cpumask kfuncs
7 ==================
8
9 1. Introduction
10 ===============
11
12 ``struct cpumask`` is a bitmap data structure in the kernel whose indices
13 reflect the CPUs on the system. Commonly, cpumasks are used to track which CPUs
14 a task is affinitized to, but they can also be used to e.g. track which cores
15 are associated with a scheduling domain, which cores on a machine are idle,
16 etc.
17
18 BPF provides programs with a set of :ref:`kfuncs-header-label` that can be
19 used to allocate, mutate, query, and free cpumasks.
20
21 2. BPF cpumask objects
22 ======================
23
24 There are two different types of cpumasks that can be used by BPF programs.
25
26 2.1 ``struct bpf_cpumask *``
27 ----------------------------
28
29 ``struct bpf_cpumask *`` is a cpumask that is allocated by BPF, on behalf of a
30 BPF program, and whose lifecycle is entirely controlled by BPF. These cpumasks
31 are RCU-protected, can be mutated, can be used as kptrs, and can be safely cast
32 to a ``struct cpumask *``.
33
34 2.1.1 ``struct bpf_cpumask *`` lifecycle
35 ----------------------------------------
36
37 A ``struct bpf_cpumask *`` is allocated, acquired, and released, using the
38 following functions:
39
40 .. kernel-doc:: kernel/bpf/cpumask.c
41 :identifiers: bpf_cpumask_create
42
43 .. kernel-doc:: kernel/bpf/cpumask.c
44 :identifiers: bpf_cpumask_acquire
45
46 .. kernel-doc:: kernel/bpf/cpumask.c
47 :identifiers: bpf_cpumask_release
48
49 For example:
50
51 .. code-block:: c
52
53 struct cpumask_map_value {
54 struct bpf_cpumask __kptr * cpumask;
55 };
56
57 struct array_map {
58 __uint(type, BPF_MAP_TYPE_ARRAY);
59 __type(key, int);
60 __type(value, struct cpumask_map_value);
61 __uint(max_entries, 65536);
62 } cpumask_map SEC(".maps");
63
64 static int cpumask_map_insert(struct bpf_cpumask *mask, u32 pid)
65 {
66 struct cpumask_map_value local, *v;
67 long status;
68 struct bpf_cpumask *old;
69 u32 key = pid;
70
71 local.cpumask = NULL;
72 status = bpf_map_update_elem(&cpumask_map, &key, &local, 0);
73 if (status) {
74 bpf_cpumask_release(mask);
75 return status;
76 }
77
78 v = bpf_map_lookup_elem(&cpumask_map, &key);
79 if (!v) {
80 bpf_cpumask_release(mask);
81 return -ENOENT;
82 }
83
84 old = bpf_kptr_xchg(&v->cpumask, mask);
85 if (old)
86 bpf_cpumask_release(old);
87
88 return 0;
89 }
90
91 /**
92 * A sample tracepoint showing how a task's cpumask can be queried and
93 * recorded as a kptr.
94 */
95 SEC("tp_btf/task_newtask")
96 int BPF_PROG(record_task_cpumask, struct task_struct *task, u64 clone_flags)
97 {
98 struct bpf_cpumask *cpumask;
99 int ret;
100
101 cpumask = bpf_cpumask_create();
102 if (!cpumask)
103 return -ENOMEM;
104
105 if (!bpf_cpumask_full(task->cpus_ptr))
106 bpf_printk("task %s has CPU affinity", task->comm);
107
108 bpf_cpumask_copy(cpumask, task->cpus_ptr);
109 return cpumask_map_insert(cpumask, task->pid);
110 }
111
112 ----
113
114 2.1.1 ``struct bpf_cpumask *`` as kptrs
115 ---------------------------------------
116
117 As mentioned and illustrated above, these ``struct bpf_cpumask *`` objects can
118 also be stored in a map and used as kptrs. If a ``struct bpf_cpumask *`` is in
119 a map, the reference can be removed from the map with bpf_kptr_xchg(), or
120 opportunistically acquired using RCU:
121
122 .. code-block:: c
123
124 /* struct containing the struct bpf_cpumask kptr which is stored in the map. */
125 struct cpumasks_kfunc_map_value {
126 struct bpf_cpumask __kptr * bpf_cpumask;
127 };
128
129 /* The map containing struct cpumasks_kfunc_map_value entries. */
130 struct {
131 __uint(type, BPF_MAP_TYPE_ARRAY);
132 __type(key, int);
133 __type(value, struct cpumasks_kfunc_map_value);
134 __uint(max_entries, 1);
135 } cpumasks_kfunc_map SEC(".maps");
136
137 /* ... */
138
139 /**
140 * A simple example tracepoint program showing how a
141 * struct bpf_cpumask * kptr that is stored in a map can
142 * be passed to kfuncs using RCU protection.
143 */
144 SEC("tp_btf/cgroup_mkdir")
145 int BPF_PROG(cgrp_ancestor_example, struct cgroup *cgrp, const char *path)
146 {
147 struct bpf_cpumask *kptr;
148 struct cpumasks_kfunc_map_value *v;
149 u32 key = 0;
150
151 /* Assume a bpf_cpumask * kptr was previously stored in the map. */
152 v = bpf_map_lookup_elem(&cpumasks_kfunc_map, &key);
153 if (!v)
154 return -ENOENT;
155
156 bpf_rcu_read_lock();
157 /* Acquire a reference to the bpf_cpumask * kptr that's already stored in the map. */
158 kptr = v->cpumask;
159 if (!kptr) {
160 /* If no bpf_cpumask was present in the map, it's because
161 * we're racing with another CPU that removed it with
162 * bpf_kptr_xchg() between the bpf_map_lookup_elem()
163 * above, and our load of the pointer from the map.
164 */
165 bpf_rcu_read_unlock();
166 return -EBUSY;
167 }
168
169 bpf_cpumask_setall(kptr);
170 bpf_rcu_read_unlock();
171
172 return 0;
173 }
174
175 ----
176
177 2.2 ``struct cpumask``
178 ----------------------
179
180 ``struct cpumask`` is the object that actually contains the cpumask bitmap
181 being queried, mutated, etc. A ``struct bpf_cpumask`` wraps a ``struct
182 cpumask``, which is why it's safe to cast it as such (note however that it is
183 **not** safe to cast a ``struct cpumask *`` to a ``struct bpf_cpumask *``, and
184 the verifier will reject any program that tries to do so).
185
186 As we'll see below, any kfunc that mutates its cpumask argument will take a
187 ``struct bpf_cpumask *`` as that argument. Any argument that simply queries the
188 cpumask will instead take a ``struct cpumask *``.
189
190 3. cpumask kfuncs
191 =================
192
193 Above, we described the kfuncs that can be used to allocate, acquire, release,
194 etc a ``struct bpf_cpumask *``. This section of the document will describe the
195 kfuncs for mutating and querying cpumasks.
196
197 3.1 Mutating cpumasks
198 ---------------------
199
200 Some cpumask kfuncs are "read-only" in that they don't mutate any of their
201 arguments, whereas others mutate at least one argument (which means that the
202 argument must be a ``struct bpf_cpumask *``, as described above).
203
204 This section will describe all of the cpumask kfuncs which mutate at least one
205 argument. :ref:`cpumasks-querying-label` below describes the read-only kfuncs.
206
207 3.1.1 Setting and clearing CPUs
208 -------------------------------
209
210 bpf_cpumask_set_cpu() and bpf_cpumask_clear_cpu() can be used to set and clear
211 a CPU in a ``struct bpf_cpumask`` respectively:
212
213 .. kernel-doc:: kernel/bpf/cpumask.c
214 :identifiers: bpf_cpumask_set_cpu bpf_cpumask_clear_cpu
215
216 These kfuncs are pretty straightforward, and can be used, for example, as
217 follows:
218
219 .. code-block:: c
220
221 /**
222 * A sample tracepoint showing how a cpumask can be queried.
223 */
224 SEC("tp_btf/task_newtask")
225 int BPF_PROG(test_set_clear_cpu, struct task_struct *task, u64 clone_flags)
226 {
227 struct bpf_cpumask *cpumask;
228
229 cpumask = bpf_cpumask_create();
230 if (!cpumask)
231 return -ENOMEM;
232
233 bpf_cpumask_set_cpu(0, cpumask);
234 if (!bpf_cpumask_test_cpu(0, cast(cpumask)))
235 /* Should never happen. */
236 goto release_exit;
237
238 bpf_cpumask_clear_cpu(0, cpumask);
239 if (bpf_cpumask_test_cpu(0, cast(cpumask)))
240 /* Should never happen. */
241 goto release_exit;
242
243 /* struct cpumask * pointers such as task->cpus_ptr can also be queried. */
244 if (bpf_cpumask_test_cpu(0, task->cpus_ptr))
245 bpf_printk("task %s can use CPU %d", task->comm, 0);
246
247 release_exit:
248 bpf_cpumask_release(cpumask);
249 return 0;
250 }
251
252 ----
253
254 bpf_cpumask_test_and_set_cpu() and bpf_cpumask_test_and_clear_cpu() are
255 complementary kfuncs that allow callers to atomically test and set (or clear)
256 CPUs:
257
258 .. kernel-doc:: kernel/bpf/cpumask.c
259 :identifiers: bpf_cpumask_test_and_set_cpu bpf_cpumask_test_and_clear_cpu
260
261 ----
262
263 We can also set and clear entire ``struct bpf_cpumask *`` objects in one
264 operation using bpf_cpumask_setall() and bpf_cpumask_clear():
265
266 .. kernel-doc:: kernel/bpf/cpumask.c
267 :identifiers: bpf_cpumask_setall bpf_cpumask_clear
268
269 3.1.2 Operations between cpumasks
270 ---------------------------------
271
272 In addition to setting and clearing individual CPUs in a single cpumask,
273 callers can also perform bitwise operations between multiple cpumasks using
274 bpf_cpumask_and(), bpf_cpumask_or(), and bpf_cpumask_xor():
275
276 .. kernel-doc:: kernel/bpf/cpumask.c
277 :identifiers: bpf_cpumask_and bpf_cpumask_or bpf_cpumask_xor
278
279 The following is an example of how they may be used. Note that some of the
280 kfuncs shown in this example will be covered in more detail below.
281
282 .. code-block:: c
283
284 /**
285 * A sample tracepoint showing how a cpumask can be mutated using
286 bitwise operators (and queried).
287 */
288 SEC("tp_btf/task_newtask")
289 int BPF_PROG(test_and_or_xor, struct task_struct *task, u64 clone_flags)
290 {
291 struct bpf_cpumask *mask1, *mask2, *dst1, *dst2;
292
293 mask1 = bpf_cpumask_create();
294 if (!mask1)
295 return -ENOMEM;
296
297 mask2 = bpf_cpumask_create();
298 if (!mask2) {
299 bpf_cpumask_release(mask1);
300 return -ENOMEM;
301 }
302
303 // ...Safely create the other two masks... */
304
305 bpf_cpumask_set_cpu(0, mask1);
306 bpf_cpumask_set_cpu(1, mask2);
307 bpf_cpumask_and(dst1, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
308 if (!bpf_cpumask_empty((const struct cpumask *)dst1))
309 /* Should never happen. */
310 goto release_exit;
311
312 bpf_cpumask_or(dst1, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
313 if (!bpf_cpumask_test_cpu(0, (const struct cpumask *)dst1))
314 /* Should never happen. */
315 goto release_exit;
316
317 if (!bpf_cpumask_test_cpu(1, (const struct cpumask *)dst1))
318 /* Should never happen. */
319 goto release_exit;
320
321 bpf_cpumask_xor(dst2, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
322 if (!bpf_cpumask_equal((const struct cpumask *)dst1,
323 (const struct cpumask *)dst2))
324 /* Should never happen. */
325 goto release_exit;
326
327 release_exit:
328 bpf_cpumask_release(mask1);
329 bpf_cpumask_release(mask2);
330 bpf_cpumask_release(dst1);
331 bpf_cpumask_release(dst2);
332 return 0;
333 }
334
335 ----
336
337 The contents of an entire cpumask may be copied to another using
338 bpf_cpumask_copy():
339
340 .. kernel-doc:: kernel/bpf/cpumask.c
341 :identifiers: bpf_cpumask_copy
342
343 ----
344
345 .. _cpumasks-querying-label:
346
347 3.2 Querying cpumasks
348 ---------------------
349
350 In addition to the above kfuncs, there is also a set of read-only kfuncs that
351 can be used to query the contents of cpumasks.
352
353 .. kernel-doc:: kernel/bpf/cpumask.c
354 :identifiers: bpf_cpumask_first bpf_cpumask_first_zero bpf_cpumask_first_and
355 bpf_cpumask_test_cpu bpf_cpumask_weight
356
357 .. kernel-doc:: kernel/bpf/cpumask.c
358 :identifiers: bpf_cpumask_equal bpf_cpumask_intersects bpf_cpumask_subset
359 bpf_cpumask_empty bpf_cpumask_full
360
361 .. kernel-doc:: kernel/bpf/cpumask.c
362 :identifiers: bpf_cpumask_any_distribute bpf_cpumask_any_and_distribute
363
364 ----
365
366 Some example usages of these querying kfuncs were shown above. We will not
367 replicate those examples here. Note, however, that all of the aforementioned
368 kfuncs are tested in `tools/testing/selftests/bpf/progs/cpumask_success.c`_, so
369 please take a look there if you're looking for more examples of how they can be
370 used.
371
372 .. _tools/testing/selftests/bpf/progs/cpumask_success.c:
373 https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/progs/cpumask_success.c
374
375
376 4. Adding BPF cpumask kfuncs
377 ============================
378
379 The set of supported BPF cpumask kfuncs are not (yet) a 1-1 match with the
380 cpumask operations in include/linux/cpumask.h. Any of those cpumask operations
381 could easily be encapsulated in a new kfunc if and when required. If you'd like
382 to support a new cpumask operation, please feel free to submit a patch. If you
383 do add a new cpumask kfunc, please document it here, and add any relevant
384 selftest testcases to the cpumask selftest suite.
385

3. 한국어 전문 번역

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

BPF cpumask kfunc 소개

1-20

이 문서는 `GPL-2.0` license를 따르며 `cpumasks-header-label` anchor에서 BPF cpumask kfunc를 설명합니다.

`struct cpumask`는 index가 system의 CPU를 나타내는 kernel bitmap data structure입니다. cpumask의 일반적인 활용은 다음과 같습니다.

  • task가 affinity를 갖는 CPU를 추적합니다.
  • scheduling domain에 연결된 core를 추적합니다.
  • machine에서 idle 상태인 core 등을 추적합니다.

BPF는 program이 cpumask를 allocate, mutate, query, free할 수 있도록 `kfuncs-header-label`에서 설명하는 kfunc 집합을 제공합니다.

BPF가 사용하는 두 cpumask object

21-33

BPF program에서 사용할 수 있는 cpumask type은 두 가지입니다.

`struct bpf_cpumask *`는 BPF program을 대신해 BPF가 allocate하며 lifecycle 전체를 BPF가 제어하는 cpumask입니다.

이 cpumask는 RCU-protected이고 mutate할 수 있으며 kptrs로 사용할 수 있습니다. 또한 `struct cpumask *`로 안전하게 cast할 수 있습니다.

struct bpf_cpumask lifecycle

34-49

`struct bpf_cpumask *`의 allocate, acquire, release에는 `kernel/bpf/cpumask.c`에서 문서화한 다음 function을 사용합니다.

  • `bpf_cpumask_create`: 새 BPF cpumask를 allocate합니다.
  • `bpf_cpumask_acquire`: 기존 BPF cpumask reference를 acquire합니다.
  • `bpf_cpumask_release`: 보유한 BPF cpumask reference를 release합니다.

Cpumask 생성과 map kptr 저장 예제

50-113

다음 예제는 `struct bpf_cpumask __kptr *` field를 가진 array map을 정의하고 새 cpumask의 ownership을 map으로 이전합니다.

struct cpumask_map_value {
        struct bpf_cpumask __kptr * cpumask;
};

struct array_map {
        __uint(type, BPF_MAP_TYPE_ARRAY);
        __type(key, int);
        __type(value, struct cpumask_map_value);
        __uint(max_entries, 65536);
} cpumask_map SEC(".maps");

static int cpumask_map_insert(struct bpf_cpumask *mask, u32 pid)
{
        struct cpumask_map_value local, *v;
        long status;
        struct bpf_cpumask *old;
        u32 key = pid;

        local.cpumask = NULL;
        status = bpf_map_update_elem(&cpumask_map, &key, &local, 0);
        if (status) {
                bpf_cpumask_release(mask);
                return status;
        }

        v = bpf_map_lookup_elem(&cpumask_map, &key);
        if (!v) {
                bpf_cpumask_release(mask);
                return -ENOENT;
        }

        old = bpf_kptr_xchg(&v->cpumask, mask);
        if (old)
                bpf_cpumask_release(old);

        return 0;
}

/**
 * A sample tracepoint showing how a task's cpumask can be queried and
 * recorded as a kptr.
 */
SEC("tp_btf/task_newtask")
int BPF_PROG(record_task_cpumask, struct task_struct *task, u64 clone_flags)
{
        struct bpf_cpumask *cpumask;
        int ret;

        cpumask = bpf_cpumask_create();
        if (!cpumask)
                return -ENOMEM;

        if (!bpf_cpumask_full(task->cpus_ptr))
                bpf_printk("task %s has CPU affinity", task->comm);

        bpf_cpumask_copy(cpumask, task->cpus_ptr);
        return cpumask_map_insert(cpumask, task->pid);
}

`cpumask_map_insert()`는 먼저 null kptr를 가진 map value를 만들고 다시 lookup한 뒤 `bpf_kptr_xchg()`로 새 `mask`를 저장합니다. 교체된 `old` pointer가 있으면 `bpf_cpumask_release(old)`로 reference를 반환합니다. update나 lookup이 실패한 경로에서도 입력 `mask`를 release하므로 ownership leak이 없습니다.

`record_task_cpumask` tracepoint program은 `bpf_cpumask_create()`로 object를 만들고, `task->cpus_ptr`가 full mask인지 query한 뒤 `bpf_cpumask_copy()`로 task의 CPU affinity를 복사합니다. 마지막에는 `cpumask_map_insert()`가 task PID key에 kptr를 기록합니다.

Map kptr와 RCU 보호

114-176

위 예제처럼 `struct bpf_cpumask *` object는 map에 저장해 kptrs로 사용할 수 있습니다. map에 있는 reference는 `bpf_kptr_xchg()`로 제거하거나 RCU를 사용해 opportunistically acquire할 수 있습니다.

/* struct containing the struct bpf_cpumask kptr which is stored in the map. */
struct cpumasks_kfunc_map_value {
        struct bpf_cpumask __kptr * bpf_cpumask;
};

/* The map containing struct cpumasks_kfunc_map_value entries. */
struct {
        __uint(type, BPF_MAP_TYPE_ARRAY);
        __type(key, int);
        __type(value, struct cpumasks_kfunc_map_value);
        __uint(max_entries, 1);
} cpumasks_kfunc_map SEC(".maps");

/* ... */

/**
 * A simple example tracepoint program showing how a
 * struct bpf_cpumask * kptr that is stored in a map can
 * be passed to kfuncs using RCU protection.
 */
SEC("tp_btf/cgroup_mkdir")
int BPF_PROG(cgrp_ancestor_example, struct cgroup *cgrp, const char *path)
{
        struct bpf_cpumask *kptr;
        struct cpumasks_kfunc_map_value *v;
        u32 key = 0;

        /* Assume a bpf_cpumask * kptr was previously stored in the map. */
        v = bpf_map_lookup_elem(&cpumasks_kfunc_map, &key);
        if (!v)
                return -ENOENT;

        bpf_rcu_read_lock();
        /* Acquire a reference to the bpf_cpumask * kptr that's already stored in the map. */
        kptr = v->cpumask;
        if (!kptr) {
                /* If no bpf_cpumask was present in the map, it's because
                 * we're racing with another CPU that removed it with
                 * bpf_kptr_xchg() between the bpf_map_lookup_elem()
                 * above, and our load of the pointer from the map.
                 */
                bpf_rcu_read_unlock();
                return -EBUSY;
        }

        bpf_cpumask_setall(kptr);
        bpf_rcu_read_unlock();

        return 0;
}

예제는 map에 미리 저장된 `struct bpf_cpumask *` kptr를 lookup한 뒤 `bpf_rcu_read_lock()`으로 RCU read-side critical section에 들어갑니다. `v->cpumask`를 읽어 null이 아니면 `bpf_cpumask_setall(kptr)`에 전달하고 `bpf_rcu_read_unlock()`으로 나옵니다.

pointer가 null이면 map lookup과 pointer load 사이에 다른 CPU가 `bpf_kptr_xchg()`로 object를 제거한 race가 발생한 것입니다. 이 경로는 RCU lock을 해제하고 `-EBUSY`를 반환합니다.

struct cpumask와 안전한 cast 방향

177-189

`struct cpumask`는 실제로 query·mutate하는 cpumask bitmap을 담는 object입니다. `struct bpf_cpumask`가 내부에서 `struct cpumask`를 감싸므로 `struct bpf_cpumask *`를 `struct cpumask *`로 cast하는 것은 안전합니다.

반대 방향인 `struct cpumask *`에서 `struct bpf_cpumask *`로의 cast는 안전하지 않습니다. verifier는 이를 시도하는 program을 reject합니다.

cpumask argument를 mutate하는 kfunc는 해당 argument를 `struct bpf_cpumask *`로 받습니다. 단순히 cpumask를 query하는 argument는 `struct cpumask *`로 받습니다.

Mutation과 query kfunc 구분

190-206

앞 절에서는 `struct bpf_cpumask *`를 allocate, acquire, release하는 kfunc를 설명했습니다. 이 절에서는 cpumask를 mutate하고 query하는 kfunc를 다룹니다.

일부 cpumask kfunc는 argument를 변경하지 않는 read-only function이고, 다른 function은 하나 이상의 argument를 mutate합니다. mutate 대상은 앞서 설명한 대로 반드시 `struct bpf_cpumask *`여야 합니다.

이하의 mutation 절은 argument를 하나 이상 바꾸는 모든 cpumask kfunc를 설명하며, `cpumasks-querying-label` 절은 read-only kfunc를 설명합니다.

CPU bit와 전체 mask 설정·해제

207-268

`bpf_cpumask_set_cpu()`와 `bpf_cpumask_clear_cpu()`는 각각 `struct bpf_cpumask`에서 지정한 CPU bit를 set하거나 clear합니다. 두 function은 `kernel/bpf/cpumask.c`에서 kernel-doc으로 문서화됩니다.

다음 tracepoint 예제는 set, clear, query를 함께 보여 줍니다.

/**
 * A sample tracepoint showing how a cpumask can be queried.
 */
SEC("tp_btf/task_newtask")
int BPF_PROG(test_set_clear_cpu, struct task_struct *task, u64 clone_flags)
{
        struct bpf_cpumask *cpumask;

        cpumask = bpf_cpumask_create();
        if (!cpumask)
                return -ENOMEM;

        bpf_cpumask_set_cpu(0, cpumask);
        if (!bpf_cpumask_test_cpu(0, cast(cpumask)))
                /* Should never happen. */
                goto release_exit;

        bpf_cpumask_clear_cpu(0, cpumask);
        if (bpf_cpumask_test_cpu(0, cast(cpumask)))
                /* Should never happen. */
                goto release_exit;

        /* struct cpumask * pointers such as task->cpus_ptr can also be queried. */
        if (bpf_cpumask_test_cpu(0, task->cpus_ptr))
                bpf_printk("task %s can use CPU %d", task->comm, 0);

release_exit:
        bpf_cpumask_release(cpumask);
        return 0;
}

program은 cpumask를 만들고 CPU 0을 set한 뒤 `bpf_cpumask_test_cpu(0, cast(cpumask))`로 bit가 설정됐는지 확인합니다. 이어 CPU 0을 clear하고 다시 query합니다. `task->cpus_ptr`처럼 원래부터 `struct cpumask *`인 pointer도 직접 query할 수 있습니다. 모든 경로는 마지막에 `bpf_cpumask_release(cpumask)`를 호출합니다.

개별 bit와 전체 mask를 변경하는 관련 kfunc는 다음과 같습니다.

  • `bpf_cpumask_test_and_set_cpu()`와 `bpf_cpumask_test_and_clear_cpu()`는 CPU bit를 atomic하게 test한 뒤 set 또는 clear합니다.
  • `bpf_cpumask_setall()`은 `struct bpf_cpumask *`의 모든 bit를 한 operation으로 set합니다.
  • `bpf_cpumask_clear()`는 `struct bpf_cpumask *` 전체를 한 operation으로 clear합니다.

Cpumask 사이의 bitwise operation과 copy

269-343

한 cpumask의 개별 CPU를 set·clear하는 것 외에도 caller는 여러 cpumask 사이에서 `bpf_cpumask_and()`, `bpf_cpumask_or()`, `bpf_cpumask_xor()`로 bitwise operation을 수행할 수 있습니다.

다음 예제에는 뒤에서 더 자세히 설명할 query kfunc도 일부 포함됩니다.

/**
 * A sample tracepoint showing how a cpumask can be mutated using
   bitwise operators (and queried).
 */
SEC("tp_btf/task_newtask")
int BPF_PROG(test_and_or_xor, struct task_struct *task, u64 clone_flags)
{
        struct bpf_cpumask *mask1, *mask2, *dst1, *dst2;

        mask1 = bpf_cpumask_create();
        if (!mask1)
                return -ENOMEM;

        mask2 = bpf_cpumask_create();
        if (!mask2) {
                bpf_cpumask_release(mask1);
                return -ENOMEM;
        }

        // ...Safely create the other two masks... */

        bpf_cpumask_set_cpu(0, mask1);
        bpf_cpumask_set_cpu(1, mask2);
        bpf_cpumask_and(dst1, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
        if (!bpf_cpumask_empty((const struct cpumask *)dst1))
                /* Should never happen. */
                goto release_exit;

        bpf_cpumask_or(dst1, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
        if (!bpf_cpumask_test_cpu(0, (const struct cpumask *)dst1))
                /* Should never happen. */
                goto release_exit;

        if (!bpf_cpumask_test_cpu(1, (const struct cpumask *)dst1))
                /* Should never happen. */
                goto release_exit;

        bpf_cpumask_xor(dst2, (const struct cpumask *)mask1, (const struct cpumask *)mask2);
        if (!bpf_cpumask_equal((const struct cpumask *)dst1,
                               (const struct cpumask *)dst2))
                /* Should never happen. */
                goto release_exit;

 release_exit:
        bpf_cpumask_release(mask1);
        bpf_cpumask_release(mask2);
        bpf_cpumask_release(dst1);
        bpf_cpumask_release(dst2);
        return 0;
}

예제는 `mask1`의 CPU 0과 `mask2`의 CPU 1을 set합니다. AND 결과 `dst1`은 empty여야 하고, OR 결과에는 CPU 0과 1이 모두 있어야 합니다. 서로 겹치지 않는 두 mask의 XOR 결과 `dst2`는 OR 결과 `dst1`과 equal해야 합니다. 종료 경로에서는 네 cpumask를 모두 release합니다.

  • `bpf_cpumask_and()`: 두 source mask의 교집합을 destination에 저장합니다.
  • `bpf_cpumask_or()`: 두 source mask의 합집합을 destination에 저장합니다.
  • `bpf_cpumask_xor()`: 두 source mask의 배타적 합을 destination에 저장합니다.
  • `bpf_cpumask_copy()`: cpumask 전체 내용을 다른 cpumask로 복사합니다.

Read-only cpumask query kfunc

344-364

`cpumasks-querying-label`에 정의된 read-only kfunc는 cpumask 내용을 변경하지 않고 검색·검사·계수합니다. `kernel/bpf/cpumask.c`에 문서화된 function은 다음과 같습니다.

  • `bpf_cpumask_first`, `bpf_cpumask_first_zero`, `bpf_cpumask_first_and`
  • `bpf_cpumask_test_cpu`, `bpf_cpumask_weight`
  • `bpf_cpumask_equal`, `bpf_cpumask_intersects`, `bpf_cpumask_subset`
  • `bpf_cpumask_empty`, `bpf_cpumask_full`
  • `bpf_cpumask_any_distribute`, `bpf_cpumask_any_and_distribute`

Query 예제와 cpumask selftest

365-375

앞 절에 query kfunc 사용 예제가 있으므로 여기서는 반복하지 않습니다. 앞에서 언급한 모든 kfunc는 `tools/testing/selftests/bpf/progs/cpumask_success.c`에서 test합니다.

추가 사용 예제는 `https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/tools/testing/selftests/bpf/progs/cpumask_success.c`의 selftest source에서 확인할 수 있습니다.

새 BPF cpumask kfunc 추가

376-384

현재 지원하는 BPF cpumask kfunc 집합은 `include/linux/cpumask.h`의 cpumask operation과 아직 일대일로 일치하지 않습니다. 필요해지면 해당 operation을 새 kfunc로 쉽게 감쌀 수 있습니다.

새 cpumask operation을 지원하려면 patch와 함께 다음 작업을 수행해야 합니다.

  • 새 cpumask kfunc를 이 문서에 추가해 설명합니다.
  • 관련 selftest testcase를 cpumask selftest suite에 추가합니다.