2 # SPDX-License-Identifier: GPL-2.0-only
4 # Copyright (C) 2018-2019 Netronome Systems, Inc.
5 # Copyright (C) 2021 Isovalent, Inc.
7 # In case user attempts to run with Python 2.
8 from __future__ import print_function
14 class NoHelperFound(BaseException):
17 class NoSyscallCommandFound(BaseException):
20 class ParsingError(BaseException):
21 def __init__(self, line='<line not provided>', reader=None):
23 BaseException.__init__(self,
24 'Error at file offset %d, parsing line: %s' %
25 (reader.tell(), line))
27 BaseException.__init__(self, 'Error parsing line: %s' % line)
30 class APIElement(object):
32 An object representing the description of an aspect of the eBPF API.
33 @proto: prototype of the API symbol
34 @desc: textual description of the symbol
35 @ret: (optional) description of any associated return value
37 def __init__(self, proto='', desc='', ret=''):
43 class Helper(APIElement):
45 An object representing the description of an eBPF helper function.
46 @proto: function prototype of the helper function
47 @desc: textual description of the helper function
48 @ret: description of the return value of the helper function
50 def proto_break_down(self):
52 Break down helper function protocol into smaller chunks: return type,
53 name, distincts arguments.
55 arg_re = re.compile('((\w+ )*?(\w+|...))( (\**)(\w+))?$')
57 proto_re = re.compile('(.+) (\**)(\w+)\(((([^,]+)(, )?){1,5})\)$')
59 capture = proto_re.match(self.proto)
60 res['ret_type'] = capture.group(1)
61 res['ret_star'] = capture.group(2)
62 res['name'] = capture.group(3)
65 args = capture.group(4).split(', ')
67 capture = arg_re.match(a)
69 'type' : capture.group(1),
70 'star' : capture.group(5),
71 'name' : capture.group(6)
77 class HeaderParser(object):
79 An object used to parse a file in order to extract the documentation of a
80 list of eBPF helper functions. All the helpers that can be retrieved are
81 stored as Helper object, in the self.helpers() array.
82 @filename: name of file to parse, usually include/uapi/linux/bpf.h in the
85 def __init__(self, filename):
86 self.reader = open(filename, 'r')
91 def parse_element(self):
92 proto = self.parse_symbol()
93 desc = self.parse_desc()
94 ret = self.parse_ret()
95 return APIElement(proto=proto, desc=desc, ret=ret)
97 def parse_helper(self):
98 proto = self.parse_proto()
99 desc = self.parse_desc()
100 ret = self.parse_ret()
101 return Helper(proto=proto, desc=desc, ret=ret)
103 def parse_symbol(self):
104 p = re.compile(' \* ?(.+)$')
105 capture = p.match(self.line)
107 raise NoSyscallCommandFound
108 end_re = re.compile(' \* ?NOTES$')
109 end = end_re.match(self.line)
111 raise NoSyscallCommandFound
112 self.line = self.reader.readline()
113 return capture.group(1)
115 def parse_proto(self):
116 # Argument can be of shape:
120 # - Same as above, with "const" and/or "struct" in front of type
121 # - "..." (undefined number of arguments, for bpf_trace_printk())
122 # There is at least one term ("void"), and at most five arguments.
123 p = re.compile(' \* ?((.+) \**\w+\((((const )?(struct )?(\w+|\.\.\.)( \**\w+)?)(, )?){1,5}\))$')
124 capture = p.match(self.line)
127 self.line = self.reader.readline()
128 return capture.group(1)
130 def parse_desc(self):
131 p = re.compile(' \* ?(?:\t| {5,8})Description$')
132 capture = p.match(self.line)
134 # Helper can have empty description and we might be parsing another
135 # attribute: return but do not consume.
137 # Description can be several lines, some of them possibly empty, and it
138 # stops when another subsection title is met.
141 self.line = self.reader.readline()
142 if self.line == ' *\n':
145 p = re.compile(' \* ?(?:\t| {5,8})(?:\t| {8})(.*)')
146 capture = p.match(self.line)
148 desc += capture.group(1) + '\n'
154 p = re.compile(' \* ?(?:\t| {5,8})Return$')
155 capture = p.match(self.line)
157 # Helper can have empty retval and we might be parsing another
158 # attribute: return but do not consume.
160 # Return value description can be several lines, some of them possibly
161 # empty, and it stops when another subsection title is met.
164 self.line = self.reader.readline()
165 if self.line == ' *\n':
168 p = re.compile(' \* ?(?:\t| {5,8})(?:\t| {8})(.*)')
169 capture = p.match(self.line)
171 ret += capture.group(1) + '\n'
176 def seek_to(self, target, help_message):
178 offset = self.reader.read().find(target)
180 raise Exception(help_message)
181 self.reader.seek(offset)
182 self.reader.readline()
183 self.reader.readline()
184 self.line = self.reader.readline()
186 def parse_syscall(self):
187 self.seek_to('* DOC: eBPF Syscall Commands',
188 'Could not find start of eBPF syscall descriptions list')
191 command = self.parse_element()
192 self.commands.append(command)
193 except NoSyscallCommandFound:
196 def parse_helpers(self):
197 self.seek_to('* Start of BPF helper function descriptions:',
198 'Could not find start of eBPF helper descriptions list')
201 helper = self.parse_helper()
202 self.helpers.append(helper)
203 except NoHelperFound:
211 ###############################################################################
213 class Printer(object):
215 A generic class for printers. Printers should be created with an array of
216 Helper objects, and implement a way to print them in the desired fashion.
217 @parser: A HeaderParser with objects to print to standard output
219 def __init__(self, parser):
223 def print_header(self):
226 def print_footer(self):
229 def print_one(self, helper):
234 for elem in self.elements:
239 class PrinterRST(Printer):
241 A generic class for printers that print ReStructured Text. Printers should
242 be created with a HeaderParser object, and implement a way to print API
243 elements in the desired fashion.
244 @parser: A HeaderParser with objects to print to standard output
246 def __init__(self, parser):
249 def print_license(self):
251 .. Copyright (C) All BPF authors and contributors from 2014 to present.
252 .. See git log include/uapi/linux/bpf.h in kernel tree for details.
254 .. %%%LICENSE_START(VERBATIM)
255 .. Permission is granted to make and distribute verbatim copies of this
256 .. manual provided the copyright notice and this permission notice are
257 .. preserved on all copies.
259 .. Permission is granted to copy and distribute modified versions of this
260 .. manual under the conditions for verbatim copying, provided that the
261 .. entire resulting derived work is distributed under the terms of a
262 .. permission notice identical to this one.
264 .. Since the Linux kernel and libraries are constantly changing, this
265 .. manual page may be incorrect or out-of-date. The author(s) assume no
266 .. responsibility for errors or omissions, or for damages resulting from
267 .. the use of the information contained herein. The author(s) may not
268 .. have taken the same level of care in the production of this manual,
269 .. which is licensed free of charge, as they might when working
272 .. Formatted or processed versions of this manual, if unaccompanied by
273 .. the source, must acknowledge the copyright and authors of this work.
276 .. Please do not edit this file. It was generated from the documentation
277 .. located in file include/uapi/linux/bpf.h of the Linux kernel sources
278 .. (helpers description), and from scripts/bpf_doc.py in the same
279 .. repository (header and footer).
283 def print_elem(self, elem):
285 print('\tDescription')
286 # Do not strip all newline characters: formatted code at the end of
287 # a section must be followed by a blank line.
288 for line in re.sub('\n$', '', elem.desc, count=1).split('\n'):
289 print('{}{}'.format('\t\t' if line else '', line))
293 for line in elem.ret.rstrip().split('\n'):
294 print('{}{}'.format('\t\t' if line else '', line))
299 class PrinterHelpersRST(PrinterRST):
301 A printer for dumping collected information about helpers as a ReStructured
302 Text page compatible with the rst2man program, which can be used to
303 generate a manual page for the helpers.
304 @parser: A HeaderParser with Helper objects to print to standard output
306 def __init__(self, parser):
307 self.elements = parser.helpers
309 def print_header(self):
314 -------------------------------------------------------------------------------
315 list of eBPF helper functions
316 -------------------------------------------------------------------------------
323 The extended Berkeley Packet Filter (eBPF) subsystem consists in programs
324 written in a pseudo-assembly language, then attached to one of the several
325 kernel hooks and run in reaction of specific events. This framework differs
326 from the older, "classic" BPF (or "cBPF") in several aspects, one of them being
327 the ability to call special functions (or "helpers") from within a program.
328 These functions are restricted to a white-list of helpers defined in the
331 These helpers are used by eBPF programs to interact with the system, or with
332 the context in which they work. For instance, they can be used to print
333 debugging messages, to get the time since the system was booted, to interact
334 with eBPF maps, or to manipulate network packets. Since there are several eBPF
335 program types, and that they do not run in the same context, each program type
336 can only call a subset of those helpers.
338 Due to eBPF conventions, a helper can not have more than five arguments.
340 Internally, eBPF programs call directly into the compiled helper functions
341 without requiring any foreign-function interface. As a result, calling helpers
342 introduces no overhead, thus offering excellent performance.
344 This document is an attempt to list and document the helpers available to eBPF
345 developers. They are sorted by chronological order (the oldest helpers in the
351 PrinterRST.print_license(self)
354 def print_footer(self):
359 Example usage for most of the eBPF helpers listed in this manual page are
360 available within the Linux kernel sources, at the following locations:
363 * *tools/testing/selftests/bpf/*
368 eBPF programs can have an associated license, passed along with the bytecode
369 instructions to the kernel when the programs are loaded. The format for that
370 string is identical to the one in use for kernel modules (Dual licenses, such
371 as "Dual BSD/GPL", may be used). Some helper functions are only accessible to
372 programs that are compatible with the GNU Privacy License (GPL).
374 In order to use such helpers, the eBPF program must be loaded with the correct
375 license string passed (via **attr**) to the **bpf**\ () system call, and this
376 generally translates into the C source code of the program containing a line
377 similar to the following:
381 char ____license[] __attribute__((section("license"), used)) = "GPL";
386 This manual page is an effort to document the existing eBPF helper functions.
387 But as of this writing, the BPF sub-system is under heavy development. New eBPF
388 program or map types are added, along with new helper functions. Some helpers
389 are occasionally made available for additional program types. So in spite of
390 the efforts of the community, this page might not be up-to-date. If you want to
391 check by yourself what helper functions exist in your kernel, or what types of
392 programs they can support, here are some files among the kernel tree that you
393 may be interested in:
395 * *include/uapi/linux/bpf.h* is the main BPF header. It contains the full list
396 of all helper functions, as well as many other BPF definitions including most
397 of the flags, structs or constants used by the helpers.
398 * *net/core/filter.c* contains the definition of most network-related helper
399 functions, and the list of program types from which they can be used.
400 * *kernel/trace/bpf_trace.c* is the equivalent for most tracing program-related
402 * *kernel/bpf/verifier.c* contains the functions used to check that valid types
403 of eBPF maps are used with a given helper function.
404 * *kernel/bpf/* directory contains other files in which additional helpers are
405 defined (for cgroups, sockmaps, etc.).
406 * The bpftool utility can be used to probe the availability of helper functions
407 on the system (as well as supported program and map types, and a number of
408 other parameters). To do so, run **bpftool feature probe** (see
409 **bpftool-feature**\ (8) for details). Add the **unprivileged** keyword to
410 list features available to unprivileged users.
412 Compatibility between helper functions and program types can generally be found
413 in the files where helper functions are defined. Look for the **struct
414 bpf_func_proto** objects and for functions returning them: these functions
415 contain a list of helpers that a given program type can call. Note that the
416 **default:** label of the **switch ... case** used to filter helpers can call
417 other functions, themselves allowing access to additional helpers. The
418 requirement for GPL license is also in those **struct bpf_func_proto**.
420 Compatibility between helper functions and map types can be found in the
421 **check_map_func_compatibility**\ () function in file *kernel/bpf/verifier.c*.
423 Helper functions that invalidate the checks on **data** and **data_end**
424 pointers for network processing are listed in function
425 **bpf_helper_changes_pkt_data**\ () in file *net/core/filter.c*.
434 **perf_event_open**\ (2),
440 def print_proto(self, helper):
442 Format function protocol with bold and italics markers. This makes RST
443 file less readable, but gives nice results in the manual page.
445 proto = helper.proto_break_down()
447 print('**%s %s%s(' % (proto['ret_type'],
448 proto['ret_star'].replace('*', '\\*'),
453 for a in proto['args']:
454 one_arg = '{}{}'.format(comma, a['type'])
457 one_arg += ' {}**\ '.format(a['star'].replace('*', '\\*'))
460 one_arg += '*{}*\\ **'.format(a['name'])
462 print(one_arg, end='')
466 def print_one(self, helper):
467 self.print_proto(helper)
468 self.print_elem(helper)
471 class PrinterSyscallRST(PrinterRST):
473 A printer for dumping collected information about the syscall API as a
474 ReStructured Text page compatible with the rst2man program, which can be
475 used to generate a manual page for the syscall.
476 @parser: A HeaderParser with APIElement objects to print to standard
479 def __init__(self, parser):
480 self.elements = parser.commands
482 def print_header(self):
487 -------------------------------------------------------------------------------
488 Perform a command on an extended BPF object
489 -------------------------------------------------------------------------------
496 PrinterRST.print_license(self)
499 def print_one(self, command):
500 print('**%s**' % (command.proto))
501 self.print_elem(command)
504 class PrinterHelpers(Printer):
506 A printer for dumping collected information about helpers as C header to
507 be included from BPF program.
508 @parser: A HeaderParser with Helper objects to print to standard output
510 def __init__(self, parser):
511 self.elements = parser.helpers
514 'struct bpf_fib_lookup',
515 'struct bpf_sk_lookup',
516 'struct bpf_perf_event_data',
517 'struct bpf_perf_event_value',
518 'struct bpf_pidns_info',
519 'struct bpf_redir_neigh',
521 'struct bpf_sock_addr',
522 'struct bpf_sock_ops',
523 'struct bpf_sock_tuple',
524 'struct bpf_spin_lock',
526 'struct bpf_tcp_sock',
527 'struct bpf_tunnel_key',
528 'struct bpf_xfrm_state',
529 'struct linux_binprm',
531 'struct sk_reuseport_md',
537 'struct tcp_timewait_sock',
538 'struct tcp_request_sock',
540 'struct task_struct',
566 'struct bpf_fib_lookup',
567 'struct bpf_perf_event_data',
568 'struct bpf_perf_event_value',
569 'struct bpf_pidns_info',
570 'struct bpf_redir_neigh',
571 'struct bpf_sk_lookup',
573 'struct bpf_sock_addr',
574 'struct bpf_sock_ops',
575 'struct bpf_sock_tuple',
576 'struct bpf_spin_lock',
578 'struct bpf_tcp_sock',
579 'struct bpf_tunnel_key',
580 'struct bpf_xfrm_state',
581 'struct linux_binprm',
583 'struct sk_reuseport_md',
589 'struct tcp_timewait_sock',
590 'struct tcp_request_sock',
592 'struct task_struct',
609 'size_t': 'unsigned long',
610 'struct bpf_map': 'void',
611 'struct sk_buff': 'struct __sk_buff',
612 'const struct sk_buff': 'const struct __sk_buff',
613 'struct sk_msg_buff': 'struct sk_msg_md',
614 'struct xdp_buff': 'struct xdp_md',
616 # Helpers overloaded for different context types.
617 overloaded_helpers = [
618 'bpf_get_socket_cookie',
622 def print_header(self):
624 /* This is auto-generated file. See bpf_doc.py for details. */
626 /* Forward declarations of BPF structs */'''
629 for fwd in self.type_fwds:
633 def print_footer(self):
637 def map_type(self, t):
638 if t in self.known_types:
640 if t in self.mapped_types:
641 return self.mapped_types[t]
642 print("Unrecognized type '%s', please add it to known types!" % t,
648 def print_one(self, helper):
649 proto = helper.proto_break_down()
651 if proto['name'] in self.seen_helpers:
653 self.seen_helpers.add(proto['name'])
656 print(" * %s" % proto['name'])
659 # Do not strip all newline characters: formatted code at the end of
660 # a section must be followed by a blank line.
661 for line in re.sub('\n$', '', helper.desc, count=1).split('\n'):
662 print(' *{}{}'.format(' \t' if line else '', line))
667 for line in helper.ret.rstrip().split('\n'):
668 print(' *{}{}'.format(' \t' if line else '', line))
671 print('static %s %s(*%s)(' % (self.map_type(proto['ret_type']),
672 proto['ret_star'], proto['name']), end='')
674 for i, a in enumerate(proto['args']):
677 if proto['name'] in self.overloaded_helpers and i == 0:
680 one_arg = '{}{}'.format(comma, self.map_type(t))
683 one_arg += ' {}'.format(a['star'])
686 one_arg += '{}'.format(n)
688 print(one_arg, end='')
690 print(') = (void *) %d;' % len(self.seen_helpers))
693 ###############################################################################
695 # If script is launched from scripts/ from kernel tree and can access
696 # ../include/uapi/linux/bpf.h, use it as a default name for the file to parse,
697 # otherwise the --filename argument will be required from the command line.
698 script = os.path.abspath(sys.argv[0])
699 linuxRoot = os.path.dirname(os.path.dirname(script))
700 bpfh = os.path.join(linuxRoot, 'include/uapi/linux/bpf.h')
703 'helpers': PrinterHelpersRST,
704 'syscall': PrinterSyscallRST,
707 argParser = argparse.ArgumentParser(description="""
708 Parse eBPF header file and generate documentation for the eBPF API.
709 The RST-formatted output produced can be turned into a manual page with the
712 argParser.add_argument('--header', action='store_true',
713 help='generate C header file')
714 if (os.path.isfile(bpfh)):
715 argParser.add_argument('--filename', help='path to include/uapi/linux/bpf.h',
718 argParser.add_argument('--filename', help='path to include/uapi/linux/bpf.h')
719 argParser.add_argument('target', nargs='?', default='helpers',
720 choices=printers.keys(), help='eBPF API target')
721 args = argParser.parse_args()
724 headerParser = HeaderParser(args.filename)
727 # Print formatted output to standard output.
729 if args.target != 'helpers':
730 raise NotImplementedError('Only helpers header generation is supported')
731 printer = PrinterHelpers(headerParser)
733 printer = printers[args.target](headerParser)