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