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