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