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