요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. SPDX-License-Identifier: GPL-2.0-only
.. Copyright (C) 2022 Red Hat, Inc.
=================================================
BPF_MAP_TYPE_DEVMAP and BPF_MAP_TYPE_DEVMAP_HASH
=================================================
.. note::
- ``BPF_MAP_TYPE_DEVMAP`` was introduced in kernel version 4.14
- ``BPF_MAP_TYPE_DEVMAP_HASH`` was introduced in kernel version 5.4
``BPF_MAP_TYPE_DEVMAP`` and ``BPF_MAP_TYPE_DEVMAP_HASH`` are BPF maps primarily
used as backend maps for the XDP BPF helper call ``bpf_redirect_map()``.
``BPF_MAP_TYPE_DEVMAP`` is backed by an array that uses the key as
the index to lookup a reference to a net device. While ``BPF_MAP_TYPE_DEVMAP_HASH``
is backed by a hash table that uses a key to lookup a reference to a net device.
The user provides either <``key``/ ``ifindex``> or <``key``/ ``struct bpf_devmap_val``>
pairs to update the maps with new net devices.
.. note::
- The key to a hash map doesn't have to be an ``ifindex``.
- While ``BPF_MAP_TYPE_DEVMAP_HASH`` allows for densely packing the net devices
it comes at the cost of a hash of the key when performing a look up.
The setup and packet enqueue/send code is shared between the two types of
devmap; only the lookup and insertion is different.
Usage
=====
Kernel BPF
----------
bpf_redirect_map()
^^^^^^^^^^^^^^^^^^
.. code-block:: c
long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags)
Redirect the packet to the endpoint referenced by ``map`` at index ``key``.
For ``BPF_MAP_TYPE_DEVMAP`` and ``BPF_MAP_TYPE_DEVMAP_HASH`` this map contains
references to net devices (for forwarding packets through other ports).
The lower two bits of *flags* are used as the return code if the map lookup
fails. This is so that the return value can be one of the XDP program return
codes up to ``XDP_TX``, as chosen by the caller. The higher bits of ``flags``
can be set to ``BPF_F_BROADCAST`` or ``BPF_F_EXCLUDE_INGRESS`` as defined
below.
With ``BPF_F_BROADCAST`` the packet will be broadcast to all the interfaces
in the map, with ``BPF_F_EXCLUDE_INGRESS`` the ingress interface will be excluded
from the broadcast.
.. note::
- The key is ignored if BPF_F_BROADCAST is set.
- The broadcast feature can also be used to implement multicast forwarding:
simply create multiple DEVMAPs, each one corresponding to a single multicast group.
This helper will return ``XDP_REDIRECT`` on success, or the value of the two
lower bits of the ``flags`` argument if the map lookup fails.
More information about redirection can be found :doc:`redirect`
bpf_map_lookup_elem()
^^^^^^^^^^^^^^^^^^^^^
.. code-block:: c
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
Net device entries can be retrieved using the ``bpf_map_lookup_elem()``
helper.
User space
----------
.. note::
DEVMAP entries can only be updated/deleted from user space and not
from an eBPF program. Trying to call these functions from a kernel eBPF
program will result in the program failing to load and a verifier warning.
bpf_map_update_elem()
^^^^^^^^^^^^^^^^^^^^^
.. code-block:: c
int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags);
Net device entries can be added or updated using the ``bpf_map_update_elem()``
helper. This helper replaces existing elements atomically. The ``value`` parameter
can be ``struct bpf_devmap_val`` or a simple ``int ifindex`` for backwards
compatibility.
.. code-block:: c
struct bpf_devmap_val {
__u32 ifindex; /* device index */
union {
int fd; /* prog fd on map write */
__u32 id; /* prog id on map read */
} bpf_prog;
};
The ``flags`` argument can be one of the following:
- ``BPF_ANY``: Create a new element or update an existing element.
- ``BPF_NOEXIST``: Create a new element only if it did not exist.
- ``BPF_EXIST``: Update an existing element.
DEVMAPs can associate a program with a device entry by adding a ``bpf_prog.fd``
to ``struct bpf_devmap_val``. Programs are run after ``XDP_REDIRECT`` and have
access to both Rx device and Tx device. The program associated with the ``fd``
must have type XDP with expected attach type ``xdp_devmap``.
When a program is associated with a device index, the program is run on an
``XDP_REDIRECT`` and before the buffer is added to the per-cpu queue. Examples
of how to attach/use xdp_devmap progs can be found in the kernel selftests:
- ``tools/testing/selftests/bpf/prog_tests/xdp_devmap_attach.c``
- ``tools/testing/selftests/bpf/progs/test_xdp_with_devmap_helpers.c``
bpf_map_lookup_elem()
^^^^^^^^^^^^^^^^^^^^^
.. code-block:: c
.. c:function::
int bpf_map_lookup_elem(int fd, const void *key, void *value);
Net device entries can be retrieved using the ``bpf_map_lookup_elem()``
helper.
bpf_map_delete_elem()
^^^^^^^^^^^^^^^^^^^^^
.. code-block:: c
.. c:function::
int bpf_map_delete_elem(int fd, const void *key);
Net device entries can be deleted using the ``bpf_map_delete_elem()``
helper. This helper will return 0 on success, or negative error in case of
failure.
Examples
========
Kernel BPF
----------
The following code snippet shows how to declare a ``BPF_MAP_TYPE_DEVMAP``
called tx_port.
.. code-block:: c
struct {
__uint(type, BPF_MAP_TYPE_DEVMAP);
__type(key, __u32);
__type(value, __u32);
__uint(max_entries, 256);
} tx_port SEC(".maps");
The following code snippet shows how to declare a ``BPF_MAP_TYPE_DEVMAP_HASH``
called forward_map.
.. code-block:: c
struct {
__uint(type, BPF_MAP_TYPE_DEVMAP_HASH);
__type(key, __u32);
__type(value, struct bpf_devmap_val);
__uint(max_entries, 32);
} forward_map SEC(".maps");
.. note::
The value type in the DEVMAP above is a ``struct bpf_devmap_val``
The following code snippet shows a simple xdp_redirect_map program. This program
would work with a user space program that populates the devmap ``forward_map`` based
on ingress ifindexes. The BPF program (below) is redirecting packets using the
ingress ``ifindex`` as the ``key``.
.. code-block:: c
SEC("xdp")
int xdp_redirect_map_func(struct xdp_md *ctx)
{
int index = ctx->ingress_ifindex;
return bpf_redirect_map(&forward_map, index, 0);
}
The following code snippet shows a BPF program that is broadcasting packets to
all the interfaces in the ``tx_port`` devmap.
.. code-block:: c
SEC("xdp")
int xdp_redirect_map_func(struct xdp_md *ctx)
{
return bpf_redirect_map(&tx_port, 0, BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS);
}
User space
----------
The following code snippet shows how to update a devmap called ``tx_port``.
.. code-block:: c
int update_devmap(int ifindex, int redirect_ifindex)
{
int ret;
ret = bpf_map_update_elem(bpf_map__fd(tx_port), &ifindex, &redirect_ifindex, 0);
if (ret < 0) {
fprintf(stderr, "Failed to update devmap_ value: %s\n",
strerror(errno));
}
return ret;
}
The following code snippet shows how to update a hash_devmap called ``forward_map``.
.. code-block:: c
int update_devmap(int ifindex, int redirect_ifindex)
{
struct bpf_devmap_val devmap_val = { .ifindex = redirect_ifindex };
int ret;
ret = bpf_map_update_elem(bpf_map__fd(forward_map), &ifindex, &devmap_val, 0);
if (ret < 0) {
fprintf(stderr, "Failed to update devmap_ value: %s\n",
strerror(errno));
}
return ret;
}
References
===========
- https://lwn.net/Articles/728146/
- https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/commit/?id=6f9d451ab1a33728adb72d7ff66a7b374d665176
- https://elixir.bootlin.com/linux/latest/source/net/core/filter.c#L4106
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
DEVMAP과 DEVMAP_HASH 개요
1-27`BPF_MAP_TYPE_DEVMAP` 및 `BPF_MAP_TYPE_DEVMAP_HASH` 문서는 `GPL-2.0-only` 라이선스와 `Copyright (C) 2022 Red Hat, Inc.`를 명시합니다.
`BPF_MAP_TYPE_DEVMAP`은 `kernel version 4.14`, `BPF_MAP_TYPE_DEVMAP_HASH`는 `kernel version 5.4`에 도입되었습니다.
두 map은 주로 XDP BPF helper인 `bpf_redirect_map()`의 backend map으로 사용됩니다. `BPF_MAP_TYPE_DEVMAP`은 key를 array index로 사용해 net device reference를 찾고, `BPF_MAP_TYPE_DEVMAP_HASH`는 hash table에서 key로 net device reference를 찾습니다.
Userspace는 새 net device를 등록하기 위해 `<key / ifindex>` 또는 `<key / struct bpf_devmap_val>` pair를 map에 넣습니다.
Hash map의 key는 `ifindex`일 필요가 없습니다. `BPF_MAP_TYPE_DEVMAP_HASH`는 net device를 조밀하게 배치할 수 있지만 lookup할 때 key hash 계산 비용이 듭니다.
두 devmap type은 setup과 packet enqueue/send code를 공유하며 lookup과 insertion 방식만 다릅니다.
Kernel BPF redirect와 lookup API
28-70Packet redirect에는 다음 `bpf_redirect_map()` helper를 사용합니다.
long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags)
Helper는 `map`의 `key` index가 참조하는 endpoint로 packet을 redirect합니다. DEVMAP과 DEVMAP_HASH에서 endpoint는 다른 port로 packet을 forwarding할 net device입니다.
`flags`의 lower two bits는 map lookup 실패 시 return code로 사용되며 caller가 `XDP_TX`까지의 XDP return code 중 하나를 선택할 수 있습니다. Higher bits에는 `BPF_F_BROADCAST` 또는 `BPF_F_EXCLUDE_INGRESS`를 지정할 수 있습니다.
`BPF_F_BROADCAST`는 map의 모든 interface로 packet을 broadcast하고, `BPF_F_EXCLUDE_INGRESS`는 broadcast 대상에서 ingress interface를 제외합니다.
`BPF_F_BROADCAST`를 설정하면 key는 무시됩니다. Multicast group마다 별도의 DEVMAP을 만들면 broadcast 기능으로 multicast forwarding도 구현할 수 있습니다.
Redirect가 성공하면 helper는 `XDP_REDIRECT`를 반환합니다. Map lookup이 실패하면 `flags` lower two bits의 값을 반환합니다. Redirect 전반에 관한 추가 설명은 `redirect` 문서에 있습니다.
Kernel BPF program에서 net device entry를 가져올 때는 다음 `bpf_map_lookup_elem()` helper를 사용합니다.
void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
Userspace map 관리와 device program 연결
71-135DEVMAP entry는 userspace에서만 update하거나 delete할 수 있습니다. Kernel eBPF program에서 이 function을 호출하면 program load가 실패하고 verifier warning이 발생합니다.
Net device entry를 추가하거나 갱신할 때는 다음 `bpf_map_update_elem()` API를 사용합니다. 이 helper는 기존 element를 atomically 교체합니다.
int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags);
Backward compatibility를 위해 `value`에는 `struct bpf_devmap_val` 또는 단순한 `int ifindex`를 전달할 수 있습니다. Structure는 device `ifindex`와 map write 시의 program `fd` 또는 map read 시의 program `id`를 담습니다.
struct bpf_devmap_val {
__u32 ifindex; /* device index */
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만 갱신합니다.
DEVMAP은 `struct bpf_devmap_val`의 `bpf_prog.fd`를 설정해 device entry에 program을 연결할 수 있습니다. 이 program은 `XDP_REDIRECT` 뒤, buffer를 per-CPU queue에 넣기 전에 실행되며 Rx device와 Tx device 모두에 접근할 수 있습니다.
연결되는 program은 expected attach type이 `xdp_devmap`인 XDP type이어야 합니다. 사용 예제는 kernel selftest에 있습니다.
- `tools/testing/selftests/bpf/prog_tests/xdp_devmap_attach.c`
- `tools/testing/selftests/bpf/progs/test_xdp_with_devmap_helpers.c`
Userspace에서 net device entry를 가져올 때는 다음 `bpf_map_lookup_elem()` API를 사용합니다.
.. c:function::
int bpf_map_lookup_elem(int fd, const void *key, void *value);
Net device entry를 삭제할 때는 다음 `bpf_map_delete_elem()` API를 사용합니다.
.. c:function::
int bpf_map_delete_elem(int fd, const void *key);
`bpf_map_delete_elem()`은 성공하면 0을 반환하고 실패하면 negative error를 반환합니다.
Kernel map 선언과 redirect 예제
136-195다음 code는 value가 `__u32`이고 최대 256개 entry를 갖는 `BPF_MAP_TYPE_DEVMAP` `tx_port`를 선언합니다.
struct {
__uint(type, BPF_MAP_TYPE_DEVMAP);
__type(key, __u32);
__type(value, __u32);
__uint(max_entries, 256);
} tx_port SEC(".maps");
다음 code는 value가 `struct bpf_devmap_val`이고 최대 32개 entry를 갖는 `BPF_MAP_TYPE_DEVMAP_HASH` `forward_map`을 선언합니다.
struct {
__uint(type, BPF_MAP_TYPE_DEVMAP_HASH);
__type(key, __u32);
__type(value, struct bpf_devmap_val);
__uint(max_entries, 32);
} forward_map SEC(".maps");
위 DEVMAP_HASH의 value type은 `struct bpf_devmap_val`입니다.
다음 단순한 `xdp_redirect_map` program은 userspace가 ingress ifindex를 기준으로 채운 `forward_map`에서 ingress `ifindex`를 key로 사용해 packet을 redirect합니다.
SEC("xdp")
int xdp_redirect_map_func(struct xdp_md *ctx)
{
int index = ctx->ingress_ifindex;
return bpf_redirect_map(&forward_map, index, 0);
}
다음 program은 `BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS`를 지정해 `tx_port` devmap의 모든 interface로 packet을 broadcast하되 ingress interface는 제외합니다.
SEC("xdp")
int xdp_redirect_map_func(struct xdp_md *ctx)
{
return bpf_redirect_map(&tx_port, 0, BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS);
}
Userspace DEVMAP update 예제
196-232다음 code는 `tx_port` devmap에 ingress `ifindex` key와 redirect destination `ifindex` value를 넣습니다. `bpf_map__fd()`로 map fd를 얻어 `bpf_map_update_elem()`에 전달하고 실패하면 error를 출력합니다.
int update_devmap(int ifindex, int redirect_ifindex)
{
int ret;
ret = bpf_map_update_elem(bpf_map__fd(tx_port), &ifindex, &redirect_ifindex, 0);
if (ret < 0) {
fprintf(stderr, "Failed to update devmap_ value: %s\n",
strerror(errno));
}
return ret;
}
다음 code는 `forward_map` hash devmap을 갱신합니다. Redirect destination을 `struct bpf_devmap_val`의 `ifindex` field에 넣고 ingress `ifindex`를 hash key로 사용합니다.
int update_devmap(int ifindex, int redirect_ifindex)
{
struct bpf_devmap_val devmap_val = { .ifindex = redirect_ifindex };
int ret;
ret = bpf_map_update_elem(bpf_map__fd(forward_map), &ifindex, &devmap_val, 0);
if (ret < 0) {
fprintf(stderr, "Failed to update devmap_ value: %s\n",
strerror(errno));
}
return ret;
}
참고 자료
233-238DEVMAP 구현과 redirect 동작에 관한 참고 자료는 다음과 같습니다.
- [https://lwn.net/Articles/728146/](https://lwn.net/Articles/728146/)
- [https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/commit/?id=6f9d451ab1a33728adb72d7ff66a7b374d665176](https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git/commit/?id=6f9d451ab1a33728adb72d7ff66a7b374d665176)
- [https://elixir.bootlin.com/linux/latest/source/net/core/filter.c#L4106](https://elixir.bootlin.com/linux/latest/source/net/core/filter.c#L4106)
요약과 해설
map_devmap.rst:1-238DEVMAP은 array index로, DEVMAP_HASH는 임의의 hash key로 net device를 찾습니다. 두 map 모두 `bpf_redirect_map()`의 backend로 packet을 다른 interface에 forwarding하는 데 사용됩니다.
`BPF_F_BROADCAST`와 `BPF_F_EXCLUDE_INGRESS`를 조합하면 ingress를 제외한 전체 interface로 전송할 수 있습니다. Multicast group별 map을 구성하면 multicast forwarding에도 활용할 수 있습니다.
Entry update와 delete는 userspace에서 수행해야 합니다. `struct bpf_devmap_val`에 XDP program fd를 넣으면 redirect 후 per-CPU queue enqueue 전에 device별 후속 program을 실행할 수 있습니다.