bpf: Defer the free of inner map when necessary
[platform/kernel/linux-rpi.git] / kernel / bpf / syscall.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #include <linux/bpf.h>
5 #include <linux/bpf-cgroup.h>
6 #include <linux/bpf_trace.h>
7 #include <linux/bpf_lirc.h>
8 #include <linux/bpf_verifier.h>
9 #include <linux/bsearch.h>
10 #include <linux/btf.h>
11 #include <linux/syscalls.h>
12 #include <linux/slab.h>
13 #include <linux/sched/signal.h>
14 #include <linux/vmalloc.h>
15 #include <linux/mmzone.h>
16 #include <linux/anon_inodes.h>
17 #include <linux/fdtable.h>
18 #include <linux/file.h>
19 #include <linux/fs.h>
20 #include <linux/license.h>
21 #include <linux/filter.h>
22 #include <linux/kernel.h>
23 #include <linux/idr.h>
24 #include <linux/cred.h>
25 #include <linux/timekeeping.h>
26 #include <linux/ctype.h>
27 #include <linux/nospec.h>
28 #include <linux/audit.h>
29 #include <uapi/linux/btf.h>
30 #include <linux/pgtable.h>
31 #include <linux/bpf_lsm.h>
32 #include <linux/poll.h>
33 #include <linux/sort.h>
34 #include <linux/bpf-netns.h>
35 #include <linux/rcupdate_trace.h>
36 #include <linux/memcontrol.h>
37 #include <linux/trace_events.h>
38 #include <net/netfilter/nf_bpf_link.h>
39
40 #include <net/tcx.h>
41
42 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
43                           (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
44                           (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
45 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
46 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
47 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
48                         IS_FD_HASH(map))
49
50 #define BPF_OBJ_FLAG_MASK   (BPF_F_RDONLY | BPF_F_WRONLY)
51
52 DEFINE_PER_CPU(int, bpf_prog_active);
53 static DEFINE_IDR(prog_idr);
54 static DEFINE_SPINLOCK(prog_idr_lock);
55 static DEFINE_IDR(map_idr);
56 static DEFINE_SPINLOCK(map_idr_lock);
57 static DEFINE_IDR(link_idr);
58 static DEFINE_SPINLOCK(link_idr_lock);
59
60 int sysctl_unprivileged_bpf_disabled __read_mostly =
61         IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
62
63 static const struct bpf_map_ops * const bpf_map_types[] = {
64 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
65 #define BPF_MAP_TYPE(_id, _ops) \
66         [_id] = &_ops,
67 #define BPF_LINK_TYPE(_id, _name)
68 #include <linux/bpf_types.h>
69 #undef BPF_PROG_TYPE
70 #undef BPF_MAP_TYPE
71 #undef BPF_LINK_TYPE
72 };
73
74 /*
75  * If we're handed a bigger struct than we know of, ensure all the unknown bits
76  * are 0 - i.e. new user-space does not rely on any kernel feature extensions
77  * we don't know about yet.
78  *
79  * There is a ToCToU between this function call and the following
80  * copy_from_user() call. However, this is not a concern since this function is
81  * meant to be a future-proofing of bits.
82  */
83 int bpf_check_uarg_tail_zero(bpfptr_t uaddr,
84                              size_t expected_size,
85                              size_t actual_size)
86 {
87         int res;
88
89         if (unlikely(actual_size > PAGE_SIZE))  /* silly large */
90                 return -E2BIG;
91
92         if (actual_size <= expected_size)
93                 return 0;
94
95         if (uaddr.is_kernel)
96                 res = memchr_inv(uaddr.kernel + expected_size, 0,
97                                  actual_size - expected_size) == NULL;
98         else
99                 res = check_zeroed_user(uaddr.user + expected_size,
100                                         actual_size - expected_size);
101         if (res < 0)
102                 return res;
103         return res ? 0 : -E2BIG;
104 }
105
106 const struct bpf_map_ops bpf_map_offload_ops = {
107         .map_meta_equal = bpf_map_meta_equal,
108         .map_alloc = bpf_map_offload_map_alloc,
109         .map_free = bpf_map_offload_map_free,
110         .map_check_btf = map_check_no_btf,
111         .map_mem_usage = bpf_map_offload_map_mem_usage,
112 };
113
114 static void bpf_map_write_active_inc(struct bpf_map *map)
115 {
116         atomic64_inc(&map->writecnt);
117 }
118
119 static void bpf_map_write_active_dec(struct bpf_map *map)
120 {
121         atomic64_dec(&map->writecnt);
122 }
123
124 bool bpf_map_write_active(const struct bpf_map *map)
125 {
126         return atomic64_read(&map->writecnt) != 0;
127 }
128
129 static u32 bpf_map_value_size(const struct bpf_map *map)
130 {
131         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
132             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
133             map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
134             map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
135                 return round_up(map->value_size, 8) * num_possible_cpus();
136         else if (IS_FD_MAP(map))
137                 return sizeof(u32);
138         else
139                 return  map->value_size;
140 }
141
142 static void maybe_wait_bpf_programs(struct bpf_map *map)
143 {
144         /* Wait for any running BPF programs to complete so that
145          * userspace, when we return to it, knows that all programs
146          * that could be running use the new map value.
147          */
148         if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
149             map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
150                 synchronize_rcu();
151 }
152
153 static int bpf_map_update_value(struct bpf_map *map, struct file *map_file,
154                                 void *key, void *value, __u64 flags)
155 {
156         int err;
157
158         /* Need to create a kthread, thus must support schedule */
159         if (bpf_map_is_offloaded(map)) {
160                 return bpf_map_offload_update_elem(map, key, value, flags);
161         } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
162                    map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
163                 return map->ops->map_update_elem(map, key, value, flags);
164         } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
165                    map->map_type == BPF_MAP_TYPE_SOCKMAP) {
166                 return sock_map_update_elem_sys(map, key, value, flags);
167         } else if (IS_FD_PROG_ARRAY(map)) {
168                 return bpf_fd_array_map_update_elem(map, map_file, key, value,
169                                                     flags);
170         }
171
172         bpf_disable_instrumentation();
173         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
174             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
175                 err = bpf_percpu_hash_update(map, key, value, flags);
176         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
177                 err = bpf_percpu_array_update(map, key, value, flags);
178         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
179                 err = bpf_percpu_cgroup_storage_update(map, key, value,
180                                                        flags);
181         } else if (IS_FD_ARRAY(map)) {
182                 rcu_read_lock();
183                 err = bpf_fd_array_map_update_elem(map, map_file, key, value,
184                                                    flags);
185                 rcu_read_unlock();
186         } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
187                 rcu_read_lock();
188                 err = bpf_fd_htab_map_update_elem(map, map_file, key, value,
189                                                   flags);
190                 rcu_read_unlock();
191         } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
192                 /* rcu_read_lock() is not needed */
193                 err = bpf_fd_reuseport_array_update_elem(map, key, value,
194                                                          flags);
195         } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
196                    map->map_type == BPF_MAP_TYPE_STACK ||
197                    map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
198                 err = map->ops->map_push_elem(map, value, flags);
199         } else {
200                 rcu_read_lock();
201                 err = map->ops->map_update_elem(map, key, value, flags);
202                 rcu_read_unlock();
203         }
204         bpf_enable_instrumentation();
205         maybe_wait_bpf_programs(map);
206
207         return err;
208 }
209
210 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
211                               __u64 flags)
212 {
213         void *ptr;
214         int err;
215
216         if (bpf_map_is_offloaded(map))
217                 return bpf_map_offload_lookup_elem(map, key, value);
218
219         bpf_disable_instrumentation();
220         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
221             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
222                 err = bpf_percpu_hash_copy(map, key, value);
223         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
224                 err = bpf_percpu_array_copy(map, key, value);
225         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
226                 err = bpf_percpu_cgroup_storage_copy(map, key, value);
227         } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
228                 err = bpf_stackmap_copy(map, key, value);
229         } else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
230                 err = bpf_fd_array_map_lookup_elem(map, key, value);
231         } else if (IS_FD_HASH(map)) {
232                 err = bpf_fd_htab_map_lookup_elem(map, key, value);
233         } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
234                 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
235         } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
236                    map->map_type == BPF_MAP_TYPE_STACK ||
237                    map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
238                 err = map->ops->map_peek_elem(map, value);
239         } else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
240                 /* struct_ops map requires directly updating "value" */
241                 err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
242         } else {
243                 rcu_read_lock();
244                 if (map->ops->map_lookup_elem_sys_only)
245                         ptr = map->ops->map_lookup_elem_sys_only(map, key);
246                 else
247                         ptr = map->ops->map_lookup_elem(map, key);
248                 if (IS_ERR(ptr)) {
249                         err = PTR_ERR(ptr);
250                 } else if (!ptr) {
251                         err = -ENOENT;
252                 } else {
253                         err = 0;
254                         if (flags & BPF_F_LOCK)
255                                 /* lock 'ptr' and copy everything but lock */
256                                 copy_map_value_locked(map, value, ptr, true);
257                         else
258                                 copy_map_value(map, value, ptr);
259                         /* mask lock and timer, since value wasn't zero inited */
260                         check_and_init_map_value(map, value);
261                 }
262                 rcu_read_unlock();
263         }
264
265         bpf_enable_instrumentation();
266         maybe_wait_bpf_programs(map);
267
268         return err;
269 }
270
271 /* Please, do not use this function outside from the map creation path
272  * (e.g. in map update path) without taking care of setting the active
273  * memory cgroup (see at bpf_map_kmalloc_node() for example).
274  */
275 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
276 {
277         /* We really just want to fail instead of triggering OOM killer
278          * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
279          * which is used for lower order allocation requests.
280          *
281          * It has been observed that higher order allocation requests done by
282          * vmalloc with __GFP_NORETRY being set might fail due to not trying
283          * to reclaim memory from the page cache, thus we set
284          * __GFP_RETRY_MAYFAIL to avoid such situations.
285          */
286
287         gfp_t gfp = bpf_memcg_flags(__GFP_NOWARN | __GFP_ZERO);
288         unsigned int flags = 0;
289         unsigned long align = 1;
290         void *area;
291
292         if (size >= SIZE_MAX)
293                 return NULL;
294
295         /* kmalloc()'ed memory can't be mmap()'ed */
296         if (mmapable) {
297                 BUG_ON(!PAGE_ALIGNED(size));
298                 align = SHMLBA;
299                 flags = VM_USERMAP;
300         } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
301                 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
302                                     numa_node);
303                 if (area != NULL)
304                         return area;
305         }
306
307         return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
308                         gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
309                         flags, numa_node, __builtin_return_address(0));
310 }
311
312 void *bpf_map_area_alloc(u64 size, int numa_node)
313 {
314         return __bpf_map_area_alloc(size, numa_node, false);
315 }
316
317 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
318 {
319         return __bpf_map_area_alloc(size, numa_node, true);
320 }
321
322 void bpf_map_area_free(void *area)
323 {
324         kvfree(area);
325 }
326
327 static u32 bpf_map_flags_retain_permanent(u32 flags)
328 {
329         /* Some map creation flags are not tied to the map object but
330          * rather to the map fd instead, so they have no meaning upon
331          * map object inspection since multiple file descriptors with
332          * different (access) properties can exist here. Thus, given
333          * this has zero meaning for the map itself, lets clear these
334          * from here.
335          */
336         return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
337 }
338
339 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
340 {
341         map->map_type = attr->map_type;
342         map->key_size = attr->key_size;
343         map->value_size = attr->value_size;
344         map->max_entries = attr->max_entries;
345         map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
346         map->numa_node = bpf_map_attr_numa_node(attr);
347         map->map_extra = attr->map_extra;
348 }
349
350 static int bpf_map_alloc_id(struct bpf_map *map)
351 {
352         int id;
353
354         idr_preload(GFP_KERNEL);
355         spin_lock_bh(&map_idr_lock);
356         id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
357         if (id > 0)
358                 map->id = id;
359         spin_unlock_bh(&map_idr_lock);
360         idr_preload_end();
361
362         if (WARN_ON_ONCE(!id))
363                 return -ENOSPC;
364
365         return id > 0 ? 0 : id;
366 }
367
368 void bpf_map_free_id(struct bpf_map *map)
369 {
370         unsigned long flags;
371
372         /* Offloaded maps are removed from the IDR store when their device
373          * disappears - even if someone holds an fd to them they are unusable,
374          * the memory is gone, all ops will fail; they are simply waiting for
375          * refcnt to drop to be freed.
376          */
377         if (!map->id)
378                 return;
379
380         spin_lock_irqsave(&map_idr_lock, flags);
381
382         idr_remove(&map_idr, map->id);
383         map->id = 0;
384
385         spin_unlock_irqrestore(&map_idr_lock, flags);
386 }
387
388 #ifdef CONFIG_MEMCG_KMEM
389 static void bpf_map_save_memcg(struct bpf_map *map)
390 {
391         /* Currently if a map is created by a process belonging to the root
392          * memory cgroup, get_obj_cgroup_from_current() will return NULL.
393          * So we have to check map->objcg for being NULL each time it's
394          * being used.
395          */
396         if (memcg_bpf_enabled())
397                 map->objcg = get_obj_cgroup_from_current();
398 }
399
400 static void bpf_map_release_memcg(struct bpf_map *map)
401 {
402         if (map->objcg)
403                 obj_cgroup_put(map->objcg);
404 }
405
406 static struct mem_cgroup *bpf_map_get_memcg(const struct bpf_map *map)
407 {
408         if (map->objcg)
409                 return get_mem_cgroup_from_objcg(map->objcg);
410
411         return root_mem_cgroup;
412 }
413
414 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
415                            int node)
416 {
417         struct mem_cgroup *memcg, *old_memcg;
418         void *ptr;
419
420         memcg = bpf_map_get_memcg(map);
421         old_memcg = set_active_memcg(memcg);
422         ptr = kmalloc_node(size, flags | __GFP_ACCOUNT, node);
423         set_active_memcg(old_memcg);
424         mem_cgroup_put(memcg);
425
426         return ptr;
427 }
428
429 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags)
430 {
431         struct mem_cgroup *memcg, *old_memcg;
432         void *ptr;
433
434         memcg = bpf_map_get_memcg(map);
435         old_memcg = set_active_memcg(memcg);
436         ptr = kzalloc(size, flags | __GFP_ACCOUNT);
437         set_active_memcg(old_memcg);
438         mem_cgroup_put(memcg);
439
440         return ptr;
441 }
442
443 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
444                        gfp_t flags)
445 {
446         struct mem_cgroup *memcg, *old_memcg;
447         void *ptr;
448
449         memcg = bpf_map_get_memcg(map);
450         old_memcg = set_active_memcg(memcg);
451         ptr = kvcalloc(n, size, flags | __GFP_ACCOUNT);
452         set_active_memcg(old_memcg);
453         mem_cgroup_put(memcg);
454
455         return ptr;
456 }
457
458 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
459                                     size_t align, gfp_t flags)
460 {
461         struct mem_cgroup *memcg, *old_memcg;
462         void __percpu *ptr;
463
464         memcg = bpf_map_get_memcg(map);
465         old_memcg = set_active_memcg(memcg);
466         ptr = __alloc_percpu_gfp(size, align, flags | __GFP_ACCOUNT);
467         set_active_memcg(old_memcg);
468         mem_cgroup_put(memcg);
469
470         return ptr;
471 }
472
473 #else
474 static void bpf_map_save_memcg(struct bpf_map *map)
475 {
476 }
477
478 static void bpf_map_release_memcg(struct bpf_map *map)
479 {
480 }
481 #endif
482
483 static int btf_field_cmp(const void *a, const void *b)
484 {
485         const struct btf_field *f1 = a, *f2 = b;
486
487         if (f1->offset < f2->offset)
488                 return -1;
489         else if (f1->offset > f2->offset)
490                 return 1;
491         return 0;
492 }
493
494 struct btf_field *btf_record_find(const struct btf_record *rec, u32 offset,
495                                   u32 field_mask)
496 {
497         struct btf_field *field;
498
499         if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & field_mask))
500                 return NULL;
501         field = bsearch(&offset, rec->fields, rec->cnt, sizeof(rec->fields[0]), btf_field_cmp);
502         if (!field || !(field->type & field_mask))
503                 return NULL;
504         return field;
505 }
506
507 void btf_record_free(struct btf_record *rec)
508 {
509         int i;
510
511         if (IS_ERR_OR_NULL(rec))
512                 return;
513         for (i = 0; i < rec->cnt; i++) {
514                 switch (rec->fields[i].type) {
515                 case BPF_KPTR_UNREF:
516                 case BPF_KPTR_REF:
517                         if (rec->fields[i].kptr.module)
518                                 module_put(rec->fields[i].kptr.module);
519                         btf_put(rec->fields[i].kptr.btf);
520                         break;
521                 case BPF_LIST_HEAD:
522                 case BPF_LIST_NODE:
523                 case BPF_RB_ROOT:
524                 case BPF_RB_NODE:
525                 case BPF_SPIN_LOCK:
526                 case BPF_TIMER:
527                 case BPF_REFCOUNT:
528                         /* Nothing to release */
529                         break;
530                 default:
531                         WARN_ON_ONCE(1);
532                         continue;
533                 }
534         }
535         kfree(rec);
536 }
537
538 void bpf_map_free_record(struct bpf_map *map)
539 {
540         btf_record_free(map->record);
541         map->record = NULL;
542 }
543
544 struct btf_record *btf_record_dup(const struct btf_record *rec)
545 {
546         const struct btf_field *fields;
547         struct btf_record *new_rec;
548         int ret, size, i;
549
550         if (IS_ERR_OR_NULL(rec))
551                 return NULL;
552         size = offsetof(struct btf_record, fields[rec->cnt]);
553         new_rec = kmemdup(rec, size, GFP_KERNEL | __GFP_NOWARN);
554         if (!new_rec)
555                 return ERR_PTR(-ENOMEM);
556         /* Do a deep copy of the btf_record */
557         fields = rec->fields;
558         new_rec->cnt = 0;
559         for (i = 0; i < rec->cnt; i++) {
560                 switch (fields[i].type) {
561                 case BPF_KPTR_UNREF:
562                 case BPF_KPTR_REF:
563                         btf_get(fields[i].kptr.btf);
564                         if (fields[i].kptr.module && !try_module_get(fields[i].kptr.module)) {
565                                 ret = -ENXIO;
566                                 goto free;
567                         }
568                         break;
569                 case BPF_LIST_HEAD:
570                 case BPF_LIST_NODE:
571                 case BPF_RB_ROOT:
572                 case BPF_RB_NODE:
573                 case BPF_SPIN_LOCK:
574                 case BPF_TIMER:
575                 case BPF_REFCOUNT:
576                         /* Nothing to acquire */
577                         break;
578                 default:
579                         ret = -EFAULT;
580                         WARN_ON_ONCE(1);
581                         goto free;
582                 }
583                 new_rec->cnt++;
584         }
585         return new_rec;
586 free:
587         btf_record_free(new_rec);
588         return ERR_PTR(ret);
589 }
590
591 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b)
592 {
593         bool a_has_fields = !IS_ERR_OR_NULL(rec_a), b_has_fields = !IS_ERR_OR_NULL(rec_b);
594         int size;
595
596         if (!a_has_fields && !b_has_fields)
597                 return true;
598         if (a_has_fields != b_has_fields)
599                 return false;
600         if (rec_a->cnt != rec_b->cnt)
601                 return false;
602         size = offsetof(struct btf_record, fields[rec_a->cnt]);
603         /* btf_parse_fields uses kzalloc to allocate a btf_record, so unused
604          * members are zeroed out. So memcmp is safe to do without worrying
605          * about padding/unused fields.
606          *
607          * While spin_lock, timer, and kptr have no relation to map BTF,
608          * list_head metadata is specific to map BTF, the btf and value_rec
609          * members in particular. btf is the map BTF, while value_rec points to
610          * btf_record in that map BTF.
611          *
612          * So while by default, we don't rely on the map BTF (which the records
613          * were parsed from) matching for both records, which is not backwards
614          * compatible, in case list_head is part of it, we implicitly rely on
615          * that by way of depending on memcmp succeeding for it.
616          */
617         return !memcmp(rec_a, rec_b, size);
618 }
619
620 void bpf_obj_free_timer(const struct btf_record *rec, void *obj)
621 {
622         if (WARN_ON_ONCE(!btf_record_has_field(rec, BPF_TIMER)))
623                 return;
624         bpf_timer_cancel_and_free(obj + rec->timer_off);
625 }
626
627 extern void __bpf_obj_drop_impl(void *p, const struct btf_record *rec);
628
629 void bpf_obj_free_fields(const struct btf_record *rec, void *obj)
630 {
631         const struct btf_field *fields;
632         int i;
633
634         if (IS_ERR_OR_NULL(rec))
635                 return;
636         fields = rec->fields;
637         for (i = 0; i < rec->cnt; i++) {
638                 struct btf_struct_meta *pointee_struct_meta;
639                 const struct btf_field *field = &fields[i];
640                 void *field_ptr = obj + field->offset;
641                 void *xchgd_field;
642
643                 switch (fields[i].type) {
644                 case BPF_SPIN_LOCK:
645                         break;
646                 case BPF_TIMER:
647                         bpf_timer_cancel_and_free(field_ptr);
648                         break;
649                 case BPF_KPTR_UNREF:
650                         WRITE_ONCE(*(u64 *)field_ptr, 0);
651                         break;
652                 case BPF_KPTR_REF:
653                         xchgd_field = (void *)xchg((unsigned long *)field_ptr, 0);
654                         if (!xchgd_field)
655                                 break;
656
657                         if (!btf_is_kernel(field->kptr.btf)) {
658                                 pointee_struct_meta = btf_find_struct_meta(field->kptr.btf,
659                                                                            field->kptr.btf_id);
660                                 migrate_disable();
661                                 __bpf_obj_drop_impl(xchgd_field, pointee_struct_meta ?
662                                                                  pointee_struct_meta->record :
663                                                                  NULL);
664                                 migrate_enable();
665                         } else {
666                                 field->kptr.dtor(xchgd_field);
667                         }
668                         break;
669                 case BPF_LIST_HEAD:
670                         if (WARN_ON_ONCE(rec->spin_lock_off < 0))
671                                 continue;
672                         bpf_list_head_free(field, field_ptr, obj + rec->spin_lock_off);
673                         break;
674                 case BPF_RB_ROOT:
675                         if (WARN_ON_ONCE(rec->spin_lock_off < 0))
676                                 continue;
677                         bpf_rb_root_free(field, field_ptr, obj + rec->spin_lock_off);
678                         break;
679                 case BPF_LIST_NODE:
680                 case BPF_RB_NODE:
681                 case BPF_REFCOUNT:
682                         break;
683                 default:
684                         WARN_ON_ONCE(1);
685                         continue;
686                 }
687         }
688 }
689
690 /* called from workqueue */
691 static void bpf_map_free_deferred(struct work_struct *work)
692 {
693         struct bpf_map *map = container_of(work, struct bpf_map, work);
694         struct btf_record *rec = map->record;
695
696         security_bpf_map_free(map);
697         bpf_map_release_memcg(map);
698         /* implementation dependent freeing */
699         map->ops->map_free(map);
700         /* Delay freeing of btf_record for maps, as map_free
701          * callback usually needs access to them. It is better to do it here
702          * than require each callback to do the free itself manually.
703          *
704          * Note that the btf_record stashed in map->inner_map_meta->record was
705          * already freed using the map_free callback for map in map case which
706          * eventually calls bpf_map_free_meta, since inner_map_meta is only a
707          * template bpf_map struct used during verification.
708          */
709         btf_record_free(rec);
710 }
711
712 static void bpf_map_put_uref(struct bpf_map *map)
713 {
714         if (atomic64_dec_and_test(&map->usercnt)) {
715                 if (map->ops->map_release_uref)
716                         map->ops->map_release_uref(map);
717         }
718 }
719
720 static void bpf_map_free_in_work(struct bpf_map *map)
721 {
722         INIT_WORK(&map->work, bpf_map_free_deferred);
723         /* Avoid spawning kworkers, since they all might contend
724          * for the same mutex like slab_mutex.
725          */
726         queue_work(system_unbound_wq, &map->work);
727 }
728
729 static void bpf_map_free_rcu_gp(struct rcu_head *rcu)
730 {
731         bpf_map_free_in_work(container_of(rcu, struct bpf_map, rcu));
732 }
733
734 static void bpf_map_free_mult_rcu_gp(struct rcu_head *rcu)
735 {
736         if (rcu_trace_implies_rcu_gp())
737                 bpf_map_free_rcu_gp(rcu);
738         else
739                 call_rcu(rcu, bpf_map_free_rcu_gp);
740 }
741
742 /* decrement map refcnt and schedule it for freeing via workqueue
743  * (underlying map implementation ops->map_free() might sleep)
744  */
745 void bpf_map_put(struct bpf_map *map)
746 {
747         if (atomic64_dec_and_test(&map->refcnt)) {
748                 /* bpf_map_free_id() must be called first */
749                 bpf_map_free_id(map);
750                 btf_put(map->btf);
751
752                 if (READ_ONCE(map->free_after_mult_rcu_gp))
753                         call_rcu_tasks_trace(&map->rcu, bpf_map_free_mult_rcu_gp);
754                 else
755                         bpf_map_free_in_work(map);
756         }
757 }
758 EXPORT_SYMBOL_GPL(bpf_map_put);
759
760 void bpf_map_put_with_uref(struct bpf_map *map)
761 {
762         bpf_map_put_uref(map);
763         bpf_map_put(map);
764 }
765
766 static int bpf_map_release(struct inode *inode, struct file *filp)
767 {
768         struct bpf_map *map = filp->private_data;
769
770         if (map->ops->map_release)
771                 map->ops->map_release(map, filp);
772
773         bpf_map_put_with_uref(map);
774         return 0;
775 }
776
777 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
778 {
779         fmode_t mode = f.file->f_mode;
780
781         /* Our file permissions may have been overridden by global
782          * map permissions facing syscall side.
783          */
784         if (READ_ONCE(map->frozen))
785                 mode &= ~FMODE_CAN_WRITE;
786         return mode;
787 }
788
789 #ifdef CONFIG_PROC_FS
790 /* Show the memory usage of a bpf map */
791 static u64 bpf_map_memory_usage(const struct bpf_map *map)
792 {
793         return map->ops->map_mem_usage(map);
794 }
795
796 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
797 {
798         struct bpf_map *map = filp->private_data;
799         u32 type = 0, jited = 0;
800
801         if (map_type_contains_progs(map)) {
802                 spin_lock(&map->owner.lock);
803                 type  = map->owner.type;
804                 jited = map->owner.jited;
805                 spin_unlock(&map->owner.lock);
806         }
807
808         seq_printf(m,
809                    "map_type:\t%u\n"
810                    "key_size:\t%u\n"
811                    "value_size:\t%u\n"
812                    "max_entries:\t%u\n"
813                    "map_flags:\t%#x\n"
814                    "map_extra:\t%#llx\n"
815                    "memlock:\t%llu\n"
816                    "map_id:\t%u\n"
817                    "frozen:\t%u\n",
818                    map->map_type,
819                    map->key_size,
820                    map->value_size,
821                    map->max_entries,
822                    map->map_flags,
823                    (unsigned long long)map->map_extra,
824                    bpf_map_memory_usage(map),
825                    map->id,
826                    READ_ONCE(map->frozen));
827         if (type) {
828                 seq_printf(m, "owner_prog_type:\t%u\n", type);
829                 seq_printf(m, "owner_jited:\t%u\n", jited);
830         }
831 }
832 #endif
833
834 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
835                               loff_t *ppos)
836 {
837         /* We need this handler such that alloc_file() enables
838          * f_mode with FMODE_CAN_READ.
839          */
840         return -EINVAL;
841 }
842
843 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
844                                size_t siz, loff_t *ppos)
845 {
846         /* We need this handler such that alloc_file() enables
847          * f_mode with FMODE_CAN_WRITE.
848          */
849         return -EINVAL;
850 }
851
852 /* called for any extra memory-mapped regions (except initial) */
853 static void bpf_map_mmap_open(struct vm_area_struct *vma)
854 {
855         struct bpf_map *map = vma->vm_file->private_data;
856
857         if (vma->vm_flags & VM_MAYWRITE)
858                 bpf_map_write_active_inc(map);
859 }
860
861 /* called for all unmapped memory region (including initial) */
862 static void bpf_map_mmap_close(struct vm_area_struct *vma)
863 {
864         struct bpf_map *map = vma->vm_file->private_data;
865
866         if (vma->vm_flags & VM_MAYWRITE)
867                 bpf_map_write_active_dec(map);
868 }
869
870 static const struct vm_operations_struct bpf_map_default_vmops = {
871         .open           = bpf_map_mmap_open,
872         .close          = bpf_map_mmap_close,
873 };
874
875 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
876 {
877         struct bpf_map *map = filp->private_data;
878         int err;
879
880         if (!map->ops->map_mmap || !IS_ERR_OR_NULL(map->record))
881                 return -ENOTSUPP;
882
883         if (!(vma->vm_flags & VM_SHARED))
884                 return -EINVAL;
885
886         mutex_lock(&map->freeze_mutex);
887
888         if (vma->vm_flags & VM_WRITE) {
889                 if (map->frozen) {
890                         err = -EPERM;
891                         goto out;
892                 }
893                 /* map is meant to be read-only, so do not allow mapping as
894                  * writable, because it's possible to leak a writable page
895                  * reference and allows user-space to still modify it after
896                  * freezing, while verifier will assume contents do not change
897                  */
898                 if (map->map_flags & BPF_F_RDONLY_PROG) {
899                         err = -EACCES;
900                         goto out;
901                 }
902         }
903
904         /* set default open/close callbacks */
905         vma->vm_ops = &bpf_map_default_vmops;
906         vma->vm_private_data = map;
907         vm_flags_clear(vma, VM_MAYEXEC);
908         if (!(vma->vm_flags & VM_WRITE))
909                 /* disallow re-mapping with PROT_WRITE */
910                 vm_flags_clear(vma, VM_MAYWRITE);
911
912         err = map->ops->map_mmap(map, vma);
913         if (err)
914                 goto out;
915
916         if (vma->vm_flags & VM_MAYWRITE)
917                 bpf_map_write_active_inc(map);
918 out:
919         mutex_unlock(&map->freeze_mutex);
920         return err;
921 }
922
923 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
924 {
925         struct bpf_map *map = filp->private_data;
926
927         if (map->ops->map_poll)
928                 return map->ops->map_poll(map, filp, pts);
929
930         return EPOLLERR;
931 }
932
933 const struct file_operations bpf_map_fops = {
934 #ifdef CONFIG_PROC_FS
935         .show_fdinfo    = bpf_map_show_fdinfo,
936 #endif
937         .release        = bpf_map_release,
938         .read           = bpf_dummy_read,
939         .write          = bpf_dummy_write,
940         .mmap           = bpf_map_mmap,
941         .poll           = bpf_map_poll,
942 };
943
944 int bpf_map_new_fd(struct bpf_map *map, int flags)
945 {
946         int ret;
947
948         ret = security_bpf_map(map, OPEN_FMODE(flags));
949         if (ret < 0)
950                 return ret;
951
952         return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
953                                 flags | O_CLOEXEC);
954 }
955
956 int bpf_get_file_flag(int flags)
957 {
958         if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
959                 return -EINVAL;
960         if (flags & BPF_F_RDONLY)
961                 return O_RDONLY;
962         if (flags & BPF_F_WRONLY)
963                 return O_WRONLY;
964         return O_RDWR;
965 }
966
967 /* helper macro to check that unused fields 'union bpf_attr' are zero */
968 #define CHECK_ATTR(CMD) \
969         memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
970                    sizeof(attr->CMD##_LAST_FIELD), 0, \
971                    sizeof(*attr) - \
972                    offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
973                    sizeof(attr->CMD##_LAST_FIELD)) != NULL
974
975 /* dst and src must have at least "size" number of bytes.
976  * Return strlen on success and < 0 on error.
977  */
978 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
979 {
980         const char *end = src + size;
981         const char *orig_src = src;
982
983         memset(dst, 0, size);
984         /* Copy all isalnum(), '_' and '.' chars. */
985         while (src < end && *src) {
986                 if (!isalnum(*src) &&
987                     *src != '_' && *src != '.')
988                         return -EINVAL;
989                 *dst++ = *src++;
990         }
991
992         /* No '\0' found in "size" number of bytes */
993         if (src == end)
994                 return -EINVAL;
995
996         return src - orig_src;
997 }
998
999 int map_check_no_btf(const struct bpf_map *map,
1000                      const struct btf *btf,
1001                      const struct btf_type *key_type,
1002                      const struct btf_type *value_type)
1003 {
1004         return -ENOTSUPP;
1005 }
1006
1007 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
1008                          u32 btf_key_id, u32 btf_value_id)
1009 {
1010         const struct btf_type *key_type, *value_type;
1011         u32 key_size, value_size;
1012         int ret = 0;
1013
1014         /* Some maps allow key to be unspecified. */
1015         if (btf_key_id) {
1016                 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
1017                 if (!key_type || key_size != map->key_size)
1018                         return -EINVAL;
1019         } else {
1020                 key_type = btf_type_by_id(btf, 0);
1021                 if (!map->ops->map_check_btf)
1022                         return -EINVAL;
1023         }
1024
1025         value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
1026         if (!value_type || value_size != map->value_size)
1027                 return -EINVAL;
1028
1029         map->record = btf_parse_fields(btf, value_type,
1030                                        BPF_SPIN_LOCK | BPF_TIMER | BPF_KPTR | BPF_LIST_HEAD |
1031                                        BPF_RB_ROOT | BPF_REFCOUNT,
1032                                        map->value_size);
1033         if (!IS_ERR_OR_NULL(map->record)) {
1034                 int i;
1035
1036                 if (!bpf_capable()) {
1037                         ret = -EPERM;
1038                         goto free_map_tab;
1039                 }
1040                 if (map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) {
1041                         ret = -EACCES;
1042                         goto free_map_tab;
1043                 }
1044                 for (i = 0; i < sizeof(map->record->field_mask) * 8; i++) {
1045                         switch (map->record->field_mask & (1 << i)) {
1046                         case 0:
1047                                 continue;
1048                         case BPF_SPIN_LOCK:
1049                                 if (map->map_type != BPF_MAP_TYPE_HASH &&
1050                                     map->map_type != BPF_MAP_TYPE_ARRAY &&
1051                                     map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
1052                                     map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1053                                     map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1054                                     map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1055                                     map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1056                                         ret = -EOPNOTSUPP;
1057                                         goto free_map_tab;
1058                                 }
1059                                 break;
1060                         case BPF_TIMER:
1061                                 if (map->map_type != BPF_MAP_TYPE_HASH &&
1062                                     map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1063                                     map->map_type != BPF_MAP_TYPE_ARRAY) {
1064                                         ret = -EOPNOTSUPP;
1065                                         goto free_map_tab;
1066                                 }
1067                                 break;
1068                         case BPF_KPTR_UNREF:
1069                         case BPF_KPTR_REF:
1070                         case BPF_REFCOUNT:
1071                                 if (map->map_type != BPF_MAP_TYPE_HASH &&
1072                                     map->map_type != BPF_MAP_TYPE_PERCPU_HASH &&
1073                                     map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1074                                     map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH &&
1075                                     map->map_type != BPF_MAP_TYPE_ARRAY &&
1076                                     map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY &&
1077                                     map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
1078                                     map->map_type != BPF_MAP_TYPE_INODE_STORAGE &&
1079                                     map->map_type != BPF_MAP_TYPE_TASK_STORAGE &&
1080                                     map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) {
1081                                         ret = -EOPNOTSUPP;
1082                                         goto free_map_tab;
1083                                 }
1084                                 break;
1085                         case BPF_LIST_HEAD:
1086                         case BPF_RB_ROOT:
1087                                 if (map->map_type != BPF_MAP_TYPE_HASH &&
1088                                     map->map_type != BPF_MAP_TYPE_LRU_HASH &&
1089                                     map->map_type != BPF_MAP_TYPE_ARRAY) {
1090                                         ret = -EOPNOTSUPP;
1091                                         goto free_map_tab;
1092                                 }
1093                                 break;
1094                         default:
1095                                 /* Fail if map_type checks are missing for a field type */
1096                                 ret = -EOPNOTSUPP;
1097                                 goto free_map_tab;
1098                         }
1099                 }
1100         }
1101
1102         ret = btf_check_and_fixup_fields(btf, map->record);
1103         if (ret < 0)
1104                 goto free_map_tab;
1105
1106         if (map->ops->map_check_btf) {
1107                 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
1108                 if (ret < 0)
1109                         goto free_map_tab;
1110         }
1111
1112         return ret;
1113 free_map_tab:
1114         bpf_map_free_record(map);
1115         return ret;
1116 }
1117
1118 #define BPF_MAP_CREATE_LAST_FIELD map_extra
1119 /* called via syscall */
1120 static int map_create(union bpf_attr *attr)
1121 {
1122         const struct bpf_map_ops *ops;
1123         int numa_node = bpf_map_attr_numa_node(attr);
1124         u32 map_type = attr->map_type;
1125         struct bpf_map *map;
1126         int f_flags;
1127         int err;
1128
1129         err = CHECK_ATTR(BPF_MAP_CREATE);
1130         if (err)
1131                 return -EINVAL;
1132
1133         if (attr->btf_vmlinux_value_type_id) {
1134                 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
1135                     attr->btf_key_type_id || attr->btf_value_type_id)
1136                         return -EINVAL;
1137         } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
1138                 return -EINVAL;
1139         }
1140
1141         if (attr->map_type != BPF_MAP_TYPE_BLOOM_FILTER &&
1142             attr->map_extra != 0)
1143                 return -EINVAL;
1144
1145         f_flags = bpf_get_file_flag(attr->map_flags);
1146         if (f_flags < 0)
1147                 return f_flags;
1148
1149         if (numa_node != NUMA_NO_NODE &&
1150             ((unsigned int)numa_node >= nr_node_ids ||
1151              !node_online(numa_node)))
1152                 return -EINVAL;
1153
1154         /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
1155         map_type = attr->map_type;
1156         if (map_type >= ARRAY_SIZE(bpf_map_types))
1157                 return -EINVAL;
1158         map_type = array_index_nospec(map_type, ARRAY_SIZE(bpf_map_types));
1159         ops = bpf_map_types[map_type];
1160         if (!ops)
1161                 return -EINVAL;
1162
1163         if (ops->map_alloc_check) {
1164                 err = ops->map_alloc_check(attr);
1165                 if (err)
1166                         return err;
1167         }
1168         if (attr->map_ifindex)
1169                 ops = &bpf_map_offload_ops;
1170         if (!ops->map_mem_usage)
1171                 return -EINVAL;
1172
1173         /* Intent here is for unprivileged_bpf_disabled to block BPF map
1174          * creation for unprivileged users; other actions depend
1175          * on fd availability and access to bpffs, so are dependent on
1176          * object creation success. Even with unprivileged BPF disabled,
1177          * capability checks are still carried out.
1178          */
1179         if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
1180                 return -EPERM;
1181
1182         /* check privileged map type permissions */
1183         switch (map_type) {
1184         case BPF_MAP_TYPE_ARRAY:
1185         case BPF_MAP_TYPE_PERCPU_ARRAY:
1186         case BPF_MAP_TYPE_PROG_ARRAY:
1187         case BPF_MAP_TYPE_PERF_EVENT_ARRAY:
1188         case BPF_MAP_TYPE_CGROUP_ARRAY:
1189         case BPF_MAP_TYPE_ARRAY_OF_MAPS:
1190         case BPF_MAP_TYPE_HASH:
1191         case BPF_MAP_TYPE_PERCPU_HASH:
1192         case BPF_MAP_TYPE_HASH_OF_MAPS:
1193         case BPF_MAP_TYPE_RINGBUF:
1194         case BPF_MAP_TYPE_USER_RINGBUF:
1195         case BPF_MAP_TYPE_CGROUP_STORAGE:
1196         case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
1197                 /* unprivileged */
1198                 break;
1199         case BPF_MAP_TYPE_SK_STORAGE:
1200         case BPF_MAP_TYPE_INODE_STORAGE:
1201         case BPF_MAP_TYPE_TASK_STORAGE:
1202         case BPF_MAP_TYPE_CGRP_STORAGE:
1203         case BPF_MAP_TYPE_BLOOM_FILTER:
1204         case BPF_MAP_TYPE_LPM_TRIE:
1205         case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY:
1206         case BPF_MAP_TYPE_STACK_TRACE:
1207         case BPF_MAP_TYPE_QUEUE:
1208         case BPF_MAP_TYPE_STACK:
1209         case BPF_MAP_TYPE_LRU_HASH:
1210         case BPF_MAP_TYPE_LRU_PERCPU_HASH:
1211         case BPF_MAP_TYPE_STRUCT_OPS:
1212         case BPF_MAP_TYPE_CPUMAP:
1213                 if (!bpf_capable())
1214                         return -EPERM;
1215                 break;
1216         case BPF_MAP_TYPE_SOCKMAP:
1217         case BPF_MAP_TYPE_SOCKHASH:
1218         case BPF_MAP_TYPE_DEVMAP:
1219         case BPF_MAP_TYPE_DEVMAP_HASH:
1220         case BPF_MAP_TYPE_XSKMAP:
1221                 if (!capable(CAP_NET_ADMIN))
1222                         return -EPERM;
1223                 break;
1224         default:
1225                 WARN(1, "unsupported map type %d", map_type);
1226                 return -EPERM;
1227         }
1228
1229         map = ops->map_alloc(attr);
1230         if (IS_ERR(map))
1231                 return PTR_ERR(map);
1232         map->ops = ops;
1233         map->map_type = map_type;
1234
1235         err = bpf_obj_name_cpy(map->name, attr->map_name,
1236                                sizeof(attr->map_name));
1237         if (err < 0)
1238                 goto free_map;
1239
1240         atomic64_set(&map->refcnt, 1);
1241         atomic64_set(&map->usercnt, 1);
1242         mutex_init(&map->freeze_mutex);
1243         spin_lock_init(&map->owner.lock);
1244
1245         if (attr->btf_key_type_id || attr->btf_value_type_id ||
1246             /* Even the map's value is a kernel's struct,
1247              * the bpf_prog.o must have BTF to begin with
1248              * to figure out the corresponding kernel's
1249              * counter part.  Thus, attr->btf_fd has
1250              * to be valid also.
1251              */
1252             attr->btf_vmlinux_value_type_id) {
1253                 struct btf *btf;
1254
1255                 btf = btf_get_by_fd(attr->btf_fd);
1256                 if (IS_ERR(btf)) {
1257                         err = PTR_ERR(btf);
1258                         goto free_map;
1259                 }
1260                 if (btf_is_kernel(btf)) {
1261                         btf_put(btf);
1262                         err = -EACCES;
1263                         goto free_map;
1264                 }
1265                 map->btf = btf;
1266
1267                 if (attr->btf_value_type_id) {
1268                         err = map_check_btf(map, btf, attr->btf_key_type_id,
1269                                             attr->btf_value_type_id);
1270                         if (err)
1271                                 goto free_map;
1272                 }
1273
1274                 map->btf_key_type_id = attr->btf_key_type_id;
1275                 map->btf_value_type_id = attr->btf_value_type_id;
1276                 map->btf_vmlinux_value_type_id =
1277                         attr->btf_vmlinux_value_type_id;
1278         }
1279
1280         err = security_bpf_map_alloc(map);
1281         if (err)
1282                 goto free_map;
1283
1284         err = bpf_map_alloc_id(map);
1285         if (err)
1286                 goto free_map_sec;
1287
1288         bpf_map_save_memcg(map);
1289
1290         err = bpf_map_new_fd(map, f_flags);
1291         if (err < 0) {
1292                 /* failed to allocate fd.
1293                  * bpf_map_put_with_uref() is needed because the above
1294                  * bpf_map_alloc_id() has published the map
1295                  * to the userspace and the userspace may
1296                  * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
1297                  */
1298                 bpf_map_put_with_uref(map);
1299                 return err;
1300         }
1301
1302         return err;
1303
1304 free_map_sec:
1305         security_bpf_map_free(map);
1306 free_map:
1307         btf_put(map->btf);
1308         map->ops->map_free(map);
1309         return err;
1310 }
1311
1312 /* if error is returned, fd is released.
1313  * On success caller should complete fd access with matching fdput()
1314  */
1315 struct bpf_map *__bpf_map_get(struct fd f)
1316 {
1317         if (!f.file)
1318                 return ERR_PTR(-EBADF);
1319         if (f.file->f_op != &bpf_map_fops) {
1320                 fdput(f);
1321                 return ERR_PTR(-EINVAL);
1322         }
1323
1324         return f.file->private_data;
1325 }
1326
1327 void bpf_map_inc(struct bpf_map *map)
1328 {
1329         atomic64_inc(&map->refcnt);
1330 }
1331 EXPORT_SYMBOL_GPL(bpf_map_inc);
1332
1333 void bpf_map_inc_with_uref(struct bpf_map *map)
1334 {
1335         atomic64_inc(&map->refcnt);
1336         atomic64_inc(&map->usercnt);
1337 }
1338 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
1339
1340 struct bpf_map *bpf_map_get(u32 ufd)
1341 {
1342         struct fd f = fdget(ufd);
1343         struct bpf_map *map;
1344
1345         map = __bpf_map_get(f);
1346         if (IS_ERR(map))
1347                 return map;
1348
1349         bpf_map_inc(map);
1350         fdput(f);
1351
1352         return map;
1353 }
1354 EXPORT_SYMBOL(bpf_map_get);
1355
1356 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
1357 {
1358         struct fd f = fdget(ufd);
1359         struct bpf_map *map;
1360
1361         map = __bpf_map_get(f);
1362         if (IS_ERR(map))
1363                 return map;
1364
1365         bpf_map_inc_with_uref(map);
1366         fdput(f);
1367
1368         return map;
1369 }
1370
1371 /* map_idr_lock should have been held or the map should have been
1372  * protected by rcu read lock.
1373  */
1374 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
1375 {
1376         int refold;
1377
1378         refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
1379         if (!refold)
1380                 return ERR_PTR(-ENOENT);
1381         if (uref)
1382                 atomic64_inc(&map->usercnt);
1383
1384         return map;
1385 }
1386
1387 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1388 {
1389         spin_lock_bh(&map_idr_lock);
1390         map = __bpf_map_inc_not_zero(map, false);
1391         spin_unlock_bh(&map_idr_lock);
1392
1393         return map;
1394 }
1395 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1396
1397 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1398 {
1399         return -ENOTSUPP;
1400 }
1401
1402 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1403 {
1404         if (key_size)
1405                 return vmemdup_user(ukey, key_size);
1406
1407         if (ukey)
1408                 return ERR_PTR(-EINVAL);
1409
1410         return NULL;
1411 }
1412
1413 static void *___bpf_copy_key(bpfptr_t ukey, u64 key_size)
1414 {
1415         if (key_size)
1416                 return kvmemdup_bpfptr(ukey, key_size);
1417
1418         if (!bpfptr_is_null(ukey))
1419                 return ERR_PTR(-EINVAL);
1420
1421         return NULL;
1422 }
1423
1424 /* last field in 'union bpf_attr' used by this command */
1425 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1426
1427 static int map_lookup_elem(union bpf_attr *attr)
1428 {
1429         void __user *ukey = u64_to_user_ptr(attr->key);
1430         void __user *uvalue = u64_to_user_ptr(attr->value);
1431         int ufd = attr->map_fd;
1432         struct bpf_map *map;
1433         void *key, *value;
1434         u32 value_size;
1435         struct fd f;
1436         int err;
1437
1438         if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1439                 return -EINVAL;
1440
1441         if (attr->flags & ~BPF_F_LOCK)
1442                 return -EINVAL;
1443
1444         f = fdget(ufd);
1445         map = __bpf_map_get(f);
1446         if (IS_ERR(map))
1447                 return PTR_ERR(map);
1448         if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1449                 err = -EPERM;
1450                 goto err_put;
1451         }
1452
1453         if ((attr->flags & BPF_F_LOCK) &&
1454             !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1455                 err = -EINVAL;
1456                 goto err_put;
1457         }
1458
1459         key = __bpf_copy_key(ukey, map->key_size);
1460         if (IS_ERR(key)) {
1461                 err = PTR_ERR(key);
1462                 goto err_put;
1463         }
1464
1465         value_size = bpf_map_value_size(map);
1466
1467         err = -ENOMEM;
1468         value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1469         if (!value)
1470                 goto free_key;
1471
1472         if (map->map_type == BPF_MAP_TYPE_BLOOM_FILTER) {
1473                 if (copy_from_user(value, uvalue, value_size))
1474                         err = -EFAULT;
1475                 else
1476                         err = bpf_map_copy_value(map, key, value, attr->flags);
1477                 goto free_value;
1478         }
1479
1480         err = bpf_map_copy_value(map, key, value, attr->flags);
1481         if (err)
1482                 goto free_value;
1483
1484         err = -EFAULT;
1485         if (copy_to_user(uvalue, value, value_size) != 0)
1486                 goto free_value;
1487
1488         err = 0;
1489
1490 free_value:
1491         kvfree(value);
1492 free_key:
1493         kvfree(key);
1494 err_put:
1495         fdput(f);
1496         return err;
1497 }
1498
1499
1500 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1501
1502 static int map_update_elem(union bpf_attr *attr, bpfptr_t uattr)
1503 {
1504         bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1505         bpfptr_t uvalue = make_bpfptr(attr->value, uattr.is_kernel);
1506         int ufd = attr->map_fd;
1507         struct bpf_map *map;
1508         void *key, *value;
1509         u32 value_size;
1510         struct fd f;
1511         int err;
1512
1513         if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1514                 return -EINVAL;
1515
1516         f = fdget(ufd);
1517         map = __bpf_map_get(f);
1518         if (IS_ERR(map))
1519                 return PTR_ERR(map);
1520         bpf_map_write_active_inc(map);
1521         if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1522                 err = -EPERM;
1523                 goto err_put;
1524         }
1525
1526         if ((attr->flags & BPF_F_LOCK) &&
1527             !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1528                 err = -EINVAL;
1529                 goto err_put;
1530         }
1531
1532         key = ___bpf_copy_key(ukey, map->key_size);
1533         if (IS_ERR(key)) {
1534                 err = PTR_ERR(key);
1535                 goto err_put;
1536         }
1537
1538         value_size = bpf_map_value_size(map);
1539         value = kvmemdup_bpfptr(uvalue, value_size);
1540         if (IS_ERR(value)) {
1541                 err = PTR_ERR(value);
1542                 goto free_key;
1543         }
1544
1545         err = bpf_map_update_value(map, f.file, key, value, attr->flags);
1546
1547         kvfree(value);
1548 free_key:
1549         kvfree(key);
1550 err_put:
1551         bpf_map_write_active_dec(map);
1552         fdput(f);
1553         return err;
1554 }
1555
1556 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1557
1558 static int map_delete_elem(union bpf_attr *attr, bpfptr_t uattr)
1559 {
1560         bpfptr_t ukey = make_bpfptr(attr->key, uattr.is_kernel);
1561         int ufd = attr->map_fd;
1562         struct bpf_map *map;
1563         struct fd f;
1564         void *key;
1565         int err;
1566
1567         if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1568                 return -EINVAL;
1569
1570         f = fdget(ufd);
1571         map = __bpf_map_get(f);
1572         if (IS_ERR(map))
1573                 return PTR_ERR(map);
1574         bpf_map_write_active_inc(map);
1575         if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1576                 err = -EPERM;
1577                 goto err_put;
1578         }
1579
1580         key = ___bpf_copy_key(ukey, map->key_size);
1581         if (IS_ERR(key)) {
1582                 err = PTR_ERR(key);
1583                 goto err_put;
1584         }
1585
1586         if (bpf_map_is_offloaded(map)) {
1587                 err = bpf_map_offload_delete_elem(map, key);
1588                 goto out;
1589         } else if (IS_FD_PROG_ARRAY(map) ||
1590                    map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1591                 /* These maps require sleepable context */
1592                 err = map->ops->map_delete_elem(map, key);
1593                 goto out;
1594         }
1595
1596         bpf_disable_instrumentation();
1597         rcu_read_lock();
1598         err = map->ops->map_delete_elem(map, key);
1599         rcu_read_unlock();
1600         bpf_enable_instrumentation();
1601         maybe_wait_bpf_programs(map);
1602 out:
1603         kvfree(key);
1604 err_put:
1605         bpf_map_write_active_dec(map);
1606         fdput(f);
1607         return err;
1608 }
1609
1610 /* last field in 'union bpf_attr' used by this command */
1611 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1612
1613 static int map_get_next_key(union bpf_attr *attr)
1614 {
1615         void __user *ukey = u64_to_user_ptr(attr->key);
1616         void __user *unext_key = u64_to_user_ptr(attr->next_key);
1617         int ufd = attr->map_fd;
1618         struct bpf_map *map;
1619         void *key, *next_key;
1620         struct fd f;
1621         int err;
1622
1623         if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1624                 return -EINVAL;
1625
1626         f = fdget(ufd);
1627         map = __bpf_map_get(f);
1628         if (IS_ERR(map))
1629                 return PTR_ERR(map);
1630         if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1631                 err = -EPERM;
1632                 goto err_put;
1633         }
1634
1635         if (ukey) {
1636                 key = __bpf_copy_key(ukey, map->key_size);
1637                 if (IS_ERR(key)) {
1638                         err = PTR_ERR(key);
1639                         goto err_put;
1640                 }
1641         } else {
1642                 key = NULL;
1643         }
1644
1645         err = -ENOMEM;
1646         next_key = kvmalloc(map->key_size, GFP_USER);
1647         if (!next_key)
1648                 goto free_key;
1649
1650         if (bpf_map_is_offloaded(map)) {
1651                 err = bpf_map_offload_get_next_key(map, key, next_key);
1652                 goto out;
1653         }
1654
1655         rcu_read_lock();
1656         err = map->ops->map_get_next_key(map, key, next_key);
1657         rcu_read_unlock();
1658 out:
1659         if (err)
1660                 goto free_next_key;
1661
1662         err = -EFAULT;
1663         if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1664                 goto free_next_key;
1665
1666         err = 0;
1667
1668 free_next_key:
1669         kvfree(next_key);
1670 free_key:
1671         kvfree(key);
1672 err_put:
1673         fdput(f);
1674         return err;
1675 }
1676
1677 int generic_map_delete_batch(struct bpf_map *map,
1678                              const union bpf_attr *attr,
1679                              union bpf_attr __user *uattr)
1680 {
1681         void __user *keys = u64_to_user_ptr(attr->batch.keys);
1682         u32 cp, max_count;
1683         int err = 0;
1684         void *key;
1685
1686         if (attr->batch.elem_flags & ~BPF_F_LOCK)
1687                 return -EINVAL;
1688
1689         if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1690             !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1691                 return -EINVAL;
1692         }
1693
1694         max_count = attr->batch.count;
1695         if (!max_count)
1696                 return 0;
1697
1698         key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1699         if (!key)
1700                 return -ENOMEM;
1701
1702         for (cp = 0; cp < max_count; cp++) {
1703                 err = -EFAULT;
1704                 if (copy_from_user(key, keys + cp * map->key_size,
1705                                    map->key_size))
1706                         break;
1707
1708                 if (bpf_map_is_offloaded(map)) {
1709                         err = bpf_map_offload_delete_elem(map, key);
1710                         break;
1711                 }
1712
1713                 bpf_disable_instrumentation();
1714                 rcu_read_lock();
1715                 err = map->ops->map_delete_elem(map, key);
1716                 rcu_read_unlock();
1717                 bpf_enable_instrumentation();
1718                 if (err)
1719                         break;
1720                 cond_resched();
1721         }
1722         if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1723                 err = -EFAULT;
1724
1725         kvfree(key);
1726
1727         maybe_wait_bpf_programs(map);
1728         return err;
1729 }
1730
1731 int generic_map_update_batch(struct bpf_map *map, struct file *map_file,
1732                              const union bpf_attr *attr,
1733                              union bpf_attr __user *uattr)
1734 {
1735         void __user *values = u64_to_user_ptr(attr->batch.values);
1736         void __user *keys = u64_to_user_ptr(attr->batch.keys);
1737         u32 value_size, cp, max_count;
1738         void *key, *value;
1739         int err = 0;
1740
1741         if (attr->batch.elem_flags & ~BPF_F_LOCK)
1742                 return -EINVAL;
1743
1744         if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1745             !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1746                 return -EINVAL;
1747         }
1748
1749         value_size = bpf_map_value_size(map);
1750
1751         max_count = attr->batch.count;
1752         if (!max_count)
1753                 return 0;
1754
1755         key = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1756         if (!key)
1757                 return -ENOMEM;
1758
1759         value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1760         if (!value) {
1761                 kvfree(key);
1762                 return -ENOMEM;
1763         }
1764
1765         for (cp = 0; cp < max_count; cp++) {
1766                 err = -EFAULT;
1767                 if (copy_from_user(key, keys + cp * map->key_size,
1768                     map->key_size) ||
1769                     copy_from_user(value, values + cp * value_size, value_size))
1770                         break;
1771
1772                 err = bpf_map_update_value(map, map_file, key, value,
1773                                            attr->batch.elem_flags);
1774
1775                 if (err)
1776                         break;
1777                 cond_resched();
1778         }
1779
1780         if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1781                 err = -EFAULT;
1782
1783         kvfree(value);
1784         kvfree(key);
1785         return err;
1786 }
1787
1788 #define MAP_LOOKUP_RETRIES 3
1789
1790 int generic_map_lookup_batch(struct bpf_map *map,
1791                                     const union bpf_attr *attr,
1792                                     union bpf_attr __user *uattr)
1793 {
1794         void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1795         void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1796         void __user *values = u64_to_user_ptr(attr->batch.values);
1797         void __user *keys = u64_to_user_ptr(attr->batch.keys);
1798         void *buf, *buf_prevkey, *prev_key, *key, *value;
1799         int err, retry = MAP_LOOKUP_RETRIES;
1800         u32 value_size, cp, max_count;
1801
1802         if (attr->batch.elem_flags & ~BPF_F_LOCK)
1803                 return -EINVAL;
1804
1805         if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1806             !btf_record_has_field(map->record, BPF_SPIN_LOCK))
1807                 return -EINVAL;
1808
1809         value_size = bpf_map_value_size(map);
1810
1811         max_count = attr->batch.count;
1812         if (!max_count)
1813                 return 0;
1814
1815         if (put_user(0, &uattr->batch.count))
1816                 return -EFAULT;
1817
1818         buf_prevkey = kvmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1819         if (!buf_prevkey)
1820                 return -ENOMEM;
1821
1822         buf = kvmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1823         if (!buf) {
1824                 kvfree(buf_prevkey);
1825                 return -ENOMEM;
1826         }
1827
1828         err = -EFAULT;
1829         prev_key = NULL;
1830         if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1831                 goto free_buf;
1832         key = buf;
1833         value = key + map->key_size;
1834         if (ubatch)
1835                 prev_key = buf_prevkey;
1836
1837         for (cp = 0; cp < max_count;) {
1838                 rcu_read_lock();
1839                 err = map->ops->map_get_next_key(map, prev_key, key);
1840                 rcu_read_unlock();
1841                 if (err)
1842                         break;
1843                 err = bpf_map_copy_value(map, key, value,
1844                                          attr->batch.elem_flags);
1845
1846                 if (err == -ENOENT) {
1847                         if (retry) {
1848                                 retry--;
1849                                 continue;
1850                         }
1851                         err = -EINTR;
1852                         break;
1853                 }
1854
1855                 if (err)
1856                         goto free_buf;
1857
1858                 if (copy_to_user(keys + cp * map->key_size, key,
1859                                  map->key_size)) {
1860                         err = -EFAULT;
1861                         goto free_buf;
1862                 }
1863                 if (copy_to_user(values + cp * value_size, value, value_size)) {
1864                         err = -EFAULT;
1865                         goto free_buf;
1866                 }
1867
1868                 if (!prev_key)
1869                         prev_key = buf_prevkey;
1870
1871                 swap(prev_key, key);
1872                 retry = MAP_LOOKUP_RETRIES;
1873                 cp++;
1874                 cond_resched();
1875         }
1876
1877         if (err == -EFAULT)
1878                 goto free_buf;
1879
1880         if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1881                     (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1882                 err = -EFAULT;
1883
1884 free_buf:
1885         kvfree(buf_prevkey);
1886         kvfree(buf);
1887         return err;
1888 }
1889
1890 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD flags
1891
1892 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1893 {
1894         void __user *ukey = u64_to_user_ptr(attr->key);
1895         void __user *uvalue = u64_to_user_ptr(attr->value);
1896         int ufd = attr->map_fd;
1897         struct bpf_map *map;
1898         void *key, *value;
1899         u32 value_size;
1900         struct fd f;
1901         int err;
1902
1903         if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1904                 return -EINVAL;
1905
1906         if (attr->flags & ~BPF_F_LOCK)
1907                 return -EINVAL;
1908
1909         f = fdget(ufd);
1910         map = __bpf_map_get(f);
1911         if (IS_ERR(map))
1912                 return PTR_ERR(map);
1913         bpf_map_write_active_inc(map);
1914         if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1915             !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1916                 err = -EPERM;
1917                 goto err_put;
1918         }
1919
1920         if (attr->flags &&
1921             (map->map_type == BPF_MAP_TYPE_QUEUE ||
1922              map->map_type == BPF_MAP_TYPE_STACK)) {
1923                 err = -EINVAL;
1924                 goto err_put;
1925         }
1926
1927         if ((attr->flags & BPF_F_LOCK) &&
1928             !btf_record_has_field(map->record, BPF_SPIN_LOCK)) {
1929                 err = -EINVAL;
1930                 goto err_put;
1931         }
1932
1933         key = __bpf_copy_key(ukey, map->key_size);
1934         if (IS_ERR(key)) {
1935                 err = PTR_ERR(key);
1936                 goto err_put;
1937         }
1938
1939         value_size = bpf_map_value_size(map);
1940
1941         err = -ENOMEM;
1942         value = kvmalloc(value_size, GFP_USER | __GFP_NOWARN);
1943         if (!value)
1944                 goto free_key;
1945
1946         err = -ENOTSUPP;
1947         if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1948             map->map_type == BPF_MAP_TYPE_STACK) {
1949                 err = map->ops->map_pop_elem(map, value);
1950         } else if (map->map_type == BPF_MAP_TYPE_HASH ||
1951                    map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1952                    map->map_type == BPF_MAP_TYPE_LRU_HASH ||
1953                    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
1954                 if (!bpf_map_is_offloaded(map)) {
1955                         bpf_disable_instrumentation();
1956                         rcu_read_lock();
1957                         err = map->ops->map_lookup_and_delete_elem(map, key, value, attr->flags);
1958                         rcu_read_unlock();
1959                         bpf_enable_instrumentation();
1960                 }
1961         }
1962
1963         if (err)
1964                 goto free_value;
1965
1966         if (copy_to_user(uvalue, value, value_size) != 0) {
1967                 err = -EFAULT;
1968                 goto free_value;
1969         }
1970
1971         err = 0;
1972
1973 free_value:
1974         kvfree(value);
1975 free_key:
1976         kvfree(key);
1977 err_put:
1978         bpf_map_write_active_dec(map);
1979         fdput(f);
1980         return err;
1981 }
1982
1983 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1984
1985 static int map_freeze(const union bpf_attr *attr)
1986 {
1987         int err = 0, ufd = attr->map_fd;
1988         struct bpf_map *map;
1989         struct fd f;
1990
1991         if (CHECK_ATTR(BPF_MAP_FREEZE))
1992                 return -EINVAL;
1993
1994         f = fdget(ufd);
1995         map = __bpf_map_get(f);
1996         if (IS_ERR(map))
1997                 return PTR_ERR(map);
1998
1999         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS || !IS_ERR_OR_NULL(map->record)) {
2000                 fdput(f);
2001                 return -ENOTSUPP;
2002         }
2003
2004         if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
2005                 fdput(f);
2006                 return -EPERM;
2007         }
2008
2009         mutex_lock(&map->freeze_mutex);
2010         if (bpf_map_write_active(map)) {
2011                 err = -EBUSY;
2012                 goto err_put;
2013         }
2014         if (READ_ONCE(map->frozen)) {
2015                 err = -EBUSY;
2016                 goto err_put;
2017         }
2018
2019         WRITE_ONCE(map->frozen, true);
2020 err_put:
2021         mutex_unlock(&map->freeze_mutex);
2022         fdput(f);
2023         return err;
2024 }
2025
2026 static const struct bpf_prog_ops * const bpf_prog_types[] = {
2027 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2028         [_id] = & _name ## _prog_ops,
2029 #define BPF_MAP_TYPE(_id, _ops)
2030 #define BPF_LINK_TYPE(_id, _name)
2031 #include <linux/bpf_types.h>
2032 #undef BPF_PROG_TYPE
2033 #undef BPF_MAP_TYPE
2034 #undef BPF_LINK_TYPE
2035 };
2036
2037 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
2038 {
2039         const struct bpf_prog_ops *ops;
2040
2041         if (type >= ARRAY_SIZE(bpf_prog_types))
2042                 return -EINVAL;
2043         type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
2044         ops = bpf_prog_types[type];
2045         if (!ops)
2046                 return -EINVAL;
2047
2048         if (!bpf_prog_is_offloaded(prog->aux))
2049                 prog->aux->ops = ops;
2050         else
2051                 prog->aux->ops = &bpf_offload_prog_ops;
2052         prog->type = type;
2053         return 0;
2054 }
2055
2056 enum bpf_audit {
2057         BPF_AUDIT_LOAD,
2058         BPF_AUDIT_UNLOAD,
2059         BPF_AUDIT_MAX,
2060 };
2061
2062 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
2063         [BPF_AUDIT_LOAD]   = "LOAD",
2064         [BPF_AUDIT_UNLOAD] = "UNLOAD",
2065 };
2066
2067 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
2068 {
2069         struct audit_context *ctx = NULL;
2070         struct audit_buffer *ab;
2071
2072         if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
2073                 return;
2074         if (audit_enabled == AUDIT_OFF)
2075                 return;
2076         if (!in_irq() && !irqs_disabled())
2077                 ctx = audit_context();
2078         ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
2079         if (unlikely(!ab))
2080                 return;
2081         audit_log_format(ab, "prog-id=%u op=%s",
2082                          prog->aux->id, bpf_audit_str[op]);
2083         audit_log_end(ab);
2084 }
2085
2086 static int bpf_prog_alloc_id(struct bpf_prog *prog)
2087 {
2088         int id;
2089
2090         idr_preload(GFP_KERNEL);
2091         spin_lock_bh(&prog_idr_lock);
2092         id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
2093         if (id > 0)
2094                 prog->aux->id = id;
2095         spin_unlock_bh(&prog_idr_lock);
2096         idr_preload_end();
2097
2098         /* id is in [1, INT_MAX) */
2099         if (WARN_ON_ONCE(!id))
2100                 return -ENOSPC;
2101
2102         return id > 0 ? 0 : id;
2103 }
2104
2105 void bpf_prog_free_id(struct bpf_prog *prog)
2106 {
2107         unsigned long flags;
2108
2109         /* cBPF to eBPF migrations are currently not in the idr store.
2110          * Offloaded programs are removed from the store when their device
2111          * disappears - even if someone grabs an fd to them they are unusable,
2112          * simply waiting for refcnt to drop to be freed.
2113          */
2114         if (!prog->aux->id)
2115                 return;
2116
2117         spin_lock_irqsave(&prog_idr_lock, flags);
2118         idr_remove(&prog_idr, prog->aux->id);
2119         prog->aux->id = 0;
2120         spin_unlock_irqrestore(&prog_idr_lock, flags);
2121 }
2122
2123 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
2124 {
2125         struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
2126
2127         kvfree(aux->func_info);
2128         kfree(aux->func_info_aux);
2129         free_uid(aux->user);
2130         security_bpf_prog_free(aux);
2131         bpf_prog_free(aux->prog);
2132 }
2133
2134 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
2135 {
2136         bpf_prog_kallsyms_del_all(prog);
2137         btf_put(prog->aux->btf);
2138         module_put(prog->aux->mod);
2139         kvfree(prog->aux->jited_linfo);
2140         kvfree(prog->aux->linfo);
2141         kfree(prog->aux->kfunc_tab);
2142         if (prog->aux->attach_btf)
2143                 btf_put(prog->aux->attach_btf);
2144
2145         if (deferred) {
2146                 if (prog->aux->sleepable)
2147                         call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
2148                 else
2149                         call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
2150         } else {
2151                 __bpf_prog_put_rcu(&prog->aux->rcu);
2152         }
2153 }
2154
2155 static void bpf_prog_put_deferred(struct work_struct *work)
2156 {
2157         struct bpf_prog_aux *aux;
2158         struct bpf_prog *prog;
2159
2160         aux = container_of(work, struct bpf_prog_aux, work);
2161         prog = aux->prog;
2162         perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
2163         bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
2164         bpf_prog_free_id(prog);
2165         __bpf_prog_put_noref(prog, true);
2166 }
2167
2168 static void __bpf_prog_put(struct bpf_prog *prog)
2169 {
2170         struct bpf_prog_aux *aux = prog->aux;
2171
2172         if (atomic64_dec_and_test(&aux->refcnt)) {
2173                 if (in_irq() || irqs_disabled()) {
2174                         INIT_WORK(&aux->work, bpf_prog_put_deferred);
2175                         schedule_work(&aux->work);
2176                 } else {
2177                         bpf_prog_put_deferred(&aux->work);
2178                 }
2179         }
2180 }
2181
2182 void bpf_prog_put(struct bpf_prog *prog)
2183 {
2184         __bpf_prog_put(prog);
2185 }
2186 EXPORT_SYMBOL_GPL(bpf_prog_put);
2187
2188 static int bpf_prog_release(struct inode *inode, struct file *filp)
2189 {
2190         struct bpf_prog *prog = filp->private_data;
2191
2192         bpf_prog_put(prog);
2193         return 0;
2194 }
2195
2196 struct bpf_prog_kstats {
2197         u64 nsecs;
2198         u64 cnt;
2199         u64 misses;
2200 };
2201
2202 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog)
2203 {
2204         struct bpf_prog_stats *stats;
2205         unsigned int flags;
2206
2207         stats = this_cpu_ptr(prog->stats);
2208         flags = u64_stats_update_begin_irqsave(&stats->syncp);
2209         u64_stats_inc(&stats->misses);
2210         u64_stats_update_end_irqrestore(&stats->syncp, flags);
2211 }
2212
2213 static void bpf_prog_get_stats(const struct bpf_prog *prog,
2214                                struct bpf_prog_kstats *stats)
2215 {
2216         u64 nsecs = 0, cnt = 0, misses = 0;
2217         int cpu;
2218
2219         for_each_possible_cpu(cpu) {
2220                 const struct bpf_prog_stats *st;
2221                 unsigned int start;
2222                 u64 tnsecs, tcnt, tmisses;
2223
2224                 st = per_cpu_ptr(prog->stats, cpu);
2225                 do {
2226                         start = u64_stats_fetch_begin(&st->syncp);
2227                         tnsecs = u64_stats_read(&st->nsecs);
2228                         tcnt = u64_stats_read(&st->cnt);
2229                         tmisses = u64_stats_read(&st->misses);
2230                 } while (u64_stats_fetch_retry(&st->syncp, start));
2231                 nsecs += tnsecs;
2232                 cnt += tcnt;
2233                 misses += tmisses;
2234         }
2235         stats->nsecs = nsecs;
2236         stats->cnt = cnt;
2237         stats->misses = misses;
2238 }
2239
2240 #ifdef CONFIG_PROC_FS
2241 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
2242 {
2243         const struct bpf_prog *prog = filp->private_data;
2244         char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2245         struct bpf_prog_kstats stats;
2246
2247         bpf_prog_get_stats(prog, &stats);
2248         bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2249         seq_printf(m,
2250                    "prog_type:\t%u\n"
2251                    "prog_jited:\t%u\n"
2252                    "prog_tag:\t%s\n"
2253                    "memlock:\t%llu\n"
2254                    "prog_id:\t%u\n"
2255                    "run_time_ns:\t%llu\n"
2256                    "run_cnt:\t%llu\n"
2257                    "recursion_misses:\t%llu\n"
2258                    "verified_insns:\t%u\n",
2259                    prog->type,
2260                    prog->jited,
2261                    prog_tag,
2262                    prog->pages * 1ULL << PAGE_SHIFT,
2263                    prog->aux->id,
2264                    stats.nsecs,
2265                    stats.cnt,
2266                    stats.misses,
2267                    prog->aux->verified_insns);
2268 }
2269 #endif
2270
2271 const struct file_operations bpf_prog_fops = {
2272 #ifdef CONFIG_PROC_FS
2273         .show_fdinfo    = bpf_prog_show_fdinfo,
2274 #endif
2275         .release        = bpf_prog_release,
2276         .read           = bpf_dummy_read,
2277         .write          = bpf_dummy_write,
2278 };
2279
2280 int bpf_prog_new_fd(struct bpf_prog *prog)
2281 {
2282         int ret;
2283
2284         ret = security_bpf_prog(prog);
2285         if (ret < 0)
2286                 return ret;
2287
2288         return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
2289                                 O_RDWR | O_CLOEXEC);
2290 }
2291
2292 static struct bpf_prog *____bpf_prog_get(struct fd f)
2293 {
2294         if (!f.file)
2295                 return ERR_PTR(-EBADF);
2296         if (f.file->f_op != &bpf_prog_fops) {
2297                 fdput(f);
2298                 return ERR_PTR(-EINVAL);
2299         }
2300
2301         return f.file->private_data;
2302 }
2303
2304 void bpf_prog_add(struct bpf_prog *prog, int i)
2305 {
2306         atomic64_add(i, &prog->aux->refcnt);
2307 }
2308 EXPORT_SYMBOL_GPL(bpf_prog_add);
2309
2310 void bpf_prog_sub(struct bpf_prog *prog, int i)
2311 {
2312         /* Only to be used for undoing previous bpf_prog_add() in some
2313          * error path. We still know that another entity in our call
2314          * path holds a reference to the program, thus atomic_sub() can
2315          * be safely used in such cases!
2316          */
2317         WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
2318 }
2319 EXPORT_SYMBOL_GPL(bpf_prog_sub);
2320
2321 void bpf_prog_inc(struct bpf_prog *prog)
2322 {
2323         atomic64_inc(&prog->aux->refcnt);
2324 }
2325 EXPORT_SYMBOL_GPL(bpf_prog_inc);
2326
2327 /* prog_idr_lock should have been held */
2328 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
2329 {
2330         int refold;
2331
2332         refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
2333
2334         if (!refold)
2335                 return ERR_PTR(-ENOENT);
2336
2337         return prog;
2338 }
2339 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
2340
2341 bool bpf_prog_get_ok(struct bpf_prog *prog,
2342                             enum bpf_prog_type *attach_type, bool attach_drv)
2343 {
2344         /* not an attachment, just a refcount inc, always allow */
2345         if (!attach_type)
2346                 return true;
2347
2348         if (prog->type != *attach_type)
2349                 return false;
2350         if (bpf_prog_is_offloaded(prog->aux) && !attach_drv)
2351                 return false;
2352
2353         return true;
2354 }
2355
2356 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
2357                                        bool attach_drv)
2358 {
2359         struct fd f = fdget(ufd);
2360         struct bpf_prog *prog;
2361
2362         prog = ____bpf_prog_get(f);
2363         if (IS_ERR(prog))
2364                 return prog;
2365         if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
2366                 prog = ERR_PTR(-EINVAL);
2367                 goto out;
2368         }
2369
2370         bpf_prog_inc(prog);
2371 out:
2372         fdput(f);
2373         return prog;
2374 }
2375
2376 struct bpf_prog *bpf_prog_get(u32 ufd)
2377 {
2378         return __bpf_prog_get(ufd, NULL, false);
2379 }
2380
2381 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2382                                        bool attach_drv)
2383 {
2384         return __bpf_prog_get(ufd, &type, attach_drv);
2385 }
2386 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
2387
2388 /* Initially all BPF programs could be loaded w/o specifying
2389  * expected_attach_type. Later for some of them specifying expected_attach_type
2390  * at load time became required so that program could be validated properly.
2391  * Programs of types that are allowed to be loaded both w/ and w/o (for
2392  * backward compatibility) expected_attach_type, should have the default attach
2393  * type assigned to expected_attach_type for the latter case, so that it can be
2394  * validated later at attach time.
2395  *
2396  * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
2397  * prog type requires it but has some attach types that have to be backward
2398  * compatible.
2399  */
2400 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2401 {
2402         switch (attr->prog_type) {
2403         case BPF_PROG_TYPE_CGROUP_SOCK:
2404                 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2405                  * exist so checking for non-zero is the way to go here.
2406                  */
2407                 if (!attr->expected_attach_type)
2408                         attr->expected_attach_type =
2409                                 BPF_CGROUP_INET_SOCK_CREATE;
2410                 break;
2411         case BPF_PROG_TYPE_SK_REUSEPORT:
2412                 if (!attr->expected_attach_type)
2413                         attr->expected_attach_type =
2414                                 BPF_SK_REUSEPORT_SELECT;
2415                 break;
2416         }
2417 }
2418
2419 static int
2420 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2421                            enum bpf_attach_type expected_attach_type,
2422                            struct btf *attach_btf, u32 btf_id,
2423                            struct bpf_prog *dst_prog)
2424 {
2425         if (btf_id) {
2426                 if (btf_id > BTF_MAX_TYPE)
2427                         return -EINVAL;
2428
2429                 if (!attach_btf && !dst_prog)
2430                         return -EINVAL;
2431
2432                 switch (prog_type) {
2433                 case BPF_PROG_TYPE_TRACING:
2434                 case BPF_PROG_TYPE_LSM:
2435                 case BPF_PROG_TYPE_STRUCT_OPS:
2436                 case BPF_PROG_TYPE_EXT:
2437                         break;
2438                 default:
2439                         return -EINVAL;
2440                 }
2441         }
2442
2443         if (attach_btf && (!btf_id || dst_prog))
2444                 return -EINVAL;
2445
2446         if (dst_prog && prog_type != BPF_PROG_TYPE_TRACING &&
2447             prog_type != BPF_PROG_TYPE_EXT)
2448                 return -EINVAL;
2449
2450         switch (prog_type) {
2451         case BPF_PROG_TYPE_CGROUP_SOCK:
2452                 switch (expected_attach_type) {
2453                 case BPF_CGROUP_INET_SOCK_CREATE:
2454                 case BPF_CGROUP_INET_SOCK_RELEASE:
2455                 case BPF_CGROUP_INET4_POST_BIND:
2456                 case BPF_CGROUP_INET6_POST_BIND:
2457                         return 0;
2458                 default:
2459                         return -EINVAL;
2460                 }
2461         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2462                 switch (expected_attach_type) {
2463                 case BPF_CGROUP_INET4_BIND:
2464                 case BPF_CGROUP_INET6_BIND:
2465                 case BPF_CGROUP_INET4_CONNECT:
2466                 case BPF_CGROUP_INET6_CONNECT:
2467                 case BPF_CGROUP_INET4_GETPEERNAME:
2468                 case BPF_CGROUP_INET6_GETPEERNAME:
2469                 case BPF_CGROUP_INET4_GETSOCKNAME:
2470                 case BPF_CGROUP_INET6_GETSOCKNAME:
2471                 case BPF_CGROUP_UDP4_SENDMSG:
2472                 case BPF_CGROUP_UDP6_SENDMSG:
2473                 case BPF_CGROUP_UDP4_RECVMSG:
2474                 case BPF_CGROUP_UDP6_RECVMSG:
2475                         return 0;
2476                 default:
2477                         return -EINVAL;
2478                 }
2479         case BPF_PROG_TYPE_CGROUP_SKB:
2480                 switch (expected_attach_type) {
2481                 case BPF_CGROUP_INET_INGRESS:
2482                 case BPF_CGROUP_INET_EGRESS:
2483                         return 0;
2484                 default:
2485                         return -EINVAL;
2486                 }
2487         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2488                 switch (expected_attach_type) {
2489                 case BPF_CGROUP_SETSOCKOPT:
2490                 case BPF_CGROUP_GETSOCKOPT:
2491                         return 0;
2492                 default:
2493                         return -EINVAL;
2494                 }
2495         case BPF_PROG_TYPE_SK_LOOKUP:
2496                 if (expected_attach_type == BPF_SK_LOOKUP)
2497                         return 0;
2498                 return -EINVAL;
2499         case BPF_PROG_TYPE_SK_REUSEPORT:
2500                 switch (expected_attach_type) {
2501                 case BPF_SK_REUSEPORT_SELECT:
2502                 case BPF_SK_REUSEPORT_SELECT_OR_MIGRATE:
2503                         return 0;
2504                 default:
2505                         return -EINVAL;
2506                 }
2507         case BPF_PROG_TYPE_NETFILTER:
2508                 if (expected_attach_type == BPF_NETFILTER)
2509                         return 0;
2510                 return -EINVAL;
2511         case BPF_PROG_TYPE_SYSCALL:
2512         case BPF_PROG_TYPE_EXT:
2513                 if (expected_attach_type)
2514                         return -EINVAL;
2515                 fallthrough;
2516         default:
2517                 return 0;
2518         }
2519 }
2520
2521 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2522 {
2523         switch (prog_type) {
2524         case BPF_PROG_TYPE_SCHED_CLS:
2525         case BPF_PROG_TYPE_SCHED_ACT:
2526         case BPF_PROG_TYPE_XDP:
2527         case BPF_PROG_TYPE_LWT_IN:
2528         case BPF_PROG_TYPE_LWT_OUT:
2529         case BPF_PROG_TYPE_LWT_XMIT:
2530         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2531         case BPF_PROG_TYPE_SK_SKB:
2532         case BPF_PROG_TYPE_SK_MSG:
2533         case BPF_PROG_TYPE_FLOW_DISSECTOR:
2534         case BPF_PROG_TYPE_CGROUP_DEVICE:
2535         case BPF_PROG_TYPE_CGROUP_SOCK:
2536         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2537         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2538         case BPF_PROG_TYPE_CGROUP_SYSCTL:
2539         case BPF_PROG_TYPE_SOCK_OPS:
2540         case BPF_PROG_TYPE_EXT: /* extends any prog */
2541         case BPF_PROG_TYPE_NETFILTER:
2542                 return true;
2543         case BPF_PROG_TYPE_CGROUP_SKB:
2544                 /* always unpriv */
2545         case BPF_PROG_TYPE_SK_REUSEPORT:
2546                 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2547         default:
2548                 return false;
2549         }
2550 }
2551
2552 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2553 {
2554         switch (prog_type) {
2555         case BPF_PROG_TYPE_KPROBE:
2556         case BPF_PROG_TYPE_TRACEPOINT:
2557         case BPF_PROG_TYPE_PERF_EVENT:
2558         case BPF_PROG_TYPE_RAW_TRACEPOINT:
2559         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2560         case BPF_PROG_TYPE_TRACING:
2561         case BPF_PROG_TYPE_LSM:
2562         case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2563         case BPF_PROG_TYPE_EXT: /* extends any prog */
2564                 return true;
2565         default:
2566                 return false;
2567         }
2568 }
2569
2570 /* last field in 'union bpf_attr' used by this command */
2571 #define BPF_PROG_LOAD_LAST_FIELD log_true_size
2572
2573 static int bpf_prog_load(union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
2574 {
2575         enum bpf_prog_type type = attr->prog_type;
2576         struct bpf_prog *prog, *dst_prog = NULL;
2577         struct btf *attach_btf = NULL;
2578         int err;
2579         char license[128];
2580
2581         if (CHECK_ATTR(BPF_PROG_LOAD))
2582                 return -EINVAL;
2583
2584         if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2585                                  BPF_F_ANY_ALIGNMENT |
2586                                  BPF_F_TEST_STATE_FREQ |
2587                                  BPF_F_SLEEPABLE |
2588                                  BPF_F_TEST_RND_HI32 |
2589                                  BPF_F_XDP_HAS_FRAGS |
2590                                  BPF_F_XDP_DEV_BOUND_ONLY))
2591                 return -EINVAL;
2592
2593         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2594             (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2595             !bpf_capable())
2596                 return -EPERM;
2597
2598         /* Intent here is for unprivileged_bpf_disabled to block BPF program
2599          * creation for unprivileged users; other actions depend
2600          * on fd availability and access to bpffs, so are dependent on
2601          * object creation success. Even with unprivileged BPF disabled,
2602          * capability checks are still carried out for these
2603          * and other operations.
2604          */
2605         if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
2606                 return -EPERM;
2607
2608         if (attr->insn_cnt == 0 ||
2609             attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2610                 return -E2BIG;
2611         if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2612             type != BPF_PROG_TYPE_CGROUP_SKB &&
2613             !bpf_capable())
2614                 return -EPERM;
2615
2616         if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2617                 return -EPERM;
2618         if (is_perfmon_prog_type(type) && !perfmon_capable())
2619                 return -EPERM;
2620
2621         /* attach_prog_fd/attach_btf_obj_fd can specify fd of either bpf_prog
2622          * or btf, we need to check which one it is
2623          */
2624         if (attr->attach_prog_fd) {
2625                 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2626                 if (IS_ERR(dst_prog)) {
2627                         dst_prog = NULL;
2628                         attach_btf = btf_get_by_fd(attr->attach_btf_obj_fd);
2629                         if (IS_ERR(attach_btf))
2630                                 return -EINVAL;
2631                         if (!btf_is_kernel(attach_btf)) {
2632                                 /* attaching through specifying bpf_prog's BTF
2633                                  * objects directly might be supported eventually
2634                                  */
2635                                 btf_put(attach_btf);
2636                                 return -ENOTSUPP;
2637                         }
2638                 }
2639         } else if (attr->attach_btf_id) {
2640                 /* fall back to vmlinux BTF, if BTF type ID is specified */
2641                 attach_btf = bpf_get_btf_vmlinux();
2642                 if (IS_ERR(attach_btf))
2643                         return PTR_ERR(attach_btf);
2644                 if (!attach_btf)
2645                         return -EINVAL;
2646                 btf_get(attach_btf);
2647         }
2648
2649         bpf_prog_load_fixup_attach_type(attr);
2650         if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2651                                        attach_btf, attr->attach_btf_id,
2652                                        dst_prog)) {
2653                 if (dst_prog)
2654                         bpf_prog_put(dst_prog);
2655                 if (attach_btf)
2656                         btf_put(attach_btf);
2657                 return -EINVAL;
2658         }
2659
2660         /* plain bpf_prog allocation */
2661         prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2662         if (!prog) {
2663                 if (dst_prog)
2664                         bpf_prog_put(dst_prog);
2665                 if (attach_btf)
2666                         btf_put(attach_btf);
2667                 return -ENOMEM;
2668         }
2669
2670         prog->expected_attach_type = attr->expected_attach_type;
2671         prog->aux->attach_btf = attach_btf;
2672         prog->aux->attach_btf_id = attr->attach_btf_id;
2673         prog->aux->dst_prog = dst_prog;
2674         prog->aux->dev_bound = !!attr->prog_ifindex;
2675         prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2676         prog->aux->xdp_has_frags = attr->prog_flags & BPF_F_XDP_HAS_FRAGS;
2677
2678         err = security_bpf_prog_alloc(prog->aux);
2679         if (err)
2680                 goto free_prog;
2681
2682         prog->aux->user = get_current_user();
2683         prog->len = attr->insn_cnt;
2684
2685         err = -EFAULT;
2686         if (copy_from_bpfptr(prog->insns,
2687                              make_bpfptr(attr->insns, uattr.is_kernel),
2688                              bpf_prog_insn_size(prog)) != 0)
2689                 goto free_prog_sec;
2690         /* copy eBPF program license from user space */
2691         if (strncpy_from_bpfptr(license,
2692                                 make_bpfptr(attr->license, uattr.is_kernel),
2693                                 sizeof(license) - 1) < 0)
2694                 goto free_prog_sec;
2695         license[sizeof(license) - 1] = 0;
2696
2697         /* eBPF programs must be GPL compatible to use GPL-ed functions */
2698         prog->gpl_compatible = license_is_gpl_compatible(license) ? 1 : 0;
2699
2700         prog->orig_prog = NULL;
2701         prog->jited = 0;
2702
2703         atomic64_set(&prog->aux->refcnt, 1);
2704
2705         if (bpf_prog_is_dev_bound(prog->aux)) {
2706                 err = bpf_prog_dev_bound_init(prog, attr);
2707                 if (err)
2708                         goto free_prog_sec;
2709         }
2710
2711         if (type == BPF_PROG_TYPE_EXT && dst_prog &&
2712             bpf_prog_is_dev_bound(dst_prog->aux)) {
2713                 err = bpf_prog_dev_bound_inherit(prog, dst_prog);
2714                 if (err)
2715                         goto free_prog_sec;
2716         }
2717
2718         /* find program type: socket_filter vs tracing_filter */
2719         err = find_prog_type(type, prog);
2720         if (err < 0)
2721                 goto free_prog_sec;
2722
2723         prog->aux->load_time = ktime_get_boottime_ns();
2724         err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2725                                sizeof(attr->prog_name));
2726         if (err < 0)
2727                 goto free_prog_sec;
2728
2729         /* run eBPF verifier */
2730         err = bpf_check(&prog, attr, uattr, uattr_size);
2731         if (err < 0)
2732                 goto free_used_maps;
2733
2734         prog = bpf_prog_select_runtime(prog, &err);
2735         if (err < 0)
2736                 goto free_used_maps;
2737
2738         err = bpf_prog_alloc_id(prog);
2739         if (err)
2740                 goto free_used_maps;
2741
2742         /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2743          * effectively publicly exposed. However, retrieving via
2744          * bpf_prog_get_fd_by_id() will take another reference,
2745          * therefore it cannot be gone underneath us.
2746          *
2747          * Only for the time /after/ successful bpf_prog_new_fd()
2748          * and before returning to userspace, we might just hold
2749          * one reference and any parallel close on that fd could
2750          * rip everything out. Hence, below notifications must
2751          * happen before bpf_prog_new_fd().
2752          *
2753          * Also, any failure handling from this point onwards must
2754          * be using bpf_prog_put() given the program is exposed.
2755          */
2756         bpf_prog_kallsyms_add(prog);
2757         perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2758         bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2759
2760         err = bpf_prog_new_fd(prog);
2761         if (err < 0)
2762                 bpf_prog_put(prog);
2763         return err;
2764
2765 free_used_maps:
2766         /* In case we have subprogs, we need to wait for a grace
2767          * period before we can tear down JIT memory since symbols
2768          * are already exposed under kallsyms.
2769          */
2770         __bpf_prog_put_noref(prog, prog->aux->func_cnt);
2771         return err;
2772 free_prog_sec:
2773         free_uid(prog->aux->user);
2774         security_bpf_prog_free(prog->aux);
2775 free_prog:
2776         if (prog->aux->attach_btf)
2777                 btf_put(prog->aux->attach_btf);
2778         bpf_prog_free(prog);
2779         return err;
2780 }
2781
2782 #define BPF_OBJ_LAST_FIELD path_fd
2783
2784 static int bpf_obj_pin(const union bpf_attr *attr)
2785 {
2786         int path_fd;
2787
2788         if (CHECK_ATTR(BPF_OBJ) || attr->file_flags & ~BPF_F_PATH_FD)
2789                 return -EINVAL;
2790
2791         /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2792         if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2793                 return -EINVAL;
2794
2795         path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2796         return bpf_obj_pin_user(attr->bpf_fd, path_fd,
2797                                 u64_to_user_ptr(attr->pathname));
2798 }
2799
2800 static int bpf_obj_get(const union bpf_attr *attr)
2801 {
2802         int path_fd;
2803
2804         if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2805             attr->file_flags & ~(BPF_OBJ_FLAG_MASK | BPF_F_PATH_FD))
2806                 return -EINVAL;
2807
2808         /* path_fd has to be accompanied by BPF_F_PATH_FD flag */
2809         if (!(attr->file_flags & BPF_F_PATH_FD) && attr->path_fd)
2810                 return -EINVAL;
2811
2812         path_fd = attr->file_flags & BPF_F_PATH_FD ? attr->path_fd : AT_FDCWD;
2813         return bpf_obj_get_user(path_fd, u64_to_user_ptr(attr->pathname),
2814                                 attr->file_flags);
2815 }
2816
2817 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2818                    const struct bpf_link_ops *ops, struct bpf_prog *prog)
2819 {
2820         atomic64_set(&link->refcnt, 1);
2821         link->type = type;
2822         link->id = 0;
2823         link->ops = ops;
2824         link->prog = prog;
2825 }
2826
2827 static void bpf_link_free_id(int id)
2828 {
2829         if (!id)
2830                 return;
2831
2832         spin_lock_bh(&link_idr_lock);
2833         idr_remove(&link_idr, id);
2834         spin_unlock_bh(&link_idr_lock);
2835 }
2836
2837 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2838  * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2839  * anon_inode's release() call. This helper marks bpf_link as
2840  * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2841  * is not decremented, it's the responsibility of a calling code that failed
2842  * to complete bpf_link initialization.
2843  * This helper eventually calls link's dealloc callback, but does not call
2844  * link's release callback.
2845  */
2846 void bpf_link_cleanup(struct bpf_link_primer *primer)
2847 {
2848         primer->link->prog = NULL;
2849         bpf_link_free_id(primer->id);
2850         fput(primer->file);
2851         put_unused_fd(primer->fd);
2852 }
2853
2854 void bpf_link_inc(struct bpf_link *link)
2855 {
2856         atomic64_inc(&link->refcnt);
2857 }
2858
2859 /* bpf_link_free is guaranteed to be called from process context */
2860 static void bpf_link_free(struct bpf_link *link)
2861 {
2862         bpf_link_free_id(link->id);
2863         if (link->prog) {
2864                 /* detach BPF program, clean up used resources */
2865                 link->ops->release(link);
2866                 bpf_prog_put(link->prog);
2867         }
2868         /* free bpf_link and its containing memory */
2869         link->ops->dealloc(link);
2870 }
2871
2872 static void bpf_link_put_deferred(struct work_struct *work)
2873 {
2874         struct bpf_link *link = container_of(work, struct bpf_link, work);
2875
2876         bpf_link_free(link);
2877 }
2878
2879 /* bpf_link_put might be called from atomic context. It needs to be called
2880  * from sleepable context in order to acquire sleeping locks during the process.
2881  */
2882 void bpf_link_put(struct bpf_link *link)
2883 {
2884         if (!atomic64_dec_and_test(&link->refcnt))
2885                 return;
2886
2887         INIT_WORK(&link->work, bpf_link_put_deferred);
2888         schedule_work(&link->work);
2889 }
2890 EXPORT_SYMBOL(bpf_link_put);
2891
2892 static void bpf_link_put_direct(struct bpf_link *link)
2893 {
2894         if (!atomic64_dec_and_test(&link->refcnt))
2895                 return;
2896         bpf_link_free(link);
2897 }
2898
2899 static int bpf_link_release(struct inode *inode, struct file *filp)
2900 {
2901         struct bpf_link *link = filp->private_data;
2902
2903         bpf_link_put_direct(link);
2904         return 0;
2905 }
2906
2907 #ifdef CONFIG_PROC_FS
2908 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2909 #define BPF_MAP_TYPE(_id, _ops)
2910 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2911 static const char *bpf_link_type_strs[] = {
2912         [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2913 #include <linux/bpf_types.h>
2914 };
2915 #undef BPF_PROG_TYPE
2916 #undef BPF_MAP_TYPE
2917 #undef BPF_LINK_TYPE
2918
2919 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2920 {
2921         const struct bpf_link *link = filp->private_data;
2922         const struct bpf_prog *prog = link->prog;
2923         char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2924
2925         seq_printf(m,
2926                    "link_type:\t%s\n"
2927                    "link_id:\t%u\n",
2928                    bpf_link_type_strs[link->type],
2929                    link->id);
2930         if (prog) {
2931                 bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2932                 seq_printf(m,
2933                            "prog_tag:\t%s\n"
2934                            "prog_id:\t%u\n",
2935                            prog_tag,
2936                            prog->aux->id);
2937         }
2938         if (link->ops->show_fdinfo)
2939                 link->ops->show_fdinfo(link, m);
2940 }
2941 #endif
2942
2943 static const struct file_operations bpf_link_fops = {
2944 #ifdef CONFIG_PROC_FS
2945         .show_fdinfo    = bpf_link_show_fdinfo,
2946 #endif
2947         .release        = bpf_link_release,
2948         .read           = bpf_dummy_read,
2949         .write          = bpf_dummy_write,
2950 };
2951
2952 static int bpf_link_alloc_id(struct bpf_link *link)
2953 {
2954         int id;
2955
2956         idr_preload(GFP_KERNEL);
2957         spin_lock_bh(&link_idr_lock);
2958         id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2959         spin_unlock_bh(&link_idr_lock);
2960         idr_preload_end();
2961
2962         return id;
2963 }
2964
2965 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2966  * reserving unused FD and allocating ID from link_idr. This is to be paired
2967  * with bpf_link_settle() to install FD and ID and expose bpf_link to
2968  * user-space, if bpf_link is successfully attached. If not, bpf_link and
2969  * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2970  * transient state is passed around in struct bpf_link_primer.
2971  * This is preferred way to create and initialize bpf_link, especially when
2972  * there are complicated and expensive operations in between creating bpf_link
2973  * itself and attaching it to BPF hook. By using bpf_link_prime() and
2974  * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2975  * expensive (and potentially failing) roll back operations in a rare case
2976  * that file, FD, or ID can't be allocated.
2977  */
2978 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2979 {
2980         struct file *file;
2981         int fd, id;
2982
2983         fd = get_unused_fd_flags(O_CLOEXEC);
2984         if (fd < 0)
2985                 return fd;
2986
2987
2988         id = bpf_link_alloc_id(link);
2989         if (id < 0) {
2990                 put_unused_fd(fd);
2991                 return id;
2992         }
2993
2994         file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2995         if (IS_ERR(file)) {
2996                 bpf_link_free_id(id);
2997                 put_unused_fd(fd);
2998                 return PTR_ERR(file);
2999         }
3000
3001         primer->link = link;
3002         primer->file = file;
3003         primer->fd = fd;
3004         primer->id = id;
3005         return 0;
3006 }
3007
3008 int bpf_link_settle(struct bpf_link_primer *primer)
3009 {
3010         /* make bpf_link fetchable by ID */
3011         spin_lock_bh(&link_idr_lock);
3012         primer->link->id = primer->id;
3013         spin_unlock_bh(&link_idr_lock);
3014         /* make bpf_link fetchable by FD */
3015         fd_install(primer->fd, primer->file);
3016         /* pass through installed FD */
3017         return primer->fd;
3018 }
3019
3020 int bpf_link_new_fd(struct bpf_link *link)
3021 {
3022         return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
3023 }
3024
3025 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
3026 {
3027         struct fd f = fdget(ufd);
3028         struct bpf_link *link;
3029
3030         if (!f.file)
3031                 return ERR_PTR(-EBADF);
3032         if (f.file->f_op != &bpf_link_fops) {
3033                 fdput(f);
3034                 return ERR_PTR(-EINVAL);
3035         }
3036
3037         link = f.file->private_data;
3038         bpf_link_inc(link);
3039         fdput(f);
3040
3041         return link;
3042 }
3043 EXPORT_SYMBOL(bpf_link_get_from_fd);
3044
3045 static void bpf_tracing_link_release(struct bpf_link *link)
3046 {
3047         struct bpf_tracing_link *tr_link =
3048                 container_of(link, struct bpf_tracing_link, link.link);
3049
3050         WARN_ON_ONCE(bpf_trampoline_unlink_prog(&tr_link->link,
3051                                                 tr_link->trampoline));
3052
3053         bpf_trampoline_put(tr_link->trampoline);
3054
3055         /* tgt_prog is NULL if target is a kernel function */
3056         if (tr_link->tgt_prog)
3057                 bpf_prog_put(tr_link->tgt_prog);
3058 }
3059
3060 static void bpf_tracing_link_dealloc(struct bpf_link *link)
3061 {
3062         struct bpf_tracing_link *tr_link =
3063                 container_of(link, struct bpf_tracing_link, link.link);
3064
3065         kfree(tr_link);
3066 }
3067
3068 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
3069                                          struct seq_file *seq)
3070 {
3071         struct bpf_tracing_link *tr_link =
3072                 container_of(link, struct bpf_tracing_link, link.link);
3073         u32 target_btf_id, target_obj_id;
3074
3075         bpf_trampoline_unpack_key(tr_link->trampoline->key,
3076                                   &target_obj_id, &target_btf_id);
3077         seq_printf(seq,
3078                    "attach_type:\t%d\n"
3079                    "target_obj_id:\t%u\n"
3080                    "target_btf_id:\t%u\n",
3081                    tr_link->attach_type,
3082                    target_obj_id,
3083                    target_btf_id);
3084 }
3085
3086 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
3087                                            struct bpf_link_info *info)
3088 {
3089         struct bpf_tracing_link *tr_link =
3090                 container_of(link, struct bpf_tracing_link, link.link);
3091
3092         info->tracing.attach_type = tr_link->attach_type;
3093         bpf_trampoline_unpack_key(tr_link->trampoline->key,
3094                                   &info->tracing.target_obj_id,
3095                                   &info->tracing.target_btf_id);
3096
3097         return 0;
3098 }
3099
3100 static const struct bpf_link_ops bpf_tracing_link_lops = {
3101         .release = bpf_tracing_link_release,
3102         .dealloc = bpf_tracing_link_dealloc,
3103         .show_fdinfo = bpf_tracing_link_show_fdinfo,
3104         .fill_link_info = bpf_tracing_link_fill_link_info,
3105 };
3106
3107 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
3108                                    int tgt_prog_fd,
3109                                    u32 btf_id,
3110                                    u64 bpf_cookie)
3111 {
3112         struct bpf_link_primer link_primer;
3113         struct bpf_prog *tgt_prog = NULL;
3114         struct bpf_trampoline *tr = NULL;
3115         struct bpf_tracing_link *link;
3116         u64 key = 0;
3117         int err;
3118
3119         switch (prog->type) {
3120         case BPF_PROG_TYPE_TRACING:
3121                 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
3122                     prog->expected_attach_type != BPF_TRACE_FEXIT &&
3123                     prog->expected_attach_type != BPF_MODIFY_RETURN) {
3124                         err = -EINVAL;
3125                         goto out_put_prog;
3126                 }
3127                 break;
3128         case BPF_PROG_TYPE_EXT:
3129                 if (prog->expected_attach_type != 0) {
3130                         err = -EINVAL;
3131                         goto out_put_prog;
3132                 }
3133                 break;
3134         case BPF_PROG_TYPE_LSM:
3135                 if (prog->expected_attach_type != BPF_LSM_MAC) {
3136                         err = -EINVAL;
3137                         goto out_put_prog;
3138                 }
3139                 break;
3140         default:
3141                 err = -EINVAL;
3142                 goto out_put_prog;
3143         }
3144
3145         if (!!tgt_prog_fd != !!btf_id) {
3146                 err = -EINVAL;
3147                 goto out_put_prog;
3148         }
3149
3150         if (tgt_prog_fd) {
3151                 /* For now we only allow new targets for BPF_PROG_TYPE_EXT */
3152                 if (prog->type != BPF_PROG_TYPE_EXT) {
3153                         err = -EINVAL;
3154                         goto out_put_prog;
3155                 }
3156
3157                 tgt_prog = bpf_prog_get(tgt_prog_fd);
3158                 if (IS_ERR(tgt_prog)) {
3159                         err = PTR_ERR(tgt_prog);
3160                         tgt_prog = NULL;
3161                         goto out_put_prog;
3162                 }
3163
3164                 key = bpf_trampoline_compute_key(tgt_prog, NULL, btf_id);
3165         }
3166
3167         link = kzalloc(sizeof(*link), GFP_USER);
3168         if (!link) {
3169                 err = -ENOMEM;
3170                 goto out_put_prog;
3171         }
3172         bpf_link_init(&link->link.link, BPF_LINK_TYPE_TRACING,
3173                       &bpf_tracing_link_lops, prog);
3174         link->attach_type = prog->expected_attach_type;
3175         link->link.cookie = bpf_cookie;
3176
3177         mutex_lock(&prog->aux->dst_mutex);
3178
3179         /* There are a few possible cases here:
3180          *
3181          * - if prog->aux->dst_trampoline is set, the program was just loaded
3182          *   and not yet attached to anything, so we can use the values stored
3183          *   in prog->aux
3184          *
3185          * - if prog->aux->dst_trampoline is NULL, the program has already been
3186          *   attached to a target and its initial target was cleared (below)
3187          *
3188          * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
3189          *   target_btf_id using the link_create API.
3190          *
3191          * - if tgt_prog == NULL when this function was called using the old
3192          *   raw_tracepoint_open API, and we need a target from prog->aux
3193          *
3194          * - if prog->aux->dst_trampoline and tgt_prog is NULL, the program
3195          *   was detached and is going for re-attachment.
3196          */
3197         if (!prog->aux->dst_trampoline && !tgt_prog) {
3198                 /*
3199                  * Allow re-attach for TRACING and LSM programs. If it's
3200                  * currently linked, bpf_trampoline_link_prog will fail.
3201                  * EXT programs need to specify tgt_prog_fd, so they
3202                  * re-attach in separate code path.
3203                  */
3204                 if (prog->type != BPF_PROG_TYPE_TRACING &&
3205                     prog->type != BPF_PROG_TYPE_LSM) {
3206                         err = -EINVAL;
3207                         goto out_unlock;
3208                 }
3209                 btf_id = prog->aux->attach_btf_id;
3210                 key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf, btf_id);
3211         }
3212
3213         if (!prog->aux->dst_trampoline ||
3214             (key && key != prog->aux->dst_trampoline->key)) {
3215                 /* If there is no saved target, or the specified target is
3216                  * different from the destination specified at load time, we
3217                  * need a new trampoline and a check for compatibility
3218                  */
3219                 struct bpf_attach_target_info tgt_info = {};
3220
3221                 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
3222                                               &tgt_info);
3223                 if (err)
3224                         goto out_unlock;
3225
3226                 if (tgt_info.tgt_mod) {
3227                         module_put(prog->aux->mod);
3228                         prog->aux->mod = tgt_info.tgt_mod;
3229                 }
3230
3231                 tr = bpf_trampoline_get(key, &tgt_info);
3232                 if (!tr) {
3233                         err = -ENOMEM;
3234                         goto out_unlock;
3235                 }
3236         } else {
3237                 /* The caller didn't specify a target, or the target was the
3238                  * same as the destination supplied during program load. This
3239                  * means we can reuse the trampoline and reference from program
3240                  * load time, and there is no need to allocate a new one. This
3241                  * can only happen once for any program, as the saved values in
3242                  * prog->aux are cleared below.
3243                  */
3244                 tr = prog->aux->dst_trampoline;
3245                 tgt_prog = prog->aux->dst_prog;
3246         }
3247
3248         err = bpf_link_prime(&link->link.link, &link_primer);
3249         if (err)
3250                 goto out_unlock;
3251
3252         err = bpf_trampoline_link_prog(&link->link, tr);
3253         if (err) {
3254                 bpf_link_cleanup(&link_primer);
3255                 link = NULL;
3256                 goto out_unlock;
3257         }
3258
3259         link->tgt_prog = tgt_prog;
3260         link->trampoline = tr;
3261
3262         /* Always clear the trampoline and target prog from prog->aux to make
3263          * sure the original attach destination is not kept alive after a
3264          * program is (re-)attached to another target.
3265          */
3266         if (prog->aux->dst_prog &&
3267             (tgt_prog_fd || tr != prog->aux->dst_trampoline))
3268                 /* got extra prog ref from syscall, or attaching to different prog */
3269                 bpf_prog_put(prog->aux->dst_prog);
3270         if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
3271                 /* we allocated a new trampoline, so free the old one */
3272                 bpf_trampoline_put(prog->aux->dst_trampoline);
3273
3274         prog->aux->dst_prog = NULL;
3275         prog->aux->dst_trampoline = NULL;
3276         mutex_unlock(&prog->aux->dst_mutex);
3277
3278         return bpf_link_settle(&link_primer);
3279 out_unlock:
3280         if (tr && tr != prog->aux->dst_trampoline)
3281                 bpf_trampoline_put(tr);
3282         mutex_unlock(&prog->aux->dst_mutex);
3283         kfree(link);
3284 out_put_prog:
3285         if (tgt_prog_fd && tgt_prog)
3286                 bpf_prog_put(tgt_prog);
3287         return err;
3288 }
3289
3290 struct bpf_raw_tp_link {
3291         struct bpf_link link;
3292         struct bpf_raw_event_map *btp;
3293 };
3294
3295 static void bpf_raw_tp_link_release(struct bpf_link *link)
3296 {
3297         struct bpf_raw_tp_link *raw_tp =
3298                 container_of(link, struct bpf_raw_tp_link, link);
3299
3300         bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
3301         bpf_put_raw_tracepoint(raw_tp->btp);
3302 }
3303
3304 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
3305 {
3306         struct bpf_raw_tp_link *raw_tp =
3307                 container_of(link, struct bpf_raw_tp_link, link);
3308
3309         kfree(raw_tp);
3310 }
3311
3312 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
3313                                         struct seq_file *seq)
3314 {
3315         struct bpf_raw_tp_link *raw_tp_link =
3316                 container_of(link, struct bpf_raw_tp_link, link);
3317
3318         seq_printf(seq,
3319                    "tp_name:\t%s\n",
3320                    raw_tp_link->btp->tp->name);
3321 }
3322
3323 static int bpf_copy_to_user(char __user *ubuf, const char *buf, u32 ulen,
3324                             u32 len)
3325 {
3326         if (ulen >= len + 1) {
3327                 if (copy_to_user(ubuf, buf, len + 1))
3328                         return -EFAULT;
3329         } else {
3330                 char zero = '\0';
3331
3332                 if (copy_to_user(ubuf, buf, ulen - 1))
3333                         return -EFAULT;
3334                 if (put_user(zero, ubuf + ulen - 1))
3335                         return -EFAULT;
3336                 return -ENOSPC;
3337         }
3338
3339         return 0;
3340 }
3341
3342 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
3343                                           struct bpf_link_info *info)
3344 {
3345         struct bpf_raw_tp_link *raw_tp_link =
3346                 container_of(link, struct bpf_raw_tp_link, link);
3347         char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
3348         const char *tp_name = raw_tp_link->btp->tp->name;
3349         u32 ulen = info->raw_tracepoint.tp_name_len;
3350         size_t tp_len = strlen(tp_name);
3351
3352         if (!ulen ^ !ubuf)
3353                 return -EINVAL;
3354
3355         info->raw_tracepoint.tp_name_len = tp_len + 1;
3356
3357         if (!ubuf)
3358                 return 0;
3359
3360         return bpf_copy_to_user(ubuf, tp_name, ulen, tp_len);
3361 }
3362
3363 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
3364         .release = bpf_raw_tp_link_release,
3365         .dealloc = bpf_raw_tp_link_dealloc,
3366         .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
3367         .fill_link_info = bpf_raw_tp_link_fill_link_info,
3368 };
3369
3370 #ifdef CONFIG_PERF_EVENTS
3371 struct bpf_perf_link {
3372         struct bpf_link link;
3373         struct file *perf_file;
3374 };
3375
3376 static void bpf_perf_link_release(struct bpf_link *link)
3377 {
3378         struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3379         struct perf_event *event = perf_link->perf_file->private_data;
3380
3381         perf_event_free_bpf_prog(event);
3382         fput(perf_link->perf_file);
3383 }
3384
3385 static void bpf_perf_link_dealloc(struct bpf_link *link)
3386 {
3387         struct bpf_perf_link *perf_link = container_of(link, struct bpf_perf_link, link);
3388
3389         kfree(perf_link);
3390 }
3391
3392 static int bpf_perf_link_fill_common(const struct perf_event *event,
3393                                      char __user *uname, u32 ulen,
3394                                      u64 *probe_offset, u64 *probe_addr,
3395                                      u32 *fd_type)
3396 {
3397         const char *buf;
3398         u32 prog_id;
3399         size_t len;
3400         int err;
3401
3402         if (!ulen ^ !uname)
3403                 return -EINVAL;
3404
3405         err = bpf_get_perf_event_info(event, &prog_id, fd_type, &buf,
3406                                       probe_offset, probe_addr);
3407         if (err)
3408                 return err;
3409         if (!uname)
3410                 return 0;
3411         if (buf) {
3412                 len = strlen(buf);
3413                 err = bpf_copy_to_user(uname, buf, ulen, len);
3414                 if (err)
3415                         return err;
3416         } else {
3417                 char zero = '\0';
3418
3419                 if (put_user(zero, uname))
3420                         return -EFAULT;
3421         }
3422         return 0;
3423 }
3424
3425 #ifdef CONFIG_KPROBE_EVENTS
3426 static int bpf_perf_link_fill_kprobe(const struct perf_event *event,
3427                                      struct bpf_link_info *info)
3428 {
3429         char __user *uname;
3430         u64 addr, offset;
3431         u32 ulen, type;
3432         int err;
3433
3434         uname = u64_to_user_ptr(info->perf_event.kprobe.func_name);
3435         ulen = info->perf_event.kprobe.name_len;
3436         err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3437                                         &type);
3438         if (err)
3439                 return err;
3440         if (type == BPF_FD_TYPE_KRETPROBE)
3441                 info->perf_event.type = BPF_PERF_EVENT_KRETPROBE;
3442         else
3443                 info->perf_event.type = BPF_PERF_EVENT_KPROBE;
3444
3445         info->perf_event.kprobe.offset = offset;
3446         if (!kallsyms_show_value(current_cred()))
3447                 addr = 0;
3448         info->perf_event.kprobe.addr = addr;
3449         return 0;
3450 }
3451 #endif
3452
3453 #ifdef CONFIG_UPROBE_EVENTS
3454 static int bpf_perf_link_fill_uprobe(const struct perf_event *event,
3455                                      struct bpf_link_info *info)
3456 {
3457         char __user *uname;
3458         u64 addr, offset;
3459         u32 ulen, type;
3460         int err;
3461
3462         uname = u64_to_user_ptr(info->perf_event.uprobe.file_name);
3463         ulen = info->perf_event.uprobe.name_len;
3464         err = bpf_perf_link_fill_common(event, uname, ulen, &offset, &addr,
3465                                         &type);
3466         if (err)
3467                 return err;
3468
3469         if (type == BPF_FD_TYPE_URETPROBE)
3470                 info->perf_event.type = BPF_PERF_EVENT_URETPROBE;
3471         else
3472                 info->perf_event.type = BPF_PERF_EVENT_UPROBE;
3473         info->perf_event.uprobe.offset = offset;
3474         return 0;
3475 }
3476 #endif
3477
3478 static int bpf_perf_link_fill_probe(const struct perf_event *event,
3479                                     struct bpf_link_info *info)
3480 {
3481 #ifdef CONFIG_KPROBE_EVENTS
3482         if (event->tp_event->flags & TRACE_EVENT_FL_KPROBE)
3483                 return bpf_perf_link_fill_kprobe(event, info);
3484 #endif
3485 #ifdef CONFIG_UPROBE_EVENTS
3486         if (event->tp_event->flags & TRACE_EVENT_FL_UPROBE)
3487                 return bpf_perf_link_fill_uprobe(event, info);
3488 #endif
3489         return -EOPNOTSUPP;
3490 }
3491
3492 static int bpf_perf_link_fill_tracepoint(const struct perf_event *event,
3493                                          struct bpf_link_info *info)
3494 {
3495         char __user *uname;
3496         u32 ulen;
3497
3498         uname = u64_to_user_ptr(info->perf_event.tracepoint.tp_name);
3499         ulen = info->perf_event.tracepoint.name_len;
3500         info->perf_event.type = BPF_PERF_EVENT_TRACEPOINT;
3501         return bpf_perf_link_fill_common(event, uname, ulen, NULL, NULL, NULL);
3502 }
3503
3504 static int bpf_perf_link_fill_perf_event(const struct perf_event *event,
3505                                          struct bpf_link_info *info)
3506 {
3507         info->perf_event.event.type = event->attr.type;
3508         info->perf_event.event.config = event->attr.config;
3509         info->perf_event.type = BPF_PERF_EVENT_EVENT;
3510         return 0;
3511 }
3512
3513 static int bpf_perf_link_fill_link_info(const struct bpf_link *link,
3514                                         struct bpf_link_info *info)
3515 {
3516         struct bpf_perf_link *perf_link;
3517         const struct perf_event *event;
3518
3519         perf_link = container_of(link, struct bpf_perf_link, link);
3520         event = perf_get_event(perf_link->perf_file);
3521         if (IS_ERR(event))
3522                 return PTR_ERR(event);
3523
3524         switch (event->prog->type) {
3525         case BPF_PROG_TYPE_PERF_EVENT:
3526                 return bpf_perf_link_fill_perf_event(event, info);
3527         case BPF_PROG_TYPE_TRACEPOINT:
3528                 return bpf_perf_link_fill_tracepoint(event, info);
3529         case BPF_PROG_TYPE_KPROBE:
3530                 return bpf_perf_link_fill_probe(event, info);
3531         default:
3532                 return -EOPNOTSUPP;
3533         }
3534 }
3535
3536 static const struct bpf_link_ops bpf_perf_link_lops = {
3537         .release = bpf_perf_link_release,
3538         .dealloc = bpf_perf_link_dealloc,
3539         .fill_link_info = bpf_perf_link_fill_link_info,
3540 };
3541
3542 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3543 {
3544         struct bpf_link_primer link_primer;
3545         struct bpf_perf_link *link;
3546         struct perf_event *event;
3547         struct file *perf_file;
3548         int err;
3549
3550         if (attr->link_create.flags)
3551                 return -EINVAL;
3552
3553         perf_file = perf_event_get(attr->link_create.target_fd);
3554         if (IS_ERR(perf_file))
3555                 return PTR_ERR(perf_file);
3556
3557         link = kzalloc(sizeof(*link), GFP_USER);
3558         if (!link) {
3559                 err = -ENOMEM;
3560                 goto out_put_file;
3561         }
3562         bpf_link_init(&link->link, BPF_LINK_TYPE_PERF_EVENT, &bpf_perf_link_lops, prog);
3563         link->perf_file = perf_file;
3564
3565         err = bpf_link_prime(&link->link, &link_primer);
3566         if (err) {
3567                 kfree(link);
3568                 goto out_put_file;
3569         }
3570
3571         event = perf_file->private_data;
3572         err = perf_event_set_bpf_prog(event, prog, attr->link_create.perf_event.bpf_cookie);
3573         if (err) {
3574                 bpf_link_cleanup(&link_primer);
3575                 goto out_put_file;
3576         }
3577         /* perf_event_set_bpf_prog() doesn't take its own refcnt on prog */
3578         bpf_prog_inc(prog);
3579
3580         return bpf_link_settle(&link_primer);
3581
3582 out_put_file:
3583         fput(perf_file);
3584         return err;
3585 }
3586 #else
3587 static int bpf_perf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
3588 {
3589         return -EOPNOTSUPP;
3590 }
3591 #endif /* CONFIG_PERF_EVENTS */
3592
3593 static int bpf_raw_tp_link_attach(struct bpf_prog *prog,
3594                                   const char __user *user_tp_name)
3595 {
3596         struct bpf_link_primer link_primer;
3597         struct bpf_raw_tp_link *link;
3598         struct bpf_raw_event_map *btp;
3599         const char *tp_name;
3600         char buf[128];
3601         int err;
3602
3603         switch (prog->type) {
3604         case BPF_PROG_TYPE_TRACING:
3605         case BPF_PROG_TYPE_EXT:
3606         case BPF_PROG_TYPE_LSM:
3607                 if (user_tp_name)
3608                         /* The attach point for this category of programs
3609                          * should be specified via btf_id during program load.
3610                          */
3611                         return -EINVAL;
3612                 if (prog->type == BPF_PROG_TYPE_TRACING &&
3613                     prog->expected_attach_type == BPF_TRACE_RAW_TP) {
3614                         tp_name = prog->aux->attach_func_name;
3615                         break;
3616                 }
3617                 return bpf_tracing_prog_attach(prog, 0, 0, 0);
3618         case BPF_PROG_TYPE_RAW_TRACEPOINT:
3619         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
3620                 if (strncpy_from_user(buf, user_tp_name, sizeof(buf) - 1) < 0)
3621                         return -EFAULT;
3622                 buf[sizeof(buf) - 1] = 0;
3623                 tp_name = buf;
3624                 break;
3625         default:
3626                 return -EINVAL;
3627         }
3628
3629         btp = bpf_get_raw_tracepoint(tp_name);
3630         if (!btp)
3631                 return -ENOENT;
3632
3633         link = kzalloc(sizeof(*link), GFP_USER);
3634         if (!link) {
3635                 err = -ENOMEM;
3636                 goto out_put_btp;
3637         }
3638         bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
3639                       &bpf_raw_tp_link_lops, prog);
3640         link->btp = btp;
3641
3642         err = bpf_link_prime(&link->link, &link_primer);
3643         if (err) {
3644                 kfree(link);
3645                 goto out_put_btp;
3646         }
3647
3648         err = bpf_probe_register(link->btp, prog);
3649         if (err) {
3650                 bpf_link_cleanup(&link_primer);
3651                 goto out_put_btp;
3652         }
3653
3654         return bpf_link_settle(&link_primer);
3655
3656 out_put_btp:
3657         bpf_put_raw_tracepoint(btp);
3658         return err;
3659 }
3660
3661 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
3662
3663 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
3664 {
3665         struct bpf_prog *prog;
3666         int fd;
3667
3668         if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
3669                 return -EINVAL;
3670
3671         prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
3672         if (IS_ERR(prog))
3673                 return PTR_ERR(prog);
3674
3675         fd = bpf_raw_tp_link_attach(prog, u64_to_user_ptr(attr->raw_tracepoint.name));
3676         if (fd < 0)
3677                 bpf_prog_put(prog);
3678         return fd;
3679 }
3680
3681 static enum bpf_prog_type
3682 attach_type_to_prog_type(enum bpf_attach_type attach_type)
3683 {
3684         switch (attach_type) {
3685         case BPF_CGROUP_INET_INGRESS:
3686         case BPF_CGROUP_INET_EGRESS:
3687                 return BPF_PROG_TYPE_CGROUP_SKB;
3688         case BPF_CGROUP_INET_SOCK_CREATE:
3689         case BPF_CGROUP_INET_SOCK_RELEASE:
3690         case BPF_CGROUP_INET4_POST_BIND:
3691         case BPF_CGROUP_INET6_POST_BIND:
3692                 return BPF_PROG_TYPE_CGROUP_SOCK;
3693         case BPF_CGROUP_INET4_BIND:
3694         case BPF_CGROUP_INET6_BIND:
3695         case BPF_CGROUP_INET4_CONNECT:
3696         case BPF_CGROUP_INET6_CONNECT:
3697         case BPF_CGROUP_INET4_GETPEERNAME:
3698         case BPF_CGROUP_INET6_GETPEERNAME:
3699         case BPF_CGROUP_INET4_GETSOCKNAME:
3700         case BPF_CGROUP_INET6_GETSOCKNAME:
3701         case BPF_CGROUP_UDP4_SENDMSG:
3702         case BPF_CGROUP_UDP6_SENDMSG:
3703         case BPF_CGROUP_UDP4_RECVMSG:
3704         case BPF_CGROUP_UDP6_RECVMSG:
3705                 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
3706         case BPF_CGROUP_SOCK_OPS:
3707                 return BPF_PROG_TYPE_SOCK_OPS;
3708         case BPF_CGROUP_DEVICE:
3709                 return BPF_PROG_TYPE_CGROUP_DEVICE;
3710         case BPF_SK_MSG_VERDICT:
3711                 return BPF_PROG_TYPE_SK_MSG;
3712         case BPF_SK_SKB_STREAM_PARSER:
3713         case BPF_SK_SKB_STREAM_VERDICT:
3714         case BPF_SK_SKB_VERDICT:
3715                 return BPF_PROG_TYPE_SK_SKB;
3716         case BPF_LIRC_MODE2:
3717                 return BPF_PROG_TYPE_LIRC_MODE2;
3718         case BPF_FLOW_DISSECTOR:
3719                 return BPF_PROG_TYPE_FLOW_DISSECTOR;
3720         case BPF_CGROUP_SYSCTL:
3721                 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3722         case BPF_CGROUP_GETSOCKOPT:
3723         case BPF_CGROUP_SETSOCKOPT:
3724                 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3725         case BPF_TRACE_ITER:
3726         case BPF_TRACE_RAW_TP:
3727         case BPF_TRACE_FENTRY:
3728         case BPF_TRACE_FEXIT:
3729         case BPF_MODIFY_RETURN:
3730                 return BPF_PROG_TYPE_TRACING;
3731         case BPF_LSM_MAC:
3732                 return BPF_PROG_TYPE_LSM;
3733         case BPF_SK_LOOKUP:
3734                 return BPF_PROG_TYPE_SK_LOOKUP;
3735         case BPF_XDP:
3736                 return BPF_PROG_TYPE_XDP;
3737         case BPF_LSM_CGROUP:
3738                 return BPF_PROG_TYPE_LSM;
3739         case BPF_TCX_INGRESS:
3740         case BPF_TCX_EGRESS:
3741                 return BPF_PROG_TYPE_SCHED_CLS;
3742         default:
3743                 return BPF_PROG_TYPE_UNSPEC;
3744         }
3745 }
3746
3747 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
3748                                              enum bpf_attach_type attach_type)
3749 {
3750         enum bpf_prog_type ptype;
3751
3752         switch (prog->type) {
3753         case BPF_PROG_TYPE_CGROUP_SOCK:
3754         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3755         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3756         case BPF_PROG_TYPE_SK_LOOKUP:
3757                 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
3758         case BPF_PROG_TYPE_CGROUP_SKB:
3759                 if (!capable(CAP_NET_ADMIN))
3760                         /* cg-skb progs can be loaded by unpriv user.
3761                          * check permissions at attach time.
3762                          */
3763                         return -EPERM;
3764                 return prog->enforce_expected_attach_type &&
3765                         prog->expected_attach_type != attach_type ?
3766                         -EINVAL : 0;
3767         case BPF_PROG_TYPE_EXT:
3768                 return 0;
3769         case BPF_PROG_TYPE_NETFILTER:
3770                 if (attach_type != BPF_NETFILTER)
3771                         return -EINVAL;
3772                 return 0;
3773         case BPF_PROG_TYPE_PERF_EVENT:
3774         case BPF_PROG_TYPE_TRACEPOINT:
3775                 if (attach_type != BPF_PERF_EVENT)
3776                         return -EINVAL;
3777                 return 0;
3778         case BPF_PROG_TYPE_KPROBE:
3779                 if (prog->expected_attach_type == BPF_TRACE_KPROBE_MULTI &&
3780                     attach_type != BPF_TRACE_KPROBE_MULTI)
3781                         return -EINVAL;
3782                 if (prog->expected_attach_type == BPF_TRACE_UPROBE_MULTI &&
3783                     attach_type != BPF_TRACE_UPROBE_MULTI)
3784                         return -EINVAL;
3785                 if (attach_type != BPF_PERF_EVENT &&
3786                     attach_type != BPF_TRACE_KPROBE_MULTI &&
3787                     attach_type != BPF_TRACE_UPROBE_MULTI)
3788                         return -EINVAL;
3789                 return 0;
3790         case BPF_PROG_TYPE_SCHED_CLS:
3791                 if (attach_type != BPF_TCX_INGRESS &&
3792                     attach_type != BPF_TCX_EGRESS)
3793                         return -EINVAL;
3794                 return 0;
3795         default:
3796                 ptype = attach_type_to_prog_type(attach_type);
3797                 if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type)
3798                         return -EINVAL;
3799                 return 0;
3800         }
3801 }
3802
3803 #define BPF_PROG_ATTACH_LAST_FIELD expected_revision
3804
3805 #define BPF_F_ATTACH_MASK_BASE  \
3806         (BPF_F_ALLOW_OVERRIDE | \
3807          BPF_F_ALLOW_MULTI |    \
3808          BPF_F_REPLACE)
3809
3810 #define BPF_F_ATTACH_MASK_MPROG \
3811         (BPF_F_REPLACE |        \
3812          BPF_F_BEFORE |         \
3813          BPF_F_AFTER |          \
3814          BPF_F_ID |             \
3815          BPF_F_LINK)
3816
3817 static int bpf_prog_attach(const union bpf_attr *attr)
3818 {
3819         enum bpf_prog_type ptype;
3820         struct bpf_prog *prog;
3821         int ret;
3822
3823         if (CHECK_ATTR(BPF_PROG_ATTACH))
3824                 return -EINVAL;
3825
3826         ptype = attach_type_to_prog_type(attr->attach_type);
3827         if (ptype == BPF_PROG_TYPE_UNSPEC)
3828                 return -EINVAL;
3829         if (bpf_mprog_supported(ptype)) {
3830                 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3831                         return -EINVAL;
3832         } else {
3833                 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_BASE)
3834                         return -EINVAL;
3835                 if (attr->relative_fd ||
3836                     attr->expected_revision)
3837                         return -EINVAL;
3838         }
3839
3840         prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3841         if (IS_ERR(prog))
3842                 return PTR_ERR(prog);
3843
3844         if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3845                 bpf_prog_put(prog);
3846                 return -EINVAL;
3847         }
3848
3849         switch (ptype) {
3850         case BPF_PROG_TYPE_SK_SKB:
3851         case BPF_PROG_TYPE_SK_MSG:
3852                 ret = sock_map_get_from_fd(attr, prog);
3853                 break;
3854         case BPF_PROG_TYPE_LIRC_MODE2:
3855                 ret = lirc_prog_attach(attr, prog);
3856                 break;
3857         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3858                 ret = netns_bpf_prog_attach(attr, prog);
3859                 break;
3860         case BPF_PROG_TYPE_CGROUP_DEVICE:
3861         case BPF_PROG_TYPE_CGROUP_SKB:
3862         case BPF_PROG_TYPE_CGROUP_SOCK:
3863         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3864         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3865         case BPF_PROG_TYPE_CGROUP_SYSCTL:
3866         case BPF_PROG_TYPE_SOCK_OPS:
3867         case BPF_PROG_TYPE_LSM:
3868                 if (ptype == BPF_PROG_TYPE_LSM &&
3869                     prog->expected_attach_type != BPF_LSM_CGROUP)
3870                         ret = -EINVAL;
3871                 else
3872                         ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3873                 break;
3874         case BPF_PROG_TYPE_SCHED_CLS:
3875                 ret = tcx_prog_attach(attr, prog);
3876                 break;
3877         default:
3878                 ret = -EINVAL;
3879         }
3880
3881         if (ret)
3882                 bpf_prog_put(prog);
3883         return ret;
3884 }
3885
3886 #define BPF_PROG_DETACH_LAST_FIELD expected_revision
3887
3888 static int bpf_prog_detach(const union bpf_attr *attr)
3889 {
3890         struct bpf_prog *prog = NULL;
3891         enum bpf_prog_type ptype;
3892         int ret;
3893
3894         if (CHECK_ATTR(BPF_PROG_DETACH))
3895                 return -EINVAL;
3896
3897         ptype = attach_type_to_prog_type(attr->attach_type);
3898         if (bpf_mprog_supported(ptype)) {
3899                 if (ptype == BPF_PROG_TYPE_UNSPEC)
3900                         return -EINVAL;
3901                 if (attr->attach_flags & ~BPF_F_ATTACH_MASK_MPROG)
3902                         return -EINVAL;
3903                 if (attr->attach_bpf_fd) {
3904                         prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3905                         if (IS_ERR(prog))
3906                                 return PTR_ERR(prog);
3907                 }
3908         } else if (attr->attach_flags ||
3909                    attr->relative_fd ||
3910                    attr->expected_revision) {
3911                 return -EINVAL;
3912         }
3913
3914         switch (ptype) {
3915         case BPF_PROG_TYPE_SK_MSG:
3916         case BPF_PROG_TYPE_SK_SKB:
3917                 ret = sock_map_prog_detach(attr, ptype);
3918                 break;
3919         case BPF_PROG_TYPE_LIRC_MODE2:
3920                 ret = lirc_prog_detach(attr);
3921                 break;
3922         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3923                 ret = netns_bpf_prog_detach(attr, ptype);
3924                 break;
3925         case BPF_PROG_TYPE_CGROUP_DEVICE:
3926         case BPF_PROG_TYPE_CGROUP_SKB:
3927         case BPF_PROG_TYPE_CGROUP_SOCK:
3928         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3929         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3930         case BPF_PROG_TYPE_CGROUP_SYSCTL:
3931         case BPF_PROG_TYPE_SOCK_OPS:
3932         case BPF_PROG_TYPE_LSM:
3933                 ret = cgroup_bpf_prog_detach(attr, ptype);
3934                 break;
3935         case BPF_PROG_TYPE_SCHED_CLS:
3936                 ret = tcx_prog_detach(attr, prog);
3937                 break;
3938         default:
3939                 ret = -EINVAL;
3940         }
3941
3942         if (prog)
3943                 bpf_prog_put(prog);
3944         return ret;
3945 }
3946
3947 #define BPF_PROG_QUERY_LAST_FIELD query.revision
3948
3949 static int bpf_prog_query(const union bpf_attr *attr,
3950                           union bpf_attr __user *uattr)
3951 {
3952         if (!capable(CAP_NET_ADMIN))
3953                 return -EPERM;
3954         if (CHECK_ATTR(BPF_PROG_QUERY))
3955                 return -EINVAL;
3956         if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3957                 return -EINVAL;
3958
3959         switch (attr->query.attach_type) {
3960         case BPF_CGROUP_INET_INGRESS:
3961         case BPF_CGROUP_INET_EGRESS:
3962         case BPF_CGROUP_INET_SOCK_CREATE:
3963         case BPF_CGROUP_INET_SOCK_RELEASE:
3964         case BPF_CGROUP_INET4_BIND:
3965         case BPF_CGROUP_INET6_BIND:
3966         case BPF_CGROUP_INET4_POST_BIND:
3967         case BPF_CGROUP_INET6_POST_BIND:
3968         case BPF_CGROUP_INET4_CONNECT:
3969         case BPF_CGROUP_INET6_CONNECT:
3970         case BPF_CGROUP_INET4_GETPEERNAME:
3971         case BPF_CGROUP_INET6_GETPEERNAME:
3972         case BPF_CGROUP_INET4_GETSOCKNAME:
3973         case BPF_CGROUP_INET6_GETSOCKNAME:
3974         case BPF_CGROUP_UDP4_SENDMSG:
3975         case BPF_CGROUP_UDP6_SENDMSG:
3976         case BPF_CGROUP_UDP4_RECVMSG:
3977         case BPF_CGROUP_UDP6_RECVMSG:
3978         case BPF_CGROUP_SOCK_OPS:
3979         case BPF_CGROUP_DEVICE:
3980         case BPF_CGROUP_SYSCTL:
3981         case BPF_CGROUP_GETSOCKOPT:
3982         case BPF_CGROUP_SETSOCKOPT:
3983         case BPF_LSM_CGROUP:
3984                 return cgroup_bpf_prog_query(attr, uattr);
3985         case BPF_LIRC_MODE2:
3986                 return lirc_prog_query(attr, uattr);
3987         case BPF_FLOW_DISSECTOR:
3988         case BPF_SK_LOOKUP:
3989                 return netns_bpf_prog_query(attr, uattr);
3990         case BPF_SK_SKB_STREAM_PARSER:
3991         case BPF_SK_SKB_STREAM_VERDICT:
3992         case BPF_SK_MSG_VERDICT:
3993         case BPF_SK_SKB_VERDICT:
3994                 return sock_map_bpf_prog_query(attr, uattr);
3995         case BPF_TCX_INGRESS:
3996         case BPF_TCX_EGRESS:
3997                 return tcx_prog_query(attr, uattr);
3998         default:
3999                 return -EINVAL;
4000         }
4001 }
4002
4003 #define BPF_PROG_TEST_RUN_LAST_FIELD test.batch_size
4004
4005 static int bpf_prog_test_run(const union bpf_attr *attr,
4006                              union bpf_attr __user *uattr)
4007 {
4008         struct bpf_prog *prog;
4009         int ret = -ENOTSUPP;
4010
4011         if (CHECK_ATTR(BPF_PROG_TEST_RUN))
4012                 return -EINVAL;
4013
4014         if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
4015             (!attr->test.ctx_size_in && attr->test.ctx_in))
4016                 return -EINVAL;
4017
4018         if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
4019             (!attr->test.ctx_size_out && attr->test.ctx_out))
4020                 return -EINVAL;
4021
4022         prog = bpf_prog_get(attr->test.prog_fd);
4023         if (IS_ERR(prog))
4024                 return PTR_ERR(prog);
4025
4026         if (prog->aux->ops->test_run)
4027                 ret = prog->aux->ops->test_run(prog, attr, uattr);
4028
4029         bpf_prog_put(prog);
4030         return ret;
4031 }
4032
4033 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
4034
4035 static int bpf_obj_get_next_id(const union bpf_attr *attr,
4036                                union bpf_attr __user *uattr,
4037                                struct idr *idr,
4038                                spinlock_t *lock)
4039 {
4040         u32 next_id = attr->start_id;
4041         int err = 0;
4042
4043         if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
4044                 return -EINVAL;
4045
4046         if (!capable(CAP_SYS_ADMIN))
4047                 return -EPERM;
4048
4049         next_id++;
4050         spin_lock_bh(lock);
4051         if (!idr_get_next(idr, &next_id))
4052                 err = -ENOENT;
4053         spin_unlock_bh(lock);
4054
4055         if (!err)
4056                 err = put_user(next_id, &uattr->next_id);
4057
4058         return err;
4059 }
4060
4061 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
4062 {
4063         struct bpf_map *map;
4064
4065         spin_lock_bh(&map_idr_lock);
4066 again:
4067         map = idr_get_next(&map_idr, id);
4068         if (map) {
4069                 map = __bpf_map_inc_not_zero(map, false);
4070                 if (IS_ERR(map)) {
4071                         (*id)++;
4072                         goto again;
4073                 }
4074         }
4075         spin_unlock_bh(&map_idr_lock);
4076
4077         return map;
4078 }
4079
4080 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
4081 {
4082         struct bpf_prog *prog;
4083
4084         spin_lock_bh(&prog_idr_lock);
4085 again:
4086         prog = idr_get_next(&prog_idr, id);
4087         if (prog) {
4088                 prog = bpf_prog_inc_not_zero(prog);
4089                 if (IS_ERR(prog)) {
4090                         (*id)++;
4091                         goto again;
4092                 }
4093         }
4094         spin_unlock_bh(&prog_idr_lock);
4095
4096         return prog;
4097 }
4098
4099 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
4100
4101 struct bpf_prog *bpf_prog_by_id(u32 id)
4102 {
4103         struct bpf_prog *prog;
4104
4105         if (!id)
4106                 return ERR_PTR(-ENOENT);
4107
4108         spin_lock_bh(&prog_idr_lock);
4109         prog = idr_find(&prog_idr, id);
4110         if (prog)
4111                 prog = bpf_prog_inc_not_zero(prog);
4112         else
4113                 prog = ERR_PTR(-ENOENT);
4114         spin_unlock_bh(&prog_idr_lock);
4115         return prog;
4116 }
4117
4118 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
4119 {
4120         struct bpf_prog *prog;
4121         u32 id = attr->prog_id;
4122         int fd;
4123
4124         if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
4125                 return -EINVAL;
4126
4127         if (!capable(CAP_SYS_ADMIN))
4128                 return -EPERM;
4129
4130         prog = bpf_prog_by_id(id);
4131         if (IS_ERR(prog))
4132                 return PTR_ERR(prog);
4133
4134         fd = bpf_prog_new_fd(prog);
4135         if (fd < 0)
4136                 bpf_prog_put(prog);
4137
4138         return fd;
4139 }
4140
4141 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
4142
4143 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
4144 {
4145         struct bpf_map *map;
4146         u32 id = attr->map_id;
4147         int f_flags;
4148         int fd;
4149
4150         if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
4151             attr->open_flags & ~BPF_OBJ_FLAG_MASK)
4152                 return -EINVAL;
4153
4154         if (!capable(CAP_SYS_ADMIN))
4155                 return -EPERM;
4156
4157         f_flags = bpf_get_file_flag(attr->open_flags);
4158         if (f_flags < 0)
4159                 return f_flags;
4160
4161         spin_lock_bh(&map_idr_lock);
4162         map = idr_find(&map_idr, id);
4163         if (map)
4164                 map = __bpf_map_inc_not_zero(map, true);
4165         else
4166                 map = ERR_PTR(-ENOENT);
4167         spin_unlock_bh(&map_idr_lock);
4168
4169         if (IS_ERR(map))
4170                 return PTR_ERR(map);
4171
4172         fd = bpf_map_new_fd(map, f_flags);
4173         if (fd < 0)
4174                 bpf_map_put_with_uref(map);
4175
4176         return fd;
4177 }
4178
4179 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
4180                                               unsigned long addr, u32 *off,
4181                                               u32 *type)
4182 {
4183         const struct bpf_map *map;
4184         int i;
4185
4186         mutex_lock(&prog->aux->used_maps_mutex);
4187         for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
4188                 map = prog->aux->used_maps[i];
4189                 if (map == (void *)addr) {
4190                         *type = BPF_PSEUDO_MAP_FD;
4191                         goto out;
4192                 }
4193                 if (!map->ops->map_direct_value_meta)
4194                         continue;
4195                 if (!map->ops->map_direct_value_meta(map, addr, off)) {
4196                         *type = BPF_PSEUDO_MAP_VALUE;
4197                         goto out;
4198                 }
4199         }
4200         map = NULL;
4201
4202 out:
4203         mutex_unlock(&prog->aux->used_maps_mutex);
4204         return map;
4205 }
4206
4207 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
4208                                               const struct cred *f_cred)
4209 {
4210         const struct bpf_map *map;
4211         struct bpf_insn *insns;
4212         u32 off, type;
4213         u64 imm;
4214         u8 code;
4215         int i;
4216
4217         insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
4218                         GFP_USER);
4219         if (!insns)
4220                 return insns;
4221
4222         for (i = 0; i < prog->len; i++) {
4223                 code = insns[i].code;
4224
4225                 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
4226                         insns[i].code = BPF_JMP | BPF_CALL;
4227                         insns[i].imm = BPF_FUNC_tail_call;
4228                         /* fall-through */
4229                 }
4230                 if (code == (BPF_JMP | BPF_CALL) ||
4231                     code == (BPF_JMP | BPF_CALL_ARGS)) {
4232                         if (code == (BPF_JMP | BPF_CALL_ARGS))
4233                                 insns[i].code = BPF_JMP | BPF_CALL;
4234                         if (!bpf_dump_raw_ok(f_cred))
4235                                 insns[i].imm = 0;
4236                         continue;
4237                 }
4238                 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
4239                         insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
4240                         continue;
4241                 }
4242
4243                 if (code != (BPF_LD | BPF_IMM | BPF_DW))
4244                         continue;
4245
4246                 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
4247                 map = bpf_map_from_imm(prog, imm, &off, &type);
4248                 if (map) {
4249                         insns[i].src_reg = type;
4250                         insns[i].imm = map->id;
4251                         insns[i + 1].imm = off;
4252                         continue;
4253                 }
4254         }
4255
4256         return insns;
4257 }
4258
4259 static int set_info_rec_size(struct bpf_prog_info *info)
4260 {
4261         /*
4262          * Ensure info.*_rec_size is the same as kernel expected size
4263          *
4264          * or
4265          *
4266          * Only allow zero *_rec_size if both _rec_size and _cnt are
4267          * zero.  In this case, the kernel will set the expected
4268          * _rec_size back to the info.
4269          */
4270
4271         if ((info->nr_func_info || info->func_info_rec_size) &&
4272             info->func_info_rec_size != sizeof(struct bpf_func_info))
4273                 return -EINVAL;
4274
4275         if ((info->nr_line_info || info->line_info_rec_size) &&
4276             info->line_info_rec_size != sizeof(struct bpf_line_info))
4277                 return -EINVAL;
4278
4279         if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
4280             info->jited_line_info_rec_size != sizeof(__u64))
4281                 return -EINVAL;
4282
4283         info->func_info_rec_size = sizeof(struct bpf_func_info);
4284         info->line_info_rec_size = sizeof(struct bpf_line_info);
4285         info->jited_line_info_rec_size = sizeof(__u64);
4286
4287         return 0;
4288 }
4289
4290 static int bpf_prog_get_info_by_fd(struct file *file,
4291                                    struct bpf_prog *prog,
4292                                    const union bpf_attr *attr,
4293                                    union bpf_attr __user *uattr)
4294 {
4295         struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4296         struct btf *attach_btf = bpf_prog_get_target_btf(prog);
4297         struct bpf_prog_info info;
4298         u32 info_len = attr->info.info_len;
4299         struct bpf_prog_kstats stats;
4300         char __user *uinsns;
4301         u32 ulen;
4302         int err;
4303
4304         err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4305         if (err)
4306                 return err;
4307         info_len = min_t(u32, sizeof(info), info_len);
4308
4309         memset(&info, 0, sizeof(info));
4310         if (copy_from_user(&info, uinfo, info_len))
4311                 return -EFAULT;
4312
4313         info.type = prog->type;
4314         info.id = prog->aux->id;
4315         info.load_time = prog->aux->load_time;
4316         info.created_by_uid = from_kuid_munged(current_user_ns(),
4317                                                prog->aux->user->uid);
4318         info.gpl_compatible = prog->gpl_compatible;
4319
4320         memcpy(info.tag, prog->tag, sizeof(prog->tag));
4321         memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
4322
4323         mutex_lock(&prog->aux->used_maps_mutex);
4324         ulen = info.nr_map_ids;
4325         info.nr_map_ids = prog->aux->used_map_cnt;
4326         ulen = min_t(u32, info.nr_map_ids, ulen);
4327         if (ulen) {
4328                 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
4329                 u32 i;
4330
4331                 for (i = 0; i < ulen; i++)
4332                         if (put_user(prog->aux->used_maps[i]->id,
4333                                      &user_map_ids[i])) {
4334                                 mutex_unlock(&prog->aux->used_maps_mutex);
4335                                 return -EFAULT;
4336                         }
4337         }
4338         mutex_unlock(&prog->aux->used_maps_mutex);
4339
4340         err = set_info_rec_size(&info);
4341         if (err)
4342                 return err;
4343
4344         bpf_prog_get_stats(prog, &stats);
4345         info.run_time_ns = stats.nsecs;
4346         info.run_cnt = stats.cnt;
4347         info.recursion_misses = stats.misses;
4348
4349         info.verified_insns = prog->aux->verified_insns;
4350
4351         if (!bpf_capable()) {
4352                 info.jited_prog_len = 0;
4353                 info.xlated_prog_len = 0;
4354                 info.nr_jited_ksyms = 0;
4355                 info.nr_jited_func_lens = 0;
4356                 info.nr_func_info = 0;
4357                 info.nr_line_info = 0;
4358                 info.nr_jited_line_info = 0;
4359                 goto done;
4360         }
4361
4362         ulen = info.xlated_prog_len;
4363         info.xlated_prog_len = bpf_prog_insn_size(prog);
4364         if (info.xlated_prog_len && ulen) {
4365                 struct bpf_insn *insns_sanitized;
4366                 bool fault;
4367
4368                 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
4369                         info.xlated_prog_insns = 0;
4370                         goto done;
4371                 }
4372                 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
4373                 if (!insns_sanitized)
4374                         return -ENOMEM;
4375                 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
4376                 ulen = min_t(u32, info.xlated_prog_len, ulen);
4377                 fault = copy_to_user(uinsns, insns_sanitized, ulen);
4378                 kfree(insns_sanitized);
4379                 if (fault)
4380                         return -EFAULT;
4381         }
4382
4383         if (bpf_prog_is_offloaded(prog->aux)) {
4384                 err = bpf_prog_offload_info_fill(&info, prog);
4385                 if (err)
4386                         return err;
4387                 goto done;
4388         }
4389
4390         /* NOTE: the following code is supposed to be skipped for offload.
4391          * bpf_prog_offload_info_fill() is the place to fill similar fields
4392          * for offload.
4393          */
4394         ulen = info.jited_prog_len;
4395         if (prog->aux->func_cnt) {
4396                 u32 i;
4397
4398                 info.jited_prog_len = 0;
4399                 for (i = 0; i < prog->aux->func_cnt; i++)
4400                         info.jited_prog_len += prog->aux->func[i]->jited_len;
4401         } else {
4402                 info.jited_prog_len = prog->jited_len;
4403         }
4404
4405         if (info.jited_prog_len && ulen) {
4406                 if (bpf_dump_raw_ok(file->f_cred)) {
4407                         uinsns = u64_to_user_ptr(info.jited_prog_insns);
4408                         ulen = min_t(u32, info.jited_prog_len, ulen);
4409
4410                         /* for multi-function programs, copy the JITed
4411                          * instructions for all the functions
4412                          */
4413                         if (prog->aux->func_cnt) {
4414                                 u32 len, free, i;
4415                                 u8 *img;
4416
4417                                 free = ulen;
4418                                 for (i = 0; i < prog->aux->func_cnt; i++) {
4419                                         len = prog->aux->func[i]->jited_len;
4420                                         len = min_t(u32, len, free);
4421                                         img = (u8 *) prog->aux->func[i]->bpf_func;
4422                                         if (copy_to_user(uinsns, img, len))
4423                                                 return -EFAULT;
4424                                         uinsns += len;
4425                                         free -= len;
4426                                         if (!free)
4427                                                 break;
4428                                 }
4429                         } else {
4430                                 if (copy_to_user(uinsns, prog->bpf_func, ulen))
4431                                         return -EFAULT;
4432                         }
4433                 } else {
4434                         info.jited_prog_insns = 0;
4435                 }
4436         }
4437
4438         ulen = info.nr_jited_ksyms;
4439         info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
4440         if (ulen) {
4441                 if (bpf_dump_raw_ok(file->f_cred)) {
4442                         unsigned long ksym_addr;
4443                         u64 __user *user_ksyms;
4444                         u32 i;
4445
4446                         /* copy the address of the kernel symbol
4447                          * corresponding to each function
4448                          */
4449                         ulen = min_t(u32, info.nr_jited_ksyms, ulen);
4450                         user_ksyms = u64_to_user_ptr(info.jited_ksyms);
4451                         if (prog->aux->func_cnt) {
4452                                 for (i = 0; i < ulen; i++) {
4453                                         ksym_addr = (unsigned long)
4454                                                 prog->aux->func[i]->bpf_func;
4455                                         if (put_user((u64) ksym_addr,
4456                                                      &user_ksyms[i]))
4457                                                 return -EFAULT;
4458                                 }
4459                         } else {
4460                                 ksym_addr = (unsigned long) prog->bpf_func;
4461                                 if (put_user((u64) ksym_addr, &user_ksyms[0]))
4462                                         return -EFAULT;
4463                         }
4464                 } else {
4465                         info.jited_ksyms = 0;
4466                 }
4467         }
4468
4469         ulen = info.nr_jited_func_lens;
4470         info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
4471         if (ulen) {
4472                 if (bpf_dump_raw_ok(file->f_cred)) {
4473                         u32 __user *user_lens;
4474                         u32 func_len, i;
4475
4476                         /* copy the JITed image lengths for each function */
4477                         ulen = min_t(u32, info.nr_jited_func_lens, ulen);
4478                         user_lens = u64_to_user_ptr(info.jited_func_lens);
4479                         if (prog->aux->func_cnt) {
4480                                 for (i = 0; i < ulen; i++) {
4481                                         func_len =
4482                                                 prog->aux->func[i]->jited_len;
4483                                         if (put_user(func_len, &user_lens[i]))
4484                                                 return -EFAULT;
4485                                 }
4486                         } else {
4487                                 func_len = prog->jited_len;
4488                                 if (put_user(func_len, &user_lens[0]))
4489                                         return -EFAULT;
4490                         }
4491                 } else {
4492                         info.jited_func_lens = 0;
4493                 }
4494         }
4495
4496         if (prog->aux->btf)
4497                 info.btf_id = btf_obj_id(prog->aux->btf);
4498         info.attach_btf_id = prog->aux->attach_btf_id;
4499         if (attach_btf)
4500                 info.attach_btf_obj_id = btf_obj_id(attach_btf);
4501
4502         ulen = info.nr_func_info;
4503         info.nr_func_info = prog->aux->func_info_cnt;
4504         if (info.nr_func_info && ulen) {
4505                 char __user *user_finfo;
4506
4507                 user_finfo = u64_to_user_ptr(info.func_info);
4508                 ulen = min_t(u32, info.nr_func_info, ulen);
4509                 if (copy_to_user(user_finfo, prog->aux->func_info,
4510                                  info.func_info_rec_size * ulen))
4511                         return -EFAULT;
4512         }
4513
4514         ulen = info.nr_line_info;
4515         info.nr_line_info = prog->aux->nr_linfo;
4516         if (info.nr_line_info && ulen) {
4517                 __u8 __user *user_linfo;
4518
4519                 user_linfo = u64_to_user_ptr(info.line_info);
4520                 ulen = min_t(u32, info.nr_line_info, ulen);
4521                 if (copy_to_user(user_linfo, prog->aux->linfo,
4522                                  info.line_info_rec_size * ulen))
4523                         return -EFAULT;
4524         }
4525
4526         ulen = info.nr_jited_line_info;
4527         if (prog->aux->jited_linfo)
4528                 info.nr_jited_line_info = prog->aux->nr_linfo;
4529         else
4530                 info.nr_jited_line_info = 0;
4531         if (info.nr_jited_line_info && ulen) {
4532                 if (bpf_dump_raw_ok(file->f_cred)) {
4533                         unsigned long line_addr;
4534                         __u64 __user *user_linfo;
4535                         u32 i;
4536
4537                         user_linfo = u64_to_user_ptr(info.jited_line_info);
4538                         ulen = min_t(u32, info.nr_jited_line_info, ulen);
4539                         for (i = 0; i < ulen; i++) {
4540                                 line_addr = (unsigned long)prog->aux->jited_linfo[i];
4541                                 if (put_user((__u64)line_addr, &user_linfo[i]))
4542                                         return -EFAULT;
4543                         }
4544                 } else {
4545                         info.jited_line_info = 0;
4546                 }
4547         }
4548
4549         ulen = info.nr_prog_tags;
4550         info.nr_prog_tags = prog->aux->func_cnt ? : 1;
4551         if (ulen) {
4552                 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
4553                 u32 i;
4554
4555                 user_prog_tags = u64_to_user_ptr(info.prog_tags);
4556                 ulen = min_t(u32, info.nr_prog_tags, ulen);
4557                 if (prog->aux->func_cnt) {
4558                         for (i = 0; i < ulen; i++) {
4559                                 if (copy_to_user(user_prog_tags[i],
4560                                                  prog->aux->func[i]->tag,
4561                                                  BPF_TAG_SIZE))
4562                                         return -EFAULT;
4563                         }
4564                 } else {
4565                         if (copy_to_user(user_prog_tags[0],
4566                                          prog->tag, BPF_TAG_SIZE))
4567                                 return -EFAULT;
4568                 }
4569         }
4570
4571 done:
4572         if (copy_to_user(uinfo, &info, info_len) ||
4573             put_user(info_len, &uattr->info.info_len))
4574                 return -EFAULT;
4575
4576         return 0;
4577 }
4578
4579 static int bpf_map_get_info_by_fd(struct file *file,
4580                                   struct bpf_map *map,
4581                                   const union bpf_attr *attr,
4582                                   union bpf_attr __user *uattr)
4583 {
4584         struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4585         struct bpf_map_info info;
4586         u32 info_len = attr->info.info_len;
4587         int err;
4588
4589         err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4590         if (err)
4591                 return err;
4592         info_len = min_t(u32, sizeof(info), info_len);
4593
4594         memset(&info, 0, sizeof(info));
4595         info.type = map->map_type;
4596         info.id = map->id;
4597         info.key_size = map->key_size;
4598         info.value_size = map->value_size;
4599         info.max_entries = map->max_entries;
4600         info.map_flags = map->map_flags;
4601         info.map_extra = map->map_extra;
4602         memcpy(info.name, map->name, sizeof(map->name));
4603
4604         if (map->btf) {
4605                 info.btf_id = btf_obj_id(map->btf);
4606                 info.btf_key_type_id = map->btf_key_type_id;
4607                 info.btf_value_type_id = map->btf_value_type_id;
4608         }
4609         info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
4610
4611         if (bpf_map_is_offloaded(map)) {
4612                 err = bpf_map_offload_info_fill(&info, map);
4613                 if (err)
4614                         return err;
4615         }
4616
4617         if (copy_to_user(uinfo, &info, info_len) ||
4618             put_user(info_len, &uattr->info.info_len))
4619                 return -EFAULT;
4620
4621         return 0;
4622 }
4623
4624 static int bpf_btf_get_info_by_fd(struct file *file,
4625                                   struct btf *btf,
4626                                   const union bpf_attr *attr,
4627                                   union bpf_attr __user *uattr)
4628 {
4629         struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4630         u32 info_len = attr->info.info_len;
4631         int err;
4632
4633         err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(*uinfo), info_len);
4634         if (err)
4635                 return err;
4636
4637         return btf_get_info_by_fd(btf, attr, uattr);
4638 }
4639
4640 static int bpf_link_get_info_by_fd(struct file *file,
4641                                   struct bpf_link *link,
4642                                   const union bpf_attr *attr,
4643                                   union bpf_attr __user *uattr)
4644 {
4645         struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
4646         struct bpf_link_info info;
4647         u32 info_len = attr->info.info_len;
4648         int err;
4649
4650         err = bpf_check_uarg_tail_zero(USER_BPFPTR(uinfo), sizeof(info), info_len);
4651         if (err)
4652                 return err;
4653         info_len = min_t(u32, sizeof(info), info_len);
4654
4655         memset(&info, 0, sizeof(info));
4656         if (copy_from_user(&info, uinfo, info_len))
4657                 return -EFAULT;
4658
4659         info.type = link->type;
4660         info.id = link->id;
4661         if (link->prog)
4662                 info.prog_id = link->prog->aux->id;
4663
4664         if (link->ops->fill_link_info) {
4665                 err = link->ops->fill_link_info(link, &info);
4666                 if (err)
4667                         return err;
4668         }
4669
4670         if (copy_to_user(uinfo, &info, info_len) ||
4671             put_user(info_len, &uattr->info.info_len))
4672                 return -EFAULT;
4673
4674         return 0;
4675 }
4676
4677
4678 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
4679
4680 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
4681                                   union bpf_attr __user *uattr)
4682 {
4683         int ufd = attr->info.bpf_fd;
4684         struct fd f;
4685         int err;
4686
4687         if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
4688                 return -EINVAL;
4689
4690         f = fdget(ufd);
4691         if (!f.file)
4692                 return -EBADFD;
4693
4694         if (f.file->f_op == &bpf_prog_fops)
4695                 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
4696                                               uattr);
4697         else if (f.file->f_op == &bpf_map_fops)
4698                 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
4699                                              uattr);
4700         else if (f.file->f_op == &btf_fops)
4701                 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
4702         else if (f.file->f_op == &bpf_link_fops)
4703                 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
4704                                               attr, uattr);
4705         else
4706                 err = -EINVAL;
4707
4708         fdput(f);
4709         return err;
4710 }
4711
4712 #define BPF_BTF_LOAD_LAST_FIELD btf_log_true_size
4713
4714 static int bpf_btf_load(const union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size)
4715 {
4716         if (CHECK_ATTR(BPF_BTF_LOAD))
4717                 return -EINVAL;
4718
4719         if (!bpf_capable())
4720                 return -EPERM;
4721
4722         return btf_new_fd(attr, uattr, uattr_size);
4723 }
4724
4725 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
4726
4727 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
4728 {
4729         if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
4730                 return -EINVAL;
4731
4732         if (!capable(CAP_SYS_ADMIN))
4733                 return -EPERM;
4734
4735         return btf_get_fd_by_id(attr->btf_id);
4736 }
4737
4738 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
4739                                     union bpf_attr __user *uattr,
4740                                     u32 prog_id, u32 fd_type,
4741                                     const char *buf, u64 probe_offset,
4742                                     u64 probe_addr)
4743 {
4744         char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
4745         u32 len = buf ? strlen(buf) : 0, input_len;
4746         int err = 0;
4747
4748         if (put_user(len, &uattr->task_fd_query.buf_len))
4749                 return -EFAULT;
4750         input_len = attr->task_fd_query.buf_len;
4751         if (input_len && ubuf) {
4752                 if (!len) {
4753                         /* nothing to copy, just make ubuf NULL terminated */
4754                         char zero = '\0';
4755
4756                         if (put_user(zero, ubuf))
4757                                 return -EFAULT;
4758                 } else if (input_len >= len + 1) {
4759                         /* ubuf can hold the string with NULL terminator */
4760                         if (copy_to_user(ubuf, buf, len + 1))
4761                                 return -EFAULT;
4762                 } else {
4763                         /* ubuf cannot hold the string with NULL terminator,
4764                          * do a partial copy with NULL terminator.
4765                          */
4766                         char zero = '\0';
4767
4768                         err = -ENOSPC;
4769                         if (copy_to_user(ubuf, buf, input_len - 1))
4770                                 return -EFAULT;
4771                         if (put_user(zero, ubuf + input_len - 1))
4772                                 return -EFAULT;
4773                 }
4774         }
4775
4776         if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
4777             put_user(fd_type, &uattr->task_fd_query.fd_type) ||
4778             put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
4779             put_user(probe_addr, &uattr->task_fd_query.probe_addr))
4780                 return -EFAULT;
4781
4782         return err;
4783 }
4784
4785 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
4786
4787 static int bpf_task_fd_query(const union bpf_attr *attr,
4788                              union bpf_attr __user *uattr)
4789 {
4790         pid_t pid = attr->task_fd_query.pid;
4791         u32 fd = attr->task_fd_query.fd;
4792         const struct perf_event *event;
4793         struct task_struct *task;
4794         struct file *file;
4795         int err;
4796
4797         if (CHECK_ATTR(BPF_TASK_FD_QUERY))
4798                 return -EINVAL;
4799
4800         if (!capable(CAP_SYS_ADMIN))
4801                 return -EPERM;
4802
4803         if (attr->task_fd_query.flags != 0)
4804                 return -EINVAL;
4805
4806         rcu_read_lock();
4807         task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
4808         rcu_read_unlock();
4809         if (!task)
4810                 return -ENOENT;
4811
4812         err = 0;
4813         file = fget_task(task, fd);
4814         put_task_struct(task);
4815         if (!file)
4816                 return -EBADF;
4817
4818         if (file->f_op == &bpf_link_fops) {
4819                 struct bpf_link *link = file->private_data;
4820
4821                 if (link->ops == &bpf_raw_tp_link_lops) {
4822                         struct bpf_raw_tp_link *raw_tp =
4823                                 container_of(link, struct bpf_raw_tp_link, link);
4824                         struct bpf_raw_event_map *btp = raw_tp->btp;
4825
4826                         err = bpf_task_fd_query_copy(attr, uattr,
4827                                                      raw_tp->link.prog->aux->id,
4828                                                      BPF_FD_TYPE_RAW_TRACEPOINT,
4829                                                      btp->tp->name, 0, 0);
4830                         goto put_file;
4831                 }
4832                 goto out_not_supp;
4833         }
4834
4835         event = perf_get_event(file);
4836         if (!IS_ERR(event)) {
4837                 u64 probe_offset, probe_addr;
4838                 u32 prog_id, fd_type;
4839                 const char *buf;
4840
4841                 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
4842                                               &buf, &probe_offset,
4843                                               &probe_addr);
4844                 if (!err)
4845                         err = bpf_task_fd_query_copy(attr, uattr, prog_id,
4846                                                      fd_type, buf,
4847                                                      probe_offset,
4848                                                      probe_addr);
4849                 goto put_file;
4850         }
4851
4852 out_not_supp:
4853         err = -ENOTSUPP;
4854 put_file:
4855         fput(file);
4856         return err;
4857 }
4858
4859 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4860
4861 #define BPF_DO_BATCH(fn, ...)                   \
4862         do {                                    \
4863                 if (!fn) {                      \
4864                         err = -ENOTSUPP;        \
4865                         goto err_put;           \
4866                 }                               \
4867                 err = fn(__VA_ARGS__);          \
4868         } while (0)
4869
4870 static int bpf_map_do_batch(const union bpf_attr *attr,
4871                             union bpf_attr __user *uattr,
4872                             int cmd)
4873 {
4874         bool has_read  = cmd == BPF_MAP_LOOKUP_BATCH ||
4875                          cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4876         bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4877         struct bpf_map *map;
4878         int err, ufd;
4879         struct fd f;
4880
4881         if (CHECK_ATTR(BPF_MAP_BATCH))
4882                 return -EINVAL;
4883
4884         ufd = attr->batch.map_fd;
4885         f = fdget(ufd);
4886         map = __bpf_map_get(f);
4887         if (IS_ERR(map))
4888                 return PTR_ERR(map);
4889         if (has_write)
4890                 bpf_map_write_active_inc(map);
4891         if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4892                 err = -EPERM;
4893                 goto err_put;
4894         }
4895         if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4896                 err = -EPERM;
4897                 goto err_put;
4898         }
4899
4900         if (cmd == BPF_MAP_LOOKUP_BATCH)
4901                 BPF_DO_BATCH(map->ops->map_lookup_batch, map, attr, uattr);
4902         else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4903                 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch, map, attr, uattr);
4904         else if (cmd == BPF_MAP_UPDATE_BATCH)
4905                 BPF_DO_BATCH(map->ops->map_update_batch, map, f.file, attr, uattr);
4906         else
4907                 BPF_DO_BATCH(map->ops->map_delete_batch, map, attr, uattr);
4908 err_put:
4909         if (has_write)
4910                 bpf_map_write_active_dec(map);
4911         fdput(f);
4912         return err;
4913 }
4914
4915 #define BPF_LINK_CREATE_LAST_FIELD link_create.uprobe_multi.pid
4916 static int link_create(union bpf_attr *attr, bpfptr_t uattr)
4917 {
4918         struct bpf_prog *prog;
4919         int ret;
4920
4921         if (CHECK_ATTR(BPF_LINK_CREATE))
4922                 return -EINVAL;
4923
4924         if (attr->link_create.attach_type == BPF_STRUCT_OPS)
4925                 return bpf_struct_ops_link_create(attr);
4926
4927         prog = bpf_prog_get(attr->link_create.prog_fd);
4928         if (IS_ERR(prog))
4929                 return PTR_ERR(prog);
4930
4931         ret = bpf_prog_attach_check_attach_type(prog,
4932                                                 attr->link_create.attach_type);
4933         if (ret)
4934                 goto out;
4935
4936         switch (prog->type) {
4937         case BPF_PROG_TYPE_CGROUP_SKB:
4938         case BPF_PROG_TYPE_CGROUP_SOCK:
4939         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4940         case BPF_PROG_TYPE_SOCK_OPS:
4941         case BPF_PROG_TYPE_CGROUP_DEVICE:
4942         case BPF_PROG_TYPE_CGROUP_SYSCTL:
4943         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4944                 ret = cgroup_bpf_link_attach(attr, prog);
4945                 break;
4946         case BPF_PROG_TYPE_EXT:
4947                 ret = bpf_tracing_prog_attach(prog,
4948                                               attr->link_create.target_fd,
4949                                               attr->link_create.target_btf_id,
4950                                               attr->link_create.tracing.cookie);
4951                 break;
4952         case BPF_PROG_TYPE_LSM:
4953         case BPF_PROG_TYPE_TRACING:
4954                 if (attr->link_create.attach_type != prog->expected_attach_type) {
4955                         ret = -EINVAL;
4956                         goto out;
4957                 }
4958                 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
4959                         ret = bpf_raw_tp_link_attach(prog, NULL);
4960                 else if (prog->expected_attach_type == BPF_TRACE_ITER)
4961                         ret = bpf_iter_link_attach(attr, uattr, prog);
4962                 else if (prog->expected_attach_type == BPF_LSM_CGROUP)
4963                         ret = cgroup_bpf_link_attach(attr, prog);
4964                 else
4965                         ret = bpf_tracing_prog_attach(prog,
4966                                                       attr->link_create.target_fd,
4967                                                       attr->link_create.target_btf_id,
4968                                                       attr->link_create.tracing.cookie);
4969                 break;
4970         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4971         case BPF_PROG_TYPE_SK_LOOKUP:
4972                 ret = netns_bpf_link_create(attr, prog);
4973                 break;
4974 #ifdef CONFIG_NET
4975         case BPF_PROG_TYPE_XDP:
4976                 ret = bpf_xdp_link_attach(attr, prog);
4977                 break;
4978         case BPF_PROG_TYPE_SCHED_CLS:
4979                 ret = tcx_link_attach(attr, prog);
4980                 break;
4981         case BPF_PROG_TYPE_NETFILTER:
4982                 ret = bpf_nf_link_attach(attr, prog);
4983                 break;
4984 #endif
4985         case BPF_PROG_TYPE_PERF_EVENT:
4986         case BPF_PROG_TYPE_TRACEPOINT:
4987                 ret = bpf_perf_link_attach(attr, prog);
4988                 break;
4989         case BPF_PROG_TYPE_KPROBE:
4990                 if (attr->link_create.attach_type == BPF_PERF_EVENT)
4991                         ret = bpf_perf_link_attach(attr, prog);
4992                 else if (attr->link_create.attach_type == BPF_TRACE_KPROBE_MULTI)
4993                         ret = bpf_kprobe_multi_link_attach(attr, prog);
4994                 else if (attr->link_create.attach_type == BPF_TRACE_UPROBE_MULTI)
4995                         ret = bpf_uprobe_multi_link_attach(attr, prog);
4996                 break;
4997         default:
4998                 ret = -EINVAL;
4999         }
5000
5001 out:
5002         if (ret < 0)
5003                 bpf_prog_put(prog);
5004         return ret;
5005 }
5006
5007 static int link_update_map(struct bpf_link *link, union bpf_attr *attr)
5008 {
5009         struct bpf_map *new_map, *old_map = NULL;
5010         int ret;
5011
5012         new_map = bpf_map_get(attr->link_update.new_map_fd);
5013         if (IS_ERR(new_map))
5014                 return PTR_ERR(new_map);
5015
5016         if (attr->link_update.flags & BPF_F_REPLACE) {
5017                 old_map = bpf_map_get(attr->link_update.old_map_fd);
5018                 if (IS_ERR(old_map)) {
5019                         ret = PTR_ERR(old_map);
5020                         goto out_put;
5021                 }
5022         } else if (attr->link_update.old_map_fd) {
5023                 ret = -EINVAL;
5024                 goto out_put;
5025         }
5026
5027         ret = link->ops->update_map(link, new_map, old_map);
5028
5029         if (old_map)
5030                 bpf_map_put(old_map);
5031 out_put:
5032         bpf_map_put(new_map);
5033         return ret;
5034 }
5035
5036 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
5037
5038 static int link_update(union bpf_attr *attr)
5039 {
5040         struct bpf_prog *old_prog = NULL, *new_prog;
5041         struct bpf_link *link;
5042         u32 flags;
5043         int ret;
5044
5045         if (CHECK_ATTR(BPF_LINK_UPDATE))
5046                 return -EINVAL;
5047
5048         flags = attr->link_update.flags;
5049         if (flags & ~BPF_F_REPLACE)
5050                 return -EINVAL;
5051
5052         link = bpf_link_get_from_fd(attr->link_update.link_fd);
5053         if (IS_ERR(link))
5054                 return PTR_ERR(link);
5055
5056         if (link->ops->update_map) {
5057                 ret = link_update_map(link, attr);
5058                 goto out_put_link;
5059         }
5060
5061         new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
5062         if (IS_ERR(new_prog)) {
5063                 ret = PTR_ERR(new_prog);
5064                 goto out_put_link;
5065         }
5066
5067         if (flags & BPF_F_REPLACE) {
5068                 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
5069                 if (IS_ERR(old_prog)) {
5070                         ret = PTR_ERR(old_prog);
5071                         old_prog = NULL;
5072                         goto out_put_progs;
5073                 }
5074         } else if (attr->link_update.old_prog_fd) {
5075                 ret = -EINVAL;
5076                 goto out_put_progs;
5077         }
5078
5079         if (link->ops->update_prog)
5080                 ret = link->ops->update_prog(link, new_prog, old_prog);
5081         else
5082                 ret = -EINVAL;
5083
5084 out_put_progs:
5085         if (old_prog)
5086                 bpf_prog_put(old_prog);
5087         if (ret)
5088                 bpf_prog_put(new_prog);
5089 out_put_link:
5090         bpf_link_put_direct(link);
5091         return ret;
5092 }
5093
5094 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
5095
5096 static int link_detach(union bpf_attr *attr)
5097 {
5098         struct bpf_link *link;
5099         int ret;
5100
5101         if (CHECK_ATTR(BPF_LINK_DETACH))
5102                 return -EINVAL;
5103
5104         link = bpf_link_get_from_fd(attr->link_detach.link_fd);
5105         if (IS_ERR(link))
5106                 return PTR_ERR(link);
5107
5108         if (link->ops->detach)
5109                 ret = link->ops->detach(link);
5110         else
5111                 ret = -EOPNOTSUPP;
5112
5113         bpf_link_put_direct(link);
5114         return ret;
5115 }
5116
5117 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
5118 {
5119         return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
5120 }
5121
5122 struct bpf_link *bpf_link_by_id(u32 id)
5123 {
5124         struct bpf_link *link;
5125
5126         if (!id)
5127                 return ERR_PTR(-ENOENT);
5128
5129         spin_lock_bh(&link_idr_lock);
5130         /* before link is "settled", ID is 0, pretend it doesn't exist yet */
5131         link = idr_find(&link_idr, id);
5132         if (link) {
5133                 if (link->id)
5134                         link = bpf_link_inc_not_zero(link);
5135                 else
5136                         link = ERR_PTR(-EAGAIN);
5137         } else {
5138                 link = ERR_PTR(-ENOENT);
5139         }
5140         spin_unlock_bh(&link_idr_lock);
5141         return link;
5142 }
5143
5144 struct bpf_link *bpf_link_get_curr_or_next(u32 *id)
5145 {
5146         struct bpf_link *link;
5147
5148         spin_lock_bh(&link_idr_lock);
5149 again:
5150         link = idr_get_next(&link_idr, id);
5151         if (link) {
5152                 link = bpf_link_inc_not_zero(link);
5153                 if (IS_ERR(link)) {
5154                         (*id)++;
5155                         goto again;
5156                 }
5157         }
5158         spin_unlock_bh(&link_idr_lock);
5159
5160         return link;
5161 }
5162
5163 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
5164
5165 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
5166 {
5167         struct bpf_link *link;
5168         u32 id = attr->link_id;
5169         int fd;
5170
5171         if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
5172                 return -EINVAL;
5173
5174         if (!capable(CAP_SYS_ADMIN))
5175                 return -EPERM;
5176
5177         link = bpf_link_by_id(id);
5178         if (IS_ERR(link))
5179                 return PTR_ERR(link);
5180
5181         fd = bpf_link_new_fd(link);
5182         if (fd < 0)
5183                 bpf_link_put_direct(link);
5184
5185         return fd;
5186 }
5187
5188 DEFINE_MUTEX(bpf_stats_enabled_mutex);
5189
5190 static int bpf_stats_release(struct inode *inode, struct file *file)
5191 {
5192         mutex_lock(&bpf_stats_enabled_mutex);
5193         static_key_slow_dec(&bpf_stats_enabled_key.key);
5194         mutex_unlock(&bpf_stats_enabled_mutex);
5195         return 0;
5196 }
5197
5198 static const struct file_operations bpf_stats_fops = {
5199         .release = bpf_stats_release,
5200 };
5201
5202 static int bpf_enable_runtime_stats(void)
5203 {
5204         int fd;
5205
5206         mutex_lock(&bpf_stats_enabled_mutex);
5207
5208         /* Set a very high limit to avoid overflow */
5209         if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
5210                 mutex_unlock(&bpf_stats_enabled_mutex);
5211                 return -EBUSY;
5212         }
5213
5214         fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
5215         if (fd >= 0)
5216                 static_key_slow_inc(&bpf_stats_enabled_key.key);
5217
5218         mutex_unlock(&bpf_stats_enabled_mutex);
5219         return fd;
5220 }
5221
5222 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
5223
5224 static int bpf_enable_stats(union bpf_attr *attr)
5225 {
5226
5227         if (CHECK_ATTR(BPF_ENABLE_STATS))
5228                 return -EINVAL;
5229
5230         if (!capable(CAP_SYS_ADMIN))
5231                 return -EPERM;
5232
5233         switch (attr->enable_stats.type) {
5234         case BPF_STATS_RUN_TIME:
5235                 return bpf_enable_runtime_stats();
5236         default:
5237                 break;
5238         }
5239         return -EINVAL;
5240 }
5241
5242 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
5243
5244 static int bpf_iter_create(union bpf_attr *attr)
5245 {
5246         struct bpf_link *link;
5247         int err;
5248
5249         if (CHECK_ATTR(BPF_ITER_CREATE))
5250                 return -EINVAL;
5251
5252         if (attr->iter_create.flags)
5253                 return -EINVAL;
5254
5255         link = bpf_link_get_from_fd(attr->iter_create.link_fd);
5256         if (IS_ERR(link))
5257                 return PTR_ERR(link);
5258
5259         err = bpf_iter_new_fd(link);
5260         bpf_link_put_direct(link);
5261
5262         return err;
5263 }
5264
5265 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
5266
5267 static int bpf_prog_bind_map(union bpf_attr *attr)
5268 {
5269         struct bpf_prog *prog;
5270         struct bpf_map *map;
5271         struct bpf_map **used_maps_old, **used_maps_new;
5272         int i, ret = 0;
5273
5274         if (CHECK_ATTR(BPF_PROG_BIND_MAP))
5275                 return -EINVAL;
5276
5277         if (attr->prog_bind_map.flags)
5278                 return -EINVAL;
5279
5280         prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
5281         if (IS_ERR(prog))
5282                 return PTR_ERR(prog);
5283
5284         map = bpf_map_get(attr->prog_bind_map.map_fd);
5285         if (IS_ERR(map)) {
5286                 ret = PTR_ERR(map);
5287                 goto out_prog_put;
5288         }
5289
5290         mutex_lock(&prog->aux->used_maps_mutex);
5291
5292         used_maps_old = prog->aux->used_maps;
5293
5294         for (i = 0; i < prog->aux->used_map_cnt; i++)
5295                 if (used_maps_old[i] == map) {
5296                         bpf_map_put(map);
5297                         goto out_unlock;
5298                 }
5299
5300         used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
5301                                       sizeof(used_maps_new[0]),
5302                                       GFP_KERNEL);
5303         if (!used_maps_new) {
5304                 ret = -ENOMEM;
5305                 goto out_unlock;
5306         }
5307
5308         memcpy(used_maps_new, used_maps_old,
5309                sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
5310         used_maps_new[prog->aux->used_map_cnt] = map;
5311
5312         prog->aux->used_map_cnt++;
5313         prog->aux->used_maps = used_maps_new;
5314
5315         kfree(used_maps_old);
5316
5317 out_unlock:
5318         mutex_unlock(&prog->aux->used_maps_mutex);
5319
5320         if (ret)
5321                 bpf_map_put(map);
5322 out_prog_put:
5323         bpf_prog_put(prog);
5324         return ret;
5325 }
5326
5327 static int __sys_bpf(int cmd, bpfptr_t uattr, unsigned int size)
5328 {
5329         union bpf_attr attr;
5330         int err;
5331
5332         err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
5333         if (err)
5334                 return err;
5335         size = min_t(u32, size, sizeof(attr));
5336
5337         /* copy attributes from user space, may be less than sizeof(bpf_attr) */
5338         memset(&attr, 0, sizeof(attr));
5339         if (copy_from_bpfptr(&attr, uattr, size) != 0)
5340                 return -EFAULT;
5341
5342         err = security_bpf(cmd, &attr, size);
5343         if (err < 0)
5344                 return err;
5345
5346         switch (cmd) {
5347         case BPF_MAP_CREATE:
5348                 err = map_create(&attr);
5349                 break;
5350         case BPF_MAP_LOOKUP_ELEM:
5351                 err = map_lookup_elem(&attr);
5352                 break;
5353         case BPF_MAP_UPDATE_ELEM:
5354                 err = map_update_elem(&attr, uattr);
5355                 break;
5356         case BPF_MAP_DELETE_ELEM:
5357                 err = map_delete_elem(&attr, uattr);
5358                 break;
5359         case BPF_MAP_GET_NEXT_KEY:
5360                 err = map_get_next_key(&attr);
5361                 break;
5362         case BPF_MAP_FREEZE:
5363                 err = map_freeze(&attr);
5364                 break;
5365         case BPF_PROG_LOAD:
5366                 err = bpf_prog_load(&attr, uattr, size);
5367                 break;
5368         case BPF_OBJ_PIN:
5369                 err = bpf_obj_pin(&attr);
5370                 break;
5371         case BPF_OBJ_GET:
5372                 err = bpf_obj_get(&attr);
5373                 break;
5374         case BPF_PROG_ATTACH:
5375                 err = bpf_prog_attach(&attr);
5376                 break;
5377         case BPF_PROG_DETACH:
5378                 err = bpf_prog_detach(&attr);
5379                 break;
5380         case BPF_PROG_QUERY:
5381                 err = bpf_prog_query(&attr, uattr.user);
5382                 break;
5383         case BPF_PROG_TEST_RUN:
5384                 err = bpf_prog_test_run(&attr, uattr.user);
5385                 break;
5386         case BPF_PROG_GET_NEXT_ID:
5387                 err = bpf_obj_get_next_id(&attr, uattr.user,
5388                                           &prog_idr, &prog_idr_lock);
5389                 break;
5390         case BPF_MAP_GET_NEXT_ID:
5391                 err = bpf_obj_get_next_id(&attr, uattr.user,
5392                                           &map_idr, &map_idr_lock);
5393                 break;
5394         case BPF_BTF_GET_NEXT_ID:
5395                 err = bpf_obj_get_next_id(&attr, uattr.user,
5396                                           &btf_idr, &btf_idr_lock);
5397                 break;
5398         case BPF_PROG_GET_FD_BY_ID:
5399                 err = bpf_prog_get_fd_by_id(&attr);
5400                 break;
5401         case BPF_MAP_GET_FD_BY_ID:
5402                 err = bpf_map_get_fd_by_id(&attr);
5403                 break;
5404         case BPF_OBJ_GET_INFO_BY_FD:
5405                 err = bpf_obj_get_info_by_fd(&attr, uattr.user);
5406                 break;
5407         case BPF_RAW_TRACEPOINT_OPEN:
5408                 err = bpf_raw_tracepoint_open(&attr);
5409                 break;
5410         case BPF_BTF_LOAD:
5411                 err = bpf_btf_load(&attr, uattr, size);
5412                 break;
5413         case BPF_BTF_GET_FD_BY_ID:
5414                 err = bpf_btf_get_fd_by_id(&attr);
5415                 break;
5416         case BPF_TASK_FD_QUERY:
5417                 err = bpf_task_fd_query(&attr, uattr.user);
5418                 break;
5419         case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
5420                 err = map_lookup_and_delete_elem(&attr);
5421                 break;
5422         case BPF_MAP_LOOKUP_BATCH:
5423                 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_LOOKUP_BATCH);
5424                 break;
5425         case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
5426                 err = bpf_map_do_batch(&attr, uattr.user,
5427                                        BPF_MAP_LOOKUP_AND_DELETE_BATCH);
5428                 break;
5429         case BPF_MAP_UPDATE_BATCH:
5430                 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_UPDATE_BATCH);
5431                 break;
5432         case BPF_MAP_DELETE_BATCH:
5433                 err = bpf_map_do_batch(&attr, uattr.user, BPF_MAP_DELETE_BATCH);
5434                 break;
5435         case BPF_LINK_CREATE:
5436                 err = link_create(&attr, uattr);
5437                 break;
5438         case BPF_LINK_UPDATE:
5439                 err = link_update(&attr);
5440                 break;
5441         case BPF_LINK_GET_FD_BY_ID:
5442                 err = bpf_link_get_fd_by_id(&attr);
5443                 break;
5444         case BPF_LINK_GET_NEXT_ID:
5445                 err = bpf_obj_get_next_id(&attr, uattr.user,
5446                                           &link_idr, &link_idr_lock);
5447                 break;
5448         case BPF_ENABLE_STATS:
5449                 err = bpf_enable_stats(&attr);
5450                 break;
5451         case BPF_ITER_CREATE:
5452                 err = bpf_iter_create(&attr);
5453                 break;
5454         case BPF_LINK_DETACH:
5455                 err = link_detach(&attr);
5456                 break;
5457         case BPF_PROG_BIND_MAP:
5458                 err = bpf_prog_bind_map(&attr);
5459                 break;
5460         default:
5461                 err = -EINVAL;
5462                 break;
5463         }
5464
5465         return err;
5466 }
5467
5468 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
5469 {
5470         return __sys_bpf(cmd, USER_BPFPTR(uattr), size);
5471 }
5472
5473 static bool syscall_prog_is_valid_access(int off, int size,
5474                                          enum bpf_access_type type,
5475                                          const struct bpf_prog *prog,
5476                                          struct bpf_insn_access_aux *info)
5477 {
5478         if (off < 0 || off >= U16_MAX)
5479                 return false;
5480         if (off % size != 0)
5481                 return false;
5482         return true;
5483 }
5484
5485 BPF_CALL_3(bpf_sys_bpf, int, cmd, union bpf_attr *, attr, u32, attr_size)
5486 {
5487         switch (cmd) {
5488         case BPF_MAP_CREATE:
5489         case BPF_MAP_DELETE_ELEM:
5490         case BPF_MAP_UPDATE_ELEM:
5491         case BPF_MAP_FREEZE:
5492         case BPF_MAP_GET_FD_BY_ID:
5493         case BPF_PROG_LOAD:
5494         case BPF_BTF_LOAD:
5495         case BPF_LINK_CREATE:
5496         case BPF_RAW_TRACEPOINT_OPEN:
5497                 break;
5498         default:
5499                 return -EINVAL;
5500         }
5501         return __sys_bpf(cmd, KERNEL_BPFPTR(attr), attr_size);
5502 }
5503
5504
5505 /* To shut up -Wmissing-prototypes.
5506  * This function is used by the kernel light skeleton
5507  * to load bpf programs when modules are loaded or during kernel boot.
5508  * See tools/lib/bpf/skel_internal.h
5509  */
5510 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);
5511
5512 int kern_sys_bpf(int cmd, union bpf_attr *attr, unsigned int size)
5513 {
5514         struct bpf_prog * __maybe_unused prog;
5515         struct bpf_tramp_run_ctx __maybe_unused run_ctx;
5516
5517         switch (cmd) {
5518 #ifdef CONFIG_BPF_JIT /* __bpf_prog_enter_sleepable used by trampoline and JIT */
5519         case BPF_PROG_TEST_RUN:
5520                 if (attr->test.data_in || attr->test.data_out ||
5521                     attr->test.ctx_out || attr->test.duration ||
5522                     attr->test.repeat || attr->test.flags)
5523                         return -EINVAL;
5524
5525                 prog = bpf_prog_get_type(attr->test.prog_fd, BPF_PROG_TYPE_SYSCALL);
5526                 if (IS_ERR(prog))
5527                         return PTR_ERR(prog);
5528
5529                 if (attr->test.ctx_size_in < prog->aux->max_ctx_offset ||
5530                     attr->test.ctx_size_in > U16_MAX) {
5531                         bpf_prog_put(prog);
5532                         return -EINVAL;
5533                 }
5534
5535                 run_ctx.bpf_cookie = 0;
5536                 if (!__bpf_prog_enter_sleepable_recur(prog, &run_ctx)) {
5537                         /* recursion detected */
5538                         __bpf_prog_exit_sleepable_recur(prog, 0, &run_ctx);
5539                         bpf_prog_put(prog);
5540                         return -EBUSY;
5541                 }
5542                 attr->test.retval = bpf_prog_run(prog, (void *) (long) attr->test.ctx_in);
5543                 __bpf_prog_exit_sleepable_recur(prog, 0 /* bpf_prog_run does runtime stats */,
5544                                                 &run_ctx);
5545                 bpf_prog_put(prog);
5546                 return 0;
5547 #endif
5548         default:
5549                 return ____bpf_sys_bpf(cmd, attr, size);
5550         }
5551 }
5552 EXPORT_SYMBOL(kern_sys_bpf);
5553
5554 static const struct bpf_func_proto bpf_sys_bpf_proto = {
5555         .func           = bpf_sys_bpf,
5556         .gpl_only       = false,
5557         .ret_type       = RET_INTEGER,
5558         .arg1_type      = ARG_ANYTHING,
5559         .arg2_type      = ARG_PTR_TO_MEM | MEM_RDONLY,
5560         .arg3_type      = ARG_CONST_SIZE,
5561 };
5562
5563 const struct bpf_func_proto * __weak
5564 tracing_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5565 {
5566         return bpf_base_func_proto(func_id);
5567 }
5568
5569 BPF_CALL_1(bpf_sys_close, u32, fd)
5570 {
5571         /* When bpf program calls this helper there should not be
5572          * an fdget() without matching completed fdput().
5573          * This helper is allowed in the following callchain only:
5574          * sys_bpf->prog_test_run->bpf_prog->bpf_sys_close
5575          */
5576         return close_fd(fd);
5577 }
5578
5579 static const struct bpf_func_proto bpf_sys_close_proto = {
5580         .func           = bpf_sys_close,
5581         .gpl_only       = false,
5582         .ret_type       = RET_INTEGER,
5583         .arg1_type      = ARG_ANYTHING,
5584 };
5585
5586 BPF_CALL_4(bpf_kallsyms_lookup_name, const char *, name, int, name_sz, int, flags, u64 *, res)
5587 {
5588         if (flags)
5589                 return -EINVAL;
5590
5591         if (name_sz <= 1 || name[name_sz - 1])
5592                 return -EINVAL;
5593
5594         if (!bpf_dump_raw_ok(current_cred()))
5595                 return -EPERM;
5596
5597         *res = kallsyms_lookup_name(name);
5598         return *res ? 0 : -ENOENT;
5599 }
5600
5601 static const struct bpf_func_proto bpf_kallsyms_lookup_name_proto = {
5602         .func           = bpf_kallsyms_lookup_name,
5603         .gpl_only       = false,
5604         .ret_type       = RET_INTEGER,
5605         .arg1_type      = ARG_PTR_TO_MEM,
5606         .arg2_type      = ARG_CONST_SIZE_OR_ZERO,
5607         .arg3_type      = ARG_ANYTHING,
5608         .arg4_type      = ARG_PTR_TO_LONG,
5609 };
5610
5611 static const struct bpf_func_proto *
5612 syscall_prog_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
5613 {
5614         switch (func_id) {
5615         case BPF_FUNC_sys_bpf:
5616                 return !perfmon_capable() ? NULL : &bpf_sys_bpf_proto;
5617         case BPF_FUNC_btf_find_by_name_kind:
5618                 return &bpf_btf_find_by_name_kind_proto;
5619         case BPF_FUNC_sys_close:
5620                 return &bpf_sys_close_proto;
5621         case BPF_FUNC_kallsyms_lookup_name:
5622                 return &bpf_kallsyms_lookup_name_proto;
5623         default:
5624                 return tracing_prog_func_proto(func_id, prog);
5625         }
5626 }
5627
5628 const struct bpf_verifier_ops bpf_syscall_verifier_ops = {
5629         .get_func_proto  = syscall_prog_func_proto,
5630         .is_valid_access = syscall_prog_is_valid_access,
5631 };
5632
5633 const struct bpf_prog_ops bpf_syscall_prog_ops = {
5634         .test_run = bpf_prog_test_run_syscall,
5635 };
5636
5637 #ifdef CONFIG_SYSCTL
5638 static int bpf_stats_handler(struct ctl_table *table, int write,
5639                              void *buffer, size_t *lenp, loff_t *ppos)
5640 {
5641         struct static_key *key = (struct static_key *)table->data;
5642         static int saved_val;
5643         int val, ret;
5644         struct ctl_table tmp = {
5645                 .data   = &val,
5646                 .maxlen = sizeof(val),
5647                 .mode   = table->mode,
5648                 .extra1 = SYSCTL_ZERO,
5649                 .extra2 = SYSCTL_ONE,
5650         };
5651
5652         if (write && !capable(CAP_SYS_ADMIN))
5653                 return -EPERM;
5654
5655         mutex_lock(&bpf_stats_enabled_mutex);
5656         val = saved_val;
5657         ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5658         if (write && !ret && val != saved_val) {
5659                 if (val)
5660                         static_key_slow_inc(key);
5661                 else
5662                         static_key_slow_dec(key);
5663                 saved_val = val;
5664         }
5665         mutex_unlock(&bpf_stats_enabled_mutex);
5666         return ret;
5667 }
5668
5669 void __weak unpriv_ebpf_notify(int new_state)
5670 {
5671 }
5672
5673 static int bpf_unpriv_handler(struct ctl_table *table, int write,
5674                               void *buffer, size_t *lenp, loff_t *ppos)
5675 {
5676         int ret, unpriv_enable = *(int *)table->data;
5677         bool locked_state = unpriv_enable == 1;
5678         struct ctl_table tmp = *table;
5679
5680         if (write && !capable(CAP_SYS_ADMIN))
5681                 return -EPERM;
5682
5683         tmp.data = &unpriv_enable;
5684         ret = proc_dointvec_minmax(&tmp, write, buffer, lenp, ppos);
5685         if (write && !ret) {
5686                 if (locked_state && unpriv_enable != 1)
5687                         return -EPERM;
5688                 *(int *)table->data = unpriv_enable;
5689         }
5690
5691         if (write)
5692                 unpriv_ebpf_notify(unpriv_enable);
5693
5694         return ret;
5695 }
5696
5697 static struct ctl_table bpf_syscall_table[] = {
5698         {
5699                 .procname       = "unprivileged_bpf_disabled",
5700                 .data           = &sysctl_unprivileged_bpf_disabled,
5701                 .maxlen         = sizeof(sysctl_unprivileged_bpf_disabled),
5702                 .mode           = 0644,
5703                 .proc_handler   = bpf_unpriv_handler,
5704                 .extra1         = SYSCTL_ZERO,
5705                 .extra2         = SYSCTL_TWO,
5706         },
5707         {
5708                 .procname       = "bpf_stats_enabled",
5709                 .data           = &bpf_stats_enabled_key.key,
5710                 .mode           = 0644,
5711                 .proc_handler   = bpf_stats_handler,
5712         },
5713         { }
5714 };
5715
5716 static int __init bpf_syscall_sysctl_init(void)
5717 {
5718         register_sysctl_init("kernel", bpf_syscall_table);
5719         return 0;
5720 }
5721 late_initcall(bpf_syscall_sysctl_init);
5722 #endif /* CONFIG_SYSCTL */