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 MODULE_KFUNC_PROBE(*module*, *function*, typeof(arg1) arg1, typeof(arg2) arge ...) 371 372This is a macro that instruments the kernel function via trampoline 373*before* the function is executed. It's defined by *function* name and 374the function arguments defined as *argX*. 375 376For example: 377```C 378KFUNC_PROBE(do_sys_open, int dfd, const char *filename, int flags, int mode) 379{ 380 ... 381``` 382 383This instruments the do_sys_open kernel function and make its arguments 384accessible as standard argument values. 385 386Examples in situ: 387[search /tools](https://github.com/iovisor/bcc/search?q=KFUNC_PROBE+path%3Atools&type=Code) 388 389### 10. kretfuncs 390 391Syntax: KRETFUNC_PROBE(*event*, typeof(arg1) arg1, typeof(arg2) arge ..., int ret) 392 MODULE_KRETFUNC_PROBE(*module*, *function*, typeof(arg1) arg1, typeof(arg2) arge ...) 393 394This is a macro that instruments the kernel function via trampoline 395*after* the function is executed. It's defined by *function* name and 396the function arguments defined as *argX*. 397 398The last argument of the probe is the return value of the instrumented function. 399 400For example: 401```C 402KRETFUNC_PROBE(do_sys_open, int dfd, const char *filename, int flags, int mode, int ret) 403{ 404 ... 405``` 406 407This instruments the do_sys_open kernel function and make its arguments 408accessible as standard argument values together with its return value. 409 410Examples in situ: 411[search /tools](https://github.com/iovisor/bcc/search?q=KRETFUNC_PROBE+path%3Atools&type=Code) 412 413 414### 11. LSM Probes 415 416Syntax: LSM_PROBE(*hook*, typeof(arg1) arg1, typeof(arg2) arg2 ...) 417 418This is a macro that instruments an LSM hook as a BPF program. It can be 419used to audit security events and implement MAC security policies in BPF. 420It is defined by specifying the hook name followed by its arguments. 421 422Hook names can be found in 423[include/linux/security.h](https://github.com/torvalds/linux/blob/v5.15/include/linux/security.h#L260) 424by taking functions like `security_hookname` and taking just the `hookname` part. 425For example, `security_bpf` would simply become `bpf`. 426 427Unlike other BPF program types, the return value specified in an LSM probe 428matters. A return value of 0 allows the hook to succeed, whereas 429any non-zero return value will cause the hook to fail and deny the 430security operation. 431 432The following example instruments a hook that denies all future BPF operations: 433```C 434LSM_PROBE(bpf, int cmd, union bpf_attr *attr, unsigned int size) 435{ 436 return -EPERM; 437} 438``` 439 440This instruments the `security_bpf` hook and causes it to return `-EPERM`. 441Changing `return -EPERM` to `return 0` would cause the BPF program 442to allow the operation instead. 443 444LSM probes require at least a 5.7+ kernel with the following configuation options set: 445- `CONFIG_BPF_LSM=y` 446- `CONFIG_LSM` comma separated string must contain "bpf" (for example, 447 `CONFIG_LSM="lockdown,yama,bpf"`) 448 449Examples in situ: 450[search /tests](https://github.com/iovisor/bcc/search?q=LSM_PROBE+path%3Atests&type=Code) 451 452### 12. BPF ITERATORS 453 454Syntax: BPF_ITER(target) 455 456This is a macro to define a program signature for a bpf iterator program. The argument *target* specifies what to iterate for the program. 457 458Currently, 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*. 459 460The following example defines a program for target *task*, which traverses all tasks in the kernel. 461```C 462BPF_ITER(task) 463{ 464 struct seq_file *seq = ctx->meta->seq; 465 struct task_struct *task = ctx->task; 466 467 if (task == (void *)0) 468 return 0; 469 470 ... task->pid, task->tgid, task->comm, ... 471 return 0; 472} 473``` 474 475BPF 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. 476 477## Data 478 479### 1. bpf_probe_read_kernel() 480 481Syntax: ```int bpf_probe_read_kernel(void *dst, int size, const void *src)``` 482 483Return: 0 on success 484 485This 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(). 486 487Examples in situ: 488[search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel+path%3Aexamples&type=Code), 489[search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel+path%3Atools&type=Code) 490 491### 2. bpf_probe_read_kernel_str() 492 493Syntax: ```int bpf_probe_read_kernel_str(void *dst, int size, const void *src)``` 494 495Return: 496 - \> 0 length of the string including the trailing NULL on success 497 - \< 0 error 498 499This 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`. 500 501Examples in situ: 502[search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel_str+path%3Aexamples&type=Code), 503[search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel_str+path%3Atools&type=Code) 504 505### 3. bpf_ktime_get_ns() 506 507Syntax: ```u64 bpf_ktime_get_ns(void)``` 508 509Return: u64 number of nanoseconds. Starts at system boot time but stops during suspend. 510 511Examples in situ: 512[search /examples](https://github.com/iovisor/bcc/search?q=bpf_ktime_get_ns+path%3Aexamples&type=Code), 513[search /tools](https://github.com/iovisor/bcc/search?q=bpf_ktime_get_ns+path%3Atools&type=Code) 514 515### 4. bpf_get_current_pid_tgid() 516 517Syntax: ```u64 bpf_get_current_pid_tgid(void)``` 518 519Return: ```current->tgid << 32 | current->pid``` 520 521Returns 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. 522 523Examples in situ: 524[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_pid_tgid+path%3Aexamples&type=Code), 525[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_pid_tgid+path%3Atools&type=Code) 526 527### 5. bpf_get_current_uid_gid() 528 529Syntax: ```u64 bpf_get_current_uid_gid(void)``` 530 531Return: ```current_gid << 32 | current_uid``` 532 533Returns the user ID and group IDs. 534 535Examples in situ: 536[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_uid_gid+path%3Aexamples&type=Code), 537[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_uid_gid+path%3Atools&type=Code) 538 539### 6. bpf_get_current_comm() 540 541Syntax: ```bpf_get_current_comm(char *buf, int size_of_buf)``` 542 543Return: 0 on success 544 545Populates 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: 546 547```C 548#include <linux/sched.h> 549 550int do_trace(struct pt_regs *ctx) { 551 char comm[TASK_COMM_LEN]; 552 bpf_get_current_comm(&comm, sizeof(comm)); 553[...] 554``` 555 556Examples in situ: 557[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_comm+path%3Aexamples&type=Code), 558[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_comm+path%3Atools&type=Code) 559 560### 7. bpf_get_current_task() 561 562Syntax: ```bpf_get_current_task()``` 563 564Return: current task as a pointer to struct task_struct. 565 566Returns 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. 567 568With Linux 4.13, due to issues with field randomization, you may need two #define directives before the includes: 569```C 570#define randomized_struct_fields_start struct { 571#define randomized_struct_fields_end }; 572#include <linux/sched.h> 573 574int do_trace(void *ctx) { 575 struct task_struct *t = (struct task_struct *)bpf_get_current_task(); 576[...] 577``` 578 579Examples in situ: 580[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_task+path%3Aexamples&type=Code), 581[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_task+path%3Atools&type=Code) 582 583### 8. bpf_log2l() 584 585Syntax: ```unsigned int bpf_log2l(unsigned long v)``` 586 587Returns the log-2 of the provided value. This is often used to create indexes for histograms, to construct power-of-2 histograms. 588 589Examples in situ: 590[search /examples](https://github.com/iovisor/bcc/search?q=bpf_log2l+path%3Aexamples&type=Code), 591[search /tools](https://github.com/iovisor/bcc/search?q=bpf_log2l+path%3Atools&type=Code) 592 593### 9. bpf_get_prandom_u32() 594 595Syntax: ```u32 bpf_get_prandom_u32()``` 596 597Returns a pseudo-random u32. 598 599Example in situ: 600[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_prandom_u32+path%3Aexamples&type=Code), 601[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_prandom_u32+path%3Atools&type=Code) 602 603### 10. bpf_probe_read_user() 604 605Syntax: ```int bpf_probe_read_user(void *dst, int size, const void *src)``` 606 607Return: 0 on success 608 609This 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(). 610 611Examples in situ: 612[search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user+path%3Aexamples&type=Code), 613[search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user+path%3Atools&type=Code) 614 615### 11. bpf_probe_read_user_str() 616 617Syntax: ```int bpf_probe_read_user_str(void *dst, int size, const void *src)``` 618 619Return: 620 - \> 0 length of the string including the trailing NULL on success 621 - \< 0 error 622 623This 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`. 624 625Examples in situ: 626[search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user_str+path%3Aexamples&type=Code), 627[search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user_str+path%3Atools&type=Code) 628 629 630### 12. bpf_get_ns_current_pid_tgid() 631 632Syntax: ```u32 bpf_get_ns_current_pid_tgid(u64 dev, u64 ino, struct bpf_pidns_info* nsdata, u32 size)``` 633 634Values for *pid* and *tgid* as seen from the current *namespace* will be returned in *nsdata*. 635 636Return 0 on success, or one of the following in case of failure: 637 638- **-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. 639 640- **-ENOENT** if pidns does not exists for the current task. 641 642Examples in situ: 643[search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_ns_current_pid_tgid+path%3Aexamples&type=Code), 644[search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_ns_current_pid_tgid+path%3Atools&type=Code) 645 646 647## Debugging 648 649### 1. bpf_override_return() 650 651Syntax: ```int bpf_override_return(struct pt_regs *, unsigned long rc)``` 652 653Return: 0 on success 654 655When used in a program attached to a function entry kprobe, causes the 656execution of the function to be skipped, immediately returning `rc` instead. 657This is used for targeted error injection. 658 659bpf_override_return will only work when the kprobed function is whitelisted to 660allow error injections. Whitelisting entails tagging a function with 661`ALLOW_ERROR_INJECTION()` in the kernel source tree; see `io_ctl_init` for 662an example. If the kprobed function is not whitelisted, the bpf program will 663fail to attach with ` ioctl(PERF_EVENT_IOC_SET_BPF): Invalid argument` 664 665 666```C 667int kprobe__io_ctl_init(void *ctx) { 668 bpf_override_return(ctx, -ENOMEM); 669 return 0; 670} 671``` 672 673## Output 674 675### 1. bpf_trace_printk() 676 677Syntax: ```int bpf_trace_printk(const char *fmt, ...)``` 678 679Return: 0 on success 680 681A 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. 682 683Examples in situ: 684[search /examples](https://github.com/iovisor/bcc/search?q=bpf_trace_printk+path%3Aexamples&type=Code), 685[search /tools](https://github.com/iovisor/bcc/search?q=bpf_trace_printk+path%3Atools&type=Code) 686 687### 2. BPF_PERF_OUTPUT 688 689Syntax: ```BPF_PERF_OUTPUT(name)``` 690 691Creates 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. 692 693For example: 694 695```C 696struct data_t { 697 u32 pid; 698 u64 ts; 699 char comm[TASK_COMM_LEN]; 700}; 701BPF_PERF_OUTPUT(events); 702 703int hello(struct pt_regs *ctx) { 704 struct data_t data = {}; 705 706 data.pid = bpf_get_current_pid_tgid(); 707 data.ts = bpf_ktime_get_ns(); 708 bpf_get_current_comm(&data.comm, sizeof(data.comm)); 709 710 events.perf_submit(ctx, &data, sizeof(data)); 711 712 return 0; 713} 714``` 715 716The output table is named ```events```, and data is pushed to it via ```events.perf_submit()```. 717 718Examples in situ: 719[search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERF_OUTPUT+path%3Aexamples&type=Code), 720[search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERF_OUTPUT+path%3Atools&type=Code) 721 722### 3. perf_submit() 723 724Syntax: ```int perf_submit((void *)ctx, (void *)data, u32 data_size)``` 725 726Return: 0 on success 727 728A 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().) 729 730The ```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. 731 732Examples in situ: 733[search /examples](https://github.com/iovisor/bcc/search?q=perf_submit+path%3Aexamples&type=Code), 734[search /tools](https://github.com/iovisor/bcc/search?q=perf_submit+path%3Atools&type=Code) 735 736### 4. perf_submit_skb() 737 738Syntax: ```int perf_submit_skb((void *)ctx, u32 packet_size, (void *)data, u32 data_size)``` 739 740Return: 0 on success 741 742A 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().) 743 744Examples in situ: 745[search /examples](https://github.com/iovisor/bcc/search?q=perf_submit_skb+path%3Aexamples&type=Code), 746[search /tools](https://github.com/iovisor/bcc/search?q=perf_submit_skb+path%3Atools&type=Code) 747 748### 5. BPF_RINGBUF_OUTPUT 749 750Syntax: ```BPF_RINGBUF_OUTPUT(name, page_cnt)``` 751 752Creates a BPF table for pushing out custom event data to user space via a ringbuf ring buffer. 753```BPF_RINGBUF_OUTPUT``` has several advantages over ```BPF_PERF_OUTPUT```, summarized as follows: 754 755- Buffer is shared across all CPUs, meaning no per-CPU allocation 756- Supports two APIs for BPF programs 757 - ```map.ringbuf_output()``` works like ```map.perf_submit()``` (covered in [ringbuf_output](#6-ringbuf_output)) 758 - ```map.ringbuf_reserve()```/```map.ringbuf_submit()```/```map.ringbuf_discard()``` 759 split the process of reserving buffer space and submitting events into two steps 760 (covered in [ringbuf_reserve](#7-ringbuf_reserve), [ringbuf_submit](#8-ringbuf_submit), [ringbuf_discard](#9-ringbuf_discard)) 761- BPF APIs do not require access to a CPU ctx argument 762- Superior performance and latency in userspace thanks to a shared ring buffer manager 763- Supports two ways of consuming data in userspace 764 765Starting in Linux 5.8, this should be the preferred method for pushing per-event data to user space. 766 767Example of both APIs: 768 769```C 770struct data_t { 771 u32 pid; 772 u64 ts; 773 char comm[TASK_COMM_LEN]; 774}; 775 776// Creates a ringbuf called events with 8 pages of space, shared across all CPUs 777BPF_RINGBUF_OUTPUT(events, 8); 778 779int first_api_example(struct pt_regs *ctx) { 780 struct data_t data = {}; 781 782 data.pid = bpf_get_current_pid_tgid(); 783 data.ts = bpf_ktime_get_ns(); 784 bpf_get_current_comm(&data.comm, sizeof(data.comm)); 785 786 events.ringbuf_output(&data, sizeof(data), 0 /* flags */); 787 788 return 0; 789} 790 791int second_api_example(struct pt_regs *ctx) { 792 struct data_t *data = events.ringbuf_reserve(sizeof(struct data_t)); 793 if (!data) { // Failed to reserve space 794 return 1; 795 } 796 797 data->pid = bpf_get_current_pid_tgid(); 798 data->ts = bpf_ktime_get_ns(); 799 bpf_get_current_comm(&data->comm, sizeof(data->comm)); 800 801 events.ringbuf_submit(data, 0 /* flags */); 802 803 return 0; 804} 805``` 806 807The output table is named ```events```. Data is allocated via ```events.ringbuf_reserve()``` and pushed to it via ```events.ringbuf_submit()```. 808 809Examples in situ: <!-- TODO --> 810[search /examples](https://github.com/iovisor/bcc/search?q=BPF_RINGBUF_OUTPUT+path%3Aexamples&type=Code), 811 812### 6. ringbuf_output() 813 814Syntax: ```int ringbuf_output((void *)data, u64 data_size, u64 flags)``` 815 816Return: 0 on success 817 818Flags: 819 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability 820 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally 821 822A method of the BPF_RINGBUF_OUTPUT table, for submitting custom event data to user space. This method works like ```perf_submit()```, 823although it does not require a ctx argument. 824 825Examples in situ: <!-- TODO --> 826[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_output+path%3Aexamples&type=Code), 827 828### 7. ringbuf_reserve() 829 830Syntax: ```void* ringbuf_reserve(u64 data_size)``` 831 832Return: Pointer to data struct on success, NULL on failure 833 834A method of the BPF_RINGBUF_OUTPUT table, for reserving space in the ring buffer and simultaenously 835allocating a data struct for output. Must be used with one of ```ringbuf_submit``` or ```ringbuf_discard```. 836 837Examples in situ: <!-- TODO --> 838[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_reserve+path%3Aexamples&type=Code), 839 840### 8. ringbuf_submit() 841 842Syntax: ```void ringbuf_submit((void *)data, u64 flags)``` 843 844Return: Nothing, always succeeds 845 846Flags: 847 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability 848 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally 849 850A method of the BPF_RINGBUF_OUTPUT table, for submitting custom event data to user space. Must be preceded by a call to 851```ringbuf_reserve()``` to reserve space for the data. 852 853Examples in situ: <!-- TODO --> 854[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_submit+path%3Aexamples&type=Code), 855 856### 9. ringbuf_discard() 857 858Syntax: ```void ringbuf_discard((void *)data, u64 flags)``` 859 860Return: Nothing, always succeeds 861 862Flags: 863 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability 864 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally 865 866A method of the BPF_RINGBUF_OUTPUT table, for discarding custom event data; userspace 867ignores the data associated with the discarded event. Must be preceded by a call to 868```ringbuf_reserve()``` to reserve space for the data. 869 870Examples in situ: <!-- TODO --> 871[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_submit+path%3Aexamples&type=Code), 872 873### 10. ringbuf_query() 874 875Syntax: ```u64 ringbuf_query(u64 flags)``` 876 877Return: Requested value, or 0, if flags are not recognized 878 879Flags: 880 - ```BPF_RB_AVAIL_DATA```: Amount of data not yet consumed 881 - ```BPF_RB_RING_SIZE```: The size of ring buffer 882 - ```BPF_RB_CONS_POS```: Consumer position 883 - ```BPF_RB_PROD_POS```: Producer(s) position 884 885A method of the BPF_RINGBUF_OUTPUT table, for getting various properties of ring buffer. Returned values are momentarily snapshots of ring buffer state and could be off by the time helper returns, so this should be used only for debugging/reporting reasons or for implementing various heuristics, that take into account highly-changeable nature of some of those characteristics. 886 887Examples in situ: <!-- TODO --> 888[search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_query+path%3Aexamples&type=Code), 889 890## Maps 891 892Maps are BPF data stores, and are the basis for higher level object types including tables, hashes, and histograms. 893 894### 1. BPF_TABLE 895 896Syntax: ```BPF_TABLE(_table_type, _key_type, _leaf_type, _name, _max_entries)``` 897 898Creates a map named ```_name```. Most of the time this will be used via higher-level macros, like BPF_HASH, BPF_ARRAY, BPF_HISTOGRAM, etc. 899 900`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 */)`. 901 902Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment(). 903 904Examples in situ: 905[search /examples](https://github.com/iovisor/bcc/search?q=BPF_TABLE+path%3Aexamples&type=Code), 906[search /tools](https://github.com/iovisor/bcc/search?q=BPF_TABLE+path%3Atools&type=Code) 907 908#### Pinned Maps 909 910Syntax: ```BPF_TABLE_PINNED(_table_type, _key_type, _leaf_type, _name, _max_entries, "/sys/fs/bpf/xyz")``` 911 912Create 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. 913 914For example: 915 916```C 917BPF_TABLE_PINNED("hash", u64, u64, ids, 1024, "/sys/fs/bpf/ids"); 918``` 919 920### 2. BPF_HASH 921 922Syntax: ```BPF_HASH(name [, key_type [, leaf_type [, size]]])``` 923 924Creates a hash map (associative array) named ```name```, with optional parameters. 925 926Defaults: ```BPF_HASH(name, key_type=u64, leaf_type=u64, size=10240)``` 927 928For example: 929 930```C 931BPF_HASH(start, struct request *); 932``` 933 934This 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. 935 936This is a wrapper macro for `BPF_TABLE("hash", ...)`. 937 938Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment(). 939 940Examples in situ: 941[search /examples](https://github.com/iovisor/bcc/search?q=BPF_HASH+path%3Aexamples&type=Code), 942[search /tools](https://github.com/iovisor/bcc/search?q=BPF_HASH+path%3Atools&type=Code) 943 944### 3. BPF_ARRAY 945 946Syntax: ```BPF_ARRAY(name [, leaf_type [, size]])``` 947 948Creates an int-indexed array which is optimized for fastest lookup and update, named ```name```, with optional parameters. 949 950Defaults: ```BPF_ARRAY(name, leaf_type=u64, size=10240)``` 951 952For example: 953 954```C 955BPF_ARRAY(counts, u64, 32); 956``` 957 958This 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. 959 960This is a wrapper macro for `BPF_TABLE("array", ...)`. 961 962Methods (covered later): map.lookup(), map.update(), map.increment(). Note that all array elements are pre-allocated with zero values and can not be deleted. 963 964Examples in situ: 965[search /examples](https://github.com/iovisor/bcc/search?q=BPF_ARRAY+path%3Aexamples&type=Code), 966[search /tools](https://github.com/iovisor/bcc/search?q=BPF_ARRAY+path%3Atools&type=Code) 967 968### 4. BPF_HISTOGRAM 969 970Syntax: ```BPF_HISTOGRAM(name [, key_type [, size ]])``` 971 972Creates a histogram map named ```name```, with optional parameters. 973 974Defaults: ```BPF_HISTOGRAM(name, key_type=int, size=64)``` 975 976For example: 977 978```C 979BPF_HISTOGRAM(dist); 980``` 981 982This creates a histogram named ```dist```, which defaults to 64 buckets indexed by keys of type int. 983 984This is a wrapper macro for `BPF_TABLE("histgram", ...)`. 985 986Methods (covered later): map.increment(). 987 988Examples in situ: 989[search /examples](https://github.com/iovisor/bcc/search?q=BPF_HISTOGRAM+path%3Aexamples&type=Code), 990[search /tools](https://github.com/iovisor/bcc/search?q=BPF_HISTOGRAM+path%3Atools&type=Code) 991 992### 5. BPF_STACK_TRACE 993 994Syntax: ```BPF_STACK_TRACE(name, max_entries)``` 995 996Creates stack trace map named ```name```, with a maximum entry count provided. These maps are used to store stack traces. 997 998For example: 999 1000```C 1001BPF_STACK_TRACE(stack_traces, 1024); 1002``` 1003 1004This creates stack trace map named ```stack_traces```, with a maximum number of stack trace entries of 1024. 1005 1006This is a wrapper macro for `BPF_TABLE("stacktrace", ...)`. 1007 1008Methods (covered later): map.get_stackid(). 1009 1010Examples in situ: 1011[search /examples](https://github.com/iovisor/bcc/search?q=BPF_STACK_TRACE+path%3Aexamples&type=Code), 1012[search /tools](https://github.com/iovisor/bcc/search?q=BPF_STACK_TRACE+path%3Atools&type=Code) 1013 1014### 6. BPF_PERF_ARRAY 1015 1016Syntax: ```BPF_PERF_ARRAY(name, max_entries)``` 1017 1018Creates 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. 1019 1020For example: 1021 1022```C 1023text=""" 1024BPF_PERF_ARRAY(cpu_cycles, NUM_CPUS); 1025""" 1026b = bcc.BPF(text=text, cflags=["-DNUM_CPUS=%d" % multiprocessing.cpu_count()]) 1027b["cpu_cycles"].open_perf_event(b["cpu_cycles"].HW_CPU_CYCLES) 1028``` 1029 1030This 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. 1031 1032Methods (covered later): map.perf_read(). 1033 1034Examples in situ: 1035[search /tests](https://github.com/iovisor/bcc/search?q=BPF_PERF_ARRAY+path%3Atests&type=Code) 1036 1037### 7. BPF_PERCPU_HASH 1038 1039Syntax: ```BPF_PERCPU_HASH(name [, key_type [, leaf_type [, size]]])``` 1040 1041Creates 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. 1042 1043Note that due to limits defined in the kernel (in linux/mm/percpu.c), the ```leaf_type``` cannot have a size of more than 32KB. 1044In other words, ```BPF_PERCPU_HASH``` elements cannot be larger than 32KB in size. 1045 1046 1047Defaults: ```BPF_PERCPU_HASH(name, key_type=u64, leaf_type=u64, size=10240)``` 1048 1049For example: 1050 1051```C 1052BPF_PERCPU_HASH(start, struct request *); 1053``` 1054 1055This creates NUM_CPU hashes named ```start``` where the key is a ```struct request *```, and the value defaults to u64. 1056 1057This is a wrapper macro for `BPF_TABLE("percpu_hash", ...)`. 1058 1059Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment(). 1060 1061Examples in situ: 1062[search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_HASH+path%3Aexamples&type=Code), 1063[search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_HASH+path%3Atools&type=Code) 1064 1065 1066### 8. BPF_PERCPU_ARRAY 1067 1068Syntax: ```BPF_PERCPU_ARRAY(name [, leaf_type [, size]])``` 1069 1070Creates 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. 1071 1072Note that due to limits defined in the kernel (in linux/mm/percpu.c), the ```leaf_type``` cannot have a size of more than 32KB. 1073In other words, ```BPF_PERCPU_ARRAY``` elements cannot be larger than 32KB in size. 1074 1075 1076Defaults: ```BPF_PERCPU_ARRAY(name, leaf_type=u64, size=10240)``` 1077 1078For example: 1079 1080```C 1081BPF_PERCPU_ARRAY(counts, u64, 32); 1082``` 1083 1084This creates NUM_CPU arrays named ```counts``` where with 32 buckets and 64-bit integer values. 1085 1086This is a wrapper macro for `BPF_TABLE("percpu_array", ...)`. 1087 1088Methods (covered later): map.lookup(), map.update(), map.increment(). Note that all array elements are pre-allocated with zero values and can not be deleted. 1089 1090Examples in situ: 1091[search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_ARRAY+path%3Aexamples&type=Code), 1092[search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_ARRAY+path%3Atools&type=Code) 1093 1094### 9. BPF_LPM_TRIE 1095 1096Syntax: `BPF_LPM_TRIE(name [, key_type [, leaf_type [, size]]])` 1097 1098Creates a longest prefix match trie map named `name`, with optional parameters. 1099 1100Defaults: `BPF_LPM_TRIE(name, key_type=u64, leaf_type=u64, size=10240)` 1101 1102For example: 1103 1104```c 1105BPF_LPM_TRIE(trie, struct key_v6); 1106``` 1107 1108This creates an LPM trie map named `trie` where the key is a `struct key_v6`, and the value defaults to u64. 1109 1110This is a wrapper macro to `BPF_F_TABLE("lpm_trie", ..., BPF_F_NO_PREALLOC)`. 1111 1112Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment(). 1113 1114Examples in situ: 1115[search /examples](https://github.com/iovisor/bcc/search?q=BPF_LPM_TRIE+path%3Aexamples&type=Code), 1116[search /tools](https://github.com/iovisor/bcc/search?q=BPF_LPM_TRIE+path%3Atools&type=Code) 1117 1118### 10. BPF_PROG_ARRAY 1119 1120Syntax: ```BPF_PROG_ARRAY(name, size)``` 1121 1122This 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. 1123 1124This is a wrapper macro for `BPF_TABLE("prog", ...)`. 1125 1126Methods (covered later): map.call(). 1127 1128Examples in situ: 1129[search /examples](https://github.com/iovisor/bcc/search?q=BPF_PROG_ARRAY+path%3Aexamples&type=Code), 1130[search /tests](https://github.com/iovisor/bcc/search?q=BPF_PROG_ARRAY+path%3Atests&type=Code), 1131[assign fd](https://github.com/iovisor/bcc/blob/master/examples/networking/tunnel_monitor/monitor.py#L24-L26) 1132 1133### 11. BPF_DEVMAP 1134 1135Syntax: ```BPF_DEVMAP(name, size)``` 1136 1137This 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. 1138 1139For example: 1140```C 1141BPF_DEVMAP(devmap, 10); 1142``` 1143 1144Methods (covered later): map.redirect_map(). 1145 1146Examples in situ: 1147[search /examples](https://github.com/iovisor/bcc/search?q=BPF_DEVMAP+path%3Aexamples&type=Code), 1148 1149### 12. BPF_CPUMAP 1150 1151Syntax: ```BPF_CPUMAP(name, size)``` 1152 1153This 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. 1154 1155For example: 1156```C 1157BPF_CPUMAP(cpumap, 16); 1158``` 1159 1160Methods (covered later): map.redirect_map(). 1161 1162Examples in situ: 1163[search /examples](https://github.com/iovisor/bcc/search?q=BPF_CPUMAP+path%3Aexamples&type=Code), 1164 1165### 13. BPF_XSKMAP 1166 1167Syntax: ```BPF_XSKMAP(name, size [, "/sys/fs/bpf/xyz"])``` 1168 1169This creates a xsk map named ```name``` with ```size``` entries and pin it to the bpffs as a FILE. 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). 1170 1171For example: 1172```C 1173BPF_XSKMAP(xsks_map, 8); 1174``` 1175 1176Methods (covered later): map.redirect_map(). map.lookup() 1177 1178Examples in situ: 1179[search /examples](https://github.com/iovisor/bcc/search?q=BPF_XSKMAP+path%3Aexamples&type=Code), 1180 1181### 14. BPF_ARRAY_OF_MAPS 1182 1183Syntax: ```BPF_ARRAY_OF_MAPS(name, inner_map_name, size)``` 1184 1185This 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```. 1186 1187For example: 1188```C 1189BPF_TABLE("hash", int, int, ex1, 1024); 1190BPF_TABLE("hash", int, int, ex2, 1024); 1191BPF_ARRAY_OF_MAPS(maps_array, "ex1", 10); 1192``` 1193 1194### 15. BPF_HASH_OF_MAPS 1195 1196Syntax: ```BPF_HASH_OF_MAPS(name, key_type, inner_map_name, size)``` 1197 1198This 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```. 1199 1200For example: 1201```C 1202BPF_ARRAY(ex1, int, 1024); 1203BPF_ARRAY(ex2, int, 1024); 1204BPF_HASH_OF_MAPS(maps_hash, struct custom_key, "ex1", 10); 1205``` 1206 1207### 16. BPF_STACK 1208 1209Syntax: ```BPF_STACK(name, leaf_type, max_entries[, flags])``` 1210 1211Creates a stack named ```name``` with value type ```leaf_type``` and max entries ```max_entries```. 1212Stack and Queue maps are only available from Linux 4.20+. 1213 1214For example: 1215 1216```C 1217BPF_STACK(stack, struct event, 10240); 1218``` 1219 1220This creates a stack named ```stack``` where the value type is ```struct event```, that holds up to 10240 entries. 1221 1222Methods (covered later): map.push(), map.pop(), map.peek(). 1223 1224Examples in situ: 1225[search /tests](https://github.com/iovisor/bcc/search?q=BPF_STACK+path%3Atests&type=Code), 1226 1227### 17. BPF_QUEUE 1228 1229Syntax: ```BPF_QUEUE(name, leaf_type, max_entries[, flags])``` 1230 1231Creates a queue named ```name``` with value type ```leaf_type``` and max entries ```max_entries```. 1232Stack and Queue maps are only available from Linux 4.20+. 1233 1234For example: 1235 1236```C 1237BPF_QUEUE(queue, struct event, 10240); 1238``` 1239 1240This creates a queue named ```queue``` where the value type is ```struct event```, that holds up to 10240 entries. 1241 1242Methods (covered later): map.push(), map.pop(), map.peek(). 1243 1244Examples in situ: 1245[search /tests](https://github.com/iovisor/bcc/search?q=BPF_QUEUE+path%3Atests&type=Code), 1246 1247### 18. BPF_SOCKHASH 1248 1249Syntax: ```BPF_SOCKHASH(name[, key_type [, max_entries)``` 1250 1251Creates a hash named ```name```, with optional parameters. sockhash is only available from Linux 4.18+. 1252 1253Default: ```BPF_SOCKHASH(name, key_type=u32, max_entries=10240)``` 1254 1255For example: 1256 1257```C 1258struct sock_key { 1259 u32 remote_ip4; 1260 u32 local_ip4; 1261 u32 remote_port; 1262 u32 local_port; 1263}; 1264BPF_HASH(skh, struct sock_key, 65535); 1265``` 1266 1267This creates a hash named ```skh``` where the key is a ```struct sock_key```. 1268 1269A 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()```). 1270 1271The 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. 1272 1273Methods (covered later): map.sock_hash_update(), map.msg_redirect_hash(), map.sk_redirect_hash(). 1274 1275[search /tests](https://github.com/iovisor/bcc/search?q=BPF_SOCKHASH+path%3Atests&type=Code) 1276 1277### 19. map.lookup() 1278 1279Syntax: ```*val map.lookup(&key)``` 1280 1281Lookup 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. 1282 1283Examples in situ: 1284[search /examples](https://github.com/iovisor/bcc/search?q=lookup+path%3Aexamples&type=Code), 1285[search /tools](https://github.com/iovisor/bcc/search?q=lookup+path%3Atools&type=Code) 1286 1287### 20. map.lookup_or_try_init() 1288 1289Syntax: ```*val map.lookup_or_try_init(&key, &zero)``` 1290 1291Lookup 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. 1292 1293Examples in situ: 1294[search /examples](https://github.com/iovisor/bcc/search?q=lookup_or_try_init+path%3Aexamples&type=Code), 1295[search /tools](https://github.com/iovisor/bcc/search?q=lookup_or_try_init+path%3Atools&type=Code) 1296 1297Note: The old map.lookup_or_init() may cause return from the function, so lookup_or_try_init() is recommended as it 1298does not have this side effect. 1299 1300### 21. map.delete() 1301 1302Syntax: ```map.delete(&key)``` 1303 1304Delete the key from the hash. 1305 1306Examples in situ: 1307[search /examples](https://github.com/iovisor/bcc/search?q=delete+path%3Aexamples&type=Code), 1308[search /tools](https://github.com/iovisor/bcc/search?q=delete+path%3Atools&type=Code) 1309 1310### 22. map.update() 1311 1312Syntax: ```map.update(&key, &val)``` 1313 1314Associate the value in the second argument to the key, overwriting any previous value. 1315 1316Examples in situ: 1317[search /examples](https://github.com/iovisor/bcc/search?q=update+path%3Aexamples&type=Code), 1318[search /tools](https://github.com/iovisor/bcc/search?q=update+path%3Atools&type=Code) 1319 1320### 23. map.insert() 1321 1322Syntax: ```map.insert(&key, &val)``` 1323 1324Associate the value in the second argument to the key, only if there was no previous value. 1325 1326Examples in situ: 1327[search /examples](https://github.com/iovisor/bcc/search?q=insert+path%3Aexamples&type=Code), 1328[search /tools](https://github.com/iovisor/bcc/search?q=insert+path%3Atools&type=Code) 1329 1330### 24. map.increment() 1331 1332Syntax: ```map.increment(key[, increment_amount])``` 1333 1334Increments the key's value by `increment_amount`, which defaults to 1. Used for histograms. 1335 1336```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. 1337 1338Note. 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. 1339 1340Examples in situ: 1341[search /examples](https://github.com/iovisor/bcc/search?q=increment+path%3Aexamples&type=Code), 1342[search /tools](https://github.com/iovisor/bcc/search?q=increment+path%3Atools&type=Code) 1343 1344### 25. map.get_stackid() 1345 1346Syntax: ```int map.get_stackid(void *ctx, u64 flags)``` 1347 1348This 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. 1349 1350Examples in situ: 1351[search /examples](https://github.com/iovisor/bcc/search?q=get_stackid+path%3Aexamples&type=Code), 1352[search /tools](https://github.com/iovisor/bcc/search?q=get_stackid+path%3Atools&type=Code) 1353 1354### 26. map.perf_read() 1355 1356Syntax: ```u64 map.perf_read(u32 cpu)``` 1357 1358This returns the hardware performance counter as configured in [5. BPF_PERF_ARRAY](#5-bpf_perf_array) 1359 1360Examples in situ: 1361[search /tests](https://github.com/iovisor/bcc/search?q=perf_read+path%3Atests&type=Code) 1362 1363### 27. map.call() 1364 1365Syntax: ```void map.call(void *ctx, int index)``` 1366 1367This 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. 1368 1369For example: 1370 1371```C 1372BPF_PROG_ARRAY(prog_array, 10); 1373 1374int tail_call(void *ctx) { 1375 bpf_trace_printk("Tail-call\n"); 1376 return 0; 1377} 1378 1379int do_tail_call(void *ctx) { 1380 bpf_trace_printk("Original program\n"); 1381 prog_array.call(ctx, 2); 1382 return 0; 1383} 1384``` 1385 1386```Python 1387b = BPF(src_file="example.c") 1388tail_fn = b.load_func("tail_call", BPF.KPROBE) 1389prog_array = b.get_table("prog_array") 1390prog_array[c_int(2)] = c_int(tail_fn.fd) 1391b.attach_kprobe(event="some_kprobe_event", fn_name="do_tail_call") 1392``` 1393 1394This 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. 1395 1396**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)). 1397 1398Examples in situ: 1399[search /examples](https://github.com/iovisor/bcc/search?l=C&q=call+path%3Aexamples&type=Code), 1400[search /tests](https://github.com/iovisor/bcc/search?l=C&q=call+path%3Atests&type=Code) 1401 1402### 28. map.redirect_map() 1403 1404Syntax: ```int map.redirect_map(int index, int flags)``` 1405 1406This 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. 1407 1408If the packet is redirected successfully, the function will return XDP_REDIRECT. Otherwise, it will return XDP_ABORTED to discard the packet. 1409 1410For example: 1411```C 1412BPF_DEVMAP(devmap, 1); 1413 1414int redirect_example(struct xdp_md *ctx) { 1415 return devmap.redirect_map(0, 0); 1416} 1417int xdp_dummy(struct xdp_md *ctx) { 1418 return XDP_PASS; 1419} 1420``` 1421 1422```Python 1423ip = pyroute2.IPRoute() 1424idx = ip.link_lookup(ifname="eth1")[0] 1425 1426b = bcc.BPF(src_file="example.c") 1427 1428devmap = b.get_table("devmap") 1429devmap[c_uint32(0)] = c_int(idx) 1430 1431in_fn = b.load_func("redirect_example", BPF.XDP) 1432out_fn = b.load_func("xdp_dummy", BPF.XDP) 1433b.attach_xdp("eth0", in_fn, 0) 1434b.attach_xdp("eth1", out_fn, 0) 1435``` 1436 1437Examples in situ: 1438[search /examples](https://github.com/iovisor/bcc/search?l=C&q=redirect_map+path%3Aexamples&type=Code), 1439 1440### 29. map.push() 1441 1442Syntax: ```int map.push(&val, int flags)``` 1443 1444Push an element onto a Stack or Queue table. 1445Passing BPF_EXIST as a flag causes the Queue or Stack to discard the oldest element if it is full. 1446Returns 0 on success, negative error on failure. 1447 1448Examples in situ: 1449[search /tests](https://github.com/iovisor/bcc/search?q=push+path%3Atests&type=Code), 1450 1451### 30. map.pop() 1452 1453Syntax: ```int map.pop(&val)``` 1454 1455Pop an element from a Stack or Queue table. ```*val``` is populated with the result. 1456Unlike peeking, popping removes the element. 1457Returns 0 on success, negative error on failure. 1458 1459Examples in situ: 1460[search /tests](https://github.com/iovisor/bcc/search?q=pop+path%3Atests&type=Code), 1461 1462### 31. map.peek() 1463 1464Syntax: ```int map.peek(&val)``` 1465 1466Peek an element at the head of a Stack or Queue table. ```*val``` is populated with the result. 1467Unlike popping, peeking does not remove the element. 1468Returns 0 on success, negative error on failure. 1469 1470Examples in situ: 1471[search /tests](https://github.com/iovisor/bcc/search?q=peek+path%3Atests&type=Code), 1472 1473### 32. map.sock_hash_update() 1474 1475Syntax: ```int map.sock_hash_update(struct bpf_sock_ops *skops, &key, int flags)``` 1476 1477Add 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: 1478 1479``` 1480BPF_NOEXIST: The entry for key must not exist in the map. 1481BPF_EXIST: The entry for key must already exist in the map. 1482BPF_ANY: No condition on the existence of the entry for key. 1483``` 1484 1485If 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. 1486 1487Return 0 on success, or a negative error in case of failure. 1488 1489Examples in situ: 1490[search /tests](https://github.com/iovisor/bcc/search?q=sock_hash_update+path%3Atests&type=Code), 1491 1492### 33. map.msg_redirect_hash() 1493 1494Syntax: ```int map.msg_redirect_hash(struct sk_msg_buff *msg, void *key, u64 flags)``` 1495 1496This 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. 1497 1498Return SK_PASS on success, or SK_DROP on error. 1499 1500Examples in situ: 1501[search /tests](https://github.com/iovisor/bcc/search?q=msg_redirect_hash+path%3Atests&type=Code), 1502 1503### 34. map.sk_redirect_hash() 1504 1505Syntax: ```int map.sk_redirect_hash(struct sk_buff *skb, void *key, u64 flags)``` 1506 1507This 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. 1508 1509Return SK_PASS on success, or SK_DROP on error. 1510 1511Examples in situ: 1512[search /tests](https://github.com/iovisor/bcc/search?q=sk_redirect_hash+path%3Atests&type=Code), 1513 1514## Licensing 1515 1516Depending on which [BPF helpers](kernel-versions.md#helpers) are used, a GPL-compatible license is required. 1517 1518The 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: 1519 1520```C 1521// SPDX-License-Identifier: GPL-2.0+ 1522#define BPF_LICENSE GPL 1523``` 1524 1525Otherwise, 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: 1526 1527```C 1528// SPDX-License-Identifier: GPL-2.0+ OR BSD-2-Clause 1529#define BPF_LICENSE Dual BSD/GPL 1530``` 1531 1532Check the [BPF helpers reference](kernel-versions.md#helpers) to see which helpers are GPL-only and what the kernel understands as GPL-compatible. 1533 1534**If the macro is not specified, BCC will automatically define the license of the program as GPL.** 1535 1536## Rewriter 1537 1538One 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. 1539 1540# bcc Python 1541 1542## Initialization 1543 1544Constructors. 1545 1546### 1. BPF 1547 1548Syntax: ```BPF({text=BPF_program | src_file=filename} [, usdt_contexts=[USDT_object, ...]] [, cflags=[arg1, ...]] [, debug=int])``` 1549 1550Creates a BPF object. This is the main object for defining a BPF program, and interacting with its output. 1551 1552Exactly one of `text` or `src_file` must be supplied (not both). 1553 1554The `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"]`. 1555 1556The `debug` flags control debug output, and can be or'ed together: 1557- `DEBUG_LLVM_IR = 0x1` compiled LLVM IR 1558- `DEBUG_BPF = 0x2` loaded BPF bytecode and register state on branches 1559- `DEBUG_PREPROCESSOR = 0x4` pre-processor result 1560- `DEBUG_SOURCE = 0x8` ASM instructions embedded with source 1561- `DEBUG_BPF_REGISTER_STATE = 0x10` register state on all instructions in addition to DEBUG_BPF 1562- `DEBUG_BTF = 0x20` print the messages from the `libbpf` library. 1563 1564Examples: 1565 1566```Python 1567# define entire BPF program in one line: 1568BPF(text='int do_trace(void *ctx) { bpf_trace_printk("hit!\\n"); return 0; }'); 1569 1570# define program as a variable: 1571prog = """ 1572int hello(void *ctx) { 1573 bpf_trace_printk("Hello, World!\\n"); 1574 return 0; 1575} 1576""" 1577b = BPF(text=prog) 1578 1579# source a file: 1580b = BPF(src_file = "vfsreadlat.c") 1581 1582# include a USDT object: 1583u = USDT(pid=int(pid)) 1584[...] 1585b = BPF(text=bpf_text, usdt_contexts=[u]) 1586 1587# add include paths: 1588u = BPF(text=prog, cflags=["-I/path/to/include"]) 1589``` 1590 1591Examples in situ: 1592[search /examples](https://github.com/iovisor/bcc/search?q=BPF+path%3Aexamples+language%3Apython&type=Code), 1593[search /tools](https://github.com/iovisor/bcc/search?q=BPF+path%3Atools+language%3Apython&type=Code) 1594 1595### 2. USDT 1596 1597Syntax: ```USDT({pid=pid | path=path})``` 1598 1599Creates an object to instrument User Statically-Defined Tracing (USDT) probes. Its primary method is ```enable_probe()```. 1600 1601Arguments: 1602 1603- pid: attach to this process ID. 1604- path: instrument USDT probes from this binary path. 1605 1606Examples: 1607 1608```Python 1609# include a USDT object: 1610u = USDT(pid=int(pid)) 1611[...] 1612b = BPF(text=bpf_text, usdt_contexts=[u]) 1613``` 1614 1615Examples in situ: 1616[search /examples](https://github.com/iovisor/bcc/search?q=USDT+path%3Aexamples+language%3Apython&type=Code), 1617[search /tools](https://github.com/iovisor/bcc/search?q=USDT+path%3Atools+language%3Apython&type=Code) 1618 1619## Events 1620 1621### 1. attach_kprobe() 1622 1623Syntax: ```BPF.attach_kprobe(event="event", fn_name="name")``` 1624 1625Instruments 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. 1626 1627For example: 1628 1629```Python 1630b.attach_kprobe(event="sys_clone", fn_name="do_trace") 1631``` 1632 1633This will instrument the kernel ```sys_clone()``` function, which will then run our BPF defined ```do_trace()``` function each time it is called. 1634 1635You can call attach_kprobe() more than once, and attach your BPF function to multiple kernel functions. 1636You can also call attach_kprobe() more than once to attach multiple BPF functions to the same kernel function. 1637 1638See the previous kprobes section for how to instrument arguments from BPF. 1639 1640Examples in situ: 1641[search /examples](https://github.com/iovisor/bcc/search?q=attach_kprobe+path%3Aexamples+language%3Apython&type=Code), 1642[search /tools](https://github.com/iovisor/bcc/search?q=attach_kprobe+path%3Atools+language%3Apython&type=Code) 1643 1644### 2. attach_kretprobe() 1645 1646Syntax: ```BPF.attach_kretprobe(event="event", fn_name="name" [, maxactive=int])``` 1647 1648Instruments 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. 1649 1650For example: 1651 1652```Python 1653b.attach_kretprobe(event="vfs_read", fn_name="do_return") 1654``` 1655 1656This will instrument the kernel ```vfs_read()``` function, which will then run our BPF defined ```do_return()``` function each time it is called. 1657 1658You can call attach_kretprobe() more than once, and attach your BPF function to multiple kernel function returns. 1659You can also call attach_kretprobe() more than once to attach multiple BPF functions to the same kernel function return. 1660 1661When 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. 1662 1663See the previous kretprobes section for how to instrument the return value from BPF. 1664 1665Examples in situ: 1666[search /examples](https://github.com/iovisor/bcc/search?q=attach_kretprobe+path%3Aexamples+language%3Apython&type=Code), 1667[search /tools](https://github.com/iovisor/bcc/search?q=attach_kretprobe+path%3Atools+language%3Apython&type=Code) 1668 1669### 3. attach_tracepoint() 1670 1671Syntax: ```BPF.attach_tracepoint(tp="tracepoint", fn_name="name")``` 1672 1673Instruments the kernel tracepoint described by ```tracepoint```, and when hit, runs the BPF function ```name()```. 1674 1675This 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. 1676 1677For example: 1678 1679```Python 1680# define BPF program 1681bpf_text = """ 1682#include <uapi/linux/ptrace.h> 1683 1684struct urandom_read_args { 1685 // from /sys/kernel/debug/tracing/events/random/urandom_read/format 1686 u64 __unused__; 1687 u32 got_bits; 1688 u32 pool_left; 1689 u32 input_left; 1690}; 1691 1692int printarg(struct urandom_read_args *args) { 1693 bpf_trace_printk("%d\\n", args->got_bits); 1694 return 0; 1695}; 1696""" 1697 1698# load BPF program 1699b = BPF(text=bpf_text) 1700b.attach_tracepoint("random:urandom_read", "printarg") 1701``` 1702 1703Notice how the first argument to ```printarg()``` is now our defined struct. 1704 1705Examples in situ: 1706[code](https://github.com/iovisor/bcc/blob/a4159da8c4ea8a05a3c6e402451f530d6e5a8b41/examples/tracing/urandomread-explicit.py#L41), 1707[search /examples](https://github.com/iovisor/bcc/search?q=attach_tracepoint+path%3Aexamples+language%3Apython&type=Code), 1708[search /tools](https://github.com/iovisor/bcc/search?q=attach_tracepoint+path%3Atools+language%3Apython&type=Code) 1709 1710### 4. attach_uprobe() 1711 1712Syntax: ```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")``` 1713 1714 1715Instruments 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. 1716 1717The 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. 1718 1719Instead 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. 1720 1721Libraries 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). 1722 1723For example: 1724 1725```Python 1726b.attach_uprobe(name="c", sym="strlen", fn_name="count") 1727``` 1728 1729This 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. 1730 1731Other examples: 1732 1733```Python 1734b.attach_uprobe(name="c", sym="getaddrinfo", fn_name="do_entry") 1735b.attach_uprobe(name="/usr/bin/python", sym="main", fn_name="do_main") 1736``` 1737 1738You can call attach_uprobe() more than once, and attach your BPF function to multiple user-level functions. 1739 1740See the previous uprobes section for how to instrument arguments from BPF. 1741 1742Examples in situ: 1743[search /examples](https://github.com/iovisor/bcc/search?q=attach_uprobe+path%3Aexamples+language%3Apython&type=Code), 1744[search /tools](https://github.com/iovisor/bcc/search?q=attach_uprobe+path%3Atools+language%3Apython&type=Code) 1745 1746### 5. attach_uretprobe() 1747 1748Syntax: ```BPF.attach_uretprobe(name="location", sym="symbol", fn_name="name")``` 1749 1750Instruments 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. 1751 1752For example: 1753 1754```Python 1755b.attach_uretprobe(name="c", sym="strlen", fn_name="count") 1756``` 1757 1758This will instrument ```strlen()``` function from libc, and call our BPF function ```count()``` when it returns. 1759 1760Other examples: 1761 1762```Python 1763b.attach_uretprobe(name="c", sym="getaddrinfo", fn_name="do_return") 1764b.attach_uretprobe(name="/usr/bin/python", sym="main", fn_name="do_main") 1765``` 1766 1767You can call attach_uretprobe() more than once, and attach your BPF function to multiple user-level functions. 1768 1769See the previous uretprobes section for how to instrument the return value from BPF. 1770 1771Examples in situ: 1772[search /examples](https://github.com/iovisor/bcc/search?q=attach_uretprobe+path%3Aexamples+language%3Apython&type=Code), 1773[search /tools](https://github.com/iovisor/bcc/search?q=attach_uretprobe+path%3Atools+language%3Apython&type=Code) 1774 1775### 6. USDT.enable_probe() 1776 1777Syntax: ```USDT.enable_probe(probe=probe, fn_name=name)``` 1778 1779Attaches a BPF C function ```name``` to the USDT probe ```probe```. 1780 1781Example: 1782 1783```Python 1784# enable USDT probe from given PID 1785u = USDT(pid=int(pid)) 1786u.enable_probe(probe="http__server__request", fn_name="do_trace") 1787``` 1788 1789To check if your binary has USDT probes, and what they are, you can run ```readelf -n binary``` and check the stap debug section. 1790 1791Examples in situ: 1792[search /examples](https://github.com/iovisor/bcc/search?q=enable_probe+path%3Aexamples+language%3Apython&type=Code), 1793[search /tools](https://github.com/iovisor/bcc/search?q=enable_probe+path%3Atools+language%3Apython&type=Code) 1794 1795### 7. attach_raw_tracepoint() 1796 1797Syntax: ```BPF.attach_raw_tracepoint(tp="tracepoint", fn_name="name")``` 1798 1799Instruments the kernel raw tracepoint described by ```tracepoint``` (```event``` only, no ```category```), and when hit, runs the BPF function ```name()```. 1800 1801This is an explicit way to instrument tracepoints. The ```RAW_TRACEPOINT_PROBE``` syntax, covered in the earlier raw tracepoints section, is an alternate method. 1802 1803For example: 1804 1805```Python 1806b.attach_raw_tracepoint("sched_switch", "do_trace") 1807``` 1808 1809Examples in situ: 1810[search /tools](https://github.com/iovisor/bcc/search?q=attach_raw_tracepoint+path%3Atools+language%3Apython&type=Code) 1811 1812### 8. attach_raw_socket() 1813 1814Syntax: ```BPF.attach_raw_socket(fn, dev)``` 1815 1816Attaches a BPF function to the specified network interface. 1817 1818The ```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)```) 1819 1820```fn.sock``` is a non-blocking raw socket that was created and bound to ```dev```. 1821 1822All 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. 1823 1824We can use this feature to capture network packets just like ```tcpdump```. 1825 1826We can use ```ss --bpf --packet -p``` to observe ```fn.sock```. 1827 1828Example: 1829 1830```Python 1831BPF.attach_raw_socket(bpf_func, ifname) 1832``` 1833 1834Examples in situ: 1835[search /examples](https://github.com/iovisor/bcc/search?q=attach_raw_socket+path%3Aexamples+language%3Apython&type=Code) 1836### 9. attach_xdp() 1837Syntax: ```BPF.attach_xdp(dev="device", fn=b.load_func("fn_name",BPF.XDP), flags)``` 1838 1839Instruments the network driver described by ```dev``` , and then receives the packet, run the BPF function ```fn_name()``` with flags. 1840 1841Here is a list of optional flags. 1842 1843```Python 1844# from xdp_flags uapi/linux/if_link.h 1845XDP_FLAGS_UPDATE_IF_NOEXIST = (1 << 0) 1846XDP_FLAGS_SKB_MODE = (1 << 1) 1847XDP_FLAGS_DRV_MODE = (1 << 2) 1848XDP_FLAGS_HW_MODE = (1 << 3) 1849XDP_FLAGS_REPLACE = (1 << 4) 1850``` 1851 1852You 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)``` 1853 1854The 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. 1855 1856Currently, bcc does not support XDP_FLAGS_REPLACE flag. The following are the descriptions of other flags. 1857 1858#### 1. XDP_FLAGS_UPDATE_IF_NOEXIST 1859If an XDP program is already attached to the specified driver, attaching the XDP program again will fail. 1860 1861#### 2. XDP_FLAGS_SKB_MODE 1862Driver doesn’t have support for XDP, but the kernel fakes it. 1863XDP 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. 1864 1865#### 3. XDP_FLAGS_DRV_MODE 1866A 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. 1867 1868#### 4. XDP_FLAGS_HW_MODE 1869XDP can be loaded and executed directly on the NIC – just a handful of NICs can do that. 1870 1871 1872For example: 1873 1874```Python 1875b.attach_xdp(dev="ens1", fn=b.load_func("do_xdp", BPF.XDP)) 1876``` 1877 1878This will instrument the network device ```ens1``` , which will then run our BPF defined ```do_xdp()``` function each time it receives packets. 1879 1880Don't forget to call ```b.remove_xdp("ens1")``` at the end! 1881 1882Examples in situ: 1883[search /examples](https://github.com/iovisor/bcc/search?q=attach_xdp+path%3Aexamples+language%3Apython&type=Code), 1884[search /tools](https://github.com/iovisor/bcc/search?q=attach_xdp+path%3Atools+language%3Apython&type=Code) 1885 1886### 10. attach_func() 1887 1888Syntax: ```BPF.attach_func(fn, attachable_fd, attach_type [, flags])``` 1889 1890Attaches 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. 1891 1892For example: 1893 1894```Python 1895b.attach_func(fn, cgroup_fd, BPFAttachType.CGROUP_SOCK_OPS) 1896b.attach_func(fn, map_fd, BPFAttachType.SK_MSG_VERDICT) 1897``` 1898 1899Note. 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. 1900 1901Examples in situ: 1902 1903[search /examples](https://github.com/iovisor/bcc/search?q=attach_func+path%3Aexamples+language%3Apython&type=Code), 1904 1905### 11. detach_func() 1906 1907Syntax: ```BPF.detach_func(fn, attachable_fd, attach_type)``` 1908 1909Detaches a BPF function of the specified type. 1910 1911For example: 1912 1913```Python 1914b.detach_func(fn, cgroup_fd, BPFAttachType.CGROUP_SOCK_OPS) 1915b.detach_func(fn, map_fd, BPFAttachType.SK_MSG_VERDICT) 1916``` 1917 1918Examples in situ: 1919 1920[search /examples](https://github.com/iovisor/bcc/search?q=detach_func+path%3Aexamples+language%3Apython&type=Code), 1921 1922### 12. detach_kprobe() 1923 1924Syntax: ```BPF.detach_kprobe(event="event", fn_name="name")``` 1925 1926Detach a kprobe handler function of the specified event. 1927 1928For example: 1929 1930```Python 1931b.detach_kprobe(event="__page_cache_alloc", fn_name="trace_func_entry") 1932``` 1933 1934### 13. detach_kretprobe() 1935 1936Syntax: ```BPF.detach_kretprobe(event="event", fn_name="name")``` 1937 1938Detach a kretprobe handler function of the specified event. 1939 1940For example: 1941 1942```Python 1943b.detach_kretprobe(event="__page_cache_alloc", fn_name="trace_func_return") 1944``` 1945 1946## Debug Output 1947 1948### 1. trace_print() 1949 1950Syntax: ```BPF.trace_print(fmt="fields")``` 1951 1952This 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. 1953 1954Arguments: 1955 1956- ```fmt```: optional, and can contain a field formatting string. It defaults to ```None```. 1957 1958Examples: 1959 1960```Python 1961# print trace_pipe output as-is: 1962b.trace_print() 1963 1964# print PID and message: 1965b.trace_print(fmt="{1} {5}") 1966``` 1967 1968Examples in situ: 1969[search /examples](https://github.com/iovisor/bcc/search?q=trace_print+path%3Aexamples+language%3Apython&type=Code), 1970[search /tools](https://github.com/iovisor/bcc/search?q=trace_print+path%3Atools+language%3Apython&type=Code) 1971 1972### 2. trace_fields() 1973 1974Syntax: ```BPF.trace_fields(nonblocking=False)``` 1975 1976This 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. 1977 1978Arguments: 1979 1980- ```nonblocking```: optional, defaults to ```False```. When set to ```True```, the program will not block waiting for input. 1981 1982Examples: 1983 1984```Python 1985while 1: 1986 try: 1987 (task, pid, cpu, flags, ts, msg) = b.trace_fields() 1988 except ValueError: 1989 continue 1990 [...] 1991``` 1992 1993Examples in situ: 1994[search /examples](https://github.com/iovisor/bcc/search?q=trace_fields+path%3Aexamples+language%3Apython&type=Code), 1995[search /tools](https://github.com/iovisor/bcc/search?q=trace_fields+path%3Atools+language%3Apython&type=Code) 1996 1997## Output APIs 1998 1999Normal output from a BPF program is either: 2000 2001- per-event: using PERF_EVENT_OUTPUT, open_perf_buffer(), and perf_buffer_poll(). 2002- map summary: using items(), or print_log2_hist(), covered in the Maps section. 2003 2004### 1. perf_buffer_poll() 2005 2006Syntax: ```BPF.perf_buffer_poll(timeout=T)``` 2007 2008This polls from all open perf ring buffers, calling the callback function that was provided when calling open_perf_buffer for each entry. 2009 2010The timeout parameter is optional and measured in milliseconds. In its absence, polling continues indefinitely. 2011 2012Example: 2013 2014```Python 2015# loop with callback to print_event 2016b["events"].open_perf_buffer(print_event) 2017while 1: 2018 try: 2019 b.perf_buffer_poll() 2020 except KeyboardInterrupt: 2021 exit(); 2022``` 2023 2024Examples in situ: 2025[code](https://github.com/iovisor/bcc/blob/v0.9.0/examples/tracing/hello_perf_output.py#L55), 2026[search /examples](https://github.com/iovisor/bcc/search?q=perf_buffer_poll+path%3Aexamples+language%3Apython&type=Code), 2027[search /tools](https://github.com/iovisor/bcc/search?q=perf_buffer_poll+path%3Atools+language%3Apython&type=Code) 2028 2029### 2. ring_buffer_poll() 2030 2031Syntax: ```BPF.ring_buffer_poll(timeout=T)``` 2032 2033This polls from all open ringbuf ring buffers, calling the callback function that was provided when calling open_ring_buffer for each entry. 2034 2035The timeout parameter is optional and measured in milliseconds. In its absence, polling continues until 2036there is no more data or the callback returns a negative value. 2037 2038Example: 2039 2040```Python 2041# loop with callback to print_event 2042b["events"].open_ring_buffer(print_event) 2043while 1: 2044 try: 2045 b.ring_buffer_poll(30) 2046 except KeyboardInterrupt: 2047 exit(); 2048``` 2049 2050Examples in situ: 2051[search /examples](https://github.com/iovisor/bcc/search?q=ring_buffer_poll+path%3Aexamples+language%3Apython&type=Code), 2052 2053### 3. ring_buffer_consume() 2054 2055Syntax: ```BPF.ring_buffer_consume()``` 2056 2057This consumes from all open ringbuf ring buffers, calling the callback function that was provided when calling open_ring_buffer for each entry. 2058 2059Unlike ```ring_buffer_poll```, this method **does not poll for data** before attempting to consume. 2060This reduces latency at the expense of higher CPU consumption. If you are unsure which to use, 2061use ```ring_buffer_poll```. 2062 2063Example: 2064 2065```Python 2066# loop with callback to print_event 2067b["events"].open_ring_buffer(print_event) 2068while 1: 2069 try: 2070 b.ring_buffer_consume() 2071 except KeyboardInterrupt: 2072 exit(); 2073``` 2074 2075Examples in situ: 2076[search /examples](https://github.com/iovisor/bcc/search?q=ring_buffer_consume+path%3Aexamples+language%3Apython&type=Code), 2077 2078## Map APIs 2079 2080Maps 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. 2081 2082### 1. get_table() 2083 2084Syntax: ```BPF.get_table(name)``` 2085 2086Returns a table object. This is no longer used, as tables can now be read as items from BPF. Eg: ```BPF[name]```. 2087 2088Examples: 2089 2090```Python 2091counts = b.get_table("counts") 2092 2093counts = b["counts"] 2094``` 2095 2096These are equivalent. 2097 2098### 2. open_perf_buffer() 2099 2100Syntax: ```table.open_perf_buffers(callback, page_cnt=N, lost_cb=None)``` 2101 2102This 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```. 2103 2104Example: 2105 2106```Python 2107# process event 2108def print_event(cpu, data, size): 2109 event = ct.cast(data, ct.POINTER(Data)).contents 2110 [...] 2111 2112# loop with callback to print_event 2113b["events"].open_perf_buffer(print_event) 2114while 1: 2115 try: 2116 b.perf_buffer_poll() 2117 except KeyboardInterrupt: 2118 exit() 2119``` 2120 2121Note that the data structure transferred will need to be declared in C in the BPF program. For example: 2122 2123```C 2124// define output data structure in C 2125struct data_t { 2126 u32 pid; 2127 u64 ts; 2128 char comm[TASK_COMM_LEN]; 2129}; 2130BPF_PERF_OUTPUT(events); 2131[...] 2132``` 2133 2134In Python, you can either let bcc generate the data structure from C declaration automatically (recommended): 2135 2136```Python 2137def print_event(cpu, data, size): 2138 event = b["events"].event(data) 2139[...] 2140``` 2141 2142or define it manually: 2143 2144```Python 2145# define output data structure in Python 2146TASK_COMM_LEN = 16 # linux/sched.h 2147class Data(ct.Structure): 2148 _fields_ = [("pid", ct.c_ulonglong), 2149 ("ts", ct.c_ulonglong), 2150 ("comm", ct.c_char * TASK_COMM_LEN)] 2151 2152def print_event(cpu, data, size): 2153 event = ct.cast(data, ct.POINTER(Data)).contents 2154[...] 2155``` 2156 2157Examples in situ: 2158[code](https://github.com/iovisor/bcc/blob/v0.9.0/examples/tracing/hello_perf_output.py#L52), 2159[search /examples](https://github.com/iovisor/bcc/search?q=open_perf_buffer+path%3Aexamples+language%3Apython&type=Code), 2160[search /tools](https://github.com/iovisor/bcc/search?q=open_perf_buffer+path%3Atools+language%3Apython&type=Code) 2161 2162### 3. items() 2163 2164Syntax: ```table.items()``` 2165 2166Returns an array of the keys in a table. This can be used with BPF_HASH maps to fetch, and iterate, over the keys. 2167 2168Example: 2169 2170```Python 2171# print output 2172print("%10s %s" % ("COUNT", "STRING")) 2173counts = b.get_table("counts") 2174for k, v in sorted(counts.items(), key=lambda counts: counts[1].value): 2175 print("%10d \"%s\"" % (v.value, k.c.encode('string-escape'))) 2176``` 2177 2178This example also uses the ```sorted()``` method to sort by value. 2179 2180Examples in situ: 2181[search /examples](https://github.com/iovisor/bcc/search?q=items+path%3Aexamples+language%3Apython&type=Code), 2182[search /tools](https://github.com/iovisor/bcc/search?q=items+path%3Atools+language%3Apython&type=Code) 2183 2184### 4. values() 2185 2186Syntax: ```table.values()``` 2187 2188Returns an array of the values in a table. 2189 2190### 5. clear() 2191 2192Syntax: ```table.clear()``` 2193 2194Clears the table: deletes all entries. 2195 2196Example: 2197 2198```Python 2199# print map summary every second: 2200while True: 2201 time.sleep(1) 2202 print("%-8s\n" % time.strftime("%H:%M:%S"), end="") 2203 dist.print_log2_hist(sym + " return:") 2204 dist.clear() 2205``` 2206 2207Examples in situ: 2208[search /examples](https://github.com/iovisor/bcc/search?q=clear+path%3Aexamples+language%3Apython&type=Code), 2209[search /tools](https://github.com/iovisor/bcc/search?q=clear+path%3Atools+language%3Apython&type=Code) 2210 2211### 6. items_lookup_and_delete_batch() 2212 2213Syntax: ```table.items_lookup_and_delete_batch()``` 2214 2215Returns 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. 2216You should rather use table.items_lookup_and_delete_batch() than table.items() followed by table.clear(). It requires kernel v5.6. 2217 2218Example: 2219 2220```Python 2221# print call rate per second: 2222print("%9s-%9s-%8s-%9s" % ("PID", "COMM", "fname", "counter")) 2223while True: 2224 for k, v in sorted(b['map'].items_lookup_and_delete_batch(), key=lambda kv: (kv[0]).pid): 2225 print("%9s-%9s-%8s-%9d" % (k.pid, k.comm, k.fname, v.counter)) 2226 sleep(1) 2227``` 2228 2229### 7. items_lookup_batch() 2230 2231Syntax: ```table.items_lookup_batch()``` 2232 2233Returns 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. 2234You should rather use table.items_lookup_batch() than table.items(). It requires kernel v5.6. 2235 2236Example: 2237 2238```Python 2239# print current value of map: 2240print("%9s-%9s-%8s-%9s" % ("PID", "COMM", "fname", "counter")) 2241while True: 2242 for k, v in sorted(b['map'].items_lookup_batch(), key=lambda kv: (kv[0]).pid): 2243 print("%9s-%9s-%8s-%9d" % (k.pid, k.comm, k.fname, v.counter)) 2244``` 2245 2246### 8. items_delete_batch() 2247 2248Syntax: ```table.items_delete_batch(keys)``` 2249 2250It 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. 2251 2252Arguments: 2253 2254- keys is optional and by default is None. 2255 2256 2257 2258### 9. items_update_batch() 2259 2260Syntax: ```table.items_update_batch(keys, values)``` 2261 2262Update 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. 2263 2264Arguments: 2265 2266- keys is the list of keys to be updated 2267- values is the list containing the new values. 2268 2269 2270### 10. print_log2_hist() 2271 2272Syntax: ```table.print_log2_hist(val_type="value", section_header="Bucket ptr", section_print_fn=None)``` 2273 2274Prints 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()```. 2275 2276Arguments: 2277 2278- val_type: optional, column header. 2279- 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. 2280- section_print_fn: if section_print_fn is not None, it will be passed the bucket value. 2281 2282Example: 2283 2284```Python 2285b = BPF(text=""" 2286BPF_HISTOGRAM(dist); 2287 2288int kprobe__blk_account_io_done(struct pt_regs *ctx, struct request *req) 2289{ 2290 dist.increment(bpf_log2l(req->__data_len / 1024)); 2291 return 0; 2292} 2293""") 2294[...] 2295 2296b["dist"].print_log2_hist("kbytes") 2297``` 2298 2299Output: 2300 2301``` 2302 kbytes : count distribution 2303 0 -> 1 : 3 | | 2304 2 -> 3 : 0 | | 2305 4 -> 7 : 211 |********** | 2306 8 -> 15 : 0 | | 2307 16 -> 31 : 0 | | 2308 32 -> 63 : 0 | | 2309 64 -> 127 : 1 | | 2310 128 -> 255 : 800 |**************************************| 2311``` 2312 2313This output shows a multi-modal distribution, with the largest mode of 128->255 kbytes and a count of 800. 2314 2315This is an efficient way to summarize data, as the summarization is performed in-kernel, and only the count column is passed to user space. 2316 2317Examples in situ: 2318[search /examples](https://github.com/iovisor/bcc/search?q=print_log2_hist+path%3Aexamples+language%3Apython&type=Code), 2319[search /tools](https://github.com/iovisor/bcc/search?q=print_log2_hist+path%3Atools+language%3Apython&type=Code) 2320 2321### 11. print_linear_hist() 2322 2323Syntax: ```table.print_linear_hist(val_type="value", section_header="Bucket ptr", section_print_fn=None)``` 2324 2325Prints a table as a linear histogram in ASCII. This is intended to visualize small integer ranges, eg, 0 to 100. 2326 2327Arguments: 2328 2329- val_type: optional, column header. 2330- 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. 2331- section_print_fn: if section_print_fn is not None, it will be passed the bucket value. 2332 2333Example: 2334 2335```Python 2336b = BPF(text=""" 2337BPF_HISTOGRAM(dist); 2338 2339int kprobe__blk_account_io_done(struct pt_regs *ctx, struct request *req) 2340{ 2341 dist.increment(req->__data_len / 1024); 2342 return 0; 2343} 2344""") 2345[...] 2346 2347b["dist"].print_linear_hist("kbytes") 2348``` 2349 2350Output: 2351 2352``` 2353 kbytes : count distribution 2354 0 : 3 |****** | 2355 1 : 0 | | 2356 2 : 0 | | 2357 3 : 0 | | 2358 4 : 19 |****************************************| 2359 5 : 0 | | 2360 6 : 0 | | 2361 7 : 0 | | 2362 8 : 4 |******** | 2363 9 : 0 | | 2364 10 : 0 | | 2365 11 : 0 | | 2366 12 : 0 | | 2367 13 : 0 | | 2368 14 : 0 | | 2369 15 : 0 | | 2370 16 : 2 |**** | 2371[...] 2372``` 2373 2374This 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. 2375 2376Examples in situ: 2377[search /examples](https://github.com/iovisor/bcc/search?q=print_linear_hist+path%3Aexamples+language%3Apython&type=Code), 2378[search /tools](https://github.com/iovisor/bcc/search?q=print_linear_hist+path%3Atools+language%3Apython&type=Code) 2379 2380### 12. open_ring_buffer() 2381 2382Syntax: ```table.open_ring_buffer(callback, ctx=None)``` 2383 2384This 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. 2385 2386Example: 2387 2388```Python 2389# process event 2390def print_event(ctx, data, size): 2391 event = ct.cast(data, ct.POINTER(Data)).contents 2392 [...] 2393 2394# loop with callback to print_event 2395b["events"].open_ring_buffer(print_event) 2396while 1: 2397 try: 2398 b.ring_buffer_poll() 2399 except KeyboardInterrupt: 2400 exit() 2401``` 2402 2403Note that the data structure transferred will need to be declared in C in the BPF program. For example: 2404 2405```C 2406// define output data structure in C 2407struct data_t { 2408 u32 pid; 2409 u64 ts; 2410 char comm[TASK_COMM_LEN]; 2411}; 2412BPF_RINGBUF_OUTPUT(events, 8); 2413[...] 2414``` 2415 2416In Python, you can either let bcc generate the data structure from C declaration automatically (recommended): 2417 2418```Python 2419def print_event(ctx, data, size): 2420 event = b["events"].event(data) 2421[...] 2422``` 2423 2424or define it manually: 2425 2426```Python 2427# define output data structure in Python 2428TASK_COMM_LEN = 16 # linux/sched.h 2429class Data(ct.Structure): 2430 _fields_ = [("pid", ct.c_ulonglong), 2431 ("ts", ct.c_ulonglong), 2432 ("comm", ct.c_char * TASK_COMM_LEN)] 2433 2434def print_event(ctx, data, size): 2435 event = ct.cast(data, ct.POINTER(Data)).contents 2436[...] 2437``` 2438 2439Examples in situ: 2440[search /examples](https://github.com/iovisor/bcc/search?q=open_ring_buffer+path%3Aexamples+language%3Apython&type=Code), 2441 2442### 13. push() 2443 2444Syntax: ```table.push(leaf, flags=0)``` 2445 2446Push an element onto a Stack or Queue table. Raises an exception if the operation does not succeed. 2447Passing QueueStack.BPF_EXIST as a flag causes the Queue or Stack to discard the oldest element if it is full. 2448 2449Examples in situ: 2450[search /tests](https://github.com/iovisor/bcc/search?q=push+path%3Atests+language%3Apython&type=Code), 2451 2452### 14. pop() 2453 2454Syntax: ```leaf = table.pop()``` 2455 2456Pop an element from a Stack or Queue table. Unlike ```peek()```, ```pop()``` 2457removes the element from the table before returning it. 2458Raises a KeyError exception if the operation does not succeed. 2459 2460Examples in situ: 2461[search /tests](https://github.com/iovisor/bcc/search?q=pop+path%3Atests+language%3Apython&type=Code), 2462 2463### 15. peek() 2464 2465Syntax: ```leaf = table.peek()``` 2466 2467Peek the element at the head of a Stack or Queue table. Unlike ```pop()```, ```peek()``` 2468does not remove the element from the table. Raises an exception if the operation does not succeed. 2469 2470Examples in situ: 2471[search /tests](https://github.com/iovisor/bcc/search?q=peek+path%3Atests+language%3Apython&type=Code), 2472 2473## Helpers 2474 2475Some 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. 2476 2477### 1. ksym() 2478 2479Syntax: ```BPF.ksym(addr)``` 2480 2481Translate a kernel memory address into a kernel function name, which is returned. 2482 2483Example: 2484 2485```Python 2486print("kernel function: " + b.ksym(addr)) 2487``` 2488 2489Examples in situ: 2490[search /examples](https://github.com/iovisor/bcc/search?q=ksym+path%3Aexamples+language%3Apython&type=Code), 2491[search /tools](https://github.com/iovisor/bcc/search?q=ksym+path%3Atools+language%3Apython&type=Code) 2492 2493### 2. ksymname() 2494 2495Syntax: ```BPF.ksymname(name)``` 2496 2497Translate a kernel name into an address. This is the reverse of ksym. Returns -1 when the function name is unknown. 2498 2499Example: 2500 2501```Python 2502print("kernel address: %x" % b.ksymname("vfs_read")) 2503``` 2504 2505Examples in situ: 2506[search /examples](https://github.com/iovisor/bcc/search?q=ksymname+path%3Aexamples+language%3Apython&type=Code), 2507[search /tools](https://github.com/iovisor/bcc/search?q=ksymname+path%3Atools+language%3Apython&type=Code) 2508 2509### 3. sym() 2510 2511Syntax: ```BPF.sym(addr, pid, show_module=False, show_offset=False)``` 2512 2513Translate 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`. 2514 2515Example: 2516 2517```Python 2518print("function: " + b.sym(addr, pid)) 2519``` 2520 2521Examples in situ: 2522[search /examples](https://github.com/iovisor/bcc/search?q=sym+path%3Aexamples+language%3Apython&type=Code), 2523[search /tools](https://github.com/iovisor/bcc/search?q=sym+path%3Atools+language%3Apython&type=Code) 2524 2525### 4. num_open_kprobes() 2526 2527Syntax: ```BPF.num_open_kprobes()``` 2528 2529Returns 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. 2530 2531Example: 2532 2533```Python 2534b.attach_kprobe(event_re=pattern, fn_name="trace_count") 2535matched = b.num_open_kprobes() 2536if matched == 0: 2537 print("0 functions matched by \"%s\". Exiting." % args.pattern) 2538 exit() 2539``` 2540 2541Examples in situ: 2542[search /examples](https://github.com/iovisor/bcc/search?q=num_open_kprobes+path%3Aexamples+language%3Apython&type=Code), 2543[search /tools](https://github.com/iovisor/bcc/search?q=num_open_kprobes+path%3Atools+language%3Apython&type=Code) 2544 2545### 5. get_syscall_fnname() 2546 2547Syntax: ```BPF.get_syscall_fnname(name : str)``` 2548 2549Return 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)) 2550 2551Example: 2552 2553```Python 2554print("The function name of %s in kernel is %s" % ("clone", b.get_syscall_fnname("clone"))) 2555# sys_clone or __x64_sys_clone or ... 2556``` 2557 2558Examples in situ: 2559[search /examples](https://github.com/iovisor/bcc/search?q=get_syscall_fnname+path%3Aexamples+language%3Apython&type=Code), 2560[search /tools](https://github.com/iovisor/bcc/search?q=get_syscall_fnname+path%3Atools+language%3Apython&type=Code) 2561 2562# BPF Errors 2563 2564See the "Understanding eBPF verifier messages" section in the kernel source under Documentation/networking/filter.txt. 2565 2566## 1. Invalid mem access 2567 2568This 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. 2569 2570Example: 2571 2572``` 2573bpf: Permission denied 25740: (bf) r6 = r1 25751: (79) r7 = *(u64 *)(r6 +80) 25762: (85) call 14 25773: (bf) r8 = r0 2578[...] 257923: (69) r1 = *(u16 *)(r7 +16) 2580R7 invalid mem access 'inv' 2581 2582Traceback (most recent call last): 2583 File "./tcpaccept", line 179, in <module> 2584 b = BPF(text=bpf_text) 2585 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 172, in __init__ 2586 self._trace_autoload() 2587 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 612, in _trace_autoload 2588 fn = self.load_func(func_name, BPF.KPROBE) 2589 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 212, in load_func 2590 raise Exception("Failed to load BPF program %s" % func_name) 2591Exception: Failed to load BPF program kretprobe__inet_csk_accept 2592``` 2593 2594## 2. Cannot call GPL only function from proprietary program 2595 2596This 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. 2597 2598Example calling `bpf_get_stackid()`, a GPL-only BPF helper, from a proprietary program (`#define BPF_LICENSE Proprietary`): 2599 2600``` 2601bpf: Failed to load program: Invalid argument 2602[...] 26038: (85) call bpf_get_stackid#27 2604cannot call GPL only function from proprietary program 2605``` 2606 2607# Environment Variables 2608 2609## 1. Kernel source directory 2610 2611eBPF program compilation needs kernel sources or kernel headers with headers 2612compiled. In case your kernel sources are at a non-standard location where BCC 2613cannot find then, its possible to provide BCC the absolute path of the location 2614by setting `BCC_KERNEL_SOURCE` to it. 2615 2616## 2. Kernel version overriding 2617 2618By default, BCC stores the `LINUX_VERSION_CODE` in the generated eBPF object 2619which is then passed along to the kernel when the eBPF program is loaded. 2620Sometimes this is quite inconvenient especially when the kernel is slightly 2621updated such as an LTS kernel release. Its extremely unlikely the slight 2622mismatch would cause any issues with the loaded eBPF program. By setting 2623`BCC_LINUX_VERSION_CODE` to the version of the kernel that's running, the check 2624for verifying the kernel version can be bypassed. This is needed for programs 2625that use kprobes. This needs to be encoded in the format: `(VERSION * 65536) + 2626(PATCHLEVEL * 256) + SUBLEVEL`. For example, if the running kernel is `4.9.10`, 2627then can set `export BCC_LINUX_VERSION_CODE=264458` to override the kernel 2628version check successfully. 2629