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