1 .. SPDX-License-Identifier: GPL-2.0-only
4 ==============================================
5 BPF_MAP_TYPE_SOCKMAP and BPF_MAP_TYPE_SOCKHASH
6 ==============================================
9 - ``BPF_MAP_TYPE_SOCKMAP`` was introduced in kernel version 4.14
10 - ``BPF_MAP_TYPE_SOCKHASH`` was introduced in kernel version 4.18
12 ``BPF_MAP_TYPE_SOCKMAP`` and ``BPF_MAP_TYPE_SOCKHASH`` maps can be used to
13 redirect skbs between sockets or to apply policy at the socket level based on
14 the result of a BPF (verdict) program with the help of the BPF helpers
15 ``bpf_sk_redirect_map()``, ``bpf_sk_redirect_hash()``,
16 ``bpf_msg_redirect_map()`` and ``bpf_msg_redirect_hash()``.
18 ``BPF_MAP_TYPE_SOCKMAP`` is backed by an array that uses an integer key as the
19 index to look up a reference to a ``struct sock``. The map values are socket
20 descriptors. Similarly, ``BPF_MAP_TYPE_SOCKHASH`` is a hash backed BPF map that
21 holds references to sockets via their socket descriptors.
24 The value type is either __u32 or __u64; the latter (__u64) is to support
25 returning socket cookies to userspace. Returning the ``struct sock *`` that
26 the map holds to user-space is neither safe nor useful.
28 These maps may have BPF programs attached to them, specifically a parser program
29 and a verdict program. The parser program determines how much data has been
30 parsed and therefore how much data needs to be queued to come to a verdict. The
31 verdict program is essentially the redirect program and can return a verdict
32 of ``__SK_DROP``, ``__SK_PASS``, or ``__SK_REDIRECT``.
34 When a socket is inserted into one of these maps, its socket callbacks are
35 replaced and a ``struct sk_psock`` is attached to it. Additionally, this
36 ``sk_psock`` inherits the programs that are attached to the map.
38 A sock object may be in multiple maps, but can only inherit a single
39 parse or verdict program. If adding a sock object to a map would result
40 in having multiple parser programs the update will return an EBUSY error.
42 The supported programs to attach to these maps are:
46 struct sk_psock_progs {
47 struct bpf_prog *msg_parser;
48 struct bpf_prog *stream_parser;
49 struct bpf_prog *stream_verdict;
50 struct bpf_prog *skb_verdict;
54 Users are not allowed to attach ``stream_verdict`` and ``skb_verdict``
55 programs to the same map.
57 The attach types for the map programs are:
59 - ``msg_parser`` program - ``BPF_SK_MSG_VERDICT``.
60 - ``stream_parser`` program - ``BPF_SK_SKB_STREAM_PARSER``.
61 - ``stream_verdict`` program - ``BPF_SK_SKB_STREAM_VERDICT``.
62 - ``skb_verdict`` program - ``BPF_SK_SKB_VERDICT``.
64 There are additional helpers available to use with the parser and verdict
65 programs: ``bpf_msg_apply_bytes()`` and ``bpf_msg_cork_bytes()``. With
66 ``bpf_msg_apply_bytes()`` BPF programs can tell the infrastructure how many
67 bytes the given verdict should apply to. The helper ``bpf_msg_cork_bytes()``
68 handles a different case where a BPF program cannot reach a verdict on a msg
69 until it receives more bytes AND the program doesn't want to forward the packet
70 until it is known to be good.
72 Finally, the helpers ``bpf_msg_pull_data()`` and ``bpf_msg_push_data()`` are
73 available to ``BPF_PROG_TYPE_SK_MSG`` BPF programs to pull in data and set the
74 start and end pointers to given values or to add metadata to the ``struct
77 All these helpers will be described in more detail below.
83 bpf_msg_redirect_map()
84 ^^^^^^^^^^^^^^^^^^^^^^
87 long bpf_msg_redirect_map(struct sk_msg_buff *msg, struct bpf_map *map, u32 key, u64 flags)
89 This helper is used in programs implementing policies at the socket level. If
90 the message ``msg`` is allowed to pass (i.e., if the verdict BPF program
91 returns ``SK_PASS``), redirect it to the socket referenced by ``map`` (of type
92 ``BPF_MAP_TYPE_SOCKMAP``) at index ``key``. Both ingress and egress interfaces
93 can be used for redirection. The ``BPF_F_INGRESS`` value in ``flags`` is used
94 to select the ingress path otherwise the egress path is selected. This is the
95 only flag supported for now.
97 Returns ``SK_PASS`` on success, or ``SK_DROP`` on error.
100 ^^^^^^^^^^^^^^^^^^^^^
103 long bpf_sk_redirect_map(struct sk_buff *skb, struct bpf_map *map, u32 key u64 flags)
105 Redirect the packet to the socket referenced by ``map`` (of type
106 ``BPF_MAP_TYPE_SOCKMAP``) at index ``key``. Both ingress and egress interfaces
107 can be used for redirection. The ``BPF_F_INGRESS`` value in ``flags`` is used
108 to select the ingress path otherwise the egress path is selected. This is the
109 only flag supported for now.
111 Returns ``SK_PASS`` on success, or ``SK_DROP`` on error.
113 bpf_map_lookup_elem()
114 ^^^^^^^^^^^^^^^^^^^^^
117 void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
119 socket entries of type ``struct sock *`` can be retrieved using the
120 ``bpf_map_lookup_elem()`` helper.
122 bpf_sock_map_update()
123 ^^^^^^^^^^^^^^^^^^^^^
126 long bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags)
128 Add an entry to, or update a ``map`` referencing sockets. The ``skops`` is used
129 as a new value for the entry associated to ``key``. The ``flags`` argument can
130 be one of the following:
132 - ``BPF_ANY``: Create a new element or update an existing element.
133 - ``BPF_NOEXIST``: Create a new element only if it did not exist.
134 - ``BPF_EXIST``: Update an existing element.
136 If the ``map`` has BPF programs (parser and verdict), those will be inherited
137 by the socket being added. If the socket is already attached to BPF programs,
138 this results in an error.
140 Returns 0 on success, or a negative error in case of failure.
142 bpf_sock_hash_update()
143 ^^^^^^^^^^^^^^^^^^^^^^
146 long bpf_sock_hash_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags)
148 Add an entry to, or update a sockhash ``map`` referencing sockets. The ``skops``
149 is used as a new value for the entry associated to ``key``.
151 The ``flags`` argument can be one of the following:
153 - ``BPF_ANY``: Create a new element or update an existing element.
154 - ``BPF_NOEXIST``: Create a new element only if it did not exist.
155 - ``BPF_EXIST``: Update an existing element.
157 If the ``map`` has BPF programs (parser and verdict), those will be inherited
158 by the socket being added. If the socket is already attached to BPF programs,
159 this results in an error.
161 Returns 0 on success, or a negative error in case of failure.
163 bpf_msg_redirect_hash()
164 ^^^^^^^^^^^^^^^^^^^^^^^
167 long bpf_msg_redirect_hash(struct sk_msg_buff *msg, struct bpf_map *map, void *key, u64 flags)
169 This helper is used in programs implementing policies at the socket level. If
170 the message ``msg`` is allowed to pass (i.e., if the verdict BPF program returns
171 ``SK_PASS``), redirect it to the socket referenced by ``map`` (of type
172 ``BPF_MAP_TYPE_SOCKHASH``) using hash ``key``. Both ingress and egress
173 interfaces can be used for redirection. The ``BPF_F_INGRESS`` value in
174 ``flags`` is used to select the ingress path otherwise the egress path is
175 selected. This is the only flag supported for now.
177 Returns ``SK_PASS`` on success, or ``SK_DROP`` on error.
179 bpf_sk_redirect_hash()
180 ^^^^^^^^^^^^^^^^^^^^^^
183 long bpf_sk_redirect_hash(struct sk_buff *skb, struct bpf_map *map, void *key, u64 flags)
185 This helper is used in programs implementing policies at the skb socket level.
186 If the sk_buff ``skb`` is allowed to pass (i.e., if the verdict BPF program
187 returns ``SK_PASS``), redirect it to the socket referenced by ``map`` (of type
188 ``BPF_MAP_TYPE_SOCKHASH``) using hash ``key``. Both ingress and egress
189 interfaces can be used for redirection. The ``BPF_F_INGRESS`` value in
190 ``flags`` is used to select the ingress path otherwise the egress path is
191 selected. This is the only flag supported for now.
193 Returns ``SK_PASS`` on success, or ``SK_DROP`` on error.
195 bpf_msg_apply_bytes()
196 ^^^^^^^^^^^^^^^^^^^^^^
199 long bpf_msg_apply_bytes(struct sk_msg_buff *msg, u32 bytes)
201 For socket policies, apply the verdict of the BPF program to the next (number
202 of ``bytes``) of message ``msg``. For example, this helper can be used in the
205 - A single ``sendmsg()`` or ``sendfile()`` system call contains multiple
206 logical messages that the BPF program is supposed to read and for which it
207 should apply a verdict.
208 - A BPF program only cares to read the first ``bytes`` of a ``msg``. If the
209 message has a large payload, then setting up and calling the BPF program
210 repeatedly for all bytes, even though the verdict is already known, would
211 create unnecessary overhead.
216 ^^^^^^^^^^^^^^^^^^^^^^
219 long bpf_msg_cork_bytes(struct sk_msg_buff *msg, u32 bytes)
221 For socket policies, prevent the execution of the verdict BPF program for
222 message ``msg`` until the number of ``bytes`` have been accumulated.
224 This can be used when one needs a specific number of bytes before a verdict can
225 be assigned, even if the data spans multiple ``sendmsg()`` or ``sendfile()``
231 ^^^^^^^^^^^^^^^^^^^^^^
234 long bpf_msg_pull_data(struct sk_msg_buff *msg, u32 start, u32 end, u64 flags)
236 For socket policies, pull in non-linear data from user space for ``msg`` and set
237 pointers ``msg->data`` and ``msg->data_end`` to ``start`` and ``end`` bytes
238 offsets into ``msg``, respectively.
240 If a program of type ``BPF_PROG_TYPE_SK_MSG`` is run on a ``msg`` it can only
241 parse data that the (``data``, ``data_end``) pointers have already consumed.
242 For ``sendmsg()`` hooks this is likely the first scatterlist element. But for
243 calls relying on MSG_SPLICE_PAGES (e.g., ``sendfile()``) this will be the
244 range (**0**, **0**) because the data is shared with user space and by default
245 the objective is to avoid allowing user space to modify data while (or after)
246 BPF verdict is being decided. This helper can be used to pull in data and to
247 set the start and end pointers to given values. Data will be copied if
248 necessary (i.e., if data was not linear and if start and end pointers do not
249 point to the same chunk).
251 A call to this helper is susceptible to change the underlying packet buffer.
252 Therefore, at load time, all checks on pointers previously done by the verifier
253 are invalidated and must be performed again, if the helper is used in
254 combination with direct packet access.
256 All values for ``flags`` are reserved for future usage, and must be left at
259 Returns 0 on success, or a negative error in case of failure.
261 bpf_map_lookup_elem()
262 ^^^^^^^^^^^^^^^^^^^^^
266 void *bpf_map_lookup_elem(struct bpf_map *map, const void *key)
268 Look up a socket entry in the sockmap or sockhash map.
270 Returns the socket entry associated to ``key``, or NULL if no entry was found.
272 bpf_map_update_elem()
273 ^^^^^^^^^^^^^^^^^^^^^
276 long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags)
278 Add or update a socket entry in a sockmap or sockhash.
280 The flags argument can be one of the following:
282 - BPF_ANY: Create a new element or update an existing element.
283 - BPF_NOEXIST: Create a new element only if it did not exist.
284 - BPF_EXIST: Update an existing element.
286 Returns 0 on success, or a negative error in case of failure.
288 bpf_map_delete_elem()
289 ^^^^^^^^^^^^^^^^^^^^^^
292 long bpf_map_delete_elem(struct bpf_map *map, const void *key)
294 Delete a socket entry from a sockmap or a sockhash.
296 Returns 0 on success, or a negative error in case of failure.
300 bpf_map_update_elem()
301 ^^^^^^^^^^^^^^^^^^^^^
304 int bpf_map_update_elem(int fd, const void *key, const void *value, __u64 flags)
306 Sockmap entries can be added or updated using the ``bpf_map_update_elem()``
307 function. The ``key`` parameter is the index value of the sockmap array. And the
308 ``value`` parameter is the FD value of that socket.
310 Under the hood, the sockmap update function uses the socket FD value to
311 retrieve the associated socket and its attached psock.
313 The flags argument can be one of the following:
315 - BPF_ANY: Create a new element or update an existing element.
316 - BPF_NOEXIST: Create a new element only if it did not exist.
317 - BPF_EXIST: Update an existing element.
319 bpf_map_lookup_elem()
320 ^^^^^^^^^^^^^^^^^^^^^
323 int bpf_map_lookup_elem(int fd, const void *key, void *value)
325 Sockmap entries can be retrieved using the ``bpf_map_lookup_elem()`` function.
328 The entry returned is a socket cookie rather than a socket itself.
330 bpf_map_delete_elem()
331 ^^^^^^^^^^^^^^^^^^^^^
334 int bpf_map_delete_elem(int fd, const void *key)
336 Sockmap entries can be deleted using the ``bpf_map_delete_elem()``
339 Returns 0 on success, or negative error in case of failure.
346 Several examples of the use of sockmap APIs can be found in:
348 - `tools/testing/selftests/bpf/progs/test_sockmap_kern.h`_
349 - `tools/testing/selftests/bpf/progs/sockmap_parse_prog.c`_
350 - `tools/testing/selftests/bpf/progs/sockmap_verdict_prog.c`_
351 - `tools/testing/selftests/bpf/progs/test_sockmap_listen.c`_
352 - `tools/testing/selftests/bpf/progs/test_sockmap_update.c`_
354 The following code snippet shows how to declare a sockmap.
359 __uint(type, BPF_MAP_TYPE_SOCKMAP);
360 __uint(max_entries, 1);
362 __type(value, __u64);
363 } sock_map_rx SEC(".maps");
365 The following code snippet shows a sample parser program.
369 SEC("sk_skb/stream_parser")
370 int bpf_prog_parser(struct __sk_buff *skb)
375 The following code snippet shows a simple verdict program that interacts with a
376 sockmap to redirect traffic to another socket based on the local port.
380 SEC("sk_skb/stream_verdict")
381 int bpf_prog_verdict(struct __sk_buff *skb)
383 __u32 lport = skb->local_port;
387 return bpf_sk_redirect_map(skb, &sock_map_rx, idx, 0);
392 The following code snippet shows how to declare a sockhash map.
404 __uint(type, BPF_MAP_TYPE_SOCKHASH);
405 __uint(max_entries, 1);
406 __type(key, struct socket_key);
407 __type(value, __u64);
408 } sock_hash_rx SEC(".maps");
410 The following code snippet shows a simple verdict program that interacts with a
411 sockhash to redirect traffic to another socket based on a hash of some of the
417 void extract_socket_key(struct __sk_buff *skb, struct socket_key *key)
419 key->src_ip = skb->remote_ip4;
420 key->dst_ip = skb->local_ip4;
421 key->src_port = skb->remote_port >> 16;
422 key->dst_port = (bpf_htonl(skb->local_port)) >> 16;
425 SEC("sk_skb/stream_verdict")
426 int bpf_prog_verdict(struct __sk_buff *skb)
428 struct socket_key key;
430 extract_socket_key(skb, &key);
432 return bpf_sk_redirect_hash(skb, &sock_hash_rx, &key, 0);
437 Several examples of the use of sockmap APIs can be found in:
439 - `tools/testing/selftests/bpf/prog_tests/sockmap_basic.c`_
440 - `tools/testing/selftests/bpf/test_sockmap.c`_
441 - `tools/testing/selftests/bpf/test_maps.c`_
443 The following code sample shows how to create a sockmap, attach a parser and
444 verdict program, as well as add a socket entry.
448 int create_sample_sockmap(int sock, int parse_prog_fd, int verdict_prog_fd)
453 map = bpf_map_create(BPF_MAP_TYPE_SOCKMAP, NULL, sizeof(int), sizeof(int), 1, NULL);
455 fprintf(stderr, "Failed to create sockmap: %s\n", strerror(errno));
459 err = bpf_prog_attach(parse_prog_fd, map, BPF_SK_SKB_STREAM_PARSER, 0);
461 fprintf(stderr, "Failed to attach_parser_prog_to_map: %s\n", strerror(errno));
465 err = bpf_prog_attach(verdict_prog_fd, map, BPF_SK_SKB_STREAM_VERDICT, 0);
467 fprintf(stderr, "Failed to attach_verdict_prog_to_map: %s\n", strerror(errno));
471 err = bpf_map_update_elem(map, &index, &sock, BPF_NOEXIST);
473 fprintf(stderr, "Failed to update sockmap: %s\n", strerror(errno));
485 - https://github.com/jrfastab/linux-kernel-xdp/commit/c89fd73cb9d2d7f3c716c3e00836f07b1aeb261f
486 - https://lwn.net/Articles/731133/
487 - http://vger.kernel.org/lpc_net2018_talks/ktls_bpf_paper.pdf
488 - https://lwn.net/Articles/748628/
489 - https://lore.kernel.org/bpf/20200218171023.844439-7-jakub@cloudflare.com/
491 .. _`tools/testing/selftests/bpf/progs/test_sockmap_kern.h`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_kern.h
492 .. _`tools/testing/selftests/bpf/progs/sockmap_parse_prog.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/sockmap_parse_prog.c
493 .. _`tools/testing/selftests/bpf/progs/sockmap_verdict_prog.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/sockmap_verdict_prog.c
494 .. _`tools/testing/selftests/bpf/prog_tests/sockmap_basic.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/prog_tests/sockmap_basic.c
495 .. _`tools/testing/selftests/bpf/test_sockmap.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/test_sockmap.c
496 .. _`tools/testing/selftests/bpf/test_maps.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/test_maps.c
497 .. _`tools/testing/selftests/bpf/progs/test_sockmap_listen.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_listen.c
498 .. _`tools/testing/selftests/bpf/progs/test_sockmap_update.c`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/testing/selftests/bpf/progs/test_sockmap_update.c