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

Linux 6.18.37 · BPF

BPF_MAP_TYPE_CPUMAP

CPUMAP의 remote CPU execution model, XDP redirect helper, userspace 관리 API와 round-robin redirect 예제를 설명합니다.

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

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

1. 요약·해설

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

요약과 해설

map_cpumap.rst:1-177

`BPF_MAP_TYPE_CPUMAP`은 CPU별 entry와 전용 kernel thread를 통해 XDP packet processing을 remote CPU로 분산합니다. Software RSS나 initial CPU의 처리량을 줄이는 구성에 적합합니다.

Kernel XDP program은 `bpf_redirect_map()`으로 packet을 전달하지만 CPUMAP entry의 생성, 조회, 삭제는 userspace에서만 수행해야 합니다. Kernel program에서 관리 API를 호출하면 verifier가 load를 거부합니다.

Remote CPU에서 실행할 program과 queue size는 `struct bpf_cpumap_val`로 설정합니다. 실제 배포에서는 possible CPU 수에 맞춰 `max_entries`를 조정하고 destination CPU의 범위를 검증해야 합니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0-only
2 .. Copyright (C) 2022 Red Hat, Inc.
3
4 ===================
5 BPF_MAP_TYPE_CPUMAP
6 ===================
7
8 .. note::
9 - ``BPF_MAP_TYPE_CPUMAP`` was introduced in kernel version 4.15
10
11 .. kernel-doc:: kernel/bpf/cpumap.c
12 :doc: cpu map
13
14 An example use-case for this map type is software based Receive Side Scaling (RSS).
15
16 The CPUMAP represents the CPUs in the system indexed as the map-key, and the
17 map-value is the config setting (per CPUMAP entry). Each CPUMAP entry has a dedicated
18 kernel thread bound to the given CPU to represent the remote CPU execution unit.
19
20 Starting from Linux kernel version 5.9 the CPUMAP can run a second XDP program
21 on the remote CPU. This allows an XDP program to split its processing across
22 multiple CPUs. For example, a scenario where the initial CPU (that sees/receives
23 the packets) needs to do minimal packet processing and the remote CPU (to which
24 the packet is directed) can afford to spend more cycles processing the frame. The
25 initial CPU is where the XDP redirect program is executed. The remote CPU
26 receives raw ``xdp_frame`` objects.
27
28 Usage
29 =====
30
31 Kernel BPF
32 ----------
33 bpf_redirect_map()
34 ^^^^^^^^^^^^^^^^^^
35 .. code-block:: c
36
37 long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags)
38
39 Redirect the packet to the endpoint referenced by ``map`` at index ``key``.
40 For ``BPF_MAP_TYPE_CPUMAP`` this map contains references to CPUs.
41
42 The lower two bits of ``flags`` are used as the return code if the map lookup
43 fails. This is so that the return value can be one of the XDP program return
44 codes up to ``XDP_TX``, as chosen by the caller.
45
46 User space
47 ----------
48 .. note::
49 CPUMAP entries can only be updated/looked up/deleted from user space and not
50 from an eBPF program. Trying to call these functions from a kernel eBPF
51 program will result in the program failing to load and a verifier warning.
52
53 bpf_map_update_elem()
54 ^^^^^^^^^^^^^^^^^^^^^
55 .. code-block:: c
56
57 int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags);
58
59 CPU entries can be added or updated using the ``bpf_map_update_elem()``
60 helper. This helper replaces existing elements atomically. The ``value`` parameter
61 can be ``struct bpf_cpumap_val``.
62
63 .. code-block:: c
64
65 struct bpf_cpumap_val {
66 __u32 qsize; /* queue size to remote target CPU */
67 union {
68 int fd; /* prog fd on map write */
69 __u32 id; /* prog id on map read */
70 } bpf_prog;
71 };
72
73 The flags argument can be one of the following:
74 - BPF_ANY: Create a new element or update an existing element.
75 - BPF_NOEXIST: Create a new element only if it did not exist.
76 - BPF_EXIST: Update an existing element.
77
78 bpf_map_lookup_elem()
79 ^^^^^^^^^^^^^^^^^^^^^
80 .. code-block:: c
81
82 int bpf_map_lookup_elem(int fd, const void *key, void *value);
83
84 CPU entries can be retrieved using the ``bpf_map_lookup_elem()``
85 helper.
86
87 bpf_map_delete_elem()
88 ^^^^^^^^^^^^^^^^^^^^^
89 .. code-block:: c
90
91 int bpf_map_delete_elem(int fd, const void *key);
92
93 CPU entries can be deleted using the ``bpf_map_delete_elem()``
94 helper. This helper will return 0 on success, or negative error in case of
95 failure.
96
97 Examples
98 ========
99 Kernel
100 ------
101
102 The following code snippet shows how to declare a ``BPF_MAP_TYPE_CPUMAP`` called
103 ``cpu_map`` and how to redirect packets to a remote CPU using a round robin scheme.
104
105 .. code-block:: c
106
107 struct {
108 __uint(type, BPF_MAP_TYPE_CPUMAP);
109 __type(key, __u32);
110 __type(value, struct bpf_cpumap_val);
111 __uint(max_entries, 12);
112 } cpu_map SEC(".maps");
113
114 struct {
115 __uint(type, BPF_MAP_TYPE_ARRAY);
116 __type(key, __u32);
117 __type(value, __u32);
118 __uint(max_entries, 12);
119 } cpus_available SEC(".maps");
120
121 struct {
122 __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
123 __type(key, __u32);
124 __type(value, __u32);
125 __uint(max_entries, 1);
126 } cpus_iterator SEC(".maps");
127
128 SEC("xdp")
129 int xdp_redir_cpu_round_robin(struct xdp_md *ctx)
130 {
131 __u32 key = 0;
132 __u32 cpu_dest = 0;
133 __u32 *cpu_selected, *cpu_iterator;
134 __u32 cpu_idx;
135
136 cpu_iterator = bpf_map_lookup_elem(&cpus_iterator, &key);
137 if (!cpu_iterator)
138 return XDP_ABORTED;
139 cpu_idx = *cpu_iterator;
140
141 *cpu_iterator += 1;
142 if (*cpu_iterator == bpf_num_possible_cpus())
143 *cpu_iterator = 0;
144
145 cpu_selected = bpf_map_lookup_elem(&cpus_available, &cpu_idx);
146 if (!cpu_selected)
147 return XDP_ABORTED;
148 cpu_dest = *cpu_selected;
149
150 if (cpu_dest >= bpf_num_possible_cpus())
151 return XDP_ABORTED;
152
153 return bpf_redirect_map(&cpu_map, cpu_dest, 0);
154 }
155
156 User space
157 ----------
158
159 The following code snippet shows how to dynamically set the max_entries for a
160 CPUMAP to the max number of cpus available on the system.
161
162 .. code-block:: c
163
164 int set_max_cpu_entries(struct bpf_map *cpu_map)
165 {
166 if (bpf_map__set_max_entries(cpu_map, libbpf_num_possible_cpus()) < 0) {
167 fprintf(stderr, "Failed to set max entries for cpu_map map: %s",
168 strerror(errno));
169 return -1;
170 }
171 return 0;
172 }
173
174 References
175 ===========
176
177 - https://developers.redhat.com/blog/2021/05/13/receive-side-scaling-rss-with-ebpf-and-cpumap#redirecting_into_a_cpumap
178

3. 한국어 전문 번역

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

CPUMAP 개요와 remote CPU 실행

1-27

`BPF_MAP_TYPE_CPUMAP` 문서는 `GPL-2.0-only` 라이선스와 `Copyright (C) 2022 Red Hat, Inc.`를 명시합니다.

`BPF_MAP_TYPE_CPUMAP`은 `kernel version 4.15`에 도입되었습니다.

이 문서는 `kernel/bpf/cpumap.c`의 `cpu map` kernel-doc을 포함합니다. 이 map type의 대표적인 사용 사례는 software based Receive Side Scaling (RSS)입니다.

CPUMAP은 system의 CPU를 map key로 index하며, map value에는 각 CPUMAP entry의 configuration을 저장합니다. Entry마다 해당 CPU에 bind된 전용 kernel thread가 있고, 이 thread가 remote CPU execution unit을 나타냅니다.

`Linux kernel version 5.9`부터 CPUMAP은 remote CPU에서 두 번째 XDP program을 실행할 수 있습니다. 따라서 한 XDP program의 processing을 여러 CPU로 나눌 수 있습니다.

예를 들어 packet을 처음 수신한 CPU에서는 최소한의 packet processing만 수행하고, packet이 전달된 remote CPU에서 frame 처리에 더 많은 cycle을 사용할 수 있습니다. Initial CPU는 XDP redirect program을 실행하고 remote CPU는 raw `xdp_frame` object를 받습니다.

Kernel BPF redirect helper

28-45

Kernel BPF program은 다음 `bpf_redirect_map()` helper를 사용합니다.

long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags)

이 helper는 `map`의 `key` index가 가리키는 endpoint로 packet을 redirect합니다. `BPF_MAP_TYPE_CPUMAP`에서 map은 CPU reference를 담습니다.

`flags`의 lower two bits는 map lookup이 실패했을 때의 return code로 사용됩니다. Caller는 이 bit를 선택해 `XDP_TX`까지의 XDP program return code 중 하나를 반환하게 할 수 있습니다.

Userspace update, lookup, delete API

46-96

CPUMAP entry는 userspace에서만 update, lookup, delete할 수 있으며 eBPF program에서는 이 operation을 수행할 수 없습니다. Kernel eBPF program에서 이 function을 호출하면 program load가 실패하고 verifier warning이 발생합니다.

CPU entry를 추가하거나 갱신할 때는 다음 `bpf_map_update_elem()` API를 사용합니다. 이 helper는 기존 element를 atomically 교체합니다.

int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags);

`value` parameter에는 다음 `struct bpf_cpumap_val`을 전달할 수 있습니다. `qsize`는 remote target CPU로 보내는 queue size이고, `bpf_prog.fd`는 map write 시 program fd, `bpf_prog.id`는 map read 시 program id입니다.

struct bpf_cpumap_val {
    __u32 qsize;  /* queue size to remote target CPU */
    union {
        int   fd; /* prog fd on map write */
        __u32 id; /* prog id on map read */
    } bpf_prog;
};

`flags` argument에는 다음 값 중 하나를 지정할 수 있습니다.

  • `BPF_ANY`: 새 element를 만들거나 기존 element를 갱신합니다.
  • `BPF_NOEXIST`: element가 없을 때만 새로 만듭니다.
  • `BPF_EXIST`: 기존 element만 갱신합니다.

CPU entry를 가져올 때는 다음 `bpf_map_lookup_elem()` API를 사용합니다.

int bpf_map_lookup_elem(int fd, const void *key, void *value);

CPU entry를 삭제할 때는 다음 `bpf_map_delete_elem()` API를 사용합니다.

int bpf_map_delete_elem(int fd, const void *key);

`bpf_map_delete_elem()`은 성공하면 0을 반환하고 실패하면 negative error를 반환합니다.

Round-robin CPU redirect 예제

97-155

다음 kernel code는 `cpu_map`이라는 `BPF_MAP_TYPE_CPUMAP`을 선언하고 round-robin 방식으로 packet을 remote CPU에 redirect합니다.

struct {
     __uint(type, BPF_MAP_TYPE_CPUMAP);
     __type(key, __u32);
     __type(value, struct bpf_cpumap_val);
     __uint(max_entries, 12);
 } cpu_map SEC(".maps");

 struct {
     __uint(type, BPF_MAP_TYPE_ARRAY);
     __type(key, __u32);
     __type(value, __u32);
     __uint(max_entries, 12);
 } cpus_available SEC(".maps");

 struct {
     __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
     __type(key, __u32);
     __type(value, __u32);
     __uint(max_entries, 1);
 } cpus_iterator SEC(".maps");

 SEC("xdp")
 int  xdp_redir_cpu_round_robin(struct xdp_md *ctx)
 {
     __u32 key = 0;
     __u32 cpu_dest = 0;
     __u32 *cpu_selected, *cpu_iterator;
     __u32 cpu_idx;

     cpu_iterator = bpf_map_lookup_elem(&cpus_iterator, &key);
     if (!cpu_iterator)
         return XDP_ABORTED;
     cpu_idx = *cpu_iterator;

     *cpu_iterator += 1;
     if (*cpu_iterator == bpf_num_possible_cpus())
         *cpu_iterator = 0;

     cpu_selected = bpf_map_lookup_elem(&cpus_available, &cpu_idx);
     if (!cpu_selected)
         return XDP_ABORTED;
     cpu_dest = *cpu_selected;

     if (cpu_dest >= bpf_num_possible_cpus())
         return XDP_ABORTED;

     return bpf_redirect_map(&cpu_map, cpu_dest, 0);
 }

`cpu_map`은 `struct bpf_cpumap_val`을 저장하고, `cpus_available`은 CPU index에 대응하는 destination CPU를 보관하며, per-CPU `cpus_iterator`는 다음 CPU index를 추적합니다.

`xdp_redir_cpu_round_robin`은 iterator와 selected CPU를 차례로 lookup합니다. Pointer가 없거나 destination이 `bpf_num_possible_cpus()` 범위를 벗어나면 `XDP_ABORTED`를 반환합니다. 유효하면 iterator를 순환시키고 `bpf_redirect_map(&cpu_map, cpu_dest, 0)`으로 packet을 전달합니다.

Dynamic max_entries 설정과 참고 자료

156-177

다음 userspace code는 CPUMAP의 `max_entries`를 system에서 사용할 수 있는 최대 CPU 수에 맞춰 동적으로 설정합니다.

int set_max_cpu_entries(struct bpf_map *cpu_map)
{
    if (bpf_map__set_max_entries(cpu_map, libbpf_num_possible_cpus()) < 0) {
        fprintf(stderr, "Failed to set max entries for cpu_map map: %s",
            strerror(errno));
        return -1;
    }
    return 0;
}

`libbpf_num_possible_cpus()`로 CPU 수를 구해 `bpf_map__set_max_entries()`에 전달합니다. 설정에 실패하면 error message를 출력하고 -1을 반환하며, 성공하면 0을 반환합니다.

[Receive Side Scaling (RSS) with eBPF and CPUMAP](https://developers.redhat.com/blog/2021/05/13/receive-side-scaling-rss-with-ebpf-and-cpumap#redirecting_into_a_cpumap) 문서에서 CPUMAP redirect 사례를 더 살펴볼 수 있습니다.