bpf: Convert bpf_prog refcnt to atomic64_t
[sfrench/cifs-2.6.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/btf.h>
8 #include <linux/syscalls.h>
9 #include <linux/slab.h>
10 #include <linux/sched/signal.h>
11 #include <linux/vmalloc.h>
12 #include <linux/mmzone.h>
13 #include <linux/anon_inodes.h>
14 #include <linux/fdtable.h>
15 #include <linux/file.h>
16 #include <linux/fs.h>
17 #include <linux/license.h>
18 #include <linux/filter.h>
19 #include <linux/version.h>
20 #include <linux/kernel.h>
21 #include <linux/idr.h>
22 #include <linux/cred.h>
23 #include <linux/timekeeping.h>
24 #include <linux/ctype.h>
25 #include <linux/nospec.h>
26 #include <uapi/linux/btf.h>
27
28 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY || \
29                            (map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
30                            (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
31                            (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
32 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
33 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_HASH(map))
34
35 #define BPF_OBJ_FLAG_MASK   (BPF_F_RDONLY | BPF_F_WRONLY)
36
37 DEFINE_PER_CPU(int, bpf_prog_active);
38 static DEFINE_IDR(prog_idr);
39 static DEFINE_SPINLOCK(prog_idr_lock);
40 static DEFINE_IDR(map_idr);
41 static DEFINE_SPINLOCK(map_idr_lock);
42
43 int sysctl_unprivileged_bpf_disabled __read_mostly;
44
45 static const struct bpf_map_ops * const bpf_map_types[] = {
46 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
47 #define BPF_MAP_TYPE(_id, _ops) \
48         [_id] = &_ops,
49 #include <linux/bpf_types.h>
50 #undef BPF_PROG_TYPE
51 #undef BPF_MAP_TYPE
52 };
53
54 /*
55  * If we're handed a bigger struct than we know of, ensure all the unknown bits
56  * are 0 - i.e. new user-space does not rely on any kernel feature extensions
57  * we don't know about yet.
58  *
59  * There is a ToCToU between this function call and the following
60  * copy_from_user() call. However, this is not a concern since this function is
61  * meant to be a future-proofing of bits.
62  */
63 int bpf_check_uarg_tail_zero(void __user *uaddr,
64                              size_t expected_size,
65                              size_t actual_size)
66 {
67         unsigned char __user *addr;
68         unsigned char __user *end;
69         unsigned char val;
70         int err;
71
72         if (unlikely(actual_size > PAGE_SIZE))  /* silly large */
73                 return -E2BIG;
74
75         if (unlikely(!access_ok(uaddr, actual_size)))
76                 return -EFAULT;
77
78         if (actual_size <= expected_size)
79                 return 0;
80
81         addr = uaddr + expected_size;
82         end  = uaddr + actual_size;
83
84         for (; addr < end; addr++) {
85                 err = get_user(val, addr);
86                 if (err)
87                         return err;
88                 if (val)
89                         return -E2BIG;
90         }
91
92         return 0;
93 }
94
95 const struct bpf_map_ops bpf_map_offload_ops = {
96         .map_alloc = bpf_map_offload_map_alloc,
97         .map_free = bpf_map_offload_map_free,
98         .map_check_btf = map_check_no_btf,
99 };
100
101 static struct bpf_map *find_and_alloc_map(union bpf_attr *attr)
102 {
103         const struct bpf_map_ops *ops;
104         u32 type = attr->map_type;
105         struct bpf_map *map;
106         int err;
107
108         if (type >= ARRAY_SIZE(bpf_map_types))
109                 return ERR_PTR(-EINVAL);
110         type = array_index_nospec(type, ARRAY_SIZE(bpf_map_types));
111         ops = bpf_map_types[type];
112         if (!ops)
113                 return ERR_PTR(-EINVAL);
114
115         if (ops->map_alloc_check) {
116                 err = ops->map_alloc_check(attr);
117                 if (err)
118                         return ERR_PTR(err);
119         }
120         if (attr->map_ifindex)
121                 ops = &bpf_map_offload_ops;
122         map = ops->map_alloc(attr);
123         if (IS_ERR(map))
124                 return map;
125         map->ops = ops;
126         map->map_type = type;
127         return map;
128 }
129
130 void *bpf_map_area_alloc(size_t size, int numa_node)
131 {
132         /* We really just want to fail instead of triggering OOM killer
133          * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
134          * which is used for lower order allocation requests.
135          *
136          * It has been observed that higher order allocation requests done by
137          * vmalloc with __GFP_NORETRY being set might fail due to not trying
138          * to reclaim memory from the page cache, thus we set
139          * __GFP_RETRY_MAYFAIL to avoid such situations.
140          */
141
142         const gfp_t flags = __GFP_NOWARN | __GFP_ZERO;
143         void *area;
144
145         if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
146                 area = kmalloc_node(size, GFP_USER | __GFP_NORETRY | flags,
147                                     numa_node);
148                 if (area != NULL)
149                         return area;
150         }
151
152         return __vmalloc_node_flags_caller(size, numa_node,
153                                            GFP_KERNEL | __GFP_RETRY_MAYFAIL |
154                                            flags, __builtin_return_address(0));
155 }
156
157 void bpf_map_area_free(void *area)
158 {
159         kvfree(area);
160 }
161
162 static u32 bpf_map_flags_retain_permanent(u32 flags)
163 {
164         /* Some map creation flags are not tied to the map object but
165          * rather to the map fd instead, so they have no meaning upon
166          * map object inspection since multiple file descriptors with
167          * different (access) properties can exist here. Thus, given
168          * this has zero meaning for the map itself, lets clear these
169          * from here.
170          */
171         return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
172 }
173
174 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
175 {
176         map->map_type = attr->map_type;
177         map->key_size = attr->key_size;
178         map->value_size = attr->value_size;
179         map->max_entries = attr->max_entries;
180         map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
181         map->numa_node = bpf_map_attr_numa_node(attr);
182 }
183
184 static int bpf_charge_memlock(struct user_struct *user, u32 pages)
185 {
186         unsigned long memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
187
188         if (atomic_long_add_return(pages, &user->locked_vm) > memlock_limit) {
189                 atomic_long_sub(pages, &user->locked_vm);
190                 return -EPERM;
191         }
192         return 0;
193 }
194
195 static void bpf_uncharge_memlock(struct user_struct *user, u32 pages)
196 {
197         if (user)
198                 atomic_long_sub(pages, &user->locked_vm);
199 }
200
201 int bpf_map_charge_init(struct bpf_map_memory *mem, size_t size)
202 {
203         u32 pages = round_up(size, PAGE_SIZE) >> PAGE_SHIFT;
204         struct user_struct *user;
205         int ret;
206
207         if (size >= U32_MAX - PAGE_SIZE)
208                 return -E2BIG;
209
210         user = get_current_user();
211         ret = bpf_charge_memlock(user, pages);
212         if (ret) {
213                 free_uid(user);
214                 return ret;
215         }
216
217         mem->pages = pages;
218         mem->user = user;
219
220         return 0;
221 }
222
223 void bpf_map_charge_finish(struct bpf_map_memory *mem)
224 {
225         bpf_uncharge_memlock(mem->user, mem->pages);
226         free_uid(mem->user);
227 }
228
229 void bpf_map_charge_move(struct bpf_map_memory *dst,
230                          struct bpf_map_memory *src)
231 {
232         *dst = *src;
233
234         /* Make sure src will not be used for the redundant uncharging. */
235         memset(src, 0, sizeof(struct bpf_map_memory));
236 }
237
238 int bpf_map_charge_memlock(struct bpf_map *map, u32 pages)
239 {
240         int ret;
241
242         ret = bpf_charge_memlock(map->memory.user, pages);
243         if (ret)
244                 return ret;
245         map->memory.pages += pages;
246         return ret;
247 }
248
249 void bpf_map_uncharge_memlock(struct bpf_map *map, u32 pages)
250 {
251         bpf_uncharge_memlock(map->memory.user, pages);
252         map->memory.pages -= pages;
253 }
254
255 static int bpf_map_alloc_id(struct bpf_map *map)
256 {
257         int id;
258
259         idr_preload(GFP_KERNEL);
260         spin_lock_bh(&map_idr_lock);
261         id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
262         if (id > 0)
263                 map->id = id;
264         spin_unlock_bh(&map_idr_lock);
265         idr_preload_end();
266
267         if (WARN_ON_ONCE(!id))
268                 return -ENOSPC;
269
270         return id > 0 ? 0 : id;
271 }
272
273 void bpf_map_free_id(struct bpf_map *map, bool do_idr_lock)
274 {
275         unsigned long flags;
276
277         /* Offloaded maps are removed from the IDR store when their device
278          * disappears - even if someone holds an fd to them they are unusable,
279          * the memory is gone, all ops will fail; they are simply waiting for
280          * refcnt to drop to be freed.
281          */
282         if (!map->id)
283                 return;
284
285         if (do_idr_lock)
286                 spin_lock_irqsave(&map_idr_lock, flags);
287         else
288                 __acquire(&map_idr_lock);
289
290         idr_remove(&map_idr, map->id);
291         map->id = 0;
292
293         if (do_idr_lock)
294                 spin_unlock_irqrestore(&map_idr_lock, flags);
295         else
296                 __release(&map_idr_lock);
297 }
298
299 /* called from workqueue */
300 static void bpf_map_free_deferred(struct work_struct *work)
301 {
302         struct bpf_map *map = container_of(work, struct bpf_map, work);
303         struct bpf_map_memory mem;
304
305         bpf_map_charge_move(&mem, &map->memory);
306         security_bpf_map_free(map);
307         /* implementation dependent freeing */
308         map->ops->map_free(map);
309         bpf_map_charge_finish(&mem);
310 }
311
312 static void bpf_map_put_uref(struct bpf_map *map)
313 {
314         if (atomic64_dec_and_test(&map->usercnt)) {
315                 if (map->ops->map_release_uref)
316                         map->ops->map_release_uref(map);
317         }
318 }
319
320 /* decrement map refcnt and schedule it for freeing via workqueue
321  * (unrelying map implementation ops->map_free() might sleep)
322  */
323 static void __bpf_map_put(struct bpf_map *map, bool do_idr_lock)
324 {
325         if (atomic64_dec_and_test(&map->refcnt)) {
326                 /* bpf_map_free_id() must be called first */
327                 bpf_map_free_id(map, do_idr_lock);
328                 btf_put(map->btf);
329                 INIT_WORK(&map->work, bpf_map_free_deferred);
330                 schedule_work(&map->work);
331         }
332 }
333
334 void bpf_map_put(struct bpf_map *map)
335 {
336         __bpf_map_put(map, true);
337 }
338 EXPORT_SYMBOL_GPL(bpf_map_put);
339
340 void bpf_map_put_with_uref(struct bpf_map *map)
341 {
342         bpf_map_put_uref(map);
343         bpf_map_put(map);
344 }
345
346 static int bpf_map_release(struct inode *inode, struct file *filp)
347 {
348         struct bpf_map *map = filp->private_data;
349
350         if (map->ops->map_release)
351                 map->ops->map_release(map, filp);
352
353         bpf_map_put_with_uref(map);
354         return 0;
355 }
356
357 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
358 {
359         fmode_t mode = f.file->f_mode;
360
361         /* Our file permissions may have been overridden by global
362          * map permissions facing syscall side.
363          */
364         if (READ_ONCE(map->frozen))
365                 mode &= ~FMODE_CAN_WRITE;
366         return mode;
367 }
368
369 #ifdef CONFIG_PROC_FS
370 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
371 {
372         const struct bpf_map *map = filp->private_data;
373         const struct bpf_array *array;
374         u32 owner_prog_type = 0;
375         u32 owner_jited = 0;
376
377         if (map->map_type == BPF_MAP_TYPE_PROG_ARRAY) {
378                 array = container_of(map, struct bpf_array, map);
379                 owner_prog_type = array->owner_prog_type;
380                 owner_jited = array->owner_jited;
381         }
382
383         seq_printf(m,
384                    "map_type:\t%u\n"
385                    "key_size:\t%u\n"
386                    "value_size:\t%u\n"
387                    "max_entries:\t%u\n"
388                    "map_flags:\t%#x\n"
389                    "memlock:\t%llu\n"
390                    "map_id:\t%u\n"
391                    "frozen:\t%u\n",
392                    map->map_type,
393                    map->key_size,
394                    map->value_size,
395                    map->max_entries,
396                    map->map_flags,
397                    map->memory.pages * 1ULL << PAGE_SHIFT,
398                    map->id,
399                    READ_ONCE(map->frozen));
400
401         if (owner_prog_type) {
402                 seq_printf(m, "owner_prog_type:\t%u\n",
403                            owner_prog_type);
404                 seq_printf(m, "owner_jited:\t%u\n",
405                            owner_jited);
406         }
407 }
408 #endif
409
410 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
411                               loff_t *ppos)
412 {
413         /* We need this handler such that alloc_file() enables
414          * f_mode with FMODE_CAN_READ.
415          */
416         return -EINVAL;
417 }
418
419 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
420                                size_t siz, loff_t *ppos)
421 {
422         /* We need this handler such that alloc_file() enables
423          * f_mode with FMODE_CAN_WRITE.
424          */
425         return -EINVAL;
426 }
427
428 const struct file_operations bpf_map_fops = {
429 #ifdef CONFIG_PROC_FS
430         .show_fdinfo    = bpf_map_show_fdinfo,
431 #endif
432         .release        = bpf_map_release,
433         .read           = bpf_dummy_read,
434         .write          = bpf_dummy_write,
435 };
436
437 int bpf_map_new_fd(struct bpf_map *map, int flags)
438 {
439         int ret;
440
441         ret = security_bpf_map(map, OPEN_FMODE(flags));
442         if (ret < 0)
443                 return ret;
444
445         return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
446                                 flags | O_CLOEXEC);
447 }
448
449 int bpf_get_file_flag(int flags)
450 {
451         if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
452                 return -EINVAL;
453         if (flags & BPF_F_RDONLY)
454                 return O_RDONLY;
455         if (flags & BPF_F_WRONLY)
456                 return O_WRONLY;
457         return O_RDWR;
458 }
459
460 /* helper macro to check that unused fields 'union bpf_attr' are zero */
461 #define CHECK_ATTR(CMD) \
462         memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
463                    sizeof(attr->CMD##_LAST_FIELD), 0, \
464                    sizeof(*attr) - \
465                    offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
466                    sizeof(attr->CMD##_LAST_FIELD)) != NULL
467
468 /* dst and src must have at least BPF_OBJ_NAME_LEN number of bytes.
469  * Return 0 on success and < 0 on error.
470  */
471 static int bpf_obj_name_cpy(char *dst, const char *src)
472 {
473         const char *end = src + BPF_OBJ_NAME_LEN;
474
475         memset(dst, 0, BPF_OBJ_NAME_LEN);
476         /* Copy all isalnum(), '_' and '.' chars. */
477         while (src < end && *src) {
478                 if (!isalnum(*src) &&
479                     *src != '_' && *src != '.')
480                         return -EINVAL;
481                 *dst++ = *src++;
482         }
483
484         /* No '\0' found in BPF_OBJ_NAME_LEN number of bytes */
485         if (src == end)
486                 return -EINVAL;
487
488         return 0;
489 }
490
491 int map_check_no_btf(const struct bpf_map *map,
492                      const struct btf *btf,
493                      const struct btf_type *key_type,
494                      const struct btf_type *value_type)
495 {
496         return -ENOTSUPP;
497 }
498
499 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
500                          u32 btf_key_id, u32 btf_value_id)
501 {
502         const struct btf_type *key_type, *value_type;
503         u32 key_size, value_size;
504         int ret = 0;
505
506         /* Some maps allow key to be unspecified. */
507         if (btf_key_id) {
508                 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
509                 if (!key_type || key_size != map->key_size)
510                         return -EINVAL;
511         } else {
512                 key_type = btf_type_by_id(btf, 0);
513                 if (!map->ops->map_check_btf)
514                         return -EINVAL;
515         }
516
517         value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
518         if (!value_type || value_size != map->value_size)
519                 return -EINVAL;
520
521         map->spin_lock_off = btf_find_spin_lock(btf, value_type);
522
523         if (map_value_has_spin_lock(map)) {
524                 if (map->map_flags & BPF_F_RDONLY_PROG)
525                         return -EACCES;
526                 if (map->map_type != BPF_MAP_TYPE_HASH &&
527                     map->map_type != BPF_MAP_TYPE_ARRAY &&
528                     map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
529                     map->map_type != BPF_MAP_TYPE_SK_STORAGE)
530                         return -ENOTSUPP;
531                 if (map->spin_lock_off + sizeof(struct bpf_spin_lock) >
532                     map->value_size) {
533                         WARN_ONCE(1,
534                                   "verifier bug spin_lock_off %d value_size %d\n",
535                                   map->spin_lock_off, map->value_size);
536                         return -EFAULT;
537                 }
538         }
539
540         if (map->ops->map_check_btf)
541                 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
542
543         return ret;
544 }
545
546 #define BPF_MAP_CREATE_LAST_FIELD btf_value_type_id
547 /* called via syscall */
548 static int map_create(union bpf_attr *attr)
549 {
550         int numa_node = bpf_map_attr_numa_node(attr);
551         struct bpf_map_memory mem;
552         struct bpf_map *map;
553         int f_flags;
554         int err;
555
556         err = CHECK_ATTR(BPF_MAP_CREATE);
557         if (err)
558                 return -EINVAL;
559
560         f_flags = bpf_get_file_flag(attr->map_flags);
561         if (f_flags < 0)
562                 return f_flags;
563
564         if (numa_node != NUMA_NO_NODE &&
565             ((unsigned int)numa_node >= nr_node_ids ||
566              !node_online(numa_node)))
567                 return -EINVAL;
568
569         /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
570         map = find_and_alloc_map(attr);
571         if (IS_ERR(map))
572                 return PTR_ERR(map);
573
574         err = bpf_obj_name_cpy(map->name, attr->map_name);
575         if (err)
576                 goto free_map;
577
578         atomic64_set(&map->refcnt, 1);
579         atomic64_set(&map->usercnt, 1);
580
581         if (attr->btf_key_type_id || attr->btf_value_type_id) {
582                 struct btf *btf;
583
584                 if (!attr->btf_value_type_id) {
585                         err = -EINVAL;
586                         goto free_map;
587                 }
588
589                 btf = btf_get_by_fd(attr->btf_fd);
590                 if (IS_ERR(btf)) {
591                         err = PTR_ERR(btf);
592                         goto free_map;
593                 }
594
595                 err = map_check_btf(map, btf, attr->btf_key_type_id,
596                                     attr->btf_value_type_id);
597                 if (err) {
598                         btf_put(btf);
599                         goto free_map;
600                 }
601
602                 map->btf = btf;
603                 map->btf_key_type_id = attr->btf_key_type_id;
604                 map->btf_value_type_id = attr->btf_value_type_id;
605         } else {
606                 map->spin_lock_off = -EINVAL;
607         }
608
609         err = security_bpf_map_alloc(map);
610         if (err)
611                 goto free_map;
612
613         err = bpf_map_alloc_id(map);
614         if (err)
615                 goto free_map_sec;
616
617         err = bpf_map_new_fd(map, f_flags);
618         if (err < 0) {
619                 /* failed to allocate fd.
620                  * bpf_map_put_with_uref() is needed because the above
621                  * bpf_map_alloc_id() has published the map
622                  * to the userspace and the userspace may
623                  * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
624                  */
625                 bpf_map_put_with_uref(map);
626                 return err;
627         }
628
629         return err;
630
631 free_map_sec:
632         security_bpf_map_free(map);
633 free_map:
634         btf_put(map->btf);
635         bpf_map_charge_move(&mem, &map->memory);
636         map->ops->map_free(map);
637         bpf_map_charge_finish(&mem);
638         return err;
639 }
640
641 /* if error is returned, fd is released.
642  * On success caller should complete fd access with matching fdput()
643  */
644 struct bpf_map *__bpf_map_get(struct fd f)
645 {
646         if (!f.file)
647                 return ERR_PTR(-EBADF);
648         if (f.file->f_op != &bpf_map_fops) {
649                 fdput(f);
650                 return ERR_PTR(-EINVAL);
651         }
652
653         return f.file->private_data;
654 }
655
656 void bpf_map_inc(struct bpf_map *map)
657 {
658         atomic64_inc(&map->refcnt);
659 }
660 EXPORT_SYMBOL_GPL(bpf_map_inc);
661
662 void bpf_map_inc_with_uref(struct bpf_map *map)
663 {
664         atomic64_inc(&map->refcnt);
665         atomic64_inc(&map->usercnt);
666 }
667 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
668
669 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
670 {
671         struct fd f = fdget(ufd);
672         struct bpf_map *map;
673
674         map = __bpf_map_get(f);
675         if (IS_ERR(map))
676                 return map;
677
678         bpf_map_inc_with_uref(map);
679         fdput(f);
680
681         return map;
682 }
683
684 /* map_idr_lock should have been held */
685 static struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
686 {
687         int refold;
688
689         refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
690         if (!refold)
691                 return ERR_PTR(-ENOENT);
692         if (uref)
693                 atomic64_inc(&map->usercnt);
694
695         return map;
696 }
697
698 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
699 {
700         spin_lock_bh(&map_idr_lock);
701         map = __bpf_map_inc_not_zero(map, false);
702         spin_unlock_bh(&map_idr_lock);
703
704         return map;
705 }
706 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
707
708 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
709 {
710         return -ENOTSUPP;
711 }
712
713 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
714 {
715         if (key_size)
716                 return memdup_user(ukey, key_size);
717
718         if (ukey)
719                 return ERR_PTR(-EINVAL);
720
721         return NULL;
722 }
723
724 /* last field in 'union bpf_attr' used by this command */
725 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
726
727 static int map_lookup_elem(union bpf_attr *attr)
728 {
729         void __user *ukey = u64_to_user_ptr(attr->key);
730         void __user *uvalue = u64_to_user_ptr(attr->value);
731         int ufd = attr->map_fd;
732         struct bpf_map *map;
733         void *key, *value, *ptr;
734         u32 value_size;
735         struct fd f;
736         int err;
737
738         if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
739                 return -EINVAL;
740
741         if (attr->flags & ~BPF_F_LOCK)
742                 return -EINVAL;
743
744         f = fdget(ufd);
745         map = __bpf_map_get(f);
746         if (IS_ERR(map))
747                 return PTR_ERR(map);
748         if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
749                 err = -EPERM;
750                 goto err_put;
751         }
752
753         if ((attr->flags & BPF_F_LOCK) &&
754             !map_value_has_spin_lock(map)) {
755                 err = -EINVAL;
756                 goto err_put;
757         }
758
759         key = __bpf_copy_key(ukey, map->key_size);
760         if (IS_ERR(key)) {
761                 err = PTR_ERR(key);
762                 goto err_put;
763         }
764
765         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
766             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
767             map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
768             map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
769                 value_size = round_up(map->value_size, 8) * num_possible_cpus();
770         else if (IS_FD_MAP(map))
771                 value_size = sizeof(u32);
772         else
773                 value_size = map->value_size;
774
775         err = -ENOMEM;
776         value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
777         if (!value)
778                 goto free_key;
779
780         if (bpf_map_is_dev_bound(map)) {
781                 err = bpf_map_offload_lookup_elem(map, key, value);
782                 goto done;
783         }
784
785         preempt_disable();
786         this_cpu_inc(bpf_prog_active);
787         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
788             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
789                 err = bpf_percpu_hash_copy(map, key, value);
790         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
791                 err = bpf_percpu_array_copy(map, key, value);
792         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
793                 err = bpf_percpu_cgroup_storage_copy(map, key, value);
794         } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
795                 err = bpf_stackmap_copy(map, key, value);
796         } else if (IS_FD_ARRAY(map)) {
797                 err = bpf_fd_array_map_lookup_elem(map, key, value);
798         } else if (IS_FD_HASH(map)) {
799                 err = bpf_fd_htab_map_lookup_elem(map, key, value);
800         } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
801                 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
802         } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
803                    map->map_type == BPF_MAP_TYPE_STACK) {
804                 err = map->ops->map_peek_elem(map, value);
805         } else {
806                 rcu_read_lock();
807                 if (map->ops->map_lookup_elem_sys_only)
808                         ptr = map->ops->map_lookup_elem_sys_only(map, key);
809                 else
810                         ptr = map->ops->map_lookup_elem(map, key);
811                 if (IS_ERR(ptr)) {
812                         err = PTR_ERR(ptr);
813                 } else if (!ptr) {
814                         err = -ENOENT;
815                 } else {
816                         err = 0;
817                         if (attr->flags & BPF_F_LOCK)
818                                 /* lock 'ptr' and copy everything but lock */
819                                 copy_map_value_locked(map, value, ptr, true);
820                         else
821                                 copy_map_value(map, value, ptr);
822                         /* mask lock, since value wasn't zero inited */
823                         check_and_init_map_lock(map, value);
824                 }
825                 rcu_read_unlock();
826         }
827         this_cpu_dec(bpf_prog_active);
828         preempt_enable();
829
830 done:
831         if (err)
832                 goto free_value;
833
834         err = -EFAULT;
835         if (copy_to_user(uvalue, value, value_size) != 0)
836                 goto free_value;
837
838         err = 0;
839
840 free_value:
841         kfree(value);
842 free_key:
843         kfree(key);
844 err_put:
845         fdput(f);
846         return err;
847 }
848
849 static void maybe_wait_bpf_programs(struct bpf_map *map)
850 {
851         /* Wait for any running BPF programs to complete so that
852          * userspace, when we return to it, knows that all programs
853          * that could be running use the new map value.
854          */
855         if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
856             map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
857                 synchronize_rcu();
858 }
859
860 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
861
862 static int map_update_elem(union bpf_attr *attr)
863 {
864         void __user *ukey = u64_to_user_ptr(attr->key);
865         void __user *uvalue = u64_to_user_ptr(attr->value);
866         int ufd = attr->map_fd;
867         struct bpf_map *map;
868         void *key, *value;
869         u32 value_size;
870         struct fd f;
871         int err;
872
873         if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
874                 return -EINVAL;
875
876         f = fdget(ufd);
877         map = __bpf_map_get(f);
878         if (IS_ERR(map))
879                 return PTR_ERR(map);
880         if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
881                 err = -EPERM;
882                 goto err_put;
883         }
884
885         if ((attr->flags & BPF_F_LOCK) &&
886             !map_value_has_spin_lock(map)) {
887                 err = -EINVAL;
888                 goto err_put;
889         }
890
891         key = __bpf_copy_key(ukey, map->key_size);
892         if (IS_ERR(key)) {
893                 err = PTR_ERR(key);
894                 goto err_put;
895         }
896
897         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
898             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
899             map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
900             map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
901                 value_size = round_up(map->value_size, 8) * num_possible_cpus();
902         else
903                 value_size = map->value_size;
904
905         err = -ENOMEM;
906         value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
907         if (!value)
908                 goto free_key;
909
910         err = -EFAULT;
911         if (copy_from_user(value, uvalue, value_size) != 0)
912                 goto free_value;
913
914         /* Need to create a kthread, thus must support schedule */
915         if (bpf_map_is_dev_bound(map)) {
916                 err = bpf_map_offload_update_elem(map, key, value, attr->flags);
917                 goto out;
918         } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
919                    map->map_type == BPF_MAP_TYPE_SOCKHASH ||
920                    map->map_type == BPF_MAP_TYPE_SOCKMAP) {
921                 err = map->ops->map_update_elem(map, key, value, attr->flags);
922                 goto out;
923         }
924
925         /* must increment bpf_prog_active to avoid kprobe+bpf triggering from
926          * inside bpf map update or delete otherwise deadlocks are possible
927          */
928         preempt_disable();
929         __this_cpu_inc(bpf_prog_active);
930         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
931             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
932                 err = bpf_percpu_hash_update(map, key, value, attr->flags);
933         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
934                 err = bpf_percpu_array_update(map, key, value, attr->flags);
935         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
936                 err = bpf_percpu_cgroup_storage_update(map, key, value,
937                                                        attr->flags);
938         } else if (IS_FD_ARRAY(map)) {
939                 rcu_read_lock();
940                 err = bpf_fd_array_map_update_elem(map, f.file, key, value,
941                                                    attr->flags);
942                 rcu_read_unlock();
943         } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
944                 rcu_read_lock();
945                 err = bpf_fd_htab_map_update_elem(map, f.file, key, value,
946                                                   attr->flags);
947                 rcu_read_unlock();
948         } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
949                 /* rcu_read_lock() is not needed */
950                 err = bpf_fd_reuseport_array_update_elem(map, key, value,
951                                                          attr->flags);
952         } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
953                    map->map_type == BPF_MAP_TYPE_STACK) {
954                 err = map->ops->map_push_elem(map, value, attr->flags);
955         } else {
956                 rcu_read_lock();
957                 err = map->ops->map_update_elem(map, key, value, attr->flags);
958                 rcu_read_unlock();
959         }
960         __this_cpu_dec(bpf_prog_active);
961         preempt_enable();
962         maybe_wait_bpf_programs(map);
963 out:
964 free_value:
965         kfree(value);
966 free_key:
967         kfree(key);
968 err_put:
969         fdput(f);
970         return err;
971 }
972
973 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
974
975 static int map_delete_elem(union bpf_attr *attr)
976 {
977         void __user *ukey = u64_to_user_ptr(attr->key);
978         int ufd = attr->map_fd;
979         struct bpf_map *map;
980         struct fd f;
981         void *key;
982         int err;
983
984         if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
985                 return -EINVAL;
986
987         f = fdget(ufd);
988         map = __bpf_map_get(f);
989         if (IS_ERR(map))
990                 return PTR_ERR(map);
991         if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
992                 err = -EPERM;
993                 goto err_put;
994         }
995
996         key = __bpf_copy_key(ukey, map->key_size);
997         if (IS_ERR(key)) {
998                 err = PTR_ERR(key);
999                 goto err_put;
1000         }
1001
1002         if (bpf_map_is_dev_bound(map)) {
1003                 err = bpf_map_offload_delete_elem(map, key);
1004                 goto out;
1005         }
1006
1007         preempt_disable();
1008         __this_cpu_inc(bpf_prog_active);
1009         rcu_read_lock();
1010         err = map->ops->map_delete_elem(map, key);
1011         rcu_read_unlock();
1012         __this_cpu_dec(bpf_prog_active);
1013         preempt_enable();
1014         maybe_wait_bpf_programs(map);
1015 out:
1016         kfree(key);
1017 err_put:
1018         fdput(f);
1019         return err;
1020 }
1021
1022 /* last field in 'union bpf_attr' used by this command */
1023 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1024
1025 static int map_get_next_key(union bpf_attr *attr)
1026 {
1027         void __user *ukey = u64_to_user_ptr(attr->key);
1028         void __user *unext_key = u64_to_user_ptr(attr->next_key);
1029         int ufd = attr->map_fd;
1030         struct bpf_map *map;
1031         void *key, *next_key;
1032         struct fd f;
1033         int err;
1034
1035         if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1036                 return -EINVAL;
1037
1038         f = fdget(ufd);
1039         map = __bpf_map_get(f);
1040         if (IS_ERR(map))
1041                 return PTR_ERR(map);
1042         if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1043                 err = -EPERM;
1044                 goto err_put;
1045         }
1046
1047         if (ukey) {
1048                 key = __bpf_copy_key(ukey, map->key_size);
1049                 if (IS_ERR(key)) {
1050                         err = PTR_ERR(key);
1051                         goto err_put;
1052                 }
1053         } else {
1054                 key = NULL;
1055         }
1056
1057         err = -ENOMEM;
1058         next_key = kmalloc(map->key_size, GFP_USER);
1059         if (!next_key)
1060                 goto free_key;
1061
1062         if (bpf_map_is_dev_bound(map)) {
1063                 err = bpf_map_offload_get_next_key(map, key, next_key);
1064                 goto out;
1065         }
1066
1067         rcu_read_lock();
1068         err = map->ops->map_get_next_key(map, key, next_key);
1069         rcu_read_unlock();
1070 out:
1071         if (err)
1072                 goto free_next_key;
1073
1074         err = -EFAULT;
1075         if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1076                 goto free_next_key;
1077
1078         err = 0;
1079
1080 free_next_key:
1081         kfree(next_key);
1082 free_key:
1083         kfree(key);
1084 err_put:
1085         fdput(f);
1086         return err;
1087 }
1088
1089 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD value
1090
1091 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1092 {
1093         void __user *ukey = u64_to_user_ptr(attr->key);
1094         void __user *uvalue = u64_to_user_ptr(attr->value);
1095         int ufd = attr->map_fd;
1096         struct bpf_map *map;
1097         void *key, *value;
1098         u32 value_size;
1099         struct fd f;
1100         int err;
1101
1102         if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1103                 return -EINVAL;
1104
1105         f = fdget(ufd);
1106         map = __bpf_map_get(f);
1107         if (IS_ERR(map))
1108                 return PTR_ERR(map);
1109         if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1110                 err = -EPERM;
1111                 goto err_put;
1112         }
1113
1114         key = __bpf_copy_key(ukey, map->key_size);
1115         if (IS_ERR(key)) {
1116                 err = PTR_ERR(key);
1117                 goto err_put;
1118         }
1119
1120         value_size = map->value_size;
1121
1122         err = -ENOMEM;
1123         value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
1124         if (!value)
1125                 goto free_key;
1126
1127         if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1128             map->map_type == BPF_MAP_TYPE_STACK) {
1129                 err = map->ops->map_pop_elem(map, value);
1130         } else {
1131                 err = -ENOTSUPP;
1132         }
1133
1134         if (err)
1135                 goto free_value;
1136
1137         if (copy_to_user(uvalue, value, value_size) != 0)
1138                 goto free_value;
1139
1140         err = 0;
1141
1142 free_value:
1143         kfree(value);
1144 free_key:
1145         kfree(key);
1146 err_put:
1147         fdput(f);
1148         return err;
1149 }
1150
1151 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1152
1153 static int map_freeze(const union bpf_attr *attr)
1154 {
1155         int err = 0, ufd = attr->map_fd;
1156         struct bpf_map *map;
1157         struct fd f;
1158
1159         if (CHECK_ATTR(BPF_MAP_FREEZE))
1160                 return -EINVAL;
1161
1162         f = fdget(ufd);
1163         map = __bpf_map_get(f);
1164         if (IS_ERR(map))
1165                 return PTR_ERR(map);
1166         if (READ_ONCE(map->frozen)) {
1167                 err = -EBUSY;
1168                 goto err_put;
1169         }
1170         if (!capable(CAP_SYS_ADMIN)) {
1171                 err = -EPERM;
1172                 goto err_put;
1173         }
1174
1175         WRITE_ONCE(map->frozen, true);
1176 err_put:
1177         fdput(f);
1178         return err;
1179 }
1180
1181 static const struct bpf_prog_ops * const bpf_prog_types[] = {
1182 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
1183         [_id] = & _name ## _prog_ops,
1184 #define BPF_MAP_TYPE(_id, _ops)
1185 #include <linux/bpf_types.h>
1186 #undef BPF_PROG_TYPE
1187 #undef BPF_MAP_TYPE
1188 };
1189
1190 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
1191 {
1192         const struct bpf_prog_ops *ops;
1193
1194         if (type >= ARRAY_SIZE(bpf_prog_types))
1195                 return -EINVAL;
1196         type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
1197         ops = bpf_prog_types[type];
1198         if (!ops)
1199                 return -EINVAL;
1200
1201         if (!bpf_prog_is_dev_bound(prog->aux))
1202                 prog->aux->ops = ops;
1203         else
1204                 prog->aux->ops = &bpf_offload_prog_ops;
1205         prog->type = type;
1206         return 0;
1207 }
1208
1209 /* drop refcnt on maps used by eBPF program and free auxilary data */
1210 static void free_used_maps(struct bpf_prog_aux *aux)
1211 {
1212         enum bpf_cgroup_storage_type stype;
1213         int i;
1214
1215         for_each_cgroup_storage_type(stype) {
1216                 if (!aux->cgroup_storage[stype])
1217                         continue;
1218                 bpf_cgroup_storage_release(aux->prog,
1219                                            aux->cgroup_storage[stype]);
1220         }
1221
1222         for (i = 0; i < aux->used_map_cnt; i++)
1223                 bpf_map_put(aux->used_maps[i]);
1224
1225         kfree(aux->used_maps);
1226 }
1227
1228 int __bpf_prog_charge(struct user_struct *user, u32 pages)
1229 {
1230         unsigned long memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1231         unsigned long user_bufs;
1232
1233         if (user) {
1234                 user_bufs = atomic_long_add_return(pages, &user->locked_vm);
1235                 if (user_bufs > memlock_limit) {
1236                         atomic_long_sub(pages, &user->locked_vm);
1237                         return -EPERM;
1238                 }
1239         }
1240
1241         return 0;
1242 }
1243
1244 void __bpf_prog_uncharge(struct user_struct *user, u32 pages)
1245 {
1246         if (user)
1247                 atomic_long_sub(pages, &user->locked_vm);
1248 }
1249
1250 static int bpf_prog_charge_memlock(struct bpf_prog *prog)
1251 {
1252         struct user_struct *user = get_current_user();
1253         int ret;
1254
1255         ret = __bpf_prog_charge(user, prog->pages);
1256         if (ret) {
1257                 free_uid(user);
1258                 return ret;
1259         }
1260
1261         prog->aux->user = user;
1262         return 0;
1263 }
1264
1265 static void bpf_prog_uncharge_memlock(struct bpf_prog *prog)
1266 {
1267         struct user_struct *user = prog->aux->user;
1268
1269         __bpf_prog_uncharge(user, prog->pages);
1270         free_uid(user);
1271 }
1272
1273 static int bpf_prog_alloc_id(struct bpf_prog *prog)
1274 {
1275         int id;
1276
1277         idr_preload(GFP_KERNEL);
1278         spin_lock_bh(&prog_idr_lock);
1279         id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
1280         if (id > 0)
1281                 prog->aux->id = id;
1282         spin_unlock_bh(&prog_idr_lock);
1283         idr_preload_end();
1284
1285         /* id is in [1, INT_MAX) */
1286         if (WARN_ON_ONCE(!id))
1287                 return -ENOSPC;
1288
1289         return id > 0 ? 0 : id;
1290 }
1291
1292 void bpf_prog_free_id(struct bpf_prog *prog, bool do_idr_lock)
1293 {
1294         /* cBPF to eBPF migrations are currently not in the idr store.
1295          * Offloaded programs are removed from the store when their device
1296          * disappears - even if someone grabs an fd to them they are unusable,
1297          * simply waiting for refcnt to drop to be freed.
1298          */
1299         if (!prog->aux->id)
1300                 return;
1301
1302         if (do_idr_lock)
1303                 spin_lock_bh(&prog_idr_lock);
1304         else
1305                 __acquire(&prog_idr_lock);
1306
1307         idr_remove(&prog_idr, prog->aux->id);
1308         prog->aux->id = 0;
1309
1310         if (do_idr_lock)
1311                 spin_unlock_bh(&prog_idr_lock);
1312         else
1313                 __release(&prog_idr_lock);
1314 }
1315
1316 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
1317 {
1318         struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
1319
1320         kvfree(aux->func_info);
1321         kfree(aux->func_info_aux);
1322         free_used_maps(aux);
1323         bpf_prog_uncharge_memlock(aux->prog);
1324         security_bpf_prog_free(aux);
1325         bpf_prog_free(aux->prog);
1326 }
1327
1328 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
1329 {
1330         bpf_prog_kallsyms_del_all(prog);
1331         btf_put(prog->aux->btf);
1332         bpf_prog_free_linfo(prog);
1333
1334         if (deferred)
1335                 call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
1336         else
1337                 __bpf_prog_put_rcu(&prog->aux->rcu);
1338 }
1339
1340 static void __bpf_prog_put(struct bpf_prog *prog, bool do_idr_lock)
1341 {
1342         if (atomic64_dec_and_test(&prog->aux->refcnt)) {
1343                 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
1344                 /* bpf_prog_free_id() must be called first */
1345                 bpf_prog_free_id(prog, do_idr_lock);
1346                 __bpf_prog_put_noref(prog, true);
1347         }
1348 }
1349
1350 void bpf_prog_put(struct bpf_prog *prog)
1351 {
1352         __bpf_prog_put(prog, true);
1353 }
1354 EXPORT_SYMBOL_GPL(bpf_prog_put);
1355
1356 static int bpf_prog_release(struct inode *inode, struct file *filp)
1357 {
1358         struct bpf_prog *prog = filp->private_data;
1359
1360         bpf_prog_put(prog);
1361         return 0;
1362 }
1363
1364 static void bpf_prog_get_stats(const struct bpf_prog *prog,
1365                                struct bpf_prog_stats *stats)
1366 {
1367         u64 nsecs = 0, cnt = 0;
1368         int cpu;
1369
1370         for_each_possible_cpu(cpu) {
1371                 const struct bpf_prog_stats *st;
1372                 unsigned int start;
1373                 u64 tnsecs, tcnt;
1374
1375                 st = per_cpu_ptr(prog->aux->stats, cpu);
1376                 do {
1377                         start = u64_stats_fetch_begin_irq(&st->syncp);
1378                         tnsecs = st->nsecs;
1379                         tcnt = st->cnt;
1380                 } while (u64_stats_fetch_retry_irq(&st->syncp, start));
1381                 nsecs += tnsecs;
1382                 cnt += tcnt;
1383         }
1384         stats->nsecs = nsecs;
1385         stats->cnt = cnt;
1386 }
1387
1388 #ifdef CONFIG_PROC_FS
1389 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
1390 {
1391         const struct bpf_prog *prog = filp->private_data;
1392         char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
1393         struct bpf_prog_stats stats;
1394
1395         bpf_prog_get_stats(prog, &stats);
1396         bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
1397         seq_printf(m,
1398                    "prog_type:\t%u\n"
1399                    "prog_jited:\t%u\n"
1400                    "prog_tag:\t%s\n"
1401                    "memlock:\t%llu\n"
1402                    "prog_id:\t%u\n"
1403                    "run_time_ns:\t%llu\n"
1404                    "run_cnt:\t%llu\n",
1405                    prog->type,
1406                    prog->jited,
1407                    prog_tag,
1408                    prog->pages * 1ULL << PAGE_SHIFT,
1409                    prog->aux->id,
1410                    stats.nsecs,
1411                    stats.cnt);
1412 }
1413 #endif
1414
1415 const struct file_operations bpf_prog_fops = {
1416 #ifdef CONFIG_PROC_FS
1417         .show_fdinfo    = bpf_prog_show_fdinfo,
1418 #endif
1419         .release        = bpf_prog_release,
1420         .read           = bpf_dummy_read,
1421         .write          = bpf_dummy_write,
1422 };
1423
1424 int bpf_prog_new_fd(struct bpf_prog *prog)
1425 {
1426         int ret;
1427
1428         ret = security_bpf_prog(prog);
1429         if (ret < 0)
1430                 return ret;
1431
1432         return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
1433                                 O_RDWR | O_CLOEXEC);
1434 }
1435
1436 static struct bpf_prog *____bpf_prog_get(struct fd f)
1437 {
1438         if (!f.file)
1439                 return ERR_PTR(-EBADF);
1440         if (f.file->f_op != &bpf_prog_fops) {
1441                 fdput(f);
1442                 return ERR_PTR(-EINVAL);
1443         }
1444
1445         return f.file->private_data;
1446 }
1447
1448 void bpf_prog_add(struct bpf_prog *prog, int i)
1449 {
1450         atomic64_add(i, &prog->aux->refcnt);
1451 }
1452 EXPORT_SYMBOL_GPL(bpf_prog_add);
1453
1454 void bpf_prog_sub(struct bpf_prog *prog, int i)
1455 {
1456         /* Only to be used for undoing previous bpf_prog_add() in some
1457          * error path. We still know that another entity in our call
1458          * path holds a reference to the program, thus atomic_sub() can
1459          * be safely used in such cases!
1460          */
1461         WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
1462 }
1463 EXPORT_SYMBOL_GPL(bpf_prog_sub);
1464
1465 void bpf_prog_inc(struct bpf_prog *prog)
1466 {
1467         atomic64_inc(&prog->aux->refcnt);
1468 }
1469 EXPORT_SYMBOL_GPL(bpf_prog_inc);
1470
1471 /* prog_idr_lock should have been held */
1472 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
1473 {
1474         int refold;
1475
1476         refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
1477
1478         if (!refold)
1479                 return ERR_PTR(-ENOENT);
1480
1481         return prog;
1482 }
1483 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
1484
1485 bool bpf_prog_get_ok(struct bpf_prog *prog,
1486                             enum bpf_prog_type *attach_type, bool attach_drv)
1487 {
1488         /* not an attachment, just a refcount inc, always allow */
1489         if (!attach_type)
1490                 return true;
1491
1492         if (prog->type != *attach_type)
1493                 return false;
1494         if (bpf_prog_is_dev_bound(prog->aux) && !attach_drv)
1495                 return false;
1496
1497         return true;
1498 }
1499
1500 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
1501                                        bool attach_drv)
1502 {
1503         struct fd f = fdget(ufd);
1504         struct bpf_prog *prog;
1505
1506         prog = ____bpf_prog_get(f);
1507         if (IS_ERR(prog))
1508                 return prog;
1509         if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
1510                 prog = ERR_PTR(-EINVAL);
1511                 goto out;
1512         }
1513
1514         bpf_prog_inc(prog);
1515 out:
1516         fdput(f);
1517         return prog;
1518 }
1519
1520 struct bpf_prog *bpf_prog_get(u32 ufd)
1521 {
1522         return __bpf_prog_get(ufd, NULL, false);
1523 }
1524
1525 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
1526                                        bool attach_drv)
1527 {
1528         return __bpf_prog_get(ufd, &type, attach_drv);
1529 }
1530 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
1531
1532 /* Initially all BPF programs could be loaded w/o specifying
1533  * expected_attach_type. Later for some of them specifying expected_attach_type
1534  * at load time became required so that program could be validated properly.
1535  * Programs of types that are allowed to be loaded both w/ and w/o (for
1536  * backward compatibility) expected_attach_type, should have the default attach
1537  * type assigned to expected_attach_type for the latter case, so that it can be
1538  * validated later at attach time.
1539  *
1540  * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
1541  * prog type requires it but has some attach types that have to be backward
1542  * compatible.
1543  */
1544 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
1545 {
1546         switch (attr->prog_type) {
1547         case BPF_PROG_TYPE_CGROUP_SOCK:
1548                 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
1549                  * exist so checking for non-zero is the way to go here.
1550                  */
1551                 if (!attr->expected_attach_type)
1552                         attr->expected_attach_type =
1553                                 BPF_CGROUP_INET_SOCK_CREATE;
1554                 break;
1555         }
1556 }
1557
1558 static int
1559 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
1560                            enum bpf_attach_type expected_attach_type,
1561                            u32 btf_id, u32 prog_fd)
1562 {
1563         switch (prog_type) {
1564         case BPF_PROG_TYPE_TRACING:
1565                 if (btf_id > BTF_MAX_TYPE)
1566                         return -EINVAL;
1567                 break;
1568         default:
1569                 if (btf_id || prog_fd)
1570                         return -EINVAL;
1571                 break;
1572         }
1573
1574         switch (prog_type) {
1575         case BPF_PROG_TYPE_CGROUP_SOCK:
1576                 switch (expected_attach_type) {
1577                 case BPF_CGROUP_INET_SOCK_CREATE:
1578                 case BPF_CGROUP_INET4_POST_BIND:
1579                 case BPF_CGROUP_INET6_POST_BIND:
1580                         return 0;
1581                 default:
1582                         return -EINVAL;
1583                 }
1584         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
1585                 switch (expected_attach_type) {
1586                 case BPF_CGROUP_INET4_BIND:
1587                 case BPF_CGROUP_INET6_BIND:
1588                 case BPF_CGROUP_INET4_CONNECT:
1589                 case BPF_CGROUP_INET6_CONNECT:
1590                 case BPF_CGROUP_UDP4_SENDMSG:
1591                 case BPF_CGROUP_UDP6_SENDMSG:
1592                 case BPF_CGROUP_UDP4_RECVMSG:
1593                 case BPF_CGROUP_UDP6_RECVMSG:
1594                         return 0;
1595                 default:
1596                         return -EINVAL;
1597                 }
1598         case BPF_PROG_TYPE_CGROUP_SKB:
1599                 switch (expected_attach_type) {
1600                 case BPF_CGROUP_INET_INGRESS:
1601                 case BPF_CGROUP_INET_EGRESS:
1602                         return 0;
1603                 default:
1604                         return -EINVAL;
1605                 }
1606         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
1607                 switch (expected_attach_type) {
1608                 case BPF_CGROUP_SETSOCKOPT:
1609                 case BPF_CGROUP_GETSOCKOPT:
1610                         return 0;
1611                 default:
1612                         return -EINVAL;
1613                 }
1614         default:
1615                 return 0;
1616         }
1617 }
1618
1619 /* last field in 'union bpf_attr' used by this command */
1620 #define BPF_PROG_LOAD_LAST_FIELD attach_prog_fd
1621
1622 static int bpf_prog_load(union bpf_attr *attr, union bpf_attr __user *uattr)
1623 {
1624         enum bpf_prog_type type = attr->prog_type;
1625         struct bpf_prog *prog;
1626         int err;
1627         char license[128];
1628         bool is_gpl;
1629
1630         if (CHECK_ATTR(BPF_PROG_LOAD))
1631                 return -EINVAL;
1632
1633         if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
1634                                  BPF_F_ANY_ALIGNMENT |
1635                                  BPF_F_TEST_STATE_FREQ |
1636                                  BPF_F_TEST_RND_HI32))
1637                 return -EINVAL;
1638
1639         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
1640             (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
1641             !capable(CAP_SYS_ADMIN))
1642                 return -EPERM;
1643
1644         /* copy eBPF program license from user space */
1645         if (strncpy_from_user(license, u64_to_user_ptr(attr->license),
1646                               sizeof(license) - 1) < 0)
1647                 return -EFAULT;
1648         license[sizeof(license) - 1] = 0;
1649
1650         /* eBPF programs must be GPL compatible to use GPL-ed functions */
1651         is_gpl = license_is_gpl_compatible(license);
1652
1653         if (attr->insn_cnt == 0 ||
1654             attr->insn_cnt > (capable(CAP_SYS_ADMIN) ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
1655                 return -E2BIG;
1656         if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
1657             type != BPF_PROG_TYPE_CGROUP_SKB &&
1658             !capable(CAP_SYS_ADMIN))
1659                 return -EPERM;
1660
1661         bpf_prog_load_fixup_attach_type(attr);
1662         if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
1663                                        attr->attach_btf_id,
1664                                        attr->attach_prog_fd))
1665                 return -EINVAL;
1666
1667         /* plain bpf_prog allocation */
1668         prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
1669         if (!prog)
1670                 return -ENOMEM;
1671
1672         prog->expected_attach_type = attr->expected_attach_type;
1673         prog->aux->attach_btf_id = attr->attach_btf_id;
1674         if (attr->attach_prog_fd) {
1675                 struct bpf_prog *tgt_prog;
1676
1677                 tgt_prog = bpf_prog_get(attr->attach_prog_fd);
1678                 if (IS_ERR(tgt_prog)) {
1679                         err = PTR_ERR(tgt_prog);
1680                         goto free_prog_nouncharge;
1681                 }
1682                 prog->aux->linked_prog = tgt_prog;
1683         }
1684
1685         prog->aux->offload_requested = !!attr->prog_ifindex;
1686
1687         err = security_bpf_prog_alloc(prog->aux);
1688         if (err)
1689                 goto free_prog_nouncharge;
1690
1691         err = bpf_prog_charge_memlock(prog);
1692         if (err)
1693                 goto free_prog_sec;
1694
1695         prog->len = attr->insn_cnt;
1696
1697         err = -EFAULT;
1698         if (copy_from_user(prog->insns, u64_to_user_ptr(attr->insns),
1699                            bpf_prog_insn_size(prog)) != 0)
1700                 goto free_prog;
1701
1702         prog->orig_prog = NULL;
1703         prog->jited = 0;
1704
1705         atomic64_set(&prog->aux->refcnt, 1);
1706         prog->gpl_compatible = is_gpl ? 1 : 0;
1707
1708         if (bpf_prog_is_dev_bound(prog->aux)) {
1709                 err = bpf_prog_offload_init(prog, attr);
1710                 if (err)
1711                         goto free_prog;
1712         }
1713
1714         /* find program type: socket_filter vs tracing_filter */
1715         err = find_prog_type(type, prog);
1716         if (err < 0)
1717                 goto free_prog;
1718
1719         prog->aux->load_time = ktime_get_boottime_ns();
1720         err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name);
1721         if (err)
1722                 goto free_prog;
1723
1724         /* run eBPF verifier */
1725         err = bpf_check(&prog, attr, uattr);
1726         if (err < 0)
1727                 goto free_used_maps;
1728
1729         prog = bpf_prog_select_runtime(prog, &err);
1730         if (err < 0)
1731                 goto free_used_maps;
1732
1733         err = bpf_prog_alloc_id(prog);
1734         if (err)
1735                 goto free_used_maps;
1736
1737         /* Upon success of bpf_prog_alloc_id(), the BPF prog is
1738          * effectively publicly exposed. However, retrieving via
1739          * bpf_prog_get_fd_by_id() will take another reference,
1740          * therefore it cannot be gone underneath us.
1741          *
1742          * Only for the time /after/ successful bpf_prog_new_fd()
1743          * and before returning to userspace, we might just hold
1744          * one reference and any parallel close on that fd could
1745          * rip everything out. Hence, below notifications must
1746          * happen before bpf_prog_new_fd().
1747          *
1748          * Also, any failure handling from this point onwards must
1749          * be using bpf_prog_put() given the program is exposed.
1750          */
1751         bpf_prog_kallsyms_add(prog);
1752         perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
1753
1754         err = bpf_prog_new_fd(prog);
1755         if (err < 0)
1756                 bpf_prog_put(prog);
1757         return err;
1758
1759 free_used_maps:
1760         /* In case we have subprogs, we need to wait for a grace
1761          * period before we can tear down JIT memory since symbols
1762          * are already exposed under kallsyms.
1763          */
1764         __bpf_prog_put_noref(prog, prog->aux->func_cnt);
1765         return err;
1766 free_prog:
1767         bpf_prog_uncharge_memlock(prog);
1768 free_prog_sec:
1769         security_bpf_prog_free(prog->aux);
1770 free_prog_nouncharge:
1771         bpf_prog_free(prog);
1772         return err;
1773 }
1774
1775 #define BPF_OBJ_LAST_FIELD file_flags
1776
1777 static int bpf_obj_pin(const union bpf_attr *attr)
1778 {
1779         if (CHECK_ATTR(BPF_OBJ) || attr->file_flags != 0)
1780                 return -EINVAL;
1781
1782         return bpf_obj_pin_user(attr->bpf_fd, u64_to_user_ptr(attr->pathname));
1783 }
1784
1785 static int bpf_obj_get(const union bpf_attr *attr)
1786 {
1787         if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
1788             attr->file_flags & ~BPF_OBJ_FLAG_MASK)
1789                 return -EINVAL;
1790
1791         return bpf_obj_get_user(u64_to_user_ptr(attr->pathname),
1792                                 attr->file_flags);
1793 }
1794
1795 static int bpf_tracing_prog_release(struct inode *inode, struct file *filp)
1796 {
1797         struct bpf_prog *prog = filp->private_data;
1798
1799         WARN_ON_ONCE(bpf_trampoline_unlink_prog(prog));
1800         bpf_prog_put(prog);
1801         return 0;
1802 }
1803
1804 static const struct file_operations bpf_tracing_prog_fops = {
1805         .release        = bpf_tracing_prog_release,
1806         .read           = bpf_dummy_read,
1807         .write          = bpf_dummy_write,
1808 };
1809
1810 static int bpf_tracing_prog_attach(struct bpf_prog *prog)
1811 {
1812         int tr_fd, err;
1813
1814         if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
1815             prog->expected_attach_type != BPF_TRACE_FEXIT) {
1816                 err = -EINVAL;
1817                 goto out_put_prog;
1818         }
1819
1820         err = bpf_trampoline_link_prog(prog);
1821         if (err)
1822                 goto out_put_prog;
1823
1824         tr_fd = anon_inode_getfd("bpf-tracing-prog", &bpf_tracing_prog_fops,
1825                                  prog, O_CLOEXEC);
1826         if (tr_fd < 0) {
1827                 WARN_ON_ONCE(bpf_trampoline_unlink_prog(prog));
1828                 err = tr_fd;
1829                 goto out_put_prog;
1830         }
1831         return tr_fd;
1832
1833 out_put_prog:
1834         bpf_prog_put(prog);
1835         return err;
1836 }
1837
1838 struct bpf_raw_tracepoint {
1839         struct bpf_raw_event_map *btp;
1840         struct bpf_prog *prog;
1841 };
1842
1843 static int bpf_raw_tracepoint_release(struct inode *inode, struct file *filp)
1844 {
1845         struct bpf_raw_tracepoint *raw_tp = filp->private_data;
1846
1847         if (raw_tp->prog) {
1848                 bpf_probe_unregister(raw_tp->btp, raw_tp->prog);
1849                 bpf_prog_put(raw_tp->prog);
1850         }
1851         bpf_put_raw_tracepoint(raw_tp->btp);
1852         kfree(raw_tp);
1853         return 0;
1854 }
1855
1856 static const struct file_operations bpf_raw_tp_fops = {
1857         .release        = bpf_raw_tracepoint_release,
1858         .read           = bpf_dummy_read,
1859         .write          = bpf_dummy_write,
1860 };
1861
1862 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
1863
1864 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
1865 {
1866         struct bpf_raw_tracepoint *raw_tp;
1867         struct bpf_raw_event_map *btp;
1868         struct bpf_prog *prog;
1869         const char *tp_name;
1870         char buf[128];
1871         int tp_fd, err;
1872
1873         if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
1874                 return -EINVAL;
1875
1876         prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
1877         if (IS_ERR(prog))
1878                 return PTR_ERR(prog);
1879
1880         if (prog->type != BPF_PROG_TYPE_RAW_TRACEPOINT &&
1881             prog->type != BPF_PROG_TYPE_TRACING &&
1882             prog->type != BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE) {
1883                 err = -EINVAL;
1884                 goto out_put_prog;
1885         }
1886
1887         if (prog->type == BPF_PROG_TYPE_TRACING) {
1888                 if (attr->raw_tracepoint.name) {
1889                         /* The attach point for this category of programs
1890                          * should be specified via btf_id during program load.
1891                          */
1892                         err = -EINVAL;
1893                         goto out_put_prog;
1894                 }
1895                 if (prog->expected_attach_type == BPF_TRACE_RAW_TP)
1896                         tp_name = prog->aux->attach_func_name;
1897                 else
1898                         return bpf_tracing_prog_attach(prog);
1899         } else {
1900                 if (strncpy_from_user(buf,
1901                                       u64_to_user_ptr(attr->raw_tracepoint.name),
1902                                       sizeof(buf) - 1) < 0) {
1903                         err = -EFAULT;
1904                         goto out_put_prog;
1905                 }
1906                 buf[sizeof(buf) - 1] = 0;
1907                 tp_name = buf;
1908         }
1909
1910         btp = bpf_get_raw_tracepoint(tp_name);
1911         if (!btp) {
1912                 err = -ENOENT;
1913                 goto out_put_prog;
1914         }
1915
1916         raw_tp = kzalloc(sizeof(*raw_tp), GFP_USER);
1917         if (!raw_tp) {
1918                 err = -ENOMEM;
1919                 goto out_put_btp;
1920         }
1921         raw_tp->btp = btp;
1922         raw_tp->prog = prog;
1923
1924         err = bpf_probe_register(raw_tp->btp, prog);
1925         if (err)
1926                 goto out_free_tp;
1927
1928         tp_fd = anon_inode_getfd("bpf-raw-tracepoint", &bpf_raw_tp_fops, raw_tp,
1929                                  O_CLOEXEC);
1930         if (tp_fd < 0) {
1931                 bpf_probe_unregister(raw_tp->btp, prog);
1932                 err = tp_fd;
1933                 goto out_free_tp;
1934         }
1935         return tp_fd;
1936
1937 out_free_tp:
1938         kfree(raw_tp);
1939 out_put_btp:
1940         bpf_put_raw_tracepoint(btp);
1941 out_put_prog:
1942         bpf_prog_put(prog);
1943         return err;
1944 }
1945
1946 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
1947                                              enum bpf_attach_type attach_type)
1948 {
1949         switch (prog->type) {
1950         case BPF_PROG_TYPE_CGROUP_SOCK:
1951         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
1952         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
1953                 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
1954         case BPF_PROG_TYPE_CGROUP_SKB:
1955                 return prog->enforce_expected_attach_type &&
1956                         prog->expected_attach_type != attach_type ?
1957                         -EINVAL : 0;
1958         default:
1959                 return 0;
1960         }
1961 }
1962
1963 #define BPF_PROG_ATTACH_LAST_FIELD attach_flags
1964
1965 #define BPF_F_ATTACH_MASK \
1966         (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI)
1967
1968 static int bpf_prog_attach(const union bpf_attr *attr)
1969 {
1970         enum bpf_prog_type ptype;
1971         struct bpf_prog *prog;
1972         int ret;
1973
1974         if (!capable(CAP_NET_ADMIN))
1975                 return -EPERM;
1976
1977         if (CHECK_ATTR(BPF_PROG_ATTACH))
1978                 return -EINVAL;
1979
1980         if (attr->attach_flags & ~BPF_F_ATTACH_MASK)
1981                 return -EINVAL;
1982
1983         switch (attr->attach_type) {
1984         case BPF_CGROUP_INET_INGRESS:
1985         case BPF_CGROUP_INET_EGRESS:
1986                 ptype = BPF_PROG_TYPE_CGROUP_SKB;
1987                 break;
1988         case BPF_CGROUP_INET_SOCK_CREATE:
1989         case BPF_CGROUP_INET4_POST_BIND:
1990         case BPF_CGROUP_INET6_POST_BIND:
1991                 ptype = BPF_PROG_TYPE_CGROUP_SOCK;
1992                 break;
1993         case BPF_CGROUP_INET4_BIND:
1994         case BPF_CGROUP_INET6_BIND:
1995         case BPF_CGROUP_INET4_CONNECT:
1996         case BPF_CGROUP_INET6_CONNECT:
1997         case BPF_CGROUP_UDP4_SENDMSG:
1998         case BPF_CGROUP_UDP6_SENDMSG:
1999         case BPF_CGROUP_UDP4_RECVMSG:
2000         case BPF_CGROUP_UDP6_RECVMSG:
2001                 ptype = BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
2002                 break;
2003         case BPF_CGROUP_SOCK_OPS:
2004                 ptype = BPF_PROG_TYPE_SOCK_OPS;
2005                 break;
2006         case BPF_CGROUP_DEVICE:
2007                 ptype = BPF_PROG_TYPE_CGROUP_DEVICE;
2008                 break;
2009         case BPF_SK_MSG_VERDICT:
2010                 ptype = BPF_PROG_TYPE_SK_MSG;
2011                 break;
2012         case BPF_SK_SKB_STREAM_PARSER:
2013         case BPF_SK_SKB_STREAM_VERDICT:
2014                 ptype = BPF_PROG_TYPE_SK_SKB;
2015                 break;
2016         case BPF_LIRC_MODE2:
2017                 ptype = BPF_PROG_TYPE_LIRC_MODE2;
2018                 break;
2019         case BPF_FLOW_DISSECTOR:
2020                 ptype = BPF_PROG_TYPE_FLOW_DISSECTOR;
2021                 break;
2022         case BPF_CGROUP_SYSCTL:
2023                 ptype = BPF_PROG_TYPE_CGROUP_SYSCTL;
2024                 break;
2025         case BPF_CGROUP_GETSOCKOPT:
2026         case BPF_CGROUP_SETSOCKOPT:
2027                 ptype = BPF_PROG_TYPE_CGROUP_SOCKOPT;
2028                 break;
2029         default:
2030                 return -EINVAL;
2031         }
2032
2033         prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
2034         if (IS_ERR(prog))
2035                 return PTR_ERR(prog);
2036
2037         if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
2038                 bpf_prog_put(prog);
2039                 return -EINVAL;
2040         }
2041
2042         switch (ptype) {
2043         case BPF_PROG_TYPE_SK_SKB:
2044         case BPF_PROG_TYPE_SK_MSG:
2045                 ret = sock_map_get_from_fd(attr, prog);
2046                 break;
2047         case BPF_PROG_TYPE_LIRC_MODE2:
2048                 ret = lirc_prog_attach(attr, prog);
2049                 break;
2050         case BPF_PROG_TYPE_FLOW_DISSECTOR:
2051                 ret = skb_flow_dissector_bpf_prog_attach(attr, prog);
2052                 break;
2053         default:
2054                 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
2055         }
2056
2057         if (ret)
2058                 bpf_prog_put(prog);
2059         return ret;
2060 }
2061
2062 #define BPF_PROG_DETACH_LAST_FIELD attach_type
2063
2064 static int bpf_prog_detach(const union bpf_attr *attr)
2065 {
2066         enum bpf_prog_type ptype;
2067
2068         if (!capable(CAP_NET_ADMIN))
2069                 return -EPERM;
2070
2071         if (CHECK_ATTR(BPF_PROG_DETACH))
2072                 return -EINVAL;
2073
2074         switch (attr->attach_type) {
2075         case BPF_CGROUP_INET_INGRESS:
2076         case BPF_CGROUP_INET_EGRESS:
2077                 ptype = BPF_PROG_TYPE_CGROUP_SKB;
2078                 break;
2079         case BPF_CGROUP_INET_SOCK_CREATE:
2080         case BPF_CGROUP_INET4_POST_BIND:
2081         case BPF_CGROUP_INET6_POST_BIND:
2082                 ptype = BPF_PROG_TYPE_CGROUP_SOCK;
2083                 break;
2084         case BPF_CGROUP_INET4_BIND:
2085         case BPF_CGROUP_INET6_BIND:
2086         case BPF_CGROUP_INET4_CONNECT:
2087         case BPF_CGROUP_INET6_CONNECT:
2088         case BPF_CGROUP_UDP4_SENDMSG:
2089         case BPF_CGROUP_UDP6_SENDMSG:
2090         case BPF_CGROUP_UDP4_RECVMSG:
2091         case BPF_CGROUP_UDP6_RECVMSG:
2092                 ptype = BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
2093                 break;
2094         case BPF_CGROUP_SOCK_OPS:
2095                 ptype = BPF_PROG_TYPE_SOCK_OPS;
2096                 break;
2097         case BPF_CGROUP_DEVICE:
2098                 ptype = BPF_PROG_TYPE_CGROUP_DEVICE;
2099                 break;
2100         case BPF_SK_MSG_VERDICT:
2101                 return sock_map_get_from_fd(attr, NULL);
2102         case BPF_SK_SKB_STREAM_PARSER:
2103         case BPF_SK_SKB_STREAM_VERDICT:
2104                 return sock_map_get_from_fd(attr, NULL);
2105         case BPF_LIRC_MODE2:
2106                 return lirc_prog_detach(attr);
2107         case BPF_FLOW_DISSECTOR:
2108                 return skb_flow_dissector_bpf_prog_detach(attr);
2109         case BPF_CGROUP_SYSCTL:
2110                 ptype = BPF_PROG_TYPE_CGROUP_SYSCTL;
2111                 break;
2112         case BPF_CGROUP_GETSOCKOPT:
2113         case BPF_CGROUP_SETSOCKOPT:
2114                 ptype = BPF_PROG_TYPE_CGROUP_SOCKOPT;
2115                 break;
2116         default:
2117                 return -EINVAL;
2118         }
2119
2120         return cgroup_bpf_prog_detach(attr, ptype);
2121 }
2122
2123 #define BPF_PROG_QUERY_LAST_FIELD query.prog_cnt
2124
2125 static int bpf_prog_query(const union bpf_attr *attr,
2126                           union bpf_attr __user *uattr)
2127 {
2128         if (!capable(CAP_NET_ADMIN))
2129                 return -EPERM;
2130         if (CHECK_ATTR(BPF_PROG_QUERY))
2131                 return -EINVAL;
2132         if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
2133                 return -EINVAL;
2134
2135         switch (attr->query.attach_type) {
2136         case BPF_CGROUP_INET_INGRESS:
2137         case BPF_CGROUP_INET_EGRESS:
2138         case BPF_CGROUP_INET_SOCK_CREATE:
2139         case BPF_CGROUP_INET4_BIND:
2140         case BPF_CGROUP_INET6_BIND:
2141         case BPF_CGROUP_INET4_POST_BIND:
2142         case BPF_CGROUP_INET6_POST_BIND:
2143         case BPF_CGROUP_INET4_CONNECT:
2144         case BPF_CGROUP_INET6_CONNECT:
2145         case BPF_CGROUP_UDP4_SENDMSG:
2146         case BPF_CGROUP_UDP6_SENDMSG:
2147         case BPF_CGROUP_UDP4_RECVMSG:
2148         case BPF_CGROUP_UDP6_RECVMSG:
2149         case BPF_CGROUP_SOCK_OPS:
2150         case BPF_CGROUP_DEVICE:
2151         case BPF_CGROUP_SYSCTL:
2152         case BPF_CGROUP_GETSOCKOPT:
2153         case BPF_CGROUP_SETSOCKOPT:
2154                 break;
2155         case BPF_LIRC_MODE2:
2156                 return lirc_prog_query(attr, uattr);
2157         case BPF_FLOW_DISSECTOR:
2158                 return skb_flow_dissector_prog_query(attr, uattr);
2159         default:
2160                 return -EINVAL;
2161         }
2162
2163         return cgroup_bpf_prog_query(attr, uattr);
2164 }
2165
2166 #define BPF_PROG_TEST_RUN_LAST_FIELD test.ctx_out
2167
2168 static int bpf_prog_test_run(const union bpf_attr *attr,
2169                              union bpf_attr __user *uattr)
2170 {
2171         struct bpf_prog *prog;
2172         int ret = -ENOTSUPP;
2173
2174         if (!capable(CAP_SYS_ADMIN))
2175                 return -EPERM;
2176         if (CHECK_ATTR(BPF_PROG_TEST_RUN))
2177                 return -EINVAL;
2178
2179         if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
2180             (!attr->test.ctx_size_in && attr->test.ctx_in))
2181                 return -EINVAL;
2182
2183         if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
2184             (!attr->test.ctx_size_out && attr->test.ctx_out))
2185                 return -EINVAL;
2186
2187         prog = bpf_prog_get(attr->test.prog_fd);
2188         if (IS_ERR(prog))
2189                 return PTR_ERR(prog);
2190
2191         if (prog->aux->ops->test_run)
2192                 ret = prog->aux->ops->test_run(prog, attr, uattr);
2193
2194         bpf_prog_put(prog);
2195         return ret;
2196 }
2197
2198 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
2199
2200 static int bpf_obj_get_next_id(const union bpf_attr *attr,
2201                                union bpf_attr __user *uattr,
2202                                struct idr *idr,
2203                                spinlock_t *lock)
2204 {
2205         u32 next_id = attr->start_id;
2206         int err = 0;
2207
2208         if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
2209                 return -EINVAL;
2210
2211         if (!capable(CAP_SYS_ADMIN))
2212                 return -EPERM;
2213
2214         next_id++;
2215         spin_lock_bh(lock);
2216         if (!idr_get_next(idr, &next_id))
2217                 err = -ENOENT;
2218         spin_unlock_bh(lock);
2219
2220         if (!err)
2221                 err = put_user(next_id, &uattr->next_id);
2222
2223         return err;
2224 }
2225
2226 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
2227
2228 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
2229 {
2230         struct bpf_prog *prog;
2231         u32 id = attr->prog_id;
2232         int fd;
2233
2234         if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
2235                 return -EINVAL;
2236
2237         if (!capable(CAP_SYS_ADMIN))
2238                 return -EPERM;
2239
2240         spin_lock_bh(&prog_idr_lock);
2241         prog = idr_find(&prog_idr, id);
2242         if (prog)
2243                 prog = bpf_prog_inc_not_zero(prog);
2244         else
2245                 prog = ERR_PTR(-ENOENT);
2246         spin_unlock_bh(&prog_idr_lock);
2247
2248         if (IS_ERR(prog))
2249                 return PTR_ERR(prog);
2250
2251         fd = bpf_prog_new_fd(prog);
2252         if (fd < 0)
2253                 bpf_prog_put(prog);
2254
2255         return fd;
2256 }
2257
2258 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
2259
2260 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
2261 {
2262         struct bpf_map *map;
2263         u32 id = attr->map_id;
2264         int f_flags;
2265         int fd;
2266
2267         if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
2268             attr->open_flags & ~BPF_OBJ_FLAG_MASK)
2269                 return -EINVAL;
2270
2271         if (!capable(CAP_SYS_ADMIN))
2272                 return -EPERM;
2273
2274         f_flags = bpf_get_file_flag(attr->open_flags);
2275         if (f_flags < 0)
2276                 return f_flags;
2277
2278         spin_lock_bh(&map_idr_lock);
2279         map = idr_find(&map_idr, id);
2280         if (map)
2281                 map = __bpf_map_inc_not_zero(map, true);
2282         else
2283                 map = ERR_PTR(-ENOENT);
2284         spin_unlock_bh(&map_idr_lock);
2285
2286         if (IS_ERR(map))
2287                 return PTR_ERR(map);
2288
2289         fd = bpf_map_new_fd(map, f_flags);
2290         if (fd < 0)
2291                 bpf_map_put_with_uref(map);
2292
2293         return fd;
2294 }
2295
2296 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
2297                                               unsigned long addr, u32 *off,
2298                                               u32 *type)
2299 {
2300         const struct bpf_map *map;
2301         int i;
2302
2303         for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
2304                 map = prog->aux->used_maps[i];
2305                 if (map == (void *)addr) {
2306                         *type = BPF_PSEUDO_MAP_FD;
2307                         return map;
2308                 }
2309                 if (!map->ops->map_direct_value_meta)
2310                         continue;
2311                 if (!map->ops->map_direct_value_meta(map, addr, off)) {
2312                         *type = BPF_PSEUDO_MAP_VALUE;
2313                         return map;
2314                 }
2315         }
2316
2317         return NULL;
2318 }
2319
2320 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog)
2321 {
2322         const struct bpf_map *map;
2323         struct bpf_insn *insns;
2324         u32 off, type;
2325         u64 imm;
2326         int i;
2327
2328         insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
2329                         GFP_USER);
2330         if (!insns)
2331                 return insns;
2332
2333         for (i = 0; i < prog->len; i++) {
2334                 if (insns[i].code == (BPF_JMP | BPF_TAIL_CALL)) {
2335                         insns[i].code = BPF_JMP | BPF_CALL;
2336                         insns[i].imm = BPF_FUNC_tail_call;
2337                         /* fall-through */
2338                 }
2339                 if (insns[i].code == (BPF_JMP | BPF_CALL) ||
2340                     insns[i].code == (BPF_JMP | BPF_CALL_ARGS)) {
2341                         if (insns[i].code == (BPF_JMP | BPF_CALL_ARGS))
2342                                 insns[i].code = BPF_JMP | BPF_CALL;
2343                         if (!bpf_dump_raw_ok())
2344                                 insns[i].imm = 0;
2345                         continue;
2346                 }
2347
2348                 if (insns[i].code != (BPF_LD | BPF_IMM | BPF_DW))
2349                         continue;
2350
2351                 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
2352                 map = bpf_map_from_imm(prog, imm, &off, &type);
2353                 if (map) {
2354                         insns[i].src_reg = type;
2355                         insns[i].imm = map->id;
2356                         insns[i + 1].imm = off;
2357                         continue;
2358                 }
2359         }
2360
2361         return insns;
2362 }
2363
2364 static int set_info_rec_size(struct bpf_prog_info *info)
2365 {
2366         /*
2367          * Ensure info.*_rec_size is the same as kernel expected size
2368          *
2369          * or
2370          *
2371          * Only allow zero *_rec_size if both _rec_size and _cnt are
2372          * zero.  In this case, the kernel will set the expected
2373          * _rec_size back to the info.
2374          */
2375
2376         if ((info->nr_func_info || info->func_info_rec_size) &&
2377             info->func_info_rec_size != sizeof(struct bpf_func_info))
2378                 return -EINVAL;
2379
2380         if ((info->nr_line_info || info->line_info_rec_size) &&
2381             info->line_info_rec_size != sizeof(struct bpf_line_info))
2382                 return -EINVAL;
2383
2384         if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
2385             info->jited_line_info_rec_size != sizeof(__u64))
2386                 return -EINVAL;
2387
2388         info->func_info_rec_size = sizeof(struct bpf_func_info);
2389         info->line_info_rec_size = sizeof(struct bpf_line_info);
2390         info->jited_line_info_rec_size = sizeof(__u64);
2391
2392         return 0;
2393 }
2394
2395 static int bpf_prog_get_info_by_fd(struct bpf_prog *prog,
2396                                    const union bpf_attr *attr,
2397                                    union bpf_attr __user *uattr)
2398 {
2399         struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
2400         struct bpf_prog_info info = {};
2401         u32 info_len = attr->info.info_len;
2402         struct bpf_prog_stats stats;
2403         char __user *uinsns;
2404         u32 ulen;
2405         int err;
2406
2407         err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
2408         if (err)
2409                 return err;
2410         info_len = min_t(u32, sizeof(info), info_len);
2411
2412         if (copy_from_user(&info, uinfo, info_len))
2413                 return -EFAULT;
2414
2415         info.type = prog->type;
2416         info.id = prog->aux->id;
2417         info.load_time = prog->aux->load_time;
2418         info.created_by_uid = from_kuid_munged(current_user_ns(),
2419                                                prog->aux->user->uid);
2420         info.gpl_compatible = prog->gpl_compatible;
2421
2422         memcpy(info.tag, prog->tag, sizeof(prog->tag));
2423         memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
2424
2425         ulen = info.nr_map_ids;
2426         info.nr_map_ids = prog->aux->used_map_cnt;
2427         ulen = min_t(u32, info.nr_map_ids, ulen);
2428         if (ulen) {
2429                 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
2430                 u32 i;
2431
2432                 for (i = 0; i < ulen; i++)
2433                         if (put_user(prog->aux->used_maps[i]->id,
2434                                      &user_map_ids[i]))
2435                                 return -EFAULT;
2436         }
2437
2438         err = set_info_rec_size(&info);
2439         if (err)
2440                 return err;
2441
2442         bpf_prog_get_stats(prog, &stats);
2443         info.run_time_ns = stats.nsecs;
2444         info.run_cnt = stats.cnt;
2445
2446         if (!capable(CAP_SYS_ADMIN)) {
2447                 info.jited_prog_len = 0;
2448                 info.xlated_prog_len = 0;
2449                 info.nr_jited_ksyms = 0;
2450                 info.nr_jited_func_lens = 0;
2451                 info.nr_func_info = 0;
2452                 info.nr_line_info = 0;
2453                 info.nr_jited_line_info = 0;
2454                 goto done;
2455         }
2456
2457         ulen = info.xlated_prog_len;
2458         info.xlated_prog_len = bpf_prog_insn_size(prog);
2459         if (info.xlated_prog_len && ulen) {
2460                 struct bpf_insn *insns_sanitized;
2461                 bool fault;
2462
2463                 if (prog->blinded && !bpf_dump_raw_ok()) {
2464                         info.xlated_prog_insns = 0;
2465                         goto done;
2466                 }
2467                 insns_sanitized = bpf_insn_prepare_dump(prog);
2468                 if (!insns_sanitized)
2469                         return -ENOMEM;
2470                 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
2471                 ulen = min_t(u32, info.xlated_prog_len, ulen);
2472                 fault = copy_to_user(uinsns, insns_sanitized, ulen);
2473                 kfree(insns_sanitized);
2474                 if (fault)
2475                         return -EFAULT;
2476         }
2477
2478         if (bpf_prog_is_dev_bound(prog->aux)) {
2479                 err = bpf_prog_offload_info_fill(&info, prog);
2480                 if (err)
2481                         return err;
2482                 goto done;
2483         }
2484
2485         /* NOTE: the following code is supposed to be skipped for offload.
2486          * bpf_prog_offload_info_fill() is the place to fill similar fields
2487          * for offload.
2488          */
2489         ulen = info.jited_prog_len;
2490         if (prog->aux->func_cnt) {
2491                 u32 i;
2492
2493                 info.jited_prog_len = 0;
2494                 for (i = 0; i < prog->aux->func_cnt; i++)
2495                         info.jited_prog_len += prog->aux->func[i]->jited_len;
2496         } else {
2497                 info.jited_prog_len = prog->jited_len;
2498         }
2499
2500         if (info.jited_prog_len && ulen) {
2501                 if (bpf_dump_raw_ok()) {
2502                         uinsns = u64_to_user_ptr(info.jited_prog_insns);
2503                         ulen = min_t(u32, info.jited_prog_len, ulen);
2504
2505                         /* for multi-function programs, copy the JITed
2506                          * instructions for all the functions
2507                          */
2508                         if (prog->aux->func_cnt) {
2509                                 u32 len, free, i;
2510                                 u8 *img;
2511
2512                                 free = ulen;
2513                                 for (i = 0; i < prog->aux->func_cnt; i++) {
2514                                         len = prog->aux->func[i]->jited_len;
2515                                         len = min_t(u32, len, free);
2516                                         img = (u8 *) prog->aux->func[i]->bpf_func;
2517                                         if (copy_to_user(uinsns, img, len))
2518                                                 return -EFAULT;
2519                                         uinsns += len;
2520                                         free -= len;
2521                                         if (!free)
2522                                                 break;
2523                                 }
2524                         } else {
2525                                 if (copy_to_user(uinsns, prog->bpf_func, ulen))
2526                                         return -EFAULT;
2527                         }
2528                 } else {
2529                         info.jited_prog_insns = 0;
2530                 }
2531         }
2532
2533         ulen = info.nr_jited_ksyms;
2534         info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
2535         if (ulen) {
2536                 if (bpf_dump_raw_ok()) {
2537                         unsigned long ksym_addr;
2538                         u64 __user *user_ksyms;
2539                         u32 i;
2540
2541                         /* copy the address of the kernel symbol
2542                          * corresponding to each function
2543                          */
2544                         ulen = min_t(u32, info.nr_jited_ksyms, ulen);
2545                         user_ksyms = u64_to_user_ptr(info.jited_ksyms);
2546                         if (prog->aux->func_cnt) {
2547                                 for (i = 0; i < ulen; i++) {
2548                                         ksym_addr = (unsigned long)
2549                                                 prog->aux->func[i]->bpf_func;
2550                                         if (put_user((u64) ksym_addr,
2551                                                      &user_ksyms[i]))
2552                                                 return -EFAULT;
2553                                 }
2554                         } else {
2555                                 ksym_addr = (unsigned long) prog->bpf_func;
2556                                 if (put_user((u64) ksym_addr, &user_ksyms[0]))
2557                                         return -EFAULT;
2558                         }
2559                 } else {
2560                         info.jited_ksyms = 0;
2561                 }
2562         }
2563
2564         ulen = info.nr_jited_func_lens;
2565         info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
2566         if (ulen) {
2567                 if (bpf_dump_raw_ok()) {
2568                         u32 __user *user_lens;
2569                         u32 func_len, i;
2570
2571                         /* copy the JITed image lengths for each function */
2572                         ulen = min_t(u32, info.nr_jited_func_lens, ulen);
2573                         user_lens = u64_to_user_ptr(info.jited_func_lens);
2574                         if (prog->aux->func_cnt) {
2575                                 for (i = 0; i < ulen; i++) {
2576                                         func_len =
2577                                                 prog->aux->func[i]->jited_len;
2578                                         if (put_user(func_len, &user_lens[i]))
2579                                                 return -EFAULT;
2580                                 }
2581                         } else {
2582                                 func_len = prog->jited_len;
2583                                 if (put_user(func_len, &user_lens[0]))
2584                                         return -EFAULT;
2585                         }
2586                 } else {
2587                         info.jited_func_lens = 0;
2588                 }
2589         }
2590
2591         if (prog->aux->btf)
2592                 info.btf_id = btf_id(prog->aux->btf);
2593
2594         ulen = info.nr_func_info;
2595         info.nr_func_info = prog->aux->func_info_cnt;
2596         if (info.nr_func_info && ulen) {
2597                 char __user *user_finfo;
2598
2599                 user_finfo = u64_to_user_ptr(info.func_info);
2600                 ulen = min_t(u32, info.nr_func_info, ulen);
2601                 if (copy_to_user(user_finfo, prog->aux->func_info,
2602                                  info.func_info_rec_size * ulen))
2603                         return -EFAULT;
2604         }
2605
2606         ulen = info.nr_line_info;
2607         info.nr_line_info = prog->aux->nr_linfo;
2608         if (info.nr_line_info && ulen) {
2609                 __u8 __user *user_linfo;
2610
2611                 user_linfo = u64_to_user_ptr(info.line_info);
2612                 ulen = min_t(u32, info.nr_line_info, ulen);
2613                 if (copy_to_user(user_linfo, prog->aux->linfo,
2614                                  info.line_info_rec_size * ulen))
2615                         return -EFAULT;
2616         }
2617
2618         ulen = info.nr_jited_line_info;
2619         if (prog->aux->jited_linfo)
2620                 info.nr_jited_line_info = prog->aux->nr_linfo;
2621         else
2622                 info.nr_jited_line_info = 0;
2623         if (info.nr_jited_line_info && ulen) {
2624                 if (bpf_dump_raw_ok()) {
2625                         __u64 __user *user_linfo;
2626                         u32 i;
2627
2628                         user_linfo = u64_to_user_ptr(info.jited_line_info);
2629                         ulen = min_t(u32, info.nr_jited_line_info, ulen);
2630                         for (i = 0; i < ulen; i++) {
2631                                 if (put_user((__u64)(long)prog->aux->jited_linfo[i],
2632                                              &user_linfo[i]))
2633                                         return -EFAULT;
2634                         }
2635                 } else {
2636                         info.jited_line_info = 0;
2637                 }
2638         }
2639
2640         ulen = info.nr_prog_tags;
2641         info.nr_prog_tags = prog->aux->func_cnt ? : 1;
2642         if (ulen) {
2643                 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
2644                 u32 i;
2645
2646                 user_prog_tags = u64_to_user_ptr(info.prog_tags);
2647                 ulen = min_t(u32, info.nr_prog_tags, ulen);
2648                 if (prog->aux->func_cnt) {
2649                         for (i = 0; i < ulen; i++) {
2650                                 if (copy_to_user(user_prog_tags[i],
2651                                                  prog->aux->func[i]->tag,
2652                                                  BPF_TAG_SIZE))
2653                                         return -EFAULT;
2654                         }
2655                 } else {
2656                         if (copy_to_user(user_prog_tags[0],
2657                                          prog->tag, BPF_TAG_SIZE))
2658                                 return -EFAULT;
2659                 }
2660         }
2661
2662 done:
2663         if (copy_to_user(uinfo, &info, info_len) ||
2664             put_user(info_len, &uattr->info.info_len))
2665                 return -EFAULT;
2666
2667         return 0;
2668 }
2669
2670 static int bpf_map_get_info_by_fd(struct bpf_map *map,
2671                                   const union bpf_attr *attr,
2672                                   union bpf_attr __user *uattr)
2673 {
2674         struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
2675         struct bpf_map_info info = {};
2676         u32 info_len = attr->info.info_len;
2677         int err;
2678
2679         err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
2680         if (err)
2681                 return err;
2682         info_len = min_t(u32, sizeof(info), info_len);
2683
2684         info.type = map->map_type;
2685         info.id = map->id;
2686         info.key_size = map->key_size;
2687         info.value_size = map->value_size;
2688         info.max_entries = map->max_entries;
2689         info.map_flags = map->map_flags;
2690         memcpy(info.name, map->name, sizeof(map->name));
2691
2692         if (map->btf) {
2693                 info.btf_id = btf_id(map->btf);
2694                 info.btf_key_type_id = map->btf_key_type_id;
2695                 info.btf_value_type_id = map->btf_value_type_id;
2696         }
2697
2698         if (bpf_map_is_dev_bound(map)) {
2699                 err = bpf_map_offload_info_fill(&info, map);
2700                 if (err)
2701                         return err;
2702         }
2703
2704         if (copy_to_user(uinfo, &info, info_len) ||
2705             put_user(info_len, &uattr->info.info_len))
2706                 return -EFAULT;
2707
2708         return 0;
2709 }
2710
2711 static int bpf_btf_get_info_by_fd(struct btf *btf,
2712                                   const union bpf_attr *attr,
2713                                   union bpf_attr __user *uattr)
2714 {
2715         struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
2716         u32 info_len = attr->info.info_len;
2717         int err;
2718
2719         err = bpf_check_uarg_tail_zero(uinfo, sizeof(*uinfo), info_len);
2720         if (err)
2721                 return err;
2722
2723         return btf_get_info_by_fd(btf, attr, uattr);
2724 }
2725
2726 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
2727
2728 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
2729                                   union bpf_attr __user *uattr)
2730 {
2731         int ufd = attr->info.bpf_fd;
2732         struct fd f;
2733         int err;
2734
2735         if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
2736                 return -EINVAL;
2737
2738         f = fdget(ufd);
2739         if (!f.file)
2740                 return -EBADFD;
2741
2742         if (f.file->f_op == &bpf_prog_fops)
2743                 err = bpf_prog_get_info_by_fd(f.file->private_data, attr,
2744                                               uattr);
2745         else if (f.file->f_op == &bpf_map_fops)
2746                 err = bpf_map_get_info_by_fd(f.file->private_data, attr,
2747                                              uattr);
2748         else if (f.file->f_op == &btf_fops)
2749                 err = bpf_btf_get_info_by_fd(f.file->private_data, attr, uattr);
2750         else
2751                 err = -EINVAL;
2752
2753         fdput(f);
2754         return err;
2755 }
2756
2757 #define BPF_BTF_LOAD_LAST_FIELD btf_log_level
2758
2759 static int bpf_btf_load(const union bpf_attr *attr)
2760 {
2761         if (CHECK_ATTR(BPF_BTF_LOAD))
2762                 return -EINVAL;
2763
2764         if (!capable(CAP_SYS_ADMIN))
2765                 return -EPERM;
2766
2767         return btf_new_fd(attr);
2768 }
2769
2770 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
2771
2772 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
2773 {
2774         if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
2775                 return -EINVAL;
2776
2777         if (!capable(CAP_SYS_ADMIN))
2778                 return -EPERM;
2779
2780         return btf_get_fd_by_id(attr->btf_id);
2781 }
2782
2783 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
2784                                     union bpf_attr __user *uattr,
2785                                     u32 prog_id, u32 fd_type,
2786                                     const char *buf, u64 probe_offset,
2787                                     u64 probe_addr)
2788 {
2789         char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
2790         u32 len = buf ? strlen(buf) : 0, input_len;
2791         int err = 0;
2792
2793         if (put_user(len, &uattr->task_fd_query.buf_len))
2794                 return -EFAULT;
2795         input_len = attr->task_fd_query.buf_len;
2796         if (input_len && ubuf) {
2797                 if (!len) {
2798                         /* nothing to copy, just make ubuf NULL terminated */
2799                         char zero = '\0';
2800
2801                         if (put_user(zero, ubuf))
2802                                 return -EFAULT;
2803                 } else if (input_len >= len + 1) {
2804                         /* ubuf can hold the string with NULL terminator */
2805                         if (copy_to_user(ubuf, buf, len + 1))
2806                                 return -EFAULT;
2807                 } else {
2808                         /* ubuf cannot hold the string with NULL terminator,
2809                          * do a partial copy with NULL terminator.
2810                          */
2811                         char zero = '\0';
2812
2813                         err = -ENOSPC;
2814                         if (copy_to_user(ubuf, buf, input_len - 1))
2815                                 return -EFAULT;
2816                         if (put_user(zero, ubuf + input_len - 1))
2817                                 return -EFAULT;
2818                 }
2819         }
2820
2821         if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
2822             put_user(fd_type, &uattr->task_fd_query.fd_type) ||
2823             put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
2824             put_user(probe_addr, &uattr->task_fd_query.probe_addr))
2825                 return -EFAULT;
2826
2827         return err;
2828 }
2829
2830 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
2831
2832 static int bpf_task_fd_query(const union bpf_attr *attr,
2833                              union bpf_attr __user *uattr)
2834 {
2835         pid_t pid = attr->task_fd_query.pid;
2836         u32 fd = attr->task_fd_query.fd;
2837         const struct perf_event *event;
2838         struct files_struct *files;
2839         struct task_struct *task;
2840         struct file *file;
2841         int err;
2842
2843         if (CHECK_ATTR(BPF_TASK_FD_QUERY))
2844                 return -EINVAL;
2845
2846         if (!capable(CAP_SYS_ADMIN))
2847                 return -EPERM;
2848
2849         if (attr->task_fd_query.flags != 0)
2850                 return -EINVAL;
2851
2852         task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
2853         if (!task)
2854                 return -ENOENT;
2855
2856         files = get_files_struct(task);
2857         put_task_struct(task);
2858         if (!files)
2859                 return -ENOENT;
2860
2861         err = 0;
2862         spin_lock(&files->file_lock);
2863         file = fcheck_files(files, fd);
2864         if (!file)
2865                 err = -EBADF;
2866         else
2867                 get_file(file);
2868         spin_unlock(&files->file_lock);
2869         put_files_struct(files);
2870
2871         if (err)
2872                 goto out;
2873
2874         if (file->f_op == &bpf_raw_tp_fops) {
2875                 struct bpf_raw_tracepoint *raw_tp = file->private_data;
2876                 struct bpf_raw_event_map *btp = raw_tp->btp;
2877
2878                 err = bpf_task_fd_query_copy(attr, uattr,
2879                                              raw_tp->prog->aux->id,
2880                                              BPF_FD_TYPE_RAW_TRACEPOINT,
2881                                              btp->tp->name, 0, 0);
2882                 goto put_file;
2883         }
2884
2885         event = perf_get_event(file);
2886         if (!IS_ERR(event)) {
2887                 u64 probe_offset, probe_addr;
2888                 u32 prog_id, fd_type;
2889                 const char *buf;
2890
2891                 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
2892                                               &buf, &probe_offset,
2893                                               &probe_addr);
2894                 if (!err)
2895                         err = bpf_task_fd_query_copy(attr, uattr, prog_id,
2896                                                      fd_type, buf,
2897                                                      probe_offset,
2898                                                      probe_addr);
2899                 goto put_file;
2900         }
2901
2902         err = -ENOTSUPP;
2903 put_file:
2904         fput(file);
2905 out:
2906         return err;
2907 }
2908
2909 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
2910 {
2911         union bpf_attr attr = {};
2912         int err;
2913
2914         if (sysctl_unprivileged_bpf_disabled && !capable(CAP_SYS_ADMIN))
2915                 return -EPERM;
2916
2917         err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
2918         if (err)
2919                 return err;
2920         size = min_t(u32, size, sizeof(attr));
2921
2922         /* copy attributes from user space, may be less than sizeof(bpf_attr) */
2923         if (copy_from_user(&attr, uattr, size) != 0)
2924                 return -EFAULT;
2925
2926         err = security_bpf(cmd, &attr, size);
2927         if (err < 0)
2928                 return err;
2929
2930         switch (cmd) {
2931         case BPF_MAP_CREATE:
2932                 err = map_create(&attr);
2933                 break;
2934         case BPF_MAP_LOOKUP_ELEM:
2935                 err = map_lookup_elem(&attr);
2936                 break;
2937         case BPF_MAP_UPDATE_ELEM:
2938                 err = map_update_elem(&attr);
2939                 break;
2940         case BPF_MAP_DELETE_ELEM:
2941                 err = map_delete_elem(&attr);
2942                 break;
2943         case BPF_MAP_GET_NEXT_KEY:
2944                 err = map_get_next_key(&attr);
2945                 break;
2946         case BPF_MAP_FREEZE:
2947                 err = map_freeze(&attr);
2948                 break;
2949         case BPF_PROG_LOAD:
2950                 err = bpf_prog_load(&attr, uattr);
2951                 break;
2952         case BPF_OBJ_PIN:
2953                 err = bpf_obj_pin(&attr);
2954                 break;
2955         case BPF_OBJ_GET:
2956                 err = bpf_obj_get(&attr);
2957                 break;
2958         case BPF_PROG_ATTACH:
2959                 err = bpf_prog_attach(&attr);
2960                 break;
2961         case BPF_PROG_DETACH:
2962                 err = bpf_prog_detach(&attr);
2963                 break;
2964         case BPF_PROG_QUERY:
2965                 err = bpf_prog_query(&attr, uattr);
2966                 break;
2967         case BPF_PROG_TEST_RUN:
2968                 err = bpf_prog_test_run(&attr, uattr);
2969                 break;
2970         case BPF_PROG_GET_NEXT_ID:
2971                 err = bpf_obj_get_next_id(&attr, uattr,
2972                                           &prog_idr, &prog_idr_lock);
2973                 break;
2974         case BPF_MAP_GET_NEXT_ID:
2975                 err = bpf_obj_get_next_id(&attr, uattr,
2976                                           &map_idr, &map_idr_lock);
2977                 break;
2978         case BPF_BTF_GET_NEXT_ID:
2979                 err = bpf_obj_get_next_id(&attr, uattr,
2980                                           &btf_idr, &btf_idr_lock);
2981                 break;
2982         case BPF_PROG_GET_FD_BY_ID:
2983                 err = bpf_prog_get_fd_by_id(&attr);
2984                 break;
2985         case BPF_MAP_GET_FD_BY_ID:
2986                 err = bpf_map_get_fd_by_id(&attr);
2987                 break;
2988         case BPF_OBJ_GET_INFO_BY_FD:
2989                 err = bpf_obj_get_info_by_fd(&attr, uattr);
2990                 break;
2991         case BPF_RAW_TRACEPOINT_OPEN:
2992                 err = bpf_raw_tracepoint_open(&attr);
2993                 break;
2994         case BPF_BTF_LOAD:
2995                 err = bpf_btf_load(&attr);
2996                 break;
2997         case BPF_BTF_GET_FD_BY_ID:
2998                 err = bpf_btf_get_fd_by_id(&attr);
2999                 break;
3000         case BPF_TASK_FD_QUERY:
3001                 err = bpf_task_fd_query(&attr, uattr);
3002                 break;
3003         case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
3004                 err = map_lookup_and_delete_elem(&attr);
3005                 break;
3006         default:
3007                 err = -EINVAL;
3008                 break;
3009         }
3010
3011         return err;
3012 }