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