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