GNU Linux-libre 5.10.215-gnu1
[releases.git] / kernel / bpf / syscall.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #include <linux/bpf.h>
5 #include <linux/bpf_trace.h>
6 #include <linux/bpf_lirc.h>
7 #include <linux/bpf_verifier.h>
8 #include <linux/btf.h>
9 #include <linux/syscalls.h>
10 #include <linux/slab.h>
11 #include <linux/sched/signal.h>
12 #include <linux/vmalloc.h>
13 #include <linux/mmzone.h>
14 #include <linux/anon_inodes.h>
15 #include <linux/fdtable.h>
16 #include <linux/file.h>
17 #include <linux/fs.h>
18 #include <linux/license.h>
19 #include <linux/filter.h>
20 #include <linux/version.h>
21 #include <linux/kernel.h>
22 #include <linux/idr.h>
23 #include <linux/cred.h>
24 #include <linux/timekeeping.h>
25 #include <linux/ctype.h>
26 #include <linux/nospec.h>
27 #include <linux/audit.h>
28 #include <uapi/linux/btf.h>
29 #include <linux/pgtable.h>
30 #include <linux/bpf_lsm.h>
31 #include <linux/poll.h>
32 #include <linux/bpf-netns.h>
33 #include <linux/rcupdate_trace.h>
34
35 #define IS_FD_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY || \
36                           (map)->map_type == BPF_MAP_TYPE_CGROUP_ARRAY || \
37                           (map)->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
38 #define IS_FD_PROG_ARRAY(map) ((map)->map_type == BPF_MAP_TYPE_PROG_ARRAY)
39 #define IS_FD_HASH(map) ((map)->map_type == BPF_MAP_TYPE_HASH_OF_MAPS)
40 #define IS_FD_MAP(map) (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map) || \
41                         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 static DEFINE_IDR(link_idr);
51 static DEFINE_SPINLOCK(link_idr_lock);
52
53 int sysctl_unprivileged_bpf_disabled __read_mostly =
54         IS_BUILTIN(CONFIG_BPF_UNPRIV_DEFAULT_OFF) ? 2 : 0;
55
56 static const struct bpf_map_ops * const bpf_map_types[] = {
57 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
58 #define BPF_MAP_TYPE(_id, _ops) \
59         [_id] = &_ops,
60 #define BPF_LINK_TYPE(_id, _name)
61 #include <linux/bpf_types.h>
62 #undef BPF_PROG_TYPE
63 #undef BPF_MAP_TYPE
64 #undef BPF_LINK_TYPE
65 };
66
67 /*
68  * If we're handed a bigger struct than we know of, ensure all the unknown bits
69  * are 0 - i.e. new user-space does not rely on any kernel feature extensions
70  * we don't know about yet.
71  *
72  * There is a ToCToU between this function call and the following
73  * copy_from_user() call. However, this is not a concern since this function is
74  * meant to be a future-proofing of bits.
75  */
76 int bpf_check_uarg_tail_zero(void __user *uaddr,
77                              size_t expected_size,
78                              size_t actual_size)
79 {
80         unsigned char __user *addr = uaddr + expected_size;
81         int res;
82
83         if (unlikely(actual_size > PAGE_SIZE))  /* silly large */
84                 return -E2BIG;
85
86         if (actual_size <= expected_size)
87                 return 0;
88
89         res = check_zeroed_user(addr, actual_size - expected_size);
90         if (res < 0)
91                 return res;
92         return res ? 0 : -E2BIG;
93 }
94
95 const struct bpf_map_ops bpf_map_offload_ops = {
96         .map_meta_equal = bpf_map_meta_equal,
97         .map_alloc = bpf_map_offload_map_alloc,
98         .map_free = bpf_map_offload_map_free,
99         .map_check_btf = map_check_no_btf,
100 };
101
102 static struct bpf_map *find_and_alloc_map(union bpf_attr *attr)
103 {
104         const struct bpf_map_ops *ops;
105         u32 type = attr->map_type;
106         struct bpf_map *map;
107         int err;
108
109         if (type >= ARRAY_SIZE(bpf_map_types))
110                 return ERR_PTR(-EINVAL);
111         type = array_index_nospec(type, ARRAY_SIZE(bpf_map_types));
112         ops = bpf_map_types[type];
113         if (!ops)
114                 return ERR_PTR(-EINVAL);
115
116         if (ops->map_alloc_check) {
117                 err = ops->map_alloc_check(attr);
118                 if (err)
119                         return ERR_PTR(err);
120         }
121         if (attr->map_ifindex)
122                 ops = &bpf_map_offload_ops;
123         map = ops->map_alloc(attr);
124         if (IS_ERR(map))
125                 return map;
126         map->ops = ops;
127         map->map_type = type;
128         return map;
129 }
130
131 static void bpf_map_write_active_inc(struct bpf_map *map)
132 {
133         atomic64_inc(&map->writecnt);
134 }
135
136 static void bpf_map_write_active_dec(struct bpf_map *map)
137 {
138         atomic64_dec(&map->writecnt);
139 }
140
141 bool bpf_map_write_active(const struct bpf_map *map)
142 {
143         return atomic64_read(&map->writecnt) != 0;
144 }
145
146 static u32 bpf_map_value_size(struct bpf_map *map)
147 {
148         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
149             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
150             map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
151             map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
152                 return round_up(map->value_size, 8) * num_possible_cpus();
153         else if (IS_FD_MAP(map))
154                 return sizeof(u32);
155         else
156                 return  map->value_size;
157 }
158
159 static void maybe_wait_bpf_programs(struct bpf_map *map)
160 {
161         /* Wait for any running BPF programs to complete so that
162          * userspace, when we return to it, knows that all programs
163          * that could be running use the new map value.
164          */
165         if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS ||
166             map->map_type == BPF_MAP_TYPE_ARRAY_OF_MAPS)
167                 synchronize_rcu();
168 }
169
170 static int bpf_map_update_value(struct bpf_map *map, struct fd f, void *key,
171                                 void *value, __u64 flags)
172 {
173         int err;
174
175         /* Need to create a kthread, thus must support schedule */
176         if (bpf_map_is_dev_bound(map)) {
177                 return bpf_map_offload_update_elem(map, key, value, flags);
178         } else if (map->map_type == BPF_MAP_TYPE_CPUMAP ||
179                    map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
180                 return map->ops->map_update_elem(map, key, value, flags);
181         } else if (map->map_type == BPF_MAP_TYPE_SOCKHASH ||
182                    map->map_type == BPF_MAP_TYPE_SOCKMAP) {
183                 return sock_map_update_elem_sys(map, key, value, flags);
184         } else if (IS_FD_PROG_ARRAY(map)) {
185                 return bpf_fd_array_map_update_elem(map, f.file, key, value,
186                                                     flags);
187         }
188
189         bpf_disable_instrumentation();
190         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
191             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
192                 err = bpf_percpu_hash_update(map, key, value, flags);
193         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
194                 err = bpf_percpu_array_update(map, key, value, flags);
195         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
196                 err = bpf_percpu_cgroup_storage_update(map, key, value,
197                                                        flags);
198         } else if (IS_FD_ARRAY(map)) {
199                 rcu_read_lock();
200                 err = bpf_fd_array_map_update_elem(map, f.file, key, value,
201                                                    flags);
202                 rcu_read_unlock();
203         } else if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
204                 rcu_read_lock();
205                 err = bpf_fd_htab_map_update_elem(map, f.file, key, value,
206                                                   flags);
207                 rcu_read_unlock();
208         } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
209                 /* rcu_read_lock() is not needed */
210                 err = bpf_fd_reuseport_array_update_elem(map, key, value,
211                                                          flags);
212         } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
213                    map->map_type == BPF_MAP_TYPE_STACK) {
214                 err = map->ops->map_push_elem(map, value, flags);
215         } else {
216                 rcu_read_lock();
217                 err = map->ops->map_update_elem(map, key, value, flags);
218                 rcu_read_unlock();
219         }
220         bpf_enable_instrumentation();
221         maybe_wait_bpf_programs(map);
222
223         return err;
224 }
225
226 static int bpf_map_copy_value(struct bpf_map *map, void *key, void *value,
227                               __u64 flags)
228 {
229         void *ptr;
230         int err;
231
232         if (bpf_map_is_dev_bound(map))
233                 return bpf_map_offload_lookup_elem(map, key, value);
234
235         bpf_disable_instrumentation();
236         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
237             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
238                 err = bpf_percpu_hash_copy(map, key, value);
239         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY) {
240                 err = bpf_percpu_array_copy(map, key, value);
241         } else if (map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) {
242                 err = bpf_percpu_cgroup_storage_copy(map, key, value);
243         } else if (map->map_type == BPF_MAP_TYPE_STACK_TRACE) {
244                 err = bpf_stackmap_copy(map, key, value);
245         } else if (IS_FD_ARRAY(map) || IS_FD_PROG_ARRAY(map)) {
246                 err = bpf_fd_array_map_lookup_elem(map, key, value);
247         } else if (IS_FD_HASH(map)) {
248                 err = bpf_fd_htab_map_lookup_elem(map, key, value);
249         } else if (map->map_type == BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) {
250                 err = bpf_fd_reuseport_array_lookup_elem(map, key, value);
251         } else if (map->map_type == BPF_MAP_TYPE_QUEUE ||
252                    map->map_type == BPF_MAP_TYPE_STACK) {
253                 err = map->ops->map_peek_elem(map, value);
254         } else if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
255                 /* struct_ops map requires directly updating "value" */
256                 err = bpf_struct_ops_map_sys_lookup_elem(map, key, value);
257         } else {
258                 rcu_read_lock();
259                 if (map->ops->map_lookup_elem_sys_only)
260                         ptr = map->ops->map_lookup_elem_sys_only(map, key);
261                 else
262                         ptr = map->ops->map_lookup_elem(map, key);
263                 if (IS_ERR(ptr)) {
264                         err = PTR_ERR(ptr);
265                 } else if (!ptr) {
266                         err = -ENOENT;
267                 } else {
268                         err = 0;
269                         if (flags & BPF_F_LOCK)
270                                 /* lock 'ptr' and copy everything but lock */
271                                 copy_map_value_locked(map, value, ptr, true);
272                         else
273                                 copy_map_value(map, value, ptr);
274                         /* mask lock, since value wasn't zero inited */
275                         check_and_init_map_lock(map, value);
276                 }
277                 rcu_read_unlock();
278         }
279
280         bpf_enable_instrumentation();
281         maybe_wait_bpf_programs(map);
282
283         return err;
284 }
285
286 static void *__bpf_map_area_alloc(u64 size, int numa_node, bool mmapable)
287 {
288         /* We really just want to fail instead of triggering OOM killer
289          * under memory pressure, therefore we set __GFP_NORETRY to kmalloc,
290          * which is used for lower order allocation requests.
291          *
292          * It has been observed that higher order allocation requests done by
293          * vmalloc with __GFP_NORETRY being set might fail due to not trying
294          * to reclaim memory from the page cache, thus we set
295          * __GFP_RETRY_MAYFAIL to avoid such situations.
296          */
297
298         const gfp_t gfp = __GFP_NOWARN | __GFP_ZERO;
299         unsigned int flags = 0;
300         unsigned long align = 1;
301         void *area;
302
303         if (size >= SIZE_MAX)
304                 return NULL;
305
306         /* kmalloc()'ed memory can't be mmap()'ed */
307         if (mmapable) {
308                 BUG_ON(!PAGE_ALIGNED(size));
309                 align = SHMLBA;
310                 flags = VM_USERMAP;
311         } else if (size <= (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER)) {
312                 area = kmalloc_node(size, gfp | GFP_USER | __GFP_NORETRY,
313                                     numa_node);
314                 if (area != NULL)
315                         return area;
316         }
317
318         return __vmalloc_node_range(size, align, VMALLOC_START, VMALLOC_END,
319                         gfp | GFP_KERNEL | __GFP_RETRY_MAYFAIL, PAGE_KERNEL,
320                         flags, numa_node, __builtin_return_address(0));
321 }
322
323 void *bpf_map_area_alloc(u64 size, int numa_node)
324 {
325         return __bpf_map_area_alloc(size, numa_node, false);
326 }
327
328 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node)
329 {
330         return __bpf_map_area_alloc(size, numa_node, true);
331 }
332
333 void bpf_map_area_free(void *area)
334 {
335         kvfree(area);
336 }
337
338 static u32 bpf_map_flags_retain_permanent(u32 flags)
339 {
340         /* Some map creation flags are not tied to the map object but
341          * rather to the map fd instead, so they have no meaning upon
342          * map object inspection since multiple file descriptors with
343          * different (access) properties can exist here. Thus, given
344          * this has zero meaning for the map itself, lets clear these
345          * from here.
346          */
347         return flags & ~(BPF_F_RDONLY | BPF_F_WRONLY);
348 }
349
350 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr)
351 {
352         map->map_type = attr->map_type;
353         map->key_size = attr->key_size;
354         map->value_size = attr->value_size;
355         map->max_entries = attr->max_entries;
356         map->map_flags = bpf_map_flags_retain_permanent(attr->map_flags);
357         map->numa_node = bpf_map_attr_numa_node(attr);
358 }
359
360 static int bpf_charge_memlock(struct user_struct *user, u32 pages)
361 {
362         unsigned long memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
363
364         if (atomic_long_add_return(pages, &user->locked_vm) > memlock_limit) {
365                 atomic_long_sub(pages, &user->locked_vm);
366                 return -EPERM;
367         }
368         return 0;
369 }
370
371 static void bpf_uncharge_memlock(struct user_struct *user, u32 pages)
372 {
373         if (user)
374                 atomic_long_sub(pages, &user->locked_vm);
375 }
376
377 int bpf_map_charge_init(struct bpf_map_memory *mem, u64 size)
378 {
379         u32 pages = round_up(size, PAGE_SIZE) >> PAGE_SHIFT;
380         struct user_struct *user;
381         int ret;
382
383         if (size >= U32_MAX - PAGE_SIZE)
384                 return -E2BIG;
385
386         user = get_current_user();
387         ret = bpf_charge_memlock(user, pages);
388         if (ret) {
389                 free_uid(user);
390                 return ret;
391         }
392
393         mem->pages = pages;
394         mem->user = user;
395
396         return 0;
397 }
398
399 void bpf_map_charge_finish(struct bpf_map_memory *mem)
400 {
401         bpf_uncharge_memlock(mem->user, mem->pages);
402         free_uid(mem->user);
403 }
404
405 void bpf_map_charge_move(struct bpf_map_memory *dst,
406                          struct bpf_map_memory *src)
407 {
408         *dst = *src;
409
410         /* Make sure src will not be used for the redundant uncharging. */
411         memset(src, 0, sizeof(struct bpf_map_memory));
412 }
413
414 int bpf_map_charge_memlock(struct bpf_map *map, u32 pages)
415 {
416         int ret;
417
418         ret = bpf_charge_memlock(map->memory.user, pages);
419         if (ret)
420                 return ret;
421         map->memory.pages += pages;
422         return ret;
423 }
424
425 void bpf_map_uncharge_memlock(struct bpf_map *map, u32 pages)
426 {
427         bpf_uncharge_memlock(map->memory.user, pages);
428         map->memory.pages -= pages;
429 }
430
431 static int bpf_map_alloc_id(struct bpf_map *map)
432 {
433         int id;
434
435         idr_preload(GFP_KERNEL);
436         spin_lock_bh(&map_idr_lock);
437         id = idr_alloc_cyclic(&map_idr, map, 1, INT_MAX, GFP_ATOMIC);
438         if (id > 0)
439                 map->id = id;
440         spin_unlock_bh(&map_idr_lock);
441         idr_preload_end();
442
443         if (WARN_ON_ONCE(!id))
444                 return -ENOSPC;
445
446         return id > 0 ? 0 : id;
447 }
448
449 void bpf_map_free_id(struct bpf_map *map, bool do_idr_lock)
450 {
451         unsigned long flags;
452
453         /* Offloaded maps are removed from the IDR store when their device
454          * disappears - even if someone holds an fd to them they are unusable,
455          * the memory is gone, all ops will fail; they are simply waiting for
456          * refcnt to drop to be freed.
457          */
458         if (!map->id)
459                 return;
460
461         if (do_idr_lock)
462                 spin_lock_irqsave(&map_idr_lock, flags);
463         else
464                 __acquire(&map_idr_lock);
465
466         idr_remove(&map_idr, map->id);
467         map->id = 0;
468
469         if (do_idr_lock)
470                 spin_unlock_irqrestore(&map_idr_lock, flags);
471         else
472                 __release(&map_idr_lock);
473 }
474
475 /* called from workqueue */
476 static void bpf_map_free_deferred(struct work_struct *work)
477 {
478         struct bpf_map *map = container_of(work, struct bpf_map, work);
479         struct bpf_map_memory mem;
480
481         bpf_map_charge_move(&mem, &map->memory);
482         security_bpf_map_free(map);
483         /* implementation dependent freeing */
484         map->ops->map_free(map);
485         bpf_map_charge_finish(&mem);
486 }
487
488 static void bpf_map_put_uref(struct bpf_map *map)
489 {
490         if (atomic64_dec_and_test(&map->usercnt)) {
491                 if (map->ops->map_release_uref)
492                         map->ops->map_release_uref(map);
493         }
494 }
495
496 static void bpf_map_free_in_work(struct bpf_map *map)
497 {
498         INIT_WORK(&map->work, bpf_map_free_deferred);
499         schedule_work(&map->work);
500 }
501
502 static void bpf_map_free_rcu_gp(struct rcu_head *rcu)
503 {
504         bpf_map_free_in_work(container_of(rcu, struct bpf_map, rcu));
505 }
506
507 static void bpf_map_free_mult_rcu_gp(struct rcu_head *rcu)
508 {
509         if (rcu_trace_implies_rcu_gp())
510                 bpf_map_free_rcu_gp(rcu);
511         else
512                 call_rcu(rcu, bpf_map_free_rcu_gp);
513 }
514
515 /* decrement map refcnt and schedule it for freeing via workqueue
516  * (unrelying map implementation ops->map_free() might sleep)
517  */
518 static void __bpf_map_put(struct bpf_map *map, bool do_idr_lock)
519 {
520         if (atomic64_dec_and_test(&map->refcnt)) {
521                 /* bpf_map_free_id() must be called first */
522                 bpf_map_free_id(map, do_idr_lock);
523                 btf_put(map->btf);
524
525                 if (READ_ONCE(map->free_after_mult_rcu_gp))
526                         call_rcu_tasks_trace(&map->rcu, bpf_map_free_mult_rcu_gp);
527                 else
528                         bpf_map_free_in_work(map);
529         }
530 }
531
532 void bpf_map_put(struct bpf_map *map)
533 {
534         __bpf_map_put(map, true);
535 }
536 EXPORT_SYMBOL_GPL(bpf_map_put);
537
538 void bpf_map_put_with_uref(struct bpf_map *map)
539 {
540         bpf_map_put_uref(map);
541         bpf_map_put(map);
542 }
543
544 static int bpf_map_release(struct inode *inode, struct file *filp)
545 {
546         struct bpf_map *map = filp->private_data;
547
548         if (map->ops->map_release)
549                 map->ops->map_release(map, filp);
550
551         bpf_map_put_with_uref(map);
552         return 0;
553 }
554
555 static fmode_t map_get_sys_perms(struct bpf_map *map, struct fd f)
556 {
557         fmode_t mode = f.file->f_mode;
558
559         /* Our file permissions may have been overridden by global
560          * map permissions facing syscall side.
561          */
562         if (READ_ONCE(map->frozen))
563                 mode &= ~FMODE_CAN_WRITE;
564         return mode;
565 }
566
567 #ifdef CONFIG_PROC_FS
568 static void bpf_map_show_fdinfo(struct seq_file *m, struct file *filp)
569 {
570         const struct bpf_map *map = filp->private_data;
571         const struct bpf_array *array;
572         u32 type = 0, jited = 0;
573
574         if (map->map_type == BPF_MAP_TYPE_PROG_ARRAY) {
575                 array = container_of(map, struct bpf_array, map);
576                 spin_lock(&array->aux->owner.lock);
577                 type  = array->aux->owner.type;
578                 jited = array->aux->owner.jited;
579                 spin_unlock(&array->aux->owner.lock);
580         }
581
582         seq_printf(m,
583                    "map_type:\t%u\n"
584                    "key_size:\t%u\n"
585                    "value_size:\t%u\n"
586                    "max_entries:\t%u\n"
587                    "map_flags:\t%#x\n"
588                    "memlock:\t%llu\n"
589                    "map_id:\t%u\n"
590                    "frozen:\t%u\n",
591                    map->map_type,
592                    map->key_size,
593                    map->value_size,
594                    map->max_entries,
595                    map->map_flags,
596                    map->memory.pages * 1ULL << PAGE_SHIFT,
597                    map->id,
598                    READ_ONCE(map->frozen));
599         if (type) {
600                 seq_printf(m, "owner_prog_type:\t%u\n", type);
601                 seq_printf(m, "owner_jited:\t%u\n", jited);
602         }
603 }
604 #endif
605
606 static ssize_t bpf_dummy_read(struct file *filp, char __user *buf, size_t siz,
607                               loff_t *ppos)
608 {
609         /* We need this handler such that alloc_file() enables
610          * f_mode with FMODE_CAN_READ.
611          */
612         return -EINVAL;
613 }
614
615 static ssize_t bpf_dummy_write(struct file *filp, const char __user *buf,
616                                size_t siz, loff_t *ppos)
617 {
618         /* We need this handler such that alloc_file() enables
619          * f_mode with FMODE_CAN_WRITE.
620          */
621         return -EINVAL;
622 }
623
624 /* called for any extra memory-mapped regions (except initial) */
625 static void bpf_map_mmap_open(struct vm_area_struct *vma)
626 {
627         struct bpf_map *map = vma->vm_file->private_data;
628
629         if (vma->vm_flags & VM_MAYWRITE)
630                 bpf_map_write_active_inc(map);
631 }
632
633 /* called for all unmapped memory region (including initial) */
634 static void bpf_map_mmap_close(struct vm_area_struct *vma)
635 {
636         struct bpf_map *map = vma->vm_file->private_data;
637
638         if (vma->vm_flags & VM_MAYWRITE)
639                 bpf_map_write_active_dec(map);
640 }
641
642 static const struct vm_operations_struct bpf_map_default_vmops = {
643         .open           = bpf_map_mmap_open,
644         .close          = bpf_map_mmap_close,
645 };
646
647 static int bpf_map_mmap(struct file *filp, struct vm_area_struct *vma)
648 {
649         struct bpf_map *map = filp->private_data;
650         int err;
651
652         if (!map->ops->map_mmap || map_value_has_spin_lock(map))
653                 return -ENOTSUPP;
654
655         if (!(vma->vm_flags & VM_SHARED))
656                 return -EINVAL;
657
658         mutex_lock(&map->freeze_mutex);
659
660         if (vma->vm_flags & VM_WRITE) {
661                 if (map->frozen) {
662                         err = -EPERM;
663                         goto out;
664                 }
665                 /* map is meant to be read-only, so do not allow mapping as
666                  * writable, because it's possible to leak a writable page
667                  * reference and allows user-space to still modify it after
668                  * freezing, while verifier will assume contents do not change
669                  */
670                 if (map->map_flags & BPF_F_RDONLY_PROG) {
671                         err = -EACCES;
672                         goto out;
673                 }
674         }
675
676         /* set default open/close callbacks */
677         vma->vm_ops = &bpf_map_default_vmops;
678         vma->vm_private_data = map;
679         vma->vm_flags &= ~VM_MAYEXEC;
680         if (!(vma->vm_flags & VM_WRITE))
681                 /* disallow re-mapping with PROT_WRITE */
682                 vma->vm_flags &= ~VM_MAYWRITE;
683
684         err = map->ops->map_mmap(map, vma);
685         if (err)
686                 goto out;
687
688         if (vma->vm_flags & VM_MAYWRITE)
689                 bpf_map_write_active_inc(map);
690 out:
691         mutex_unlock(&map->freeze_mutex);
692         return err;
693 }
694
695 static __poll_t bpf_map_poll(struct file *filp, struct poll_table_struct *pts)
696 {
697         struct bpf_map *map = filp->private_data;
698
699         if (map->ops->map_poll)
700                 return map->ops->map_poll(map, filp, pts);
701
702         return EPOLLERR;
703 }
704
705 const struct file_operations bpf_map_fops = {
706 #ifdef CONFIG_PROC_FS
707         .show_fdinfo    = bpf_map_show_fdinfo,
708 #endif
709         .release        = bpf_map_release,
710         .read           = bpf_dummy_read,
711         .write          = bpf_dummy_write,
712         .mmap           = bpf_map_mmap,
713         .poll           = bpf_map_poll,
714 };
715
716 int bpf_map_new_fd(struct bpf_map *map, int flags)
717 {
718         int ret;
719
720         ret = security_bpf_map(map, OPEN_FMODE(flags));
721         if (ret < 0)
722                 return ret;
723
724         return anon_inode_getfd("bpf-map", &bpf_map_fops, map,
725                                 flags | O_CLOEXEC);
726 }
727
728 int bpf_get_file_flag(int flags)
729 {
730         if ((flags & BPF_F_RDONLY) && (flags & BPF_F_WRONLY))
731                 return -EINVAL;
732         if (flags & BPF_F_RDONLY)
733                 return O_RDONLY;
734         if (flags & BPF_F_WRONLY)
735                 return O_WRONLY;
736         return O_RDWR;
737 }
738
739 /* helper macro to check that unused fields 'union bpf_attr' are zero */
740 #define CHECK_ATTR(CMD) \
741         memchr_inv((void *) &attr->CMD##_LAST_FIELD + \
742                    sizeof(attr->CMD##_LAST_FIELD), 0, \
743                    sizeof(*attr) - \
744                    offsetof(union bpf_attr, CMD##_LAST_FIELD) - \
745                    sizeof(attr->CMD##_LAST_FIELD)) != NULL
746
747 /* dst and src must have at least "size" number of bytes.
748  * Return strlen on success and < 0 on error.
749  */
750 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size)
751 {
752         const char *end = src + size;
753         const char *orig_src = src;
754
755         memset(dst, 0, size);
756         /* Copy all isalnum(), '_' and '.' chars. */
757         while (src < end && *src) {
758                 if (!isalnum(*src) &&
759                     *src != '_' && *src != '.')
760                         return -EINVAL;
761                 *dst++ = *src++;
762         }
763
764         /* No '\0' found in "size" number of bytes */
765         if (src == end)
766                 return -EINVAL;
767
768         return src - orig_src;
769 }
770
771 int map_check_no_btf(const struct bpf_map *map,
772                      const struct btf *btf,
773                      const struct btf_type *key_type,
774                      const struct btf_type *value_type)
775 {
776         return -ENOTSUPP;
777 }
778
779 static int map_check_btf(struct bpf_map *map, const struct btf *btf,
780                          u32 btf_key_id, u32 btf_value_id)
781 {
782         const struct btf_type *key_type, *value_type;
783         u32 key_size, value_size;
784         int ret = 0;
785
786         /* Some maps allow key to be unspecified. */
787         if (btf_key_id) {
788                 key_type = btf_type_id_size(btf, &btf_key_id, &key_size);
789                 if (!key_type || key_size != map->key_size)
790                         return -EINVAL;
791         } else {
792                 key_type = btf_type_by_id(btf, 0);
793                 if (!map->ops->map_check_btf)
794                         return -EINVAL;
795         }
796
797         value_type = btf_type_id_size(btf, &btf_value_id, &value_size);
798         if (!value_type || value_size != map->value_size)
799                 return -EINVAL;
800
801         map->spin_lock_off = btf_find_spin_lock(btf, value_type);
802
803         if (map_value_has_spin_lock(map)) {
804                 if (map->map_flags & BPF_F_RDONLY_PROG)
805                         return -EACCES;
806                 if (map->map_type != BPF_MAP_TYPE_HASH &&
807                     map->map_type != BPF_MAP_TYPE_ARRAY &&
808                     map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE &&
809                     map->map_type != BPF_MAP_TYPE_SK_STORAGE &&
810                     map->map_type != BPF_MAP_TYPE_INODE_STORAGE)
811                         return -ENOTSUPP;
812                 if (map->spin_lock_off + sizeof(struct bpf_spin_lock) >
813                     map->value_size) {
814                         WARN_ONCE(1,
815                                   "verifier bug spin_lock_off %d value_size %d\n",
816                                   map->spin_lock_off, map->value_size);
817                         return -EFAULT;
818                 }
819         }
820
821         if (map->ops->map_check_btf)
822                 ret = map->ops->map_check_btf(map, btf, key_type, value_type);
823
824         return ret;
825 }
826
827 #define BPF_MAP_CREATE_LAST_FIELD btf_vmlinux_value_type_id
828 /* called via syscall */
829 static int map_create(union bpf_attr *attr)
830 {
831         int numa_node = bpf_map_attr_numa_node(attr);
832         struct bpf_map_memory mem;
833         struct bpf_map *map;
834         int f_flags;
835         int err;
836
837         err = CHECK_ATTR(BPF_MAP_CREATE);
838         if (err)
839                 return -EINVAL;
840
841         if (attr->btf_vmlinux_value_type_id) {
842                 if (attr->map_type != BPF_MAP_TYPE_STRUCT_OPS ||
843                     attr->btf_key_type_id || attr->btf_value_type_id)
844                         return -EINVAL;
845         } else if (attr->btf_key_type_id && !attr->btf_value_type_id) {
846                 return -EINVAL;
847         }
848
849         f_flags = bpf_get_file_flag(attr->map_flags);
850         if (f_flags < 0)
851                 return f_flags;
852
853         if (numa_node != NUMA_NO_NODE &&
854             ((unsigned int)numa_node >= nr_node_ids ||
855              !node_online(numa_node)))
856                 return -EINVAL;
857
858         /* find map type and init map: hashtable vs rbtree vs bloom vs ... */
859         map = find_and_alloc_map(attr);
860         if (IS_ERR(map))
861                 return PTR_ERR(map);
862
863         err = bpf_obj_name_cpy(map->name, attr->map_name,
864                                sizeof(attr->map_name));
865         if (err < 0)
866                 goto free_map;
867
868         atomic64_set(&map->refcnt, 1);
869         atomic64_set(&map->usercnt, 1);
870         mutex_init(&map->freeze_mutex);
871
872         map->spin_lock_off = -EINVAL;
873         if (attr->btf_key_type_id || attr->btf_value_type_id ||
874             /* Even the map's value is a kernel's struct,
875              * the bpf_prog.o must have BTF to begin with
876              * to figure out the corresponding kernel's
877              * counter part.  Thus, attr->btf_fd has
878              * to be valid also.
879              */
880             attr->btf_vmlinux_value_type_id) {
881                 struct btf *btf;
882
883                 btf = btf_get_by_fd(attr->btf_fd);
884                 if (IS_ERR(btf)) {
885                         err = PTR_ERR(btf);
886                         goto free_map;
887                 }
888                 map->btf = btf;
889
890                 if (attr->btf_value_type_id) {
891                         err = map_check_btf(map, btf, attr->btf_key_type_id,
892                                             attr->btf_value_type_id);
893                         if (err)
894                                 goto free_map;
895                 }
896
897                 map->btf_key_type_id = attr->btf_key_type_id;
898                 map->btf_value_type_id = attr->btf_value_type_id;
899                 map->btf_vmlinux_value_type_id =
900                         attr->btf_vmlinux_value_type_id;
901         }
902
903         err = security_bpf_map_alloc(map);
904         if (err)
905                 goto free_map;
906
907         err = bpf_map_alloc_id(map);
908         if (err)
909                 goto free_map_sec;
910
911         err = bpf_map_new_fd(map, f_flags);
912         if (err < 0) {
913                 /* failed to allocate fd.
914                  * bpf_map_put_with_uref() is needed because the above
915                  * bpf_map_alloc_id() has published the map
916                  * to the userspace and the userspace may
917                  * have refcnt-ed it through BPF_MAP_GET_FD_BY_ID.
918                  */
919                 bpf_map_put_with_uref(map);
920                 return err;
921         }
922
923         return err;
924
925 free_map_sec:
926         security_bpf_map_free(map);
927 free_map:
928         btf_put(map->btf);
929         bpf_map_charge_move(&mem, &map->memory);
930         map->ops->map_free(map);
931         bpf_map_charge_finish(&mem);
932         return err;
933 }
934
935 /* if error is returned, fd is released.
936  * On success caller should complete fd access with matching fdput()
937  */
938 struct bpf_map *__bpf_map_get(struct fd f)
939 {
940         if (!f.file)
941                 return ERR_PTR(-EBADF);
942         if (f.file->f_op != &bpf_map_fops) {
943                 fdput(f);
944                 return ERR_PTR(-EINVAL);
945         }
946
947         return f.file->private_data;
948 }
949
950 void bpf_map_inc(struct bpf_map *map)
951 {
952         atomic64_inc(&map->refcnt);
953 }
954 EXPORT_SYMBOL_GPL(bpf_map_inc);
955
956 void bpf_map_inc_with_uref(struct bpf_map *map)
957 {
958         atomic64_inc(&map->refcnt);
959         atomic64_inc(&map->usercnt);
960 }
961 EXPORT_SYMBOL_GPL(bpf_map_inc_with_uref);
962
963 struct bpf_map *bpf_map_get(u32 ufd)
964 {
965         struct fd f = fdget(ufd);
966         struct bpf_map *map;
967
968         map = __bpf_map_get(f);
969         if (IS_ERR(map))
970                 return map;
971
972         bpf_map_inc(map);
973         fdput(f);
974
975         return map;
976 }
977
978 struct bpf_map *bpf_map_get_with_uref(u32 ufd)
979 {
980         struct fd f = fdget(ufd);
981         struct bpf_map *map;
982
983         map = __bpf_map_get(f);
984         if (IS_ERR(map))
985                 return map;
986
987         bpf_map_inc_with_uref(map);
988         fdput(f);
989
990         return map;
991 }
992
993 /* map_idr_lock should have been held */
994 static struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref)
995 {
996         int refold;
997
998         refold = atomic64_fetch_add_unless(&map->refcnt, 1, 0);
999         if (!refold)
1000                 return ERR_PTR(-ENOENT);
1001         if (uref)
1002                 atomic64_inc(&map->usercnt);
1003
1004         return map;
1005 }
1006
1007 struct bpf_map *bpf_map_inc_not_zero(struct bpf_map *map)
1008 {
1009         spin_lock_bh(&map_idr_lock);
1010         map = __bpf_map_inc_not_zero(map, false);
1011         spin_unlock_bh(&map_idr_lock);
1012
1013         return map;
1014 }
1015 EXPORT_SYMBOL_GPL(bpf_map_inc_not_zero);
1016
1017 int __weak bpf_stackmap_copy(struct bpf_map *map, void *key, void *value)
1018 {
1019         return -ENOTSUPP;
1020 }
1021
1022 static void *__bpf_copy_key(void __user *ukey, u64 key_size)
1023 {
1024         if (key_size)
1025                 return memdup_user(ukey, key_size);
1026
1027         if (ukey)
1028                 return ERR_PTR(-EINVAL);
1029
1030         return NULL;
1031 }
1032
1033 /* last field in 'union bpf_attr' used by this command */
1034 #define BPF_MAP_LOOKUP_ELEM_LAST_FIELD flags
1035
1036 static int map_lookup_elem(union bpf_attr *attr)
1037 {
1038         void __user *ukey = u64_to_user_ptr(attr->key);
1039         void __user *uvalue = u64_to_user_ptr(attr->value);
1040         int ufd = attr->map_fd;
1041         struct bpf_map *map;
1042         void *key, *value;
1043         u32 value_size;
1044         struct fd f;
1045         int err;
1046
1047         if (CHECK_ATTR(BPF_MAP_LOOKUP_ELEM))
1048                 return -EINVAL;
1049
1050         if (attr->flags & ~BPF_F_LOCK)
1051                 return -EINVAL;
1052
1053         f = fdget(ufd);
1054         map = __bpf_map_get(f);
1055         if (IS_ERR(map))
1056                 return PTR_ERR(map);
1057         if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1058                 err = -EPERM;
1059                 goto err_put;
1060         }
1061
1062         if ((attr->flags & BPF_F_LOCK) &&
1063             !map_value_has_spin_lock(map)) {
1064                 err = -EINVAL;
1065                 goto err_put;
1066         }
1067
1068         key = __bpf_copy_key(ukey, map->key_size);
1069         if (IS_ERR(key)) {
1070                 err = PTR_ERR(key);
1071                 goto err_put;
1072         }
1073
1074         value_size = bpf_map_value_size(map);
1075
1076         err = -ENOMEM;
1077         value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
1078         if (!value)
1079                 goto free_key;
1080
1081         err = bpf_map_copy_value(map, key, value, attr->flags);
1082         if (err)
1083                 goto free_value;
1084
1085         err = -EFAULT;
1086         if (copy_to_user(uvalue, value, value_size) != 0)
1087                 goto free_value;
1088
1089         err = 0;
1090
1091 free_value:
1092         kfree(value);
1093 free_key:
1094         kfree(key);
1095 err_put:
1096         fdput(f);
1097         return err;
1098 }
1099
1100
1101 #define BPF_MAP_UPDATE_ELEM_LAST_FIELD flags
1102
1103 static int map_update_elem(union bpf_attr *attr)
1104 {
1105         void __user *ukey = u64_to_user_ptr(attr->key);
1106         void __user *uvalue = u64_to_user_ptr(attr->value);
1107         int ufd = attr->map_fd;
1108         struct bpf_map *map;
1109         void *key, *value;
1110         u32 value_size;
1111         struct fd f;
1112         int err;
1113
1114         if (CHECK_ATTR(BPF_MAP_UPDATE_ELEM))
1115                 return -EINVAL;
1116
1117         f = fdget(ufd);
1118         map = __bpf_map_get(f);
1119         if (IS_ERR(map))
1120                 return PTR_ERR(map);
1121         bpf_map_write_active_inc(map);
1122         if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1123                 err = -EPERM;
1124                 goto err_put;
1125         }
1126
1127         if ((attr->flags & BPF_F_LOCK) &&
1128             !map_value_has_spin_lock(map)) {
1129                 err = -EINVAL;
1130                 goto err_put;
1131         }
1132
1133         key = __bpf_copy_key(ukey, map->key_size);
1134         if (IS_ERR(key)) {
1135                 err = PTR_ERR(key);
1136                 goto err_put;
1137         }
1138
1139         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
1140             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
1141             map->map_type == BPF_MAP_TYPE_PERCPU_ARRAY ||
1142             map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE)
1143                 value_size = round_up(map->value_size, 8) * num_possible_cpus();
1144         else
1145                 value_size = map->value_size;
1146
1147         err = -ENOMEM;
1148         value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
1149         if (!value)
1150                 goto free_key;
1151
1152         err = -EFAULT;
1153         if (copy_from_user(value, uvalue, value_size) != 0)
1154                 goto free_value;
1155
1156         err = bpf_map_update_value(map, f, key, value, attr->flags);
1157
1158 free_value:
1159         kfree(value);
1160 free_key:
1161         kfree(key);
1162 err_put:
1163         bpf_map_write_active_dec(map);
1164         fdput(f);
1165         return err;
1166 }
1167
1168 #define BPF_MAP_DELETE_ELEM_LAST_FIELD key
1169
1170 static int map_delete_elem(union bpf_attr *attr)
1171 {
1172         void __user *ukey = u64_to_user_ptr(attr->key);
1173         int ufd = attr->map_fd;
1174         struct bpf_map *map;
1175         struct fd f;
1176         void *key;
1177         int err;
1178
1179         if (CHECK_ATTR(BPF_MAP_DELETE_ELEM))
1180                 return -EINVAL;
1181
1182         f = fdget(ufd);
1183         map = __bpf_map_get(f);
1184         if (IS_ERR(map))
1185                 return PTR_ERR(map);
1186         bpf_map_write_active_inc(map);
1187         if (!(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1188                 err = -EPERM;
1189                 goto err_put;
1190         }
1191
1192         key = __bpf_copy_key(ukey, map->key_size);
1193         if (IS_ERR(key)) {
1194                 err = PTR_ERR(key);
1195                 goto err_put;
1196         }
1197
1198         if (bpf_map_is_dev_bound(map)) {
1199                 err = bpf_map_offload_delete_elem(map, key);
1200                 goto out;
1201         } else if (IS_FD_PROG_ARRAY(map) ||
1202                    map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1203                 /* These maps require sleepable context */
1204                 err = map->ops->map_delete_elem(map, key);
1205                 goto out;
1206         }
1207
1208         bpf_disable_instrumentation();
1209         rcu_read_lock();
1210         err = map->ops->map_delete_elem(map, key);
1211         rcu_read_unlock();
1212         bpf_enable_instrumentation();
1213         maybe_wait_bpf_programs(map);
1214 out:
1215         kfree(key);
1216 err_put:
1217         bpf_map_write_active_dec(map);
1218         fdput(f);
1219         return err;
1220 }
1221
1222 /* last field in 'union bpf_attr' used by this command */
1223 #define BPF_MAP_GET_NEXT_KEY_LAST_FIELD next_key
1224
1225 static int map_get_next_key(union bpf_attr *attr)
1226 {
1227         void __user *ukey = u64_to_user_ptr(attr->key);
1228         void __user *unext_key = u64_to_user_ptr(attr->next_key);
1229         int ufd = attr->map_fd;
1230         struct bpf_map *map;
1231         void *key, *next_key;
1232         struct fd f;
1233         int err;
1234
1235         if (CHECK_ATTR(BPF_MAP_GET_NEXT_KEY))
1236                 return -EINVAL;
1237
1238         f = fdget(ufd);
1239         map = __bpf_map_get(f);
1240         if (IS_ERR(map))
1241                 return PTR_ERR(map);
1242         if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
1243                 err = -EPERM;
1244                 goto err_put;
1245         }
1246
1247         if (ukey) {
1248                 key = __bpf_copy_key(ukey, map->key_size);
1249                 if (IS_ERR(key)) {
1250                         err = PTR_ERR(key);
1251                         goto err_put;
1252                 }
1253         } else {
1254                 key = NULL;
1255         }
1256
1257         err = -ENOMEM;
1258         next_key = kmalloc(map->key_size, GFP_USER);
1259         if (!next_key)
1260                 goto free_key;
1261
1262         if (bpf_map_is_dev_bound(map)) {
1263                 err = bpf_map_offload_get_next_key(map, key, next_key);
1264                 goto out;
1265         }
1266
1267         rcu_read_lock();
1268         err = map->ops->map_get_next_key(map, key, next_key);
1269         rcu_read_unlock();
1270 out:
1271         if (err)
1272                 goto free_next_key;
1273
1274         err = -EFAULT;
1275         if (copy_to_user(unext_key, next_key, map->key_size) != 0)
1276                 goto free_next_key;
1277
1278         err = 0;
1279
1280 free_next_key:
1281         kfree(next_key);
1282 free_key:
1283         kfree(key);
1284 err_put:
1285         fdput(f);
1286         return err;
1287 }
1288
1289 int generic_map_delete_batch(struct bpf_map *map,
1290                              const union bpf_attr *attr,
1291                              union bpf_attr __user *uattr)
1292 {
1293         void __user *keys = u64_to_user_ptr(attr->batch.keys);
1294         u32 cp, max_count;
1295         int err = 0;
1296         void *key;
1297
1298         if (attr->batch.elem_flags & ~BPF_F_LOCK)
1299                 return -EINVAL;
1300
1301         if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1302             !map_value_has_spin_lock(map)) {
1303                 return -EINVAL;
1304         }
1305
1306         max_count = attr->batch.count;
1307         if (!max_count)
1308                 return 0;
1309
1310         if (put_user(0, &uattr->batch.count))
1311                 return -EFAULT;
1312
1313         key = kmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1314         if (!key)
1315                 return -ENOMEM;
1316
1317         for (cp = 0; cp < max_count; cp++) {
1318                 err = -EFAULT;
1319                 if (copy_from_user(key, keys + cp * map->key_size,
1320                                    map->key_size))
1321                         break;
1322
1323                 if (bpf_map_is_dev_bound(map)) {
1324                         err = bpf_map_offload_delete_elem(map, key);
1325                         break;
1326                 }
1327
1328                 bpf_disable_instrumentation();
1329                 rcu_read_lock();
1330                 err = map->ops->map_delete_elem(map, key);
1331                 rcu_read_unlock();
1332                 bpf_enable_instrumentation();
1333                 maybe_wait_bpf_programs(map);
1334                 if (err)
1335                         break;
1336                 cond_resched();
1337         }
1338         if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1339                 err = -EFAULT;
1340
1341         kfree(key);
1342         return err;
1343 }
1344
1345 int generic_map_update_batch(struct bpf_map *map,
1346                              const union bpf_attr *attr,
1347                              union bpf_attr __user *uattr)
1348 {
1349         void __user *values = u64_to_user_ptr(attr->batch.values);
1350         void __user *keys = u64_to_user_ptr(attr->batch.keys);
1351         u32 value_size, cp, max_count;
1352         int ufd = attr->batch.map_fd;
1353         void *key, *value;
1354         struct fd f;
1355         int err = 0;
1356
1357         if (attr->batch.elem_flags & ~BPF_F_LOCK)
1358                 return -EINVAL;
1359
1360         if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1361             !map_value_has_spin_lock(map)) {
1362                 return -EINVAL;
1363         }
1364
1365         value_size = bpf_map_value_size(map);
1366
1367         max_count = attr->batch.count;
1368         if (!max_count)
1369                 return 0;
1370
1371         if (put_user(0, &uattr->batch.count))
1372                 return -EFAULT;
1373
1374         key = kmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1375         if (!key)
1376                 return -ENOMEM;
1377
1378         value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
1379         if (!value) {
1380                 kfree(key);
1381                 return -ENOMEM;
1382         }
1383
1384         f = fdget(ufd); /* bpf_map_do_batch() guarantees ufd is valid */
1385         for (cp = 0; cp < max_count; cp++) {
1386                 err = -EFAULT;
1387                 if (copy_from_user(key, keys + cp * map->key_size,
1388                     map->key_size) ||
1389                     copy_from_user(value, values + cp * value_size, value_size))
1390                         break;
1391
1392                 err = bpf_map_update_value(map, f, key, value,
1393                                            attr->batch.elem_flags);
1394
1395                 if (err)
1396                         break;
1397                 cond_resched();
1398         }
1399
1400         if (copy_to_user(&uattr->batch.count, &cp, sizeof(cp)))
1401                 err = -EFAULT;
1402
1403         kfree(value);
1404         kfree(key);
1405         fdput(f);
1406         return err;
1407 }
1408
1409 #define MAP_LOOKUP_RETRIES 3
1410
1411 int generic_map_lookup_batch(struct bpf_map *map,
1412                                     const union bpf_attr *attr,
1413                                     union bpf_attr __user *uattr)
1414 {
1415         void __user *uobatch = u64_to_user_ptr(attr->batch.out_batch);
1416         void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1417         void __user *values = u64_to_user_ptr(attr->batch.values);
1418         void __user *keys = u64_to_user_ptr(attr->batch.keys);
1419         void *buf, *buf_prevkey, *prev_key, *key, *value;
1420         int err, retry = MAP_LOOKUP_RETRIES;
1421         u32 value_size, cp, max_count;
1422
1423         if (attr->batch.elem_flags & ~BPF_F_LOCK)
1424                 return -EINVAL;
1425
1426         if ((attr->batch.elem_flags & BPF_F_LOCK) &&
1427             !map_value_has_spin_lock(map))
1428                 return -EINVAL;
1429
1430         value_size = bpf_map_value_size(map);
1431
1432         max_count = attr->batch.count;
1433         if (!max_count)
1434                 return 0;
1435
1436         if (put_user(0, &uattr->batch.count))
1437                 return -EFAULT;
1438
1439         buf_prevkey = kmalloc(map->key_size, GFP_USER | __GFP_NOWARN);
1440         if (!buf_prevkey)
1441                 return -ENOMEM;
1442
1443         buf = kmalloc(map->key_size + value_size, GFP_USER | __GFP_NOWARN);
1444         if (!buf) {
1445                 kfree(buf_prevkey);
1446                 return -ENOMEM;
1447         }
1448
1449         err = -EFAULT;
1450         prev_key = NULL;
1451         if (ubatch && copy_from_user(buf_prevkey, ubatch, map->key_size))
1452                 goto free_buf;
1453         key = buf;
1454         value = key + map->key_size;
1455         if (ubatch)
1456                 prev_key = buf_prevkey;
1457
1458         for (cp = 0; cp < max_count;) {
1459                 rcu_read_lock();
1460                 err = map->ops->map_get_next_key(map, prev_key, key);
1461                 rcu_read_unlock();
1462                 if (err)
1463                         break;
1464                 err = bpf_map_copy_value(map, key, value,
1465                                          attr->batch.elem_flags);
1466
1467                 if (err == -ENOENT) {
1468                         if (retry) {
1469                                 retry--;
1470                                 continue;
1471                         }
1472                         err = -EINTR;
1473                         break;
1474                 }
1475
1476                 if (err)
1477                         goto free_buf;
1478
1479                 if (copy_to_user(keys + cp * map->key_size, key,
1480                                  map->key_size)) {
1481                         err = -EFAULT;
1482                         goto free_buf;
1483                 }
1484                 if (copy_to_user(values + cp * value_size, value, value_size)) {
1485                         err = -EFAULT;
1486                         goto free_buf;
1487                 }
1488
1489                 if (!prev_key)
1490                         prev_key = buf_prevkey;
1491
1492                 swap(prev_key, key);
1493                 retry = MAP_LOOKUP_RETRIES;
1494                 cp++;
1495                 cond_resched();
1496         }
1497
1498         if (err == -EFAULT)
1499                 goto free_buf;
1500
1501         if ((copy_to_user(&uattr->batch.count, &cp, sizeof(cp)) ||
1502                     (cp && copy_to_user(uobatch, prev_key, map->key_size))))
1503                 err = -EFAULT;
1504
1505 free_buf:
1506         kfree(buf_prevkey);
1507         kfree(buf);
1508         return err;
1509 }
1510
1511 #define BPF_MAP_LOOKUP_AND_DELETE_ELEM_LAST_FIELD value
1512
1513 static int map_lookup_and_delete_elem(union bpf_attr *attr)
1514 {
1515         void __user *ukey = u64_to_user_ptr(attr->key);
1516         void __user *uvalue = u64_to_user_ptr(attr->value);
1517         int ufd = attr->map_fd;
1518         struct bpf_map *map;
1519         void *key, *value;
1520         u32 value_size;
1521         struct fd f;
1522         int err;
1523
1524         if (CHECK_ATTR(BPF_MAP_LOOKUP_AND_DELETE_ELEM))
1525                 return -EINVAL;
1526
1527         f = fdget(ufd);
1528         map = __bpf_map_get(f);
1529         if (IS_ERR(map))
1530                 return PTR_ERR(map);
1531         bpf_map_write_active_inc(map);
1532         if (!(map_get_sys_perms(map, f) & FMODE_CAN_READ) ||
1533             !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
1534                 err = -EPERM;
1535                 goto err_put;
1536         }
1537
1538         key = __bpf_copy_key(ukey, map->key_size);
1539         if (IS_ERR(key)) {
1540                 err = PTR_ERR(key);
1541                 goto err_put;
1542         }
1543
1544         value_size = map->value_size;
1545
1546         err = -ENOMEM;
1547         value = kmalloc(value_size, GFP_USER | __GFP_NOWARN);
1548         if (!value)
1549                 goto free_key;
1550
1551         if (map->map_type == BPF_MAP_TYPE_QUEUE ||
1552             map->map_type == BPF_MAP_TYPE_STACK) {
1553                 err = map->ops->map_pop_elem(map, value);
1554         } else {
1555                 err = -ENOTSUPP;
1556         }
1557
1558         if (err)
1559                 goto free_value;
1560
1561         if (copy_to_user(uvalue, value, value_size) != 0) {
1562                 err = -EFAULT;
1563                 goto free_value;
1564         }
1565
1566         err = 0;
1567
1568 free_value:
1569         kfree(value);
1570 free_key:
1571         kfree(key);
1572 err_put:
1573         bpf_map_write_active_dec(map);
1574         fdput(f);
1575         return err;
1576 }
1577
1578 #define BPF_MAP_FREEZE_LAST_FIELD map_fd
1579
1580 static int map_freeze(const union bpf_attr *attr)
1581 {
1582         int err = 0, ufd = attr->map_fd;
1583         struct bpf_map *map;
1584         struct fd f;
1585
1586         if (CHECK_ATTR(BPF_MAP_FREEZE))
1587                 return -EINVAL;
1588
1589         f = fdget(ufd);
1590         map = __bpf_map_get(f);
1591         if (IS_ERR(map))
1592                 return PTR_ERR(map);
1593
1594         if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) {
1595                 fdput(f);
1596                 return -ENOTSUPP;
1597         }
1598
1599         mutex_lock(&map->freeze_mutex);
1600         if (bpf_map_write_active(map)) {
1601                 err = -EBUSY;
1602                 goto err_put;
1603         }
1604         if (READ_ONCE(map->frozen)) {
1605                 err = -EBUSY;
1606                 goto err_put;
1607         }
1608         if (!bpf_capable()) {
1609                 err = -EPERM;
1610                 goto err_put;
1611         }
1612
1613         WRITE_ONCE(map->frozen, true);
1614 err_put:
1615         mutex_unlock(&map->freeze_mutex);
1616         fdput(f);
1617         return err;
1618 }
1619
1620 static const struct bpf_prog_ops * const bpf_prog_types[] = {
1621 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
1622         [_id] = & _name ## _prog_ops,
1623 #define BPF_MAP_TYPE(_id, _ops)
1624 #define BPF_LINK_TYPE(_id, _name)
1625 #include <linux/bpf_types.h>
1626 #undef BPF_PROG_TYPE
1627 #undef BPF_MAP_TYPE
1628 #undef BPF_LINK_TYPE
1629 };
1630
1631 static int find_prog_type(enum bpf_prog_type type, struct bpf_prog *prog)
1632 {
1633         const struct bpf_prog_ops *ops;
1634
1635         if (type >= ARRAY_SIZE(bpf_prog_types))
1636                 return -EINVAL;
1637         type = array_index_nospec(type, ARRAY_SIZE(bpf_prog_types));
1638         ops = bpf_prog_types[type];
1639         if (!ops)
1640                 return -EINVAL;
1641
1642         if (!bpf_prog_is_dev_bound(prog->aux))
1643                 prog->aux->ops = ops;
1644         else
1645                 prog->aux->ops = &bpf_offload_prog_ops;
1646         prog->type = type;
1647         return 0;
1648 }
1649
1650 enum bpf_audit {
1651         BPF_AUDIT_LOAD,
1652         BPF_AUDIT_UNLOAD,
1653         BPF_AUDIT_MAX,
1654 };
1655
1656 static const char * const bpf_audit_str[BPF_AUDIT_MAX] = {
1657         [BPF_AUDIT_LOAD]   = "LOAD",
1658         [BPF_AUDIT_UNLOAD] = "UNLOAD",
1659 };
1660
1661 static void bpf_audit_prog(const struct bpf_prog *prog, unsigned int op)
1662 {
1663         struct audit_context *ctx = NULL;
1664         struct audit_buffer *ab;
1665
1666         if (WARN_ON_ONCE(op >= BPF_AUDIT_MAX))
1667                 return;
1668         if (audit_enabled == AUDIT_OFF)
1669                 return;
1670         if (op == BPF_AUDIT_LOAD)
1671                 ctx = audit_context();
1672         ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_BPF);
1673         if (unlikely(!ab))
1674                 return;
1675         audit_log_format(ab, "prog-id=%u op=%s",
1676                          prog->aux->id, bpf_audit_str[op]);
1677         audit_log_end(ab);
1678 }
1679
1680 int __bpf_prog_charge(struct user_struct *user, u32 pages)
1681 {
1682         unsigned long memlock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1683         unsigned long user_bufs;
1684
1685         if (user) {
1686                 user_bufs = atomic_long_add_return(pages, &user->locked_vm);
1687                 if (user_bufs > memlock_limit) {
1688                         atomic_long_sub(pages, &user->locked_vm);
1689                         return -EPERM;
1690                 }
1691         }
1692
1693         return 0;
1694 }
1695
1696 void __bpf_prog_uncharge(struct user_struct *user, u32 pages)
1697 {
1698         if (user)
1699                 atomic_long_sub(pages, &user->locked_vm);
1700 }
1701
1702 static int bpf_prog_charge_memlock(struct bpf_prog *prog)
1703 {
1704         struct user_struct *user = get_current_user();
1705         int ret;
1706
1707         ret = __bpf_prog_charge(user, prog->pages);
1708         if (ret) {
1709                 free_uid(user);
1710                 return ret;
1711         }
1712
1713         prog->aux->user = user;
1714         return 0;
1715 }
1716
1717 static void bpf_prog_uncharge_memlock(struct bpf_prog *prog)
1718 {
1719         struct user_struct *user = prog->aux->user;
1720
1721         __bpf_prog_uncharge(user, prog->pages);
1722         free_uid(user);
1723 }
1724
1725 static int bpf_prog_alloc_id(struct bpf_prog *prog)
1726 {
1727         int id;
1728
1729         idr_preload(GFP_KERNEL);
1730         spin_lock_bh(&prog_idr_lock);
1731         id = idr_alloc_cyclic(&prog_idr, prog, 1, INT_MAX, GFP_ATOMIC);
1732         if (id > 0)
1733                 prog->aux->id = id;
1734         spin_unlock_bh(&prog_idr_lock);
1735         idr_preload_end();
1736
1737         /* id is in [1, INT_MAX) */
1738         if (WARN_ON_ONCE(!id))
1739                 return -ENOSPC;
1740
1741         return id > 0 ? 0 : id;
1742 }
1743
1744 void bpf_prog_free_id(struct bpf_prog *prog, bool do_idr_lock)
1745 {
1746         /* cBPF to eBPF migrations are currently not in the idr store.
1747          * Offloaded programs are removed from the store when their device
1748          * disappears - even if someone grabs an fd to them they are unusable,
1749          * simply waiting for refcnt to drop to be freed.
1750          */
1751         if (!prog->aux->id)
1752                 return;
1753
1754         if (do_idr_lock)
1755                 spin_lock_bh(&prog_idr_lock);
1756         else
1757                 __acquire(&prog_idr_lock);
1758
1759         idr_remove(&prog_idr, prog->aux->id);
1760         prog->aux->id = 0;
1761
1762         if (do_idr_lock)
1763                 spin_unlock_bh(&prog_idr_lock);
1764         else
1765                 __release(&prog_idr_lock);
1766 }
1767
1768 static void __bpf_prog_put_rcu(struct rcu_head *rcu)
1769 {
1770         struct bpf_prog_aux *aux = container_of(rcu, struct bpf_prog_aux, rcu);
1771
1772         kvfree(aux->func_info);
1773         kfree(aux->func_info_aux);
1774         bpf_prog_uncharge_memlock(aux->prog);
1775         security_bpf_prog_free(aux);
1776         bpf_prog_free(aux->prog);
1777 }
1778
1779 static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
1780 {
1781         bpf_prog_kallsyms_del_all(prog);
1782         btf_put(prog->aux->btf);
1783         bpf_prog_free_linfo(prog);
1784
1785         if (deferred) {
1786                 if (prog->aux->sleepable)
1787                         call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
1788                 else
1789                         call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
1790         } else {
1791                 __bpf_prog_put_rcu(&prog->aux->rcu);
1792         }
1793 }
1794
1795 static void __bpf_prog_put(struct bpf_prog *prog, bool do_idr_lock)
1796 {
1797         if (atomic64_dec_and_test(&prog->aux->refcnt)) {
1798                 perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_UNLOAD, 0);
1799                 bpf_audit_prog(prog, BPF_AUDIT_UNLOAD);
1800                 /* bpf_prog_free_id() must be called first */
1801                 bpf_prog_free_id(prog, do_idr_lock);
1802                 __bpf_prog_put_noref(prog, true);
1803         }
1804 }
1805
1806 void bpf_prog_put(struct bpf_prog *prog)
1807 {
1808         __bpf_prog_put(prog, true);
1809 }
1810 EXPORT_SYMBOL_GPL(bpf_prog_put);
1811
1812 static int bpf_prog_release(struct inode *inode, struct file *filp)
1813 {
1814         struct bpf_prog *prog = filp->private_data;
1815
1816         bpf_prog_put(prog);
1817         return 0;
1818 }
1819
1820 static void bpf_prog_get_stats(const struct bpf_prog *prog,
1821                                struct bpf_prog_stats *stats)
1822 {
1823         u64 nsecs = 0, cnt = 0;
1824         int cpu;
1825
1826         for_each_possible_cpu(cpu) {
1827                 const struct bpf_prog_stats *st;
1828                 unsigned int start;
1829                 u64 tnsecs, tcnt;
1830
1831                 st = per_cpu_ptr(prog->aux->stats, cpu);
1832                 do {
1833                         start = u64_stats_fetch_begin_irq(&st->syncp);
1834                         tnsecs = st->nsecs;
1835                         tcnt = st->cnt;
1836                 } while (u64_stats_fetch_retry_irq(&st->syncp, start));
1837                 nsecs += tnsecs;
1838                 cnt += tcnt;
1839         }
1840         stats->nsecs = nsecs;
1841         stats->cnt = cnt;
1842 }
1843
1844 #ifdef CONFIG_PROC_FS
1845 static void bpf_prog_show_fdinfo(struct seq_file *m, struct file *filp)
1846 {
1847         const struct bpf_prog *prog = filp->private_data;
1848         char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
1849         struct bpf_prog_stats stats;
1850
1851         bpf_prog_get_stats(prog, &stats);
1852         bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
1853         seq_printf(m,
1854                    "prog_type:\t%u\n"
1855                    "prog_jited:\t%u\n"
1856                    "prog_tag:\t%s\n"
1857                    "memlock:\t%llu\n"
1858                    "prog_id:\t%u\n"
1859                    "run_time_ns:\t%llu\n"
1860                    "run_cnt:\t%llu\n",
1861                    prog->type,
1862                    prog->jited,
1863                    prog_tag,
1864                    prog->pages * 1ULL << PAGE_SHIFT,
1865                    prog->aux->id,
1866                    stats.nsecs,
1867                    stats.cnt);
1868 }
1869 #endif
1870
1871 const struct file_operations bpf_prog_fops = {
1872 #ifdef CONFIG_PROC_FS
1873         .show_fdinfo    = bpf_prog_show_fdinfo,
1874 #endif
1875         .release        = bpf_prog_release,
1876         .read           = bpf_dummy_read,
1877         .write          = bpf_dummy_write,
1878 };
1879
1880 int bpf_prog_new_fd(struct bpf_prog *prog)
1881 {
1882         int ret;
1883
1884         ret = security_bpf_prog(prog);
1885         if (ret < 0)
1886                 return ret;
1887
1888         return anon_inode_getfd("bpf-prog", &bpf_prog_fops, prog,
1889                                 O_RDWR | O_CLOEXEC);
1890 }
1891
1892 static struct bpf_prog *____bpf_prog_get(struct fd f)
1893 {
1894         if (!f.file)
1895                 return ERR_PTR(-EBADF);
1896         if (f.file->f_op != &bpf_prog_fops) {
1897                 fdput(f);
1898                 return ERR_PTR(-EINVAL);
1899         }
1900
1901         return f.file->private_data;
1902 }
1903
1904 void bpf_prog_add(struct bpf_prog *prog, int i)
1905 {
1906         atomic64_add(i, &prog->aux->refcnt);
1907 }
1908 EXPORT_SYMBOL_GPL(bpf_prog_add);
1909
1910 void bpf_prog_sub(struct bpf_prog *prog, int i)
1911 {
1912         /* Only to be used for undoing previous bpf_prog_add() in some
1913          * error path. We still know that another entity in our call
1914          * path holds a reference to the program, thus atomic_sub() can
1915          * be safely used in such cases!
1916          */
1917         WARN_ON(atomic64_sub_return(i, &prog->aux->refcnt) == 0);
1918 }
1919 EXPORT_SYMBOL_GPL(bpf_prog_sub);
1920
1921 void bpf_prog_inc(struct bpf_prog *prog)
1922 {
1923         atomic64_inc(&prog->aux->refcnt);
1924 }
1925 EXPORT_SYMBOL_GPL(bpf_prog_inc);
1926
1927 /* prog_idr_lock should have been held */
1928 struct bpf_prog *bpf_prog_inc_not_zero(struct bpf_prog *prog)
1929 {
1930         int refold;
1931
1932         refold = atomic64_fetch_add_unless(&prog->aux->refcnt, 1, 0);
1933
1934         if (!refold)
1935                 return ERR_PTR(-ENOENT);
1936
1937         return prog;
1938 }
1939 EXPORT_SYMBOL_GPL(bpf_prog_inc_not_zero);
1940
1941 bool bpf_prog_get_ok(struct bpf_prog *prog,
1942                             enum bpf_prog_type *attach_type, bool attach_drv)
1943 {
1944         /* not an attachment, just a refcount inc, always allow */
1945         if (!attach_type)
1946                 return true;
1947
1948         if (prog->type != *attach_type)
1949                 return false;
1950         if (bpf_prog_is_dev_bound(prog->aux) && !attach_drv)
1951                 return false;
1952
1953         return true;
1954 }
1955
1956 static struct bpf_prog *__bpf_prog_get(u32 ufd, enum bpf_prog_type *attach_type,
1957                                        bool attach_drv)
1958 {
1959         struct fd f = fdget(ufd);
1960         struct bpf_prog *prog;
1961
1962         prog = ____bpf_prog_get(f);
1963         if (IS_ERR(prog))
1964                 return prog;
1965         if (!bpf_prog_get_ok(prog, attach_type, attach_drv)) {
1966                 prog = ERR_PTR(-EINVAL);
1967                 goto out;
1968         }
1969
1970         bpf_prog_inc(prog);
1971 out:
1972         fdput(f);
1973         return prog;
1974 }
1975
1976 struct bpf_prog *bpf_prog_get(u32 ufd)
1977 {
1978         return __bpf_prog_get(ufd, NULL, false);
1979 }
1980
1981 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
1982                                        bool attach_drv)
1983 {
1984         return __bpf_prog_get(ufd, &type, attach_drv);
1985 }
1986 EXPORT_SYMBOL_GPL(bpf_prog_get_type_dev);
1987
1988 /* Initially all BPF programs could be loaded w/o specifying
1989  * expected_attach_type. Later for some of them specifying expected_attach_type
1990  * at load time became required so that program could be validated properly.
1991  * Programs of types that are allowed to be loaded both w/ and w/o (for
1992  * backward compatibility) expected_attach_type, should have the default attach
1993  * type assigned to expected_attach_type for the latter case, so that it can be
1994  * validated later at attach time.
1995  *
1996  * bpf_prog_load_fixup_attach_type() sets expected_attach_type in @attr if
1997  * prog type requires it but has some attach types that have to be backward
1998  * compatible.
1999  */
2000 static void bpf_prog_load_fixup_attach_type(union bpf_attr *attr)
2001 {
2002         switch (attr->prog_type) {
2003         case BPF_PROG_TYPE_CGROUP_SOCK:
2004                 /* Unfortunately BPF_ATTACH_TYPE_UNSPEC enumeration doesn't
2005                  * exist so checking for non-zero is the way to go here.
2006                  */
2007                 if (!attr->expected_attach_type)
2008                         attr->expected_attach_type =
2009                                 BPF_CGROUP_INET_SOCK_CREATE;
2010                 break;
2011         }
2012 }
2013
2014 static int
2015 bpf_prog_load_check_attach(enum bpf_prog_type prog_type,
2016                            enum bpf_attach_type expected_attach_type,
2017                            u32 btf_id, u32 prog_fd)
2018 {
2019         if (btf_id) {
2020                 if (btf_id > BTF_MAX_TYPE)
2021                         return -EINVAL;
2022
2023                 switch (prog_type) {
2024                 case BPF_PROG_TYPE_TRACING:
2025                 case BPF_PROG_TYPE_LSM:
2026                 case BPF_PROG_TYPE_STRUCT_OPS:
2027                 case BPF_PROG_TYPE_EXT:
2028                         break;
2029                 default:
2030                         return -EINVAL;
2031                 }
2032         }
2033
2034         if (prog_fd && prog_type != BPF_PROG_TYPE_TRACING &&
2035             prog_type != BPF_PROG_TYPE_EXT)
2036                 return -EINVAL;
2037
2038         switch (prog_type) {
2039         case BPF_PROG_TYPE_CGROUP_SOCK:
2040                 switch (expected_attach_type) {
2041                 case BPF_CGROUP_INET_SOCK_CREATE:
2042                 case BPF_CGROUP_INET_SOCK_RELEASE:
2043                 case BPF_CGROUP_INET4_POST_BIND:
2044                 case BPF_CGROUP_INET6_POST_BIND:
2045                         return 0;
2046                 default:
2047                         return -EINVAL;
2048                 }
2049         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2050                 switch (expected_attach_type) {
2051                 case BPF_CGROUP_INET4_BIND:
2052                 case BPF_CGROUP_INET6_BIND:
2053                 case BPF_CGROUP_INET4_CONNECT:
2054                 case BPF_CGROUP_INET6_CONNECT:
2055                 case BPF_CGROUP_INET4_GETPEERNAME:
2056                 case BPF_CGROUP_INET6_GETPEERNAME:
2057                 case BPF_CGROUP_INET4_GETSOCKNAME:
2058                 case BPF_CGROUP_INET6_GETSOCKNAME:
2059                 case BPF_CGROUP_UDP4_SENDMSG:
2060                 case BPF_CGROUP_UDP6_SENDMSG:
2061                 case BPF_CGROUP_UDP4_RECVMSG:
2062                 case BPF_CGROUP_UDP6_RECVMSG:
2063                         return 0;
2064                 default:
2065                         return -EINVAL;
2066                 }
2067         case BPF_PROG_TYPE_CGROUP_SKB:
2068                 switch (expected_attach_type) {
2069                 case BPF_CGROUP_INET_INGRESS:
2070                 case BPF_CGROUP_INET_EGRESS:
2071                         return 0;
2072                 default:
2073                         return -EINVAL;
2074                 }
2075         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2076                 switch (expected_attach_type) {
2077                 case BPF_CGROUP_SETSOCKOPT:
2078                 case BPF_CGROUP_GETSOCKOPT:
2079                         return 0;
2080                 default:
2081                         return -EINVAL;
2082                 }
2083         case BPF_PROG_TYPE_SK_LOOKUP:
2084                 if (expected_attach_type == BPF_SK_LOOKUP)
2085                         return 0;
2086                 return -EINVAL;
2087         case BPF_PROG_TYPE_EXT:
2088                 if (expected_attach_type)
2089                         return -EINVAL;
2090                 fallthrough;
2091         default:
2092                 return 0;
2093         }
2094 }
2095
2096 static bool is_net_admin_prog_type(enum bpf_prog_type prog_type)
2097 {
2098         switch (prog_type) {
2099         case BPF_PROG_TYPE_SCHED_CLS:
2100         case BPF_PROG_TYPE_SCHED_ACT:
2101         case BPF_PROG_TYPE_XDP:
2102         case BPF_PROG_TYPE_LWT_IN:
2103         case BPF_PROG_TYPE_LWT_OUT:
2104         case BPF_PROG_TYPE_LWT_XMIT:
2105         case BPF_PROG_TYPE_LWT_SEG6LOCAL:
2106         case BPF_PROG_TYPE_SK_SKB:
2107         case BPF_PROG_TYPE_SK_MSG:
2108         case BPF_PROG_TYPE_LIRC_MODE2:
2109         case BPF_PROG_TYPE_FLOW_DISSECTOR:
2110         case BPF_PROG_TYPE_CGROUP_DEVICE:
2111         case BPF_PROG_TYPE_CGROUP_SOCK:
2112         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2113         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2114         case BPF_PROG_TYPE_CGROUP_SYSCTL:
2115         case BPF_PROG_TYPE_SOCK_OPS:
2116         case BPF_PROG_TYPE_EXT: /* extends any prog */
2117                 return true;
2118         case BPF_PROG_TYPE_CGROUP_SKB:
2119                 /* always unpriv */
2120         case BPF_PROG_TYPE_SK_REUSEPORT:
2121                 /* equivalent to SOCKET_FILTER. need CAP_BPF only */
2122         default:
2123                 return false;
2124         }
2125 }
2126
2127 static bool is_perfmon_prog_type(enum bpf_prog_type prog_type)
2128 {
2129         switch (prog_type) {
2130         case BPF_PROG_TYPE_KPROBE:
2131         case BPF_PROG_TYPE_TRACEPOINT:
2132         case BPF_PROG_TYPE_PERF_EVENT:
2133         case BPF_PROG_TYPE_RAW_TRACEPOINT:
2134         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2135         case BPF_PROG_TYPE_TRACING:
2136         case BPF_PROG_TYPE_LSM:
2137         case BPF_PROG_TYPE_STRUCT_OPS: /* has access to struct sock */
2138         case BPF_PROG_TYPE_EXT: /* extends any prog */
2139                 return true;
2140         default:
2141                 return false;
2142         }
2143 }
2144
2145 /* last field in 'union bpf_attr' used by this command */
2146 #define BPF_PROG_LOAD_LAST_FIELD attach_prog_fd
2147
2148 static int bpf_prog_load(union bpf_attr *attr, union bpf_attr __user *uattr)
2149 {
2150         enum bpf_prog_type type = attr->prog_type;
2151         struct bpf_prog *prog;
2152         int err;
2153         char license[128];
2154         bool is_gpl;
2155
2156         if (CHECK_ATTR(BPF_PROG_LOAD))
2157                 return -EINVAL;
2158
2159         if (attr->prog_flags & ~(BPF_F_STRICT_ALIGNMENT |
2160                                  BPF_F_ANY_ALIGNMENT |
2161                                  BPF_F_TEST_STATE_FREQ |
2162                                  BPF_F_SLEEPABLE |
2163                                  BPF_F_TEST_RND_HI32))
2164                 return -EINVAL;
2165
2166         if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) &&
2167             (attr->prog_flags & BPF_F_ANY_ALIGNMENT) &&
2168             !bpf_capable())
2169                 return -EPERM;
2170
2171         /* copy eBPF program license from user space */
2172         if (strncpy_from_user(license, u64_to_user_ptr(attr->license),
2173                               sizeof(license) - 1) < 0)
2174                 return -EFAULT;
2175         license[sizeof(license) - 1] = 0;
2176
2177         /* eBPF programs must be GPL compatible to use GPL-ed functions */
2178         is_gpl = license_is_gpl_compatible(license);
2179
2180         if (attr->insn_cnt == 0 ||
2181             attr->insn_cnt > (bpf_capable() ? BPF_COMPLEXITY_LIMIT_INSNS : BPF_MAXINSNS))
2182                 return -E2BIG;
2183         if (type != BPF_PROG_TYPE_SOCKET_FILTER &&
2184             type != BPF_PROG_TYPE_CGROUP_SKB &&
2185             !bpf_capable())
2186                 return -EPERM;
2187
2188         if (is_net_admin_prog_type(type) && !capable(CAP_NET_ADMIN) && !capable(CAP_SYS_ADMIN))
2189                 return -EPERM;
2190         if (is_perfmon_prog_type(type) && !perfmon_capable())
2191                 return -EPERM;
2192
2193         bpf_prog_load_fixup_attach_type(attr);
2194         if (bpf_prog_load_check_attach(type, attr->expected_attach_type,
2195                                        attr->attach_btf_id,
2196                                        attr->attach_prog_fd))
2197                 return -EINVAL;
2198
2199         /* plain bpf_prog allocation */
2200         prog = bpf_prog_alloc(bpf_prog_size(attr->insn_cnt), GFP_USER);
2201         if (!prog)
2202                 return -ENOMEM;
2203
2204         prog->expected_attach_type = attr->expected_attach_type;
2205         prog->aux->attach_btf_id = attr->attach_btf_id;
2206         if (attr->attach_prog_fd) {
2207                 struct bpf_prog *dst_prog;
2208
2209                 dst_prog = bpf_prog_get(attr->attach_prog_fd);
2210                 if (IS_ERR(dst_prog)) {
2211                         err = PTR_ERR(dst_prog);
2212                         goto free_prog_nouncharge;
2213                 }
2214                 prog->aux->dst_prog = dst_prog;
2215         }
2216
2217         prog->aux->offload_requested = !!attr->prog_ifindex;
2218         prog->aux->sleepable = attr->prog_flags & BPF_F_SLEEPABLE;
2219
2220         err = security_bpf_prog_alloc(prog->aux);
2221         if (err)
2222                 goto free_prog_nouncharge;
2223
2224         err = bpf_prog_charge_memlock(prog);
2225         if (err)
2226                 goto free_prog_sec;
2227
2228         prog->len = attr->insn_cnt;
2229
2230         err = -EFAULT;
2231         if (copy_from_user(prog->insns, u64_to_user_ptr(attr->insns),
2232                            bpf_prog_insn_size(prog)) != 0)
2233                 goto free_prog;
2234
2235         prog->orig_prog = NULL;
2236         prog->jited = 0;
2237
2238         atomic64_set(&prog->aux->refcnt, 1);
2239         prog->gpl_compatible = is_gpl ? 1 : 0;
2240
2241         if (bpf_prog_is_dev_bound(prog->aux)) {
2242                 err = bpf_prog_offload_init(prog, attr);
2243                 if (err)
2244                         goto free_prog;
2245         }
2246
2247         /* find program type: socket_filter vs tracing_filter */
2248         err = find_prog_type(type, prog);
2249         if (err < 0)
2250                 goto free_prog;
2251
2252         prog->aux->load_time = ktime_get_boottime_ns();
2253         err = bpf_obj_name_cpy(prog->aux->name, attr->prog_name,
2254                                sizeof(attr->prog_name));
2255         if (err < 0)
2256                 goto free_prog;
2257
2258         /* run eBPF verifier */
2259         err = bpf_check(&prog, attr, uattr);
2260         if (err < 0)
2261                 goto free_used_maps;
2262
2263         prog = bpf_prog_select_runtime(prog, &err);
2264         if (err < 0)
2265                 goto free_used_maps;
2266
2267         err = bpf_prog_alloc_id(prog);
2268         if (err)
2269                 goto free_used_maps;
2270
2271         /* Upon success of bpf_prog_alloc_id(), the BPF prog is
2272          * effectively publicly exposed. However, retrieving via
2273          * bpf_prog_get_fd_by_id() will take another reference,
2274          * therefore it cannot be gone underneath us.
2275          *
2276          * Only for the time /after/ successful bpf_prog_new_fd()
2277          * and before returning to userspace, we might just hold
2278          * one reference and any parallel close on that fd could
2279          * rip everything out. Hence, below notifications must
2280          * happen before bpf_prog_new_fd().
2281          *
2282          * Also, any failure handling from this point onwards must
2283          * be using bpf_prog_put() given the program is exposed.
2284          */
2285         bpf_prog_kallsyms_add(prog);
2286         perf_event_bpf_event(prog, PERF_BPF_EVENT_PROG_LOAD, 0);
2287         bpf_audit_prog(prog, BPF_AUDIT_LOAD);
2288
2289         err = bpf_prog_new_fd(prog);
2290         if (err < 0)
2291                 bpf_prog_put(prog);
2292         return err;
2293
2294 free_used_maps:
2295         /* In case we have subprogs, we need to wait for a grace
2296          * period before we can tear down JIT memory since symbols
2297          * are already exposed under kallsyms.
2298          */
2299         __bpf_prog_put_noref(prog, prog->aux->func_cnt);
2300         return err;
2301 free_prog:
2302         bpf_prog_uncharge_memlock(prog);
2303 free_prog_sec:
2304         security_bpf_prog_free(prog->aux);
2305 free_prog_nouncharge:
2306         bpf_prog_free(prog);
2307         return err;
2308 }
2309
2310 #define BPF_OBJ_LAST_FIELD file_flags
2311
2312 static int bpf_obj_pin(const union bpf_attr *attr)
2313 {
2314         if (CHECK_ATTR(BPF_OBJ) || attr->file_flags != 0)
2315                 return -EINVAL;
2316
2317         return bpf_obj_pin_user(attr->bpf_fd, u64_to_user_ptr(attr->pathname));
2318 }
2319
2320 static int bpf_obj_get(const union bpf_attr *attr)
2321 {
2322         if (CHECK_ATTR(BPF_OBJ) || attr->bpf_fd != 0 ||
2323             attr->file_flags & ~BPF_OBJ_FLAG_MASK)
2324                 return -EINVAL;
2325
2326         return bpf_obj_get_user(u64_to_user_ptr(attr->pathname),
2327                                 attr->file_flags);
2328 }
2329
2330 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2331                    const struct bpf_link_ops *ops, struct bpf_prog *prog)
2332 {
2333         atomic64_set(&link->refcnt, 1);
2334         link->type = type;
2335         link->id = 0;
2336         link->ops = ops;
2337         link->prog = prog;
2338 }
2339
2340 static void bpf_link_free_id(int id)
2341 {
2342         if (!id)
2343                 return;
2344
2345         spin_lock_bh(&link_idr_lock);
2346         idr_remove(&link_idr, id);
2347         spin_unlock_bh(&link_idr_lock);
2348 }
2349
2350 /* Clean up bpf_link and corresponding anon_inode file and FD. After
2351  * anon_inode is created, bpf_link can't be just kfree()'d due to deferred
2352  * anon_inode's release() call. This helper marksbpf_link as
2353  * defunct, releases anon_inode file and puts reserved FD. bpf_prog's refcnt
2354  * is not decremented, it's the responsibility of a calling code that failed
2355  * to complete bpf_link initialization.
2356  */
2357 void bpf_link_cleanup(struct bpf_link_primer *primer)
2358 {
2359         primer->link->prog = NULL;
2360         bpf_link_free_id(primer->id);
2361         fput(primer->file);
2362         put_unused_fd(primer->fd);
2363 }
2364
2365 void bpf_link_inc(struct bpf_link *link)
2366 {
2367         atomic64_inc(&link->refcnt);
2368 }
2369
2370 /* bpf_link_free is guaranteed to be called from process context */
2371 static void bpf_link_free(struct bpf_link *link)
2372 {
2373         bpf_link_free_id(link->id);
2374         if (link->prog) {
2375                 /* detach BPF program, clean up used resources */
2376                 link->ops->release(link);
2377                 bpf_prog_put(link->prog);
2378         }
2379         /* free bpf_link and its containing memory */
2380         link->ops->dealloc(link);
2381 }
2382
2383 static void bpf_link_put_deferred(struct work_struct *work)
2384 {
2385         struct bpf_link *link = container_of(work, struct bpf_link, work);
2386
2387         bpf_link_free(link);
2388 }
2389
2390 /* bpf_link_put can be called from atomic context, but ensures that resources
2391  * are freed from process context
2392  */
2393 void bpf_link_put(struct bpf_link *link)
2394 {
2395         if (!atomic64_dec_and_test(&link->refcnt))
2396                 return;
2397
2398         if (in_atomic()) {
2399                 INIT_WORK(&link->work, bpf_link_put_deferred);
2400                 schedule_work(&link->work);
2401         } else {
2402                 bpf_link_free(link);
2403         }
2404 }
2405
2406 static int bpf_link_release(struct inode *inode, struct file *filp)
2407 {
2408         struct bpf_link *link = filp->private_data;
2409
2410         bpf_link_put(link);
2411         return 0;
2412 }
2413
2414 #ifdef CONFIG_PROC_FS
2415 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
2416 #define BPF_MAP_TYPE(_id, _ops)
2417 #define BPF_LINK_TYPE(_id, _name) [_id] = #_name,
2418 static const char *bpf_link_type_strs[] = {
2419         [BPF_LINK_TYPE_UNSPEC] = "<invalid>",
2420 #include <linux/bpf_types.h>
2421 };
2422 #undef BPF_PROG_TYPE
2423 #undef BPF_MAP_TYPE
2424 #undef BPF_LINK_TYPE
2425
2426 static void bpf_link_show_fdinfo(struct seq_file *m, struct file *filp)
2427 {
2428         const struct bpf_link *link = filp->private_data;
2429         const struct bpf_prog *prog = link->prog;
2430         char prog_tag[sizeof(prog->tag) * 2 + 1] = { };
2431
2432         bin2hex(prog_tag, prog->tag, sizeof(prog->tag));
2433         seq_printf(m,
2434                    "link_type:\t%s\n"
2435                    "link_id:\t%u\n"
2436                    "prog_tag:\t%s\n"
2437                    "prog_id:\t%u\n",
2438                    bpf_link_type_strs[link->type],
2439                    link->id,
2440                    prog_tag,
2441                    prog->aux->id);
2442         if (link->ops->show_fdinfo)
2443                 link->ops->show_fdinfo(link, m);
2444 }
2445 #endif
2446
2447 static const struct file_operations bpf_link_fops = {
2448 #ifdef CONFIG_PROC_FS
2449         .show_fdinfo    = bpf_link_show_fdinfo,
2450 #endif
2451         .release        = bpf_link_release,
2452         .read           = bpf_dummy_read,
2453         .write          = bpf_dummy_write,
2454 };
2455
2456 static int bpf_link_alloc_id(struct bpf_link *link)
2457 {
2458         int id;
2459
2460         idr_preload(GFP_KERNEL);
2461         spin_lock_bh(&link_idr_lock);
2462         id = idr_alloc_cyclic(&link_idr, link, 1, INT_MAX, GFP_ATOMIC);
2463         spin_unlock_bh(&link_idr_lock);
2464         idr_preload_end();
2465
2466         return id;
2467 }
2468
2469 /* Prepare bpf_link to be exposed to user-space by allocating anon_inode file,
2470  * reserving unused FD and allocating ID from link_idr. This is to be paired
2471  * with bpf_link_settle() to install FD and ID and expose bpf_link to
2472  * user-space, if bpf_link is successfully attached. If not, bpf_link and
2473  * pre-allocated resources are to be freed with bpf_cleanup() call. All the
2474  * transient state is passed around in struct bpf_link_primer.
2475  * This is preferred way to create and initialize bpf_link, especially when
2476  * there are complicated and expensive operations inbetween creating bpf_link
2477  * itself and attaching it to BPF hook. By using bpf_link_prime() and
2478  * bpf_link_settle() kernel code using bpf_link doesn't have to perform
2479  * expensive (and potentially failing) roll back operations in a rare case
2480  * that file, FD, or ID can't be allocated.
2481  */
2482 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer)
2483 {
2484         struct file *file;
2485         int fd, id;
2486
2487         fd = get_unused_fd_flags(O_CLOEXEC);
2488         if (fd < 0)
2489                 return fd;
2490
2491
2492         id = bpf_link_alloc_id(link);
2493         if (id < 0) {
2494                 put_unused_fd(fd);
2495                 return id;
2496         }
2497
2498         file = anon_inode_getfile("bpf_link", &bpf_link_fops, link, O_CLOEXEC);
2499         if (IS_ERR(file)) {
2500                 bpf_link_free_id(id);
2501                 put_unused_fd(fd);
2502                 return PTR_ERR(file);
2503         }
2504
2505         primer->link = link;
2506         primer->file = file;
2507         primer->fd = fd;
2508         primer->id = id;
2509         return 0;
2510 }
2511
2512 int bpf_link_settle(struct bpf_link_primer *primer)
2513 {
2514         /* make bpf_link fetchable by ID */
2515         spin_lock_bh(&link_idr_lock);
2516         primer->link->id = primer->id;
2517         spin_unlock_bh(&link_idr_lock);
2518         /* make bpf_link fetchable by FD */
2519         fd_install(primer->fd, primer->file);
2520         /* pass through installed FD */
2521         return primer->fd;
2522 }
2523
2524 int bpf_link_new_fd(struct bpf_link *link)
2525 {
2526         return anon_inode_getfd("bpf-link", &bpf_link_fops, link, O_CLOEXEC);
2527 }
2528
2529 struct bpf_link *bpf_link_get_from_fd(u32 ufd)
2530 {
2531         struct fd f = fdget(ufd);
2532         struct bpf_link *link;
2533
2534         if (!f.file)
2535                 return ERR_PTR(-EBADF);
2536         if (f.file->f_op != &bpf_link_fops) {
2537                 fdput(f);
2538                 return ERR_PTR(-EINVAL);
2539         }
2540
2541         link = f.file->private_data;
2542         bpf_link_inc(link);
2543         fdput(f);
2544
2545         return link;
2546 }
2547
2548 struct bpf_tracing_link {
2549         struct bpf_link link;
2550         enum bpf_attach_type attach_type;
2551         struct bpf_trampoline *trampoline;
2552         struct bpf_prog *tgt_prog;
2553 };
2554
2555 static void bpf_tracing_link_release(struct bpf_link *link)
2556 {
2557         struct bpf_tracing_link *tr_link =
2558                 container_of(link, struct bpf_tracing_link, link);
2559
2560         WARN_ON_ONCE(bpf_trampoline_unlink_prog(link->prog,
2561                                                 tr_link->trampoline));
2562
2563         bpf_trampoline_put(tr_link->trampoline);
2564
2565         /* tgt_prog is NULL if target is a kernel function */
2566         if (tr_link->tgt_prog)
2567                 bpf_prog_put(tr_link->tgt_prog);
2568 }
2569
2570 static void bpf_tracing_link_dealloc(struct bpf_link *link)
2571 {
2572         struct bpf_tracing_link *tr_link =
2573                 container_of(link, struct bpf_tracing_link, link);
2574
2575         kfree(tr_link);
2576 }
2577
2578 static void bpf_tracing_link_show_fdinfo(const struct bpf_link *link,
2579                                          struct seq_file *seq)
2580 {
2581         struct bpf_tracing_link *tr_link =
2582                 container_of(link, struct bpf_tracing_link, link);
2583
2584         seq_printf(seq,
2585                    "attach_type:\t%d\n",
2586                    tr_link->attach_type);
2587 }
2588
2589 static int bpf_tracing_link_fill_link_info(const struct bpf_link *link,
2590                                            struct bpf_link_info *info)
2591 {
2592         struct bpf_tracing_link *tr_link =
2593                 container_of(link, struct bpf_tracing_link, link);
2594
2595         info->tracing.attach_type = tr_link->attach_type;
2596
2597         return 0;
2598 }
2599
2600 static const struct bpf_link_ops bpf_tracing_link_lops = {
2601         .release = bpf_tracing_link_release,
2602         .dealloc = bpf_tracing_link_dealloc,
2603         .show_fdinfo = bpf_tracing_link_show_fdinfo,
2604         .fill_link_info = bpf_tracing_link_fill_link_info,
2605 };
2606
2607 static int bpf_tracing_prog_attach(struct bpf_prog *prog,
2608                                    int tgt_prog_fd,
2609                                    u32 btf_id)
2610 {
2611         struct bpf_link_primer link_primer;
2612         struct bpf_prog *tgt_prog = NULL;
2613         struct bpf_trampoline *tr = NULL;
2614         struct bpf_tracing_link *link;
2615         u64 key = 0;
2616         int err;
2617
2618         switch (prog->type) {
2619         case BPF_PROG_TYPE_TRACING:
2620                 if (prog->expected_attach_type != BPF_TRACE_FENTRY &&
2621                     prog->expected_attach_type != BPF_TRACE_FEXIT &&
2622                     prog->expected_attach_type != BPF_MODIFY_RETURN) {
2623                         err = -EINVAL;
2624                         goto out_put_prog;
2625                 }
2626                 break;
2627         case BPF_PROG_TYPE_EXT:
2628                 if (prog->expected_attach_type != 0) {
2629                         err = -EINVAL;
2630                         goto out_put_prog;
2631                 }
2632                 break;
2633         case BPF_PROG_TYPE_LSM:
2634                 if (prog->expected_attach_type != BPF_LSM_MAC) {
2635                         err = -EINVAL;
2636                         goto out_put_prog;
2637                 }
2638                 break;
2639         default:
2640                 err = -EINVAL;
2641                 goto out_put_prog;
2642         }
2643
2644         if (!!tgt_prog_fd != !!btf_id) {
2645                 err = -EINVAL;
2646                 goto out_put_prog;
2647         }
2648
2649         if (tgt_prog_fd) {
2650                 /* For now we only allow new targets for BPF_PROG_TYPE_EXT */
2651                 if (prog->type != BPF_PROG_TYPE_EXT) {
2652                         err = -EINVAL;
2653                         goto out_put_prog;
2654                 }
2655
2656                 tgt_prog = bpf_prog_get(tgt_prog_fd);
2657                 if (IS_ERR(tgt_prog)) {
2658                         err = PTR_ERR(tgt_prog);
2659                         tgt_prog = NULL;
2660                         goto out_put_prog;
2661                 }
2662
2663                 key = bpf_trampoline_compute_key(tgt_prog, btf_id);
2664         }
2665
2666         link = kzalloc(sizeof(*link), GFP_USER);
2667         if (!link) {
2668                 err = -ENOMEM;
2669                 goto out_put_prog;
2670         }
2671         bpf_link_init(&link->link, BPF_LINK_TYPE_TRACING,
2672                       &bpf_tracing_link_lops, prog);
2673         link->attach_type = prog->expected_attach_type;
2674
2675         mutex_lock(&prog->aux->dst_mutex);
2676
2677         /* There are a few possible cases here:
2678          *
2679          * - if prog->aux->dst_trampoline is set, the program was just loaded
2680          *   and not yet attached to anything, so we can use the values stored
2681          *   in prog->aux
2682          *
2683          * - if prog->aux->dst_trampoline is NULL, the program has already been
2684          *   attached to a target and its initial target was cleared (below)
2685          *
2686          * - if tgt_prog != NULL, the caller specified tgt_prog_fd +
2687          *   target_btf_id using the link_create API.
2688          *
2689          * - if tgt_prog == NULL when this function was called using the old
2690          *   raw_tracepoint_open API, and we need a target from prog->aux
2691          *
2692          * The combination of no saved target in prog->aux, and no target
2693          * specified on load is illegal, and we reject that here.
2694          */
2695         if (!prog->aux->dst_trampoline && !tgt_prog) {
2696                 err = -ENOENT;
2697                 goto out_unlock;
2698         }
2699
2700         if (!prog->aux->dst_trampoline ||
2701             (key && key != prog->aux->dst_trampoline->key)) {
2702                 /* If there is no saved target, or the specified target is
2703                  * different from the destination specified at load time, we
2704                  * need a new trampoline and a check for compatibility
2705                  */
2706                 struct bpf_attach_target_info tgt_info = {};
2707
2708                 err = bpf_check_attach_target(NULL, prog, tgt_prog, btf_id,
2709                                               &tgt_info);
2710                 if (err)
2711                         goto out_unlock;
2712
2713                 tr = bpf_trampoline_get(key, &tgt_info);
2714                 if (!tr) {
2715                         err = -ENOMEM;
2716                         goto out_unlock;
2717                 }
2718         } else {
2719                 /* The caller didn't specify a target, or the target was the
2720                  * same as the destination supplied during program load. This
2721                  * means we can reuse the trampoline and reference from program
2722                  * load time, and there is no need to allocate a new one. This
2723                  * can only happen once for any program, as the saved values in
2724                  * prog->aux are cleared below.
2725                  */
2726                 tr = prog->aux->dst_trampoline;
2727                 tgt_prog = prog->aux->dst_prog;
2728         }
2729
2730         err = bpf_link_prime(&link->link, &link_primer);
2731         if (err)
2732                 goto out_unlock;
2733
2734         err = bpf_trampoline_link_prog(prog, tr);
2735         if (err) {
2736                 bpf_link_cleanup(&link_primer);
2737                 link = NULL;
2738                 goto out_unlock;
2739         }
2740
2741         link->tgt_prog = tgt_prog;
2742         link->trampoline = tr;
2743
2744         /* Always clear the trampoline and target prog from prog->aux to make
2745          * sure the original attach destination is not kept alive after a
2746          * program is (re-)attached to another target.
2747          */
2748         if (prog->aux->dst_prog &&
2749             (tgt_prog_fd || tr != prog->aux->dst_trampoline))
2750                 /* got extra prog ref from syscall, or attaching to different prog */
2751                 bpf_prog_put(prog->aux->dst_prog);
2752         if (prog->aux->dst_trampoline && tr != prog->aux->dst_trampoline)
2753                 /* we allocated a new trampoline, so free the old one */
2754                 bpf_trampoline_put(prog->aux->dst_trampoline);
2755
2756         prog->aux->dst_prog = NULL;
2757         prog->aux->dst_trampoline = NULL;
2758         mutex_unlock(&prog->aux->dst_mutex);
2759
2760         return bpf_link_settle(&link_primer);
2761 out_unlock:
2762         if (tr && tr != prog->aux->dst_trampoline)
2763                 bpf_trampoline_put(tr);
2764         mutex_unlock(&prog->aux->dst_mutex);
2765         kfree(link);
2766 out_put_prog:
2767         if (tgt_prog_fd && tgt_prog)
2768                 bpf_prog_put(tgt_prog);
2769         return err;
2770 }
2771
2772 struct bpf_raw_tp_link {
2773         struct bpf_link link;
2774         struct bpf_raw_event_map *btp;
2775 };
2776
2777 static void bpf_raw_tp_link_release(struct bpf_link *link)
2778 {
2779         struct bpf_raw_tp_link *raw_tp =
2780                 container_of(link, struct bpf_raw_tp_link, link);
2781
2782         bpf_probe_unregister(raw_tp->btp, raw_tp->link.prog);
2783         bpf_put_raw_tracepoint(raw_tp->btp);
2784 }
2785
2786 static void bpf_raw_tp_link_dealloc(struct bpf_link *link)
2787 {
2788         struct bpf_raw_tp_link *raw_tp =
2789                 container_of(link, struct bpf_raw_tp_link, link);
2790
2791         kfree(raw_tp);
2792 }
2793
2794 static void bpf_raw_tp_link_show_fdinfo(const struct bpf_link *link,
2795                                         struct seq_file *seq)
2796 {
2797         struct bpf_raw_tp_link *raw_tp_link =
2798                 container_of(link, struct bpf_raw_tp_link, link);
2799
2800         seq_printf(seq,
2801                    "tp_name:\t%s\n",
2802                    raw_tp_link->btp->tp->name);
2803 }
2804
2805 static int bpf_raw_tp_link_fill_link_info(const struct bpf_link *link,
2806                                           struct bpf_link_info *info)
2807 {
2808         struct bpf_raw_tp_link *raw_tp_link =
2809                 container_of(link, struct bpf_raw_tp_link, link);
2810         char __user *ubuf = u64_to_user_ptr(info->raw_tracepoint.tp_name);
2811         const char *tp_name = raw_tp_link->btp->tp->name;
2812         u32 ulen = info->raw_tracepoint.tp_name_len;
2813         size_t tp_len = strlen(tp_name);
2814
2815         if (!ulen ^ !ubuf)
2816                 return -EINVAL;
2817
2818         info->raw_tracepoint.tp_name_len = tp_len + 1;
2819
2820         if (!ubuf)
2821                 return 0;
2822
2823         if (ulen >= tp_len + 1) {
2824                 if (copy_to_user(ubuf, tp_name, tp_len + 1))
2825                         return -EFAULT;
2826         } else {
2827                 char zero = '\0';
2828
2829                 if (copy_to_user(ubuf, tp_name, ulen - 1))
2830                         return -EFAULT;
2831                 if (put_user(zero, ubuf + ulen - 1))
2832                         return -EFAULT;
2833                 return -ENOSPC;
2834         }
2835
2836         return 0;
2837 }
2838
2839 static const struct bpf_link_ops bpf_raw_tp_link_lops = {
2840         .release = bpf_raw_tp_link_release,
2841         .dealloc = bpf_raw_tp_link_dealloc,
2842         .show_fdinfo = bpf_raw_tp_link_show_fdinfo,
2843         .fill_link_info = bpf_raw_tp_link_fill_link_info,
2844 };
2845
2846 #define BPF_RAW_TRACEPOINT_OPEN_LAST_FIELD raw_tracepoint.prog_fd
2847
2848 static int bpf_raw_tracepoint_open(const union bpf_attr *attr)
2849 {
2850         struct bpf_link_primer link_primer;
2851         struct bpf_raw_tp_link *link;
2852         struct bpf_raw_event_map *btp;
2853         struct bpf_prog *prog;
2854         const char *tp_name;
2855         char buf[128];
2856         int err;
2857
2858         if (CHECK_ATTR(BPF_RAW_TRACEPOINT_OPEN))
2859                 return -EINVAL;
2860
2861         prog = bpf_prog_get(attr->raw_tracepoint.prog_fd);
2862         if (IS_ERR(prog))
2863                 return PTR_ERR(prog);
2864
2865         switch (prog->type) {
2866         case BPF_PROG_TYPE_TRACING:
2867         case BPF_PROG_TYPE_EXT:
2868         case BPF_PROG_TYPE_LSM:
2869                 if (attr->raw_tracepoint.name) {
2870                         /* The attach point for this category of programs
2871                          * should be specified via btf_id during program load.
2872                          */
2873                         err = -EINVAL;
2874                         goto out_put_prog;
2875                 }
2876                 if (prog->type == BPF_PROG_TYPE_TRACING &&
2877                     prog->expected_attach_type == BPF_TRACE_RAW_TP) {
2878                         tp_name = prog->aux->attach_func_name;
2879                         break;
2880                 }
2881                 err = bpf_tracing_prog_attach(prog, 0, 0);
2882                 if (err >= 0)
2883                         return err;
2884                 goto out_put_prog;
2885         case BPF_PROG_TYPE_RAW_TRACEPOINT:
2886         case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
2887                 if (strncpy_from_user(buf,
2888                                       u64_to_user_ptr(attr->raw_tracepoint.name),
2889                                       sizeof(buf) - 1) < 0) {
2890                         err = -EFAULT;
2891                         goto out_put_prog;
2892                 }
2893                 buf[sizeof(buf) - 1] = 0;
2894                 tp_name = buf;
2895                 break;
2896         default:
2897                 err = -EINVAL;
2898                 goto out_put_prog;
2899         }
2900
2901         btp = bpf_get_raw_tracepoint(tp_name);
2902         if (!btp) {
2903                 err = -ENOENT;
2904                 goto out_put_prog;
2905         }
2906
2907         link = kzalloc(sizeof(*link), GFP_USER);
2908         if (!link) {
2909                 err = -ENOMEM;
2910                 goto out_put_btp;
2911         }
2912         bpf_link_init(&link->link, BPF_LINK_TYPE_RAW_TRACEPOINT,
2913                       &bpf_raw_tp_link_lops, prog);
2914         link->btp = btp;
2915
2916         err = bpf_link_prime(&link->link, &link_primer);
2917         if (err) {
2918                 kfree(link);
2919                 goto out_put_btp;
2920         }
2921
2922         err = bpf_probe_register(link->btp, prog);
2923         if (err) {
2924                 bpf_link_cleanup(&link_primer);
2925                 goto out_put_btp;
2926         }
2927
2928         return bpf_link_settle(&link_primer);
2929
2930 out_put_btp:
2931         bpf_put_raw_tracepoint(btp);
2932 out_put_prog:
2933         bpf_prog_put(prog);
2934         return err;
2935 }
2936
2937 static int bpf_prog_attach_check_attach_type(const struct bpf_prog *prog,
2938                                              enum bpf_attach_type attach_type)
2939 {
2940         switch (prog->type) {
2941         case BPF_PROG_TYPE_CGROUP_SOCK:
2942         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
2943         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
2944         case BPF_PROG_TYPE_SK_LOOKUP:
2945                 return attach_type == prog->expected_attach_type ? 0 : -EINVAL;
2946         case BPF_PROG_TYPE_CGROUP_SKB:
2947                 if (!capable(CAP_NET_ADMIN))
2948                         /* cg-skb progs can be loaded by unpriv user.
2949                          * check permissions at attach time.
2950                          */
2951                         return -EPERM;
2952                 return prog->enforce_expected_attach_type &&
2953                         prog->expected_attach_type != attach_type ?
2954                         -EINVAL : 0;
2955         default:
2956                 return 0;
2957         }
2958 }
2959
2960 static enum bpf_prog_type
2961 attach_type_to_prog_type(enum bpf_attach_type attach_type)
2962 {
2963         switch (attach_type) {
2964         case BPF_CGROUP_INET_INGRESS:
2965         case BPF_CGROUP_INET_EGRESS:
2966                 return BPF_PROG_TYPE_CGROUP_SKB;
2967         case BPF_CGROUP_INET_SOCK_CREATE:
2968         case BPF_CGROUP_INET_SOCK_RELEASE:
2969         case BPF_CGROUP_INET4_POST_BIND:
2970         case BPF_CGROUP_INET6_POST_BIND:
2971                 return BPF_PROG_TYPE_CGROUP_SOCK;
2972         case BPF_CGROUP_INET4_BIND:
2973         case BPF_CGROUP_INET6_BIND:
2974         case BPF_CGROUP_INET4_CONNECT:
2975         case BPF_CGROUP_INET6_CONNECT:
2976         case BPF_CGROUP_INET4_GETPEERNAME:
2977         case BPF_CGROUP_INET6_GETPEERNAME:
2978         case BPF_CGROUP_INET4_GETSOCKNAME:
2979         case BPF_CGROUP_INET6_GETSOCKNAME:
2980         case BPF_CGROUP_UDP4_SENDMSG:
2981         case BPF_CGROUP_UDP6_SENDMSG:
2982         case BPF_CGROUP_UDP4_RECVMSG:
2983         case BPF_CGROUP_UDP6_RECVMSG:
2984                 return BPF_PROG_TYPE_CGROUP_SOCK_ADDR;
2985         case BPF_CGROUP_SOCK_OPS:
2986                 return BPF_PROG_TYPE_SOCK_OPS;
2987         case BPF_CGROUP_DEVICE:
2988                 return BPF_PROG_TYPE_CGROUP_DEVICE;
2989         case BPF_SK_MSG_VERDICT:
2990                 return BPF_PROG_TYPE_SK_MSG;
2991         case BPF_SK_SKB_STREAM_PARSER:
2992         case BPF_SK_SKB_STREAM_VERDICT:
2993                 return BPF_PROG_TYPE_SK_SKB;
2994         case BPF_LIRC_MODE2:
2995                 return BPF_PROG_TYPE_LIRC_MODE2;
2996         case BPF_FLOW_DISSECTOR:
2997                 return BPF_PROG_TYPE_FLOW_DISSECTOR;
2998         case BPF_CGROUP_SYSCTL:
2999                 return BPF_PROG_TYPE_CGROUP_SYSCTL;
3000         case BPF_CGROUP_GETSOCKOPT:
3001         case BPF_CGROUP_SETSOCKOPT:
3002                 return BPF_PROG_TYPE_CGROUP_SOCKOPT;
3003         case BPF_TRACE_ITER:
3004                 return BPF_PROG_TYPE_TRACING;
3005         case BPF_SK_LOOKUP:
3006                 return BPF_PROG_TYPE_SK_LOOKUP;
3007         case BPF_XDP:
3008                 return BPF_PROG_TYPE_XDP;
3009         default:
3010                 return BPF_PROG_TYPE_UNSPEC;
3011         }
3012 }
3013
3014 #define BPF_PROG_ATTACH_LAST_FIELD replace_bpf_fd
3015
3016 #define BPF_F_ATTACH_MASK \
3017         (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI | BPF_F_REPLACE)
3018
3019 static int bpf_prog_attach(const union bpf_attr *attr)
3020 {
3021         enum bpf_prog_type ptype;
3022         struct bpf_prog *prog;
3023         int ret;
3024
3025         if (CHECK_ATTR(BPF_PROG_ATTACH))
3026                 return -EINVAL;
3027
3028         if (attr->attach_flags & ~BPF_F_ATTACH_MASK)
3029                 return -EINVAL;
3030
3031         ptype = attach_type_to_prog_type(attr->attach_type);
3032         if (ptype == BPF_PROG_TYPE_UNSPEC)
3033                 return -EINVAL;
3034
3035         prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
3036         if (IS_ERR(prog))
3037                 return PTR_ERR(prog);
3038
3039         if (bpf_prog_attach_check_attach_type(prog, attr->attach_type)) {
3040                 bpf_prog_put(prog);
3041                 return -EINVAL;
3042         }
3043
3044         switch (ptype) {
3045         case BPF_PROG_TYPE_SK_SKB:
3046         case BPF_PROG_TYPE_SK_MSG:
3047                 ret = sock_map_get_from_fd(attr, prog);
3048                 break;
3049         case BPF_PROG_TYPE_LIRC_MODE2:
3050                 ret = lirc_prog_attach(attr, prog);
3051                 break;
3052         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3053                 ret = netns_bpf_prog_attach(attr, prog);
3054                 break;
3055         case BPF_PROG_TYPE_CGROUP_DEVICE:
3056         case BPF_PROG_TYPE_CGROUP_SKB:
3057         case BPF_PROG_TYPE_CGROUP_SOCK:
3058         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3059         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3060         case BPF_PROG_TYPE_CGROUP_SYSCTL:
3061         case BPF_PROG_TYPE_SOCK_OPS:
3062                 ret = cgroup_bpf_prog_attach(attr, ptype, prog);
3063                 break;
3064         default:
3065                 ret = -EINVAL;
3066         }
3067
3068         if (ret)
3069                 bpf_prog_put(prog);
3070         return ret;
3071 }
3072
3073 #define BPF_PROG_DETACH_LAST_FIELD attach_type
3074
3075 static int bpf_prog_detach(const union bpf_attr *attr)
3076 {
3077         enum bpf_prog_type ptype;
3078
3079         if (CHECK_ATTR(BPF_PROG_DETACH))
3080                 return -EINVAL;
3081
3082         ptype = attach_type_to_prog_type(attr->attach_type);
3083
3084         switch (ptype) {
3085         case BPF_PROG_TYPE_SK_MSG:
3086         case BPF_PROG_TYPE_SK_SKB:
3087                 return sock_map_prog_detach(attr, ptype);
3088         case BPF_PROG_TYPE_LIRC_MODE2:
3089                 return lirc_prog_detach(attr);
3090         case BPF_PROG_TYPE_FLOW_DISSECTOR:
3091                 return netns_bpf_prog_detach(attr, ptype);
3092         case BPF_PROG_TYPE_CGROUP_DEVICE:
3093         case BPF_PROG_TYPE_CGROUP_SKB:
3094         case BPF_PROG_TYPE_CGROUP_SOCK:
3095         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
3096         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
3097         case BPF_PROG_TYPE_CGROUP_SYSCTL:
3098         case BPF_PROG_TYPE_SOCK_OPS:
3099                 return cgroup_bpf_prog_detach(attr, ptype);
3100         default:
3101                 return -EINVAL;
3102         }
3103 }
3104
3105 #define BPF_PROG_QUERY_LAST_FIELD query.prog_cnt
3106
3107 static int bpf_prog_query(const union bpf_attr *attr,
3108                           union bpf_attr __user *uattr)
3109 {
3110         if (!capable(CAP_NET_ADMIN))
3111                 return -EPERM;
3112         if (CHECK_ATTR(BPF_PROG_QUERY))
3113                 return -EINVAL;
3114         if (attr->query.query_flags & ~BPF_F_QUERY_EFFECTIVE)
3115                 return -EINVAL;
3116
3117         switch (attr->query.attach_type) {
3118         case BPF_CGROUP_INET_INGRESS:
3119         case BPF_CGROUP_INET_EGRESS:
3120         case BPF_CGROUP_INET_SOCK_CREATE:
3121         case BPF_CGROUP_INET_SOCK_RELEASE:
3122         case BPF_CGROUP_INET4_BIND:
3123         case BPF_CGROUP_INET6_BIND:
3124         case BPF_CGROUP_INET4_POST_BIND:
3125         case BPF_CGROUP_INET6_POST_BIND:
3126         case BPF_CGROUP_INET4_CONNECT:
3127         case BPF_CGROUP_INET6_CONNECT:
3128         case BPF_CGROUP_INET4_GETPEERNAME:
3129         case BPF_CGROUP_INET6_GETPEERNAME:
3130         case BPF_CGROUP_INET4_GETSOCKNAME:
3131         case BPF_CGROUP_INET6_GETSOCKNAME:
3132         case BPF_CGROUP_UDP4_SENDMSG:
3133         case BPF_CGROUP_UDP6_SENDMSG:
3134         case BPF_CGROUP_UDP4_RECVMSG:
3135         case BPF_CGROUP_UDP6_RECVMSG:
3136         case BPF_CGROUP_SOCK_OPS:
3137         case BPF_CGROUP_DEVICE:
3138         case BPF_CGROUP_SYSCTL:
3139         case BPF_CGROUP_GETSOCKOPT:
3140         case BPF_CGROUP_SETSOCKOPT:
3141                 return cgroup_bpf_prog_query(attr, uattr);
3142         case BPF_LIRC_MODE2:
3143                 return lirc_prog_query(attr, uattr);
3144         case BPF_FLOW_DISSECTOR:
3145         case BPF_SK_LOOKUP:
3146                 return netns_bpf_prog_query(attr, uattr);
3147         default:
3148                 return -EINVAL;
3149         }
3150 }
3151
3152 #define BPF_PROG_TEST_RUN_LAST_FIELD test.cpu
3153
3154 static int bpf_prog_test_run(const union bpf_attr *attr,
3155                              union bpf_attr __user *uattr)
3156 {
3157         struct bpf_prog *prog;
3158         int ret = -ENOTSUPP;
3159
3160         if (CHECK_ATTR(BPF_PROG_TEST_RUN))
3161                 return -EINVAL;
3162
3163         if ((attr->test.ctx_size_in && !attr->test.ctx_in) ||
3164             (!attr->test.ctx_size_in && attr->test.ctx_in))
3165                 return -EINVAL;
3166
3167         if ((attr->test.ctx_size_out && !attr->test.ctx_out) ||
3168             (!attr->test.ctx_size_out && attr->test.ctx_out))
3169                 return -EINVAL;
3170
3171         prog = bpf_prog_get(attr->test.prog_fd);
3172         if (IS_ERR(prog))
3173                 return PTR_ERR(prog);
3174
3175         if (prog->aux->ops->test_run)
3176                 ret = prog->aux->ops->test_run(prog, attr, uattr);
3177
3178         bpf_prog_put(prog);
3179         return ret;
3180 }
3181
3182 #define BPF_OBJ_GET_NEXT_ID_LAST_FIELD next_id
3183
3184 static int bpf_obj_get_next_id(const union bpf_attr *attr,
3185                                union bpf_attr __user *uattr,
3186                                struct idr *idr,
3187                                spinlock_t *lock)
3188 {
3189         u32 next_id = attr->start_id;
3190         int err = 0;
3191
3192         if (CHECK_ATTR(BPF_OBJ_GET_NEXT_ID) || next_id >= INT_MAX)
3193                 return -EINVAL;
3194
3195         if (!capable(CAP_SYS_ADMIN))
3196                 return -EPERM;
3197
3198         next_id++;
3199         spin_lock_bh(lock);
3200         if (!idr_get_next(idr, &next_id))
3201                 err = -ENOENT;
3202         spin_unlock_bh(lock);
3203
3204         if (!err)
3205                 err = put_user(next_id, &uattr->next_id);
3206
3207         return err;
3208 }
3209
3210 struct bpf_map *bpf_map_get_curr_or_next(u32 *id)
3211 {
3212         struct bpf_map *map;
3213
3214         spin_lock_bh(&map_idr_lock);
3215 again:
3216         map = idr_get_next(&map_idr, id);
3217         if (map) {
3218                 map = __bpf_map_inc_not_zero(map, false);
3219                 if (IS_ERR(map)) {
3220                         (*id)++;
3221                         goto again;
3222                 }
3223         }
3224         spin_unlock_bh(&map_idr_lock);
3225
3226         return map;
3227 }
3228
3229 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id)
3230 {
3231         struct bpf_prog *prog;
3232
3233         spin_lock_bh(&prog_idr_lock);
3234 again:
3235         prog = idr_get_next(&prog_idr, id);
3236         if (prog) {
3237                 prog = bpf_prog_inc_not_zero(prog);
3238                 if (IS_ERR(prog)) {
3239                         (*id)++;
3240                         goto again;
3241                 }
3242         }
3243         spin_unlock_bh(&prog_idr_lock);
3244
3245         return prog;
3246 }
3247
3248 #define BPF_PROG_GET_FD_BY_ID_LAST_FIELD prog_id
3249
3250 struct bpf_prog *bpf_prog_by_id(u32 id)
3251 {
3252         struct bpf_prog *prog;
3253
3254         if (!id)
3255                 return ERR_PTR(-ENOENT);
3256
3257         spin_lock_bh(&prog_idr_lock);
3258         prog = idr_find(&prog_idr, id);
3259         if (prog)
3260                 prog = bpf_prog_inc_not_zero(prog);
3261         else
3262                 prog = ERR_PTR(-ENOENT);
3263         spin_unlock_bh(&prog_idr_lock);
3264         return prog;
3265 }
3266
3267 static int bpf_prog_get_fd_by_id(const union bpf_attr *attr)
3268 {
3269         struct bpf_prog *prog;
3270         u32 id = attr->prog_id;
3271         int fd;
3272
3273         if (CHECK_ATTR(BPF_PROG_GET_FD_BY_ID))
3274                 return -EINVAL;
3275
3276         if (!capable(CAP_SYS_ADMIN))
3277                 return -EPERM;
3278
3279         prog = bpf_prog_by_id(id);
3280         if (IS_ERR(prog))
3281                 return PTR_ERR(prog);
3282
3283         fd = bpf_prog_new_fd(prog);
3284         if (fd < 0)
3285                 bpf_prog_put(prog);
3286
3287         return fd;
3288 }
3289
3290 #define BPF_MAP_GET_FD_BY_ID_LAST_FIELD open_flags
3291
3292 static int bpf_map_get_fd_by_id(const union bpf_attr *attr)
3293 {
3294         struct bpf_map *map;
3295         u32 id = attr->map_id;
3296         int f_flags;
3297         int fd;
3298
3299         if (CHECK_ATTR(BPF_MAP_GET_FD_BY_ID) ||
3300             attr->open_flags & ~BPF_OBJ_FLAG_MASK)
3301                 return -EINVAL;
3302
3303         if (!capable(CAP_SYS_ADMIN))
3304                 return -EPERM;
3305
3306         f_flags = bpf_get_file_flag(attr->open_flags);
3307         if (f_flags < 0)
3308                 return f_flags;
3309
3310         spin_lock_bh(&map_idr_lock);
3311         map = idr_find(&map_idr, id);
3312         if (map)
3313                 map = __bpf_map_inc_not_zero(map, true);
3314         else
3315                 map = ERR_PTR(-ENOENT);
3316         spin_unlock_bh(&map_idr_lock);
3317
3318         if (IS_ERR(map))
3319                 return PTR_ERR(map);
3320
3321         fd = bpf_map_new_fd(map, f_flags);
3322         if (fd < 0)
3323                 bpf_map_put_with_uref(map);
3324
3325         return fd;
3326 }
3327
3328 static const struct bpf_map *bpf_map_from_imm(const struct bpf_prog *prog,
3329                                               unsigned long addr, u32 *off,
3330                                               u32 *type)
3331 {
3332         const struct bpf_map *map;
3333         int i;
3334
3335         mutex_lock(&prog->aux->used_maps_mutex);
3336         for (i = 0, *off = 0; i < prog->aux->used_map_cnt; i++) {
3337                 map = prog->aux->used_maps[i];
3338                 if (map == (void *)addr) {
3339                         *type = BPF_PSEUDO_MAP_FD;
3340                         goto out;
3341                 }
3342                 if (!map->ops->map_direct_value_meta)
3343                         continue;
3344                 if (!map->ops->map_direct_value_meta(map, addr, off)) {
3345                         *type = BPF_PSEUDO_MAP_VALUE;
3346                         goto out;
3347                 }
3348         }
3349         map = NULL;
3350
3351 out:
3352         mutex_unlock(&prog->aux->used_maps_mutex);
3353         return map;
3354 }
3355
3356 static struct bpf_insn *bpf_insn_prepare_dump(const struct bpf_prog *prog,
3357                                               const struct cred *f_cred)
3358 {
3359         const struct bpf_map *map;
3360         struct bpf_insn *insns;
3361         u32 off, type;
3362         u64 imm;
3363         u8 code;
3364         int i;
3365
3366         insns = kmemdup(prog->insnsi, bpf_prog_insn_size(prog),
3367                         GFP_USER);
3368         if (!insns)
3369                 return insns;
3370
3371         for (i = 0; i < prog->len; i++) {
3372                 code = insns[i].code;
3373
3374                 if (code == (BPF_JMP | BPF_TAIL_CALL)) {
3375                         insns[i].code = BPF_JMP | BPF_CALL;
3376                         insns[i].imm = BPF_FUNC_tail_call;
3377                         /* fall-through */
3378                 }
3379                 if (code == (BPF_JMP | BPF_CALL) ||
3380                     code == (BPF_JMP | BPF_CALL_ARGS)) {
3381                         if (code == (BPF_JMP | BPF_CALL_ARGS))
3382                                 insns[i].code = BPF_JMP | BPF_CALL;
3383                         if (!bpf_dump_raw_ok(f_cred))
3384                                 insns[i].imm = 0;
3385                         continue;
3386                 }
3387                 if (BPF_CLASS(code) == BPF_LDX && BPF_MODE(code) == BPF_PROBE_MEM) {
3388                         insns[i].code = BPF_LDX | BPF_SIZE(code) | BPF_MEM;
3389                         continue;
3390                 }
3391
3392                 if (code != (BPF_LD | BPF_IMM | BPF_DW))
3393                         continue;
3394
3395                 imm = ((u64)insns[i + 1].imm << 32) | (u32)insns[i].imm;
3396                 map = bpf_map_from_imm(prog, imm, &off, &type);
3397                 if (map) {
3398                         insns[i].src_reg = type;
3399                         insns[i].imm = map->id;
3400                         insns[i + 1].imm = off;
3401                         continue;
3402                 }
3403         }
3404
3405         return insns;
3406 }
3407
3408 static int set_info_rec_size(struct bpf_prog_info *info)
3409 {
3410         /*
3411          * Ensure info.*_rec_size is the same as kernel expected size
3412          *
3413          * or
3414          *
3415          * Only allow zero *_rec_size if both _rec_size and _cnt are
3416          * zero.  In this case, the kernel will set the expected
3417          * _rec_size back to the info.
3418          */
3419
3420         if ((info->nr_func_info || info->func_info_rec_size) &&
3421             info->func_info_rec_size != sizeof(struct bpf_func_info))
3422                 return -EINVAL;
3423
3424         if ((info->nr_line_info || info->line_info_rec_size) &&
3425             info->line_info_rec_size != sizeof(struct bpf_line_info))
3426                 return -EINVAL;
3427
3428         if ((info->nr_jited_line_info || info->jited_line_info_rec_size) &&
3429             info->jited_line_info_rec_size != sizeof(__u64))
3430                 return -EINVAL;
3431
3432         info->func_info_rec_size = sizeof(struct bpf_func_info);
3433         info->line_info_rec_size = sizeof(struct bpf_line_info);
3434         info->jited_line_info_rec_size = sizeof(__u64);
3435
3436         return 0;
3437 }
3438
3439 static int bpf_prog_get_info_by_fd(struct file *file,
3440                                    struct bpf_prog *prog,
3441                                    const union bpf_attr *attr,
3442                                    union bpf_attr __user *uattr)
3443 {
3444         struct bpf_prog_info __user *uinfo = u64_to_user_ptr(attr->info.info);
3445         struct bpf_prog_info info;
3446         u32 info_len = attr->info.info_len;
3447         struct bpf_prog_stats stats;
3448         char __user *uinsns;
3449         u32 ulen;
3450         int err;
3451
3452         err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
3453         if (err)
3454                 return err;
3455         info_len = min_t(u32, sizeof(info), info_len);
3456
3457         memset(&info, 0, sizeof(info));
3458         if (copy_from_user(&info, uinfo, info_len))
3459                 return -EFAULT;
3460
3461         info.type = prog->type;
3462         info.id = prog->aux->id;
3463         info.load_time = prog->aux->load_time;
3464         info.created_by_uid = from_kuid_munged(current_user_ns(),
3465                                                prog->aux->user->uid);
3466         info.gpl_compatible = prog->gpl_compatible;
3467
3468         memcpy(info.tag, prog->tag, sizeof(prog->tag));
3469         memcpy(info.name, prog->aux->name, sizeof(prog->aux->name));
3470
3471         mutex_lock(&prog->aux->used_maps_mutex);
3472         ulen = info.nr_map_ids;
3473         info.nr_map_ids = prog->aux->used_map_cnt;
3474         ulen = min_t(u32, info.nr_map_ids, ulen);
3475         if (ulen) {
3476                 u32 __user *user_map_ids = u64_to_user_ptr(info.map_ids);
3477                 u32 i;
3478
3479                 for (i = 0; i < ulen; i++)
3480                         if (put_user(prog->aux->used_maps[i]->id,
3481                                      &user_map_ids[i])) {
3482                                 mutex_unlock(&prog->aux->used_maps_mutex);
3483                                 return -EFAULT;
3484                         }
3485         }
3486         mutex_unlock(&prog->aux->used_maps_mutex);
3487
3488         err = set_info_rec_size(&info);
3489         if (err)
3490                 return err;
3491
3492         bpf_prog_get_stats(prog, &stats);
3493         info.run_time_ns = stats.nsecs;
3494         info.run_cnt = stats.cnt;
3495
3496         if (!bpf_capable()) {
3497                 info.jited_prog_len = 0;
3498                 info.xlated_prog_len = 0;
3499                 info.nr_jited_ksyms = 0;
3500                 info.nr_jited_func_lens = 0;
3501                 info.nr_func_info = 0;
3502                 info.nr_line_info = 0;
3503                 info.nr_jited_line_info = 0;
3504                 goto done;
3505         }
3506
3507         ulen = info.xlated_prog_len;
3508         info.xlated_prog_len = bpf_prog_insn_size(prog);
3509         if (info.xlated_prog_len && ulen) {
3510                 struct bpf_insn *insns_sanitized;
3511                 bool fault;
3512
3513                 if (prog->blinded && !bpf_dump_raw_ok(file->f_cred)) {
3514                         info.xlated_prog_insns = 0;
3515                         goto done;
3516                 }
3517                 insns_sanitized = bpf_insn_prepare_dump(prog, file->f_cred);
3518                 if (!insns_sanitized)
3519                         return -ENOMEM;
3520                 uinsns = u64_to_user_ptr(info.xlated_prog_insns);
3521                 ulen = min_t(u32, info.xlated_prog_len, ulen);
3522                 fault = copy_to_user(uinsns, insns_sanitized, ulen);
3523                 kfree(insns_sanitized);
3524                 if (fault)
3525                         return -EFAULT;
3526         }
3527
3528         if (bpf_prog_is_dev_bound(prog->aux)) {
3529                 err = bpf_prog_offload_info_fill(&info, prog);
3530                 if (err)
3531                         return err;
3532                 goto done;
3533         }
3534
3535         /* NOTE: the following code is supposed to be skipped for offload.
3536          * bpf_prog_offload_info_fill() is the place to fill similar fields
3537          * for offload.
3538          */
3539         ulen = info.jited_prog_len;
3540         if (prog->aux->func_cnt) {
3541                 u32 i;
3542
3543                 info.jited_prog_len = 0;
3544                 for (i = 0; i < prog->aux->func_cnt; i++)
3545                         info.jited_prog_len += prog->aux->func[i]->jited_len;
3546         } else {
3547                 info.jited_prog_len = prog->jited_len;
3548         }
3549
3550         if (info.jited_prog_len && ulen) {
3551                 if (bpf_dump_raw_ok(file->f_cred)) {
3552                         uinsns = u64_to_user_ptr(info.jited_prog_insns);
3553                         ulen = min_t(u32, info.jited_prog_len, ulen);
3554
3555                         /* for multi-function programs, copy the JITed
3556                          * instructions for all the functions
3557                          */
3558                         if (prog->aux->func_cnt) {
3559                                 u32 len, free, i;
3560                                 u8 *img;
3561
3562                                 free = ulen;
3563                                 for (i = 0; i < prog->aux->func_cnt; i++) {
3564                                         len = prog->aux->func[i]->jited_len;
3565                                         len = min_t(u32, len, free);
3566                                         img = (u8 *) prog->aux->func[i]->bpf_func;
3567                                         if (copy_to_user(uinsns, img, len))
3568                                                 return -EFAULT;
3569                                         uinsns += len;
3570                                         free -= len;
3571                                         if (!free)
3572                                                 break;
3573                                 }
3574                         } else {
3575                                 if (copy_to_user(uinsns, prog->bpf_func, ulen))
3576                                         return -EFAULT;
3577                         }
3578                 } else {
3579                         info.jited_prog_insns = 0;
3580                 }
3581         }
3582
3583         ulen = info.nr_jited_ksyms;
3584         info.nr_jited_ksyms = prog->aux->func_cnt ? : 1;
3585         if (ulen) {
3586                 if (bpf_dump_raw_ok(file->f_cred)) {
3587                         unsigned long ksym_addr;
3588                         u64 __user *user_ksyms;
3589                         u32 i;
3590
3591                         /* copy the address of the kernel symbol
3592                          * corresponding to each function
3593                          */
3594                         ulen = min_t(u32, info.nr_jited_ksyms, ulen);
3595                         user_ksyms = u64_to_user_ptr(info.jited_ksyms);
3596                         if (prog->aux->func_cnt) {
3597                                 for (i = 0; i < ulen; i++) {
3598                                         ksym_addr = (unsigned long)
3599                                                 prog->aux->func[i]->bpf_func;
3600                                         if (put_user((u64) ksym_addr,
3601                                                      &user_ksyms[i]))
3602                                                 return -EFAULT;
3603                                 }
3604                         } else {
3605                                 ksym_addr = (unsigned long) prog->bpf_func;
3606                                 if (put_user((u64) ksym_addr, &user_ksyms[0]))
3607                                         return -EFAULT;
3608                         }
3609                 } else {
3610                         info.jited_ksyms = 0;
3611                 }
3612         }
3613
3614         ulen = info.nr_jited_func_lens;
3615         info.nr_jited_func_lens = prog->aux->func_cnt ? : 1;
3616         if (ulen) {
3617                 if (bpf_dump_raw_ok(file->f_cred)) {
3618                         u32 __user *user_lens;
3619                         u32 func_len, i;
3620
3621                         /* copy the JITed image lengths for each function */
3622                         ulen = min_t(u32, info.nr_jited_func_lens, ulen);
3623                         user_lens = u64_to_user_ptr(info.jited_func_lens);
3624                         if (prog->aux->func_cnt) {
3625                                 for (i = 0; i < ulen; i++) {
3626                                         func_len =
3627                                                 prog->aux->func[i]->jited_len;
3628                                         if (put_user(func_len, &user_lens[i]))
3629                                                 return -EFAULT;
3630                                 }
3631                         } else {
3632                                 func_len = prog->jited_len;
3633                                 if (put_user(func_len, &user_lens[0]))
3634                                         return -EFAULT;
3635                         }
3636                 } else {
3637                         info.jited_func_lens = 0;
3638                 }
3639         }
3640
3641         if (prog->aux->btf)
3642                 info.btf_id = btf_id(prog->aux->btf);
3643
3644         ulen = info.nr_func_info;
3645         info.nr_func_info = prog->aux->func_info_cnt;
3646         if (info.nr_func_info && ulen) {
3647                 char __user *user_finfo;
3648
3649                 user_finfo = u64_to_user_ptr(info.func_info);
3650                 ulen = min_t(u32, info.nr_func_info, ulen);
3651                 if (copy_to_user(user_finfo, prog->aux->func_info,
3652                                  info.func_info_rec_size * ulen))
3653                         return -EFAULT;
3654         }
3655
3656         ulen = info.nr_line_info;
3657         info.nr_line_info = prog->aux->nr_linfo;
3658         if (info.nr_line_info && ulen) {
3659                 __u8 __user *user_linfo;
3660
3661                 user_linfo = u64_to_user_ptr(info.line_info);
3662                 ulen = min_t(u32, info.nr_line_info, ulen);
3663                 if (copy_to_user(user_linfo, prog->aux->linfo,
3664                                  info.line_info_rec_size * ulen))
3665                         return -EFAULT;
3666         }
3667
3668         ulen = info.nr_jited_line_info;
3669         if (prog->aux->jited_linfo)
3670                 info.nr_jited_line_info = prog->aux->nr_linfo;
3671         else
3672                 info.nr_jited_line_info = 0;
3673         if (info.nr_jited_line_info && ulen) {
3674                 if (bpf_dump_raw_ok(file->f_cred)) {
3675                         __u64 __user *user_linfo;
3676                         u32 i;
3677
3678                         user_linfo = u64_to_user_ptr(info.jited_line_info);
3679                         ulen = min_t(u32, info.nr_jited_line_info, ulen);
3680                         for (i = 0; i < ulen; i++) {
3681                                 if (put_user((__u64)(long)prog->aux->jited_linfo[i],
3682                                              &user_linfo[i]))
3683                                         return -EFAULT;
3684                         }
3685                 } else {
3686                         info.jited_line_info = 0;
3687                 }
3688         }
3689
3690         ulen = info.nr_prog_tags;
3691         info.nr_prog_tags = prog->aux->func_cnt ? : 1;
3692         if (ulen) {
3693                 __u8 __user (*user_prog_tags)[BPF_TAG_SIZE];
3694                 u32 i;
3695
3696                 user_prog_tags = u64_to_user_ptr(info.prog_tags);
3697                 ulen = min_t(u32, info.nr_prog_tags, ulen);
3698                 if (prog->aux->func_cnt) {
3699                         for (i = 0; i < ulen; i++) {
3700                                 if (copy_to_user(user_prog_tags[i],
3701                                                  prog->aux->func[i]->tag,
3702                                                  BPF_TAG_SIZE))
3703                                         return -EFAULT;
3704                         }
3705                 } else {
3706                         if (copy_to_user(user_prog_tags[0],
3707                                          prog->tag, BPF_TAG_SIZE))
3708                                 return -EFAULT;
3709                 }
3710         }
3711
3712 done:
3713         if (copy_to_user(uinfo, &info, info_len) ||
3714             put_user(info_len, &uattr->info.info_len))
3715                 return -EFAULT;
3716
3717         return 0;
3718 }
3719
3720 static int bpf_map_get_info_by_fd(struct file *file,
3721                                   struct bpf_map *map,
3722                                   const union bpf_attr *attr,
3723                                   union bpf_attr __user *uattr)
3724 {
3725         struct bpf_map_info __user *uinfo = u64_to_user_ptr(attr->info.info);
3726         struct bpf_map_info info;
3727         u32 info_len = attr->info.info_len;
3728         int err;
3729
3730         err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
3731         if (err)
3732                 return err;
3733         info_len = min_t(u32, sizeof(info), info_len);
3734
3735         memset(&info, 0, sizeof(info));
3736         info.type = map->map_type;
3737         info.id = map->id;
3738         info.key_size = map->key_size;
3739         info.value_size = map->value_size;
3740         info.max_entries = map->max_entries;
3741         info.map_flags = map->map_flags;
3742         memcpy(info.name, map->name, sizeof(map->name));
3743
3744         if (map->btf) {
3745                 info.btf_id = btf_id(map->btf);
3746                 info.btf_key_type_id = map->btf_key_type_id;
3747                 info.btf_value_type_id = map->btf_value_type_id;
3748         }
3749         info.btf_vmlinux_value_type_id = map->btf_vmlinux_value_type_id;
3750
3751         if (bpf_map_is_dev_bound(map)) {
3752                 err = bpf_map_offload_info_fill(&info, map);
3753                 if (err)
3754                         return err;
3755         }
3756
3757         if (copy_to_user(uinfo, &info, info_len) ||
3758             put_user(info_len, &uattr->info.info_len))
3759                 return -EFAULT;
3760
3761         return 0;
3762 }
3763
3764 static int bpf_btf_get_info_by_fd(struct file *file,
3765                                   struct btf *btf,
3766                                   const union bpf_attr *attr,
3767                                   union bpf_attr __user *uattr)
3768 {
3769         struct bpf_btf_info __user *uinfo = u64_to_user_ptr(attr->info.info);
3770         u32 info_len = attr->info.info_len;
3771         int err;
3772
3773         err = bpf_check_uarg_tail_zero(uinfo, sizeof(*uinfo), info_len);
3774         if (err)
3775                 return err;
3776
3777         return btf_get_info_by_fd(btf, attr, uattr);
3778 }
3779
3780 static int bpf_link_get_info_by_fd(struct file *file,
3781                                   struct bpf_link *link,
3782                                   const union bpf_attr *attr,
3783                                   union bpf_attr __user *uattr)
3784 {
3785         struct bpf_link_info __user *uinfo = u64_to_user_ptr(attr->info.info);
3786         struct bpf_link_info info;
3787         u32 info_len = attr->info.info_len;
3788         int err;
3789
3790         err = bpf_check_uarg_tail_zero(uinfo, sizeof(info), info_len);
3791         if (err)
3792                 return err;
3793         info_len = min_t(u32, sizeof(info), info_len);
3794
3795         memset(&info, 0, sizeof(info));
3796         if (copy_from_user(&info, uinfo, info_len))
3797                 return -EFAULT;
3798
3799         info.type = link->type;
3800         info.id = link->id;
3801         info.prog_id = link->prog->aux->id;
3802
3803         if (link->ops->fill_link_info) {
3804                 err = link->ops->fill_link_info(link, &info);
3805                 if (err)
3806                         return err;
3807         }
3808
3809         if (copy_to_user(uinfo, &info, info_len) ||
3810             put_user(info_len, &uattr->info.info_len))
3811                 return -EFAULT;
3812
3813         return 0;
3814 }
3815
3816
3817 #define BPF_OBJ_GET_INFO_BY_FD_LAST_FIELD info.info
3818
3819 static int bpf_obj_get_info_by_fd(const union bpf_attr *attr,
3820                                   union bpf_attr __user *uattr)
3821 {
3822         int ufd = attr->info.bpf_fd;
3823         struct fd f;
3824         int err;
3825
3826         if (CHECK_ATTR(BPF_OBJ_GET_INFO_BY_FD))
3827                 return -EINVAL;
3828
3829         f = fdget(ufd);
3830         if (!f.file)
3831                 return -EBADFD;
3832
3833         if (f.file->f_op == &bpf_prog_fops)
3834                 err = bpf_prog_get_info_by_fd(f.file, f.file->private_data, attr,
3835                                               uattr);
3836         else if (f.file->f_op == &bpf_map_fops)
3837                 err = bpf_map_get_info_by_fd(f.file, f.file->private_data, attr,
3838                                              uattr);
3839         else if (f.file->f_op == &btf_fops)
3840                 err = bpf_btf_get_info_by_fd(f.file, f.file->private_data, attr, uattr);
3841         else if (f.file->f_op == &bpf_link_fops)
3842                 err = bpf_link_get_info_by_fd(f.file, f.file->private_data,
3843                                               attr, uattr);
3844         else
3845                 err = -EINVAL;
3846
3847         fdput(f);
3848         return err;
3849 }
3850
3851 #define BPF_BTF_LOAD_LAST_FIELD btf_log_level
3852
3853 static int bpf_btf_load(const union bpf_attr *attr)
3854 {
3855         if (CHECK_ATTR(BPF_BTF_LOAD))
3856                 return -EINVAL;
3857
3858         if (!bpf_capable())
3859                 return -EPERM;
3860
3861         return btf_new_fd(attr);
3862 }
3863
3864 #define BPF_BTF_GET_FD_BY_ID_LAST_FIELD btf_id
3865
3866 static int bpf_btf_get_fd_by_id(const union bpf_attr *attr)
3867 {
3868         if (CHECK_ATTR(BPF_BTF_GET_FD_BY_ID))
3869                 return -EINVAL;
3870
3871         if (!capable(CAP_SYS_ADMIN))
3872                 return -EPERM;
3873
3874         return btf_get_fd_by_id(attr->btf_id);
3875 }
3876
3877 static int bpf_task_fd_query_copy(const union bpf_attr *attr,
3878                                     union bpf_attr __user *uattr,
3879                                     u32 prog_id, u32 fd_type,
3880                                     const char *buf, u64 probe_offset,
3881                                     u64 probe_addr)
3882 {
3883         char __user *ubuf = u64_to_user_ptr(attr->task_fd_query.buf);
3884         u32 len = buf ? strlen(buf) : 0, input_len;
3885         int err = 0;
3886
3887         if (put_user(len, &uattr->task_fd_query.buf_len))
3888                 return -EFAULT;
3889         input_len = attr->task_fd_query.buf_len;
3890         if (input_len && ubuf) {
3891                 if (!len) {
3892                         /* nothing to copy, just make ubuf NULL terminated */
3893                         char zero = '\0';
3894
3895                         if (put_user(zero, ubuf))
3896                                 return -EFAULT;
3897                 } else if (input_len >= len + 1) {
3898                         /* ubuf can hold the string with NULL terminator */
3899                         if (copy_to_user(ubuf, buf, len + 1))
3900                                 return -EFAULT;
3901                 } else {
3902                         /* ubuf cannot hold the string with NULL terminator,
3903                          * do a partial copy with NULL terminator.
3904                          */
3905                         char zero = '\0';
3906
3907                         err = -ENOSPC;
3908                         if (copy_to_user(ubuf, buf, input_len - 1))
3909                                 return -EFAULT;
3910                         if (put_user(zero, ubuf + input_len - 1))
3911                                 return -EFAULT;
3912                 }
3913         }
3914
3915         if (put_user(prog_id, &uattr->task_fd_query.prog_id) ||
3916             put_user(fd_type, &uattr->task_fd_query.fd_type) ||
3917             put_user(probe_offset, &uattr->task_fd_query.probe_offset) ||
3918             put_user(probe_addr, &uattr->task_fd_query.probe_addr))
3919                 return -EFAULT;
3920
3921         return err;
3922 }
3923
3924 #define BPF_TASK_FD_QUERY_LAST_FIELD task_fd_query.probe_addr
3925
3926 static int bpf_task_fd_query(const union bpf_attr *attr,
3927                              union bpf_attr __user *uattr)
3928 {
3929         pid_t pid = attr->task_fd_query.pid;
3930         u32 fd = attr->task_fd_query.fd;
3931         const struct perf_event *event;
3932         struct files_struct *files;
3933         struct task_struct *task;
3934         struct file *file;
3935         int err;
3936
3937         if (CHECK_ATTR(BPF_TASK_FD_QUERY))
3938                 return -EINVAL;
3939
3940         if (!capable(CAP_SYS_ADMIN))
3941                 return -EPERM;
3942
3943         if (attr->task_fd_query.flags != 0)
3944                 return -EINVAL;
3945
3946         rcu_read_lock();
3947         task = get_pid_task(find_vpid(pid), PIDTYPE_PID);
3948         rcu_read_unlock();
3949         if (!task)
3950                 return -ENOENT;
3951
3952         files = get_files_struct(task);
3953         put_task_struct(task);
3954         if (!files)
3955                 return -ENOENT;
3956
3957         err = 0;
3958         spin_lock(&files->file_lock);
3959         file = fcheck_files(files, fd);
3960         if (!file)
3961                 err = -EBADF;
3962         else
3963                 get_file(file);
3964         spin_unlock(&files->file_lock);
3965         put_files_struct(files);
3966
3967         if (err)
3968                 goto out;
3969
3970         if (file->f_op == &bpf_link_fops) {
3971                 struct bpf_link *link = file->private_data;
3972
3973                 if (link->ops == &bpf_raw_tp_link_lops) {
3974                         struct bpf_raw_tp_link *raw_tp =
3975                                 container_of(link, struct bpf_raw_tp_link, link);
3976                         struct bpf_raw_event_map *btp = raw_tp->btp;
3977
3978                         err = bpf_task_fd_query_copy(attr, uattr,
3979                                                      raw_tp->link.prog->aux->id,
3980                                                      BPF_FD_TYPE_RAW_TRACEPOINT,
3981                                                      btp->tp->name, 0, 0);
3982                         goto put_file;
3983                 }
3984                 goto out_not_supp;
3985         }
3986
3987         event = perf_get_event(file);
3988         if (!IS_ERR(event)) {
3989                 u64 probe_offset, probe_addr;
3990                 u32 prog_id, fd_type;
3991                 const char *buf;
3992
3993                 err = bpf_get_perf_event_info(event, &prog_id, &fd_type,
3994                                               &buf, &probe_offset,
3995                                               &probe_addr);
3996                 if (!err)
3997                         err = bpf_task_fd_query_copy(attr, uattr, prog_id,
3998                                                      fd_type, buf,
3999                                                      probe_offset,
4000                                                      probe_addr);
4001                 goto put_file;
4002         }
4003
4004 out_not_supp:
4005         err = -ENOTSUPP;
4006 put_file:
4007         fput(file);
4008 out:
4009         return err;
4010 }
4011
4012 #define BPF_MAP_BATCH_LAST_FIELD batch.flags
4013
4014 #define BPF_DO_BATCH(fn)                        \
4015         do {                                    \
4016                 if (!fn) {                      \
4017                         err = -ENOTSUPP;        \
4018                         goto err_put;           \
4019                 }                               \
4020                 err = fn(map, attr, uattr);     \
4021         } while (0)
4022
4023 static int bpf_map_do_batch(const union bpf_attr *attr,
4024                             union bpf_attr __user *uattr,
4025                             int cmd)
4026 {
4027         bool has_read  = cmd == BPF_MAP_LOOKUP_BATCH ||
4028                          cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH;
4029         bool has_write = cmd != BPF_MAP_LOOKUP_BATCH;
4030         struct bpf_map *map;
4031         int err, ufd;
4032         struct fd f;
4033
4034         if (CHECK_ATTR(BPF_MAP_BATCH))
4035                 return -EINVAL;
4036
4037         ufd = attr->batch.map_fd;
4038         f = fdget(ufd);
4039         map = __bpf_map_get(f);
4040         if (IS_ERR(map))
4041                 return PTR_ERR(map);
4042         if (has_write)
4043                 bpf_map_write_active_inc(map);
4044         if (has_read && !(map_get_sys_perms(map, f) & FMODE_CAN_READ)) {
4045                 err = -EPERM;
4046                 goto err_put;
4047         }
4048         if (has_write && !(map_get_sys_perms(map, f) & FMODE_CAN_WRITE)) {
4049                 err = -EPERM;
4050                 goto err_put;
4051         }
4052
4053         if (cmd == BPF_MAP_LOOKUP_BATCH)
4054                 BPF_DO_BATCH(map->ops->map_lookup_batch);
4055         else if (cmd == BPF_MAP_LOOKUP_AND_DELETE_BATCH)
4056                 BPF_DO_BATCH(map->ops->map_lookup_and_delete_batch);
4057         else if (cmd == BPF_MAP_UPDATE_BATCH)
4058                 BPF_DO_BATCH(map->ops->map_update_batch);
4059         else
4060                 BPF_DO_BATCH(map->ops->map_delete_batch);
4061 err_put:
4062         if (has_write)
4063                 bpf_map_write_active_dec(map);
4064         fdput(f);
4065         return err;
4066 }
4067
4068 static int tracing_bpf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
4069 {
4070         if (attr->link_create.attach_type != prog->expected_attach_type)
4071                 return -EINVAL;
4072
4073         if (prog->expected_attach_type == BPF_TRACE_ITER)
4074                 return bpf_iter_link_attach(attr, prog);
4075         else if (prog->type == BPF_PROG_TYPE_EXT)
4076                 return bpf_tracing_prog_attach(prog,
4077                                                attr->link_create.target_fd,
4078                                                attr->link_create.target_btf_id);
4079         return -EINVAL;
4080 }
4081
4082 #define BPF_LINK_CREATE_LAST_FIELD link_create.iter_info_len
4083 static int link_create(union bpf_attr *attr)
4084 {
4085         enum bpf_prog_type ptype;
4086         struct bpf_prog *prog;
4087         int ret;
4088
4089         if (CHECK_ATTR(BPF_LINK_CREATE))
4090                 return -EINVAL;
4091
4092         prog = bpf_prog_get(attr->link_create.prog_fd);
4093         if (IS_ERR(prog))
4094                 return PTR_ERR(prog);
4095
4096         ret = bpf_prog_attach_check_attach_type(prog,
4097                                                 attr->link_create.attach_type);
4098         if (ret)
4099                 goto out;
4100
4101         if (prog->type == BPF_PROG_TYPE_EXT) {
4102                 ret = tracing_bpf_link_attach(attr, prog);
4103                 goto out;
4104         }
4105
4106         ptype = attach_type_to_prog_type(attr->link_create.attach_type);
4107         if (ptype == BPF_PROG_TYPE_UNSPEC || ptype != prog->type) {
4108                 ret = -EINVAL;
4109                 goto out;
4110         }
4111
4112         switch (ptype) {
4113         case BPF_PROG_TYPE_CGROUP_SKB:
4114         case BPF_PROG_TYPE_CGROUP_SOCK:
4115         case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
4116         case BPF_PROG_TYPE_SOCK_OPS:
4117         case BPF_PROG_TYPE_CGROUP_DEVICE:
4118         case BPF_PROG_TYPE_CGROUP_SYSCTL:
4119         case BPF_PROG_TYPE_CGROUP_SOCKOPT:
4120                 ret = cgroup_bpf_link_attach(attr, prog);
4121                 break;
4122         case BPF_PROG_TYPE_TRACING:
4123                 ret = tracing_bpf_link_attach(attr, prog);
4124                 break;
4125         case BPF_PROG_TYPE_FLOW_DISSECTOR:
4126         case BPF_PROG_TYPE_SK_LOOKUP:
4127                 ret = netns_bpf_link_create(attr, prog);
4128                 break;
4129 #ifdef CONFIG_NET
4130         case BPF_PROG_TYPE_XDP:
4131                 ret = bpf_xdp_link_attach(attr, prog);
4132                 break;
4133 #endif
4134         default:
4135                 ret = -EINVAL;
4136         }
4137
4138 out:
4139         if (ret < 0)
4140                 bpf_prog_put(prog);
4141         return ret;
4142 }
4143
4144 #define BPF_LINK_UPDATE_LAST_FIELD link_update.old_prog_fd
4145
4146 static int link_update(union bpf_attr *attr)
4147 {
4148         struct bpf_prog *old_prog = NULL, *new_prog;
4149         struct bpf_link *link;
4150         u32 flags;
4151         int ret;
4152
4153         if (CHECK_ATTR(BPF_LINK_UPDATE))
4154                 return -EINVAL;
4155
4156         flags = attr->link_update.flags;
4157         if (flags & ~BPF_F_REPLACE)
4158                 return -EINVAL;
4159
4160         link = bpf_link_get_from_fd(attr->link_update.link_fd);
4161         if (IS_ERR(link))
4162                 return PTR_ERR(link);
4163
4164         new_prog = bpf_prog_get(attr->link_update.new_prog_fd);
4165         if (IS_ERR(new_prog)) {
4166                 ret = PTR_ERR(new_prog);
4167                 goto out_put_link;
4168         }
4169
4170         if (flags & BPF_F_REPLACE) {
4171                 old_prog = bpf_prog_get(attr->link_update.old_prog_fd);
4172                 if (IS_ERR(old_prog)) {
4173                         ret = PTR_ERR(old_prog);
4174                         old_prog = NULL;
4175                         goto out_put_progs;
4176                 }
4177         } else if (attr->link_update.old_prog_fd) {
4178                 ret = -EINVAL;
4179                 goto out_put_progs;
4180         }
4181
4182         if (link->ops->update_prog)
4183                 ret = link->ops->update_prog(link, new_prog, old_prog);
4184         else
4185                 ret = -EINVAL;
4186
4187 out_put_progs:
4188         if (old_prog)
4189                 bpf_prog_put(old_prog);
4190         if (ret)
4191                 bpf_prog_put(new_prog);
4192 out_put_link:
4193         bpf_link_put(link);
4194         return ret;
4195 }
4196
4197 #define BPF_LINK_DETACH_LAST_FIELD link_detach.link_fd
4198
4199 static int link_detach(union bpf_attr *attr)
4200 {
4201         struct bpf_link *link;
4202         int ret;
4203
4204         if (CHECK_ATTR(BPF_LINK_DETACH))
4205                 return -EINVAL;
4206
4207         link = bpf_link_get_from_fd(attr->link_detach.link_fd);
4208         if (IS_ERR(link))
4209                 return PTR_ERR(link);
4210
4211         if (link->ops->detach)
4212                 ret = link->ops->detach(link);
4213         else
4214                 ret = -EOPNOTSUPP;
4215
4216         bpf_link_put(link);
4217         return ret;
4218 }
4219
4220 static struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
4221 {
4222         return atomic64_fetch_add_unless(&link->refcnt, 1, 0) ? link : ERR_PTR(-ENOENT);
4223 }
4224
4225 struct bpf_link *bpf_link_by_id(u32 id)
4226 {
4227         struct bpf_link *link;
4228
4229         if (!id)
4230                 return ERR_PTR(-ENOENT);
4231
4232         spin_lock_bh(&link_idr_lock);
4233         /* before link is "settled", ID is 0, pretend it doesn't exist yet */
4234         link = idr_find(&link_idr, id);
4235         if (link) {
4236                 if (link->id)
4237                         link = bpf_link_inc_not_zero(link);
4238                 else
4239                         link = ERR_PTR(-EAGAIN);
4240         } else {
4241                 link = ERR_PTR(-ENOENT);
4242         }
4243         spin_unlock_bh(&link_idr_lock);
4244         return link;
4245 }
4246
4247 #define BPF_LINK_GET_FD_BY_ID_LAST_FIELD link_id
4248
4249 static int bpf_link_get_fd_by_id(const union bpf_attr *attr)
4250 {
4251         struct bpf_link *link;
4252         u32 id = attr->link_id;
4253         int fd;
4254
4255         if (CHECK_ATTR(BPF_LINK_GET_FD_BY_ID))
4256                 return -EINVAL;
4257
4258         if (!capable(CAP_SYS_ADMIN))
4259                 return -EPERM;
4260
4261         link = bpf_link_by_id(id);
4262         if (IS_ERR(link))
4263                 return PTR_ERR(link);
4264
4265         fd = bpf_link_new_fd(link);
4266         if (fd < 0)
4267                 bpf_link_put(link);
4268
4269         return fd;
4270 }
4271
4272 DEFINE_MUTEX(bpf_stats_enabled_mutex);
4273
4274 static int bpf_stats_release(struct inode *inode, struct file *file)
4275 {
4276         mutex_lock(&bpf_stats_enabled_mutex);
4277         static_key_slow_dec(&bpf_stats_enabled_key.key);
4278         mutex_unlock(&bpf_stats_enabled_mutex);
4279         return 0;
4280 }
4281
4282 static const struct file_operations bpf_stats_fops = {
4283         .release = bpf_stats_release,
4284 };
4285
4286 static int bpf_enable_runtime_stats(void)
4287 {
4288         int fd;
4289
4290         mutex_lock(&bpf_stats_enabled_mutex);
4291
4292         /* Set a very high limit to avoid overflow */
4293         if (static_key_count(&bpf_stats_enabled_key.key) > INT_MAX / 2) {
4294                 mutex_unlock(&bpf_stats_enabled_mutex);
4295                 return -EBUSY;
4296         }
4297
4298         fd = anon_inode_getfd("bpf-stats", &bpf_stats_fops, NULL, O_CLOEXEC);
4299         if (fd >= 0)
4300                 static_key_slow_inc(&bpf_stats_enabled_key.key);
4301
4302         mutex_unlock(&bpf_stats_enabled_mutex);
4303         return fd;
4304 }
4305
4306 #define BPF_ENABLE_STATS_LAST_FIELD enable_stats.type
4307
4308 static int bpf_enable_stats(union bpf_attr *attr)
4309 {
4310
4311         if (CHECK_ATTR(BPF_ENABLE_STATS))
4312                 return -EINVAL;
4313
4314         if (!capable(CAP_SYS_ADMIN))
4315                 return -EPERM;
4316
4317         switch (attr->enable_stats.type) {
4318         case BPF_STATS_RUN_TIME:
4319                 return bpf_enable_runtime_stats();
4320         default:
4321                 break;
4322         }
4323         return -EINVAL;
4324 }
4325
4326 #define BPF_ITER_CREATE_LAST_FIELD iter_create.flags
4327
4328 static int bpf_iter_create(union bpf_attr *attr)
4329 {
4330         struct bpf_link *link;
4331         int err;
4332
4333         if (CHECK_ATTR(BPF_ITER_CREATE))
4334                 return -EINVAL;
4335
4336         if (attr->iter_create.flags)
4337                 return -EINVAL;
4338
4339         link = bpf_link_get_from_fd(attr->iter_create.link_fd);
4340         if (IS_ERR(link))
4341                 return PTR_ERR(link);
4342
4343         err = bpf_iter_new_fd(link);
4344         bpf_link_put(link);
4345
4346         return err;
4347 }
4348
4349 #define BPF_PROG_BIND_MAP_LAST_FIELD prog_bind_map.flags
4350
4351 static int bpf_prog_bind_map(union bpf_attr *attr)
4352 {
4353         struct bpf_prog *prog;
4354         struct bpf_map *map;
4355         struct bpf_map **used_maps_old, **used_maps_new;
4356         int i, ret = 0;
4357
4358         if (CHECK_ATTR(BPF_PROG_BIND_MAP))
4359                 return -EINVAL;
4360
4361         if (attr->prog_bind_map.flags)
4362                 return -EINVAL;
4363
4364         prog = bpf_prog_get(attr->prog_bind_map.prog_fd);
4365         if (IS_ERR(prog))
4366                 return PTR_ERR(prog);
4367
4368         map = bpf_map_get(attr->prog_bind_map.map_fd);
4369         if (IS_ERR(map)) {
4370                 ret = PTR_ERR(map);
4371                 goto out_prog_put;
4372         }
4373
4374         mutex_lock(&prog->aux->used_maps_mutex);
4375
4376         used_maps_old = prog->aux->used_maps;
4377
4378         for (i = 0; i < prog->aux->used_map_cnt; i++)
4379                 if (used_maps_old[i] == map) {
4380                         bpf_map_put(map);
4381                         goto out_unlock;
4382                 }
4383
4384         used_maps_new = kmalloc_array(prog->aux->used_map_cnt + 1,
4385                                       sizeof(used_maps_new[0]),
4386                                       GFP_KERNEL);
4387         if (!used_maps_new) {
4388                 ret = -ENOMEM;
4389                 goto out_unlock;
4390         }
4391
4392         memcpy(used_maps_new, used_maps_old,
4393                sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
4394         used_maps_new[prog->aux->used_map_cnt] = map;
4395
4396         prog->aux->used_map_cnt++;
4397         prog->aux->used_maps = used_maps_new;
4398
4399         kfree(used_maps_old);
4400
4401 out_unlock:
4402         mutex_unlock(&prog->aux->used_maps_mutex);
4403
4404         if (ret)
4405                 bpf_map_put(map);
4406 out_prog_put:
4407         bpf_prog_put(prog);
4408         return ret;
4409 }
4410
4411 SYSCALL_DEFINE3(bpf, int, cmd, union bpf_attr __user *, uattr, unsigned int, size)
4412 {
4413         union bpf_attr attr;
4414         int err;
4415
4416         if (sysctl_unprivileged_bpf_disabled && !bpf_capable())
4417                 return -EPERM;
4418
4419         err = bpf_check_uarg_tail_zero(uattr, sizeof(attr), size);
4420         if (err)
4421                 return err;
4422         size = min_t(u32, size, sizeof(attr));
4423
4424         /* copy attributes from user space, may be less than sizeof(bpf_attr) */
4425         memset(&attr, 0, sizeof(attr));
4426         if (copy_from_user(&attr, uattr, size) != 0)
4427                 return -EFAULT;
4428
4429         err = security_bpf(cmd, &attr, size);
4430         if (err < 0)
4431                 return err;
4432
4433         switch (cmd) {
4434         case BPF_MAP_CREATE:
4435                 err = map_create(&attr);
4436                 break;
4437         case BPF_MAP_LOOKUP_ELEM:
4438                 err = map_lookup_elem(&attr);
4439                 break;
4440         case BPF_MAP_UPDATE_ELEM:
4441                 err = map_update_elem(&attr);
4442                 break;
4443         case BPF_MAP_DELETE_ELEM:
4444                 err = map_delete_elem(&attr);
4445                 break;
4446         case BPF_MAP_GET_NEXT_KEY:
4447                 err = map_get_next_key(&attr);
4448                 break;
4449         case BPF_MAP_FREEZE:
4450                 err = map_freeze(&attr);
4451                 break;
4452         case BPF_PROG_LOAD:
4453                 err = bpf_prog_load(&attr, uattr);
4454                 break;
4455         case BPF_OBJ_PIN:
4456                 err = bpf_obj_pin(&attr);
4457                 break;
4458         case BPF_OBJ_GET:
4459                 err = bpf_obj_get(&attr);
4460                 break;
4461         case BPF_PROG_ATTACH:
4462                 err = bpf_prog_attach(&attr);
4463                 break;
4464         case BPF_PROG_DETACH:
4465                 err = bpf_prog_detach(&attr);
4466                 break;
4467         case BPF_PROG_QUERY:
4468                 err = bpf_prog_query(&attr, uattr);
4469                 break;
4470         case BPF_PROG_TEST_RUN:
4471                 err = bpf_prog_test_run(&attr, uattr);
4472                 break;
4473         case BPF_PROG_GET_NEXT_ID:
4474                 err = bpf_obj_get_next_id(&attr, uattr,
4475                                           &prog_idr, &prog_idr_lock);
4476                 break;
4477         case BPF_MAP_GET_NEXT_ID:
4478                 err = bpf_obj_get_next_id(&attr, uattr,
4479                                           &map_idr, &map_idr_lock);
4480                 break;
4481         case BPF_BTF_GET_NEXT_ID:
4482                 err = bpf_obj_get_next_id(&attr, uattr,
4483                                           &btf_idr, &btf_idr_lock);
4484                 break;
4485         case BPF_PROG_GET_FD_BY_ID:
4486                 err = bpf_prog_get_fd_by_id(&attr);
4487                 break;
4488         case BPF_MAP_GET_FD_BY_ID:
4489                 err = bpf_map_get_fd_by_id(&attr);
4490                 break;
4491         case BPF_OBJ_GET_INFO_BY_FD:
4492                 err = bpf_obj_get_info_by_fd(&attr, uattr);
4493                 break;
4494         case BPF_RAW_TRACEPOINT_OPEN:
4495                 err = bpf_raw_tracepoint_open(&attr);
4496                 break;
4497         case BPF_BTF_LOAD:
4498                 err = bpf_btf_load(&attr);
4499                 break;
4500         case BPF_BTF_GET_FD_BY_ID:
4501                 err = bpf_btf_get_fd_by_id(&attr);
4502                 break;
4503         case BPF_TASK_FD_QUERY:
4504                 err = bpf_task_fd_query(&attr, uattr);
4505                 break;
4506         case BPF_MAP_LOOKUP_AND_DELETE_ELEM:
4507                 err = map_lookup_and_delete_elem(&attr);
4508                 break;
4509         case BPF_MAP_LOOKUP_BATCH:
4510                 err = bpf_map_do_batch(&attr, uattr, BPF_MAP_LOOKUP_BATCH);
4511                 break;
4512         case BPF_MAP_LOOKUP_AND_DELETE_BATCH:
4513                 err = bpf_map_do_batch(&attr, uattr,
4514                                        BPF_MAP_LOOKUP_AND_DELETE_BATCH);
4515                 break;
4516         case BPF_MAP_UPDATE_BATCH:
4517                 err = bpf_map_do_batch(&attr, uattr, BPF_MAP_UPDATE_BATCH);
4518                 break;
4519         case BPF_MAP_DELETE_BATCH:
4520                 err = bpf_map_do_batch(&attr, uattr, BPF_MAP_DELETE_BATCH);
4521                 break;
4522         case BPF_LINK_CREATE:
4523                 err = link_create(&attr);
4524                 break;
4525         case BPF_LINK_UPDATE:
4526                 err = link_update(&attr);
4527                 break;
4528         case BPF_LINK_GET_FD_BY_ID:
4529                 err = bpf_link_get_fd_by_id(&attr);
4530                 break;
4531         case BPF_LINK_GET_NEXT_ID:
4532                 err = bpf_obj_get_next_id(&attr, uattr,
4533                                           &link_idr, &link_idr_lock);
4534                 break;
4535         case BPF_ENABLE_STATS:
4536                 err = bpf_enable_stats(&attr);
4537                 break;
4538         case BPF_ITER_CREATE:
4539                 err = bpf_iter_create(&attr);
4540                 break;
4541         case BPF_LINK_DETACH:
4542                 err = link_detach(&attr);
4543                 break;
4544         case BPF_PROG_BIND_MAP:
4545                 err = bpf_prog_bind_map(&attr);
4546                 break;
4547         default:
4548                 err = -EINVAL;
4549                 break;
4550         }
4551
4552         return err;
4553 }