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