1# bcc Reference Guide 2 3Intended for search (Ctrl-F) and reference. For tutorials, start with [tutorial.md](tutorial.md). 4 5This guide is incomplete. If something feels missing, check the bcc and kernel source. And if you confirm we're missing something, please send a pull request to fix it, and help out everyone. 6 7## Contents 8 9- [BPF C](#bpf-c) 10 - [Events & Arguments](#events--arguments) 11 - [1. kprobes](#1-kprobes) 12 - [2. kretprobes](#2-kretprobes) 13 - [3. Tracepoints](#3-tracepoints) 14 - [4. uprobes](#4-uprobes) 15 - [5. uretprobes](#5-uretprobes) 16 - [6. USDT probes](#6-usdt-probes) 17 - [7. Raw Tracepoints](#7-raw-tracepoints) 18 - [8. system call tracepoints](#8-system-call-tracepoints) 19 - [9. kfuncs](#9-kfuncs) 20 - [10. kretfuncs](#10-kretfuncs) 21 - [11. lsm probes](#11-lsm-probes) 22 - [12. bpf iterators](#12-bpf-iterators) 23 - [Data](#data) 24 - [1. bpf_probe_read_kernel()](#1-bpf_probe_read_kernel) 25 - [2. bpf_probe_read_kernel_str()](#2-bpf_probe_read_kernel_str) 26 - [3. bpf_ktime_get_ns()](#3-bpf_ktime_get_ns) 27 - [4. bpf_get_current_pid_tgid()](#4-bpf_get_current_pid_tgid) 28 - [5. bpf_get_current_uid_gid()](#5-bpf_get_current_uid_gid) 29 - [6. bpf_get_current_comm()](#6-bpf_get_current_comm) 30 - [7. bpf_get_current_task()](#7-bpf_get_current_task) 31 - [8. bpf_log2l()](#8-bpf_log2l) 32 - [9. bpf_get_prandom_u32()](#9-bpf_get_prandom_u32) 33 - [10. bpf_probe_read_user()](#10-bpf_probe_read_user) 34 - [11. bpf_probe_read_user_str()](#11-bpf_probe_read_user_str) 35 - [12. bpf_get_ns_current_pid_tgid()](#12-bpf_get_ns_current_pid_tgid) 36 - [Debugging](#debugging) 37 - [1. bpf_override_return()](#1-bpf_override_return) 38 - [Output](#output) 39 - [1. bpf_trace_printk()](#1-bpf_trace_printk) 40 - [2. BPF_PERF_OUTPUT](#2-bpf_perf_output) 41 - [3. perf_submit()](#3-perf_submit) 42 - [4. perf_submit_skb()](#4-perf_submit_skb) 43 - [5. BPF_RINGBUF_OUTPUT](#5-bpf_ringbuf_output) 44 - [6. ringbuf_output()](#6-ringbuf_output) 45 - [7. ringbuf_reserve()](#7-ringbuf_reserve) 46 - [8. ringbuf_submit()](#8-ringbuf_submit) 47 - [9. ringbuf_discard()](#9-ringbuf_discard) 48 - [Maps](#maps) 49 - [1. BPF_TABLE](#1-bpf_table) 50 - [2. BPF_HASH](#2-bpf_hash) 51 - [3. BPF_ARRAY](#3-bpf_array) 52 - [4. BPF_HISTOGRAM](#4-bpf_histogram) 53 - [5. BPF_STACK_TRACE](#5-bpf_stack_trace) 54 - [6. BPF_PERF_ARRAY](#6-bpf_perf_array) 55 - [7. BPF_PERCPU_HASH](#7-bpf_percpu_hash) 56 - [8. BPF_PERCPU_ARRAY](#8-bpf_percpu_array) 57 - [9. BPF_LPM_TRIE](#9-bpf_lpm_trie) 58 - [10. BPF_PROG_ARRAY](#10-bpf_prog_array) 59 - [11. BPF_DEVMAP](#11-bpf_devmap) 60 - [12. BPF_CPUMAP](#12-bpf_cpumap) 61 - [13. BPF_XSKMAP](#13-bpf_xskmap) 62 - [14. BPF_ARRAY_OF_MAPS](#14-bpf_array_of_maps) 63 - [15. BPF_HASH_OF_MAPS](#15-bpf_hash_of_maps) 64 - [16. BPF_STACK](#16-bpf_stack) 65 - [17. BPF_QUEUE](#17-bpf_queue) 66 - [18. BPF_SOCKHASH](#18-bpf_sockhash) 67 - [19. map.lookup()](#19-maplookup) 68 - [20. map.lookup_or_try_init()](#20-maplookup_or_try_init) 69 - [21. map.delete()](#21-mapdelete) 70 - [22. map.update()](#22-mapupdate) 71 - [23. map.insert()](#23-mapinsert) 72 - [24. map.increment()](#24-mapincrement) 73 - [25. map.get_stackid()](#25-mapget_stackid) 74 - [26. map.perf_read()](#26-mapperf_read) 75 - [27. map.call()](#27-mapcall) 76 - [28. map.redirect_map()](#28-mapredirect_map) 77 - [29. map.push()](#29-mappush) 78 - [30. map.pop()](#30-mappop) 79 - [31. map.peek()](#31-mappeek) 80 - [32. map.sock_hash_update()](#32-mapsock_hash_update) 81 - [33. map.msg_redirect_hash()](#33-mapmsg_redirect_hash) 82 - [34. map.sk_redirect_hash()](#34-mapsk_redirect_hash) 83 - [Licensing](#licensing) 84 - [Rewriter](#rewriter) 85 86- [bcc Python](#bcc-python) 87 - [Initialization](#initialization) 88 - [1. BPF](#1-bpf) 89 - [2. USDT](#2-usdt) 90 - [Events](#events) 91 - [1. attach_kprobe()](#1-attach_kprobe) 92 - [2. attach_kretprobe()](#2-attach_kretprobe) 93 - [3. attach_tracepoint()](#3-attach_tracepoint) 94 - [4. attach_uprobe()](#4-attach_uprobe) 95 - [5. attach_uretprobe()](#5-attach_uretprobe) 96 - [6. USDT.enable_probe()](#6-usdtenable_probe) 97 - [7. attach_raw_tracepoint()](#7-attach_raw_tracepoint) 98 - [8. attach_raw_socket()](#8-attach_raw_socket) 99 - [9. attach_xdp()](#9-attach_xdp) 100 - [10. attach_func()](#10-attach_func) 101 - [11. detach_func()](#11-detach_func) 102 - [12. detach_kprobe()](#12-detach_kprobe) 103 - [13. detach_kretprobe()](#13-detach_kretprobe) 104 - [Debug Output](#debug-output) 105 - [1. trace_print()](#1-trace_print) 106 - [2. trace_fields()](#2-trace_fields) 107 - [Output APIs](#output-apis) 108 - [1. perf_buffer_poll()](#1-perf_buffer_poll) 109 - [2. ring_buffer_poll()](#2-ring_buffer_poll) 110 - [3. ring_buffer_consume()](#3-ring_buffer_consume) 111 - [Map APIs](#map-apis) 112 - [1. get_table()](#1-get_table) 113 - [2. open_perf_buffer()](#2-open_perf_buffer) 114 - [3. items()](#3-items) 115 - [4. values()](#4-values) 116 - [5. clear()](#5-clear) 117 - [6. items_lookup_and_delete_batch()](#6-items_lookup_and_delete_batch) 118 - [7. items_lookup_batch()](#7-items_lookup_batch) 119 - [8. items_delete_batch()](#8-items_delete_batch) 120 - [9. items_update_batch()](#9-items_update_batch) 121 - [10. print_log2_hist()](#10-print_log2_hist) 122 - [11. print_linear_hist()](#11-print_linear_hist) 123 - [12. open_ring_buffer()](#12-open_ring_buffer) 124 - [13. push()](#13-push) 125 - [14. pop()](#14-pop) 126 - [15. peek()](#15-peek) 127 - [Helpers](#helpers) 128 - [1. ksym()](#1-ksym) 129 - [2. ksymname()](#2-ksymname) 130 - [3. sym()](#3-sym) 131 - [4. num_open_kprobes()](#4-num_open_kprobes) 132 - [5. get_syscall_fnname()](#5-get_syscall_fnname) 133 134- [BPF Errors](#bpf-errors) 135 - [1. Invalid mem access](#1-invalid-mem-access) 136 - [2. Cannot call GPL only function from proprietary program](#2-cannot-call-gpl-only-function-from-proprietary-program) 137 138- [Environment Variables](#Environment-Variables) 139 - [1. kernel source directory](#1-kernel-source-directory) 140 - [2. kernel version overriding](#2-kernel-version-overriding) 141 142# BPF C 143 144This section describes the C part of a bcc program. 145 146## Events & Arguments 147 148### 1. kprobes 149 150Syntax: kprobe__*kernel_function_name* 151 152```kprobe__``` is a special prefix that creates a kprobe (dynamic tracing of a kernel function call) for the kernel function name provided as the remainder. You can also use kprobes by declaring a normal C function, then using the Python ```BPF.attach_kprobe()``` (covered later) to associate it with a kernel function. 153 154Arguments are specified on the function declaration: kprobe__*kernel_function_name*(struct pt_regs *ctx [, *argument1* ...]) 155 156For example: 157 158```C 159int kprobe__tcp_v4_connect(struct pt_regs *ctx, struct sock *sk) { 160 [...] 161} 162``` 163 164This instruments the tcp_v4_connect() kernel function using a kprobe, with the following arguments: 165 166- ```struct pt_regs *ctx```: Registers and BPF context. 167- ```struct sock *sk```: First argument to tcp_v4_connect(). 168 169The first argument is always ```struct pt_regs *```, the remainder are the arguments to the function (they don't need to be specified, if you don't intend to use them). 170 171Examples in situ: 172[code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/tcpv4connect.py#L28) ([output](https://github.com/iovisor/bcc/blob/5bd0eb21fd148927b078deb8ac29fff2fb044b66/examples/tracing/tcpv4connect_example.txt#L8)), 173[code](https://github.com/iovisor/bcc/commit/310ab53710cfd46095c1f6b3e44f1dbc8d1a41d8#diff-8cd1822359ffee26e7469f991ce0ef00R26) ([output](https://github.com/iovisor/bcc/blob/3b9679a3bd9b922c736f6061dc65cb56de7e0250/examples/tracing/bitehist_example.txt#L6)) 174<!--- I can't add search links here, since github currently cannot handle partial-word searches needed for "kprobe__" ---> 175 176### 2. kretprobes 177 178Syntax: kretprobe__*kernel_function_name* 179 180```kretprobe__``` is a special prefix that creates a kretprobe (dynamic tracing of a kernel function return) for the kernel function name provided as the remainder. You can also use kretprobes by declaring a normal C function, then using the Python ```BPF.attach_kretprobe()``` (covered later) to associate it with a kernel function. 181 182Return value is available as ```PT_REGS_RC(ctx)```, given a function declaration of: kretprobe__*kernel_function_name*(struct pt_regs *ctx) 183 184For example: 185 186```C 187int kretprobe__tcp_v4_connect(struct pt_regs *ctx) 188{ 189 int ret = PT_REGS_RC(ctx); 190 [...] 191} 192``` 193 194This instruments the return of the tcp_v4_connect() kernel function using a kretprobe, and stores the return value in ```ret```. 195 196Examples in situ: 197[code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/tcpv4connect.py#L38) ([output](https://github.com/iovisor/bcc/blob/5bd0eb21fd148927b078deb8ac29fff2fb044b66/examples/tracing/tcpv4connect_example.txt#L8)) 198 199### 3. Tracepoints 200 201Syntax: TRACEPOINT_PROBE(*category*, *event*) 202 203This is a macro that instruments the tracepoint defined by *category*:*event*. 204 205The tracepoint name is `<category>:<event>`. 206The probe function name is `tracepoint__<category>__<event>`. 207 208Arguments are available in an ```args``` struct, which are the tracepoint arguments. One way to list these is to cat the relevant format file under /sys/kernel/debug/tracing/events/*category*/*event*/format. 209 210The ```args``` struct can be used in place of ``ctx`` in each functions requiring a context as an argument. This includes notably [perf_submit()](#3-perf_submit). 211 212For example: 213 214```C 215TRACEPOINT_PROBE(random, urandom_read) { 216 // args is from /sys/kernel/debug/tracing/events/random/urandom_read/format 217 bpf_trace_printk("%d\\n", args->got_bits); 218 return 0; 219} 220``` 221 222This instruments the tracepoint `random:urandom_read tracepoint`, and prints the tracepoint argument ```got_bits```. 223When using Python API, this probe is automatically attached to the right tracepoint target. 224For C++, this tracepoint probe can be attached by specifying the tracepoint target and function name explicitly: 225`BPF::attach_tracepoint("random:urandom_read", "tracepoint__random__urandom_read")` 226Note the name of the probe function defined above is `tracepoint__random__urandom_read`. 227 228Examples in situ: 229[code](https://github.com/iovisor/bcc/blob/a4159da8c4ea8a05a3c6e402451f530d6e5a8b41/examples/tracing/urandomread.py#L19) ([output](https://github.com/iovisor/bcc/commit/e422f5e50ecefb96579b6391a2ada7f6367b83c4#diff-41e5ecfae4a3b38de5f4e0887ed160e5R10)), 230[search /examples](https://github.com/iovisor/bcc/search?q=TRACEPOINT_PROBE+path%3Aexamples&type=Code), 231[search /tools](https://github.com/iovisor/bcc/search?q=TRACEPOINT_PROBE+path%3Atools&type=Code) 232 233### 4. uprobes 234 235These are instrumented by declaring a normal function in C, then associating it as a uprobe probe in Python via ```BPF.attach_uprobe()``` (covered later). 236 237Arguments can be examined using ```PT_REGS_PARM``` macros. 238 239For example: 240 241```C 242int count(struct pt_regs *ctx) { 243 char buf[64]; 244 bpf_probe_read_user(&buf, sizeof(buf), (void *)PT_REGS_PARM1(ctx)); 245 bpf_trace_printk("%s %d", buf, PT_REGS_PARM2(ctx)); 246 return(0); 247} 248``` 249 250This reads the first argument as a string, and then prints it with the second argument as an integer. 251 252Examples in situ: 253[code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/strlen_count.py#L26) 254 255### 5. uretprobes 256 257These are instrumented by declaring a normal function in C, then associating it as a uretprobe probe in Python via ```BPF.attach_uretprobe()``` (covered later). 258 259Return value is available as ```PT_REGS_RC(ctx)```, given a function declaration of: *function_name*(struct pt_regs *ctx) 260 261For example: 262 263```C 264BPF_HISTOGRAM(dist); 265int count(struct pt_regs *ctx) { 266 dist.increment(PT_REGS_RC(ctx)); 267 return 0; 268} 269``` 270 271This increments the bucket in the ```dist``` histogram that is indexed by the return value. 272 273Examples in situ: 274[code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/strlen_hist.py#L39) ([output](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/strlen_hist.py#L15)), 275[code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/tools/bashreadline.py) ([output](https://github.com/iovisor/bcc/commit/aa87997d21e5c1a6a20e2c96dd25eb92adc8e85d#diff-2fd162f9e594206f789246ce97d62cf0R7)) 276 277### 6. USDT probes 278 279These are User Statically-Defined Tracing (USDT) probes, which may be placed in some applications or libraries to provide a user-level equivalent of tracepoints. The primary BPF method provided for USDT support method is ```enable_probe()```. USDT probes are instrumented by declaring a normal function in C, then associating it as a USDT probe in Python via ```USDT.enable_probe()```. 280 281Arguments can be read via: bpf_usdt_readarg(*index*, ctx, &addr) 282 283For example: 284 285```C 286int do_trace(struct pt_regs *ctx) { 287 uint64_t addr; 288 char path[128]; 289 bpf_usdt_readarg(6, ctx, &addr); 290 bpf_probe_read_user(&path, sizeof(path), (void *)addr); 291 bpf_trace_printk("path:%s\\n", path); 292 return 0; 293}; 294``` 295 296This reads the sixth USDT argument, and then pulls it in as a string to ```path```. 297 298When initializing USDTs via the third argument of ```BPF::init``` in the C API, if any USDT fails to ```init```, entire ```BPF::init``` will fail. If you're OK with some USDTs failing to ```init```, use ```BPF::init_usdt``` before calling ```BPF::init```. 299 300Examples in situ: 301[code](https://github.com/iovisor/bcc/commit/4f88a9401357d7b75e917abd994aa6ea97dda4d3#diff-04a7cad583be5646080970344c48c1f4R24), 302[search /examples](https://github.com/iovisor/bcc/search?q=bpf_usdt_readarg+path%3Aexamples&type=Code), 303[search /tools](https://github.com/iovisor/bcc/search?q=bpf_usdt_readarg+path%3Atools&type=Code) 304 305### 7. Raw Tracepoints 306 307Syntax: RAW_TRACEPOINT_PROBE(*event*) 308 309This is a macro that instruments the raw tracepoint defined by *event*. 310 311The argument is a pointer to struct ```bpf_raw_tracepoint_args```, which is defined in [bpf.h](https://github.com/iovisor/bcc/blob/master/src/cc/compat/linux/virtual_bpf.h). The struct field ```args``` contains all parameters of the raw tracepoint where you can found at linux tree [include/trace/events](https://github.com/torvalds/linux/tree/master/include/trace/events) 312directory. 313 314For example: 315```C 316RAW_TRACEPOINT_PROBE(sched_switch) 317{ 318 // TP_PROTO(bool preempt, struct task_struct *prev, struct task_struct *next) 319 struct task_struct *prev = (struct task_struct *)ctx->args[1]; 320 struct task_struct *next= (struct task_struct *)ctx->args[2]; 321 s32 prev_tgid, next_tgid; 322 323 bpf_probe_read_kernel(&prev_tgid, sizeof(prev->tgid), &prev->tgid); 324 bpf_probe_read_kernel(&next_tgid, sizeof(next->tgid), &next->tgid); 325 bpf_trace_printk("%d -> %d\\n", prev_tgid, next_tgid); 326} 327``` 328 329This instruments the sched:sched_switch tracepoint, and prints the prev and next tgid. 330 331Examples in situ: 332[search /tools](https://github.com/iovisor/bcc/search?q=RAW_TRACEPOINT_PROBE+path%3Atools&type=Code) 333 334### 8. system call tracepoints 335 336Syntax: ```syscall__SYSCALLNAME``` 337 338```syscall__``` is a special prefix that creates a kprobe for the system call name provided as the remainder. You can use it by declaring a normal C function, then using the Python ```BPF.get_syscall_fnname(SYSCALLNAME)``` and ```BPF.attach_kprobe()``` to associate it. 339 340Arguments are specified on the function declaration: ```syscall__SYSCALLNAME(struct pt_regs *ctx, [, argument1 ...])```. 341 342For example: 343```C 344int syscall__execve(struct pt_regs *ctx, 345 const char __user *filename, 346 const char __user *const __user *__argv, 347 const char __user *const __user *__envp) 348{ 349 [...] 350} 351``` 352 353This instruments the execve system call. 354 355The first argument is always ```struct pt_regs *```, the remainder are the arguments to the function (they don't need to be specified, if you don't intend to use them). 356 357Corresponding Python code: 358```Python 359b = BPF(text=bpf_text) 360execve_fnname = b.get_syscall_fnname("execve") 361b.attach_kprobe(event=execve_fnname, fn_name="syscall__execve") 362``` 363 364Examples in situ: 365[code](https://github.com/iovisor/bcc/blob/552658edda09298afdccc8a4b5e17311a2d8a771/tools/execsnoop.py#L101) ([output](https://github.com/iovisor/bcc/blob/552658edda09298afdccc8a4b5e17311a2d8a771/tools/execsnoop_example.txt#L8)) 366 367### 9. kfuncs 368 369Syntax: KFUNC_PROBE(*function*, typeof(arg1) arg1, typeof(arg2) arge ...) 370 371This is a macro that instruments the kernel function via trampoline 372*before* the function is executed. It's defined by *function* name and 373the function arguments defined as *argX*. 374 375For example: 376```C 377KFUNC_PROBE(do_sys_open, int dfd, const char *filename, int flags, int mode) 378{ 379 ... 380``` 381 382This instruments the do_sys_open kernel function and make its arguments 383accessible as standard argument values. 384 385Examples in situ: 386[search /tools](https://github.com/iovisor/bcc/search?q=KFUNC_PROBE+path%3Atools&type=Code) 387 388### 10. kretfuncs 389 390Syntax: KRETFUNC_PROBE(*event*, typeof(arg1) arg1, typeof(arg2) arge ..., int ret) 391 392This is a macro that instruments the kernel function via trampoline 393*after* the function is executed. It's defined by *function* name and 394the function arguments defined as *argX*. 395 396The last argument of the probe is the return value of the instrumented function. 397 398For example: 399```C 400KRETFUNC_PROBE(do_sys_open, int dfd, const char *filename, int flags, int mode, int ret) 401{ 402 ... 403``` 404 405This instruments the do_sys_open kernel function and make its arguments 406accessible as standard argument values together with its return value. 407 408Examples in situ: 409[search /tools](https://github.com/iovisor/bcc/search?q=KRETFUNC_PROBE+path%3Atools&type=Code) 410 411 412### 11. LSM Probes 413 414Syntax: LSM_PROBE(*hook*, typeof(arg1) arg1, typeof(arg2) arg2 ...) 415 416This is a macro that instruments an LSM hook as a BPF program. It can be 417used to audit security events and implement MAC security policies in BPF. 418It is defined by specifying the hook name followed by its arguments. 419 420Hook names can be found in 421[include/linux/security.h](https://github.com/torvalds/linux/blob/v5.15/include/linux/security.h#L260) 422by taking functions like `security_hookname` and taking just the `hookname` part. 423For example, `security_bpf` would simply become `bpf`. 424 425Unlike other BPF program types, the return value specified in an LSM probe 426matters. A return value of 0 allows the hook to succeed, whereas 427any non-zero return value will cause the hook to fail and deny the 428security operation. 429 430The following example instruments a hook that denies all future BPF operations: 431```C 432LSM_PROBE(bpf, int cmd, union bpf_attr *attr, unsigned int size) 433{ 434 return -EPERM; 435} 436``` 437 438This instruments the `security_bpf` hook and causes it to return `-EPERM`. 439Changing `return -EPERM` to `return 0` would cause the BPF program 440to allow the operation instead. 441 442LSM probes require at least a 5.7+ kernel with the following configuation options set: 443- `CONFIG_BPF_LSM=y` 444- `CONFIG_LSM` comma separated string must contain "bpf" (for example, 445 `CONFIG_LSM="lockdown,yama,bpf"`) 446 447Examples in situ: 448[search /tests](https://github.com/iovisor/bcc/search?q=LSM_PROBE+path%3Atests&type=Code) 449 450### 12. BPF ITERATORS 451 452Syntax: BPF_ITER(target) 453 454This is a macro to define a program signature for a bpf iterator program. The argument *target* specifies what to iterate for the program. 455 456Currently, kernel does not have interface to discover what targets are supported. A good place to find what is supported is in [tools/testing/selftests/bpf/prog_test/bpf_iter.c](https://github.com/torvalds/linux/blob/master/tools/testing/selftests/bpf/prog_tests/bpf_iter.c) and some sample bpf iter programs are in [tools/testing/selftests/bpf/progs](https://github.com/torvalds/linux/tree/master/tools/testing/selftests/bpf/progs) with file name prefix *bpf_iter*. 457 458The following example defines a program for target *task*, which traverses all tasks in the kernel. 459```C 460BPF_ITER(task) 461{ 462 struct seq_file *seq = ctx->meta->seq; 463 struct task_struct *task = ctx->task; 464 465 if (task == (void *)0) 466 return 0; 467 468 ... task->pid, task->tgid, task->comm, ... 469 return 0; 470} 471``` 472 473BPF iterators are introduced in 5.8 kernel for task, task_file, bpf_map, netlink_sock and ipv6_route . In 5.9, support is added to tcp/udp sockets and bpf map element (hashmap, arraymap and sk_local_storage_map) traversal. 474 475## Data 476 477### 1. bpf_probe_read_kernel() 478 479Syntax: ```int bpf_probe_read_kernel(void *dst, int size, const void *src)``` 480 481Return: 0 on success 482 483This copies size bytes from kernel address space to the BPF stack, so that BPF can later operate on it. For safety, all kernel memory reads must pass through bpf_probe_read_kernel(). This happens automatically in some cases, such as dereferencing kernel variables, as bcc will rewrite the BPF program to include the necessary bpf_probe_read_kernel(). 484 485Examples in situ: 486[search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel+path%3Aexamples&type=Code), 487[search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel+path%3Atools&type=Code) 488 489### 2. bpf_probe_read_kernel_str() 490 491Syntax: ```int bpf_probe_read_kernel_str(void *dst, int size, const void *src)``` 492 493Return: 494 - \> 0 length of the string including the trailing NULL on success 495 - \< 0 error 496 497This copies a `NULL` terminated string from kernel address space to the BPF stack, so that BPF can later operate on it. In case the string length is smaller than size, the target is not padded with further `NULL` bytes. In case the string length is larger than size, just `size - 1` bytes are copied and the last byte is set to `NULL`. 498 499Examples in situ: 500[search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel_str+path%3Aexamples&type=Code), 501[search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel_str+path%3Atools&type=Code) 502 503### 3. bpf_ktime_get_ns() 504 505Syntax: ```u64 bpf_ktime_get_ns(void)``` 506 507Return: u64 number of nanoseconds. Starts at system boot time but stops during suspend. 508 509Examples in situ: 510[search /examples](https://github.com/iovisor/bcc/search?q=bpf_ktime_get_ns+path%3Aexamples&type=Code), 511[search /tools](https://github.com/iovisor/bcc/search?q=bpf_ktime_get_ns+path%3Atools&type=Code) 512 513### 4. bpf_get_current_pid_tgid() 514 515Syntax: ```u64 bpf_get_current_pid_tgid(void)``` 516 517Return: ```current->tgid << 32 | current->pid``` 518 519Returns the process ID in the lower 32 bits (kernel's view of the PID, which in user space is usually presented as the thread ID), and the thread group ID in the upper 32 bits (what user space often thinks of as the PID). By directly setting this to a u32, we discard the upper 32 bits. 520 521Examples in situ: 522[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_pid_tgid+path%3Aexamples&type=Code), 523[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_pid_tgid+path%3Atools&type=Code) 524 525### 5. bpf_get_current_uid_gid() 526 527Syntax: ```u64 bpf_get_current_uid_gid(void)``` 528 529Return: ```current_gid << 32 | current_uid``` 530 531Returns the user ID and group IDs. 532 533Examples in situ: 534[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_uid_gid+path%3Aexamples&type=Code), 535[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_uid_gid+path%3Atools&type=Code) 536 537### 6. bpf_get_current_comm() 538 539Syntax: ```bpf_get_current_comm(char *buf, int size_of_buf)``` 540 541Return: 0 on success 542 543Populates the first argument address with the current process name. It should be a pointer to a char array of at least size TASK_COMM_LEN, which is defined in linux/sched.h. For example: 544 545```C 546#include <linux/sched.h> 547 548int do_trace(struct pt_regs *ctx) { 549 char comm[TASK_COMM_LEN]; 550 bpf_get_current_comm(&comm, sizeof(comm)); 551[...] 552``` 553 554Examples in situ: 555[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_comm+path%3Aexamples&type=Code), 556[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_comm+path%3Atools&type=Code) 557 558### 7. bpf_get_current_task() 559 560Syntax: ```bpf_get_current_task()``` 561 562Return: current task as a pointer to struct task_struct. 563 564Returns a pointer to the current task's task_struct object. This helper can be used to compute the on-CPU time for a process, identify kernel threads, get the current CPU's run queue, or retrieve many other pieces of information. 565 566With Linux 4.13, due to issues with field randomization, you may need two #define directives before the includes: 567```C 568#define randomized_struct_fields_start struct { 569#define randomized_struct_fields_end }; 570#include <linux/sched.h> 571 572int do_trace(void *ctx) { 573 struct task_struct *t = (struct task_struct *)bpf_get_current_task(); 574[...] 575``` 576 577Examples in situ: 578[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_task+path%3Aexamples&type=Code), 579[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_task+path%3Atools&type=Code) 580 581### 8. bpf_log2l() 582 583Syntax: ```unsigned int bpf_log2l(unsigned long v)``` 584 585Returns the log-2 of the provided value. This is often used to create indexes for histograms, to construct power-of-2 histograms. 586 587Examples in situ: 588[search /examples](https://github.com/iovisor/bcc/search?q=bpf_log2l+path%3Aexamples&type=Code), 589[search /tools](https://github.com/iovisor/bcc/search?q=bpf_log2l+path%3Atools&type=Code) 590 591### 9. bpf_get_prandom_u32() 592 593Syntax: ```u32 bpf_get_prandom_u32()``` 594 595Returns a pseudo-random u32. 596 597Example in situ: 598[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_prandom_u32+path%3Aexamples&type=Code), 599[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_prandom_u32+path%3Atools&type=Code) 600 601### 10. bpf_probe_read_user() 602 603Syntax: ```int bpf_probe_read_user(void *dst, int size, const void *src)``` 604 605Return: 0 on success 606 607This attempts to safely read size bytes from user address space to the BPF stack, so that BPF can later operate on it. For safety, all user address space memory reads must pass through bpf_probe_read_user(). 608 609Examples in situ: 610[search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user+path%3Aexamples&type=Code), 611[search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user+path%3Atools&type=Code) 612 613### 11. bpf_probe_read_user_str() 614 615Syntax: ```int bpf_probe_read_user_str(void *dst, int size, const void *src)``` 616 617Return: 618 - \> 0 length of the string including the trailing NULL on success 619 - \< 0 error 620 621This copies a `NULL` terminated string from user address space to the BPF stack, so that BPF can later operate on it. In case the string length is smaller than size, the target is not padded with further `NULL` bytes. In case the string length is larger than size, just `size - 1` bytes are copied and the last byte is set to `NULL`. 622 623Examples in situ: 624[search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user_str+path%3Aexamples&type=Code), 625[search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user_str+path%3Atools&type=Code) 626 627 628### 12. bpf_get_ns_current_pid_tgid() 629 630Syntax: ```u32 bpf_get_ns_current_pid_tgid(u64 dev, u64 ino, struct bpf_pidns_info* nsdata, u32 size)``` 631 632Values for *pid* and *tgid* as seen from the current *namespace* will be returned in *nsdata*. 633 634Return 0 on success, or one of the following in case of failure: 635 636- **-EINVAL** if dev and inum supplied don't match dev_t and inode number with nsfs of current task, or if dev conversion to dev_t lost high bits. 637 638- **-ENOENT** if pidns does not exists for the current task. 639 640Examples in situ: 641[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_ns_current_pid_tgid+path%3Aexamples&type=Code), 642[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_ns_current_pid_tgid+path%3Atools&type=Code) 643 644 645## Debugging 646 647### 1. bpf_override_return() 648 649Syntax: ```int bpf_override_return(struct pt_regs *, unsigned long rc)``` 650 651Return: 0 on success 652 653When used in a program attached to a function entry kprobe, causes the 654execution of the function to be skipped, immediately returning `rc` instead. 655This is used for targeted error injection. 656 657bpf_override_return will only work when the kprobed function is whitelisted to 658allow error injections. Whitelisting entails tagging a function with 659`ALLOW_ERROR_INJECTION()` in the kernel source tree; see `io_ctl_init` for 660an example. If the kprobed function is not whitelisted, the bpf program will 661fail to attach with ` ioctl(PERF_EVENT_IOC_SET_BPF): Invalid argument` 662 663 664```C 665int kprobe__io_ctl_init(void *ctx) { 666 bpf_override_return(ctx, -ENOMEM); 667 return 0; 668} 669``` 670 671## Output 672 673### 1. bpf_trace_printk() 674 675Syntax: ```int bpf_trace_printk(const char *fmt, ...)``` 676 677Return: 0 on success 678 679A simple kernel facility for printf() to the common trace_pipe (/sys/kernel/debug/tracing/trace_pipe). This is ok for some quick examples, but has limitations: 3 args max, 1 %s only, and trace_pipe is globally shared, so concurrent programs will have clashing output. A better interface is via BPF_PERF_OUTPUT(). Note that calling this helper is made simpler than the original kernel version, which has ```fmt_size``` as the second parameter. 680 681Examples in situ: 682[search /examples](https://github.com/iovisor/bcc/search?q=bpf_trace_printk+path%3Aexamples&type=Code), 683[search /tools](https://github.com/iovisor/bcc/search?q=bpf_trace_printk+path%3Atools&type=Code) 684 685### 2. BPF_PERF_OUTPUT 686 687Syntax: ```BPF_PERF_OUTPUT(name)``` 688 689Creates a BPF table for pushing out custom event data to user space via a perf ring buffer. This is the preferred method for pushing per-event data to user space. 690 691For example: 692 693```C 694struct data_t { 695 u32 pid; 696 u64 ts; 697 char comm[TASK_COMM_LEN]; 698}; 699BPF_PERF_OUTPUT(events); 700 701int hello(struct pt_regs *ctx) { 702 struct data_t data = {}; 703 704 data.pid = bpf_get_current_pid_tgid(); 705 data.ts = bpf_ktime_get_ns(); 706 bpf_get_current_comm(&data.comm, sizeof(data.comm)); 707 708 events.perf_submit(ctx, &data, sizeof(data)); 709 710 return 0; 711} 712``` 713 714The output table is named ```events```, and data is pushed to it via ```events.perf_submit()```. 715 716Examples in situ: 717[search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERF_OUTPUT+path%3Aexamples&type=Code), 718[search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERF_OUTPUT+path%3Atools&type=Code) 719 720### 3. perf_submit() 721 722Syntax: ```int perf_submit((void *)ctx, (void *)data, u32 data_size)``` 723 724Return: 0 on success 725 726A method of a BPF_PERF_OUTPUT table, for submitting custom event data to user space. See the BPF_PERF_OUTPUT entry. (This ultimately calls bpf_perf_event_output().) 727 728The ```ctx``` parameter is provided in [kprobes](#1-kprobes) or [kretprobes](#2-kretprobes). For ```SCHED_CLS``` or ```SOCKET_FILTER``` programs, the ```struct __sk_buff *skb``` must be used instead. 729 730Examples in situ: 731[search /examples](https://github.com/iovisor/bcc/search?q=perf_submit+path%3Aexamples&type=Code), 732[search /tools](https://github.com/iovisor/bcc/search?q=perf_submit+path%3Atools&type=Code) 733 734### 4. perf_submit_skb() 735 736Syntax: ```int perf_submit_skb((void *)ctx, u32 packet_size, (void *)data, u32 data_size)``` 737 738Return: 0 on success 739 740A method of a BPF_PERF_OUTPUT table available in networking program types, for submitting custom event data to user space, along with the first ```packet_size``` bytes of the packet buffer. See the BPF_PERF_OUTPUT entry. (This ultimately calls bpf_perf_event_output().) 741 742Examples in situ: 743[search /examples](https://github.com/iovisor/bcc/search?q=perf_submit_skb+path%3Aexamples&type=Code), 744[search /tools](https://github.com/iovisor/bcc/search?q=perf_submit_skb+path%3Atools&type=Code) 745 746### 5. BPF_RINGBUF_OUTPUT 747 748Syntax: ```BPF_RINGBUF_OUTPUT(name, page_cnt)``` 749 750Creates a BPF table for pushing out custom event data to user space via a ringbuf ring buffer. 751```BPF_RINGBUF_OUTPUT``` has several advantages over ```BPF_PERF_OUTPUT```, summarized as follows: 752 753- Buffer is shared across all CPUs, meaning no per-CPU allocation 754- Supports two APIs for BPF programs 755 - ```map.ringbuf_output()``` works like ```map.perf_submit()``` (covered in [ringbuf_output](#6-ringbuf_output)) 756 - ```map.ringbuf_reserve()```/```map.ringbuf_submit()```/```map.ringbuf_discard()``` 757 split the process of reserving buffer space and submitting events into two steps 758 (covered in [ringbuf_reserve](#7-ringbuf_reserve), [ringbuf_submit](#8-ringbuf_submit), [ringbuf_discard](#9-ringbuf_discard)) 759- BPF APIs do not require access to a CPU ctx argument 760- Superior performance and latency in userspace thanks to a shared ring buffer manager 761- Supports two ways of consuming data in userspace 762 763Starting in Linux 5.8, this should be the preferred method for pushing per-event data to user space. 764 765Example of both APIs: 766 767```C 768struct data_t { 769 u32 pid; 770 u64 ts; 771 char comm[TASK_COMM_LEN]; 772}; 773 774// Creates a ringbuf called events with 8 pages of space, shared across all CPUs 775BPF_RINGBUF_OUTPUT(events, 8); 776 777int first_api_example(struct pt_regs *ctx) { 778 struct data_t data = {}; 779 780 data.pid = bpf_get_current_pid_tgid(); 781 data.ts = bpf_ktime_get_ns(); 782 bpf_get_current_comm(&data.comm, sizeof(data.comm)); 783 784 events.ringbuf_output(&data, sizeof(data), 0 /* flags */); 785 786 return 0; 787} 788 789int second_api_example(struct pt_regs *ctx) { 790 struct data_t *data = events.ringbuf_reserve(sizeof(struct data_t)); 791 if (!data) { // Failed to reserve space 792 return 1; 793 } 794 795 data->pid = bpf_get_current_pid_tgid(); 796 data->ts = bpf_ktime_get_ns(); 797 bpf_get_current_comm(&data->comm, sizeof(data->comm)); 798 799 events.ringbuf_submit(data, 0 /* flags */); 800 801 return 0; 802} 803``` 804 805The output table is named ```events```. Data is allocated via ```events.ringbuf_reserve()``` and pushed to it via ```events.ringbuf_submit()```. 806 807Examples in situ: <!-- TODO --> 808[search /examples](https://github.com/iovisor/bcc/search?q=BPF_RINGBUF_OUTPUT+path%3Aexamples&type=Code), 809 810### 6. ringbuf_output() 811 812Syntax: ```int ringbuf_output((void *)data, u64 data_size, u64 flags)``` 813 814Return: 0 on success 815 816Flags: 817 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability 818 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally 819 820A method of the BPF_RINGBUF_OUTPUT table, for submitting custom event data to user space. This method works like ```perf_submit()```, 821although it does not require a ctx argument. 822 823Examples in situ: <!-- TODO --> 824[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_output+path%3Aexamples&type=Code), 825 826### 7. ringbuf_reserve() 827 828Syntax: ```void* ringbuf_reserve(u64 data_size)``` 829 830Return: Pointer to data struct on success, NULL on failure 831 832A method of the BPF_RINGBUF_OUTPUT table, for reserving space in the ring buffer and simultaenously 833allocating a data struct for output. Must be used with one of ```ringbuf_submit``` or ```ringbuf_discard```. 834 835Examples in situ: <!-- TODO --> 836[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_reserve+path%3Aexamples&type=Code), 837 838### 8. ringbuf_submit() 839 840Syntax: ```void ringbuf_submit((void *)data, u64 flags)``` 841 842Return: Nothing, always succeeds 843 844Flags: 845 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability 846 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally 847 848A method of the BPF_RINGBUF_OUTPUT table, for submitting custom event data to user space. Must be preceded by a call to 849```ringbuf_reserve()``` to reserve space for the data. 850 851Examples in situ: <!-- TODO --> 852[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_submit+path%3Aexamples&type=Code), 853 854### 9. ringbuf_discard() 855 856Syntax: ```void ringbuf_discard((void *)data, u64 flags)``` 857 858Return: Nothing, always succeeds 859 860Flags: 861 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability 862 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally 863 864A method of the BPF_RINGBUF_OUTPUT table, for discarding custom event data; userspace 865ignores the data associated with the discarded event. Must be preceded by a call to 866```ringbuf_reserve()``` to reserve space for the data. 867 868Examples in situ: <!-- TODO --> 869[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_submit+path%3Aexamples&type=Code), 870 871## Maps 872 873Maps are BPF data stores, and are the basis for higher level object types including tables, hashes, and histograms. 874 875### 1. BPF_TABLE 876 877Syntax: ```BPF_TABLE(_table_type, _key_type, _leaf_type, _name, _max_entries)``` 878 879Creates a map named ```_name```. Most of the time this will be used via higher-level macros, like BPF_HASH, BPF_ARRAY, BPF_HISTOGRAM, etc. 880 881`BPF_F_TABLE` is a variant that takes a flag in the last parameter. `BPF_TABLE(...)` is actually a wrapper to `BPF_F_TABLE(..., 0 /* flag */)`. 882 883Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment(). 884 885Examples in situ: 886[search /examples](https://github.com/iovisor/bcc/search?q=BPF_TABLE+path%3Aexamples&type=Code), 887[search /tools](https://github.com/iovisor/bcc/search?q=BPF_TABLE+path%3Atools&type=Code) 888 889#### Pinned Maps 890 891Syntax: ```BPF_TABLE_PINNED(_table_type, _key_type, _leaf_type, _name, _max_entries, "/sys/fs/bpf/xyz")``` 892 893Create a new map if it doesn't exist and pin it to the bpffs as a FILE, otherwise use the map that was pinned to the bpffs. The type information is not enforced and the actual map type depends on the map that got pinned to the location. 894 895For example: 896 897```C 898BPF_TABLE_PINNED("hash", u64, u64, ids, 1024, "/sys/fs/bpf/ids"); 899``` 900 901### 2. BPF_HASH 902 903Syntax: ```BPF_HASH(name [, key_type [, leaf_type [, size]]])``` 904 905Creates a hash map (associative array) named ```name```, with optional parameters. 906 907Defaults: ```BPF_HASH(name, key_type=u64, leaf_type=u64, size=10240)``` 908 909For example: 910 911```C 912BPF_HASH(start, struct request *); 913``` 914 915This creates a hash named ```start``` where the key is a ```struct request *```, and the value defaults to u64. This hash is used by the disksnoop.py example for saving timestamps for each I/O request, where the key is the pointer to struct request, and the value is the timestamp. 916 917This is a wrapper macro for `BPF_TABLE("hash", ...)`. 918 919Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment(). 920 921Examples in situ: 922[search /examples](https://github.com/iovisor/bcc/search?q=BPF_HASH+path%3Aexamples&type=Code), 923[search /tools](https://github.com/iovisor/bcc/search?q=BPF_HASH+path%3Atools&type=Code) 924 925### 3. BPF_ARRAY 926 927Syntax: ```BPF_ARRAY(name [, leaf_type [, size]])``` 928 929Creates an int-indexed array which is optimized for fastest lookup and update, named ```name```, with optional parameters. 930 931Defaults: ```BPF_ARRAY(name, leaf_type=u64, size=10240)``` 932 933For example: 934 935```C 936BPF_ARRAY(counts, u64, 32); 937``` 938 939This creates an array named ```counts``` where with 32 buckets and 64-bit integer values. This array is used by the funccount.py example for saving call count of each function. 940 941This is a wrapper macro for `BPF_TABLE("array", ...)`. 942 943Methods (covered later): map.lookup(), map.update(), map.increment(). Note that all array elements are pre-allocated with zero values and can not be deleted. 944 945Examples in situ: 946[search /examples](https://github.com/iovisor/bcc/search?q=BPF_ARRAY+path%3Aexamples&type=Code), 947[search /tools](https://github.com/iovisor/bcc/search?q=BPF_ARRAY+path%3Atools&type=Code) 948 949### 4. BPF_HISTOGRAM 950 951Syntax: ```BPF_HISTOGRAM(name [, key_type [, size ]])``` 952 953Creates a histogram map named ```name```, with optional parameters. 954 955Defaults: ```BPF_HISTOGRAM(name, key_type=int, size=64)``` 956 957For example: 958 959```C 960BPF_HISTOGRAM(dist); 961``` 962 963This creates a histogram named ```dist```, which defaults to 64 buckets indexed by keys of type int. 964 965This is a wrapper macro for `BPF_TABLE("histgram", ...)`. 966 967Methods (covered later): map.increment(). 968 969Examples in situ: 970[search /examples](https://github.com/iovisor/bcc/search?q=BPF_HISTOGRAM+path%3Aexamples&type=Code), 971[search /tools](https://github.com/iovisor/bcc/search?q=BPF_HISTOGRAM+path%3Atools&type=Code) 972 973### 5. BPF_STACK_TRACE 974 975Syntax: ```BPF_STACK_TRACE(name, max_entries)``` 976 977Creates stack trace map named ```name```, with a maximum entry count provided. These maps are used to store stack traces. 978 979For example: 980 981```C 982BPF_STACK_TRACE(stack_traces, 1024); 983``` 984 985This creates stack trace map named ```stack_traces```, with a maximum number of stack trace entries of 1024. 986 987This is a wrapper macro for `BPF_TABLE("stacktrace", ...)`. 988 989Methods (covered later): map.get_stackid(). 990 991Examples in situ: 992[search /examples](https://github.com/iovisor/bcc/search?q=BPF_STACK_TRACE+path%3Aexamples&type=Code), 993[search /tools](https://github.com/iovisor/bcc/search?q=BPF_STACK_TRACE+path%3Atools&type=Code) 994 995### 6. BPF_PERF_ARRAY 996 997Syntax: ```BPF_PERF_ARRAY(name, max_entries)``` 998 999Creates perf array named ```name```, with a maximum entry count provided, which must be equal to the number of system cpus. These maps are used to fetch hardware performance counters. 1000 1001For example: 1002 1003```C 1004text=""" 1005BPF_PERF_ARRAY(cpu_cycles, NUM_CPUS); 1006""" 1007b = bcc.BPF(text=text, cflags=["-DNUM_CPUS=%d" % multiprocessing.cpu_count()]) 1008b["cpu_cycles"].open_perf_event(b["cpu_cycles"].HW_CPU_CYCLES) 1009``` 1010 1011This creates a perf array named ```cpu_cycles```, with number of entries equal to the number of cpus/cores. The array is configured so that later calling map.perf_read() will return a hardware-calculated counter of the number of cycles elapsed from some point in the past. Only one type of hardware counter may be configured per table at a time. 1012 1013Methods (covered later): map.perf_read(). 1014 1015Examples in situ: 1016[search /tests](https://github.com/iovisor/bcc/search?q=BPF_PERF_ARRAY+path%3Atests&type=Code) 1017 1018### 7. BPF_PERCPU_HASH 1019 1020Syntax: ```BPF_PERCPU_HASH(name [, key_type [, leaf_type [, size]]])``` 1021 1022Creates NUM_CPU int-indexed hash maps (associative arrays) named ```name```, with optional parameters. Each CPU will have a separate copy of this array. The copies are not kept synchronized in any way. 1023 1024Note that due to limits defined in the kernel (in linux/mm/percpu.c), the ```leaf_type``` cannot have a size of more than 32KB. 1025In other words, ```BPF_PERCPU_HASH``` elements cannot be larger than 32KB in size. 1026 1027 1028Defaults: ```BPF_PERCPU_HASH(name, key_type=u64, leaf_type=u64, size=10240)``` 1029 1030For example: 1031 1032```C 1033BPF_PERCPU_HASH(start, struct request *); 1034``` 1035 1036This creates NUM_CPU hashes named ```start``` where the key is a ```struct request *```, and the value defaults to u64. 1037 1038This is a wrapper macro for `BPF_TABLE("percpu_hash", ...)`. 1039 1040Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment(). 1041 1042Examples in situ: 1043[search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_HASH+path%3Aexamples&type=Code), 1044[search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_HASH+path%3Atools&type=Code) 1045 1046 1047### 8. BPF_PERCPU_ARRAY 1048 1049Syntax: ```BPF_PERCPU_ARRAY(name [, leaf_type [, size]])``` 1050 1051Creates NUM_CPU int-indexed arrays which are optimized for fastest lookup and update, named ```name```, with optional parameters. Each CPU will have a separate copy of this array. The copies are not kept synchronized in any way. 1052 1053Note that due to limits defined in the kernel (in linux/mm/percpu.c), the ```leaf_type``` cannot have a size of more than 32KB. 1054In other words, ```BPF_PERCPU_ARRAY``` elements cannot be larger than 32KB in size. 1055 1056 1057Defaults: ```BPF_PERCPU_ARRAY(name, leaf_type=u64, size=10240)``` 1058 1059For example: 1060 1061```C 1062BPF_PERCPU_ARRAY(counts, u64, 32); 1063``` 1064 1065This creates NUM_CPU arrays named ```counts``` where with 32 buckets and 64-bit integer values. 1066 1067This is a wrapper macro for `BPF_TABLE("percpu_array", ...)`. 1068 1069Methods (covered later): map.lookup(), map.update(), map.increment(). Note that all array elements are pre-allocated with zero values and can not be deleted. 1070 1071Examples in situ: 1072[search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_ARRAY+path%3Aexamples&type=Code), 1073[search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_ARRAY+path%3Atools&type=Code) 1074 1075### 9. BPF_LPM_TRIE 1076 1077Syntax: `BPF_LPM_TRIE(name [, key_type [, leaf_type [, size]]])` 1078 1079Creates a longest prefix match trie map named `name`, with optional parameters. 1080 1081Defaults: `BPF_LPM_TRIE(name, key_type=u64, leaf_type=u64, size=10240)` 1082 1083For example: 1084 1085```c 1086BPF_LPM_TRIE(trie, struct key_v6); 1087``` 1088 1089This creates an LPM trie map named `trie` where the key is a `struct key_v6`, and the value defaults to u64. 1090 1091This is a wrapper macro to `BPF_F_TABLE("lpm_trie", ..., BPF_F_NO_PREALLOC)`. 1092 1093Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment(). 1094 1095Examples in situ: 1096[search /examples](https://github.com/iovisor/bcc/search?q=BPF_LPM_TRIE+path%3Aexamples&type=Code), 1097[search /tools](https://github.com/iovisor/bcc/search?q=BPF_LPM_TRIE+path%3Atools&type=Code) 1098 1099### 10. BPF_PROG_ARRAY 1100 1101Syntax: ```BPF_PROG_ARRAY(name, size)``` 1102 1103This creates a program array named ```name``` with ```size``` entries. Each entry of the array is either a file descriptor to a bpf program or ```NULL```. The array acts as a jump table so that bpf programs can "tail-call" other bpf programs. 1104 1105This is a wrapper macro for `BPF_TABLE("prog", ...)`. 1106 1107Methods (covered later): map.call(). 1108 1109Examples in situ: 1110[search /examples](https://github.com/iovisor/bcc/search?q=BPF_PROG_ARRAY+path%3Aexamples&type=Code), 1111[search /tests](https://github.com/iovisor/bcc/search?q=BPF_PROG_ARRAY+path%3Atests&type=Code), 1112[assign fd](https://github.com/iovisor/bcc/blob/master/examples/networking/tunnel_monitor/monitor.py#L24-L26) 1113 1114### 11. BPF_DEVMAP 1115 1116Syntax: ```BPF_DEVMAP(name, size)``` 1117 1118This creates a device map named ```name``` with ```size``` entries. Each entry of the map is an `ifindex` to a network interface. This map is only used in XDP. 1119 1120For example: 1121```C 1122BPF_DEVMAP(devmap, 10); 1123``` 1124 1125Methods (covered later): map.redirect_map(). 1126 1127Examples in situ: 1128[search /examples](https://github.com/iovisor/bcc/search?q=BPF_DEVMAP+path%3Aexamples&type=Code), 1129 1130### 12. BPF_CPUMAP 1131 1132Syntax: ```BPF_CPUMAP(name, size)``` 1133 1134This creates a cpu map named ```name``` with ```size``` entries. The index of the map represents the CPU id and each entry is the size of the ring buffer allocated for the CPU. This map is only used in XDP. 1135 1136For example: 1137```C 1138BPF_CPUMAP(cpumap, 16); 1139``` 1140 1141Methods (covered later): map.redirect_map(). 1142 1143Examples in situ: 1144[search /examples](https://github.com/iovisor/bcc/search?q=BPF_CPUMAP+path%3Aexamples&type=Code), 1145 1146### 13. BPF_XSKMAP 1147 1148Syntax: ```BPF_XSKMAP(name, size)``` 1149 1150This creates a xsk map named ```name``` with ```size``` entries. Each entry represents one NIC's queue id. This map is only used in XDP to redirect packet to an AF_XDP socket. If the AF_XDP socket is binded to a queue which is different than the current packet's queue id, the packet will be dropped. For kernel v5.3 and latter, `lookup` method is available and can be used to check whether and AF_XDP socket is available for the current packet's queue id. More details at [AF_XDP](https://www.kernel.org/doc/html/latest/networking/af_xdp.html). 1151 1152For example: 1153```C 1154BPF_XSKMAP(xsks_map, 8); 1155``` 1156 1157Methods (covered later): map.redirect_map(). map.lookup() 1158 1159Examples in situ: 1160[search /examples](https://github.com/iovisor/bcc/search?q=BPF_XSKMAP+path%3Aexamples&type=Code), 1161 1162### 14. BPF_ARRAY_OF_MAPS 1163 1164Syntax: ```BPF_ARRAY_OF_MAPS(name, inner_map_name, size)``` 1165 1166This creates an array map with a map-in-map type (BPF_MAP_TYPE_HASH_OF_MAPS) map named ```name``` with ```size``` entries. The inner map meta data is provided by map ```inner_map_name``` and can be most of array or hash maps except ```BPF_MAP_TYPE_PROG_ARRAY```, ```BPF_MAP_TYPE_CGROUP_STORAGE``` and ```BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE```. 1167 1168For example: 1169```C 1170BPF_TABLE("hash", int, int, ex1, 1024); 1171BPF_TABLE("hash", int, int, ex2, 1024); 1172BPF_ARRAY_OF_MAPS(maps_array, "ex1", 10); 1173``` 1174 1175### 15. BPF_HASH_OF_MAPS 1176 1177Syntax: ```BPF_HASH_OF_MAPS(name, key_type, inner_map_name, size)``` 1178 1179This creates a hash map with a map-in-map type (BPF_MAP_TYPE_HASH_OF_MAPS) map named ```name``` with ```size``` entries. The inner map meta data is provided by map ```inner_map_name``` and can be most of array or hash maps except ```BPF_MAP_TYPE_PROG_ARRAY```, ```BPF_MAP_TYPE_CGROUP_STORAGE``` and ```BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE```. 1180 1181For example: 1182```C 1183BPF_ARRAY(ex1, int, 1024); 1184BPF_ARRAY(ex2, int, 1024); 1185BPF_HASH_OF_MAPS(maps_hash, struct custom_key, "ex1", 10); 1186``` 1187 1188### 16. BPF_STACK 1189 1190Syntax: ```BPF_STACK(name, leaf_type, max_entries[, flags])``` 1191 1192Creates a stack named ```name``` with value type ```leaf_type``` and max entries ```max_entries```. 1193Stack and Queue maps are only available from Linux 4.20+. 1194 1195For example: 1196 1197```C 1198BPF_STACK(stack, struct event, 10240); 1199``` 1200 1201This creates a stack named ```stack``` where the value type is ```struct event```, that holds up to 10240 entries. 1202 1203Methods (covered later): map.push(), map.pop(), map.peek(). 1204 1205Examples in situ: 1206[search /tests](https://github.com/iovisor/bcc/search?q=BPF_STACK+path%3Atests&type=Code), 1207 1208### 17. BPF_QUEUE 1209 1210Syntax: ```BPF_QUEUE(name, leaf_type, max_entries[, flags])``` 1211 1212Creates a queue named ```name``` with value type ```leaf_type``` and max entries ```max_entries```. 1213Stack and Queue maps are only available from Linux 4.20+. 1214 1215For example: 1216 1217```C 1218BPF_QUEUE(queue, struct event, 10240); 1219``` 1220 1221This creates a queue named ```queue``` where the value type is ```struct event```, that holds up to 10240 entries. 1222 1223Methods (covered later): map.push(), map.pop(), map.peek(). 1224 1225Examples in situ: 1226[search /tests](https://github.com/iovisor/bcc/search?q=BPF_QUEUE+path%3Atests&type=Code), 1227 1228### 18. BPF_SOCKHASH 1229 1230Syntax: ```BPF_SOCKHASH(name[, key_type [, max_entries)``` 1231 1232Creates a hash named ```name```, with optional parameters. sockhash is only available from Linux 4.18+. 1233 1234Default: ```BPF_SOCKHASH(name, key_type=u32, max_entries=10240)``` 1235 1236For example: 1237 1238```C 1239struct sock_key { 1240 u32 remote_ip4; 1241 u32 local_ip4; 1242 u32 remote_port; 1243 u32 local_port; 1244}; 1245BPF_HASH(skh, struct sock_key, 65535); 1246``` 1247 1248This creates a hash named ```skh``` where the key is a ```struct sock_key```. 1249 1250A sockhash is a BPF map type that holds references to sock structs. Then with a new sk/msg redirect bpf helper BPF programs can use the map to redirect skbs/msgs between sockets (```map.sk_redirect_hash()/map.msg_redirect_hash()```). 1251 1252The difference between ```BPF_SOCKHASH``` and ```BPF_SOCKMAP``` is that ```BPF_SOCKMAP``` is implemented based on an array, and enforces keys to be four bytes. While ```BPF_SOCKHASH``` is implemented based on hash table, and the type of key can be specified freely. 1253 1254Methods (covered later): map.sock_hash_update(), map.msg_redirect_hash(), map.sk_redirect_hash(). 1255 1256[search /tests](https://github.com/iovisor/bcc/search?q=BPF_SOCKHASH+path%3Atests&type=Code) 1257 1258### 19. map.lookup() 1259 1260Syntax: ```*val map.lookup(&key)``` 1261 1262Lookup the key in the map, and return a pointer to its value if it exists, else NULL. We pass the key in as an address to a pointer. 1263 1264Examples in situ: 1265[search /examples](https://github.com/iovisor/bcc/search?q=lookup+path%3Aexamples&type=Code), 1266[search /tools](https://github.com/iovisor/bcc/search?q=lookup+path%3Atools&type=Code) 1267 1268### 20. map.lookup_or_try_init() 1269 1270Syntax: ```*val map.lookup_or_try_init(&key, &zero)``` 1271 1272Lookup the key in the map, and return a pointer to its value if it exists, else initialize the key's value to the second argument. This is often used to initialize values to zero. If the key cannot be inserted (e.g. the map is full) then NULL is returned. 1273 1274Examples in situ: 1275[search /examples](https://github.com/iovisor/bcc/search?q=lookup_or_try_init+path%3Aexamples&type=Code), 1276[search /tools](https://github.com/iovisor/bcc/search?q=lookup_or_try_init+path%3Atools&type=Code) 1277 1278Note: The old map.lookup_or_init() may cause return from the function, so lookup_or_try_init() is recommended as it 1279does not have this side effect. 1280 1281### 21. map.delete() 1282 1283Syntax: ```map.delete(&key)``` 1284 1285Delete the key from the hash. 1286 1287Examples in situ: 1288[search /examples](https://github.com/iovisor/bcc/search?q=delete+path%3Aexamples&type=Code), 1289[search /tools](https://github.com/iovisor/bcc/search?q=delete+path%3Atools&type=Code) 1290 1291### 22. map.update() 1292 1293Syntax: ```map.update(&key, &val)``` 1294 1295Associate the value in the second argument to the key, overwriting any previous value. 1296 1297Examples in situ: 1298[search /examples](https://github.com/iovisor/bcc/search?q=update+path%3Aexamples&type=Code), 1299[search /tools](https://github.com/iovisor/bcc/search?q=update+path%3Atools&type=Code) 1300 1301### 23. map.insert() 1302 1303Syntax: ```map.insert(&key, &val)``` 1304 1305Associate the value in the second argument to the key, only if there was no previous value. 1306 1307Examples in situ: 1308[search /examples](https://github.com/iovisor/bcc/search?q=insert+path%3Aexamples&type=Code), 1309[search /tools](https://github.com/iovisor/bcc/search?q=insert+path%3Atools&type=Code) 1310 1311### 24. map.increment() 1312 1313Syntax: ```map.increment(key[, increment_amount])``` 1314 1315Increments the key's value by `increment_amount`, which defaults to 1. Used for histograms. 1316 1317```map.increment()``` are not atomic. In the concurrency case. If you want more accurate results, use ```map.atomic_increment()``` instead of ```map.increment()```. The overhead of ```map.increment()``` and ```map.atomic_increment()``` is similar. 1318 1319Note. When using ```map.atomic_increment()``` to operate on a BPF map of type ```BPF_MAP_TYPE_HASH```, ```map.atomic_increment()``` does not guarantee the atomicity of the operation when the specified key does not exist. 1320 1321Examples in situ: 1322[search /examples](https://github.com/iovisor/bcc/search?q=increment+path%3Aexamples&type=Code), 1323[search /tools](https://github.com/iovisor/bcc/search?q=increment+path%3Atools&type=Code) 1324 1325### 25. map.get_stackid() 1326 1327Syntax: ```int map.get_stackid(void *ctx, u64 flags)``` 1328 1329This walks the stack found via the struct pt_regs in ```ctx```, saves it in the stack trace map, and returns a unique ID for the stack trace. 1330 1331Examples in situ: 1332[search /examples](https://github.com/iovisor/bcc/search?q=get_stackid+path%3Aexamples&type=Code), 1333[search /tools](https://github.com/iovisor/bcc/search?q=get_stackid+path%3Atools&type=Code) 1334 1335### 26. map.perf_read() 1336 1337Syntax: ```u64 map.perf_read(u32 cpu)``` 1338 1339This returns the hardware performance counter as configured in [5. BPF_PERF_ARRAY](#5-bpf_perf_array) 1340 1341Examples in situ: 1342[search /tests](https://github.com/iovisor/bcc/search?q=perf_read+path%3Atests&type=Code) 1343 1344### 27. map.call() 1345 1346Syntax: ```void map.call(void *ctx, int index)``` 1347 1348This invokes ```bpf_tail_call()``` to tail-call the bpf program which the ```index``` entry in [BPF_PROG_ARRAY](#10-bpf_prog_array) points to. A tail-call is different from the normal call. It reuses the current stack frame after jumping to another bpf program and never goes back. If the ```index``` entry is empty, it won't jump anywhere and the program execution continues as normal. 1349 1350For example: 1351 1352```C 1353BPF_PROG_ARRAY(prog_array, 10); 1354 1355int tail_call(void *ctx) { 1356 bpf_trace_printk("Tail-call\n"); 1357 return 0; 1358} 1359 1360int do_tail_call(void *ctx) { 1361 bpf_trace_printk("Original program\n"); 1362 prog_array.call(ctx, 2); 1363 return 0; 1364} 1365``` 1366 1367```Python 1368b = BPF(src_file="example.c") 1369tail_fn = b.load_func("tail_call", BPF.KPROBE) 1370prog_array = b.get_table("prog_array") 1371prog_array[c_int(2)] = c_int(tail_fn.fd) 1372b.attach_kprobe(event="some_kprobe_event", fn_name="do_tail_call") 1373``` 1374 1375This assigns ```tail_call()``` to ```prog_array[2]```. In the end of ```do_tail_call()```, ```prog_array.call(ctx, 2)``` tail-calls ```tail_call()``` and executes it. 1376 1377**NOTE:** To prevent infinite loop, the maximum number of tail-calls is 32 ([```MAX_TAIL_CALL_CNT```](https://github.com/torvalds/linux/search?l=C&q=MAX_TAIL_CALL_CNT+path%3Ainclude%2Flinux&type=Code)). 1378 1379Examples in situ: 1380[search /examples](https://github.com/iovisor/bcc/search?l=C&q=call+path%3Aexamples&type=Code), 1381[search /tests](https://github.com/iovisor/bcc/search?l=C&q=call+path%3Atests&type=Code) 1382 1383### 28. map.redirect_map() 1384 1385Syntax: ```int map.redirect_map(int index, int flags)``` 1386 1387This redirects the incoming packets based on the ```index``` entry. If the map is [BPF_DEVMAP](#11-bpf_devmap), the packet will be sent to the transmit queue of the network interface that the entry points to. If the map is [BPF_CPUMAP](#12-bpf_cpumap), the packet will be sent to the ring buffer of the ```index``` CPU and be processed by the CPU later. If the map is [BPF_XSKMAP](#13-bpf_xskmap), the packet will be sent to the AF_XDP socket attached to the queue. 1388 1389If the packet is redirected successfully, the function will return XDP_REDIRECT. Otherwise, it will return XDP_ABORTED to discard the packet. 1390 1391For example: 1392```C 1393BPF_DEVMAP(devmap, 1); 1394 1395int redirect_example(struct xdp_md *ctx) { 1396 return devmap.redirect_map(0, 0); 1397} 1398int xdp_dummy(struct xdp_md *ctx) { 1399 return XDP_PASS; 1400} 1401``` 1402 1403```Python 1404ip = pyroute2.IPRoute() 1405idx = ip.link_lookup(ifname="eth1")[0] 1406 1407b = bcc.BPF(src_file="example.c") 1408 1409devmap = b.get_table("devmap") 1410devmap[c_uint32(0)] = c_int(idx) 1411 1412in_fn = b.load_func("redirect_example", BPF.XDP) 1413out_fn = b.load_func("xdp_dummy", BPF.XDP) 1414b.attach_xdp("eth0", in_fn, 0) 1415b.attach_xdp("eth1", out_fn, 0) 1416``` 1417 1418Examples in situ: 1419[search /examples](https://github.com/iovisor/bcc/search?l=C&q=redirect_map+path%3Aexamples&type=Code), 1420 1421### 29. map.push() 1422 1423Syntax: ```int map.push(&val, int flags)``` 1424 1425Push an element onto a Stack or Queue table. 1426Passing BPF_EXIST as a flag causes the Queue or Stack to discard the oldest element if it is full. 1427Returns 0 on success, negative error on failure. 1428 1429Examples in situ: 1430[search /tests](https://github.com/iovisor/bcc/search?q=push+path%3Atests&type=Code), 1431 1432### 30. map.pop() 1433 1434Syntax: ```int map.pop(&val)``` 1435 1436Pop an element from a Stack or Queue table. ```*val``` is populated with the result. 1437Unlike peeking, popping removes the element. 1438Returns 0 on success, negative error on failure. 1439 1440Examples in situ: 1441[search /tests](https://github.com/iovisor/bcc/search?q=pop+path%3Atests&type=Code), 1442 1443### 31. map.peek() 1444 1445Syntax: ```int map.peek(&val)``` 1446 1447Peek an element at the head of a Stack or Queue table. ```*val``` is populated with the result. 1448Unlike popping, peeking does not remove the element. 1449Returns 0 on success, negative error on failure. 1450 1451Examples in situ: 1452[search /tests](https://github.com/iovisor/bcc/search?q=peek+path%3Atests&type=Code), 1453 1454### 32. map.sock_hash_update() 1455 1456Syntax: ```int map.sock_hash_update(struct bpf_sock_ops *skops, &key, int flags)``` 1457 1458Add an entry to, or update a sockhash map referencing sockets. The skops is used as a new value for the entry associated to key. flags is one of: 1459 1460``` 1461BPF_NOEXIST: The entry for key must not exist in the map. 1462BPF_EXIST: The entry for key must already exist in the map. 1463BPF_ANY: No condition on the existence of the entry for key. 1464``` 1465 1466If the map has eBPF programs (parser and verdict), those will be inherited by the socket being added. If the socket is already attached to eBPF programs, this results in an error. 1467 1468Return 0 on success, or a negative error in case of failure. 1469 1470Examples in situ: 1471[search /tests](https://github.com/iovisor/bcc/search?q=sock_hash_update+path%3Atests&type=Code), 1472 1473### 33. map.msg_redirect_hash() 1474 1475Syntax: ```int map.msg_redirect_hash(struct sk_msg_buff *msg, void *key, u64 flags)``` 1476 1477This helper is used in programs implementing policies at the socket level. If the message msg is allowed to pass (i.e. if the verdict eBPF program returns SK_PASS), redirect it to the socket referenced by map (of type BPF_MAP_TYPE_SOCKHASH) using hash key. Both ingress and egress interfaces can be used for redirection. The BPF_F_INGRESS value in flags is used to make the distinction (ingress path is selected if the flag is present, egress path otherwise). This is the only flag supported for now. 1478 1479Return SK_PASS on success, or SK_DROP on error. 1480 1481Examples in situ: 1482[search /tests](https://github.com/iovisor/bcc/search?q=msg_redirect_hash+path%3Atests&type=Code), 1483 1484### 34. map.sk_redirect_hash() 1485 1486Syntax: ```int map.sk_redirect_hash(struct sk_buff *skb, void *key, u64 flags)``` 1487 1488This helper is used in programs implementing policies at the skb socket level. If the sk_buff skb is allowed to pass (i.e. if the verdict eBPF program returns SK_PASS), redirect it to the socket referenced by map (of type BPF_MAP_TYPE_SOCKHASH) using hash key. Both ingress and egress interfaces can be used for redirection. The BPF_F_INGRESS value in flags is used to make the distinction (ingress path is selected if the flag is present, egress otherwise). This is the only flag supported for now. 1489 1490Return SK_PASS on success, or SK_DROP on error. 1491 1492Examples in situ: 1493[search /tests](https://github.com/iovisor/bcc/search?q=sk_redirect_hash+path%3Atests&type=Code), 1494 1495## Licensing 1496 1497Depending on which [BPF helpers](kernel-versions.md#helpers) are used, a GPL-compatible license is required. 1498 1499The special BCC macro `BPF_LICENSE` specifies the license of the BPF program. You can set the license as a comment in your source code, but the kernel has a special interface to specify it programmatically. If you need to use GPL-only helpers, it is recommended to specify the macro in your C code so that the kernel can understand it: 1500 1501```C 1502// SPDX-License-Identifier: GPL-2.0+ 1503#define BPF_LICENSE GPL 1504``` 1505 1506Otherwise, the kernel may reject loading your program (see the [error description](#2-cannot-call-gpl-only-function-from-proprietary-program) below). Note that it supports multiple words and quotes are not necessary: 1507 1508```C 1509// SPDX-License-Identifier: GPL-2.0+ OR BSD-2-Clause 1510#define BPF_LICENSE Dual BSD/GPL 1511``` 1512 1513Check the [BPF helpers reference](kernel-versions.md#helpers) to see which helpers are GPL-only and what the kernel understands as GPL-compatible. 1514 1515**If the macro is not specified, BCC will automatically define the license of the program as GPL.** 1516 1517## Rewriter 1518 1519One of jobs for rewriter is to turn implicit memory accesses to explicit ones using kernel helpers. Recent kernel introduced a config option ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE which will be set for architectures who user address space and kernel address are disjoint. x86 and arm has this config option set while s390 does not. If ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE is not set, the bpf old helper `bpf_probe_read()` will not be available. Some existing users may have implicit memory accesses to access user memory, so using `bpf_probe_read_kernel()` will cause their application to fail. Therefore, for non-s390, the rewriter will use `bpf_probe_read()` for these implicit memory accesses. For s390, `bpf_probe_read_kernel()` is used as default and users should use `bpf_probe_read_user()` explicitly when accessing user memories. 1520 1521# bcc Python 1522 1523## Initialization 1524 1525Constructors. 1526 1527### 1. BPF 1528 1529Syntax: ```BPF({text=BPF_program | src_file=filename} [, usdt_contexts=[USDT_object, ...]] [, cflags=[arg1, ...]] [, debug=int])``` 1530 1531Creates a BPF object. This is the main object for defining a BPF program, and interacting with its output. 1532 1533Exactly one of `text` or `src_file` must be supplied (not both). 1534 1535The `cflags` specifies additional arguments to be passed to the compiler, for example `-DMACRO_NAME=value` or `-I/include/path`. The arguments are passed as an array, with each element being an additional argument. Note that strings are not split on whitespace, so each argument must be a different element of the array, e.g. `["-include", "header.h"]`. 1536 1537The `debug` flags control debug output, and can be or'ed together: 1538- `DEBUG_LLVM_IR = 0x1` compiled LLVM IR 1539- `DEBUG_BPF = 0x2` loaded BPF bytecode and register state on branches 1540- `DEBUG_PREPROCESSOR = 0x4` pre-processor result 1541- `DEBUG_SOURCE = 0x8` ASM instructions embedded with source 1542- `DEBUG_BPF_REGISTER_STATE = 0x10` register state on all instructions in addition to DEBUG_BPF 1543- `DEBUG_BTF = 0x20` print the messages from the `libbpf` library. 1544 1545Examples: 1546 1547```Python 1548# define entire BPF program in one line: 1549BPF(text='int do_trace(void *ctx) { bpf_trace_printk("hit!\\n"); return 0; }'); 1550 1551# define program as a variable: 1552prog = """ 1553int hello(void *ctx) { 1554 bpf_trace_printk("Hello, World!\\n"); 1555 return 0; 1556} 1557""" 1558b = BPF(text=prog) 1559 1560# source a file: 1561b = BPF(src_file = "vfsreadlat.c") 1562 1563# include a USDT object: 1564u = USDT(pid=int(pid)) 1565[...] 1566b = BPF(text=bpf_text, usdt_contexts=[u]) 1567 1568# add include paths: 1569u = BPF(text=prog, cflags=["-I/path/to/include"]) 1570``` 1571 1572Examples in situ: 1573[search /examples](https://github.com/iovisor/bcc/search?q=BPF+path%3Aexamples+language%3Apython&type=Code), 1574[search /tools](https://github.com/iovisor/bcc/search?q=BPF+path%3Atools+language%3Apython&type=Code) 1575 1576### 2. USDT 1577 1578Syntax: ```USDT({pid=pid | path=path})``` 1579 1580Creates an object to instrument User Statically-Defined Tracing (USDT) probes. Its primary method is ```enable_probe()```. 1581 1582Arguments: 1583 1584- pid: attach to this process ID. 1585- path: instrument USDT probes from this binary path. 1586 1587Examples: 1588 1589```Python 1590# include a USDT object: 1591u = USDT(pid=int(pid)) 1592[...] 1593b = BPF(text=bpf_text, usdt_contexts=[u]) 1594``` 1595 1596Examples in situ: 1597[search /examples](https://github.com/iovisor/bcc/search?q=USDT+path%3Aexamples+language%3Apython&type=Code), 1598[search /tools](https://github.com/iovisor/bcc/search?q=USDT+path%3Atools+language%3Apython&type=Code) 1599 1600## Events 1601 1602### 1. attach_kprobe() 1603 1604Syntax: ```BPF.attach_kprobe(event="event", fn_name="name")``` 1605 1606Instruments the kernel function ```event()``` using kernel dynamic tracing of the function entry, and attaches our C defined function ```name()``` to be called when the kernel function is called. 1607 1608For example: 1609 1610```Python 1611b.attach_kprobe(event="sys_clone", fn_name="do_trace") 1612``` 1613 1614This will instrument the kernel ```sys_clone()``` function, which will then run our BPF defined ```do_trace()``` function each time it is called. 1615 1616You can call attach_kprobe() more than once, and attach your BPF function to multiple kernel functions. 1617You can also call attach_kprobe() more than once to attach multiple BPF functions to the same kernel function. 1618 1619See the previous kprobes section for how to instrument arguments from BPF. 1620 1621Examples in situ: 1622[search /examples](https://github.com/iovisor/bcc/search?q=attach_kprobe+path%3Aexamples+language%3Apython&type=Code), 1623[search /tools](https://github.com/iovisor/bcc/search?q=attach_kprobe+path%3Atools+language%3Apython&type=Code) 1624 1625### 2. attach_kretprobe() 1626 1627Syntax: ```BPF.attach_kretprobe(event="event", fn_name="name" [, maxactive=int])``` 1628 1629Instruments the return of the kernel function ```event()``` using kernel dynamic tracing of the function return, and attaches our C defined function ```name()``` to be called when the kernel function returns. 1630 1631For example: 1632 1633```Python 1634b.attach_kretprobe(event="vfs_read", fn_name="do_return") 1635``` 1636 1637This will instrument the kernel ```vfs_read()``` function, which will then run our BPF defined ```do_return()``` function each time it is called. 1638 1639You can call attach_kretprobe() more than once, and attach your BPF function to multiple kernel function returns. 1640You can also call attach_kretprobe() more than once to attach multiple BPF functions to the same kernel function return. 1641 1642When a kretprobe is installed on a kernel function, there is a limit on how many parallel calls it can catch. You can change that limit with ```maxactive```. See the kprobes documentation for its default value. 1643 1644See the previous kretprobes section for how to instrument the return value from BPF. 1645 1646Examples in situ: 1647[search /examples](https://github.com/iovisor/bcc/search?q=attach_kretprobe+path%3Aexamples+language%3Apython&type=Code), 1648[search /tools](https://github.com/iovisor/bcc/search?q=attach_kretprobe+path%3Atools+language%3Apython&type=Code) 1649 1650### 3. attach_tracepoint() 1651 1652Syntax: ```BPF.attach_tracepoint(tp="tracepoint", fn_name="name")``` 1653 1654Instruments the kernel tracepoint described by ```tracepoint```, and when hit, runs the BPF function ```name()```. 1655 1656This is an explicit way to instrument tracepoints. The ```TRACEPOINT_PROBE``` syntax, covered in the earlier tracepoints section, is an alternate method with the advantage of auto-declaring an ```args``` struct containing the tracepoint arguments. With ```attach_tracepoint()```, the tracepoint arguments need to be declared in the BPF program. 1657 1658For example: 1659 1660```Python 1661# define BPF program 1662bpf_text = """ 1663#include <uapi/linux/ptrace.h> 1664 1665struct urandom_read_args { 1666 // from /sys/kernel/debug/tracing/events/random/urandom_read/format 1667 u64 __unused__; 1668 u32 got_bits; 1669 u32 pool_left; 1670 u32 input_left; 1671}; 1672 1673int printarg(struct urandom_read_args *args) { 1674 bpf_trace_printk("%d\\n", args->got_bits); 1675 return 0; 1676}; 1677""" 1678 1679# load BPF program 1680b = BPF(text=bpf_text) 1681b.attach_tracepoint("random:urandom_read", "printarg") 1682``` 1683 1684Notice how the first argument to ```printarg()``` is now our defined struct. 1685 1686Examples in situ: 1687[code](https://github.com/iovisor/bcc/blob/a4159da8c4ea8a05a3c6e402451f530d6e5a8b41/examples/tracing/urandomread-explicit.py#L41), 1688[search /examples](https://github.com/iovisor/bcc/search?q=attach_tracepoint+path%3Aexamples+language%3Apython&type=Code), 1689[search /tools](https://github.com/iovisor/bcc/search?q=attach_tracepoint+path%3Atools+language%3Apython&type=Code) 1690 1691### 4. attach_uprobe() 1692 1693Syntax: ```BPF.attach_uprobe(name="location", sym="symbol", fn_name="name" [, sym_off=int])```, ```BPF.attach_uprobe(name="location", sym_re="regex", fn_name="name")```, ```BPF.attach_uprobe(name="location", addr=int, fn_name="name")``` 1694 1695 1696Instruments the user-level function ```symbol()``` from either the library or binary named by ```location``` using user-level dynamic tracing of the function entry, and attach our C defined function ```name()``` to be called whenever the user-level function is called. If ```sym_off``` is given, the function is attached to the offset within the symbol. 1697 1698The real address ```addr``` may be supplied in place of ```sym```, in which case ```sym``` must be set to its default value. If the file is a non-PIE executable, ```addr``` must be a virtual address, otherwise it must be an offset relative to the file load address. 1699 1700Instead of a symbol name, a regular expression can be provided in ```sym_re```. The uprobe will then attach to symbols that match the provided regular expression. 1701 1702Libraries can be given in the name argument without the lib prefix, or with the full path (/usr/lib/...). Binaries can be given only with the full path (/bin/sh). 1703 1704For example: 1705 1706```Python 1707b.attach_uprobe(name="c", sym="strlen", fn_name="count") 1708``` 1709 1710This will instrument ```strlen()``` function from libc, and call our BPF function ```count()``` when it is called. Note how the "lib" in "libc" is not necessary to specify. 1711 1712Other examples: 1713 1714```Python 1715b.attach_uprobe(name="c", sym="getaddrinfo", fn_name="do_entry") 1716b.attach_uprobe(name="/usr/bin/python", sym="main", fn_name="do_main") 1717``` 1718 1719You can call attach_uprobe() more than once, and attach your BPF function to multiple user-level functions. 1720 1721See the previous uprobes section for how to instrument arguments from BPF. 1722 1723Examples in situ: 1724[search /examples](https://github.com/iovisor/bcc/search?q=attach_uprobe+path%3Aexamples+language%3Apython&type=Code), 1725[search /tools](https://github.com/iovisor/bcc/search?q=attach_uprobe+path%3Atools+language%3Apython&type=Code) 1726 1727### 5. attach_uretprobe() 1728 1729Syntax: ```BPF.attach_uretprobe(name="location", sym="symbol", fn_name="name")``` 1730 1731Instruments the return of the user-level function ```symbol()``` from either the library or binary named by ```location``` using user-level dynamic tracing of the function return, and attach our C defined function ```name()``` to be called whenever the user-level function returns. 1732 1733For example: 1734 1735```Python 1736b.attach_uretprobe(name="c", sym="strlen", fn_name="count") 1737``` 1738 1739This will instrument ```strlen()``` function from libc, and call our BPF function ```count()``` when it returns. 1740 1741Other examples: 1742 1743```Python 1744b.attach_uretprobe(name="c", sym="getaddrinfo", fn_name="do_return") 1745b.attach_uretprobe(name="/usr/bin/python", sym="main", fn_name="do_main") 1746``` 1747 1748You can call attach_uretprobe() more than once, and attach your BPF function to multiple user-level functions. 1749 1750See the previous uretprobes section for how to instrument the return value from BPF. 1751 1752Examples in situ: 1753[search /examples](https://github.com/iovisor/bcc/search?q=attach_uretprobe+path%3Aexamples+language%3Apython&type=Code), 1754[search /tools](https://github.com/iovisor/bcc/search?q=attach_uretprobe+path%3Atools+language%3Apython&type=Code) 1755 1756### 6. USDT.enable_probe() 1757 1758Syntax: ```USDT.enable_probe(probe=probe, fn_name=name)``` 1759 1760Attaches a BPF C function ```name``` to the USDT probe ```probe```. 1761 1762Example: 1763 1764```Python 1765# enable USDT probe from given PID 1766u = USDT(pid=int(pid)) 1767u.enable_probe(probe="http__server__request", fn_name="do_trace") 1768``` 1769 1770To check if your binary has USDT probes, and what they are, you can run ```readelf -n binary``` and check the stap debug section. 1771 1772Examples in situ: 1773[search /examples](https://github.com/iovisor/bcc/search?q=enable_probe+path%3Aexamples+language%3Apython&type=Code), 1774[search /tools](https://github.com/iovisor/bcc/search?q=enable_probe+path%3Atools+language%3Apython&type=Code) 1775 1776### 7. attach_raw_tracepoint() 1777 1778Syntax: ```BPF.attach_raw_tracepoint(tp="tracepoint", fn_name="name")``` 1779 1780Instruments the kernel raw tracepoint described by ```tracepoint``` (```event``` only, no ```category```), and when hit, runs the BPF function ```name()```. 1781 1782This is an explicit way to instrument tracepoints. The ```RAW_TRACEPOINT_PROBE``` syntax, covered in the earlier raw tracepoints section, is an alternate method. 1783 1784For example: 1785 1786```Python 1787b.attach_raw_tracepoint("sched_switch", "do_trace") 1788``` 1789 1790Examples in situ: 1791[search /tools](https://github.com/iovisor/bcc/search?q=attach_raw_tracepoint+path%3Atools+language%3Apython&type=Code) 1792 1793### 8. attach_raw_socket() 1794 1795Syntax: ```BPF.attach_raw_socket(fn, dev)``` 1796 1797Attaches a BPF function to the specified network interface. 1798 1799The ```fn``` must be the type of ```BPF.function``` and the bpf_prog type needs to be ```BPF_PROG_TYPE_SOCKET_FILTER``` (```fn=BPF.load_func(func_name, BPF.SOCKET_FILTER)```) 1800 1801```fn.sock``` is a non-blocking raw socket that was created and bound to ```dev```. 1802 1803All network packets processed by ```dev``` are copied to the ```recv-q``` of ```fn.sock``` after being processed by bpf_prog. Try to recv packet form ```fn.sock``` with rev/recvfrom/recvmsg. Note that if the ```recv-q``` is not read in time after the ```recv-q``` is full, the copied packets will be discarded. 1804 1805We can use this feature to capture network packets just like ```tcpdump```. 1806 1807We can use ```ss --bpf --packet -p``` to observe ```fn.sock```. 1808 1809Example: 1810 1811```Python 1812BPF.attach_raw_socket(bpf_func, ifname) 1813``` 1814 1815Examples in situ: 1816[search /examples](https://github.com/iovisor/bcc/search?q=attach_raw_socket+path%3Aexamples+language%3Apython&type=Code) 1817### 9. attach_xdp() 1818Syntax: ```BPF.attach_xdp(dev="device", fn=b.load_func("fn_name",BPF.XDP), flags)``` 1819 1820Instruments the network driver described by ```dev``` , and then receives the packet, run the BPF function ```fn_name()``` with flags. 1821 1822Here is a list of optional flags. 1823 1824```Python 1825# from xdp_flags uapi/linux/if_link.h 1826XDP_FLAGS_UPDATE_IF_NOEXIST = (1 << 0) 1827XDP_FLAGS_SKB_MODE = (1 << 1) 1828XDP_FLAGS_DRV_MODE = (1 << 2) 1829XDP_FLAGS_HW_MODE = (1 << 3) 1830XDP_FLAGS_REPLACE = (1 << 4) 1831``` 1832 1833You can use flags like this ```BPF.attach_xdp(dev="device", fn=b.load_func("fn_name",BPF.XDP), flags=BPF.XDP_FLAGS_UPDATE_IF_NOEXIST)``` 1834 1835The default value of flags is 0. This means if there is no xdp program with `device`, the fn will run with that device. If there is an xdp program running with device, the old program will be replaced with new fn program. 1836 1837Currently, bcc does not support XDP_FLAGS_REPLACE flag. The following are the descriptions of other flags. 1838 1839#### 1. XDP_FLAGS_UPDATE_IF_NOEXIST 1840If an XDP program is already attached to the specified driver, attaching the XDP program again will fail. 1841 1842#### 2. XDP_FLAGS_SKB_MODE 1843Driver doesn’t have support for XDP, but the kernel fakes it. 1844XDP program works, but there’s no real performance benefit because packets are handed to kernel stack anyways which then emulates XDP – this is usually supported with generic network drivers used in home computers, laptops, and virtualized HW. 1845 1846#### 3. XDP_FLAGS_DRV_MODE 1847A driver has XDP support and can hand then to XDP without kernel stack interaction – Few drivers can support it and those are usually for enterprise HW. 1848 1849#### 4. XDP_FLAGS_HW_MODE 1850XDP can be loaded and executed directly on the NIC – just a handful of NICs can do that. 1851 1852 1853For example: 1854 1855```Python 1856b.attach_xdp(dev="ens1", fn=b.load_func("do_xdp", BPF.XDP)) 1857``` 1858 1859This will instrument the network device ```ens1``` , which will then run our BPF defined ```do_xdp()``` function each time it receives packets. 1860 1861Don't forget to call ```b.remove_xdp("ens1")``` at the end! 1862 1863Examples in situ: 1864[search /examples](https://github.com/iovisor/bcc/search?q=attach_xdp+path%3Aexamples+language%3Apython&type=Code), 1865[search /tools](https://github.com/iovisor/bcc/search?q=attach_xdp+path%3Atools+language%3Apython&type=Code) 1866 1867### 10. attach_func() 1868 1869Syntax: ```BPF.attach_func(fn, attachable_fd, attach_type [, flags])``` 1870 1871Attaches a BPF function of the specified type to a particular ```attachable_fd```. if the ```attach_type``` is ```BPF_FLOW_DISSECTOR```, the function is expected to attach to current net namespace and ```attachable_fd``` must be 0. 1872 1873For example: 1874 1875```Python 1876b.attach_func(fn, cgroup_fd, BPFAttachType.CGROUP_SOCK_OPS) 1877b.attach_func(fn, map_fd, BPFAttachType.SK_MSG_VERDICT) 1878``` 1879 1880Note. When attached to "global" hooks (xdp, tc, lwt, cgroup). If the "BPF function" is no longer needed after the program terminates, be sure to call `detach_func` when the program exits. 1881 1882Examples in situ: 1883 1884[search /examples](https://github.com/iovisor/bcc/search?q=attach_func+path%3Aexamples+language%3Apython&type=Code), 1885 1886### 11. detach_func() 1887 1888Syntax: ```BPF.detach_func(fn, attachable_fd, attach_type)``` 1889 1890Detaches a BPF function of the specified type. 1891 1892For example: 1893 1894```Python 1895b.detach_func(fn, cgroup_fd, BPFAttachType.CGROUP_SOCK_OPS) 1896b.detach_func(fn, map_fd, BPFAttachType.SK_MSG_VERDICT) 1897``` 1898 1899Examples in situ: 1900 1901[search /examples](https://github.com/iovisor/bcc/search?q=detach_func+path%3Aexamples+language%3Apython&type=Code), 1902 1903### 12. detach_kprobe() 1904 1905Syntax: ```BPF.detach_kprobe(event="event", fn_name="name")``` 1906 1907Detach a kprobe handler function of the specified event. 1908 1909For example: 1910 1911```Python 1912b.detach_kprobe(event="__page_cache_alloc", fn_name="trace_func_entry") 1913``` 1914 1915### 13. detach_kretprobe() 1916 1917Syntax: ```BPF.detach_kretprobe(event="event", fn_name="name")``` 1918 1919Detach a kretprobe handler function of the specified event. 1920 1921For example: 1922 1923```Python 1924b.detach_kretprobe(event="__page_cache_alloc", fn_name="trace_func_return") 1925``` 1926 1927## Debug Output 1928 1929### 1. trace_print() 1930 1931Syntax: ```BPF.trace_print(fmt="fields")``` 1932 1933This method continually reads the globally shared /sys/kernel/debug/tracing/trace_pipe file and prints its contents. This file can be written to via BPF and the bpf_trace_printk() function, however, that method has limitations, including a lack of concurrent tracing support. The BPF_PERF_OUTPUT mechanism, covered earlier, is preferred. 1934 1935Arguments: 1936 1937- ```fmt```: optional, and can contain a field formatting string. It defaults to ```None```. 1938 1939Examples: 1940 1941```Python 1942# print trace_pipe output as-is: 1943b.trace_print() 1944 1945# print PID and message: 1946b.trace_print(fmt="{1} {5}") 1947``` 1948 1949Examples in situ: 1950[search /examples](https://github.com/iovisor/bcc/search?q=trace_print+path%3Aexamples+language%3Apython&type=Code), 1951[search /tools](https://github.com/iovisor/bcc/search?q=trace_print+path%3Atools+language%3Apython&type=Code) 1952 1953### 2. trace_fields() 1954 1955Syntax: ```BPF.trace_fields(nonblocking=False)``` 1956 1957This method reads one line from the globally shared /sys/kernel/debug/tracing/trace_pipe file and returns it as fields. This file can be written to via BPF and the bpf_trace_printk() function, however, that method has limitations, including a lack of concurrent tracing support. The BPF_PERF_OUTPUT mechanism, covered earlier, is preferred. 1958 1959Arguments: 1960 1961- ```nonblocking```: optional, defaults to ```False```. When set to ```True```, the program will not block waiting for input. 1962 1963Examples: 1964 1965```Python 1966while 1: 1967 try: 1968 (task, pid, cpu, flags, ts, msg) = b.trace_fields() 1969 except ValueError: 1970 continue 1971 [...] 1972``` 1973 1974Examples in situ: 1975[search /examples](https://github.com/iovisor/bcc/search?q=trace_fields+path%3Aexamples+language%3Apython&type=Code), 1976[search /tools](https://github.com/iovisor/bcc/search?q=trace_fields+path%3Atools+language%3Apython&type=Code) 1977 1978## Output APIs 1979 1980Normal output from a BPF program is either: 1981 1982- per-event: using PERF_EVENT_OUTPUT, open_perf_buffer(), and perf_buffer_poll(). 1983- map summary: using items(), or print_log2_hist(), covered in the Maps section. 1984 1985### 1. perf_buffer_poll() 1986 1987Syntax: ```BPF.perf_buffer_poll(timeout=T)``` 1988 1989This polls from all open perf ring buffers, calling the callback function that was provided when calling open_perf_buffer for each entry. 1990 1991The timeout parameter is optional and measured in milliseconds. In its absence, polling continues indefinitely. 1992 1993Example: 1994 1995```Python 1996# loop with callback to print_event 1997b["events"].open_perf_buffer(print_event) 1998while 1: 1999 try: 2000 b.perf_buffer_poll() 2001 except KeyboardInterrupt: 2002 exit(); 2003``` 2004 2005Examples in situ: 2006[code](https://github.com/iovisor/bcc/blob/v0.9.0/examples/tracing/hello_perf_output.py#L55), 2007[search /examples](https://github.com/iovisor/bcc/search?q=perf_buffer_poll+path%3Aexamples+language%3Apython&type=Code), 2008[search /tools](https://github.com/iovisor/bcc/search?q=perf_buffer_poll+path%3Atools+language%3Apython&type=Code) 2009 2010### 2. ring_buffer_poll() 2011 2012Syntax: ```BPF.ring_buffer_poll(timeout=T)``` 2013 2014This polls from all open ringbuf ring buffers, calling the callback function that was provided when calling open_ring_buffer for each entry. 2015 2016The timeout parameter is optional and measured in milliseconds. In its absence, polling continues until 2017there is no more data or the callback returns a negative value. 2018 2019Example: 2020 2021```Python 2022# loop with callback to print_event 2023b["events"].open_ring_buffer(print_event) 2024while 1: 2025 try: 2026 b.ring_buffer_poll(30) 2027 except KeyboardInterrupt: 2028 exit(); 2029``` 2030 2031Examples in situ: 2032[search /examples](https://github.com/iovisor/bcc/search?q=ring_buffer_poll+path%3Aexamples+language%3Apython&type=Code), 2033 2034### 3. ring_buffer_consume() 2035 2036Syntax: ```BPF.ring_buffer_consume()``` 2037 2038This consumes from all open ringbuf ring buffers, calling the callback function that was provided when calling open_ring_buffer for each entry. 2039 2040Unlike ```ring_buffer_poll```, this method **does not poll for data** before attempting to consume. 2041This reduces latency at the expense of higher CPU consumption. If you are unsure which to use, 2042use ```ring_buffer_poll```. 2043 2044Example: 2045 2046```Python 2047# loop with callback to print_event 2048b["events"].open_ring_buffer(print_event) 2049while 1: 2050 try: 2051 b.ring_buffer_consume() 2052 except KeyboardInterrupt: 2053 exit(); 2054``` 2055 2056Examples in situ: 2057[search /examples](https://github.com/iovisor/bcc/search?q=ring_buffer_consume+path%3Aexamples+language%3Apython&type=Code), 2058 2059## Map APIs 2060 2061Maps are BPF data stores, and are used in bcc to implement a table, and then higher level objects on top of tables, including hashes and histograms. 2062 2063### 1. get_table() 2064 2065Syntax: ```BPF.get_table(name)``` 2066 2067Returns a table object. This is no longer used, as tables can now be read as items from BPF. Eg: ```BPF[name]```. 2068 2069Examples: 2070 2071```Python 2072counts = b.get_table("counts") 2073 2074counts = b["counts"] 2075``` 2076 2077These are equivalent. 2078 2079### 2. open_perf_buffer() 2080 2081Syntax: ```table.open_perf_buffers(callback, page_cnt=N, lost_cb=None)``` 2082 2083This operates on a table as defined in BPF as BPF_PERF_OUTPUT(), and associates the callback Python function ```callback``` to be called when data is available in the perf ring buffer. This is part of the recommended mechanism for transferring per-event data from kernel to user space. The size of the perf ring buffer can be specified via the ```page_cnt``` parameter, which must be a power of two number of pages and defaults to 8. If the callback is not processing data fast enough, some submitted data may be lost. ```lost_cb``` will be called to log / monitor the lost count. If ```lost_cb``` is the default ```None``` value, it will just print a line of message to ```stderr```. 2084 2085Example: 2086 2087```Python 2088# process event 2089def print_event(cpu, data, size): 2090 event = ct.cast(data, ct.POINTER(Data)).contents 2091 [...] 2092 2093# loop with callback to print_event 2094b["events"].open_perf_buffer(print_event) 2095while 1: 2096 try: 2097 b.perf_buffer_poll() 2098 except KeyboardInterrupt: 2099 exit() 2100``` 2101 2102Note that the data structure transferred will need to be declared in C in the BPF program. For example: 2103 2104```C 2105// define output data structure in C 2106struct data_t { 2107 u32 pid; 2108 u64 ts; 2109 char comm[TASK_COMM_LEN]; 2110}; 2111BPF_PERF_OUTPUT(events); 2112[...] 2113``` 2114 2115In Python, you can either let bcc generate the data structure from C declaration automatically (recommended): 2116 2117```Python 2118def print_event(cpu, data, size): 2119 event = b["events"].event(data) 2120[...] 2121``` 2122 2123or define it manually: 2124 2125```Python 2126# define output data structure in Python 2127TASK_COMM_LEN = 16 # linux/sched.h 2128class Data(ct.Structure): 2129 _fields_ = [("pid", ct.c_ulonglong), 2130 ("ts", ct.c_ulonglong), 2131 ("comm", ct.c_char * TASK_COMM_LEN)] 2132 2133def print_event(cpu, data, size): 2134 event = ct.cast(data, ct.POINTER(Data)).contents 2135[...] 2136``` 2137 2138Examples in situ: 2139[code](https://github.com/iovisor/bcc/blob/v0.9.0/examples/tracing/hello_perf_output.py#L52), 2140[search /examples](https://github.com/iovisor/bcc/search?q=open_perf_buffer+path%3Aexamples+language%3Apython&type=Code), 2141[search /tools](https://github.com/iovisor/bcc/search?q=open_perf_buffer+path%3Atools+language%3Apython&type=Code) 2142 2143### 3. items() 2144 2145Syntax: ```table.items()``` 2146 2147Returns an array of the keys in a table. This can be used with BPF_HASH maps to fetch, and iterate, over the keys. 2148 2149Example: 2150 2151```Python 2152# print output 2153print("%10s %s" % ("COUNT", "STRING")) 2154counts = b.get_table("counts") 2155for k, v in sorted(counts.items(), key=lambda counts: counts[1].value): 2156 print("%10d \"%s\"" % (v.value, k.c.encode('string-escape'))) 2157``` 2158 2159This example also uses the ```sorted()``` method to sort by value. 2160 2161Examples in situ: 2162[search /examples](https://github.com/iovisor/bcc/search?q=items+path%3Aexamples+language%3Apython&type=Code), 2163[search /tools](https://github.com/iovisor/bcc/search?q=items+path%3Atools+language%3Apython&type=Code) 2164 2165### 4. values() 2166 2167Syntax: ```table.values()``` 2168 2169Returns an array of the values in a table. 2170 2171### 5. clear() 2172 2173Syntax: ```table.clear()``` 2174 2175Clears the table: deletes all entries. 2176 2177Example: 2178 2179```Python 2180# print map summary every second: 2181while True: 2182 time.sleep(1) 2183 print("%-8s\n" % time.strftime("%H:%M:%S"), end="") 2184 dist.print_log2_hist(sym + " return:") 2185 dist.clear() 2186``` 2187 2188Examples in situ: 2189[search /examples](https://github.com/iovisor/bcc/search?q=clear+path%3Aexamples+language%3Apython&type=Code), 2190[search /tools](https://github.com/iovisor/bcc/search?q=clear+path%3Atools+language%3Apython&type=Code) 2191 2192### 6. items_lookup_and_delete_batch() 2193 2194Syntax: ```table.items_lookup_and_delete_batch()``` 2195 2196Returns an array of the keys in a table with a single call to BPF syscall. This can be used with BPF_HASH maps to fetch, and iterate, over the keys. It also clears the table: deletes all entries. 2197You should rather use table.items_lookup_and_delete_batch() than table.items() followed by table.clear(). It requires kernel v5.6. 2198 2199Example: 2200 2201```Python 2202# print call rate per second: 2203print("%9s-%9s-%8s-%9s" % ("PID", "COMM", "fname", "counter")) 2204while True: 2205 for k, v in sorted(b['map'].items_lookup_and_delete_batch(), key=lambda kv: (kv[0]).pid): 2206 print("%9s-%9s-%8s-%9d" % (k.pid, k.comm, k.fname, v.counter)) 2207 sleep(1) 2208``` 2209 2210### 7. items_lookup_batch() 2211 2212Syntax: ```table.items_lookup_batch()``` 2213 2214Returns an array of the keys in a table with a single call to BPF syscall. This can be used with BPF_HASH maps to fetch, and iterate, over the keys. 2215You should rather use table.items_lookup_batch() than table.items(). It requires kernel v5.6. 2216 2217Example: 2218 2219```Python 2220# print current value of map: 2221print("%9s-%9s-%8s-%9s" % ("PID", "COMM", "fname", "counter")) 2222while True: 2223 for k, v in sorted(b['map'].items_lookup_batch(), key=lambda kv: (kv[0]).pid): 2224 print("%9s-%9s-%8s-%9d" % (k.pid, k.comm, k.fname, v.counter)) 2225``` 2226 2227### 8. items_delete_batch() 2228 2229Syntax: ```table.items_delete_batch(keys)``` 2230 2231It clears all entries of a BPF_HASH map when keys is None. It is more efficient than table.clear() since it generates only one system call. You can delete a subset of a map by giving an array of keys as parameter. Those keys and their associated values will be deleted. It requires kernel v5.6. 2232 2233Arguments: 2234 2235- keys is optional and by default is None. 2236 2237 2238 2239### 9. items_update_batch() 2240 2241Syntax: ```table.items_update_batch(keys, values)``` 2242 2243Update all the provided keys with new values. The two arguments must be the same length and within the map limits (between 1 and the maximum entries). It requires kernel v5.6. 2244 2245Arguments: 2246 2247- keys is the list of keys to be updated 2248- values is the list containing the new values. 2249 2250 2251### 10. print_log2_hist() 2252 2253Syntax: ```table.print_log2_hist(val_type="value", section_header="Bucket ptr", section_print_fn=None)``` 2254 2255Prints a table as a log2 histogram in ASCII. The table must be stored as log2, which can be done using the BPF function ```bpf_log2l()```. 2256 2257Arguments: 2258 2259- val_type: optional, column header. 2260- section_header: if the histogram has a secondary key, multiple tables will print and section_header can be used as a header description for each. 2261- section_print_fn: if section_print_fn is not None, it will be passed the bucket value. 2262 2263Example: 2264 2265```Python 2266b = BPF(text=""" 2267BPF_HISTOGRAM(dist); 2268 2269int kprobe__blk_account_io_done(struct pt_regs *ctx, struct request *req) 2270{ 2271 dist.increment(bpf_log2l(req->__data_len / 1024)); 2272 return 0; 2273} 2274""") 2275[...] 2276 2277b["dist"].print_log2_hist("kbytes") 2278``` 2279 2280Output: 2281 2282``` 2283 kbytes : count distribution 2284 0 -> 1 : 3 | | 2285 2 -> 3 : 0 | | 2286 4 -> 7 : 211 |********** | 2287 8 -> 15 : 0 | | 2288 16 -> 31 : 0 | | 2289 32 -> 63 : 0 | | 2290 64 -> 127 : 1 | | 2291 128 -> 255 : 800 |**************************************| 2292``` 2293 2294This output shows a multi-modal distribution, with the largest mode of 128->255 kbytes and a count of 800. 2295 2296This is an efficient way to summarize data, as the summarization is performed in-kernel, and only the count column is passed to user space. 2297 2298Examples in situ: 2299[search /examples](https://github.com/iovisor/bcc/search?q=print_log2_hist+path%3Aexamples+language%3Apython&type=Code), 2300[search /tools](https://github.com/iovisor/bcc/search?q=print_log2_hist+path%3Atools+language%3Apython&type=Code) 2301 2302### 11. print_linear_hist() 2303 2304Syntax: ```table.print_linear_hist(val_type="value", section_header="Bucket ptr", section_print_fn=None)``` 2305 2306Prints a table as a linear histogram in ASCII. This is intended to visualize small integer ranges, eg, 0 to 100. 2307 2308Arguments: 2309 2310- val_type: optional, column header. 2311- section_header: if the histogram has a secondary key, multiple tables will print and section_header can be used as a header description for each. 2312- section_print_fn: if section_print_fn is not None, it will be passed the bucket value. 2313 2314Example: 2315 2316```Python 2317b = BPF(text=""" 2318BPF_HISTOGRAM(dist); 2319 2320int kprobe__blk_account_io_done(struct pt_regs *ctx, struct request *req) 2321{ 2322 dist.increment(req->__data_len / 1024); 2323 return 0; 2324} 2325""") 2326[...] 2327 2328b["dist"].print_linear_hist("kbytes") 2329``` 2330 2331Output: 2332 2333``` 2334 kbytes : count distribution 2335 0 : 3 |****** | 2336 1 : 0 | | 2337 2 : 0 | | 2338 3 : 0 | | 2339 4 : 19 |****************************************| 2340 5 : 0 | | 2341 6 : 0 | | 2342 7 : 0 | | 2343 8 : 4 |******** | 2344 9 : 0 | | 2345 10 : 0 | | 2346 11 : 0 | | 2347 12 : 0 | | 2348 13 : 0 | | 2349 14 : 0 | | 2350 15 : 0 | | 2351 16 : 2 |**** | 2352[...] 2353``` 2354 2355This is an efficient way to summarize data, as the summarization is performed in-kernel, and only the values in the count column are passed to user space. 2356 2357Examples in situ: 2358[search /examples](https://github.com/iovisor/bcc/search?q=print_linear_hist+path%3Aexamples+language%3Apython&type=Code), 2359[search /tools](https://github.com/iovisor/bcc/search?q=print_linear_hist+path%3Atools+language%3Apython&type=Code) 2360 2361### 12. open_ring_buffer() 2362 2363Syntax: ```table.open_ring_buffer(callback, ctx=None)``` 2364 2365This operates on a table as defined in BPF as BPF_RINGBUF_OUTPUT(), and associates the callback Python function ```callback``` to be called when data is available in the ringbuf ring buffer. This is part of the new (Linux 5.8+) recommended mechanism for transferring per-event data from kernel to user space. Unlike perf buffers, ringbuf sizes are specified within the BPF program, as part of the ```BPF_RINGBUF_OUTPUT``` macro. If the callback is not processing data fast enough, some submitted data may be lost. In this case, the events should be polled more frequently and/or the size of the ring buffer should be increased. 2366 2367Example: 2368 2369```Python 2370# process event 2371def print_event(ctx, data, size): 2372 event = ct.cast(data, ct.POINTER(Data)).contents 2373 [...] 2374 2375# loop with callback to print_event 2376b["events"].open_ring_buffer(print_event) 2377while 1: 2378 try: 2379 b.ring_buffer_poll() 2380 except KeyboardInterrupt: 2381 exit() 2382``` 2383 2384Note that the data structure transferred will need to be declared in C in the BPF program. For example: 2385 2386```C 2387// define output data structure in C 2388struct data_t { 2389 u32 pid; 2390 u64 ts; 2391 char comm[TASK_COMM_LEN]; 2392}; 2393BPF_RINGBUF_OUTPUT(events, 8); 2394[...] 2395``` 2396 2397In Python, you can either let bcc generate the data structure from C declaration automatically (recommended): 2398 2399```Python 2400def print_event(ctx, data, size): 2401 event = b["events"].event(data) 2402[...] 2403``` 2404 2405or define it manually: 2406 2407```Python 2408# define output data structure in Python 2409TASK_COMM_LEN = 16 # linux/sched.h 2410class Data(ct.Structure): 2411 _fields_ = [("pid", ct.c_ulonglong), 2412 ("ts", ct.c_ulonglong), 2413 ("comm", ct.c_char * TASK_COMM_LEN)] 2414 2415def print_event(ctx, data, size): 2416 event = ct.cast(data, ct.POINTER(Data)).contents 2417[...] 2418``` 2419 2420Examples in situ: 2421[search /examples](https://github.com/iovisor/bcc/search?q=open_ring_buffer+path%3Aexamples+language%3Apython&type=Code), 2422 2423### 13. push() 2424 2425Syntax: ```table.push(leaf, flags=0)``` 2426 2427Push an element onto a Stack or Queue table. Raises an exception if the operation does not succeed. 2428Passing QueueStack.BPF_EXIST as a flag causes the Queue or Stack to discard the oldest element if it is full. 2429 2430Examples in situ: 2431[search /tests](https://github.com/iovisor/bcc/search?q=push+path%3Atests+language%3Apython&type=Code), 2432 2433### 14. pop() 2434 2435Syntax: ```leaf = table.pop()``` 2436 2437Pop an element from a Stack or Queue table. Unlike ```peek()```, ```pop()``` 2438removes the element from the table before returning it. 2439Raises a KeyError exception if the operation does not succeed. 2440 2441Examples in situ: 2442[search /tests](https://github.com/iovisor/bcc/search?q=pop+path%3Atests+language%3Apython&type=Code), 2443 2444### 15. peek() 2445 2446Syntax: ```leaf = table.peek()``` 2447 2448Peek the element at the head of a Stack or Queue table. Unlike ```pop()```, ```peek()``` 2449does not remove the element from the table. Raises an exception if the operation does not succeed. 2450 2451Examples in situ: 2452[search /tests](https://github.com/iovisor/bcc/search?q=peek+path%3Atests+language%3Apython&type=Code), 2453 2454## Helpers 2455 2456Some helper methods provided by bcc. Note that since we're in Python, we can import any Python library and their methods, including, for example, the libraries: argparse, collections, ctypes, datetime, re, socket, struct, subprocess, sys, and time. 2457 2458### 1. ksym() 2459 2460Syntax: ```BPF.ksym(addr)``` 2461 2462Translate a kernel memory address into a kernel function name, which is returned. 2463 2464Example: 2465 2466```Python 2467print("kernel function: " + b.ksym(addr)) 2468``` 2469 2470Examples in situ: 2471[search /examples](https://github.com/iovisor/bcc/search?q=ksym+path%3Aexamples+language%3Apython&type=Code), 2472[search /tools](https://github.com/iovisor/bcc/search?q=ksym+path%3Atools+language%3Apython&type=Code) 2473 2474### 2. ksymname() 2475 2476Syntax: ```BPF.ksymname(name)``` 2477 2478Translate a kernel name into an address. This is the reverse of ksym. Returns -1 when the function name is unknown. 2479 2480Example: 2481 2482```Python 2483print("kernel address: %x" % b.ksymname("vfs_read")) 2484``` 2485 2486Examples in situ: 2487[search /examples](https://github.com/iovisor/bcc/search?q=ksymname+path%3Aexamples+language%3Apython&type=Code), 2488[search /tools](https://github.com/iovisor/bcc/search?q=ksymname+path%3Atools+language%3Apython&type=Code) 2489 2490### 3. sym() 2491 2492Syntax: ```BPF.sym(addr, pid, show_module=False, show_offset=False)``` 2493 2494Translate a memory address into a function name for a pid, which is returned. A pid of less than zero will access the kernel symbol cache. The `show_module` and `show_offset` parameters control whether the module in which the symbol lies should be displayed, and whether the instruction offset from the beginning of the symbol should be displayed. These extra parameters default to `False`. 2495 2496Example: 2497 2498```Python 2499print("function: " + b.sym(addr, pid)) 2500``` 2501 2502Examples in situ: 2503[search /examples](https://github.com/iovisor/bcc/search?q=sym+path%3Aexamples+language%3Apython&type=Code), 2504[search /tools](https://github.com/iovisor/bcc/search?q=sym+path%3Atools+language%3Apython&type=Code) 2505 2506### 4. num_open_kprobes() 2507 2508Syntax: ```BPF.num_open_kprobes()``` 2509 2510Returns the number of open k[ret]probes. Can be useful for scenarios where event_re is used while attaching and detaching probes. Excludes perf_events readers. 2511 2512Example: 2513 2514```Python 2515b.attach_kprobe(event_re=pattern, fn_name="trace_count") 2516matched = b.num_open_kprobes() 2517if matched == 0: 2518 print("0 functions matched by \"%s\". Exiting." % args.pattern) 2519 exit() 2520``` 2521 2522Examples in situ: 2523[search /examples](https://github.com/iovisor/bcc/search?q=num_open_kprobes+path%3Aexamples+language%3Apython&type=Code), 2524[search /tools](https://github.com/iovisor/bcc/search?q=num_open_kprobes+path%3Atools+language%3Apython&type=Code) 2525 2526### 5. get_syscall_fnname() 2527 2528Syntax: ```BPF.get_syscall_fnname(name : str)``` 2529 2530Return the corresponding kernel function name of the syscall. This helper function will try different prefixes and use the right one to concatenate with the syscall name. Note that the return value may vary in different versions of linux kernel and sometimes it will causing trouble. (see [#2590](https://github.com/iovisor/bcc/issues/2590)) 2531 2532Example: 2533 2534```Python 2535print("The function name of %s in kernel is %s" % ("clone", b.get_syscall_fnname("clone"))) 2536# sys_clone or __x64_sys_clone or ... 2537``` 2538 2539Examples in situ: 2540[search /examples](https://github.com/iovisor/bcc/search?q=get_syscall_fnname+path%3Aexamples+language%3Apython&type=Code), 2541[search /tools](https://github.com/iovisor/bcc/search?q=get_syscall_fnname+path%3Atools+language%3Apython&type=Code) 2542 2543# BPF Errors 2544 2545See the "Understanding eBPF verifier messages" section in the kernel source under Documentation/networking/filter.txt. 2546 2547## 1. Invalid mem access 2548 2549This can be due to trying to read memory directly, instead of operating on memory on the BPF stack. All kernel memory reads must be passed via bpf_probe_read_kernel() to copy kernel memory into the BPF stack, which can be automatic by the bcc rewriter in some cases of simple dereferencing. bpf_probe_read_kernel() does all the required checks. 2550 2551Example: 2552 2553``` 2554bpf: Permission denied 25550: (bf) r6 = r1 25561: (79) r7 = *(u64 *)(r6 +80) 25572: (85) call 14 25583: (bf) r8 = r0 2559[...] 256023: (69) r1 = *(u16 *)(r7 +16) 2561R7 invalid mem access 'inv' 2562 2563Traceback (most recent call last): 2564 File "./tcpaccept", line 179, in <module> 2565 b = BPF(text=bpf_text) 2566 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 172, in __init__ 2567 self._trace_autoload() 2568 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 612, in _trace_autoload 2569 fn = self.load_func(func_name, BPF.KPROBE) 2570 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 212, in load_func 2571 raise Exception("Failed to load BPF program %s" % func_name) 2572Exception: Failed to load BPF program kretprobe__inet_csk_accept 2573``` 2574 2575## 2. Cannot call GPL only function from proprietary program 2576 2577This error happens when a GPL-only helper is called from a non-GPL BPF program. To fix this error, do not use GPL-only helpers from a proprietary BPF program, or relicense the BPF program under a GPL-compatible license. Check which [BPF helpers](https://github.com/iovisor/bcc/blob/master/docs/kernel-versions.md#helpers) are GPL-only, and what licenses are considered GPL-compatible. 2578 2579Example calling `bpf_get_stackid()`, a GPL-only BPF helper, from a proprietary program (`#define BPF_LICENSE Proprietary`): 2580 2581``` 2582bpf: Failed to load program: Invalid argument 2583[...] 25848: (85) call bpf_get_stackid#27 2585cannot call GPL only function from proprietary program 2586``` 2587 2588# Environment Variables 2589 2590## 1. Kernel source directory 2591 2592eBPF program compilation needs kernel sources or kernel headers with headers 2593compiled. In case your kernel sources are at a non-standard location where BCC 2594cannot find then, its possible to provide BCC the absolute path of the location 2595by setting `BCC_KERNEL_SOURCE` to it. 2596 2597## 2. Kernel version overriding 2598 2599By default, BCC stores the `LINUX_VERSION_CODE` in the generated eBPF object 2600which is then passed along to the kernel when the eBPF program is loaded. 2601Sometimes this is quite inconvenient especially when the kernel is slightly 2602updated such as an LTS kernel release. Its extremely unlikely the slight 2603mismatch would cause any issues with the loaded eBPF program. By setting 2604`BCC_LINUX_VERSION_CODE` to the version of the kernel that's running, the check 2605for verifying the kernel version can be bypassed. This is needed for programs 2606that use kprobes. This needs to be encoded in the format: `(VERSION * 65536) + 2607(PATCHLEVEL * 256) + SUBLEVEL`. For example, if the running kernel is `4.9.10`, 2608then can set `export BCC_LINUX_VERSION_CODE=264458` to override the kernel 2609version check successfully. 2610