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