575867d694965cc65ad52910a1850442d52a5f34
[platform/kernel/linux-rpi.git] / tools / lib / bpf / bpf.c
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2
3 /*
4  * common eBPF ELF operations.
5  *
6  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
7  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
8  * Copyright (C) 2015 Huawei Inc.
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation;
13  * version 2.1 of the License (not later!)
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this program; if not,  see <http://www.gnu.org/licenses>
22  */
23
24 #include <stdlib.h>
25 #include <string.h>
26 #include <memory.h>
27 #include <unistd.h>
28 #include <asm/unistd.h>
29 #include <errno.h>
30 #include <linux/bpf.h>
31 #include <linux/filter.h>
32 #include <linux/kernel.h>
33 #include <limits.h>
34 #include <sys/resource.h>
35 #include "bpf.h"
36 #include "libbpf.h"
37 #include "libbpf_internal.h"
38
39 /*
40  * When building perf, unistd.h is overridden. __NR_bpf is
41  * required to be defined explicitly.
42  */
43 #ifndef __NR_bpf
44 # if defined(__i386__)
45 #  define __NR_bpf 357
46 # elif defined(__x86_64__)
47 #  define __NR_bpf 321
48 # elif defined(__aarch64__)
49 #  define __NR_bpf 280
50 # elif defined(__sparc__)
51 #  define __NR_bpf 349
52 # elif defined(__s390__)
53 #  define __NR_bpf 351
54 # elif defined(__arc__)
55 #  define __NR_bpf 280
56 # elif defined(__mips__) && defined(_ABIO32)
57 #  define __NR_bpf 4355
58 # elif defined(__mips__) && defined(_ABIN32)
59 #  define __NR_bpf 6319
60 # elif defined(__mips__) && defined(_ABI64)
61 #  define __NR_bpf 5315
62 # else
63 #  error __NR_bpf not defined. libbpf does not support your arch.
64 # endif
65 #endif
66
67 static inline __u64 ptr_to_u64(const void *ptr)
68 {
69         return (__u64) (unsigned long) ptr;
70 }
71
72 static inline int sys_bpf(enum bpf_cmd cmd, union bpf_attr *attr,
73                           unsigned int size)
74 {
75         return syscall(__NR_bpf, cmd, attr, size);
76 }
77
78 static inline int sys_bpf_fd(enum bpf_cmd cmd, union bpf_attr *attr,
79                              unsigned int size)
80 {
81         int fd;
82
83         fd = sys_bpf(cmd, attr, size);
84         return ensure_good_fd(fd);
85 }
86
87 int sys_bpf_prog_load(union bpf_attr *attr, unsigned int size, int attempts)
88 {
89         int fd;
90
91         do {
92                 fd = sys_bpf_fd(BPF_PROG_LOAD, attr, size);
93         } while (fd < 0 && errno == EAGAIN && --attempts > 0);
94
95         return fd;
96 }
97
98 /* Probe whether kernel switched from memlock-based (RLIMIT_MEMLOCK) to
99  * memcg-based memory accounting for BPF maps and progs. This was done in [0].
100  * We use the support for bpf_ktime_get_coarse_ns() helper, which was added in
101  * the same 5.11 Linux release ([1]), to detect memcg-based accounting for BPF.
102  *
103  *   [0] https://lore.kernel.org/bpf/20201201215900.3569844-1-guro@fb.com/
104  *   [1] d05512618056 ("bpf: Add bpf_ktime_get_coarse_ns helper")
105  */
106 int probe_memcg_account(void)
107 {
108         const size_t prog_load_attr_sz = offsetofend(union bpf_attr, attach_btf_obj_fd);
109         struct bpf_insn insns[] = {
110                 BPF_EMIT_CALL(BPF_FUNC_ktime_get_coarse_ns),
111                 BPF_EXIT_INSN(),
112         };
113         size_t insn_cnt = ARRAY_SIZE(insns);
114         union bpf_attr attr;
115         int prog_fd;
116
117         /* attempt loading freplace trying to use custom BTF */
118         memset(&attr, 0, prog_load_attr_sz);
119         attr.prog_type = BPF_PROG_TYPE_SOCKET_FILTER;
120         attr.insns = ptr_to_u64(insns);
121         attr.insn_cnt = insn_cnt;
122         attr.license = ptr_to_u64("GPL");
123
124         prog_fd = sys_bpf_fd(BPF_PROG_LOAD, &attr, prog_load_attr_sz);
125         if (prog_fd >= 0) {
126                 close(prog_fd);
127                 return 1;
128         }
129         return 0;
130 }
131
132 static bool memlock_bumped;
133 static rlim_t memlock_rlim = RLIM_INFINITY;
134
135 int libbpf_set_memlock_rlim(size_t memlock_bytes)
136 {
137         if (memlock_bumped)
138                 return libbpf_err(-EBUSY);
139
140         memlock_rlim = memlock_bytes;
141         return 0;
142 }
143
144 int bump_rlimit_memlock(void)
145 {
146         struct rlimit rlim;
147
148         /* if kernel supports memcg-based accounting, skip bumping RLIMIT_MEMLOCK */
149         if (memlock_bumped || kernel_supports(NULL, FEAT_MEMCG_ACCOUNT))
150                 return 0;
151
152         memlock_bumped = true;
153
154         /* zero memlock_rlim_max disables auto-bumping RLIMIT_MEMLOCK */
155         if (memlock_rlim == 0)
156                 return 0;
157
158         rlim.rlim_cur = rlim.rlim_max = memlock_rlim;
159         if (setrlimit(RLIMIT_MEMLOCK, &rlim))
160                 return -errno;
161
162         return 0;
163 }
164
165 int bpf_map_create(enum bpf_map_type map_type,
166                    const char *map_name,
167                    __u32 key_size,
168                    __u32 value_size,
169                    __u32 max_entries,
170                    const struct bpf_map_create_opts *opts)
171 {
172         const size_t attr_sz = offsetofend(union bpf_attr, map_extra);
173         union bpf_attr attr;
174         int fd;
175
176         bump_rlimit_memlock();
177
178         memset(&attr, 0, attr_sz);
179
180         if (!OPTS_VALID(opts, bpf_map_create_opts))
181                 return libbpf_err(-EINVAL);
182
183         attr.map_type = map_type;
184         if (map_name && kernel_supports(NULL, FEAT_PROG_NAME))
185                 libbpf_strlcpy(attr.map_name, map_name, sizeof(attr.map_name));
186         attr.key_size = key_size;
187         attr.value_size = value_size;
188         attr.max_entries = max_entries;
189
190         attr.btf_fd = OPTS_GET(opts, btf_fd, 0);
191         attr.btf_key_type_id = OPTS_GET(opts, btf_key_type_id, 0);
192         attr.btf_value_type_id = OPTS_GET(opts, btf_value_type_id, 0);
193         attr.btf_vmlinux_value_type_id = OPTS_GET(opts, btf_vmlinux_value_type_id, 0);
194
195         attr.inner_map_fd = OPTS_GET(opts, inner_map_fd, 0);
196         attr.map_flags = OPTS_GET(opts, map_flags, 0);
197         attr.map_extra = OPTS_GET(opts, map_extra, 0);
198         attr.numa_node = OPTS_GET(opts, numa_node, 0);
199         attr.map_ifindex = OPTS_GET(opts, map_ifindex, 0);
200
201         fd = sys_bpf_fd(BPF_MAP_CREATE, &attr, attr_sz);
202         return libbpf_err_errno(fd);
203 }
204
205 static void *
206 alloc_zero_tailing_info(const void *orecord, __u32 cnt,
207                         __u32 actual_rec_size, __u32 expected_rec_size)
208 {
209         __u64 info_len = (__u64)actual_rec_size * cnt;
210         void *info, *nrecord;
211         int i;
212
213         info = malloc(info_len);
214         if (!info)
215                 return NULL;
216
217         /* zero out bytes kernel does not understand */
218         nrecord = info;
219         for (i = 0; i < cnt; i++) {
220                 memcpy(nrecord, orecord, expected_rec_size);
221                 memset(nrecord + expected_rec_size, 0,
222                        actual_rec_size - expected_rec_size);
223                 orecord += actual_rec_size;
224                 nrecord += actual_rec_size;
225         }
226
227         return info;
228 }
229
230 int bpf_prog_load(enum bpf_prog_type prog_type,
231                   const char *prog_name, const char *license,
232                   const struct bpf_insn *insns, size_t insn_cnt,
233                   const struct bpf_prog_load_opts *opts)
234 {
235         void *finfo = NULL, *linfo = NULL;
236         const char *func_info, *line_info;
237         __u32 log_size, log_level, attach_prog_fd, attach_btf_obj_fd;
238         __u32 func_info_rec_size, line_info_rec_size;
239         int fd, attempts;
240         union bpf_attr attr;
241         char *log_buf;
242
243         bump_rlimit_memlock();
244
245         if (!OPTS_VALID(opts, bpf_prog_load_opts))
246                 return libbpf_err(-EINVAL);
247
248         attempts = OPTS_GET(opts, attempts, 0);
249         if (attempts < 0)
250                 return libbpf_err(-EINVAL);
251         if (attempts == 0)
252                 attempts = PROG_LOAD_ATTEMPTS;
253
254         memset(&attr, 0, sizeof(attr));
255
256         attr.prog_type = prog_type;
257         attr.expected_attach_type = OPTS_GET(opts, expected_attach_type, 0);
258
259         attr.prog_btf_fd = OPTS_GET(opts, prog_btf_fd, 0);
260         attr.prog_flags = OPTS_GET(opts, prog_flags, 0);
261         attr.prog_ifindex = OPTS_GET(opts, prog_ifindex, 0);
262         attr.kern_version = OPTS_GET(opts, kern_version, 0);
263
264         if (prog_name && kernel_supports(NULL, FEAT_PROG_NAME))
265                 libbpf_strlcpy(attr.prog_name, prog_name, sizeof(attr.prog_name));
266         attr.license = ptr_to_u64(license);
267
268         if (insn_cnt > UINT_MAX)
269                 return libbpf_err(-E2BIG);
270
271         attr.insns = ptr_to_u64(insns);
272         attr.insn_cnt = (__u32)insn_cnt;
273
274         attach_prog_fd = OPTS_GET(opts, attach_prog_fd, 0);
275         attach_btf_obj_fd = OPTS_GET(opts, attach_btf_obj_fd, 0);
276
277         if (attach_prog_fd && attach_btf_obj_fd)
278                 return libbpf_err(-EINVAL);
279
280         attr.attach_btf_id = OPTS_GET(opts, attach_btf_id, 0);
281         if (attach_prog_fd)
282                 attr.attach_prog_fd = attach_prog_fd;
283         else
284                 attr.attach_btf_obj_fd = attach_btf_obj_fd;
285
286         log_buf = OPTS_GET(opts, log_buf, NULL);
287         log_size = OPTS_GET(opts, log_size, 0);
288         log_level = OPTS_GET(opts, log_level, 0);
289
290         if (!!log_buf != !!log_size)
291                 return libbpf_err(-EINVAL);
292         if (log_level > (4 | 2 | 1))
293                 return libbpf_err(-EINVAL);
294         if (log_level && !log_buf)
295                 return libbpf_err(-EINVAL);
296
297         func_info_rec_size = OPTS_GET(opts, func_info_rec_size, 0);
298         func_info = OPTS_GET(opts, func_info, NULL);
299         attr.func_info_rec_size = func_info_rec_size;
300         attr.func_info = ptr_to_u64(func_info);
301         attr.func_info_cnt = OPTS_GET(opts, func_info_cnt, 0);
302
303         line_info_rec_size = OPTS_GET(opts, line_info_rec_size, 0);
304         line_info = OPTS_GET(opts, line_info, NULL);
305         attr.line_info_rec_size = line_info_rec_size;
306         attr.line_info = ptr_to_u64(line_info);
307         attr.line_info_cnt = OPTS_GET(opts, line_info_cnt, 0);
308
309         attr.fd_array = ptr_to_u64(OPTS_GET(opts, fd_array, NULL));
310
311         if (log_level) {
312                 attr.log_buf = ptr_to_u64(log_buf);
313                 attr.log_size = log_size;
314                 attr.log_level = log_level;
315         }
316
317         fd = sys_bpf_prog_load(&attr, sizeof(attr), attempts);
318         if (fd >= 0)
319                 return fd;
320
321         /* After bpf_prog_load, the kernel may modify certain attributes
322          * to give user space a hint how to deal with loading failure.
323          * Check to see whether we can make some changes and load again.
324          */
325         while (errno == E2BIG && (!finfo || !linfo)) {
326                 if (!finfo && attr.func_info_cnt &&
327                     attr.func_info_rec_size < func_info_rec_size) {
328                         /* try with corrected func info records */
329                         finfo = alloc_zero_tailing_info(func_info,
330                                                         attr.func_info_cnt,
331                                                         func_info_rec_size,
332                                                         attr.func_info_rec_size);
333                         if (!finfo) {
334                                 errno = E2BIG;
335                                 goto done;
336                         }
337
338                         attr.func_info = ptr_to_u64(finfo);
339                         attr.func_info_rec_size = func_info_rec_size;
340                 } else if (!linfo && attr.line_info_cnt &&
341                            attr.line_info_rec_size < line_info_rec_size) {
342                         linfo = alloc_zero_tailing_info(line_info,
343                                                         attr.line_info_cnt,
344                                                         line_info_rec_size,
345                                                         attr.line_info_rec_size);
346                         if (!linfo) {
347                                 errno = E2BIG;
348                                 goto done;
349                         }
350
351                         attr.line_info = ptr_to_u64(linfo);
352                         attr.line_info_rec_size = line_info_rec_size;
353                 } else {
354                         break;
355                 }
356
357                 fd = sys_bpf_prog_load(&attr, sizeof(attr), attempts);
358                 if (fd >= 0)
359                         goto done;
360         }
361
362         if (log_level == 0 && log_buf) {
363                 /* log_level == 0 with non-NULL log_buf requires retrying on error
364                  * with log_level == 1 and log_buf/log_buf_size set, to get details of
365                  * failure
366                  */
367                 attr.log_buf = ptr_to_u64(log_buf);
368                 attr.log_size = log_size;
369                 attr.log_level = 1;
370
371                 fd = sys_bpf_prog_load(&attr, sizeof(attr), attempts);
372         }
373 done:
374         /* free() doesn't affect errno, so we don't need to restore it */
375         free(finfo);
376         free(linfo);
377         return libbpf_err_errno(fd);
378 }
379
380 int bpf_map_update_elem(int fd, const void *key, const void *value,
381                         __u64 flags)
382 {
383         union bpf_attr attr;
384         int ret;
385
386         memset(&attr, 0, sizeof(attr));
387         attr.map_fd = fd;
388         attr.key = ptr_to_u64(key);
389         attr.value = ptr_to_u64(value);
390         attr.flags = flags;
391
392         ret = sys_bpf(BPF_MAP_UPDATE_ELEM, &attr, sizeof(attr));
393         return libbpf_err_errno(ret);
394 }
395
396 int bpf_map_lookup_elem(int fd, const void *key, void *value)
397 {
398         union bpf_attr attr;
399         int ret;
400
401         memset(&attr, 0, sizeof(attr));
402         attr.map_fd = fd;
403         attr.key = ptr_to_u64(key);
404         attr.value = ptr_to_u64(value);
405
406         ret = sys_bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
407         return libbpf_err_errno(ret);
408 }
409
410 int bpf_map_lookup_elem_flags(int fd, const void *key, void *value, __u64 flags)
411 {
412         union bpf_attr attr;
413         int ret;
414
415         memset(&attr, 0, sizeof(attr));
416         attr.map_fd = fd;
417         attr.key = ptr_to_u64(key);
418         attr.value = ptr_to_u64(value);
419         attr.flags = flags;
420
421         ret = sys_bpf(BPF_MAP_LOOKUP_ELEM, &attr, sizeof(attr));
422         return libbpf_err_errno(ret);
423 }
424
425 int bpf_map_lookup_and_delete_elem(int fd, const void *key, void *value)
426 {
427         union bpf_attr attr;
428         int ret;
429
430         memset(&attr, 0, sizeof(attr));
431         attr.map_fd = fd;
432         attr.key = ptr_to_u64(key);
433         attr.value = ptr_to_u64(value);
434
435         ret = sys_bpf(BPF_MAP_LOOKUP_AND_DELETE_ELEM, &attr, sizeof(attr));
436         return libbpf_err_errno(ret);
437 }
438
439 int bpf_map_lookup_and_delete_elem_flags(int fd, const void *key, void *value, __u64 flags)
440 {
441         union bpf_attr attr;
442         int ret;
443
444         memset(&attr, 0, sizeof(attr));
445         attr.map_fd = fd;
446         attr.key = ptr_to_u64(key);
447         attr.value = ptr_to_u64(value);
448         attr.flags = flags;
449
450         ret = sys_bpf(BPF_MAP_LOOKUP_AND_DELETE_ELEM, &attr, sizeof(attr));
451         return libbpf_err_errno(ret);
452 }
453
454 int bpf_map_delete_elem(int fd, const void *key)
455 {
456         union bpf_attr attr;
457         int ret;
458
459         memset(&attr, 0, sizeof(attr));
460         attr.map_fd = fd;
461         attr.key = ptr_to_u64(key);
462
463         ret = sys_bpf(BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
464         return libbpf_err_errno(ret);
465 }
466
467 int bpf_map_delete_elem_flags(int fd, const void *key, __u64 flags)
468 {
469         union bpf_attr attr;
470         int ret;
471
472         memset(&attr, 0, sizeof(attr));
473         attr.map_fd = fd;
474         attr.key = ptr_to_u64(key);
475         attr.flags = flags;
476
477         ret = sys_bpf(BPF_MAP_DELETE_ELEM, &attr, sizeof(attr));
478         return libbpf_err_errno(ret);
479 }
480
481 int bpf_map_get_next_key(int fd, const void *key, void *next_key)
482 {
483         union bpf_attr attr;
484         int ret;
485
486         memset(&attr, 0, sizeof(attr));
487         attr.map_fd = fd;
488         attr.key = ptr_to_u64(key);
489         attr.next_key = ptr_to_u64(next_key);
490
491         ret = sys_bpf(BPF_MAP_GET_NEXT_KEY, &attr, sizeof(attr));
492         return libbpf_err_errno(ret);
493 }
494
495 int bpf_map_freeze(int fd)
496 {
497         union bpf_attr attr;
498         int ret;
499
500         memset(&attr, 0, sizeof(attr));
501         attr.map_fd = fd;
502
503         ret = sys_bpf(BPF_MAP_FREEZE, &attr, sizeof(attr));
504         return libbpf_err_errno(ret);
505 }
506
507 static int bpf_map_batch_common(int cmd, int fd, void  *in_batch,
508                                 void *out_batch, void *keys, void *values,
509                                 __u32 *count,
510                                 const struct bpf_map_batch_opts *opts)
511 {
512         union bpf_attr attr;
513         int ret;
514
515         if (!OPTS_VALID(opts, bpf_map_batch_opts))
516                 return libbpf_err(-EINVAL);
517
518         memset(&attr, 0, sizeof(attr));
519         attr.batch.map_fd = fd;
520         attr.batch.in_batch = ptr_to_u64(in_batch);
521         attr.batch.out_batch = ptr_to_u64(out_batch);
522         attr.batch.keys = ptr_to_u64(keys);
523         attr.batch.values = ptr_to_u64(values);
524         attr.batch.count = *count;
525         attr.batch.elem_flags  = OPTS_GET(opts, elem_flags, 0);
526         attr.batch.flags = OPTS_GET(opts, flags, 0);
527
528         ret = sys_bpf(cmd, &attr, sizeof(attr));
529         *count = attr.batch.count;
530
531         return libbpf_err_errno(ret);
532 }
533
534 int bpf_map_delete_batch(int fd, const void *keys, __u32 *count,
535                          const struct bpf_map_batch_opts *opts)
536 {
537         return bpf_map_batch_common(BPF_MAP_DELETE_BATCH, fd, NULL,
538                                     NULL, (void *)keys, NULL, count, opts);
539 }
540
541 int bpf_map_lookup_batch(int fd, void *in_batch, void *out_batch, void *keys,
542                          void *values, __u32 *count,
543                          const struct bpf_map_batch_opts *opts)
544 {
545         return bpf_map_batch_common(BPF_MAP_LOOKUP_BATCH, fd, in_batch,
546                                     out_batch, keys, values, count, opts);
547 }
548
549 int bpf_map_lookup_and_delete_batch(int fd, void *in_batch, void *out_batch,
550                                     void *keys, void *values, __u32 *count,
551                                     const struct bpf_map_batch_opts *opts)
552 {
553         return bpf_map_batch_common(BPF_MAP_LOOKUP_AND_DELETE_BATCH,
554                                     fd, in_batch, out_batch, keys, values,
555                                     count, opts);
556 }
557
558 int bpf_map_update_batch(int fd, const void *keys, const void *values, __u32 *count,
559                          const struct bpf_map_batch_opts *opts)
560 {
561         return bpf_map_batch_common(BPF_MAP_UPDATE_BATCH, fd, NULL, NULL,
562                                     (void *)keys, (void *)values, count, opts);
563 }
564
565 int bpf_obj_pin(int fd, const char *pathname)
566 {
567         union bpf_attr attr;
568         int ret;
569
570         memset(&attr, 0, sizeof(attr));
571         attr.pathname = ptr_to_u64((void *)pathname);
572         attr.bpf_fd = fd;
573
574         ret = sys_bpf(BPF_OBJ_PIN, &attr, sizeof(attr));
575         return libbpf_err_errno(ret);
576 }
577
578 int bpf_obj_get(const char *pathname)
579 {
580         return bpf_obj_get_opts(pathname, NULL);
581 }
582
583 int bpf_obj_get_opts(const char *pathname, const struct bpf_obj_get_opts *opts)
584 {
585         union bpf_attr attr;
586         int fd;
587
588         if (!OPTS_VALID(opts, bpf_obj_get_opts))
589                 return libbpf_err(-EINVAL);
590
591         memset(&attr, 0, sizeof(attr));
592         attr.pathname = ptr_to_u64((void *)pathname);
593         attr.file_flags = OPTS_GET(opts, file_flags, 0);
594
595         fd = sys_bpf_fd(BPF_OBJ_GET, &attr, sizeof(attr));
596         return libbpf_err_errno(fd);
597 }
598
599 int bpf_prog_attach(int prog_fd, int target_fd, enum bpf_attach_type type,
600                     unsigned int flags)
601 {
602         DECLARE_LIBBPF_OPTS(bpf_prog_attach_opts, opts,
603                 .flags = flags,
604         );
605
606         return bpf_prog_attach_opts(prog_fd, target_fd, type, &opts);
607 }
608
609 int bpf_prog_attach_opts(int prog_fd, int target_fd,
610                           enum bpf_attach_type type,
611                           const struct bpf_prog_attach_opts *opts)
612 {
613         union bpf_attr attr;
614         int ret;
615
616         if (!OPTS_VALID(opts, bpf_prog_attach_opts))
617                 return libbpf_err(-EINVAL);
618
619         memset(&attr, 0, sizeof(attr));
620         attr.target_fd     = target_fd;
621         attr.attach_bpf_fd = prog_fd;
622         attr.attach_type   = type;
623         attr.attach_flags  = OPTS_GET(opts, flags, 0);
624         attr.replace_bpf_fd = OPTS_GET(opts, replace_prog_fd, 0);
625
626         ret = sys_bpf(BPF_PROG_ATTACH, &attr, sizeof(attr));
627         return libbpf_err_errno(ret);
628 }
629
630 __attribute__((alias("bpf_prog_attach_opts")))
631 int bpf_prog_attach_xattr(int prog_fd, int target_fd,
632                           enum bpf_attach_type type,
633                           const struct bpf_prog_attach_opts *opts);
634
635 int bpf_prog_detach(int target_fd, enum bpf_attach_type type)
636 {
637         union bpf_attr attr;
638         int ret;
639
640         memset(&attr, 0, sizeof(attr));
641         attr.target_fd   = target_fd;
642         attr.attach_type = type;
643
644         ret = sys_bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
645         return libbpf_err_errno(ret);
646 }
647
648 int bpf_prog_detach2(int prog_fd, int target_fd, enum bpf_attach_type type)
649 {
650         union bpf_attr attr;
651         int ret;
652
653         memset(&attr, 0, sizeof(attr));
654         attr.target_fd   = target_fd;
655         attr.attach_bpf_fd = prog_fd;
656         attr.attach_type = type;
657
658         ret = sys_bpf(BPF_PROG_DETACH, &attr, sizeof(attr));
659         return libbpf_err_errno(ret);
660 }
661
662 int bpf_link_create(int prog_fd, int target_fd,
663                     enum bpf_attach_type attach_type,
664                     const struct bpf_link_create_opts *opts)
665 {
666         __u32 target_btf_id, iter_info_len;
667         union bpf_attr attr;
668         int fd, err;
669
670         if (!OPTS_VALID(opts, bpf_link_create_opts))
671                 return libbpf_err(-EINVAL);
672
673         iter_info_len = OPTS_GET(opts, iter_info_len, 0);
674         target_btf_id = OPTS_GET(opts, target_btf_id, 0);
675
676         /* validate we don't have unexpected combinations of non-zero fields */
677         if (iter_info_len || target_btf_id) {
678                 if (iter_info_len && target_btf_id)
679                         return libbpf_err(-EINVAL);
680                 if (!OPTS_ZEROED(opts, target_btf_id))
681                         return libbpf_err(-EINVAL);
682         }
683
684         memset(&attr, 0, sizeof(attr));
685         attr.link_create.prog_fd = prog_fd;
686         attr.link_create.target_fd = target_fd;
687         attr.link_create.attach_type = attach_type;
688         attr.link_create.flags = OPTS_GET(opts, flags, 0);
689
690         if (target_btf_id) {
691                 attr.link_create.target_btf_id = target_btf_id;
692                 goto proceed;
693         }
694
695         switch (attach_type) {
696         case BPF_TRACE_ITER:
697                 attr.link_create.iter_info = ptr_to_u64(OPTS_GET(opts, iter_info, (void *)0));
698                 attr.link_create.iter_info_len = iter_info_len;
699                 break;
700         case BPF_PERF_EVENT:
701                 attr.link_create.perf_event.bpf_cookie = OPTS_GET(opts, perf_event.bpf_cookie, 0);
702                 if (!OPTS_ZEROED(opts, perf_event))
703                         return libbpf_err(-EINVAL);
704                 break;
705         case BPF_TRACE_KPROBE_MULTI:
706                 attr.link_create.kprobe_multi.flags = OPTS_GET(opts, kprobe_multi.flags, 0);
707                 attr.link_create.kprobe_multi.cnt = OPTS_GET(opts, kprobe_multi.cnt, 0);
708                 attr.link_create.kprobe_multi.syms = ptr_to_u64(OPTS_GET(opts, kprobe_multi.syms, 0));
709                 attr.link_create.kprobe_multi.addrs = ptr_to_u64(OPTS_GET(opts, kprobe_multi.addrs, 0));
710                 attr.link_create.kprobe_multi.cookies = ptr_to_u64(OPTS_GET(opts, kprobe_multi.cookies, 0));
711                 if (!OPTS_ZEROED(opts, kprobe_multi))
712                         return libbpf_err(-EINVAL);
713                 break;
714         case BPF_TRACE_FENTRY:
715         case BPF_TRACE_FEXIT:
716         case BPF_MODIFY_RETURN:
717         case BPF_LSM_MAC:
718                 attr.link_create.tracing.cookie = OPTS_GET(opts, tracing.cookie, 0);
719                 if (!OPTS_ZEROED(opts, tracing))
720                         return libbpf_err(-EINVAL);
721                 break;
722         default:
723                 if (!OPTS_ZEROED(opts, flags))
724                         return libbpf_err(-EINVAL);
725                 break;
726         }
727 proceed:
728         fd = sys_bpf_fd(BPF_LINK_CREATE, &attr, sizeof(attr));
729         if (fd >= 0)
730                 return fd;
731         /* we'll get EINVAL if LINK_CREATE doesn't support attaching fentry
732          * and other similar programs
733          */
734         err = -errno;
735         if (err != -EINVAL)
736                 return libbpf_err(err);
737
738         /* if user used features not supported by
739          * BPF_RAW_TRACEPOINT_OPEN command, then just give up immediately
740          */
741         if (attr.link_create.target_fd || attr.link_create.target_btf_id)
742                 return libbpf_err(err);
743         if (!OPTS_ZEROED(opts, sz))
744                 return libbpf_err(err);
745
746         /* otherwise, for few select kinds of programs that can be
747          * attached using BPF_RAW_TRACEPOINT_OPEN command, try that as
748          * a fallback for older kernels
749          */
750         switch (attach_type) {
751         case BPF_TRACE_RAW_TP:
752         case BPF_LSM_MAC:
753         case BPF_TRACE_FENTRY:
754         case BPF_TRACE_FEXIT:
755         case BPF_MODIFY_RETURN:
756                 return bpf_raw_tracepoint_open(NULL, prog_fd);
757         default:
758                 return libbpf_err(err);
759         }
760 }
761
762 int bpf_link_detach(int link_fd)
763 {
764         union bpf_attr attr;
765         int ret;
766
767         memset(&attr, 0, sizeof(attr));
768         attr.link_detach.link_fd = link_fd;
769
770         ret = sys_bpf(BPF_LINK_DETACH, &attr, sizeof(attr));
771         return libbpf_err_errno(ret);
772 }
773
774 int bpf_link_update(int link_fd, int new_prog_fd,
775                     const struct bpf_link_update_opts *opts)
776 {
777         union bpf_attr attr;
778         int ret;
779
780         if (!OPTS_VALID(opts, bpf_link_update_opts))
781                 return libbpf_err(-EINVAL);
782
783         memset(&attr, 0, sizeof(attr));
784         attr.link_update.link_fd = link_fd;
785         attr.link_update.new_prog_fd = new_prog_fd;
786         attr.link_update.flags = OPTS_GET(opts, flags, 0);
787         attr.link_update.old_prog_fd = OPTS_GET(opts, old_prog_fd, 0);
788
789         ret = sys_bpf(BPF_LINK_UPDATE, &attr, sizeof(attr));
790         return libbpf_err_errno(ret);
791 }
792
793 int bpf_iter_create(int link_fd)
794 {
795         union bpf_attr attr;
796         int fd;
797
798         memset(&attr, 0, sizeof(attr));
799         attr.iter_create.link_fd = link_fd;
800
801         fd = sys_bpf_fd(BPF_ITER_CREATE, &attr, sizeof(attr));
802         return libbpf_err_errno(fd);
803 }
804
805 int bpf_prog_query_opts(int target_fd,
806                         enum bpf_attach_type type,
807                         struct bpf_prog_query_opts *opts)
808 {
809         union bpf_attr attr;
810         int ret;
811
812         if (!OPTS_VALID(opts, bpf_prog_query_opts))
813                 return libbpf_err(-EINVAL);
814
815         memset(&attr, 0, sizeof(attr));
816
817         attr.query.target_fd    = target_fd;
818         attr.query.attach_type  = type;
819         attr.query.query_flags  = OPTS_GET(opts, query_flags, 0);
820         attr.query.prog_cnt     = OPTS_GET(opts, prog_cnt, 0);
821         attr.query.prog_ids     = ptr_to_u64(OPTS_GET(opts, prog_ids, NULL));
822         attr.query.prog_attach_flags = ptr_to_u64(OPTS_GET(opts, prog_attach_flags, NULL));
823
824         ret = sys_bpf(BPF_PROG_QUERY, &attr, sizeof(attr));
825
826         OPTS_SET(opts, attach_flags, attr.query.attach_flags);
827         OPTS_SET(opts, prog_cnt, attr.query.prog_cnt);
828
829         return libbpf_err_errno(ret);
830 }
831
832 int bpf_prog_query(int target_fd, enum bpf_attach_type type, __u32 query_flags,
833                    __u32 *attach_flags, __u32 *prog_ids, __u32 *prog_cnt)
834 {
835         LIBBPF_OPTS(bpf_prog_query_opts, opts);
836         int ret;
837
838         opts.query_flags = query_flags;
839         opts.prog_ids = prog_ids;
840         opts.prog_cnt = *prog_cnt;
841
842         ret = bpf_prog_query_opts(target_fd, type, &opts);
843
844         if (attach_flags)
845                 *attach_flags = opts.attach_flags;
846         *prog_cnt = opts.prog_cnt;
847
848         return libbpf_err_errno(ret);
849 }
850
851 int bpf_prog_test_run_opts(int prog_fd, struct bpf_test_run_opts *opts)
852 {
853         union bpf_attr attr;
854         int ret;
855
856         if (!OPTS_VALID(opts, bpf_test_run_opts))
857                 return libbpf_err(-EINVAL);
858
859         memset(&attr, 0, sizeof(attr));
860         attr.test.prog_fd = prog_fd;
861         attr.test.batch_size = OPTS_GET(opts, batch_size, 0);
862         attr.test.cpu = OPTS_GET(opts, cpu, 0);
863         attr.test.flags = OPTS_GET(opts, flags, 0);
864         attr.test.repeat = OPTS_GET(opts, repeat, 0);
865         attr.test.duration = OPTS_GET(opts, duration, 0);
866         attr.test.ctx_size_in = OPTS_GET(opts, ctx_size_in, 0);
867         attr.test.ctx_size_out = OPTS_GET(opts, ctx_size_out, 0);
868         attr.test.data_size_in = OPTS_GET(opts, data_size_in, 0);
869         attr.test.data_size_out = OPTS_GET(opts, data_size_out, 0);
870         attr.test.ctx_in = ptr_to_u64(OPTS_GET(opts, ctx_in, NULL));
871         attr.test.ctx_out = ptr_to_u64(OPTS_GET(opts, ctx_out, NULL));
872         attr.test.data_in = ptr_to_u64(OPTS_GET(opts, data_in, NULL));
873         attr.test.data_out = ptr_to_u64(OPTS_GET(opts, data_out, NULL));
874
875         ret = sys_bpf(BPF_PROG_TEST_RUN, &attr, sizeof(attr));
876
877         OPTS_SET(opts, data_size_out, attr.test.data_size_out);
878         OPTS_SET(opts, ctx_size_out, attr.test.ctx_size_out);
879         OPTS_SET(opts, duration, attr.test.duration);
880         OPTS_SET(opts, retval, attr.test.retval);
881
882         return libbpf_err_errno(ret);
883 }
884
885 static int bpf_obj_get_next_id(__u32 start_id, __u32 *next_id, int cmd)
886 {
887         union bpf_attr attr;
888         int err;
889
890         memset(&attr, 0, sizeof(attr));
891         attr.start_id = start_id;
892
893         err = sys_bpf(cmd, &attr, sizeof(attr));
894         if (!err)
895                 *next_id = attr.next_id;
896
897         return libbpf_err_errno(err);
898 }
899
900 int bpf_prog_get_next_id(__u32 start_id, __u32 *next_id)
901 {
902         return bpf_obj_get_next_id(start_id, next_id, BPF_PROG_GET_NEXT_ID);
903 }
904
905 int bpf_map_get_next_id(__u32 start_id, __u32 *next_id)
906 {
907         return bpf_obj_get_next_id(start_id, next_id, BPF_MAP_GET_NEXT_ID);
908 }
909
910 int bpf_btf_get_next_id(__u32 start_id, __u32 *next_id)
911 {
912         return bpf_obj_get_next_id(start_id, next_id, BPF_BTF_GET_NEXT_ID);
913 }
914
915 int bpf_link_get_next_id(__u32 start_id, __u32 *next_id)
916 {
917         return bpf_obj_get_next_id(start_id, next_id, BPF_LINK_GET_NEXT_ID);
918 }
919
920 int bpf_prog_get_fd_by_id(__u32 id)
921 {
922         union bpf_attr attr;
923         int fd;
924
925         memset(&attr, 0, sizeof(attr));
926         attr.prog_id = id;
927
928         fd = sys_bpf_fd(BPF_PROG_GET_FD_BY_ID, &attr, sizeof(attr));
929         return libbpf_err_errno(fd);
930 }
931
932 int bpf_map_get_fd_by_id(__u32 id)
933 {
934         union bpf_attr attr;
935         int fd;
936
937         memset(&attr, 0, sizeof(attr));
938         attr.map_id = id;
939
940         fd = sys_bpf_fd(BPF_MAP_GET_FD_BY_ID, &attr, sizeof(attr));
941         return libbpf_err_errno(fd);
942 }
943
944 int bpf_btf_get_fd_by_id(__u32 id)
945 {
946         union bpf_attr attr;
947         int fd;
948
949         memset(&attr, 0, sizeof(attr));
950         attr.btf_id = id;
951
952         fd = sys_bpf_fd(BPF_BTF_GET_FD_BY_ID, &attr, sizeof(attr));
953         return libbpf_err_errno(fd);
954 }
955
956 int bpf_link_get_fd_by_id(__u32 id)
957 {
958         union bpf_attr attr;
959         int fd;
960
961         memset(&attr, 0, sizeof(attr));
962         attr.link_id = id;
963
964         fd = sys_bpf_fd(BPF_LINK_GET_FD_BY_ID, &attr, sizeof(attr));
965         return libbpf_err_errno(fd);
966 }
967
968 int bpf_obj_get_info_by_fd(int bpf_fd, void *info, __u32 *info_len)
969 {
970         union bpf_attr attr;
971         int err;
972
973         memset(&attr, 0, sizeof(attr));
974         attr.info.bpf_fd = bpf_fd;
975         attr.info.info_len = *info_len;
976         attr.info.info = ptr_to_u64(info);
977
978         err = sys_bpf(BPF_OBJ_GET_INFO_BY_FD, &attr, sizeof(attr));
979
980         if (!err)
981                 *info_len = attr.info.info_len;
982
983         return libbpf_err_errno(err);
984 }
985
986 int bpf_raw_tracepoint_open(const char *name, int prog_fd)
987 {
988         union bpf_attr attr;
989         int fd;
990
991         memset(&attr, 0, sizeof(attr));
992         attr.raw_tracepoint.name = ptr_to_u64(name);
993         attr.raw_tracepoint.prog_fd = prog_fd;
994
995         fd = sys_bpf_fd(BPF_RAW_TRACEPOINT_OPEN, &attr, sizeof(attr));
996         return libbpf_err_errno(fd);
997 }
998
999 int bpf_btf_load(const void *btf_data, size_t btf_size, const struct bpf_btf_load_opts *opts)
1000 {
1001         const size_t attr_sz = offsetofend(union bpf_attr, btf_log_level);
1002         union bpf_attr attr;
1003         char *log_buf;
1004         size_t log_size;
1005         __u32 log_level;
1006         int fd;
1007
1008         bump_rlimit_memlock();
1009
1010         memset(&attr, 0, attr_sz);
1011
1012         if (!OPTS_VALID(opts, bpf_btf_load_opts))
1013                 return libbpf_err(-EINVAL);
1014
1015         log_buf = OPTS_GET(opts, log_buf, NULL);
1016         log_size = OPTS_GET(opts, log_size, 0);
1017         log_level = OPTS_GET(opts, log_level, 0);
1018
1019         if (log_size > UINT_MAX)
1020                 return libbpf_err(-EINVAL);
1021         if (log_size && !log_buf)
1022                 return libbpf_err(-EINVAL);
1023
1024         attr.btf = ptr_to_u64(btf_data);
1025         attr.btf_size = btf_size;
1026         /* log_level == 0 and log_buf != NULL means "try loading without
1027          * log_buf, but retry with log_buf and log_level=1 on error", which is
1028          * consistent across low-level and high-level BTF and program loading
1029          * APIs within libbpf and provides a sensible behavior in practice
1030          */
1031         if (log_level) {
1032                 attr.btf_log_buf = ptr_to_u64(log_buf);
1033                 attr.btf_log_size = (__u32)log_size;
1034                 attr.btf_log_level = log_level;
1035         }
1036
1037         fd = sys_bpf_fd(BPF_BTF_LOAD, &attr, attr_sz);
1038         if (fd < 0 && log_buf && log_level == 0) {
1039                 attr.btf_log_buf = ptr_to_u64(log_buf);
1040                 attr.btf_log_size = (__u32)log_size;
1041                 attr.btf_log_level = 1;
1042                 fd = sys_bpf_fd(BPF_BTF_LOAD, &attr, attr_sz);
1043         }
1044         return libbpf_err_errno(fd);
1045 }
1046
1047 int bpf_task_fd_query(int pid, int fd, __u32 flags, char *buf, __u32 *buf_len,
1048                       __u32 *prog_id, __u32 *fd_type, __u64 *probe_offset,
1049                       __u64 *probe_addr)
1050 {
1051         union bpf_attr attr = {};
1052         int err;
1053
1054         attr.task_fd_query.pid = pid;
1055         attr.task_fd_query.fd = fd;
1056         attr.task_fd_query.flags = flags;
1057         attr.task_fd_query.buf = ptr_to_u64(buf);
1058         attr.task_fd_query.buf_len = *buf_len;
1059
1060         err = sys_bpf(BPF_TASK_FD_QUERY, &attr, sizeof(attr));
1061
1062         *buf_len = attr.task_fd_query.buf_len;
1063         *prog_id = attr.task_fd_query.prog_id;
1064         *fd_type = attr.task_fd_query.fd_type;
1065         *probe_offset = attr.task_fd_query.probe_offset;
1066         *probe_addr = attr.task_fd_query.probe_addr;
1067
1068         return libbpf_err_errno(err);
1069 }
1070
1071 int bpf_enable_stats(enum bpf_stats_type type)
1072 {
1073         union bpf_attr attr;
1074         int fd;
1075
1076         memset(&attr, 0, sizeof(attr));
1077         attr.enable_stats.type = type;
1078
1079         fd = sys_bpf_fd(BPF_ENABLE_STATS, &attr, sizeof(attr));
1080         return libbpf_err_errno(fd);
1081 }
1082
1083 int bpf_prog_bind_map(int prog_fd, int map_fd,
1084                       const struct bpf_prog_bind_opts *opts)
1085 {
1086         union bpf_attr attr;
1087         int ret;
1088
1089         if (!OPTS_VALID(opts, bpf_prog_bind_opts))
1090                 return libbpf_err(-EINVAL);
1091
1092         memset(&attr, 0, sizeof(attr));
1093         attr.prog_bind_map.prog_fd = prog_fd;
1094         attr.prog_bind_map.map_fd = map_fd;
1095         attr.prog_bind_map.flags = OPTS_GET(opts, flags, 0);
1096
1097         ret = sys_bpf(BPF_PROG_BIND_MAP, &attr, sizeof(attr));
1098         return libbpf_err_errno(ret);
1099 }