]> git.ipfire.org Git - thirdparty/man-pages.git/blob - man2/bpf.2
4f516104b716d4583c12ab9bde889aab4f89a176
[thirdparty/man-pages.git] / man2 / bpf.2
1 .\" Copyright (C) 2015 Alexei Starovoitov <ast@kernel.org>
2 .\" and Copyright (C) 2015 Michael Kerrisk <mtk.manpages@gmail.com>
3 .\"
4 .\" SPDX-License-Identifier: Linux-man-pages-copyleft
5 .\"
6 .TH BPF 2 2021-08-27 "Linux" "Linux Programmer's Manual"
7 .SH NAME
8 bpf \- perform a command on an extended BPF map or program
9 .SH SYNOPSIS
10 .nf
11 .B #include <linux/bpf.h>
12 .PP
13 .BI "int bpf(int " cmd ", union bpf_attr *" attr ", unsigned int " size );
14 .fi
15 .SH DESCRIPTION
16 The
17 .BR bpf ()
18 system call performs a range of operations related to extended
19 Berkeley Packet Filters.
20 Extended BPF (or eBPF) is similar to
21 the original ("classic") BPF (cBPF) used to filter network packets.
22 For both cBPF and eBPF programs,
23 the kernel statically analyzes the programs before loading them,
24 in order to ensure that they cannot harm the running system.
25 .PP
26 eBPF extends cBPF in multiple ways, including the ability to call
27 a fixed set of in-kernel helper functions
28 .\" See 'enum bpf_func_id' in include/uapi/linux/bpf.h
29 (via the
30 .B BPF_CALL
31 opcode extension provided by eBPF)
32 and access shared data structures such as eBPF maps.
33 .\"
34 .SS Extended BPF Design/Architecture
35 eBPF maps are a generic data structure for storage of different data types.
36 Data types are generally treated as binary blobs, so a user just specifies
37 the size of the key and the size of the value at map-creation time.
38 In other words, a key/value for a given map can have an arbitrary structure.
39 .PP
40 A user process can create multiple maps (with key/value-pairs being
41 opaque bytes of data) and access them via file descriptors.
42 Different eBPF programs can access the same maps in parallel.
43 It's up to the user process and eBPF program to decide what they store
44 inside maps.
45 .PP
46 There's one special map type, called a program array.
47 This type of map stores file descriptors referring to other eBPF programs.
48 When a lookup in the map is performed, the program flow is
49 redirected in-place to the beginning of another eBPF program and does not
50 return back to the calling program.
51 The level of nesting has a fixed limit of 32,
52 .\" Defined by the kernel constant MAX_TAIL_CALL_CNT in include/linux/bpf.h
53 so that infinite loops cannot be crafted.
54 At run time, the program file descriptors stored in the map can be modified,
55 so program functionality can be altered based on specific requirements.
56 All programs referred to in a program-array map must
57 have been previously loaded into the kernel via
58 .BR bpf ().
59 If a map lookup fails, the current program continues its execution.
60 See
61 .B BPF_MAP_TYPE_PROG_ARRAY
62 below for further details.
63 .PP
64 Generally, eBPF programs are loaded by the user process and automatically
65 unloaded when the process exits.
66 In some cases, for example,
67 .BR tc\-bpf (8),
68 the program will continue to stay alive inside the kernel even after the
69 process that loaded the program exits.
70 In that case,
71 the tc subsystem holds a reference to the eBPF program after the
72 file descriptor has been closed by the user-space program.
73 Thus, whether a specific program continues to live inside the kernel
74 depends on how it is further attached to a given kernel subsystem
75 after it was loaded via
76 .BR bpf ().
77 .PP
78 Each eBPF program is a set of instructions that is safe to run until
79 its completion.
80 An in-kernel verifier statically determines that the eBPF program
81 terminates and is safe to execute.
82 During verification, the kernel increments reference counts for each of
83 the maps that the eBPF program uses,
84 so that the attached maps can't be removed until the program is unloaded.
85 .PP
86 eBPF programs can be attached to different events.
87 These events can be the arrival of network packets, tracing
88 events, classification events by network queueing disciplines
89 (for eBPF programs attached to a
90 .BR tc (8)
91 classifier), and other types that may be added in the future.
92 A new event triggers execution of the eBPF program, which
93 may store information about the event in eBPF maps.
94 Beyond storing data, eBPF programs may call a fixed set of
95 in-kernel helper functions.
96 .PP
97 The same eBPF program can be attached to multiple events and different
98 eBPF programs can access the same map:
99 .PP
100 .in +4n
101 .EX
102 tracing tracing tracing packet packet packet
103 event A event B event C on eth0 on eth1 on eth2
104 | | | | | \(ha
105 | | | | v |
106 \-\-> tracing <\-\- tracing socket tc ingress tc egress
107 prog_1 prog_2 prog_3 classifier action
108 | | | | prog_4 prog_5
109 |\-\-\- \-\-\-\-\-| |\-\-\-\-\-\-| map_3 | |
110 map_1 map_2 \-\-| map_4 |\-\-
111 .EE
112 .in
113 .\"
114 .SS Arguments
115 The operation to be performed by the
116 .BR bpf ()
117 system call is determined by the
118 .I cmd
119 argument.
120 Each operation takes an accompanying argument,
121 provided via
122 .IR attr ,
123 which is a pointer to a union of type
124 .I bpf_attr
125 (see below).
126 The
127 .I size
128 argument is the size of the union pointed to by
129 .IR attr .
130 .PP
131 The value provided in
132 .I cmd
133 is one of the following:
134 .TP
135 .B BPF_MAP_CREATE
136 Create a map and return a file descriptor that refers to the map.
137 The close-on-exec file descriptor flag (see
138 .BR fcntl (2))
139 is automatically enabled for the new file descriptor.
140 .TP
141 .B BPF_MAP_LOOKUP_ELEM
142 Look up an element by key in a specified map and return its value.
143 .TP
144 .B BPF_MAP_UPDATE_ELEM
145 Create or update an element (key/value pair) in a specified map.
146 .TP
147 .B BPF_MAP_DELETE_ELEM
148 Look up and delete an element by key in a specified map.
149 .TP
150 .B BPF_MAP_GET_NEXT_KEY
151 Look up an element by key in a specified map and return the key
152 of the next element.
153 .TP
154 .B BPF_PROG_LOAD
155 Verify and load an eBPF program,
156 returning a new file descriptor associated with the program.
157 The close-on-exec file descriptor flag (see
158 .BR fcntl (2))
159 is automatically enabled for the new file descriptor.
160 .IP
161 The
162 .I bpf_attr
163 union consists of various anonymous structures that are used by different
164 .BR bpf ()
165 commands:
166 .PP
167 .in +4n
168 .EX
169 union bpf_attr {
170 struct { /* Used by BPF_MAP_CREATE */
171 __u32 map_type;
172 __u32 key_size; /* size of key in bytes */
173 __u32 value_size; /* size of value in bytes */
174 __u32 max_entries; /* maximum number of entries
175 in a map */
176 };
177
178 struct { /* Used by BPF_MAP_*_ELEM and BPF_MAP_GET_NEXT_KEY
179 commands */
180 __u32 map_fd;
181 __aligned_u64 key;
182 union {
183 __aligned_u64 value;
184 __aligned_u64 next_key;
185 };
186 __u64 flags;
187 };
188
189 struct { /* Used by BPF_PROG_LOAD */
190 __u32 prog_type;
191 __u32 insn_cnt;
192 __aligned_u64 insns; /* \(aqconst struct bpf_insn *\(aq */
193 __aligned_u64 license; /* \(aqconst char *\(aq */
194 __u32 log_level; /* verbosity level of verifier */
195 __u32 log_size; /* size of user buffer */
196 __aligned_u64 log_buf; /* user supplied \(aqchar *\(aq
197 buffer */
198 __u32 kern_version;
199 /* checked when prog_type=kprobe
200 (since Linux 4.1) */
201 .\" commit 2541517c32be2531e0da59dfd7efc1ce844644f5
202 };
203 } __attribute__((aligned(8)));
204 .EE
205 .in
206 .\"
207 .SS eBPF maps
208 Maps are a generic data structure for storage of different types of data.
209 They allow sharing of data between eBPF kernel programs,
210 and also between kernel and user-space applications.
211 .PP
212 Each map type has the following attributes:
213 .IP * 3
214 type
215 .IP *
216 maximum number of elements
217 .IP *
218 key size in bytes
219 .IP *
220 value size in bytes
221 .PP
222 The following wrapper functions demonstrate how various
223 .BR bpf ()
224 commands can be used to access the maps.
225 The functions use the
226 .I cmd
227 argument to invoke different operations.
228 .TP
229 .B BPF_MAP_CREATE
230 The
231 .B BPF_MAP_CREATE
232 command creates a new map,
233 returning a new file descriptor that refers to the map.
234 .IP
235 .in +4n
236 .EX
237 int
238 bpf_create_map(enum bpf_map_type map_type,
239 unsigned int key_size,
240 unsigned int value_size,
241 unsigned int max_entries)
242 {
243 union bpf_attr attr = {
244 .map_type = map_type,
245 .key_size = key_size,
246 .value_size = value_size,
247 .max_entries = max_entries
248 };
249
250 return bpf(BPF_MAP_CREATE, &attr, sizeof(attr));
251 }
252 .EE
253 .in
254 .IP
255 The new map has the type specified by
256 .IR map_type ,
257 and attributes as specified in
258 .IR key_size ,
259 .IR value_size ,
260 and
261 .IR max_entries .
262 On success, this operation returns a file descriptor.
263 On error, \-1 is returned and
264 .I errno
265 is set to
266 .BR EINVAL ,
267 .BR EPERM ,
268 or
269 .BR ENOMEM .
270 .IP
271 The
272 .I key_size
273 and
274 .I value_size
275 attributes will be used by the verifier during program loading
276 to check that the program is calling
277 .BR bpf_map_*_elem ()
278 helper functions with a correctly initialized
279 .I key
280 and to check that the program doesn't access the map element
281 .I value
282 beyond the specified
283 .IR value_size .
284 For example, when a map is created with a
285 .I key_size
286 of 8 and the eBPF program calls
287 .IP
288 .in +4n
289 .EX
290 bpf_map_lookup_elem(map_fd, fp \- 4)
291 .EE
292 .in
293 .IP
294 the program will be rejected,
295 since the in-kernel helper function
296 .IP
297 .in +4n
298 .EX
299 bpf_map_lookup_elem(map_fd, void *key)
300 .EE
301 .in
302 .IP
303 expects to read 8 bytes from the location pointed to by
304 .IR key ,
305 but the
306 .I fp\ \-\ 4
307 (where
308 .I fp
309 is the top of the stack)
310 starting address will cause out-of-bounds stack access.
311 .IP
312 Similarly, when a map is created with a
313 .I value_size
314 of 1 and the eBPF program contains
315 .IP
316 .in +4n
317 .EX
318 value = bpf_map_lookup_elem(...);
319 *(u32 *) value = 1;
320 .EE
321 .in
322 .IP
323 the program will be rejected, since it accesses the
324 .I value
325 pointer beyond the specified 1 byte
326 .I value_size
327 limit.
328 .IP
329 Currently, the following values are supported for
330 .IR map_type :
331 .IP
332 .in +4n
333 .EX
334 enum bpf_map_type {
335 BPF_MAP_TYPE_UNSPEC, /* Reserve 0 as invalid map type */
336 BPF_MAP_TYPE_HASH,
337 BPF_MAP_TYPE_ARRAY,
338 BPF_MAP_TYPE_PROG_ARRAY,
339 BPF_MAP_TYPE_PERF_EVENT_ARRAY,
340 BPF_MAP_TYPE_PERCPU_HASH,
341 BPF_MAP_TYPE_PERCPU_ARRAY,
342 BPF_MAP_TYPE_STACK_TRACE,
343 BPF_MAP_TYPE_CGROUP_ARRAY,
344 BPF_MAP_TYPE_LRU_HASH,
345 BPF_MAP_TYPE_LRU_PERCPU_HASH,
346 BPF_MAP_TYPE_LPM_TRIE,
347 BPF_MAP_TYPE_ARRAY_OF_MAPS,
348 BPF_MAP_TYPE_HASH_OF_MAPS,
349 BPF_MAP_TYPE_DEVMAP,
350 BPF_MAP_TYPE_SOCKMAP,
351 BPF_MAP_TYPE_CPUMAP,
352 BPF_MAP_TYPE_XSKMAP,
353 BPF_MAP_TYPE_SOCKHASH,
354 BPF_MAP_TYPE_CGROUP_STORAGE,
355 BPF_MAP_TYPE_REUSEPORT_SOCKARRAY,
356 BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE,
357 BPF_MAP_TYPE_QUEUE,
358 BPF_MAP_TYPE_STACK,
359 /* See /usr/include/linux/bpf.h for the full list. */
360 };
361 .EE
362 .in
363 .IP
364 .I map_type
365 selects one of the available map implementations in the kernel.
366 .\" FIXME We need an explanation of why one might choose each of
367 .\" these map implementations
368 For all map types,
369 eBPF programs access maps with the same
370 .BR bpf_map_lookup_elem ()
371 and
372 .BR bpf_map_update_elem ()
373 helper functions.
374 Further details of the various map types are given below.
375 .TP
376 .B BPF_MAP_LOOKUP_ELEM
377 The
378 .B BPF_MAP_LOOKUP_ELEM
379 command looks up an element with a given
380 .I key
381 in the map referred to by the file descriptor
382 .IR fd .
383 .IP
384 .in +4n
385 .EX
386 int
387 bpf_lookup_elem(int fd, const void *key, void *value)
388 {
389 union bpf_attr attr = {
390 .map_fd = fd,
391 .key = ptr_to_u64(key),
392 .value = ptr_to_u64(value),
393 };
394
395 return bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
396 }
397 .EE
398 .in
399 .IP
400 If an element is found,
401 the operation returns zero and stores the element's value into
402 .IR value ,
403 which must point to a buffer of
404 .I value_size
405 bytes.
406 .IP
407 If no element is found, the operation returns \-1 and sets
408 .I errno
409 to
410 .BR ENOENT .
411 .TP
412 .B BPF_MAP_UPDATE_ELEM
413 The
414 .B BPF_MAP_UPDATE_ELEM
415 command
416 creates or updates an element with a given
417 .I key/value
418 in the map referred to by the file descriptor
419 .IR fd .
420 .IP
421 .in +4n
422 .EX
423 int
424 bpf_update_elem(int fd, const void *key, const void *value,
425 uint64_t flags)
426 {
427 union bpf_attr attr = {
428 .map_fd = fd,
429 .key = ptr_to_u64(key),
430 .value = ptr_to_u64(value),
431 .flags = flags,
432 };
433
434 return bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
435 }
436 .EE
437 .in
438 .IP
439 The
440 .I flags
441 argument should be specified as one of the following:
442 .RS
443 .TP
444 .B BPF_ANY
445 Create a new element or update an existing element.
446 .TP
447 .B BPF_NOEXIST
448 Create a new element only if it did not exist.
449 .TP
450 .B BPF_EXIST
451 Update an existing element.
452 .RE
453 .IP
454 On success, the operation returns zero.
455 On error, \-1 is returned and
456 .I errno
457 is set to
458 .BR EINVAL ,
459 .BR EPERM ,
460 .BR ENOMEM ,
461 or
462 .BR E2BIG .
463 .B E2BIG
464 indicates that the number of elements in the map reached the
465 .I max_entries
466 limit specified at map creation time.
467 .B EEXIST
468 will be returned if
469 .I flags
470 specifies
471 .B BPF_NOEXIST
472 and the element with
473 .I key
474 already exists in the map.
475 .B ENOENT
476 will be returned if
477 .I flags
478 specifies
479 .B BPF_EXIST
480 and the element with
481 .I key
482 doesn't exist in the map.
483 .TP
484 .B BPF_MAP_DELETE_ELEM
485 The
486 .B BPF_MAP_DELETE_ELEM
487 command
488 deletes the element whose key is
489 .I key
490 from the map referred to by the file descriptor
491 .IR fd .
492 .IP
493 .in +4n
494 .EX
495 int
496 bpf_delete_elem(int fd, const void *key)
497 {
498 union bpf_attr attr = {
499 .map_fd = fd,
500 .key = ptr_to_u64(key),
501 };
502
503 return bpf(BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
504 }
505 .EE
506 .in
507 .IP
508 On success, zero is returned.
509 If the element is not found, \-1 is returned and
510 .I errno
511 is set to
512 .BR ENOENT .
513 .TP
514 .B BPF_MAP_GET_NEXT_KEY
515 The
516 .B BPF_MAP_GET_NEXT_KEY
517 command looks up an element by
518 .I key
519 in the map referred to by the file descriptor
520 .I fd
521 and sets the
522 .I next_key
523 pointer to the key of the next element.
524 .IP
525 .in +4n
526 .EX
527 int
528 bpf_get_next_key(int fd, const void *key, void *next_key)
529 {
530 union bpf_attr attr = {
531 .map_fd = fd,
532 .key = ptr_to_u64(key),
533 .next_key = ptr_to_u64(next_key),
534 };
535
536 return bpf(BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
537 }
538 .EE
539 .in
540 .IP
541 If
542 .I key
543 is found, the operation returns zero and sets the
544 .I next_key
545 pointer to the key of the next element.
546 If
547 .I key
548 is not found, the operation returns zero and sets the
549 .I next_key
550 pointer to the key of the first element.
551 If
552 .I key
553 is the last element, \-1 is returned and
554 .I errno
555 is set to
556 .BR ENOENT .
557 Other possible
558 .I errno
559 values are
560 .BR ENOMEM ,
561 .BR EFAULT ,
562 .BR EPERM ,
563 and
564 .BR EINVAL .
565 This method can be used to iterate over all elements in the map.
566 .TP
567 .B close(map_fd)
568 Delete the map referred to by the file descriptor
569 .IR map_fd .
570 When the user-space program that created a map exits, all maps will
571 be deleted automatically (but see NOTES).
572 .\"
573 .SS eBPF map types
574 The following map types are supported:
575 .TP
576 .B BPF_MAP_TYPE_HASH
577 .\" commit 0f8e4bd8a1fc8c4185f1630061d0a1f2d197a475
578 Hash-table maps have the following characteristics:
579 .RS
580 .IP * 3
581 Maps are created and destroyed by user-space programs.
582 Both user-space and eBPF programs
583 can perform lookup, update, and delete operations.
584 .IP *
585 The kernel takes care of allocating and freeing key/value pairs.
586 .IP *
587 The
588 .BR map_update_elem ()
589 helper will fail to insert new element when the
590 .I max_entries
591 limit is reached.
592 (This ensures that eBPF programs cannot exhaust memory.)
593 .IP *
594 .BR map_update_elem ()
595 replaces existing elements atomically.
596 .RE
597 .IP
598 Hash-table maps are
599 optimized for speed of lookup.
600 .TP
601 .B BPF_MAP_TYPE_ARRAY
602 .\" commit 28fbcfa08d8ed7c5a50d41a0433aad222835e8e3
603 Array maps have the following characteristics:
604 .RS
605 .IP * 3
606 Optimized for fastest possible lookup.
607 In the future the verifier/JIT compiler
608 may recognize lookup() operations that employ a constant key
609 and optimize it into constant pointer.
610 It is possible to optimize a non-constant
611 key into direct pointer arithmetic as well, since pointers and
612 .I value_size
613 are constant for the life of the eBPF program.
614 In other words,
615 .BR array_map_lookup_elem ()
616 may be 'inlined' by the verifier/JIT compiler
617 while preserving concurrent access to this map from user space.
618 .IP *
619 All array elements pre-allocated and zero initialized at init time
620 .IP *
621 The key is an array index, and must be exactly four bytes.
622 .IP *
623 .BR map_delete_elem ()
624 fails with the error
625 .BR EINVAL ,
626 since elements cannot be deleted.
627 .IP *
628 .BR map_update_elem ()
629 replaces elements in a
630 .B nonatomic
631 fashion;
632 for atomic updates, a hash-table map should be used instead.
633 There is however one special case that can also be used with arrays:
634 the atomic built-in
635 .B __sync_fetch_and_add()
636 can be used on 32 and 64 bit atomic counters.
637 For example, it can be
638 applied on the whole value itself if it represents a single counter,
639 or in case of a structure containing multiple counters, it could be
640 used on individual counters.
641 This is quite often useful for aggregation and accounting of events.
642 .RE
643 .IP
644 Among the uses for array maps are the following:
645 .RS
646 .IP * 3
647 As "global" eBPF variables: an array of 1 element whose key is (index) 0
648 and where the value is a collection of 'global' variables which
649 eBPF programs can use to keep state between events.
650 .IP *
651 Aggregation of tracing events into a fixed set of buckets.
652 .IP *
653 Accounting of networking events, for example, number of packets and packet
654 sizes.
655 .RE
656 .TP
657 .BR BPF_MAP_TYPE_PROG_ARRAY " (since Linux 4.2)"
658 A program array map is a special kind of array map whose map values
659 contain only file descriptors referring to other eBPF programs.
660 Thus, both the
661 .I key_size
662 and
663 .I value_size
664 must be exactly four bytes.
665 This map is used in conjunction with the
666 .BR bpf_tail_call ()
667 helper.
668 .IP
669 This means that an eBPF program with a program array map attached to it
670 can call from kernel side into
671 .IP
672 .in +4n
673 .EX
674 void bpf_tail_call(void *context, void *prog_map,
675 unsigned int index);
676 .EE
677 .in
678 .IP
679 and therefore replace its own program flow with the one from the program
680 at the given program array slot, if present.
681 This can be regarded as kind of a jump table to a different eBPF program.
682 The invoked program will then reuse the same stack.
683 When a jump into the new program has been performed,
684 it won't return to the old program anymore.
685 .IP
686 If no eBPF program is found at the given index of the program array
687 (because the map slot doesn't contain a valid program file descriptor,
688 the specified lookup index/key is out of bounds,
689 or the limit of 32
690 .\" MAX_TAIL_CALL_CNT
691 nested calls has been exceed),
692 execution continues with the current eBPF program.
693 This can be used as a fall-through for default cases.
694 .IP
695 A program array map is useful, for example, in tracing or networking, to
696 handle individual system calls or protocols in their own subprograms and
697 use their identifiers as an individual map index.
698 This approach may result in performance benefits,
699 and also makes it possible to overcome the maximum
700 instruction limit of a single eBPF program.
701 In dynamic environments,
702 a user-space daemon might atomically replace individual subprograms
703 at run-time with newer versions to alter overall program behavior,
704 for instance, if global policies change.
705 .\"
706 .SS eBPF programs
707 The
708 .B BPF_PROG_LOAD
709 command is used to load an eBPF program into the kernel.
710 The return value for this command is a new file descriptor associated
711 with this eBPF program.
712 .PP
713 .in +4n
714 .EX
715 char bpf_log_buf[LOG_BUF_SIZE];
716
717 int
718 bpf_prog_load(enum bpf_prog_type type,
719 const struct bpf_insn *insns, int insn_cnt,
720 const char *license)
721 {
722 union bpf_attr attr = {
723 .prog_type = type,
724 .insns = ptr_to_u64(insns),
725 .insn_cnt = insn_cnt,
726 .license = ptr_to_u64(license),
727 .log_buf = ptr_to_u64(bpf_log_buf),
728 .log_size = LOG_BUF_SIZE,
729 .log_level = 1,
730 };
731
732 return bpf(BPF_PROG_LOAD, &attr, sizeof(attr));
733 }
734 .EE
735 .in
736 .PP
737 .I prog_type
738 is one of the available program types:
739 .IP
740 .in +4n
741 .EX
742 enum bpf_prog_type {
743 BPF_PROG_TYPE_UNSPEC, /* Reserve 0 as invalid
744 program type */
745 BPF_PROG_TYPE_SOCKET_FILTER,
746 BPF_PROG_TYPE_KPROBE,
747 BPF_PROG_TYPE_SCHED_CLS,
748 BPF_PROG_TYPE_SCHED_ACT,
749 BPF_PROG_TYPE_TRACEPOINT,
750 BPF_PROG_TYPE_XDP,
751 BPF_PROG_TYPE_PERF_EVENT,
752 BPF_PROG_TYPE_CGROUP_SKB,
753 BPF_PROG_TYPE_CGROUP_SOCK,
754 BPF_PROG_TYPE_LWT_IN,
755 BPF_PROG_TYPE_LWT_OUT,
756 BPF_PROG_TYPE_LWT_XMIT,
757 BPF_PROG_TYPE_SOCK_OPS,
758 BPF_PROG_TYPE_SK_SKB,
759 BPF_PROG_TYPE_CGROUP_DEVICE,
760 BPF_PROG_TYPE_SK_MSG,
761 BPF_PROG_TYPE_RAW_TRACEPOINT,
762 BPF_PROG_TYPE_CGROUP_SOCK_ADDR,
763 BPF_PROG_TYPE_LWT_SEG6LOCAL,
764 BPF_PROG_TYPE_LIRC_MODE2,
765 BPF_PROG_TYPE_SK_REUSEPORT,
766 BPF_PROG_TYPE_FLOW_DISSECTOR,
767 /* See /usr/include/linux/bpf.h for the full list. */
768 };
769 .EE
770 .in
771 .PP
772 For further details of eBPF program types, see below.
773 .PP
774 The remaining fields of
775 .I bpf_attr
776 are set as follows:
777 .IP * 3
778 .I insns
779 is an array of
780 .I "struct bpf_insn"
781 instructions.
782 .IP *
783 .I insn_cnt
784 is the number of instructions in the program referred to by
785 .IR insns .
786 .IP *
787 .I license
788 is a license string, which must be GPL compatible to call helper functions
789 marked
790 .IR gpl_only .
791 (The licensing rules are the same as for kernel modules,
792 so that also dual licenses, such as "Dual BSD/GPL", may be used.)
793 .IP *
794 .I log_buf
795 is a pointer to a caller-allocated buffer in which the in-kernel
796 verifier can store the verification log.
797 This log is a multi-line string that can be checked by
798 the program author in order to understand how the verifier came to
799 the conclusion that the eBPF program is unsafe.
800 The format of the output can change at any time as the verifier evolves.
801 .IP *
802 .I log_size
803 size of the buffer pointed to by
804 .IR log_buf .
805 If the size of the buffer is not large enough to store all
806 verifier messages, \-1 is returned and
807 .I errno
808 is set to
809 .BR ENOSPC .
810 .IP *
811 .I log_level
812 verbosity level of the verifier.
813 A value of zero means that the verifier will not provide a log;
814 in this case,
815 .I log_buf
816 must be a NULL pointer, and
817 .I log_size
818 must be zero.
819 .PP
820 Applying
821 .BR close (2)
822 to the file descriptor returned by
823 .B BPF_PROG_LOAD
824 will unload the eBPF program (but see NOTES).
825 .PP
826 Maps are accessible from eBPF programs and are used to exchange data between
827 eBPF programs and between eBPF programs and user-space programs.
828 For example,
829 eBPF programs can process various events (like kprobe, packets) and
830 store their data into a map,
831 and user-space programs can then fetch data from the map.
832 Conversely, user-space programs can use a map as a configuration mechanism,
833 populating the map with values checked by the eBPF program,
834 which then modifies its behavior on the fly according to those values.
835 .\"
836 .\"
837 .SS eBPF program types
838 The eBPF program type
839 .RI ( prog_type )
840 determines the subset of kernel helper functions that the program
841 may call.
842 The program type also determines the program input (context)\(emthe
843 format of
844 .I "struct bpf_context"
845 (which is the data blob passed into the eBPF program as the first argument).
846 .\"
847 .\" FIXME
848 .\" Somewhere in this page we need a general introduction to the
849 .\" bpf_context. For example, how does a BPF program access the
850 .\" context?
851 .PP
852 For example, a tracing program does not have the exact same
853 subset of helper functions as a socket filter program
854 (though they may have some helpers in common).
855 Similarly,
856 the input (context) for a tracing program is a set of register values,
857 while for a socket filter it is a network packet.
858 .PP
859 The set of functions available to eBPF programs of a given type may increase
860 in the future.
861 .PP
862 The following program types are supported:
863 .TP
864 .BR BPF_PROG_TYPE_SOCKET_FILTER " (since Linux 3.19)"
865 Currently, the set of functions for
866 .B BPF_PROG_TYPE_SOCKET_FILTER
867 is:
868 .IP
869 .in +4n
870 .EX
871 bpf_map_lookup_elem(map_fd, void *key)
872 /* look up key in a map_fd */
873 bpf_map_update_elem(map_fd, void *key, void *value)
874 /* update key/value */
875 bpf_map_delete_elem(map_fd, void *key)
876 /* delete key in a map_fd */
877 .EE
878 .in
879 .IP
880 The
881 .I bpf_context
882 argument is a pointer to a
883 .IR "struct __sk_buff" .
884 .\" FIXME: We need some text here to explain how the program
885 .\" accesses __sk_buff.
886 .\" See 'struct __sk_buff' and commit 9bac3d6d548e5
887 .\"
888 .\" Alexei commented:
889 .\" Actually now in case of SOCKET_FILTER, SCHED_CLS, SCHED_ACT
890 .\" the program can now access skb fields.
891 .\"
892 .TP
893 .BR BPF_PROG_TYPE_KPROBE " (since Linux 4.1)"
894 .\" commit 2541517c32be2531e0da59dfd7efc1ce844644f5
895 [To be documented]
896 .\" FIXME Document this program type
897 .\" Describe allowed helper functions for this program type
898 .\" Describe bpf_context for this program type
899 .\"
900 .\" FIXME We need text here to describe 'kern_version'
901 .TP
902 .BR BPF_PROG_TYPE_SCHED_CLS " (since Linux 4.1)"
903 .\" commit 96be4325f443dbbfeb37d2a157675ac0736531a1
904 .\" commit e2e9b6541dd4b31848079da80fe2253daaafb549
905 [To be documented]
906 .\" FIXME Document this program type
907 .\" Describe allowed helper functions for this program type
908 .\" Describe bpf_context for this program type
909 .TP
910 .BR BPF_PROG_TYPE_SCHED_ACT " (since Linux 4.1)"
911 .\" commit 94caee8c312d96522bcdae88791aaa9ebcd5f22c
912 .\" commit a8cb5f556b567974d75ea29c15181c445c541b1f
913 [To be documented]
914 .\" FIXME Document this program type
915 .\" Describe allowed helper functions for this program type
916 .\" Describe bpf_context for this program type
917 .SS Events
918 Once a program is loaded, it can be attached to an event.
919 Various kernel subsystems have different ways to do so.
920 .PP
921 Since Linux 3.19,
922 .\" commit 89aa075832b0da4402acebd698d0411dcc82d03e
923 the following call will attach the program
924 .I prog_fd
925 to the socket
926 .IR sockfd ,
927 which was created by an earlier call to
928 .BR socket (2):
929 .PP
930 .in +4n
931 .EX
932 setsockopt(sockfd, SOL_SOCKET, SO_ATTACH_BPF,
933 &prog_fd, sizeof(prog_fd));
934 .EE
935 .in
936 .PP
937 Since Linux 4.1,
938 .\" commit 2541517c32be2531e0da59dfd7efc1ce844644f5
939 the following call may be used to attach
940 the eBPF program referred to by the file descriptor
941 .I prog_fd
942 to a perf event file descriptor,
943 .IR event_fd ,
944 that was created by a previous call to
945 .BR perf_event_open (2):
946 .PP
947 .in +4n
948 .EX
949 ioctl(event_fd, PERF_EVENT_IOC_SET_BPF, prog_fd);
950 .EE
951 .in
952 .\"
953 .\"
954 .SH RETURN VALUE
955 For a successful call, the return value depends on the operation:
956 .TP
957 .B BPF_MAP_CREATE
958 The new file descriptor associated with the eBPF map.
959 .TP
960 .B BPF_PROG_LOAD
961 The new file descriptor associated with the eBPF program.
962 .TP
963 All other commands
964 Zero.
965 .PP
966 On error, \-1 is returned, and
967 .I errno
968 is set to indicate the error.
969 .SH ERRORS
970 .TP
971 .B E2BIG
972 The eBPF program is too large or a map reached the
973 .I max_entries
974 limit (maximum number of elements).
975 .TP
976 .B EACCES
977 For
978 .BR BPF_PROG_LOAD ,
979 even though all program instructions are valid, the program has been
980 rejected because it was deemed unsafe.
981 This may be because it may have
982 accessed a disallowed memory region or an uninitialized stack/register or
983 because the function constraints don't match the actual types or because
984 there was a misaligned memory access.
985 In this case, it is recommended to call
986 .BR bpf ()
987 again with
988 .I log_level = 1
989 and examine
990 .I log_buf
991 for the specific reason provided by the verifier.
992 .TP
993 .B EBADF
994 .I fd
995 is not an open file descriptor.
996 .TP
997 .B EFAULT
998 One of the pointers
999 .RI ( key
1000 or
1001 .I value
1002 or
1003 .I log_buf
1004 or
1005 .IR insns )
1006 is outside the accessible address space.
1007 .TP
1008 .B EINVAL
1009 The value specified in
1010 .I cmd
1011 is not recognized by this kernel.
1012 .TP
1013 .B EINVAL
1014 For
1015 .BR BPF_MAP_CREATE ,
1016 either
1017 .I map_type
1018 or attributes are invalid.
1019 .TP
1020 .B EINVAL
1021 For
1022 .B BPF_MAP_*_ELEM
1023 commands,
1024 some of the fields of
1025 .I "union bpf_attr"
1026 that are not used by this command
1027 are not set to zero.
1028 .TP
1029 .B EINVAL
1030 For
1031 .BR BPF_PROG_LOAD ,
1032 indicates an attempt to load an invalid program.
1033 eBPF programs can be deemed
1034 invalid due to unrecognized instructions, the use of reserved fields, jumps
1035 out of range, infinite loops or calls of unknown functions.
1036 .TP
1037 .B ENOENT
1038 For
1039 .B BPF_MAP_LOOKUP_ELEM
1040 or
1041 .BR BPF_MAP_DELETE_ELEM ,
1042 indicates that the element with the given
1043 .I key
1044 was not found.
1045 .TP
1046 .B ENOMEM
1047 Cannot allocate sufficient memory.
1048 .TP
1049 .B EPERM
1050 The call was made without sufficient privilege
1051 (without the
1052 .B CAP_SYS_ADMIN
1053 capability).
1054 .SH VERSIONS
1055 The
1056 .BR bpf ()
1057 system call first appeared in Linux 3.18.
1058 .SH CONFORMING TO
1059 The
1060 .BR bpf ()
1061 system call is Linux-specific.
1062 .SH NOTES
1063 Prior to Linux 4.4, all
1064 .BR bpf ()
1065 commands require the caller to have the
1066 .B CAP_SYS_ADMIN
1067 capability.
1068 From Linux 4.4 onwards,
1069 .\" commit 1be7f75d1668d6296b80bf35dcf6762393530afc
1070 an unprivileged user may create limited programs of type
1071 .BR BPF_PROG_TYPE_SOCKET_FILTER
1072 and associated maps.
1073 However they may not store kernel pointers within
1074 the maps and are presently limited to the following helper functions:
1075 .\" [Linux 5.6] mtk: The list of available functions is, I think, governed
1076 .\" by the check in net/core/filter.c::bpf_base_func_proto().
1077 .IP * 3
1078 get_random
1079 .PD 0
1080 .IP *
1081 get_smp_processor_id
1082 .IP *
1083 tail_call
1084 .IP *
1085 ktime_get_ns
1086 .PD 1
1087 .PP
1088 Unprivileged access may be blocked by writing the value 1 to the file
1089 .IR /proc/sys/kernel/unprivileged_bpf_disabled .
1090 .PP
1091 eBPF objects (maps and programs) can be shared between processes.
1092 For example, after
1093 .BR fork (2),
1094 the child inherits file descriptors referring to the same eBPF objects.
1095 In addition, file descriptors referring to eBPF objects can be
1096 transferred over UNIX domain sockets.
1097 File descriptors referring to eBPF objects can be duplicated
1098 in the usual way, using
1099 .BR dup (2)
1100 and similar calls.
1101 An eBPF object is deallocated only after all file descriptors
1102 referring to the object have been closed.
1103 .PP
1104 eBPF programs can be written in a restricted C that is compiled (using the
1105 .B clang
1106 compiler) into eBPF bytecode.
1107 Various features are omitted from this restricted C, such as loops,
1108 global variables, variadic functions, floating-point numbers,
1109 and passing structures as function arguments.
1110 Some examples can be found in the
1111 .I samples/bpf/*_kern.c
1112 files in the kernel source tree.
1113 .\" There are also examples for the tc classifier, in the iproute2
1114 .\" project, in examples/bpf
1115 .PP
1116 The kernel contains a just-in-time (JIT) compiler that translates
1117 eBPF bytecode into native machine code for better performance.
1118 In kernels before Linux 4.15,
1119 the JIT compiler is disabled by default,
1120 but its operation can be controlled by writing one of the
1121 following integer strings to the file
1122 .IR /proc/sys/net/core/bpf_jit_enable :
1123 .IP 0 3
1124 Disable JIT compilation (default).
1125 .IP 1
1126 Normal compilation.
1127 .IP 2
1128 Debugging mode.
1129 The generated opcodes are dumped in hexadecimal into the kernel log.
1130 These opcodes can then be disassembled using the program
1131 .I tools/net/bpf_jit_disasm.c
1132 provided in the kernel source tree.
1133 .PP
1134 Since Linux 4.15,
1135 .\" commit 290af86629b25ffd1ed6232c4e9107da031705cb
1136 the kernel may configured with the
1137 .B CONFIG_BPF_JIT_ALWAYS_ON
1138 option.
1139 In this case, the JIT compiler is always enabled, and the
1140 .I bpf_jit_enable
1141 is initialized to 1 and is immutable.
1142 (This kernel configuration option was provided as a mitigation for
1143 one of the Spectre attacks against the BPF interpreter.)
1144 .PP
1145 The JIT compiler for eBPF is currently
1146 .\" Last reviewed in Linux 4.18-rc by grepping for BPF_ALU64 in arch/
1147 .\" and by checking the documentation for bpf_jit_enable in
1148 .\" Documentation/sysctl/net.txt
1149 available for the following architectures:
1150 .IP * 3
1151 x86-64 (since Linux 3.18; cBPF since Linux 3.0);
1152 .\" commit 0a14842f5a3c0e88a1e59fac5c3025db39721f74
1153 .PD 0
1154 .IP *
1155 ARM32 (since Linux 3.18; cBPF since Linux 3.4);
1156 .\" commit ddecdfcea0ae891f782ae853771c867ab51024c2
1157 .IP *
1158 SPARC 32 (since Linux 3.18; cBPF since Linux 3.5);
1159 .\" commit 2809a2087cc44b55e4377d7b9be3f7f5d2569091
1160 .IP *
1161 ARM-64 (since Linux 3.18);
1162 .\" commit e54bcde3d69d40023ae77727213d14f920eb264a
1163 .IP *
1164 s390 (since Linux 4.1; cBPF since Linux 3.7);
1165 .\" commit c10302efe569bfd646b4c22df29577a4595b4580
1166 .IP *
1167 PowerPC 64 (since Linux 4.8; cBPF since Linux 3.1);
1168 .\" commit 0ca87f05ba8bdc6791c14878464efc901ad71e99
1169 .\" commit 156d0e290e969caba25f1851c52417c14d141b24
1170 .IP *
1171 SPARC 64 (since Linux 4.12);
1172 .\" commit 7a12b5031c6b947cc13918237ae652b536243b76
1173 .IP *
1174 x86-32 (since Linux 4.18);
1175 .\" commit 03f5781be2c7b7e728d724ac70ba10799cc710d7
1176 .IP *
1177 MIPS 64 (since Linux 4.18; cBPF since Linux 3.16);
1178 .\" commit c6610de353da5ca6eee5b8960e838a87a90ead0c
1179 .\" commit f381bf6d82f032b7410185b35d000ea370ac706b
1180 .IP *
1181 riscv (since Linux 5.1).
1182 .\" commit 2353ecc6f91fd15b893fa01bf85a1c7a823ee4f2
1183 .PD
1184 .SH EXAMPLES
1185 .EX
1186 /* bpf+sockets example:
1187 * 1. create array map of 256 elements
1188 * 2. load program that counts number of packets received
1189 * r0 = skb\->data[ETH_HLEN + offsetof(struct iphdr, protocol)]
1190 * map[r0]++
1191 * 3. attach prog_fd to raw socket via setsockopt()
1192 * 4. print number of received TCP/UDP packets every second
1193 */
1194 int
1195 main(int argc, char *argv[])
1196 {
1197 int sock, map_fd, prog_fd, key;
1198 long long value = 0, tcp_cnt, udp_cnt;
1199
1200 map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(key),
1201 sizeof(value), 256);
1202 if (map_fd < 0) {
1203 printf("failed to create map \(aq%s\(aq\en", strerror(errno));
1204 /* likely not run as root */
1205 return 1;
1206 }
1207
1208 struct bpf_insn prog[] = {
1209 BPF_MOV64_REG(BPF_REG_6, BPF_REG_1), /* r6 = r1 */
1210 BPF_LD_ABS(BPF_B, ETH_HLEN + offsetof(struct iphdr, protocol)),
1211 /* r0 = ip\->proto */
1212 BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_0, \-4),
1213 /* *(u32 *)(fp \- 4) = r0 */
1214 BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), /* r2 = fp */
1215 BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, \-4), /* r2 = r2 \- 4 */
1216 BPF_LD_MAP_FD(BPF_REG_1, map_fd), /* r1 = map_fd */
1217 BPF_CALL_FUNC(BPF_FUNC_map_lookup_elem),
1218 /* r0 = map_lookup(r1, r2) */
1219 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2),
1220 /* if (r0 == 0) goto pc+2 */
1221 BPF_MOV64_IMM(BPF_REG_1, 1), /* r1 = 1 */
1222 BPF_XADD(BPF_DW, BPF_REG_0, BPF_REG_1, 0, 0),
1223 /* lock *(u64 *) r0 += r1 */
1224 .\" == atomic64_add
1225 BPF_MOV64_IMM(BPF_REG_0, 0), /* r0 = 0 */
1226 BPF_EXIT_INSN(), /* return r0 */
1227 };
1228
1229 prog_fd = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, prog,
1230 sizeof(prog) / sizeof(prog[0]), "GPL");
1231
1232 sock = open_raw_sock("lo");
1233
1234 assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
1235 sizeof(prog_fd)) == 0);
1236
1237 for (;;) {
1238 key = IPPROTO_TCP;
1239 assert(bpf_lookup_elem(map_fd, &key, &tcp_cnt) == 0);
1240 key = IPPROTO_UDP;
1241 assert(bpf_lookup_elem(map_fd, &key, &udp_cnt) == 0);
1242 printf("TCP %lld UDP %lld packets\en", tcp_cnt, udp_cnt);
1243 sleep(1);
1244 }
1245
1246 return 0;
1247 }
1248 .EE
1249 .PP
1250 Some complete working code can be found in the
1251 .I samples/bpf
1252 directory in the kernel source tree.
1253 .SH SEE ALSO
1254 .BR seccomp (2),
1255 .BR bpf\-helpers (7),
1256 .BR socket (7),
1257 .BR tc (8),
1258 .BR tc\-bpf (8)
1259 .PP
1260 Both classic and extended BPF are explained in the kernel source file
1261 .IR Documentation/networking/filter.txt .