xref: /linux/include/linux/bpf.h (revision 2beb1b31a12b57e19cd5c82ea6d54e56520605e8)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3  */
4 #ifndef _LINUX_BPF_H
5 #define _LINUX_BPF_H 1
6 
7 #include <uapi/linux/bpf.h>
8 #include <uapi/linux/filter.h>
9 #include <linux/bpf_defs.h>
10 
11 #include <crypto/sha2.h>
12 #include <linux/workqueue.h>
13 #include <linux/file.h>
14 #include <linux/percpu.h>
15 #include <linux/err.h>
16 #include <linux/rbtree_latch.h>
17 #include <linux/numa.h>
18 #include <linux/mm_types.h>
19 #include <linux/wait.h>
20 #include <linux/refcount.h>
21 #include <linux/mutex.h>
22 #include <linux/module.h>
23 #include <linux/kallsyms.h>
24 #include <linux/capability.h>
25 #include <linux/sched/mm.h>
26 #include <linux/slab.h>
27 #include <linux/percpu-refcount.h>
28 #include <linux/stddef.h>
29 #include <linux/bpfptr.h>
30 #include <linux/btf.h>
31 #include <linux/rcupdate_trace.h>
32 #include <linux/static_call.h>
33 #include <linux/memcontrol.h>
34 #include <linux/cfi.h>
35 #include <linux/xattr.h>
36 #include <linux/key.h>
37 #include <linux/ftrace.h>
38 #include <asm/rqspinlock.h>
39 
40 struct bpf_verifier_env;
41 struct bpf_verifier_log;
42 struct perf_event;
43 struct bpf_prog;
44 struct bpf_prog_aux;
45 struct bpf_map;
46 struct bpf_arena;
47 struct sock;
48 struct seq_file;
49 struct btf;
50 struct btf_type;
51 struct exception_table_entry;
52 struct seq_operations;
53 struct bpf_iter_aux_info;
54 struct bpf_local_storage;
55 struct bpf_local_storage_map;
56 struct kobject;
57 struct mem_cgroup;
58 struct module;
59 struct bpf_func_state;
60 struct ftrace_ops;
61 struct cgroup;
62 struct bpf_token;
63 struct user_namespace;
64 struct super_block;
65 struct inode;
66 
67 extern struct idr btf_idr;
68 extern spinlock_t btf_idr_lock;
69 extern struct kobject *btf_kobj;
70 extern struct bpf_mem_alloc bpf_global_ma, bpf_global_percpu_ma;
71 extern bool bpf_global_ma_set;
72 
73 typedef u64 (*bpf_callback_t)(u64, u64, u64, u64, u64);
74 typedef int (*bpf_iter_init_seq_priv_t)(void *private_data,
75 					struct bpf_iter_aux_info *aux);
76 typedef void (*bpf_iter_fini_seq_priv_t)(void *private_data);
77 typedef unsigned int (*bpf_func_t)(const void *,
78 				   const struct bpf_insn *);
79 struct bpf_iter_seq_info {
80 	const struct seq_operations *seq_ops;
81 	bpf_iter_init_seq_priv_t init_seq_private;
82 	bpf_iter_fini_seq_priv_t fini_seq_private;
83 	u32 seq_priv_size;
84 };
85 
86 /* map is generic key/value storage optionally accessible by eBPF programs */
87 struct bpf_map_ops {
88 	/* funcs callable from userspace (via syscall) */
89 	int (*map_alloc_check)(union bpf_attr *attr);
90 	struct bpf_map *(*map_alloc)(union bpf_attr *attr);
91 	void (*map_release)(struct bpf_map *map, struct file *map_file);
92 	void (*map_free)(struct bpf_map *map);
93 	int (*map_get_next_key)(struct bpf_map *map, void *key, void *next_key);
94 	void (*map_release_uref)(struct bpf_map *map);
95 	void *(*map_lookup_elem_sys_only)(struct bpf_map *map, void *key);
96 	int (*map_lookup_batch)(struct bpf_map *map, const union bpf_attr *attr,
97 				union bpf_attr __user *uattr);
98 	int (*map_lookup_and_delete_elem)(struct bpf_map *map, void *key,
99 					  void *value, u64 flags);
100 	int (*map_lookup_and_delete_batch)(struct bpf_map *map,
101 					   const union bpf_attr *attr,
102 					   union bpf_attr __user *uattr);
103 	int (*map_update_batch)(struct bpf_map *map, struct file *map_file,
104 				const union bpf_attr *attr,
105 				union bpf_attr __user *uattr);
106 	int (*map_delete_batch)(struct bpf_map *map, const union bpf_attr *attr,
107 				union bpf_attr __user *uattr);
108 
109 	/* funcs callable from userspace and from eBPF programs */
110 	void *(*map_lookup_elem)(struct bpf_map *map, void *key);
111 	long (*map_update_elem)(struct bpf_map *map, void *key, void *value, u64 flags);
112 	long (*map_delete_elem)(struct bpf_map *map, void *key);
113 	long (*map_push_elem)(struct bpf_map *map, void *value, u64 flags);
114 	long (*map_pop_elem)(struct bpf_map *map, void *value);
115 	long (*map_peek_elem)(struct bpf_map *map, void *value);
116 	void *(*map_lookup_percpu_elem)(struct bpf_map *map, void *key, u32 cpu);
117 	int (*map_get_hash)(struct bpf_map *map);
118 
119 	/* funcs called by prog_array and perf_event_array map */
120 	void *(*map_fd_get_ptr)(struct bpf_map *map, struct file *map_file,
121 				int fd);
122 	/* If need_defer is true, the implementation should guarantee that
123 	 * the to-be-put element is still alive before the bpf program, which
124 	 * may manipulate it, exists.
125 	 */
126 	void (*map_fd_put_ptr)(struct bpf_map *map, void *ptr, bool need_defer);
127 	int (*map_gen_lookup)(struct bpf_map *map, struct bpf_insn *insn_buf);
128 	u32 (*map_fd_sys_lookup_elem)(void *ptr);
129 	void (*map_seq_show_elem)(struct bpf_map *map, void *key,
130 				  struct seq_file *m);
131 	int (*map_check_btf)(struct bpf_map *map,
132 			     const struct btf *btf,
133 			     const struct btf_type *key_type,
134 			     const struct btf_type *value_type);
135 
136 	/* Prog poke tracking helpers. */
137 	int (*map_poke_track)(struct bpf_map *map, struct bpf_prog_aux *aux);
138 	void (*map_poke_untrack)(struct bpf_map *map, struct bpf_prog_aux *aux);
139 	void (*map_poke_run)(struct bpf_map *map, u32 key, struct bpf_prog *old,
140 			     struct bpf_prog *new);
141 
142 	/* Direct value access helpers. */
143 	int (*map_direct_value_addr)(const struct bpf_map *map,
144 				     u64 *imm, u32 off);
145 	int (*map_direct_value_meta)(const struct bpf_map *map,
146 				     u64 imm, u32 *off);
147 	int (*map_mmap)(struct bpf_map *map, struct vm_area_struct *vma);
148 	vm_fault_t (*map_mmap_fault)(struct bpf_map *map, struct vm_fault *vmf);
149 	__poll_t (*map_poll)(struct bpf_map *map, struct file *filp,
150 			     struct poll_table_struct *pts);
151 	unsigned long (*map_get_unmapped_area)(struct file *filep, unsigned long addr,
152 					       unsigned long len, unsigned long pgoff,
153 					       unsigned long flags);
154 
155 	/* Functions called by bpf_local_storage maps */
156 	int (*map_local_storage_charge)(struct bpf_local_storage_map *smap,
157 					void *owner, u32 size);
158 	void (*map_local_storage_uncharge)(struct bpf_local_storage_map *smap,
159 					   void *owner, u32 size);
160 	struct bpf_local_storage __rcu ** (*map_owner_storage_ptr)(void *owner);
161 
162 	/* Misc helpers.*/
163 	long (*map_redirect)(struct bpf_map *map, u64 key, u64 flags);
164 
165 	/* map_meta_equal must be implemented for maps that can be
166 	 * used as an inner map.  It is a runtime check to ensure
167 	 * an inner map can be inserted to an outer map.
168 	 *
169 	 * Some properties of the inner map has been used during the
170 	 * verification time.  When inserting an inner map at the runtime,
171 	 * map_meta_equal has to ensure the inserting map has the same
172 	 * properties that the verifier has used earlier.
173 	 */
174 	bool (*map_meta_equal)(const struct bpf_map *meta0,
175 			       const struct bpf_map *meta1);
176 
177 
178 	int (*map_set_for_each_callback_args)(struct bpf_verifier_env *env,
179 					      struct bpf_func_state *caller,
180 					      struct bpf_func_state *callee);
181 	long (*map_for_each_callback)(struct bpf_map *map,
182 				     bpf_callback_t callback_fn,
183 				     void *callback_ctx, u64 flags);
184 
185 	u64 (*map_mem_usage)(const struct bpf_map *map);
186 
187 	/* BTF id of struct allocated by map_alloc */
188 	int *map_btf_id;
189 
190 	/* bpf_iter info used to open a seq_file */
191 	const struct bpf_iter_seq_info *iter_seq_info;
192 };
193 
194 enum {
195 	/* Support at most 11 fields in a BTF type */
196 	BTF_FIELDS_MAX	   = 11,
197 };
198 
199 enum btf_field_type {
200 	BPF_SPIN_LOCK  = (1 << 0),
201 	BPF_TIMER      = (1 << 1),
202 	BPF_KPTR_UNREF = (1 << 2),
203 	BPF_KPTR_REF   = (1 << 3),
204 	BPF_KPTR_PERCPU = (1 << 4),
205 	BPF_KPTR       = BPF_KPTR_UNREF | BPF_KPTR_REF | BPF_KPTR_PERCPU,
206 	BPF_LIST_HEAD  = (1 << 5),
207 	BPF_LIST_NODE  = (1 << 6),
208 	BPF_RB_ROOT    = (1 << 7),
209 	BPF_RB_NODE    = (1 << 8),
210 	BPF_GRAPH_NODE = BPF_RB_NODE | BPF_LIST_NODE,
211 	BPF_GRAPH_ROOT = BPF_RB_ROOT | BPF_LIST_HEAD,
212 	BPF_REFCOUNT   = (1 << 9),
213 	BPF_WORKQUEUE  = (1 << 10),
214 	BPF_UPTR       = (1 << 11),
215 	BPF_RES_SPIN_LOCK = (1 << 12),
216 	BPF_TASK_WORK  = (1 << 13),
217 };
218 
219 enum bpf_cgroup_storage_type {
220 	BPF_CGROUP_STORAGE_SHARED,
221 	BPF_CGROUP_STORAGE_PERCPU,
222 	__BPF_CGROUP_STORAGE_MAX
223 #define MAX_BPF_CGROUP_STORAGE_TYPE __BPF_CGROUP_STORAGE_MAX
224 };
225 
226 #ifdef CONFIG_CGROUP_BPF
227 # define for_each_cgroup_storage_type(stype) \
228 	for (stype = 0; stype < MAX_BPF_CGROUP_STORAGE_TYPE; stype++)
229 #else
230 # define for_each_cgroup_storage_type(stype) for (; false; )
231 #endif /* CONFIG_CGROUP_BPF */
232 
233 typedef void (*btf_dtor_kfunc_t)(void *);
234 
235 struct btf_field_kptr {
236 	struct btf *btf;
237 	struct module *module;
238 	/* dtor used if btf_is_kernel(btf), otherwise the type is
239 	 * program-allocated, dtor is NULL,  and __bpf_obj_drop_impl is used
240 	 */
241 	btf_dtor_kfunc_t dtor;
242 	u32 btf_id;
243 };
244 
245 struct btf_field_graph_root {
246 	struct btf *btf;
247 	u32 value_btf_id;
248 	u32 node_offset;
249 	struct btf_record *value_rec;
250 };
251 
252 struct btf_field {
253 	u32 offset;
254 	u32 size;
255 	enum btf_field_type type;
256 	union {
257 		struct btf_field_kptr kptr;
258 		struct btf_field_graph_root graph_root;
259 	};
260 };
261 
262 struct btf_record {
263 	u32 cnt;
264 	u32 field_mask;
265 	int spin_lock_off;
266 	int res_spin_lock_off;
267 	int timer_off;
268 	int wq_off;
269 	int refcount_off;
270 	int task_work_off;
271 	struct btf_field fields[];
272 };
273 
274 /* Non-opaque version of bpf_rb_node in uapi/linux/bpf.h */
275 struct bpf_rb_node_kern {
276 	struct rb_node rb_node;
277 	void *owner;
278 } __attribute__((aligned(8)));
279 
280 /* Non-opaque version of bpf_list_node in uapi/linux/bpf.h */
281 struct bpf_list_node_kern {
282 	struct list_head list_head;
283 	void *owner;
284 } __attribute__((aligned(8)));
285 
286 /* 'Ownership' of program-containing map is claimed by the first program
287  * that is going to use this map or by the first program which FD is
288  * stored in the map to make sure that all callers and callees have the
289  * same prog type, JITed flag and xdp_has_frags flag.
290  */
291 struct bpf_map_owner {
292 	enum bpf_prog_type type;
293 	bool jited;
294 	bool xdp_has_frags;
295 	bool sleepable;
296 	u64 storage_cookie[MAX_BPF_CGROUP_STORAGE_TYPE];
297 	const struct btf_type *attach_func_proto;
298 	enum bpf_attach_type expected_attach_type;
299 };
300 
301 struct bpf_map {
302 	u8 sha[SHA256_DIGEST_SIZE];
303 	const struct bpf_map_ops *ops;
304 	struct bpf_map *inner_map_meta;
305 #ifdef CONFIG_SECURITY
306 	void *security;
307 #endif
308 	enum bpf_map_type map_type;
309 	u32 key_size;
310 	u32 value_size;
311 	u32 max_entries;
312 	u64 map_extra; /* any per-map-type extra fields */
313 	u32 map_flags;
314 	u32 id;
315 	struct btf_record *record;
316 	int numa_node;
317 	u32 btf_key_type_id;
318 	u32 btf_value_type_id;
319 	u32 btf_vmlinux_value_type_id;
320 	struct btf *btf;
321 #ifdef CONFIG_MEMCG
322 	struct obj_cgroup *objcg;
323 #endif
324 	char name[BPF_OBJ_NAME_LEN];
325 	struct mutex freeze_mutex;
326 	atomic64_t refcnt;
327 	atomic64_t usercnt;
328 	/* rcu is used before freeing and work is only used during freeing */
329 	union {
330 		struct work_struct work;
331 		struct rcu_head rcu;
332 	};
333 	atomic64_t writecnt;
334 	spinlock_t owner_lock;
335 	struct bpf_map_owner *owner;
336 	bool bypass_spec_v1;
337 	bool frozen; /* write-once; write-protected by freeze_mutex */
338 	bool free_after_mult_rcu_gp;
339 	bool free_after_rcu_gp;
340 	atomic64_t sleepable_refcnt;
341 	s64 __percpu *elem_count;
342 	u64 cookie; /* write-once */
343 	char *excl_prog_sha;
344 };
345 
btf_field_type_name(enum btf_field_type type)346 static inline const char *btf_field_type_name(enum btf_field_type type)
347 {
348 	switch (type) {
349 	case BPF_SPIN_LOCK:
350 		return "bpf_spin_lock";
351 	case BPF_RES_SPIN_LOCK:
352 		return "bpf_res_spin_lock";
353 	case BPF_TIMER:
354 		return "bpf_timer";
355 	case BPF_WORKQUEUE:
356 		return "bpf_wq";
357 	case BPF_KPTR_UNREF:
358 	case BPF_KPTR_REF:
359 		return "kptr";
360 	case BPF_KPTR_PERCPU:
361 		return "percpu_kptr";
362 	case BPF_UPTR:
363 		return "uptr";
364 	case BPF_LIST_HEAD:
365 		return "bpf_list_head";
366 	case BPF_LIST_NODE:
367 		return "bpf_list_node";
368 	case BPF_RB_ROOT:
369 		return "bpf_rb_root";
370 	case BPF_RB_NODE:
371 		return "bpf_rb_node";
372 	case BPF_REFCOUNT:
373 		return "bpf_refcount";
374 	case BPF_TASK_WORK:
375 		return "bpf_task_work";
376 	default:
377 		WARN_ON_ONCE(1);
378 		return "unknown";
379 	}
380 }
381 
382 #if IS_ENABLED(CONFIG_DEBUG_KERNEL)
383 #define BPF_WARN_ONCE(cond, format...) WARN_ONCE(cond, format)
384 #else
385 #define BPF_WARN_ONCE(cond, format...) BUILD_BUG_ON_INVALID(cond)
386 #endif
387 
btf_field_type_size(enum btf_field_type type)388 static inline u32 btf_field_type_size(enum btf_field_type type)
389 {
390 	switch (type) {
391 	case BPF_SPIN_LOCK:
392 		return sizeof(struct bpf_spin_lock);
393 	case BPF_RES_SPIN_LOCK:
394 		return sizeof(struct bpf_res_spin_lock);
395 	case BPF_TIMER:
396 		return sizeof(struct bpf_timer);
397 	case BPF_WORKQUEUE:
398 		return sizeof(struct bpf_wq);
399 	case BPF_KPTR_UNREF:
400 	case BPF_KPTR_REF:
401 	case BPF_KPTR_PERCPU:
402 	case BPF_UPTR:
403 		return sizeof(u64);
404 	case BPF_LIST_HEAD:
405 		return sizeof(struct bpf_list_head);
406 	case BPF_LIST_NODE:
407 		return sizeof(struct bpf_list_node);
408 	case BPF_RB_ROOT:
409 		return sizeof(struct bpf_rb_root);
410 	case BPF_RB_NODE:
411 		return sizeof(struct bpf_rb_node);
412 	case BPF_REFCOUNT:
413 		return sizeof(struct bpf_refcount);
414 	case BPF_TASK_WORK:
415 		return sizeof(struct bpf_task_work);
416 	default:
417 		WARN_ON_ONCE(1);
418 		return 0;
419 	}
420 }
421 
btf_field_type_align(enum btf_field_type type)422 static inline u32 btf_field_type_align(enum btf_field_type type)
423 {
424 	switch (type) {
425 	case BPF_SPIN_LOCK:
426 		return __alignof__(struct bpf_spin_lock);
427 	case BPF_RES_SPIN_LOCK:
428 		return __alignof__(struct bpf_res_spin_lock);
429 	case BPF_TIMER:
430 		return __alignof__(struct bpf_timer);
431 	case BPF_WORKQUEUE:
432 		return __alignof__(struct bpf_wq);
433 	case BPF_KPTR_UNREF:
434 	case BPF_KPTR_REF:
435 	case BPF_KPTR_PERCPU:
436 	case BPF_UPTR:
437 		return __alignof__(u64);
438 	case BPF_LIST_HEAD:
439 		return __alignof__(struct bpf_list_head);
440 	case BPF_LIST_NODE:
441 		return __alignof__(struct bpf_list_node);
442 	case BPF_RB_ROOT:
443 		return __alignof__(struct bpf_rb_root);
444 	case BPF_RB_NODE:
445 		return __alignof__(struct bpf_rb_node);
446 	case BPF_REFCOUNT:
447 		return __alignof__(struct bpf_refcount);
448 	case BPF_TASK_WORK:
449 		return __alignof__(struct bpf_task_work);
450 	default:
451 		WARN_ON_ONCE(1);
452 		return 0;
453 	}
454 }
455 
bpf_obj_init_field(const struct btf_field * field,void * addr)456 static inline void bpf_obj_init_field(const struct btf_field *field, void *addr)
457 {
458 	memset(addr, 0, field->size);
459 
460 	switch (field->type) {
461 	case BPF_REFCOUNT:
462 		refcount_set((refcount_t *)addr, 1);
463 		break;
464 	case BPF_RB_NODE:
465 		RB_CLEAR_NODE((struct rb_node *)addr);
466 		break;
467 	case BPF_LIST_HEAD:
468 	case BPF_LIST_NODE:
469 		INIT_LIST_HEAD((struct list_head *)addr);
470 		break;
471 	case BPF_RB_ROOT:
472 		/* RB_ROOT_CACHED 0-inits, no need to do anything after memset */
473 	case BPF_SPIN_LOCK:
474 	case BPF_RES_SPIN_LOCK:
475 	case BPF_TIMER:
476 	case BPF_WORKQUEUE:
477 	case BPF_KPTR_UNREF:
478 	case BPF_KPTR_REF:
479 	case BPF_KPTR_PERCPU:
480 	case BPF_UPTR:
481 	case BPF_TASK_WORK:
482 		break;
483 	default:
484 		WARN_ON_ONCE(1);
485 		return;
486 	}
487 }
488 
btf_record_has_field(const struct btf_record * rec,enum btf_field_type type)489 static inline bool btf_record_has_field(const struct btf_record *rec, enum btf_field_type type)
490 {
491 	if (IS_ERR_OR_NULL(rec))
492 		return false;
493 	return rec->field_mask & type;
494 }
495 
btf_field_is_nmi_safe(enum btf_field_type type)496 static inline bool btf_field_is_nmi_safe(enum btf_field_type type)
497 {
498 	switch (type) {
499 	case BPF_SPIN_LOCK:
500 	case BPF_RES_SPIN_LOCK:
501 	case BPF_TIMER:
502 	case BPF_WORKQUEUE:
503 	case BPF_TASK_WORK:
504 	case BPF_KPTR_UNREF:
505 	case BPF_REFCOUNT:
506 		return true;
507 	default:
508 		return false;
509 	}
510 }
511 
btf_record_has_nmi_unsafe_fields(const struct btf_record * rec)512 static inline bool btf_record_has_nmi_unsafe_fields(const struct btf_record *rec)
513 {
514 	int i;
515 
516 	if (IS_ERR_OR_NULL(rec))
517 		return false;
518 	for (i = 0; i < rec->cnt; i++) {
519 		if (!btf_field_is_nmi_safe(rec->fields[i].type))
520 			return true;
521 	}
522 	return false;
523 }
524 
bpf_obj_init(const struct btf_record * rec,void * obj)525 static inline void bpf_obj_init(const struct btf_record *rec, void *obj)
526 {
527 	int i;
528 
529 	if (IS_ERR_OR_NULL(rec))
530 		return;
531 	for (i = 0; i < rec->cnt; i++)
532 		bpf_obj_init_field(&rec->fields[i], obj + rec->fields[i].offset);
533 }
534 
535 /* 'dst' must be a temporary buffer and should not point to memory that is being
536  * used in parallel by a bpf program or bpf syscall, otherwise the access from
537  * the bpf program or bpf syscall may be corrupted by the reinitialization,
538  * leading to weird problems. Even 'dst' is newly-allocated from bpf memory
539  * allocator, it is still possible for 'dst' to be used in parallel by a bpf
540  * program or bpf syscall.
541  */
check_and_init_map_value(struct bpf_map * map,void * dst)542 static inline void check_and_init_map_value(struct bpf_map *map, void *dst)
543 {
544 	bpf_obj_init(map->record, dst);
545 }
546 
547 /* memcpy that is used with 8-byte aligned pointers, power-of-8 size and
548  * forced to use 'long' read/writes to try to atomically copy long counters.
549  * Best-effort only.  No barriers here, since it _will_ race with concurrent
550  * updates from BPF programs. Called from bpf syscall and mostly used with
551  * size 8 or 16 bytes, so ask compiler to inline it.
552  */
bpf_long_memcpy(void * dst,const void * src,u32 size)553 static inline void bpf_long_memcpy(void *dst, const void *src, u32 size)
554 {
555 	const long *lsrc = src;
556 	long *ldst = dst;
557 
558 	size /= sizeof(long);
559 	while (size--)
560 		data_race(*ldst++ = *lsrc++);
561 }
562 
563 /* copy everything but bpf_spin_lock, bpf_timer, and kptrs. There could be one of each. */
bpf_obj_memcpy(struct btf_record * rec,void * dst,void * src,u32 size,bool long_memcpy)564 static inline void bpf_obj_memcpy(struct btf_record *rec,
565 				  void *dst, void *src, u32 size,
566 				  bool long_memcpy)
567 {
568 	u32 curr_off = 0;
569 	int i;
570 
571 	if (IS_ERR_OR_NULL(rec)) {
572 		if (long_memcpy)
573 			bpf_long_memcpy(dst, src, size);
574 		else
575 			memcpy(dst, src, size);
576 		return;
577 	}
578 
579 	for (i = 0; i < rec->cnt; i++) {
580 		u32 next_off = rec->fields[i].offset;
581 		u32 sz = next_off - curr_off;
582 
583 		memcpy(dst + curr_off, src + curr_off, sz);
584 		curr_off += rec->fields[i].size + sz;
585 	}
586 	memcpy(dst + curr_off, src + curr_off, size - curr_off);
587 }
588 
copy_map_value(struct bpf_map * map,void * dst,void * src)589 static inline void copy_map_value(struct bpf_map *map, void *dst, void *src)
590 {
591 	bpf_obj_memcpy(map->record, dst, src, map->value_size, false);
592 }
593 
copy_map_value_long(struct bpf_map * map,void * dst,void * src)594 static inline void copy_map_value_long(struct bpf_map *map, void *dst, void *src)
595 {
596 	bpf_obj_memcpy(map->record, dst, src, round_up(map->value_size, 8), true);
597 }
598 
bpf_obj_swap_uptrs(const struct btf_record * rec,void * dst,void * src)599 static inline void bpf_obj_swap_uptrs(const struct btf_record *rec, void *dst, void *src)
600 {
601 	unsigned long *src_uptr, *dst_uptr;
602 	const struct btf_field *field;
603 	int i;
604 
605 	if (!btf_record_has_field(rec, BPF_UPTR))
606 		return;
607 
608 	for (i = 0, field = rec->fields; i < rec->cnt; i++, field++) {
609 		if (field->type != BPF_UPTR)
610 			continue;
611 
612 		src_uptr = src + field->offset;
613 		dst_uptr = dst + field->offset;
614 		swap(*src_uptr, *dst_uptr);
615 	}
616 }
617 
bpf_obj_memzero(struct btf_record * rec,void * dst,u32 size)618 static inline void bpf_obj_memzero(struct btf_record *rec, void *dst, u32 size)
619 {
620 	u32 curr_off = 0;
621 	int i;
622 
623 	if (IS_ERR_OR_NULL(rec)) {
624 		memset(dst, 0, size);
625 		return;
626 	}
627 
628 	for (i = 0; i < rec->cnt; i++) {
629 		u32 next_off = rec->fields[i].offset;
630 		u32 sz = next_off - curr_off;
631 
632 		memset(dst + curr_off, 0, sz);
633 		curr_off += rec->fields[i].size + sz;
634 	}
635 	memset(dst + curr_off, 0, size - curr_off);
636 }
637 
zero_map_value(struct bpf_map * map,void * dst)638 static inline void zero_map_value(struct bpf_map *map, void *dst)
639 {
640 	bpf_obj_memzero(map->record, dst, map->value_size);
641 }
642 
643 void copy_map_value_locked(struct bpf_map *map, void *dst, void *src,
644 			   bool lock_src);
645 void bpf_timer_cancel_and_free(void *timer);
646 void bpf_wq_cancel_and_free(void *timer);
647 void bpf_task_work_cancel_and_free(void *timer);
648 void bpf_list_head_free(const struct btf_field *field, void *list_head,
649 			struct bpf_spin_lock *spin_lock);
650 void bpf_rb_root_free(const struct btf_field *field, void *rb_root,
651 		      struct bpf_spin_lock *spin_lock);
652 u64 bpf_arena_get_kern_vm_start(struct bpf_arena *arena);
653 u64 bpf_arena_get_user_vm_start(struct bpf_arena *arena);
654 u64 bpf_arena_map_kern_vm_start(struct bpf_map *map);
655 struct bpf_map *bpf_prog_arena(struct bpf_prog *prog);
656 int bpf_obj_name_cpy(char *dst, const char *src, unsigned int size);
657 
658 struct bpf_offload_dev;
659 struct bpf_offloaded_map;
660 
661 struct bpf_map_dev_ops {
662 	int (*map_get_next_key)(struct bpf_offloaded_map *map,
663 				void *key, void *next_key);
664 	int (*map_lookup_elem)(struct bpf_offloaded_map *map,
665 			       void *key, void *value);
666 	int (*map_update_elem)(struct bpf_offloaded_map *map,
667 			       void *key, void *value, u64 flags);
668 	int (*map_delete_elem)(struct bpf_offloaded_map *map, void *key);
669 };
670 
671 struct bpf_offloaded_map {
672 	struct bpf_map map;
673 	struct net_device *netdev;
674 	const struct bpf_map_dev_ops *dev_ops;
675 	void *dev_priv;
676 	struct list_head offloads;
677 };
678 
map_to_offmap(struct bpf_map * map)679 static inline struct bpf_offloaded_map *map_to_offmap(struct bpf_map *map)
680 {
681 	return container_of(map, struct bpf_offloaded_map, map);
682 }
683 
bpf_map_offload_neutral(const struct bpf_map * map)684 static inline bool bpf_map_offload_neutral(const struct bpf_map *map)
685 {
686 	return map->map_type == BPF_MAP_TYPE_PERF_EVENT_ARRAY;
687 }
688 
bpf_map_support_seq_show(const struct bpf_map * map)689 static inline bool bpf_map_support_seq_show(const struct bpf_map *map)
690 {
691 	return (map->btf_value_type_id || map->btf_vmlinux_value_type_id) &&
692 		map->ops->map_seq_show_elem;
693 }
694 
695 int map_check_no_btf(struct bpf_map *map,
696 		     const struct btf *btf,
697 		     const struct btf_type *key_type,
698 		     const struct btf_type *value_type);
699 
700 bool bpf_map_meta_equal(const struct bpf_map *meta0,
701 			const struct bpf_map *meta1);
702 
bpf_map_has_internal_structs(struct bpf_map * map)703 static inline bool bpf_map_has_internal_structs(struct bpf_map *map)
704 {
705 	return btf_record_has_field(map->record, BPF_TIMER | BPF_WORKQUEUE | BPF_TASK_WORK);
706 }
707 
708 void bpf_map_free_internal_structs(struct bpf_map *map, void *obj);
709 
710 int bpf_dynptr_from_file_sleepable(struct file *file, u32 flags,
711 				   struct bpf_dynptr *ptr__uninit);
712 
713 #if defined(CONFIG_MMU) && defined(CONFIG_64BIT)
714 void *bpf_arena_alloc_pages_non_sleepable(void *p__map, void *addr__ign, u32 page_cnt, int node_id,
715 					  u64 flags);
716 void bpf_arena_free_pages_non_sleepable(void *p__map, void *ptr__ign, u32 page_cnt);
717 void *bpf_arena_alloc_pages_sleepable(void *p__map, void *addr__ign, u32 page_cnt, int node_id,
718 				      u64 flags);
719 #else
bpf_arena_alloc_pages_non_sleepable(void * p__map,void * addr__ign,u32 page_cnt,int node_id,u64 flags)720 static inline void *bpf_arena_alloc_pages_non_sleepable(void *p__map, void *addr__ign, u32 page_cnt,
721 							int node_id, u64 flags)
722 {
723 	return NULL;
724 }
725 
bpf_arena_free_pages_non_sleepable(void * p__map,void * ptr__ign,u32 page_cnt)726 static inline void bpf_arena_free_pages_non_sleepable(void *p__map, void *ptr__ign, u32 page_cnt)
727 {
728 }
729 
bpf_arena_alloc_pages_sleepable(void * p__map,void * addr__ign,u32 page_cnt,int node_id,u64 flags)730 static inline void *bpf_arena_alloc_pages_sleepable(void *p__map, void *addr__ign, u32 page_cnt,
731 						    int node_id, u64 flags)
732 {
733 	return NULL;
734 }
735 #endif
736 
737 extern const struct bpf_map_ops bpf_map_offload_ops;
738 
739 /* bpf_type_flag contains a set of flags that are applicable to the values of
740  * arg_type, ret_type and reg_type. For example, a pointer value may be null,
741  * or a memory is read-only. We classify types into two categories: base types
742  * and extended types. Extended types are base types combined with a type flag.
743  *
744  * Currently there are no more than 32 base types in arg_type, ret_type and
745  * reg_types.
746  */
747 #define BPF_BASE_TYPE_BITS	8
748 
749 enum bpf_type_flag {
750 	/* PTR may be NULL. */
751 	PTR_MAYBE_NULL		= BIT(0 + BPF_BASE_TYPE_BITS),
752 
753 	/* MEM is read-only. When applied on bpf_arg, it indicates the arg is
754 	 * compatible with both mutable and immutable memory.
755 	 */
756 	MEM_RDONLY		= BIT(1 + BPF_BASE_TYPE_BITS),
757 
758 	/* MEM points to BPF ring buffer reservation. */
759 	MEM_RINGBUF		= BIT(2 + BPF_BASE_TYPE_BITS),
760 
761 	/* MEM is in user address space. */
762 	MEM_USER		= BIT(3 + BPF_BASE_TYPE_BITS),
763 
764 	/* MEM is a percpu memory. MEM_PERCPU tags PTR_TO_BTF_ID. When tagged
765 	 * with MEM_PERCPU, PTR_TO_BTF_ID _cannot_ be directly accessed. In
766 	 * order to drop this tag, it must be passed into bpf_per_cpu_ptr()
767 	 * or bpf_this_cpu_ptr(), which will return the pointer corresponding
768 	 * to the specified cpu.
769 	 */
770 	MEM_PERCPU		= BIT(4 + BPF_BASE_TYPE_BITS),
771 
772 	/* Indicates that the argument will be released. */
773 	OBJ_RELEASE		= BIT(5 + BPF_BASE_TYPE_BITS),
774 
775 	/* PTR is not trusted. This is only used with PTR_TO_BTF_ID, to mark
776 	 * unreferenced and referenced kptr loaded from map value using a load
777 	 * instruction, so that they can only be dereferenced but not escape the
778 	 * BPF program into the kernel (i.e. cannot be passed as arguments to
779 	 * kfunc or bpf helpers).
780 	 */
781 	PTR_UNTRUSTED		= BIT(6 + BPF_BASE_TYPE_BITS),
782 
783 	/* MEM can be uninitialized. */
784 	MEM_UNINIT		= BIT(7 + BPF_BASE_TYPE_BITS),
785 
786 	/* DYNPTR points to memory local to the bpf program. */
787 	DYNPTR_TYPE_LOCAL	= BIT(8 + BPF_BASE_TYPE_BITS),
788 
789 	/* DYNPTR points to a kernel-produced ringbuf record. */
790 	DYNPTR_TYPE_RINGBUF	= BIT(9 + BPF_BASE_TYPE_BITS),
791 
792 	/* Size is known at compile time. */
793 	MEM_FIXED_SIZE		= BIT(10 + BPF_BASE_TYPE_BITS),
794 
795 	/* MEM is of an allocated object of type in program BTF. This is used to
796 	 * tag PTR_TO_BTF_ID allocated using bpf_obj_new.
797 	 */
798 	MEM_ALLOC		= BIT(11 + BPF_BASE_TYPE_BITS),
799 
800 	/* PTR was passed from the kernel in a trusted context, and may be
801 	 * passed to kfuncs or BPF helper functions.
802 	 * Confusingly, this is _not_ the opposite of PTR_UNTRUSTED above.
803 	 * PTR_UNTRUSTED refers to a kptr that was read directly from a map
804 	 * without invoking bpf_kptr_xchg(). What we really need to know is
805 	 * whether a pointer is safe to pass to a kfunc or BPF helper function.
806 	 * While PTR_UNTRUSTED pointers are unsafe to pass to kfuncs and BPF
807 	 * helpers, they do not cover all possible instances of unsafe
808 	 * pointers. For example, a pointer that was obtained from walking a
809 	 * struct will _not_ get the PTR_UNTRUSTED type modifier, despite the
810 	 * fact that it may be NULL, invalid, etc. This is due to backwards
811 	 * compatibility requirements, as this was the behavior that was first
812 	 * introduced when kptrs were added. The behavior is now considered
813 	 * deprecated, and PTR_UNTRUSTED will eventually be removed.
814 	 *
815 	 * PTR_TRUSTED, on the other hand, is a pointer that the kernel
816 	 * guarantees to be valid and safe to pass to kfuncs and BPF helpers.
817 	 * For example, pointers passed to tracepoint arguments are considered
818 	 * PTR_TRUSTED, as are pointers that are passed to struct_ops
819 	 * callbacks. As alluded to above, pointers that are obtained from
820 	 * walking PTR_TRUSTED pointers are _not_ trusted. For example, if a
821 	 * struct task_struct *task is PTR_TRUSTED, then accessing
822 	 * task->last_wakee will lose the PTR_TRUSTED modifier when it's stored
823 	 * in a BPF register. Similarly, pointers passed to certain programs
824 	 * types such as kretprobes are not guaranteed to be valid, as they may
825 	 * for example contain an object that was recently freed.
826 	 */
827 	PTR_TRUSTED		= BIT(12 + BPF_BASE_TYPE_BITS),
828 
829 	/* MEM is tagged with rcu and memory access needs rcu_read_lock protection. */
830 	MEM_RCU			= BIT(13 + BPF_BASE_TYPE_BITS),
831 
832 	/* Used to tag PTR_TO_BTF_ID | MEM_ALLOC references which are non-owning.
833 	 * Currently only valid for linked-list and rbtree nodes. If the nodes
834 	 * have a bpf_refcount_field, they must be tagged MEM_RCU as well.
835 	 */
836 	NON_OWN_REF		= BIT(14 + BPF_BASE_TYPE_BITS),
837 
838 	/* DYNPTR points to sk_buff */
839 	DYNPTR_TYPE_SKB		= BIT(15 + BPF_BASE_TYPE_BITS),
840 
841 	/* DYNPTR points to xdp_buff */
842 	DYNPTR_TYPE_XDP		= BIT(16 + BPF_BASE_TYPE_BITS),
843 
844 	/* Memory must be aligned on some architectures, used in combination with
845 	 * MEM_FIXED_SIZE.
846 	 */
847 	MEM_ALIGNED		= BIT(17 + BPF_BASE_TYPE_BITS),
848 
849 	/* MEM is being written to, often combined with MEM_UNINIT. Non-presence
850 	 * of MEM_WRITE means that MEM is only being read. MEM_WRITE without the
851 	 * MEM_UNINIT means that memory needs to be initialized since it is also
852 	 * read.
853 	 */
854 	MEM_WRITE		= BIT(18 + BPF_BASE_TYPE_BITS),
855 
856 	/* DYNPTR points to skb_metadata_end()-skb_metadata_len() */
857 	DYNPTR_TYPE_SKB_META	= BIT(19 + BPF_BASE_TYPE_BITS),
858 
859 	/* DYNPTR points to file */
860 	DYNPTR_TYPE_FILE	= BIT(20 + BPF_BASE_TYPE_BITS),
861 
862 	__BPF_TYPE_FLAG_MAX,
863 	__BPF_TYPE_LAST_FLAG	= __BPF_TYPE_FLAG_MAX - 1,
864 };
865 
866 #define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB \
867 				 | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META | DYNPTR_TYPE_FILE)
868 
869 /* Max number of base types. */
870 #define BPF_BASE_TYPE_LIMIT	(1UL << BPF_BASE_TYPE_BITS)
871 
872 /* Max number of all types. */
873 #define BPF_TYPE_LIMIT		(__BPF_TYPE_LAST_FLAG | (__BPF_TYPE_LAST_FLAG - 1))
874 
875 /* function argument constraints */
876 enum bpf_arg_type {
877 	ARG_DONTCARE = 0,	/* unused argument in helper function */
878 
879 	/* the following constraints used to prototype
880 	 * bpf_map_lookup/update/delete_elem() functions
881 	 */
882 	ARG_CONST_MAP_PTR,	/* const argument used as pointer to bpf_map */
883 	ARG_PTR_TO_MAP_KEY,	/* pointer to stack used as map key */
884 	ARG_PTR_TO_MAP_VALUE,	/* pointer to stack used as map value */
885 
886 	/* Used to prototype bpf_memcmp() and other functions that access data
887 	 * on eBPF program stack
888 	 */
889 	ARG_PTR_TO_MEM,		/* pointer to valid memory (stack, packet, map value) */
890 	ARG_PTR_TO_ARENA,
891 
892 	ARG_MEM_SIZE,		/* number of bytes accessed from memory */
893 	ARG_MEM_SIZE_OR_ZERO,	/* number of bytes accessed from memory or 0 */
894 
895 	ARG_PTR_TO_CTX,		/* pointer to context */
896 	ARG_ANYTHING,		/* any (initialized) argument is ok */
897 	ARG_SCALAR,		/* scalar argument */
898 	ARG_PTR_TO_SPIN_LOCK,	/* pointer to bpf_spin_lock */
899 	ARG_PTR_TO_SOCK_COMMON,	/* pointer to sock_common */
900 	ARG_PTR_TO_SOCKET,	/* pointer to bpf_sock (fullsock) */
901 	ARG_PTR_TO_BTF_ID,	/* pointer to in-kernel struct */
902 	ARG_PTR_TO_RINGBUF_MEM,	/* pointer to dynamically reserved ringbuf memory */
903 	ARG_CONST_ALLOC_SIZE_OR_ZERO,	/* number of allocated bytes requested */
904 	ARG_PTR_TO_BTF_ID_SOCK_COMMON,	/* pointer to in-kernel sock_common or bpf-mirrored bpf_sock */
905 	ARG_PTR_TO_PERCPU_BTF_ID,	/* pointer to in-kernel percpu type */
906 	ARG_PTR_TO_FUNC,	/* pointer to a bpf program function */
907 	ARG_PTR_TO_STACK,	/* pointer to stack */
908 	ARG_PTR_TO_CONST_STR,	/* pointer to a null terminated read-only string */
909 	ARG_PTR_TO_TIMER,	/* pointer to bpf_timer */
910 	ARG_KPTR_XCHG_DEST,	/* pointer to destination that kptrs are bpf_kptr_xchg'd into */
911 	ARG_PTR_TO_DYNPTR,      /* pointer to bpf_dynptr. See bpf_type_flag for dynptr type */
912 	__BPF_ARG_TYPE_MAX,
913 
914 	/* Extended arg_types. */
915 	ARG_PTR_TO_MAP_VALUE_OR_NULL	= PTR_MAYBE_NULL | ARG_PTR_TO_MAP_VALUE,
916 	ARG_PTR_TO_MEM_OR_NULL		= PTR_MAYBE_NULL | ARG_PTR_TO_MEM,
917 	ARG_PTR_TO_CTX_OR_NULL		= PTR_MAYBE_NULL | ARG_PTR_TO_CTX,
918 	ARG_PTR_TO_SOCKET_OR_NULL	= PTR_MAYBE_NULL | ARG_PTR_TO_SOCKET,
919 	ARG_PTR_TO_STACK_OR_NULL	= PTR_MAYBE_NULL | ARG_PTR_TO_STACK,
920 	ARG_PTR_TO_BTF_ID_OR_NULL	= PTR_MAYBE_NULL | ARG_PTR_TO_BTF_ID,
921 	/* Pointer to memory does not need to be initialized, since helper function
922 	 * fills all bytes or clears them in error case.
923 	 */
924 	ARG_PTR_TO_UNINIT_MEM		= MEM_UNINIT | MEM_WRITE | ARG_PTR_TO_MEM,
925 	/* Pointer to valid memory of size known at compile time. */
926 	ARG_PTR_TO_FIXED_SIZE_MEM	= MEM_FIXED_SIZE | ARG_PTR_TO_MEM,
927 
928 	/* This must be the last entry. Its purpose is to ensure the enum is
929 	 * wide enough to hold the higher bits reserved for bpf_type_flag.
930 	 */
931 	__BPF_ARG_TYPE_LIMIT	= BPF_TYPE_LIMIT,
932 };
933 static_assert(__BPF_ARG_TYPE_MAX <= BPF_BASE_TYPE_LIMIT);
934 
935 /* type of values returned from helper functions */
936 enum bpf_return_type {
937 	RET_INTEGER,			/* function returns integer */
938 	RET_VOID,			/* function doesn't return anything */
939 	RET_PTR_TO_MAP_VALUE,		/* returns a pointer to map elem value */
940 	RET_PTR_TO_SOCKET,		/* returns a pointer to a socket */
941 	RET_PTR_TO_TCP_SOCK,		/* returns a pointer to a tcp_sock */
942 	RET_PTR_TO_SOCK_COMMON,		/* returns a pointer to a sock_common */
943 	RET_PTR_TO_MEM,			/* returns a pointer to memory */
944 	RET_PTR_TO_MEM_OR_BTF_ID,	/* returns a pointer to a valid memory or a btf_id */
945 	RET_PTR_TO_BTF_ID,		/* returns a pointer to a btf_id */
946 	__BPF_RET_TYPE_MAX,
947 
948 	/* Extended ret_types. */
949 	RET_PTR_TO_MAP_VALUE_OR_NULL	= PTR_MAYBE_NULL | RET_PTR_TO_MAP_VALUE,
950 	RET_PTR_TO_SOCKET_OR_NULL	= PTR_MAYBE_NULL | RET_PTR_TO_SOCKET,
951 	RET_PTR_TO_TCP_SOCK_OR_NULL	= PTR_MAYBE_NULL | RET_PTR_TO_TCP_SOCK,
952 	RET_PTR_TO_SOCK_COMMON_OR_NULL	= PTR_MAYBE_NULL | RET_PTR_TO_SOCK_COMMON,
953 	RET_PTR_TO_RINGBUF_MEM_OR_NULL	= PTR_MAYBE_NULL | MEM_RINGBUF | RET_PTR_TO_MEM,
954 	RET_PTR_TO_DYNPTR_MEM_OR_NULL	= PTR_MAYBE_NULL | RET_PTR_TO_MEM,
955 	RET_PTR_TO_BTF_ID_OR_NULL	= PTR_MAYBE_NULL | RET_PTR_TO_BTF_ID,
956 	RET_PTR_TO_BTF_ID_TRUSTED	= PTR_TRUSTED	 | RET_PTR_TO_BTF_ID,
957 
958 	/* This must be the last entry. Its purpose is to ensure the enum is
959 	 * wide enough to hold the higher bits reserved for bpf_type_flag.
960 	 */
961 	__BPF_RET_TYPE_LIMIT	= BPF_TYPE_LIMIT,
962 };
963 static_assert(__BPF_RET_TYPE_MAX <= BPF_BASE_TYPE_LIMIT);
964 
965 /* The longest tracepoint has 12 args.
966  * See include/trace/bpf_probe.h
967  *
968  * Also reuse this macro for maximum number of arguments a BPF function
969  * or a kfunc can have. Args 1-5 are passed in registers, args 6-12 via
970  * stack arg slots. The JIT may map some stack arg slots to registers based
971  * on the native calling convention (e.g., arg 6 to R9 on x86-64).
972  */
973 #define MAX_BPF_FUNC_ARGS 12
974 
975 /* The maximum number of arguments passed through registers
976  * a single function may have.
977  */
978 #define MAX_BPF_FUNC_REG_ARGS 5
979 
980 /* eBPF function prototype used by verifier to allow BPF_CALLs from eBPF programs
981  * to in-kernel helper functions and for adjusting imm32 field in BPF_CALL
982  * instructions after verifying
983  */
984 struct bpf_func_proto {
985 	u64 (*func)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
986 	bool gpl_only;
987 	bool pkt_access;
988 	bool might_sleep;
989 	/* set to true if helper follows contract for llvm
990 	 * attribute bpf_fastcall:
991 	 * - void functions do not scratch r0
992 	 * - functions taking N arguments scratch only registers r1-rN
993 	 */
994 	bool allow_fastcall;
995 	enum bpf_return_type ret_type;
996 	union {
997 		struct {
998 			enum bpf_arg_type arg1_type;
999 			enum bpf_arg_type arg2_type;
1000 			enum bpf_arg_type arg3_type;
1001 			enum bpf_arg_type arg4_type;
1002 			enum bpf_arg_type arg5_type;
1003 		};
1004 		enum bpf_arg_type arg_type[MAX_BPF_FUNC_ARGS];
1005 	};
1006 	union {
1007 		struct {
1008 			u32 *arg1_btf_id;
1009 			u32 *arg2_btf_id;
1010 			u32 *arg3_btf_id;
1011 			u32 *arg4_btf_id;
1012 			u32 *arg5_btf_id;
1013 		};
1014 		u32 *arg_btf_id[MAX_BPF_FUNC_ARGS];
1015 		struct {
1016 			size_t arg1_size;
1017 			size_t arg2_size;
1018 			size_t arg3_size;
1019 			size_t arg4_size;
1020 			size_t arg5_size;
1021 		};
1022 		size_t arg_size[MAX_BPF_FUNC_ARGS];
1023 	};
1024 	int *ret_btf_id; /* return value btf_id */
1025 	bool (*allowed)(const struct bpf_prog *prog);
1026 };
1027 
1028 /* bpf_context is intentionally undefined structure. Pointer to bpf_context is
1029  * the first argument to eBPF programs.
1030  * For socket filters: 'struct bpf_context *' == 'struct sk_buff *'
1031  */
1032 struct bpf_context;
1033 
1034 enum bpf_access_type {
1035 	BPF_READ = 1,
1036 	BPF_WRITE = 2
1037 };
1038 
1039 /* types of values stored in eBPF registers */
1040 /* Pointer types represent:
1041  * pointer
1042  * pointer + imm
1043  * pointer + (u16) var
1044  * pointer + (u16) var + imm
1045  * if (range > 0) then [ptr, ptr + range - off) is safe to access
1046  * if (id > 0) means that some 'var' was added
1047  * if (off > 0) means that 'imm' was added
1048  */
1049 enum bpf_reg_type {
1050 	NOT_INIT = 0,		 /* nothing was written into register */
1051 	SCALAR_VALUE,		 /* reg doesn't contain a valid pointer */
1052 	PTR_TO_CTX,		 /* reg points to bpf_context */
1053 	CONST_PTR_TO_MAP,	 /* reg points to struct bpf_map */
1054 	PTR_TO_MAP_VALUE,	 /* reg points to map element value */
1055 	PTR_TO_MAP_KEY,		 /* reg points to a map element key */
1056 	PTR_TO_STACK,		 /* reg == frame_pointer + offset */
1057 	PTR_TO_PACKET_META,	 /* skb->data - meta_len */
1058 	PTR_TO_PACKET,		 /* reg points to skb->data */
1059 	PTR_TO_PACKET_END,	 /* skb->data + headlen */
1060 	PTR_TO_FLOW_KEYS,	 /* reg points to bpf_flow_keys */
1061 	PTR_TO_SOCKET,		 /* reg points to struct bpf_sock */
1062 	PTR_TO_SOCK_COMMON,	 /* reg points to sock_common */
1063 	PTR_TO_TCP_SOCK,	 /* reg points to struct tcp_sock */
1064 	PTR_TO_TP_BUFFER,	 /* reg points to a writable raw tp's buffer */
1065 	PTR_TO_XDP_SOCK,	 /* reg points to struct xdp_sock */
1066 	/* PTR_TO_BTF_ID points to a kernel struct that does not need
1067 	 * to be null checked by the BPF program. This does not imply the
1068 	 * pointer is _not_ null and in practice this can easily be a null
1069 	 * pointer when reading pointer chains. The assumption is program
1070 	 * context will handle null pointer dereference typically via fault
1071 	 * handling. The verifier must keep this in mind and can make no
1072 	 * assumptions about null or non-null when doing branch analysis.
1073 	 * Further, when passed into helpers the helpers can not, without
1074 	 * additional context, assume the value is non-null.
1075 	 */
1076 	PTR_TO_BTF_ID,
1077 	PTR_TO_MEM,		 /* reg points to valid memory region */
1078 	PTR_TO_ARENA,
1079 	PTR_TO_BUF,		 /* reg points to a read/write buffer */
1080 	PTR_TO_FUNC,		 /* reg points to a bpf program function */
1081 	PTR_TO_INSN,		 /* reg points to a bpf program instruction */
1082 	CONST_PTR_TO_DYNPTR,	 /* reg points to a const struct bpf_dynptr */
1083 	__BPF_REG_TYPE_MAX,
1084 
1085 	/* Extended reg_types. */
1086 	PTR_TO_MAP_VALUE_OR_NULL	= PTR_MAYBE_NULL | PTR_TO_MAP_VALUE,
1087 	PTR_TO_SOCKET_OR_NULL		= PTR_MAYBE_NULL | PTR_TO_SOCKET,
1088 	PTR_TO_SOCK_COMMON_OR_NULL	= PTR_MAYBE_NULL | PTR_TO_SOCK_COMMON,
1089 	PTR_TO_TCP_SOCK_OR_NULL		= PTR_MAYBE_NULL | PTR_TO_TCP_SOCK,
1090 	/* PTR_TO_BTF_ID_OR_NULL points to a kernel struct that has not
1091 	 * been checked for null. Used primarily to inform the verifier
1092 	 * an explicit null check is required for this struct.
1093 	 */
1094 	PTR_TO_BTF_ID_OR_NULL		= PTR_MAYBE_NULL | PTR_TO_BTF_ID,
1095 
1096 	/* This must be the last entry. Its purpose is to ensure the enum is
1097 	 * wide enough to hold the higher bits reserved for bpf_type_flag.
1098 	 */
1099 	__BPF_REG_TYPE_LIMIT	= BPF_TYPE_LIMIT,
1100 };
1101 static_assert(__BPF_REG_TYPE_MAX <= BPF_BASE_TYPE_LIMIT);
1102 
1103 /* The information passed from prog-specific *_is_valid_access
1104  * back to the verifier.
1105  */
1106 struct bpf_insn_access_aux {
1107 	enum bpf_reg_type reg_type;
1108 	bool is_ldsx;
1109 	union {
1110 		int ctx_field_size;
1111 		struct {
1112 			struct btf *btf;
1113 			u32 btf_id;
1114 			u32 ref_id;
1115 		};
1116 	};
1117 	struct bpf_verifier_log *log; /* for verbose logs */
1118 	bool is_retval; /* is accessing function return value ? */
1119 };
1120 
1121 static inline void
bpf_ctx_record_field_size(struct bpf_insn_access_aux * aux,u32 size)1122 bpf_ctx_record_field_size(struct bpf_insn_access_aux *aux, u32 size)
1123 {
1124 	aux->ctx_field_size = size;
1125 }
1126 
bpf_is_ldimm64(const struct bpf_insn * insn)1127 static bool bpf_is_ldimm64(const struct bpf_insn *insn)
1128 {
1129 	return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
1130 }
1131 
bpf_pseudo_func(const struct bpf_insn * insn)1132 static inline bool bpf_pseudo_func(const struct bpf_insn *insn)
1133 {
1134 	return bpf_is_ldimm64(insn) && insn->src_reg == BPF_PSEUDO_FUNC;
1135 }
1136 
1137 struct bpf_prog_ops {
1138 	int (*test_run)(struct bpf_prog *prog, const union bpf_attr *kattr,
1139 			union bpf_attr __user *uattr);
1140 };
1141 
1142 struct bpf_reg_state;
1143 struct bpf_verifier_ops {
1144 	/* return eBPF function prototype for verification */
1145 	const struct bpf_func_proto *
1146 	(*get_func_proto)(enum bpf_func_id func_id,
1147 			  const struct bpf_prog *prog);
1148 
1149 	/* return true if 'size' wide access at offset 'off' within bpf_context
1150 	 * with 'type' (read or write) is allowed
1151 	 */
1152 	bool (*is_valid_access)(int off, int size, enum bpf_access_type type,
1153 				const struct bpf_prog *prog,
1154 				struct bpf_insn_access_aux *info);
1155 	int (*gen_prologue)(struct bpf_insn *insn, bool direct_write,
1156 			    const struct bpf_prog *prog);
1157 	int (*gen_epilogue)(struct bpf_insn *insn, const struct bpf_prog *prog,
1158 			    s16 ctx_stack_off);
1159 	int (*gen_ld_abs)(const struct bpf_insn *orig,
1160 			  struct bpf_insn *insn_buf);
1161 	u32 (*convert_ctx_access)(enum bpf_access_type type,
1162 				  const struct bpf_insn *src,
1163 				  struct bpf_insn *dst,
1164 				  struct bpf_prog *prog, u32 *target_size);
1165 	int (*btf_struct_access)(struct bpf_verifier_log *log,
1166 				 const struct bpf_reg_state *reg,
1167 				 int off, int size);
1168 };
1169 
1170 struct bpf_prog_offload_ops {
1171 	/* verifier basic callbacks */
1172 	int (*insn_hook)(struct bpf_verifier_env *env,
1173 			 int insn_idx, int prev_insn_idx);
1174 	int (*finalize)(struct bpf_verifier_env *env);
1175 	/* verifier optimization callbacks (called after .finalize) */
1176 	int (*replace_insn)(struct bpf_verifier_env *env, u32 off,
1177 			    struct bpf_insn *insn);
1178 	int (*remove_insns)(struct bpf_verifier_env *env, u32 off, u32 cnt);
1179 	/* program management callbacks */
1180 	int (*prepare)(struct bpf_prog *prog);
1181 	int (*translate)(struct bpf_prog *prog);
1182 	void (*destroy)(struct bpf_prog *prog);
1183 };
1184 
1185 struct bpf_prog_offload {
1186 	struct bpf_prog		*prog;
1187 	struct net_device	*netdev;
1188 	struct bpf_offload_dev	*offdev;
1189 	void			*dev_priv;
1190 	struct list_head	offloads;
1191 	bool			dev_state;
1192 	bool			opt_failed;
1193 	void			*jited_image;
1194 	u32			jited_len;
1195 };
1196 
1197 /* The argument is signed. */
1198 #define BTF_FMODEL_SIGNED_ARG		BIT(1)
1199 
1200 /* The argument is an arena pointer. */
1201 #define BTF_FMODEL_ARENA_ARG		BIT(2)
1202 
1203 /* The argument is nullable. */
1204 #define BTF_FMODEL_NULLABLE_ARG		BIT(3)
1205 
1206 struct btf_func_model {
1207 	u8 ret_size;
1208 	u8 ret_flags;
1209 	u8 nr_args;
1210 	u8 arg_size[MAX_BPF_FUNC_ARGS];
1211 	u8 arg_flags[MAX_BPF_FUNC_ARGS];
1212 };
1213 
1214 /* Restore arguments before returning from trampoline to let original function
1215  * continue executing. This flag is used for fentry progs when there are no
1216  * fexit progs.
1217  */
1218 #define BPF_TRAMP_F_RESTORE_REGS	BIT(0)
1219 /* Call original function after fentry progs, but before fexit progs.
1220  * Makes sense for fentry/fexit, normal calls and indirect calls.
1221  */
1222 #define BPF_TRAMP_F_CALL_ORIG		BIT(1)
1223 /* Skip current frame and return to parent.  Makes sense for fentry/fexit
1224  * programs only. Should not be used with normal calls and indirect calls.
1225  */
1226 #define BPF_TRAMP_F_SKIP_FRAME		BIT(2)
1227 /* Store IP address of the caller on the trampoline stack,
1228  * so it's available for trampoline's programs.
1229  */
1230 #define BPF_TRAMP_F_IP_ARG		BIT(3)
1231 /* Return the return value of fentry prog. Only used by bpf_struct_ops. */
1232 #define BPF_TRAMP_F_RET_FENTRY_RET	BIT(4)
1233 
1234 /* Get original function from stack instead of from provided direct address.
1235  * Makes sense for trampolines with fexit or fmod_ret programs.
1236  */
1237 #define BPF_TRAMP_F_ORIG_STACK		BIT(5)
1238 
1239 /* This trampoline is on a function with another ftrace_ops with IPMODIFY,
1240  * e.g., a live patch. This flag is set and cleared by ftrace call backs,
1241  */
1242 #define BPF_TRAMP_F_SHARE_IPMODIFY	BIT(6)
1243 
1244 /* Indicate that current trampoline is in a tail call context. Then, it has to
1245  * cache and restore tail_call_cnt to avoid infinite tail call loop.
1246  */
1247 #define BPF_TRAMP_F_TAIL_CALL_CTX	BIT(7)
1248 
1249 /*
1250  * Indicate the trampoline should be suitable to receive indirect calls;
1251  * without this indirectly calling the generated code can result in #UD/#CP,
1252  * depending on the CFI options.
1253  *
1254  * Used by bpf_struct_ops.
1255  *
1256  * Incompatible with FENTRY usage, overloads @func_addr argument.
1257  */
1258 #define BPF_TRAMP_F_INDIRECT		BIT(8)
1259 
1260 /* Each call __bpf_prog_enter + call bpf_func + call __bpf_prog_exit is ~50
1261  * bytes on x86.
1262  */
1263 enum {
1264 #if defined(__s390x__)
1265 	BPF_MAX_TRAMP_LINKS = 27,
1266 #else
1267 	BPF_MAX_TRAMP_LINKS = 38,
1268 #endif
1269 };
1270 
1271 #define BPF_TRAMP_COOKIE_INDEX_SHIFT	8
1272 #define BPF_TRAMP_IS_RETURN_SHIFT	63
1273 
1274 struct bpf_tramp_nodes {
1275 	struct bpf_tramp_node *nodes[BPF_MAX_TRAMP_LINKS];
1276 	int nr_nodes;
1277 };
1278 
1279 /*
1280  * The arena base against which a struct_ops trampoline converts the
1281  * arguments marked with BTF_FMODEL_ARENA_ARG while saving them into the BPF
1282  * ctx, ctx[arg] = (u32)(kaddr - kern_vm_start). Zero when the trampoline
1283  * converts nothing.
1284  */
1285 u64 bpf_tramp_arena_base(const struct btf_func_model *m,
1286 			 struct bpf_tramp_nodes *tnodes, u32 flags);
1287 
1288 struct bpf_tramp_run_ctx;
1289 
1290 /* Different use cases for BPF trampoline:
1291  * 1. replace nop at the function entry (kprobe equivalent)
1292  *    flags = BPF_TRAMP_F_RESTORE_REGS
1293  *    fentry = a set of programs to run before returning from trampoline
1294  *
1295  * 2. replace nop at the function entry (kprobe + kretprobe equivalent)
1296  *    flags = BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_SKIP_FRAME
1297  *    orig_call = fentry_ip + MCOUNT_INSN_SIZE
1298  *    fentry = a set of program to run before calling original function
1299  *    fexit = a set of program to run after original function
1300  *
1301  * 3. replace direct call instruction anywhere in the function body
1302  *    or assign a function pointer for indirect call (like tcp_congestion_ops->cong_avoid)
1303  *    With flags = 0
1304  *      fentry = a set of programs to run before returning from trampoline
1305  *    With flags = BPF_TRAMP_F_CALL_ORIG
1306  *      orig_call = original callback addr or direct function addr
1307  *      fentry = a set of program to run before calling original function
1308  *      fexit = a set of program to run after original function
1309  */
1310 struct bpf_tramp_image;
1311 int arch_prepare_bpf_trampoline(struct bpf_tramp_image *im, void *image, void *image_end,
1312 				const struct btf_func_model *m, u32 flags,
1313 				struct bpf_tramp_nodes *tnodes,
1314 				void *func_addr);
1315 void *arch_alloc_bpf_trampoline(unsigned int size);
1316 void arch_free_bpf_trampoline(void *image, unsigned int size);
1317 int __must_check arch_protect_bpf_trampoline(void *image, unsigned int size);
1318 int arch_bpf_trampoline_size(const struct btf_func_model *m, u32 flags,
1319 			     struct bpf_tramp_nodes *tnodes, void *func_addr);
1320 
1321 u64 notrace __bpf_prog_enter_sleepable_recur(struct bpf_prog *prog,
1322 					     struct bpf_tramp_run_ctx *run_ctx);
1323 void notrace __bpf_prog_exit_sleepable_recur(struct bpf_prog *prog, u64 start,
1324 					     struct bpf_tramp_run_ctx *run_ctx);
1325 void notrace __bpf_tramp_enter(struct bpf_tramp_image *tr);
1326 void notrace __bpf_tramp_exit(struct bpf_tramp_image *tr);
1327 typedef u64 (*bpf_trampoline_enter_t)(struct bpf_prog *prog,
1328 				      struct bpf_tramp_run_ctx *run_ctx);
1329 typedef void (*bpf_trampoline_exit_t)(struct bpf_prog *prog, u64 start,
1330 				      struct bpf_tramp_run_ctx *run_ctx);
1331 bpf_trampoline_enter_t bpf_trampoline_enter(const struct bpf_prog *prog);
1332 bpf_trampoline_exit_t bpf_trampoline_exit(const struct bpf_prog *prog);
1333 
1334 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_JMP
bpf_trampoline_use_jmp(u64 flags)1335 static inline bool bpf_trampoline_use_jmp(u64 flags)
1336 {
1337 	return flags & BPF_TRAMP_F_CALL_ORIG && !(flags & BPF_TRAMP_F_SKIP_FRAME);
1338 }
1339 #else
bpf_trampoline_use_jmp(u64 flags)1340 static inline bool bpf_trampoline_use_jmp(u64 flags)
1341 {
1342 	return false;
1343 }
1344 #endif
1345 
1346 struct bpf_ksym {
1347 	unsigned long		 start;
1348 	unsigned long		 end;
1349 	char			 name[KSYM_NAME_LEN];
1350 	struct list_head	 lnode;
1351 	struct latch_tree_node	 tnode;
1352 	bool			 prog;
1353 	u32			 fp_start;
1354 	u32			 fp_end;
1355 };
1356 
1357 enum bpf_tramp_prog_type {
1358 	BPF_TRAMP_FENTRY,
1359 	BPF_TRAMP_FEXIT,
1360 	BPF_TRAMP_MODIFY_RETURN,
1361 	BPF_TRAMP_MAX,
1362 	BPF_TRAMP_REPLACE, /* more than MAX */
1363 	BPF_TRAMP_FSESSION,
1364 };
1365 
1366 struct bpf_tramp_image {
1367 	void *image;
1368 	int size;
1369 	struct bpf_ksym ksym;
1370 	struct percpu_ref pcref;
1371 	void *ip_after_call;
1372 	void *ip_epilogue;
1373 	union {
1374 		struct rcu_head rcu;
1375 		struct work_struct work;
1376 	};
1377 };
1378 
1379 struct bpf_trampoline {
1380 	/* hlist for trampoline_key_table */
1381 	struct hlist_node hlist_key;
1382 	/* hlist for trampoline_ip_table */
1383 	struct hlist_node hlist_ip;
1384 	struct ftrace_ops *fops;
1385 	refcount_t refcnt;
1386 	u32 flags;
1387 	u64 key;
1388 	unsigned long ip;
1389 	struct {
1390 		struct btf_func_model model;
1391 		void *addr;
1392 		bool ftrace_managed;
1393 	} func;
1394 	/* if !NULL this is BPF_PROG_TYPE_EXT program that extends another BPF
1395 	 * program by replacing one of its functions. func.addr is the address
1396 	 * of the function it replaced.
1397 	 */
1398 	struct bpf_prog *extension_prog;
1399 	/* list of BPF programs using this trampoline */
1400 	struct hlist_head progs_hlist[BPF_TRAMP_MAX];
1401 	/* Number of attached programs. A counter per kind. */
1402 	int progs_cnt[BPF_TRAMP_MAX];
1403 	/* Executable image of trampoline */
1404 	struct bpf_tramp_image *cur_image;
1405 	/* Used as temporary old image storage for multi_attach */
1406 	struct {
1407 		struct bpf_tramp_image *old_image;
1408 		u32 old_flags;
1409 	} multi_attach;
1410 };
1411 
1412 struct bpf_attach_target_info {
1413 	struct btf_func_model fmodel;
1414 	long tgt_addr;
1415 	struct module *tgt_mod;
1416 	const char *tgt_name;
1417 	const struct btf_type *tgt_type;
1418 };
1419 
1420 #define BPF_DISPATCHER_MAX 48 /* Fits in 2048B */
1421 
1422 struct bpf_dispatcher_prog {
1423 	struct bpf_prog *prog;
1424 	refcount_t users;
1425 };
1426 
1427 struct bpf_dispatcher {
1428 	/* dispatcher mutex */
1429 	struct mutex mutex;
1430 	void *func;
1431 	struct bpf_dispatcher_prog progs[BPF_DISPATCHER_MAX];
1432 	int num_progs;
1433 	void *image;
1434 	void *rw_image;
1435 	u32 image_off;
1436 	struct bpf_ksym ksym;
1437 #ifdef CONFIG_HAVE_STATIC_CALL
1438 	struct static_call_key *sc_key;
1439 	void *sc_tramp;
1440 #endif
1441 };
1442 
1443 #ifndef __bpfcall
1444 #define __bpfcall __nocfi
1445 #endif
1446 
bpf_dispatcher_nop_func(const void * ctx,const struct bpf_insn * insnsi,bpf_func_t bpf_func)1447 static __always_inline __bpfcall unsigned int bpf_dispatcher_nop_func(
1448 	const void *ctx,
1449 	const struct bpf_insn *insnsi,
1450 	bpf_func_t bpf_func)
1451 {
1452 	return bpf_func(ctx, insnsi);
1453 }
1454 
1455 /* the implementation of the opaque uapi struct bpf_dynptr */
1456 struct bpf_dynptr_kern {
1457 	void *data;
1458 	/* Size represents the number of usable bytes of dynptr data.
1459 	 * If for example the offset is at 4 for a local dynptr whose data is
1460 	 * of type u64, the number of usable bytes is 4.
1461 	 *
1462 	 * The upper 8 bits are reserved. It is as follows:
1463 	 * Bits 0 - 23 = size
1464 	 * Bits 24 - 30 = dynptr type
1465 	 * Bit 31 = whether dynptr is read-only
1466 	 */
1467 	u32 size;
1468 	u32 offset;
1469 } __aligned(8);
1470 
1471 enum bpf_dynptr_type {
1472 	BPF_DYNPTR_TYPE_INVALID,
1473 	/* Points to memory that is local to the bpf program */
1474 	BPF_DYNPTR_TYPE_LOCAL,
1475 	/* Underlying data is a ringbuf record */
1476 	BPF_DYNPTR_TYPE_RINGBUF,
1477 	/* Underlying data is a sk_buff */
1478 	BPF_DYNPTR_TYPE_SKB,
1479 	/* Underlying data is a xdp_buff */
1480 	BPF_DYNPTR_TYPE_XDP,
1481 	/* Points to skb_metadata_end()-skb_metadata_len() */
1482 	BPF_DYNPTR_TYPE_SKB_META,
1483 	/* Underlying data is a file */
1484 	BPF_DYNPTR_TYPE_FILE,
1485 };
1486 
1487 int bpf_dynptr_check_size(u64 size);
1488 u64 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr);
1489 const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u64 len);
1490 void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u64 len);
1491 bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr);
1492 int __bpf_dynptr_write(const struct bpf_dynptr_kern *dst, u64 offset,
1493 		       void *src, u64 len, u64 flags);
1494 void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *p, u64 offset,
1495 			    void *buffer__nullable, u64 buffer__szk);
1496 
bpf_dynptr_check_off_len(const struct bpf_dynptr_kern * ptr,u64 offset,u64 len)1497 static inline int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u64 offset, u64 len)
1498 {
1499 	u64 size = __bpf_dynptr_size(ptr);
1500 
1501 	if (len > size || offset > size - len)
1502 		return -E2BIG;
1503 
1504 	return 0;
1505 }
1506 
1507 struct bpf_tracing_multi_link;
1508 
1509 #ifdef CONFIG_BPF_JIT
1510 int bpf_trampoline_link_prog(struct bpf_tramp_node *node,
1511 			     struct bpf_trampoline *tr,
1512 			     struct bpf_prog *tgt_prog);
1513 int bpf_trampoline_unlink_prog(struct bpf_tramp_node *node,
1514 			       struct bpf_trampoline *tr,
1515 			       struct bpf_prog *tgt_prog);
1516 struct bpf_trampoline *bpf_trampoline_get(u64 key,
1517 					  struct bpf_attach_target_info *tgt_info);
1518 void bpf_trampoline_put(struct bpf_trampoline *tr);
1519 int arch_prepare_bpf_dispatcher(void *image, void *buf, s64 *funcs, int num_funcs);
1520 
1521 int bpf_trampoline_multi_attach(struct bpf_prog *prog, u32 *ids,
1522 				struct bpf_tracing_multi_link *link);
1523 void bpf_trampoline_multi_detach(struct bpf_prog *prog,
1524 				 struct bpf_tracing_multi_link *link);
1525 void bpf_trampoline_set_flags(struct bpf_trampoline *tr, u32 flags);
1526 
1527 /*
1528  * When the architecture supports STATIC_CALL replace the bpf_dispatcher_fn
1529  * indirection with a direct call to the bpf program. If the architecture does
1530  * not have STATIC_CALL, avoid a double-indirection.
1531  */
1532 #ifdef CONFIG_HAVE_STATIC_CALL
1533 
1534 #define __BPF_DISPATCHER_SC_INIT(_name)				\
1535 	.sc_key = &STATIC_CALL_KEY(_name),			\
1536 	.sc_tramp = STATIC_CALL_TRAMP_ADDR(_name),
1537 
1538 #define __BPF_DISPATCHER_SC(name)				\
1539 	DEFINE_STATIC_CALL(bpf_dispatcher_##name##_call, bpf_dispatcher_nop_func)
1540 
1541 #define __BPF_DISPATCHER_CALL(name)				\
1542 	static_call(bpf_dispatcher_##name##_call)(ctx, insnsi, bpf_func)
1543 
1544 #define __BPF_DISPATCHER_UPDATE(_d, _new)			\
1545 	__static_call_update((_d)->sc_key, (_d)->sc_tramp, (_new))
1546 
1547 #else
1548 #define __BPF_DISPATCHER_SC_INIT(name)
1549 #define __BPF_DISPATCHER_SC(name)
1550 #define __BPF_DISPATCHER_CALL(name)		bpf_func(ctx, insnsi)
1551 #define __BPF_DISPATCHER_UPDATE(_d, _new)
1552 #endif
1553 
1554 #define BPF_DISPATCHER_INIT(_name) {				\
1555 	.mutex = __MUTEX_INITIALIZER(_name.mutex),		\
1556 	.func = &_name##_func,					\
1557 	.progs = {},						\
1558 	.num_progs = 0,						\
1559 	.image = NULL,						\
1560 	.image_off = 0,						\
1561 	.ksym = {						\
1562 		.name  = #_name,				\
1563 		.lnode = LIST_HEAD_INIT(_name.ksym.lnode),	\
1564 	},							\
1565 	__BPF_DISPATCHER_SC_INIT(_name##_call)			\
1566 }
1567 
1568 #define DEFINE_BPF_DISPATCHER(name)					\
1569 	__BPF_DISPATCHER_SC(name);					\
1570 	noinline __bpfcall unsigned int bpf_dispatcher_##name##_func(	\
1571 		const void *ctx,					\
1572 		const struct bpf_insn *insnsi,				\
1573 		bpf_func_t bpf_func)					\
1574 	{								\
1575 		return __BPF_DISPATCHER_CALL(name);			\
1576 	}								\
1577 	EXPORT_SYMBOL(bpf_dispatcher_##name##_func);			\
1578 	struct bpf_dispatcher bpf_dispatcher_##name =			\
1579 		BPF_DISPATCHER_INIT(bpf_dispatcher_##name);
1580 
1581 #define DECLARE_BPF_DISPATCHER(name)					\
1582 	unsigned int bpf_dispatcher_##name##_func(			\
1583 		const void *ctx,					\
1584 		const struct bpf_insn *insnsi,				\
1585 		bpf_func_t bpf_func);					\
1586 	extern struct bpf_dispatcher bpf_dispatcher_##name;
1587 
1588 #define BPF_DISPATCHER_FUNC(name) bpf_dispatcher_##name##_func
1589 #define BPF_DISPATCHER_PTR(name) (&bpf_dispatcher_##name)
1590 void bpf_dispatcher_change_prog(struct bpf_dispatcher *d, struct bpf_prog *from,
1591 				struct bpf_prog *to);
1592 /* Called only from JIT-enabled code, so there's no need for stubs. */
1593 void bpf_image_ksym_init(void *data, unsigned int size, struct bpf_ksym *ksym);
1594 void bpf_image_ksym_add(struct bpf_ksym *ksym);
1595 void bpf_image_ksym_del(struct bpf_ksym *ksym);
1596 void bpf_ksym_add(struct bpf_ksym *ksym);
1597 void bpf_ksym_del(struct bpf_ksym *ksym);
1598 bool bpf_has_frame_pointer(unsigned long ip);
1599 int bpf_jit_charge_modmem(u32 size);
1600 void bpf_jit_uncharge_modmem(u32 size);
1601 bool bpf_prog_has_trampoline(const struct bpf_prog *prog);
1602 bool bpf_insn_is_indirect_target(const struct bpf_verifier_env *env, const struct bpf_prog *prog,
1603 				 int insn_idx);
1604 u16 bpf_out_stack_arg_cnt(const struct bpf_verifier_env *env, const struct bpf_prog *prog);
1605 #else
bpf_trampoline_link_prog(struct bpf_tramp_node * node,struct bpf_trampoline * tr,struct bpf_prog * tgt_prog)1606 static inline int bpf_trampoline_link_prog(struct bpf_tramp_node *node,
1607 					   struct bpf_trampoline *tr,
1608 					   struct bpf_prog *tgt_prog)
1609 {
1610 	return -ENOTSUPP;
1611 }
bpf_trampoline_unlink_prog(struct bpf_tramp_node * node,struct bpf_trampoline * tr,struct bpf_prog * tgt_prog)1612 static inline int bpf_trampoline_unlink_prog(struct bpf_tramp_node *node,
1613 					     struct bpf_trampoline *tr,
1614 					     struct bpf_prog *tgt_prog)
1615 {
1616 	return -ENOTSUPP;
1617 }
bpf_trampoline_get(u64 key,struct bpf_attach_target_info * tgt_info)1618 static inline struct bpf_trampoline *bpf_trampoline_get(u64 key,
1619 							struct bpf_attach_target_info *tgt_info)
1620 {
1621 	return NULL;
1622 }
bpf_trampoline_put(struct bpf_trampoline * tr)1623 static inline void bpf_trampoline_put(struct bpf_trampoline *tr) {}
1624 #define DEFINE_BPF_DISPATCHER(name)
1625 #define DECLARE_BPF_DISPATCHER(name)
1626 #define BPF_DISPATCHER_FUNC(name) bpf_dispatcher_nop_func
1627 #define BPF_DISPATCHER_PTR(name) NULL
bpf_dispatcher_change_prog(struct bpf_dispatcher * d,struct bpf_prog * from,struct bpf_prog * to)1628 static inline void bpf_dispatcher_change_prog(struct bpf_dispatcher *d,
1629 					      struct bpf_prog *from,
1630 					      struct bpf_prog *to) {}
is_bpf_image_address(unsigned long address)1631 static inline bool is_bpf_image_address(unsigned long address)
1632 {
1633 	return false;
1634 }
bpf_prog_has_trampoline(const struct bpf_prog * prog)1635 static inline bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
1636 {
1637 	return false;
1638 }
bpf_trampoline_multi_attach(struct bpf_prog * prog,u32 * ids,struct bpf_tracing_multi_link * link)1639 static inline int bpf_trampoline_multi_attach(struct bpf_prog *prog, u32 *ids,
1640 					      struct bpf_tracing_multi_link *link)
1641 {
1642 	return -ENOTSUPP;
1643 }
bpf_trampoline_multi_detach(struct bpf_prog * prog,struct bpf_tracing_multi_link * link)1644 static inline void bpf_trampoline_multi_detach(struct bpf_prog *prog,
1645 					       struct bpf_tracing_multi_link *link)
1646 {
1647 }
bpf_trampoline_set_flags(struct bpf_trampoline * tr,u32 flags)1648 static inline void bpf_trampoline_set_flags(struct bpf_trampoline *tr, u32 flags) {}
1649 #endif
1650 
1651 struct bpf_func_info_aux {
1652 	u16 linkage;
1653 	bool unreliable;
1654 	bool called : 1;
1655 	bool verified : 1;
1656 };
1657 
1658 enum bpf_jit_poke_reason {
1659 	BPF_POKE_REASON_TAIL_CALL,
1660 };
1661 
1662 /* Descriptor of pokes pointing /into/ the JITed image. */
1663 struct bpf_jit_poke_descriptor {
1664 	void *tailcall_target;
1665 	void *tailcall_bypass;
1666 	void *bypass_addr;
1667 	void *aux;
1668 	union {
1669 		struct {
1670 			struct bpf_map *map;
1671 			u32 key;
1672 		} tail_call;
1673 	};
1674 	bool tailcall_target_stable;
1675 	u8 adj_off;
1676 	u16 reason;
1677 	u32 insn_idx;
1678 };
1679 
1680 /* reg_type info for ctx arguments */
1681 struct bpf_ctx_arg_aux {
1682 	u32 offset;
1683 	enum bpf_reg_type reg_type;
1684 	struct btf *btf;
1685 	u32 btf_id;
1686 	u32 ref_id;
1687 	bool refcounted;
1688 };
1689 
1690 struct btf_mod_pair {
1691 	struct btf *btf;
1692 	struct module *module;
1693 };
1694 
1695 struct bpf_kfunc_desc_tab;
1696 
1697 enum bpf_stream_id {
1698 	BPF_STDOUT = 1,
1699 	BPF_STDERR = 2,
1700 };
1701 
1702 struct bpf_stream_elem {
1703 	struct llist_node node;
1704 	int total_len;
1705 	int consumed_len;
1706 	char str[];
1707 };
1708 
1709 enum {
1710 	/* 100k bytes */
1711 	BPF_STREAM_MAX_CAPACITY = 100000ULL,
1712 };
1713 
1714 struct bpf_stream {
1715 	atomic_t capacity;
1716 	struct llist_head log;	/* list of in-flight stream elements in LIFO order */
1717 
1718 	struct mutex lock;  /* lock protecting backlog_{head,tail} */
1719 	struct llist_node *backlog_head; /* list of in-flight stream elements in FIFO order */
1720 	struct llist_node *backlog_tail; /* tail of the list above */
1721 };
1722 
1723 struct bpf_stream_stage {
1724 	struct llist_head log;
1725 	int len;
1726 };
1727 
1728 enum bpf_sig_verdict {
1729 	BPF_SIG_UNSIGNED = 0,
1730 	BPF_SIG_VERIFIED,
1731 };
1732 
1733 enum bpf_sig_keyring {
1734 	BPF_SIG_KEYRING_NONE = 0,
1735 	BPF_SIG_KEYRING_BUILTIN,
1736 	BPF_SIG_KEYRING_SECONDARY,
1737 	BPF_SIG_KEYRING_PLATFORM,
1738 	BPF_SIG_KEYRING_USER,
1739 };
1740 
1741 struct bpf_prog_aux {
1742 	atomic64_t refcnt;
1743 	u32 used_map_cnt;
1744 	u32 used_btf_cnt;
1745 	u32 max_ctx_offset;
1746 	u32 max_pkt_offset;
1747 	u32 max_tp_access;
1748 	u32 stack_depth;
1749 	u32 id;
1750 	u32 func_cnt; /* used by non-func prog as the number of func progs */
1751 	u32 real_func_cnt; /* includes hidden progs, only used for JIT and freeing progs */
1752 	u32 func_idx; /* 0 for non-func prog, the index in func array for func prog */
1753 	u32 attach_btf_id; /* in-kernel BTF type id to attach to */
1754 	u32 attach_st_ops_member_off;
1755 	u32 ctx_arg_info_size;
1756 	u32 max_rdonly_access;
1757 	u32 max_rdwr_access;
1758 	u32 subprog_start;
1759 	struct btf *attach_btf;
1760 	struct bpf_ctx_arg_aux *ctx_arg_info;
1761 	void __percpu *priv_stack_ptr;
1762 	struct mutex dst_mutex; /* protects dst_* pointers below, *after* prog becomes visible */
1763 	struct bpf_prog *dst_prog;
1764 	struct bpf_trampoline *dst_trampoline;
1765 	enum bpf_prog_type saved_dst_prog_type;
1766 	enum bpf_attach_type saved_dst_attach_type;
1767 	bool verifier_zext; /* Zero extensions has been inserted by verifier. */
1768 	bool dev_bound; /* Program is bound to the netdev. */
1769 	bool offload_requested; /* Program is bound and offloaded to the netdev. */
1770 	bool attach_btf_trace; /* true if attaching to BTF-enabled raw tp */
1771 	bool attach_tracing_prog; /* true if tracing another tracing program */
1772 	bool func_proto_unreliable;
1773 	bool tail_call_reachable;
1774 	bool xdp_has_frags;
1775 	bool exception_cb;
1776 	bool exception_boundary;
1777 	bool is_extended; /* true if extended by freplace program */
1778 	bool jits_use_priv_stack;
1779 	bool priv_stack_requested;
1780 	bool changes_pkt_data;
1781 	bool might_sleep;
1782 	bool kprobe_write_ctx;
1783 	struct {
1784 		s32 keyring_serial;
1785 		u8 keyring_type;
1786 		u8 verdict;
1787 	} sig;
1788 	u64 prog_array_member_cnt; /* counts how many times as member of prog_array */
1789 	struct mutex ext_mutex; /* mutex for is_extended and prog_array_member_cnt */
1790 	struct bpf_arena *arena;
1791 	void (*recursion_detected)(struct bpf_prog *prog); /* callback if recursion is detected */
1792 	/* BTF_KIND_FUNC_PROTO for valid attach_btf_id */
1793 	const struct btf_type *attach_func_proto;
1794 	/* function name for valid attach_btf_id */
1795 	const char *attach_func_name;
1796 	struct bpf_prog **func;
1797 	struct bpf_prog_aux *main_prog_aux;
1798 	void *jit_data; /* JIT specific data. arch dependent */
1799 	struct bpf_jit_poke_descriptor *poke_tab;
1800 	struct bpf_kfunc_desc_tab *kfunc_tab;
1801 	struct bpf_kfunc_btf_tab *kfunc_btf_tab;
1802 	u32 size_poke_tab;
1803 #ifdef CONFIG_FINEIBT
1804 	struct bpf_ksym ksym_prefix;
1805 #endif
1806 	struct bpf_ksym ksym;
1807 	const struct bpf_prog_ops *ops;
1808 	const struct bpf_struct_ops *st_ops;
1809 	struct bpf_map **used_maps;
1810 	struct mutex used_maps_mutex; /* mutex for used_maps and used_map_cnt */
1811 	struct btf_mod_pair *used_btfs;
1812 	struct bpf_prog *prog;
1813 	struct user_struct *user;
1814 	u64 load_time; /* ns since boottime */
1815 	u32 verified_insns;
1816 	int cgroup_atype; /* enum cgroup_bpf_attach_type */
1817 	struct bpf_map *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE];
1818 	char name[BPF_OBJ_NAME_LEN];
1819 	u64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64);
1820 	u16 stack_arg_sp_adjust;
1821 #ifdef CONFIG_SECURITY
1822 	void *security;
1823 #endif
1824 	struct bpf_token *token;
1825 	struct bpf_prog_offload *offload;
1826 	struct btf *btf;
1827 	struct bpf_func_info *func_info;
1828 	struct bpf_func_info_aux *func_info_aux;
1829 	/* bpf_line_info loaded from userspace.  linfo->insn_off
1830 	 * has the xlated insn offset.
1831 	 * Both the main and sub prog share the same linfo.
1832 	 * The subprog can access its first linfo by
1833 	 * using the linfo_idx.
1834 	 */
1835 	struct bpf_line_info *linfo;
1836 	/* jited_linfo is the jited addr of the linfo.  It has a
1837 	 * one to one mapping to linfo:
1838 	 * jited_linfo[i] is the jited addr for the linfo[i]->insn_off.
1839 	 * Both the main and sub prog share the same jited_linfo.
1840 	 * The subprog can access its first jited_linfo by
1841 	 * using the linfo_idx.
1842 	 */
1843 	void **jited_linfo;
1844 	u32 func_info_cnt;
1845 	u32 nr_linfo;
1846 	/* subprog can use linfo_idx to access its first linfo and
1847 	 * jited_linfo.
1848 	 * main prog always has linfo_idx == 0
1849 	 */
1850 	u32 linfo_idx;
1851 	struct module *mod;
1852 	u32 num_exentries;
1853 	struct exception_table_entry *extable;
1854 	union {
1855 		struct work_struct work;
1856 		struct rcu_head	rcu;
1857 	};
1858 	struct bpf_stream stream[2];
1859 	struct mutex st_ops_assoc_mutex;
1860 	struct bpf_map __rcu *st_ops_assoc;
1861 };
1862 
1863 #define BPF_NR_CONTEXTS        4       /* normal, softirq, hardirq, NMI */
1864 
1865 struct bpf_prog {
1866 	u16			pages;		/* Number of allocated pages */
1867 	u32			jited:1,	/* Is our filter JIT'ed? */
1868 				jit_requested:1,/* archs need to JIT the prog */
1869 				jit_required:1,	/* program strictly requires JIT compiler */
1870 				gpl_compatible:1, /* Is filter GPL compatible? */
1871 				cb_access:1,	/* Is control block accessed? */
1872 				dst_needed:1,	/* Do we need dst entry? */
1873 				blinding_requested:1, /* needs constant blinding */
1874 				blinded:1,	/* Was blinded */
1875 				is_func:1,	/* program is a bpf function */
1876 				kprobe_override:1, /* Do we override a kprobe? */
1877 				has_callchain_buf:1, /* callchain buffer allocated? */
1878 				enforce_expected_attach_type:1, /* Enforce expected_attach_type checking at attach time */
1879 				call_get_stack:1, /* Do we call bpf_get_stack() or bpf_get_stackid() */
1880 				call_get_func_ip:1, /* Do we call get_func_ip() */
1881 				call_session_cookie:1, /* Do we call bpf_session_cookie() */
1882 				tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
1883 				sleepable:1;	/* BPF program is sleepable */
1884 	enum bpf_prog_type	type;		/* Type of BPF program */
1885 	enum bpf_attach_type	expected_attach_type; /* For some prog types */
1886 	u32			len;		/* Number of filter blocks */
1887 	u32			jited_len;	/* Size of jited insns in bytes */
1888 	union {
1889 		u8 digest[SHA256_DIGEST_SIZE];
1890 		u8 tag[BPF_TAG_SIZE];
1891 	};
1892 	struct bpf_prog_stats __percpu *stats;
1893 	u8 __percpu		*active;	/* u8[BPF_NR_CONTEXTS] for recursion protection */
1894 	unsigned int		(*bpf_func)(const void *ctx,
1895 					    const struct bpf_insn *insn);
1896 	struct bpf_prog_aux	*aux;		/* Auxiliary fields */
1897 	struct sock_fprog_kern	*orig_prog;	/* Original BPF program */
1898 	/* Instructions for interpreter */
1899 	union {
1900 		DECLARE_FLEX_ARRAY(struct sock_filter, insns);
1901 		DECLARE_FLEX_ARRAY(struct bpf_insn, insnsi);
1902 	};
1903 };
1904 
1905 struct bpf_array_aux {
1906 	/* Programs with direct jumps into programs part of this array. */
1907 	struct list_head poke_progs;
1908 	struct bpf_map *map;
1909 	struct mutex poke_mutex;
1910 	struct work_struct work;
1911 };
1912 
1913 struct bpf_link {
1914 	atomic64_t refcnt;
1915 	u32 id;
1916 	enum bpf_link_type type;
1917 	const struct bpf_link_ops *ops;
1918 	struct bpf_prog *prog;
1919 
1920 	u32 flags;
1921 	enum bpf_attach_type attach_type;
1922 
1923 	/* rcu is used before freeing, work can be used to schedule that
1924 	 * RCU-based freeing before that, so they never overlap
1925 	 */
1926 	union {
1927 		struct rcu_head rcu;
1928 		struct work_struct work;
1929 	};
1930 	/* whether BPF link itself has "sleepable" semantics, which can differ
1931 	 * from underlying BPF program having a "sleepable" semantics, as BPF
1932 	 * link's semantics is determined by target attach hook
1933 	 */
1934 	bool sleepable;
1935 };
1936 
1937 struct bpf_link_ops {
1938 	void (*release)(struct bpf_link *link);
1939 	/* deallocate link resources callback, called without RCU grace period
1940 	 * waiting
1941 	 */
1942 	void (*dealloc)(struct bpf_link *link);
1943 	/* deallocate link resources callback, called after RCU grace period;
1944 	 * if either the underlying BPF program is sleepable or BPF link's
1945 	 * target hook is sleepable, we'll go through tasks trace RCU GP and
1946 	 * then "classic" RCU GP; this need for chaining tasks trace and
1947 	 * classic RCU GPs is designated by setting bpf_link->sleepable flag
1948 	 *
1949 	 * For non-sleepable tracepoint links we go through SRCU gp instead,
1950 	 * since RCU is not used in that case. Sleepable tracepoints still
1951 	 * follow the scheme above.
1952 	 */
1953 	void (*dealloc_deferred)(struct bpf_link *link);
1954 	int (*detach)(struct bpf_link *link);
1955 	int (*update_prog)(struct bpf_link *link, struct bpf_prog *new_prog,
1956 			   struct bpf_prog *old_prog);
1957 	void (*show_fdinfo)(const struct bpf_link *link, struct seq_file *seq);
1958 	int (*fill_link_info)(const struct bpf_link *link,
1959 			      struct bpf_link_info *info);
1960 	int (*update_map)(struct bpf_link *link, struct bpf_map *new_map,
1961 			  struct bpf_map *old_map);
1962 	__poll_t (*poll)(struct file *file, struct poll_table_struct *pts);
1963 };
1964 
1965 struct bpf_tramp_node {
1966 	struct bpf_link *link;
1967 	struct hlist_node tramp_hlist;
1968 	u64 cookie;
1969 };
1970 
1971 struct bpf_tramp_link {
1972 	struct bpf_link link;
1973 	struct bpf_tramp_node node;
1974 };
1975 
1976 struct bpf_shim_tramp_link {
1977 	struct bpf_tramp_link link;
1978 	struct bpf_trampoline *trampoline;
1979 };
1980 
1981 struct bpf_tracing_link {
1982 	struct bpf_tramp_link link;
1983 	struct bpf_tramp_node fexit;
1984 	struct bpf_trampoline *trampoline;
1985 	struct bpf_prog *tgt_prog;
1986 };
1987 
1988 struct bpf_tracing_multi_node {
1989 	struct bpf_tramp_node node;
1990 	struct bpf_trampoline *trampoline;
1991 	struct ftrace_func_entry entry;
1992 };
1993 
1994 struct bpf_tracing_multi_data {
1995 	struct ftrace_hash *unreg;
1996 	struct ftrace_hash *modify;
1997 	struct ftrace_hash *reg;
1998 	struct ftrace_func_entry *entry;
1999 };
2000 
2001 struct bpf_tracing_multi_link {
2002 	struct bpf_link link;
2003 	struct bpf_tracing_multi_data data;
2004 	u64 *cookies;
2005 	struct bpf_tramp_node *fexits;
2006 	int nodes_cnt;
2007 	struct bpf_tracing_multi_node nodes[] __counted_by(nodes_cnt);
2008 };
2009 
2010 struct bpf_raw_tp_link {
2011 	struct bpf_link link;
2012 	struct bpf_raw_event_map *btp;
2013 	u64 cookie;
2014 };
2015 
2016 struct bpf_link_primer {
2017 	struct bpf_link *link;
2018 	struct file *file;
2019 	int fd;
2020 	u32 id;
2021 };
2022 
2023 struct bpf_mount_opts {
2024 	kuid_t uid;
2025 	kgid_t gid;
2026 	umode_t mode;
2027 
2028 	/* BPF token-related delegation options */
2029 	u64 delegate_cmds;
2030 	u64 delegate_maps;
2031 	u64 delegate_progs;
2032 	u64 delegate_attachs;
2033 
2034 	struct simple_xattr_cache xa_cache;
2035 };
2036 
2037 struct bpf_token {
2038 	struct work_struct work;
2039 	atomic64_t refcnt;
2040 	struct user_namespace *userns;
2041 	u64 allowed_cmds;
2042 	u64 allowed_maps;
2043 	u64 allowed_progs;
2044 	u64 allowed_attachs;
2045 #ifdef CONFIG_SECURITY
2046 	void *security;
2047 #endif
2048 };
2049 
2050 struct bpf_struct_ops_value;
2051 struct btf_member;
2052 
2053 #define BPF_STRUCT_OPS_MAX_NR_MEMBERS 64
2054 /**
2055  * struct bpf_struct_ops - A structure of callbacks allowing a subsystem to
2056  *			   define a BPF_MAP_TYPE_STRUCT_OPS map type composed
2057  *			   of BPF_PROG_TYPE_STRUCT_OPS progs.
2058  * @verifier_ops: A structure of callbacks that are invoked by the verifier
2059  *		  when determining whether the struct_ops progs in the
2060  *		  struct_ops map are valid.
2061  * @init: A callback that is invoked a single time, and before any other
2062  *	  callback, to initialize the structure. A nonzero return value means
2063  *	  the subsystem could not be initialized.
2064  * @check_member: When defined, a callback invoked by the verifier to allow
2065  *		  the subsystem to determine if an entry in the struct_ops map
2066  *		  is valid. A nonzero return value means that the map is
2067  *		  invalid and should be rejected by the verifier.
2068  * @init_member: A callback that is invoked for each member of the struct_ops
2069  *		 map to allow the subsystem to initialize the member. A nonzero
2070  *		 value means the member could not be initialized. This callback
2071  *		 is exclusive with the @type, @type_id, @value_type, and
2072  *		 @value_id fields.
2073  * @reg: A callback that is invoked when the struct_ops map has been
2074  *	 initialized and is being attached to. Zero means the struct_ops map
2075  *	 has been successfully registered and is live. A nonzero return value
2076  *	 means the struct_ops map could not be registered.
2077  * @unreg: A callback that is invoked when the struct_ops map should be
2078  *	   unregistered.
2079  * @update: A callback that is invoked when the live struct_ops map is being
2080  *	    updated to contain new values. This callback is only invoked when
2081  *	    the struct_ops map is loaded with BPF_F_LINK. If not defined, the
2082  *	    it is assumed that the struct_ops map cannot be updated.
2083  * @validate: A callback that is invoked after all of the members have been
2084  *	      initialized. This callback should perform static checks on the
2085  *	      map, meaning that it should either fail or succeed
2086  *	      deterministically. A struct_ops map that has been validated may
2087  *	      not necessarily succeed in being registered if the call to @reg
2088  *	      fails. For example, a valid struct_ops map may be loaded, but
2089  *	      then fail to be registered due to there being another active
2090  *	      struct_ops map on the system in the subsystem already. For this
2091  *	      reason, if this callback is not defined, the check is skipped as
2092  *	      the struct_ops map will have final verification performed in
2093  *	      @reg.
2094  * @cfi_stubs: Pointer to a structure of stub functions for CFI. These stubs
2095  *	       provide the correct Control Flow Integrity hashes for the
2096  *	       trampolines generated by BPF struct_ops.
2097  * @owner: The module that owns this struct_ops. Used for module reference
2098  *	   counting to ensure the module providing the struct_ops cannot be
2099  *	   unloaded while in use.
2100  * @name: The name of the struct bpf_struct_ops object.
2101  * @func_models: Func models
2102  */
2103 struct bpf_struct_ops {
2104 	const struct bpf_verifier_ops *verifier_ops;
2105 	int (*init)(struct btf *btf);
2106 	int (*check_member)(const struct btf_type *t,
2107 			    const struct btf_member *member,
2108 			    const struct bpf_prog *prog);
2109 	int (*init_member)(const struct btf_type *t,
2110 			   const struct btf_member *member,
2111 			   void *kdata, const void *udata);
2112 	int (*reg)(void *kdata, struct bpf_link *link);
2113 	void (*unreg)(void *kdata, struct bpf_link *link);
2114 	int (*update)(void *kdata, void *old_kdata, struct bpf_link *link);
2115 	int (*validate)(void *kdata);
2116 	void *cfi_stubs;
2117 	struct module *owner;
2118 	const char *name;
2119 	struct btf_func_model func_models[BPF_STRUCT_OPS_MAX_NR_MEMBERS];
2120 };
2121 
2122 /* Every member of a struct_ops type has an instance even a member is not
2123  * an operator (function pointer). The "info" field will be assigned to
2124  * prog->aux->ctx_arg_info of BPF struct_ops programs to provide the
2125  * argument information required by the verifier to verify the program.
2126  *
2127  * btf_ctx_access() will lookup prog->aux->ctx_arg_info to find the
2128  * corresponding entry for an given argument.
2129  */
2130 struct bpf_struct_ops_arg_info {
2131 	struct bpf_ctx_arg_aux *info;
2132 	u32 cnt;
2133 };
2134 
2135 struct bpf_struct_ops_desc {
2136 	struct bpf_struct_ops *st_ops;
2137 
2138 	const struct btf_type *type;
2139 	const struct btf_type *value_type;
2140 	u32 type_id;
2141 	u32 value_id;
2142 
2143 	/* Collection of argument information for each member */
2144 	struct bpf_struct_ops_arg_info *arg_info;
2145 };
2146 
2147 enum bpf_struct_ops_state {
2148 	BPF_STRUCT_OPS_STATE_INIT,
2149 	BPF_STRUCT_OPS_STATE_INUSE,
2150 	BPF_STRUCT_OPS_STATE_TOBEFREE,
2151 	BPF_STRUCT_OPS_STATE_READY,
2152 };
2153 
2154 struct bpf_struct_ops_common_value {
2155 	refcount_t refcnt;
2156 	enum bpf_struct_ops_state state;
2157 };
2158 
bpf_prog_get_recursion_context(struct bpf_prog * prog)2159 static inline bool bpf_prog_get_recursion_context(struct bpf_prog *prog)
2160 {
2161 #ifdef CONFIG_ARM64
2162 	u8 rctx = interrupt_context_level();
2163 	u8 *active = this_cpu_ptr(prog->active);
2164 	u32 val;
2165 
2166 	preempt_disable();
2167 	active[rctx]++;
2168 	val = le32_to_cpu(*(__le32 *)active);
2169 	preempt_enable();
2170 	if (val != BIT(rctx * 8))
2171 		return false;
2172 
2173 	return true;
2174 #else
2175 	return this_cpu_inc_return(*(int __percpu *)(prog->active)) == 1;
2176 #endif
2177 }
2178 
bpf_prog_put_recursion_context(struct bpf_prog * prog)2179 static inline void bpf_prog_put_recursion_context(struct bpf_prog *prog)
2180 {
2181 #ifdef CONFIG_ARM64
2182 	u8 rctx = interrupt_context_level();
2183 	u8 *active = this_cpu_ptr(prog->active);
2184 
2185 	preempt_disable();
2186 	active[rctx]--;
2187 	preempt_enable();
2188 #else
2189 	this_cpu_dec(*(int __percpu *)(prog->active));
2190 #endif
2191 }
2192 
is_tracing_multi(enum bpf_attach_type type)2193 static inline bool is_tracing_multi(enum bpf_attach_type type)
2194 {
2195 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
2196 	       type == BPF_TRACE_FSESSION_MULTI;
2197 }
2198 
is_struct_ops_tramp(const struct bpf_tramp_nodes * fentry_nodes)2199 static inline bool is_struct_ops_tramp(const struct bpf_tramp_nodes *fentry_nodes)
2200 {
2201 	return fentry_nodes->nr_nodes == 1 &&
2202 	       fentry_nodes->nodes[0]->link->type == BPF_LINK_TYPE_STRUCT_OPS;
2203 }
2204 
2205 #if defined(CONFIG_BPF_JIT) && defined(CONFIG_BPF_SYSCALL)
2206 /* This macro helps developer to register a struct_ops type and generate
2207  * type information correctly. Developers should use this macro to register
2208  * a struct_ops type instead of calling __register_bpf_struct_ops() directly.
2209  */
2210 #define register_bpf_struct_ops(st_ops, type)				\
2211 	({								\
2212 		struct bpf_struct_ops_##type {				\
2213 			struct bpf_struct_ops_common_value common;	\
2214 			struct type data ____cacheline_aligned_in_smp;	\
2215 		};							\
2216 		BTF_TYPE_EMIT(struct bpf_struct_ops_##type);		\
2217 		__register_bpf_struct_ops(st_ops);			\
2218 	})
2219 #define BPF_MODULE_OWNER ((void *)((0xeB9FUL << 2) + POISON_POINTER_DELTA))
2220 bool bpf_struct_ops_get(const void *kdata);
2221 void bpf_struct_ops_put(const void *kdata);
2222 int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff);
2223 int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,
2224 				       void *value);
2225 int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes,
2226 				      struct bpf_tramp_node *node,
2227 				      const struct btf_func_model *model,
2228 				      void *stub_func,
2229 				      void **image, u32 *image_off,
2230 				      bool allow_alloc);
2231 void bpf_struct_ops_image_free(void *image);
bpf_try_module_get(const void * data,struct module * owner)2232 static inline bool bpf_try_module_get(const void *data, struct module *owner)
2233 {
2234 	if (owner == BPF_MODULE_OWNER)
2235 		return bpf_struct_ops_get(data);
2236 	else
2237 		return try_module_get(owner);
2238 }
bpf_module_put(const void * data,struct module * owner)2239 static inline void bpf_module_put(const void *data, struct module *owner)
2240 {
2241 	if (owner == BPF_MODULE_OWNER)
2242 		bpf_struct_ops_put(data);
2243 	else
2244 		module_put(owner);
2245 }
2246 int bpf_struct_ops_link_create(union bpf_attr *attr);
2247 int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map);
2248 void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog);
2249 void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux);
2250 u32 bpf_struct_ops_id(const void *kdata);
2251 int bpf_struct_ops_for_each_prog(const void *kdata,
2252 				 int (*cb)(struct bpf_prog *prog, void *data),
2253 				 void *data);
2254 
2255 #ifdef CONFIG_NET
2256 /* Define it here to avoid the use of forward declaration */
2257 struct bpf_dummy_ops_state {
2258 	int val;
2259 };
2260 
2261 struct bpf_dummy_ops {
2262 	int (*test_1)(struct bpf_dummy_ops_state *cb);
2263 	int (*test_2)(struct bpf_dummy_ops_state *cb, int a1, unsigned short a2,
2264 		      char a3, unsigned long a4);
2265 	int (*test_sleepable)(struct bpf_dummy_ops_state *cb);
2266 };
2267 
2268 int bpf_struct_ops_test_run(struct bpf_prog *prog, const union bpf_attr *kattr,
2269 			    union bpf_attr __user *uattr);
2270 #endif
2271 int bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc,
2272 			     struct btf *btf,
2273 			     struct bpf_verifier_log *log);
2274 void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map);
2275 void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc);
2276 #else
2277 #define register_bpf_struct_ops(st_ops, type) ({ (void *)(st_ops); 0; })
bpf_try_module_get(const void * data,struct module * owner)2278 static inline bool bpf_try_module_get(const void *data, struct module *owner)
2279 {
2280 	return try_module_get(owner);
2281 }
bpf_module_put(const void * data,struct module * owner)2282 static inline void bpf_module_put(const void *data, struct module *owner)
2283 {
2284 	module_put(owner);
2285 }
bpf_struct_ops_supported(const struct bpf_struct_ops * st_ops,u32 moff)2286 static inline int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff)
2287 {
2288 	return -ENOTSUPP;
2289 }
bpf_struct_ops_map_sys_lookup_elem(struct bpf_map * map,void * key,void * value)2290 static inline int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map,
2291 						     void *key,
2292 						     void *value)
2293 {
2294 	return -EINVAL;
2295 }
bpf_struct_ops_link_create(union bpf_attr * attr)2296 static inline int bpf_struct_ops_link_create(union bpf_attr *attr)
2297 {
2298 	return -EOPNOTSUPP;
2299 }
bpf_prog_assoc_struct_ops(struct bpf_prog * prog,struct bpf_map * map)2300 static inline int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map)
2301 {
2302 	return -EOPNOTSUPP;
2303 }
bpf_prog_disassoc_struct_ops(struct bpf_prog * prog)2304 static inline void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog)
2305 {
2306 }
bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux * aux)2307 static inline void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux)
2308 {
2309 	return NULL;
2310 }
bpf_map_struct_ops_info_fill(struct bpf_map_info * info,struct bpf_map * map)2311 static inline void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map)
2312 {
2313 }
2314 
bpf_struct_ops_desc_release(struct bpf_struct_ops_desc * st_ops_desc)2315 static inline void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc)
2316 {
2317 }
2318 
2319 #endif
2320 
bpf_fsession_cnt(struct bpf_tramp_nodes * nodes)2321 static inline int bpf_fsession_cnt(struct bpf_tramp_nodes *nodes)
2322 {
2323 	struct bpf_tramp_nodes fentries = nodes[BPF_TRAMP_FENTRY];
2324 	int cnt = 0;
2325 
2326 	for (int i = 0; i < nodes[BPF_TRAMP_FENTRY].nr_nodes; i++) {
2327 		if (fentries.nodes[i]->link->prog->expected_attach_type == BPF_TRACE_FSESSION)
2328 			cnt++;
2329 		if (fentries.nodes[i]->link->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)
2330 			cnt++;
2331 	}
2332 
2333 	return cnt;
2334 }
2335 
bpf_prog_calls_session_cookie(struct bpf_tramp_node * node)2336 static inline bool bpf_prog_calls_session_cookie(struct bpf_tramp_node *node)
2337 {
2338 	return node->link->prog->call_session_cookie;
2339 }
2340 
bpf_fsession_cookie_cnt(struct bpf_tramp_nodes * nodes)2341 static inline int bpf_fsession_cookie_cnt(struct bpf_tramp_nodes *nodes)
2342 {
2343 	struct bpf_tramp_nodes fentries = nodes[BPF_TRAMP_FENTRY];
2344 	int cnt = 0;
2345 
2346 	for (int i = 0; i < nodes[BPF_TRAMP_FENTRY].nr_nodes; i++) {
2347 		if (bpf_prog_calls_session_cookie(fentries.nodes[i]))
2348 			cnt++;
2349 	}
2350 
2351 	return cnt;
2352 }
2353 
2354 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
2355 			       const struct bpf_ctx_arg_aux *info, u32 cnt);
2356 
2357 #if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_BPF_LSM)
2358 int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
2359 				    int cgroup_atype,
2360 				    enum bpf_attach_type attach_type);
2361 void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog);
2362 #else
bpf_trampoline_link_cgroup_shim(struct bpf_prog * prog,int cgroup_atype,enum bpf_attach_type attach_type)2363 static inline int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
2364 						  int cgroup_atype,
2365 						  enum bpf_attach_type attach_type)
2366 {
2367 	return -EOPNOTSUPP;
2368 }
bpf_trampoline_unlink_cgroup_shim(struct bpf_prog * prog)2369 static inline void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog)
2370 {
2371 }
2372 #endif
2373 
2374 struct bpf_array {
2375 	struct bpf_map map;
2376 	u32 elem_size;
2377 	u32 index_mask;
2378 	struct bpf_array_aux *aux;
2379 	union {
2380 		DECLARE_FLEX_ARRAY(char, value) __aligned(8);
2381 		DECLARE_FLEX_ARRAY(void *, ptrs) __aligned(8);
2382 		DECLARE_FLEX_ARRAY(void __percpu *, pptrs) __aligned(8);
2383 	};
2384 };
2385 
2386 /*
2387  * The bpf_array_get_next_key() function may be used for all array-like
2388  * maps, i.e., maps with u32 keys with range [0 ,..., max_entries)
2389  */
2390 int bpf_array_get_next_key(struct bpf_map *map, void *key, void *next_key);
2391 
2392 #define BPF_COMPLEXITY_LIMIT_INSNS      1000000 /* yes. 1M insns */
2393 #define MAX_TAIL_CALL_CNT 33
2394 
2395 /* Maximum number of loops for bpf_loop and bpf_iter_num.
2396  * It's enum to expose it (and thus make it discoverable) through BTF.
2397  */
2398 enum {
2399 	BPF_MAX_LOOPS = 8 * 1024 * 1024,
2400 	BPF_MAX_TIMED_LOOPS = 0xffff,
2401 };
2402 
2403 #define BPF_F_ACCESS_MASK	(BPF_F_RDONLY |		\
2404 				 BPF_F_RDONLY_PROG |	\
2405 				 BPF_F_WRONLY |		\
2406 				 BPF_F_WRONLY_PROG)
2407 
2408 #define BPF_MAP_CAN_READ	BIT(0)
2409 #define BPF_MAP_CAN_WRITE	BIT(1)
2410 
2411 /* Maximum number of user-producer ring buffer samples that can be drained in
2412  * a call to bpf_user_ringbuf_drain().
2413  */
2414 #define BPF_MAX_USER_RINGBUF_SAMPLES (128 * 1024)
2415 
bpf_map_flags_to_cap(struct bpf_map * map)2416 static inline u32 bpf_map_flags_to_cap(struct bpf_map *map)
2417 {
2418 	u32 access_flags = map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG);
2419 
2420 	/* Combination of BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG is
2421 	 * not possible.
2422 	 */
2423 	if (access_flags & BPF_F_RDONLY_PROG)
2424 		return BPF_MAP_CAN_READ;
2425 	else if (access_flags & BPF_F_WRONLY_PROG)
2426 		return BPF_MAP_CAN_WRITE;
2427 	else
2428 		return BPF_MAP_CAN_READ | BPF_MAP_CAN_WRITE;
2429 }
2430 
bpf_map_flags_access_ok(u32 access_flags)2431 static inline bool bpf_map_flags_access_ok(u32 access_flags)
2432 {
2433 	return (access_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) !=
2434 	       (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG);
2435 }
2436 
bpf_map_owner_alloc(struct bpf_map * map)2437 static inline struct bpf_map_owner *bpf_map_owner_alloc(struct bpf_map *map)
2438 {
2439 	return kzalloc_obj(*map->owner, GFP_ATOMIC);
2440 }
2441 
bpf_map_owner_free(struct bpf_map * map)2442 static inline void bpf_map_owner_free(struct bpf_map *map)
2443 {
2444 	kfree(map->owner);
2445 }
2446 
2447 struct bpf_event_entry {
2448 	struct perf_event *event;
2449 	struct file *perf_file;
2450 	struct file *map_file;
2451 	struct rcu_head rcu;
2452 };
2453 
map_type_contains_progs(struct bpf_map * map)2454 static inline bool map_type_contains_progs(struct bpf_map *map)
2455 {
2456 	return map->map_type == BPF_MAP_TYPE_PROG_ARRAY ||
2457 	       map->map_type == BPF_MAP_TYPE_DEVMAP ||
2458 	       map->map_type == BPF_MAP_TYPE_CPUMAP;
2459 }
2460 
2461 bool bpf_prog_map_compatible(struct bpf_map *map, const struct bpf_prog *fp);
2462 int bpf_prog_calc_tag(struct bpf_prog *fp);
2463 
2464 const struct bpf_func_proto *bpf_get_trace_printk_proto(void);
2465 const struct bpf_func_proto *bpf_get_trace_vprintk_proto(void);
2466 
2467 const struct bpf_func_proto *bpf_get_perf_event_read_value_proto(void);
2468 
2469 typedef unsigned long (*bpf_ctx_copy_t)(void *dst, const void *src,
2470 					unsigned long off, unsigned long len);
2471 typedef u32 (*bpf_convert_ctx_access_t)(enum bpf_access_type type,
2472 					const struct bpf_insn *src,
2473 					struct bpf_insn *dst,
2474 					struct bpf_prog *prog,
2475 					u32 *target_size);
2476 
2477 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
2478 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy);
2479 
2480 /* an array of programs to be executed under rcu_lock.
2481  *
2482  * Typical usage:
2483  * ret = bpf_prog_run_array(rcu_dereference(&bpf_prog_array), ctx, bpf_prog_run);
2484  *
2485  * the structure returned by bpf_prog_array_alloc() should be populated
2486  * with program pointers and the last pointer must be NULL.
2487  * The user has to keep refcnt on the program and make sure the program
2488  * is removed from the array before bpf_prog_put().
2489  * The 'struct bpf_prog_array *' should only be replaced with xchg()
2490  * since other cpus are walking the array of pointers in parallel.
2491  */
2492 struct bpf_prog_array_item {
2493 	struct bpf_prog *prog;
2494 	union {
2495 		struct bpf_cgroup_storage *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE];
2496 		u64 bpf_cookie;
2497 	};
2498 };
2499 
2500 struct bpf_prog_array {
2501 	struct rcu_head rcu;
2502 	struct bpf_prog_array_item items[];
2503 };
2504 
2505 /* to avoid allocating empty bpf_prog_array for cgroups that
2506  * don't have bpf program attached use one global 'bpf_empty_prog_array'
2507  * It will not be modified the caller of bpf_prog_array_alloc()
2508  * (since caller requested prog_cnt == 0)
2509  * that pointer should be 'freed' by bpf_prog_array_free()
2510  */
2511 extern struct bpf_prog_array bpf_empty_prog_array;
2512 
2513 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags);
2514 void bpf_prog_array_free(struct bpf_prog_array *progs);
2515 /* Use when traversal over the bpf_prog_array uses tasks_trace rcu */
2516 void bpf_prog_array_free_sleepable(struct bpf_prog_array *progs);
2517 int bpf_prog_array_length(struct bpf_prog_array *progs);
2518 bool bpf_prog_array_is_empty(struct bpf_prog_array *array);
2519 int bpf_prog_array_copy_to_user(struct bpf_prog_array *progs,
2520 				__u32 __user *prog_ids, u32 cnt);
2521 
2522 void bpf_prog_array_delete_safe(struct bpf_prog_array *progs,
2523 				struct bpf_prog *old_prog);
2524 int bpf_prog_array_delete_safe_at(struct bpf_prog_array *array, int index);
2525 int bpf_prog_array_update_at(struct bpf_prog_array *array, int index,
2526 			     struct bpf_prog *prog);
2527 int bpf_prog_array_copy_info(struct bpf_prog_array *array,
2528 			     u32 *prog_ids, u32 request_cnt,
2529 			     u32 *prog_cnt);
2530 int bpf_prog_array_copy(struct bpf_prog_array *old_array,
2531 			struct bpf_prog *exclude_prog,
2532 			struct bpf_prog *include_prog,
2533 			u64 bpf_cookie,
2534 			struct bpf_prog_array **new_array);
2535 
2536 struct bpf_run_ctx {};
2537 
2538 struct bpf_cg_run_ctx {
2539 	struct bpf_run_ctx run_ctx;
2540 	const struct bpf_prog_array_item *prog_item;
2541 	int retval;
2542 };
2543 
2544 struct bpf_trace_run_ctx {
2545 	struct bpf_run_ctx run_ctx;
2546 	u64 bpf_cookie;
2547 	bool is_uprobe;
2548 };
2549 
2550 struct bpf_tramp_run_ctx {
2551 	struct bpf_run_ctx run_ctx;
2552 	u64 bpf_cookie;
2553 	struct bpf_run_ctx *saved_run_ctx;
2554 };
2555 
bpf_set_run_ctx(struct bpf_run_ctx * new_ctx)2556 static inline struct bpf_run_ctx *bpf_set_run_ctx(struct bpf_run_ctx *new_ctx)
2557 {
2558 	struct bpf_run_ctx *old_ctx = NULL;
2559 
2560 #ifdef CONFIG_BPF_SYSCALL
2561 	old_ctx = current->bpf_ctx;
2562 	current->bpf_ctx = new_ctx;
2563 #endif
2564 	return old_ctx;
2565 }
2566 
bpf_reset_run_ctx(struct bpf_run_ctx * old_ctx)2567 static inline void bpf_reset_run_ctx(struct bpf_run_ctx *old_ctx)
2568 {
2569 #ifdef CONFIG_BPF_SYSCALL
2570 	current->bpf_ctx = old_ctx;
2571 #endif
2572 }
2573 
2574 /* BPF program asks to bypass CAP_NET_BIND_SERVICE in bind. */
2575 #define BPF_RET_BIND_NO_CAP_NET_BIND_SERVICE			(1 << 0)
2576 /* BPF program asks to set CN on the packet. */
2577 #define BPF_RET_SET_CN						(1 << 0)
2578 
2579 typedef u32 (*bpf_prog_run_fn)(const struct bpf_prog *prog, const void *ctx);
2580 
2581 static __always_inline u32
bpf_prog_run_array(const struct bpf_prog_array * array,const void * ctx,bpf_prog_run_fn run_prog)2582 bpf_prog_run_array(const struct bpf_prog_array *array,
2583 		   const void *ctx, bpf_prog_run_fn run_prog)
2584 {
2585 	const struct bpf_prog_array_item *item;
2586 	const struct bpf_prog *prog;
2587 	struct bpf_run_ctx *old_run_ctx;
2588 	struct bpf_trace_run_ctx run_ctx;
2589 	u32 ret = 1;
2590 
2591 	RCU_LOCKDEP_WARN(!rcu_read_lock_held(), "no rcu lock held");
2592 
2593 	if (unlikely(!array))
2594 		return ret;
2595 
2596 	run_ctx.is_uprobe = false;
2597 
2598 	migrate_disable();
2599 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2600 	item = &array->items[0];
2601 	while ((prog = READ_ONCE(item->prog))) {
2602 		run_ctx.bpf_cookie = item->bpf_cookie;
2603 		ret &= run_prog(prog, ctx);
2604 		item++;
2605 	}
2606 	bpf_reset_run_ctx(old_run_ctx);
2607 	migrate_enable();
2608 	return ret;
2609 }
2610 
2611 /* Notes on RCU design for bpf_prog_arrays containing sleepable programs:
2612  *
2613  * We use the tasks_trace rcu flavor read section to protect the bpf_prog_array
2614  * overall. As a result, we must use the bpf_prog_array_free_sleepable
2615  * in order to use the tasks_trace rcu grace period.
2616  *
2617  * When a non-sleepable program is inside the array, we take the rcu read
2618  * section and disable preemption for that program alone, so it can access
2619  * rcu-protected dynamically sized maps.
2620  */
2621 static __always_inline u32
bpf_prog_run_array_uprobe(const struct bpf_prog_array * array,const void * ctx,bpf_prog_run_fn run_prog)2622 bpf_prog_run_array_uprobe(const struct bpf_prog_array *array,
2623 			  const void *ctx, bpf_prog_run_fn run_prog)
2624 {
2625 	const struct bpf_prog_array_item *item;
2626 	const struct bpf_prog *prog;
2627 	struct bpf_run_ctx *old_run_ctx;
2628 	struct bpf_trace_run_ctx run_ctx;
2629 	u32 ret = 1;
2630 
2631 	might_fault();
2632 	RCU_LOCKDEP_WARN(!rcu_read_lock_trace_held(), "no rcu lock held");
2633 
2634 	if (unlikely(!array))
2635 		return ret;
2636 
2637 	migrate_disable();
2638 
2639 	run_ctx.is_uprobe = true;
2640 
2641 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2642 	item = &array->items[0];
2643 	while ((prog = READ_ONCE(item->prog))) {
2644 		if (!prog->sleepable)
2645 			rcu_read_lock();
2646 
2647 		run_ctx.bpf_cookie = item->bpf_cookie;
2648 		ret &= run_prog(prog, ctx);
2649 		item++;
2650 
2651 		if (!prog->sleepable)
2652 			rcu_read_unlock();
2653 	}
2654 	bpf_reset_run_ctx(old_run_ctx);
2655 	migrate_enable();
2656 	return ret;
2657 }
2658 
2659 bool bpf_jit_bypass_spec_v1(void);
2660 bool bpf_jit_bypass_spec_v4(void);
2661 
2662 #define bpf_rcu_lock_held() \
2663 	(rcu_read_lock_held() || rcu_read_lock_trace_held() || rcu_read_lock_bh_held())
2664 
2665 #ifdef CONFIG_BPF_SYSCALL
2666 DECLARE_PER_CPU(int, bpf_prog_active);
2667 extern struct mutex bpf_stats_enabled_mutex;
2668 
2669 /*
2670  * Block execution of BPF programs attached to instrumentation (perf,
2671  * kprobes, tracepoints) to prevent deadlocks on map operations as any of
2672  * these events can happen inside a region which holds a map bucket lock
2673  * and can deadlock on it.
2674  */
bpf_disable_instrumentation(void)2675 static inline void bpf_disable_instrumentation(void)
2676 {
2677 	migrate_disable();
2678 	this_cpu_inc(bpf_prog_active);
2679 }
2680 
bpf_enable_instrumentation(void)2681 static inline void bpf_enable_instrumentation(void)
2682 {
2683 	this_cpu_dec(bpf_prog_active);
2684 	migrate_enable();
2685 }
2686 
2687 extern const struct super_operations bpf_super_ops;
2688 extern const struct file_operations bpf_map_fops;
2689 extern const struct file_operations bpf_prog_fops;
2690 extern const struct file_operations bpf_iter_fops;
2691 extern const struct file_operations bpf_token_fops;
2692 
2693 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2694 	extern const struct bpf_prog_ops _name ## _prog_ops; \
2695 	extern const struct bpf_verifier_ops _name ## _verifier_ops;
2696 #define BPF_MAP_TYPE(_id, _ops) \
2697 	extern const struct bpf_map_ops _ops;
2698 #define BPF_LINK_TYPE(_id, _name)
2699 #include <linux/bpf_types.h>
2700 #undef BPF_PROG_TYPE
2701 #undef BPF_MAP_TYPE
2702 #undef BPF_LINK_TYPE
2703 
2704 extern const struct bpf_prog_ops bpf_offload_prog_ops;
2705 extern const struct bpf_verifier_ops tc_cls_act_analyzer_ops;
2706 extern const struct bpf_verifier_ops xdp_analyzer_ops;
2707 
2708 struct bpf_prog *bpf_prog_get(u32 ufd);
2709 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2710 				       bool attach_drv);
2711 void bpf_prog_add(struct bpf_prog *prog, int i);
2712 void bpf_prog_sub(struct bpf_prog *prog, int i);
2713 void bpf_prog_inc(struct bpf_prog *prog);
2714 struct bpf_prog * __must_check bpf_prog_inc_not_zero(struct bpf_prog *prog);
2715 void bpf_prog_put(struct bpf_prog *prog);
2716 
2717 void bpf_prog_free_id(struct bpf_prog *prog);
2718 void bpf_map_free_id(struct bpf_map *map);
2719 
2720 struct btf_field *btf_record_find(const struct btf_record *rec,
2721 				  u32 offset, u32 field_mask);
2722 void btf_record_free(struct btf_record *rec);
2723 void bpf_map_free_record(struct bpf_map *map);
2724 struct btf_record *btf_record_dup(const struct btf_record *rec);
2725 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b);
2726 void bpf_obj_free_timer(const struct btf_record *rec, void *obj);
2727 void bpf_obj_free_workqueue(const struct btf_record *rec, void *obj);
2728 void bpf_obj_free_task_work(const struct btf_record *rec, void *obj);
2729 void bpf_obj_cancel_fields(struct bpf_map *map, void *obj);
2730 void bpf_obj_free_fields(const struct btf_record *rec, void *obj);
2731 void __bpf_obj_drop_impl(void *p, const struct btf_record *rec, bool percpu);
2732 
2733 struct bpf_map *bpf_map_get(u32 ufd);
2734 struct bpf_map *bpf_map_get_with_uref(u32 ufd);
2735 
2736 /*
2737  * The __bpf_map_get() and __btf_get_by_fd() functions parse a file
2738  * descriptor and return a corresponding map or btf object.
2739  * Their names are double underscored to emphasize the fact that they
2740  * do not increase refcnt. To also increase refcnt use corresponding
2741  * bpf_map_get() and btf_get_by_fd() functions.
2742  */
2743 
__bpf_map_get(struct fd f)2744 static inline struct bpf_map *__bpf_map_get(struct fd f)
2745 {
2746 	if (fd_empty(f))
2747 		return ERR_PTR(-EBADF);
2748 	if (unlikely(fd_file(f)->f_op != &bpf_map_fops))
2749 		return ERR_PTR(-EINVAL);
2750 	return fd_file(f)->private_data;
2751 }
2752 
__btf_get_by_fd(struct fd f)2753 static inline struct btf *__btf_get_by_fd(struct fd f)
2754 {
2755 	if (fd_empty(f))
2756 		return ERR_PTR(-EBADF);
2757 	if (unlikely(fd_file(f)->f_op != &btf_fops))
2758 		return ERR_PTR(-EINVAL);
2759 	return fd_file(f)->private_data;
2760 }
2761 
2762 void bpf_map_inc(struct bpf_map *map);
2763 void bpf_map_inc_with_uref(struct bpf_map *map);
2764 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref);
2765 struct bpf_map * __must_check bpf_map_inc_not_zero(struct bpf_map *map);
2766 void bpf_map_put_with_uref(struct bpf_map *map);
2767 void bpf_map_put(struct bpf_map *map);
2768 void *bpf_map_area_alloc(u64 size, int numa_node);
2769 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node);
2770 void bpf_map_area_free(void *base);
2771 bool bpf_map_write_active(const struct bpf_map *map);
2772 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr);
2773 int  generic_map_lookup_batch(struct bpf_map *map,
2774 			      const union bpf_attr *attr,
2775 			      union bpf_attr __user *uattr);
2776 int  generic_map_update_batch(struct bpf_map *map, struct file *map_file,
2777 			      const union bpf_attr *attr,
2778 			      union bpf_attr __user *uattr);
2779 int  generic_map_delete_batch(struct bpf_map *map,
2780 			      const union bpf_attr *attr,
2781 			      union bpf_attr __user *uattr);
2782 struct bpf_map *bpf_map_get_curr_or_next(u32 *id);
2783 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id);
2784 
2785 
2786 int bpf_map_alloc_pages(const struct bpf_map *map, int nid,
2787 			unsigned long nr_pages, struct page **page_array);
2788 #ifdef CONFIG_MEMCG
2789 void bpf_map_memcg_enter(const struct bpf_map *map, struct mem_cgroup **old_memcg,
2790 			 struct mem_cgroup **new_memcg);
2791 void bpf_map_memcg_exit(struct mem_cgroup *old_memcg,
2792 			struct mem_cgroup *memcg);
2793 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
2794 			   int node);
2795 void *bpf_map_kmalloc_nolock(const struct bpf_map *map, size_t size, gfp_t flags,
2796 			     int node);
2797 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags);
2798 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
2799 		       gfp_t flags);
2800 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
2801 				    size_t align, gfp_t flags);
2802 #else
2803 /*
2804  * These specialized allocators have to be macros for their allocations to be
2805  * accounted separately (to have separate alloc_tag).
2806  */
2807 #define bpf_map_kmalloc_node(_map, _size, _flags, _node)	\
2808 		kmalloc_node(_size, _flags, _node)
2809 #define bpf_map_kmalloc_nolock(_map, _size, _flags, _node)	\
2810 		kmalloc_nolock(_size, _flags, _node)
2811 #define bpf_map_kzalloc(_map, _size, _flags)			\
2812 		kzalloc(_size, _flags)
2813 #define bpf_map_kvcalloc(_map, _n, _size, _flags)		\
2814 		kvcalloc(_n, _size, _flags)
2815 #define bpf_map_alloc_percpu(_map, _size, _align, _flags)	\
2816 		__alloc_percpu_gfp(_size, _align, _flags)
bpf_map_memcg_enter(const struct bpf_map * map,struct mem_cgroup ** old_memcg,struct mem_cgroup ** new_memcg)2817 static inline void bpf_map_memcg_enter(const struct bpf_map *map, struct mem_cgroup **old_memcg,
2818 				       struct mem_cgroup **new_memcg)
2819 {
2820 	*new_memcg = NULL;
2821 	*old_memcg = NULL;
2822 }
2823 
bpf_map_memcg_exit(struct mem_cgroup * old_memcg,struct mem_cgroup * memcg)2824 static inline void bpf_map_memcg_exit(struct mem_cgroup *old_memcg,
2825 				      struct mem_cgroup *memcg)
2826 {
2827 }
2828 #endif
2829 
2830 static inline int
bpf_map_init_elem_count(struct bpf_map * map)2831 bpf_map_init_elem_count(struct bpf_map *map)
2832 {
2833 	size_t size = sizeof(*map->elem_count), align = size;
2834 	gfp_t flags = GFP_USER | __GFP_NOWARN;
2835 
2836 	map->elem_count = bpf_map_alloc_percpu(map, size, align, flags);
2837 	if (!map->elem_count)
2838 		return -ENOMEM;
2839 
2840 	return 0;
2841 }
2842 
2843 static inline void
bpf_map_free_elem_count(struct bpf_map * map)2844 bpf_map_free_elem_count(struct bpf_map *map)
2845 {
2846 	free_percpu(map->elem_count);
2847 }
2848 
bpf_map_inc_elem_count(struct bpf_map * map)2849 static inline void bpf_map_inc_elem_count(struct bpf_map *map)
2850 {
2851 	this_cpu_inc(*map->elem_count);
2852 }
2853 
bpf_map_dec_elem_count(struct bpf_map * map)2854 static inline void bpf_map_dec_elem_count(struct bpf_map *map)
2855 {
2856 	this_cpu_dec(*map->elem_count);
2857 }
2858 
2859 extern int sysctl_unprivileged_bpf_disabled;
2860 
2861 bool bpf_token_capable(const struct bpf_token *token, int cap);
2862 
bpf_allow_ptr_leaks(const struct bpf_token * token)2863 static inline bool bpf_allow_ptr_leaks(const struct bpf_token *token)
2864 {
2865 	return bpf_token_capable(token, CAP_PERFMON);
2866 }
2867 
bpf_allow_uninit_stack(const struct bpf_token * token)2868 static inline bool bpf_allow_uninit_stack(const struct bpf_token *token)
2869 {
2870 	return bpf_token_capable(token, CAP_PERFMON);
2871 }
2872 
bpf_bypass_spec_v1(const struct bpf_token * token)2873 static inline bool bpf_bypass_spec_v1(const struct bpf_token *token)
2874 {
2875 	return bpf_jit_bypass_spec_v1() ||
2876 		cpu_mitigations_off() ||
2877 		bpf_token_capable(token, CAP_PERFMON);
2878 }
2879 
bpf_bypass_spec_v4(const struct bpf_token * token)2880 static inline bool bpf_bypass_spec_v4(const struct bpf_token *token)
2881 {
2882 	return bpf_jit_bypass_spec_v4() ||
2883 		cpu_mitigations_off() ||
2884 		bpf_token_capable(token, CAP_PERFMON);
2885 }
2886 
2887 int bpf_map_new_fd(struct bpf_map *map, int flags);
2888 int bpf_prog_new_fd(struct bpf_prog *prog);
2889 
2890 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2891 		   const struct bpf_link_ops *ops, struct bpf_prog *prog,
2892 		   enum bpf_attach_type attach_type);
2893 void bpf_link_init_sleepable(struct bpf_link *link, enum bpf_link_type type,
2894 			     const struct bpf_link_ops *ops, struct bpf_prog *prog,
2895 			     enum bpf_attach_type attach_type, bool sleepable);
2896 void bpf_tramp_link_init(struct bpf_tramp_link *link, enum bpf_link_type type,
2897 			 const struct bpf_link_ops *ops, struct bpf_prog *prog,
2898 			 enum bpf_attach_type attach_type, u64 cookie);
2899 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer);
2900 int bpf_link_settle(struct bpf_link_primer *primer);
2901 void bpf_link_cleanup(struct bpf_link_primer *primer);
2902 void bpf_link_inc(struct bpf_link *link);
2903 struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link);
2904 void bpf_link_put(struct bpf_link *link);
2905 int bpf_link_new_fd(struct bpf_link *link);
2906 struct bpf_link *bpf_link_get_from_fd(u32 ufd);
2907 struct bpf_link *bpf_link_get_curr_or_next(u32 *id);
2908 
2909 void bpf_token_inc(struct bpf_token *token);
2910 void bpf_token_put(struct bpf_token *token);
2911 int bpf_token_create(union bpf_attr *attr);
2912 struct bpf_token *bpf_token_get_from_fd(u32 ufd);
2913 int bpf_token_get_info_by_fd(struct bpf_token *token,
2914 			     const union bpf_attr *attr,
2915 			     union bpf_attr __user *uattr);
2916 
2917 bool bpf_token_allow_cmd(const struct bpf_token *token, enum bpf_cmd cmd);
2918 bool bpf_token_allow_map_type(const struct bpf_token *token, enum bpf_map_type type);
2919 bool bpf_token_allow_prog_type(const struct bpf_token *token,
2920 			       enum bpf_prog_type prog_type,
2921 			       enum bpf_attach_type attach_type);
2922 
2923 int bpf_obj_pin_user(u32 ufd, int path_fd, const char __user *pathname);
2924 int bpf_obj_get_user(int path_fd, const char __user *pathname, int flags);
2925 struct inode *bpf_get_inode(struct super_block *sb, const struct inode *dir,
2926 			    umode_t mode);
2927 
2928 #define BPF_ITER_FUNC_PREFIX "bpf_iter_"
2929 #define DEFINE_BPF_ITER_FUNC(target, args...)			\
2930 	extern int bpf_iter_ ## target(args);			\
2931 	int __init bpf_iter_ ## target(args) { return 0; }
2932 
2933 /*
2934  * The task type of iterators.
2935  *
2936  * For BPF task iterators, they can be parameterized with various
2937  * parameters to visit only some of tasks.
2938  *
2939  * BPF_TASK_ITER_ALL (default)
2940  *	Iterate over resources of every task.
2941  *
2942  * BPF_TASK_ITER_TID
2943  *	Iterate over resources of a task/tid.
2944  *
2945  * BPF_TASK_ITER_TGID
2946  *	Iterate over resources of every task of a process / task group.
2947  */
2948 enum bpf_iter_task_type {
2949 	BPF_TASK_ITER_ALL = 0,
2950 	BPF_TASK_ITER_TID,
2951 	BPF_TASK_ITER_TGID,
2952 };
2953 
2954 struct bpf_iter_aux_info {
2955 	/* for map_elem iter */
2956 	struct bpf_map *map;
2957 
2958 	/* for cgroup iter */
2959 	struct {
2960 		struct cgroup *start; /* starting cgroup */
2961 		enum bpf_cgroup_iter_order order;
2962 	} cgroup;
2963 	struct {
2964 		enum bpf_iter_task_type	type;
2965 		u32 pid;
2966 	} task;
2967 };
2968 
2969 typedef int (*bpf_iter_attach_target_t)(struct bpf_prog *prog,
2970 					union bpf_iter_link_info *linfo,
2971 					struct bpf_iter_aux_info *aux);
2972 typedef void (*bpf_iter_detach_target_t)(struct bpf_iter_aux_info *aux);
2973 typedef void (*bpf_iter_show_fdinfo_t) (const struct bpf_iter_aux_info *aux,
2974 					struct seq_file *seq);
2975 typedef int (*bpf_iter_fill_link_info_t)(const struct bpf_iter_aux_info *aux,
2976 					 struct bpf_link_info *info);
2977 typedef const struct bpf_func_proto *
2978 (*bpf_iter_get_func_proto_t)(enum bpf_func_id func_id,
2979 			     const struct bpf_prog *prog);
2980 
2981 enum bpf_iter_feature {
2982 	BPF_ITER_RESCHED	= BIT(0),
2983 };
2984 
2985 #define BPF_ITER_CTX_ARG_MAX 2
2986 struct bpf_iter_reg {
2987 	const char *target;
2988 	bpf_iter_attach_target_t attach_target;
2989 	bpf_iter_detach_target_t detach_target;
2990 	bpf_iter_show_fdinfo_t show_fdinfo;
2991 	bpf_iter_fill_link_info_t fill_link_info;
2992 	bpf_iter_get_func_proto_t get_func_proto;
2993 	u32 ctx_arg_info_size;
2994 	u32 feature;
2995 	struct bpf_ctx_arg_aux ctx_arg_info[BPF_ITER_CTX_ARG_MAX];
2996 	const struct bpf_iter_seq_info *seq_info;
2997 };
2998 
2999 struct bpf_iter_meta {
3000 	__bpf_md_ptr(struct seq_file *, seq);
3001 	u64 session_id;
3002 	u64 seq_num;
3003 };
3004 
3005 struct bpf_iter__bpf_map_elem {
3006 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
3007 	__bpf_md_ptr(struct bpf_map *, map);
3008 	__bpf_md_ptr(void *, key);
3009 	__bpf_md_ptr(void *, value);
3010 };
3011 
3012 int bpf_iter_reg_target(const struct bpf_iter_reg *reg_info);
3013 void bpf_iter_unreg_target(const struct bpf_iter_reg *reg_info);
3014 int bpf_iter_prog_supported(struct bpf_prog *prog);
3015 const struct bpf_func_proto *
3016 bpf_iter_get_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog);
3017 int bpf_iter_link_attach(const union bpf_attr *attr, bpfptr_t uattr, struct bpf_prog *prog);
3018 int bpf_iter_new_fd(struct bpf_link *link);
3019 bool bpf_link_is_iter(struct bpf_link *link);
3020 struct bpf_prog *bpf_iter_get_info(struct bpf_iter_meta *meta, bool in_stop);
3021 int bpf_iter_run_prog(struct bpf_prog *prog, void *ctx);
3022 void bpf_iter_map_show_fdinfo(const struct bpf_iter_aux_info *aux,
3023 			      struct seq_file *seq);
3024 int bpf_iter_map_fill_link_info(const struct bpf_iter_aux_info *aux,
3025 				struct bpf_link_info *info);
3026 
3027 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
3028 				   struct bpf_func_state *caller,
3029 				   struct bpf_func_state *callee);
3030 
3031 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value, u64 flags);
3032 int bpf_percpu_array_copy(struct bpf_map *map, void *key, void *value, u64 flags);
3033 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value,
3034 			   u64 flags);
3035 int bpf_percpu_array_update(struct bpf_map *map, void *key, void *value,
3036 			    u64 flags);
3037 
3038 int bpf_stackmap_extract(struct bpf_map *map, void *key, void *value, bool delete);
3039 
3040 int bpf_fd_array_map_update_elem(struct bpf_map *map, struct file *map_file,
3041 				 void *key, void *value, u64 map_flags);
3042 int bpf_fd_array_map_lookup_elem(struct bpf_map *map, void *key, u32 *value);
3043 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file,
3044 				void *key, void *value, u64 map_flags);
3045 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value);
3046 
3047 int bpf_get_file_flag(int flags);
3048 int bpf_check_uarg_tail_zero(bpfptr_t uaddr, size_t expected_size,
3049 			     size_t actual_size);
3050 
3051 /* verify correctness of eBPF program */
3052 struct bpf_log_attr;
3053 int bpf_check(struct bpf_prog **fp, union bpf_attr *attr, bpfptr_t uattr,
3054 	      struct bpf_log_attr *attr_log);
3055 
3056 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3057 int bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth);
3058 s32 bpf_call_args_imm(s16 idx);
3059 #else
bpf_call_args_imm(s16 idx)3060 static inline s32 bpf_call_args_imm(s16 idx)
3061 {
3062 	return 0;
3063 }
3064 #endif
3065 
3066 struct btf *bpf_get_btf_vmlinux(void);
3067 
3068 /* Map specifics */
3069 struct xdp_frame;
3070 struct sk_buff;
3071 struct bpf_dtab_netdev;
3072 struct bpf_cpu_map_entry;
3073 
3074 void __dev_flush(struct list_head *flush_list);
3075 int dev_xdp_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
3076 		    struct net_device *dev_rx);
3077 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_frame *xdpf,
3078 		    struct net_device *dev_rx);
3079 int dev_map_enqueue_multi(struct xdp_frame *xdpf, struct net_device *dev_rx,
3080 			  struct bpf_map *map, bool exclude_ingress);
3081 int dev_map_generic_redirect(struct bpf_dtab_netdev *dst, struct sk_buff *skb,
3082 			     const struct bpf_prog *xdp_prog);
3083 int dev_map_redirect_multi(struct net_device *dev, struct sk_buff *skb,
3084 			   const struct bpf_prog *xdp_prog,
3085 			   struct bpf_map *map, bool exclude_ingress);
3086 
3087 void __cpu_map_flush(struct list_head *flush_list);
3088 int cpu_map_enqueue(struct bpf_cpu_map_entry *rcpu, struct xdp_frame *xdpf,
3089 		    struct net_device *dev_rx);
3090 int cpu_map_generic_redirect(struct bpf_cpu_map_entry *rcpu,
3091 			     struct sk_buff *skb);
3092 
3093 /* Return map's numa specified by userspace */
bpf_map_attr_numa_node(const union bpf_attr * attr)3094 static inline int bpf_map_attr_numa_node(const union bpf_attr *attr)
3095 {
3096 	return (attr->map_flags & BPF_F_NUMA_NODE) ?
3097 		attr->numa_node : NUMA_NO_NODE;
3098 }
3099 
3100 struct bpf_prog *bpf_prog_get_type_path(const char *name, enum bpf_prog_type type);
3101 int array_map_alloc_check(union bpf_attr *attr);
3102 
3103 int bpf_prog_test_run_xdp(struct bpf_prog *prog, const union bpf_attr *kattr,
3104 			  union bpf_attr __user *uattr);
3105 int bpf_prog_test_run_skb(struct bpf_prog *prog, const union bpf_attr *kattr,
3106 			  union bpf_attr __user *uattr);
3107 int bpf_prog_test_run_tracing(struct bpf_prog *prog,
3108 			      const union bpf_attr *kattr,
3109 			      union bpf_attr __user *uattr);
3110 int bpf_prog_test_run_flow_dissector(struct bpf_prog *prog,
3111 				     const union bpf_attr *kattr,
3112 				     union bpf_attr __user *uattr);
3113 int bpf_prog_test_run_raw_tp(struct bpf_prog *prog,
3114 			     const union bpf_attr *kattr,
3115 			     union bpf_attr __user *uattr);
3116 int bpf_prog_test_run_sk_lookup(struct bpf_prog *prog,
3117 				const union bpf_attr *kattr,
3118 				union bpf_attr __user *uattr);
3119 int bpf_prog_test_run_nf(struct bpf_prog *prog,
3120 			 const union bpf_attr *kattr,
3121 			 union bpf_attr __user *uattr);
3122 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
3123 		    const struct bpf_prog *prog,
3124 		    struct bpf_insn_access_aux *info);
3125 
bpf_tracing_ctx_access(int off,int size,enum bpf_access_type type)3126 static inline bool bpf_tracing_ctx_access(int off, int size,
3127 					  enum bpf_access_type type)
3128 {
3129 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
3130 		return false;
3131 	if (type != BPF_READ)
3132 		return false;
3133 	if (off % size != 0)
3134 		return false;
3135 	return true;
3136 }
3137 
bpf_tracing_btf_ctx_access(int off,int size,enum bpf_access_type type,const struct bpf_prog * prog,struct bpf_insn_access_aux * info)3138 static inline bool bpf_tracing_btf_ctx_access(int off, int size,
3139 					      enum bpf_access_type type,
3140 					      const struct bpf_prog *prog,
3141 					      struct bpf_insn_access_aux *info)
3142 {
3143 	if (!bpf_tracing_ctx_access(off, size, type))
3144 		return false;
3145 	return btf_ctx_access(off, size, type, prog, info);
3146 }
3147 
3148 int btf_struct_access(struct bpf_verifier_log *log,
3149 		      const struct bpf_reg_state *reg,
3150 		      int off, int size, enum bpf_access_type atype,
3151 		      u32 *next_btf_id, enum bpf_type_flag *flag, const char **field_name);
3152 bool btf_struct_ids_match(struct bpf_verifier_log *log,
3153 			  const struct btf *btf, u32 id, int off,
3154 			  const struct btf *need_btf, u32 need_type_id,
3155 			  bool strict, bool walk_flex_arrays);
3156 
3157 int btf_distill_func_proto(struct bpf_verifier_log *log,
3158 			   struct btf *btf,
3159 			   const struct btf_type *func_proto,
3160 			   const char *func_name,
3161 			   struct btf_func_model *m);
3162 
3163 struct bpf_reg_state;
3164 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog);
3165 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
3166 			 struct btf *btf, const struct btf_type *t);
3167 const char *btf_find_decl_tag_value(const struct btf *btf, const struct btf_type *pt,
3168 				    int comp_idx, const char *tag_key);
3169 int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
3170 			   int comp_idx, const char *tag_key, int last_id);
3171 
3172 struct bpf_prog *bpf_prog_by_id(u32 id);
3173 struct bpf_link *bpf_link_by_id(u32 id);
3174 
3175 const struct bpf_func_proto *bpf_base_func_proto(enum bpf_func_id func_id,
3176 						 const struct bpf_prog *prog);
3177 void bpf_task_storage_free(struct task_struct *task);
3178 void bpf_cgrp_storage_free(struct cgroup *cgroup);
3179 const struct btf_func_model *
3180 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3181 			 const struct bpf_insn *insn);
3182 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3183 		       u16 btf_fd_idx, u8 **func_addr);
3184 
3185 struct bpf_core_ctx {
3186 	struct bpf_verifier_log *log;
3187 	const struct btf *btf;
3188 };
3189 
3190 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
3191 				const struct bpf_reg_state *reg,
3192 				const char *field_name, u32 btf_id, const char *suffix);
3193 
3194 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
3195 			       const struct btf *reg_btf, u32 reg_id,
3196 			       const struct btf *arg_btf, u32 arg_id);
3197 
3198 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
3199 		   int relo_idx, void *insn);
3200 
unprivileged_ebpf_enabled(void)3201 static inline bool unprivileged_ebpf_enabled(void)
3202 {
3203 	return !sysctl_unprivileged_bpf_disabled;
3204 }
3205 
3206 /* Not all bpf prog type has the bpf_ctx.
3207  * For the bpf prog type that has initialized the bpf_ctx,
3208  * this function can be used to decide if a kernel function
3209  * is called by a bpf program.
3210  */
has_current_bpf_ctx(void)3211 static inline bool has_current_bpf_ctx(void)
3212 {
3213 	return !!current->bpf_ctx;
3214 }
3215 
3216 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog);
3217 
3218 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
3219 		     enum bpf_dynptr_type type, u32 offset, u32 size);
3220 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr);
3221 void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr);
3222 void bpf_prog_report_arena_violation(bool write, unsigned long addr, unsigned long fault_ip);
3223 
3224 static __always_inline u32
bpf_prog_run_array_sleepable(const struct bpf_prog_array * array,const void * ctx,bpf_prog_run_fn run_prog)3225 bpf_prog_run_array_sleepable(const struct bpf_prog_array *array,
3226 			     const void *ctx, bpf_prog_run_fn run_prog)
3227 {
3228 	const struct bpf_prog_array_item *item;
3229 	struct bpf_prog *prog;
3230 	struct bpf_run_ctx *old_run_ctx;
3231 	struct bpf_trace_run_ctx run_ctx;
3232 	u32 ret = 1;
3233 
3234 	if (unlikely(!array))
3235 		return ret;
3236 
3237 	migrate_disable();
3238 
3239 	run_ctx.is_uprobe = false;
3240 
3241 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
3242 	item = &array->items[0];
3243 	while ((prog = READ_ONCE(item->prog))) {
3244 		/* Skip dummy_bpf_prog placeholder (len == 0) */
3245 		if (unlikely(!prog->len)) {
3246 			item++;
3247 			continue;
3248 		}
3249 
3250 		if (unlikely(!bpf_prog_get_recursion_context(prog))) {
3251 			bpf_prog_inc_misses_counter(prog);
3252 			bpf_prog_put_recursion_context(prog);
3253 			item++;
3254 			continue;
3255 		}
3256 
3257 		run_ctx.bpf_cookie = item->bpf_cookie;
3258 
3259 		if (!prog->sleepable) {
3260 			guard(rcu)();
3261 			ret &= run_prog(prog, ctx);
3262 		} else {
3263 			ret &= run_prog(prog, ctx);
3264 		}
3265 
3266 		bpf_prog_put_recursion_context(prog);
3267 		item++;
3268 	}
3269 	bpf_reset_run_ctx(old_run_ctx);
3270 	migrate_enable();
3271 	return ret;
3272 }
3273 
3274 #else /* !CONFIG_BPF_SYSCALL */
bpf_prog_get(u32 ufd)3275 static inline struct bpf_prog *bpf_prog_get(u32 ufd)
3276 {
3277 	return ERR_PTR(-EOPNOTSUPP);
3278 }
3279 
bpf_prog_get_type_dev(u32 ufd,enum bpf_prog_type type,bool attach_drv)3280 static inline struct bpf_prog *bpf_prog_get_type_dev(u32 ufd,
3281 						     enum bpf_prog_type type,
3282 						     bool attach_drv)
3283 {
3284 	return ERR_PTR(-EOPNOTSUPP);
3285 }
3286 
bpf_prog_add(struct bpf_prog * prog,int i)3287 static inline void bpf_prog_add(struct bpf_prog *prog, int i)
3288 {
3289 }
3290 
bpf_prog_sub(struct bpf_prog * prog,int i)3291 static inline void bpf_prog_sub(struct bpf_prog *prog, int i)
3292 {
3293 }
3294 
bpf_prog_put(struct bpf_prog * prog)3295 static inline void bpf_prog_put(struct bpf_prog *prog)
3296 {
3297 }
3298 
bpf_prog_inc(struct bpf_prog * prog)3299 static inline void bpf_prog_inc(struct bpf_prog *prog)
3300 {
3301 }
3302 
3303 static inline struct bpf_prog *__must_check
bpf_prog_inc_not_zero(struct bpf_prog * prog)3304 bpf_prog_inc_not_zero(struct bpf_prog *prog)
3305 {
3306 	return ERR_PTR(-EOPNOTSUPP);
3307 }
3308 
bpf_link_init(struct bpf_link * link,enum bpf_link_type type,const struct bpf_link_ops * ops,struct bpf_prog * prog,enum bpf_attach_type attach_type)3309 static inline void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
3310 				 const struct bpf_link_ops *ops,
3311 				 struct bpf_prog *prog, enum bpf_attach_type attach_type)
3312 {
3313 }
3314 
bpf_link_init_sleepable(struct bpf_link * link,enum bpf_link_type type,const struct bpf_link_ops * ops,struct bpf_prog * prog,enum bpf_attach_type attach_type,bool sleepable)3315 static inline void bpf_link_init_sleepable(struct bpf_link *link, enum bpf_link_type type,
3316 					   const struct bpf_link_ops *ops, struct bpf_prog *prog,
3317 					   enum bpf_attach_type attach_type, bool sleepable)
3318 {
3319 }
3320 
bpf_tramp_link_init(struct bpf_tramp_link * link,enum bpf_link_type type,const struct bpf_link_ops * ops,struct bpf_prog * prog,enum bpf_attach_type attach_type,u64 cookie)3321 static inline void bpf_tramp_link_init(struct bpf_tramp_link *link, enum bpf_link_type type,
3322 				       const struct bpf_link_ops *ops, struct bpf_prog *prog,
3323 				       enum bpf_attach_type attach_type, u64 cookie)
3324 {
3325 }
3326 
bpf_link_prime(struct bpf_link * link,struct bpf_link_primer * primer)3327 static inline int bpf_link_prime(struct bpf_link *link,
3328 				 struct bpf_link_primer *primer)
3329 {
3330 	return -EOPNOTSUPP;
3331 }
3332 
bpf_link_settle(struct bpf_link_primer * primer)3333 static inline int bpf_link_settle(struct bpf_link_primer *primer)
3334 {
3335 	return -EOPNOTSUPP;
3336 }
3337 
bpf_link_cleanup(struct bpf_link_primer * primer)3338 static inline void bpf_link_cleanup(struct bpf_link_primer *primer)
3339 {
3340 }
3341 
bpf_link_inc(struct bpf_link * link)3342 static inline void bpf_link_inc(struct bpf_link *link)
3343 {
3344 }
3345 
bpf_link_inc_not_zero(struct bpf_link * link)3346 static inline struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
3347 {
3348 	return NULL;
3349 }
3350 
bpf_link_put(struct bpf_link * link)3351 static inline void bpf_link_put(struct bpf_link *link)
3352 {
3353 }
3354 
bpf_obj_get_user(const char __user * pathname,int flags)3355 static inline int bpf_obj_get_user(const char __user *pathname, int flags)
3356 {
3357 	return -EOPNOTSUPP;
3358 }
3359 
bpf_token_capable(const struct bpf_token * token,int cap)3360 static inline bool bpf_token_capable(const struct bpf_token *token, int cap)
3361 {
3362 	return capable(cap) || (cap != CAP_SYS_ADMIN && capable(CAP_SYS_ADMIN));
3363 }
3364 
bpf_token_inc(struct bpf_token * token)3365 static inline void bpf_token_inc(struct bpf_token *token)
3366 {
3367 }
3368 
bpf_token_put(struct bpf_token * token)3369 static inline void bpf_token_put(struct bpf_token *token)
3370 {
3371 }
3372 
bpf_token_get_from_fd(u32 ufd)3373 static inline struct bpf_token *bpf_token_get_from_fd(u32 ufd)
3374 {
3375 	return ERR_PTR(-EOPNOTSUPP);
3376 }
3377 
bpf_token_get_info_by_fd(struct bpf_token * token,const union bpf_attr * attr,union bpf_attr __user * uattr)3378 static inline int bpf_token_get_info_by_fd(struct bpf_token *token,
3379 					   const union bpf_attr *attr,
3380 					   union bpf_attr __user *uattr)
3381 {
3382 	return -EOPNOTSUPP;
3383 }
3384 
__dev_flush(struct list_head * flush_list)3385 static inline void __dev_flush(struct list_head *flush_list)
3386 {
3387 }
3388 
3389 struct xdp_frame;
3390 struct bpf_dtab_netdev;
3391 struct bpf_cpu_map_entry;
3392 
3393 static inline
dev_xdp_enqueue(struct net_device * dev,struct xdp_frame * xdpf,struct net_device * dev_rx)3394 int dev_xdp_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
3395 		    struct net_device *dev_rx)
3396 {
3397 	return 0;
3398 }
3399 
3400 static inline
dev_map_enqueue(struct bpf_dtab_netdev * dst,struct xdp_frame * xdpf,struct net_device * dev_rx)3401 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_frame *xdpf,
3402 		    struct net_device *dev_rx)
3403 {
3404 	return 0;
3405 }
3406 
3407 static inline
dev_map_enqueue_multi(struct xdp_frame * xdpf,struct net_device * dev_rx,struct bpf_map * map,bool exclude_ingress)3408 int dev_map_enqueue_multi(struct xdp_frame *xdpf, struct net_device *dev_rx,
3409 			  struct bpf_map *map, bool exclude_ingress)
3410 {
3411 	return 0;
3412 }
3413 
3414 struct sk_buff;
3415 
dev_map_generic_redirect(struct bpf_dtab_netdev * dst,struct sk_buff * skb,const struct bpf_prog * xdp_prog)3416 static inline int dev_map_generic_redirect(struct bpf_dtab_netdev *dst,
3417 					   struct sk_buff *skb,
3418 					   const struct bpf_prog *xdp_prog)
3419 {
3420 	return 0;
3421 }
3422 
3423 static inline
dev_map_redirect_multi(struct net_device * dev,struct sk_buff * skb,const struct bpf_prog * xdp_prog,struct bpf_map * map,bool exclude_ingress)3424 int dev_map_redirect_multi(struct net_device *dev, struct sk_buff *skb,
3425 			   const struct bpf_prog *xdp_prog,
3426 			   struct bpf_map *map, bool exclude_ingress)
3427 {
3428 	return 0;
3429 }
3430 
__cpu_map_flush(struct list_head * flush_list)3431 static inline void __cpu_map_flush(struct list_head *flush_list)
3432 {
3433 }
3434 
cpu_map_enqueue(struct bpf_cpu_map_entry * rcpu,struct xdp_frame * xdpf,struct net_device * dev_rx)3435 static inline int cpu_map_enqueue(struct bpf_cpu_map_entry *rcpu,
3436 				  struct xdp_frame *xdpf,
3437 				  struct net_device *dev_rx)
3438 {
3439 	return 0;
3440 }
3441 
cpu_map_generic_redirect(struct bpf_cpu_map_entry * rcpu,struct sk_buff * skb)3442 static inline int cpu_map_generic_redirect(struct bpf_cpu_map_entry *rcpu,
3443 					   struct sk_buff *skb)
3444 {
3445 	return -EOPNOTSUPP;
3446 }
3447 
bpf_prog_get_type_path(const char * name,enum bpf_prog_type type)3448 static inline struct bpf_prog *bpf_prog_get_type_path(const char *name,
3449 				enum bpf_prog_type type)
3450 {
3451 	return ERR_PTR(-EOPNOTSUPP);
3452 }
3453 
bpf_prog_test_run_xdp(struct bpf_prog * prog,const union bpf_attr * kattr,union bpf_attr __user * uattr)3454 static inline int bpf_prog_test_run_xdp(struct bpf_prog *prog,
3455 					const union bpf_attr *kattr,
3456 					union bpf_attr __user *uattr)
3457 {
3458 	return -ENOTSUPP;
3459 }
3460 
bpf_prog_test_run_skb(struct bpf_prog * prog,const union bpf_attr * kattr,union bpf_attr __user * uattr)3461 static inline int bpf_prog_test_run_skb(struct bpf_prog *prog,
3462 					const union bpf_attr *kattr,
3463 					union bpf_attr __user *uattr)
3464 {
3465 	return -ENOTSUPP;
3466 }
3467 
bpf_prog_test_run_tracing(struct bpf_prog * prog,const union bpf_attr * kattr,union bpf_attr __user * uattr)3468 static inline int bpf_prog_test_run_tracing(struct bpf_prog *prog,
3469 					    const union bpf_attr *kattr,
3470 					    union bpf_attr __user *uattr)
3471 {
3472 	return -ENOTSUPP;
3473 }
3474 
bpf_prog_test_run_flow_dissector(struct bpf_prog * prog,const union bpf_attr * kattr,union bpf_attr __user * uattr)3475 static inline int bpf_prog_test_run_flow_dissector(struct bpf_prog *prog,
3476 						   const union bpf_attr *kattr,
3477 						   union bpf_attr __user *uattr)
3478 {
3479 	return -ENOTSUPP;
3480 }
3481 
bpf_prog_test_run_sk_lookup(struct bpf_prog * prog,const union bpf_attr * kattr,union bpf_attr __user * uattr)3482 static inline int bpf_prog_test_run_sk_lookup(struct bpf_prog *prog,
3483 					      const union bpf_attr *kattr,
3484 					      union bpf_attr __user *uattr)
3485 {
3486 	return -ENOTSUPP;
3487 }
3488 
bpf_map_put(struct bpf_map * map)3489 static inline void bpf_map_put(struct bpf_map *map)
3490 {
3491 }
3492 
bpf_prog_by_id(u32 id)3493 static inline struct bpf_prog *bpf_prog_by_id(u32 id)
3494 {
3495 	return ERR_PTR(-ENOTSUPP);
3496 }
3497 
btf_struct_access(struct bpf_verifier_log * log,const struct bpf_reg_state * reg,int off,int size,enum bpf_access_type atype,u32 * next_btf_id,enum bpf_type_flag * flag,const char ** field_name)3498 static inline int btf_struct_access(struct bpf_verifier_log *log,
3499 				    const struct bpf_reg_state *reg,
3500 				    int off, int size, enum bpf_access_type atype,
3501 				    u32 *next_btf_id, enum bpf_type_flag *flag,
3502 				    const char **field_name)
3503 {
3504 	return -EACCES;
3505 }
3506 
3507 static inline const struct bpf_func_proto *
bpf_base_func_proto(enum bpf_func_id func_id,const struct bpf_prog * prog)3508 bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
3509 {
3510 	return NULL;
3511 }
3512 
bpf_task_storage_free(struct task_struct * task)3513 static inline void bpf_task_storage_free(struct task_struct *task)
3514 {
3515 }
3516 
3517 static inline const struct btf_func_model *
bpf_jit_find_kfunc_model(const struct bpf_prog * prog,const struct bpf_insn * insn)3518 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3519 			 const struct bpf_insn *insn)
3520 {
3521 	return NULL;
3522 }
3523 
3524 static inline int
bpf_get_kfunc_addr(const struct bpf_prog * prog,u32 func_id,u16 btf_fd_idx,u8 ** func_addr)3525 bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3526 		   u16 btf_fd_idx, u8 **func_addr)
3527 {
3528 	return -ENOTSUPP;
3529 }
3530 
unprivileged_ebpf_enabled(void)3531 static inline bool unprivileged_ebpf_enabled(void)
3532 {
3533 	return false;
3534 }
3535 
has_current_bpf_ctx(void)3536 static inline bool has_current_bpf_ctx(void)
3537 {
3538 	return false;
3539 }
3540 
bpf_prog_inc_misses_counter(struct bpf_prog * prog)3541 static inline void bpf_prog_inc_misses_counter(struct bpf_prog *prog)
3542 {
3543 }
3544 
bpf_cgrp_storage_free(struct cgroup * cgroup)3545 static inline void bpf_cgrp_storage_free(struct cgroup *cgroup)
3546 {
3547 }
3548 
bpf_dynptr_init(struct bpf_dynptr_kern * ptr,void * data,enum bpf_dynptr_type type,u32 offset,u32 size)3549 static inline void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
3550 				   enum bpf_dynptr_type type, u32 offset, u32 size)
3551 {
3552 }
3553 
bpf_dynptr_set_null(struct bpf_dynptr_kern * ptr)3554 static inline void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
3555 {
3556 }
3557 
bpf_dynptr_set_rdonly(struct bpf_dynptr_kern * ptr)3558 static inline void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
3559 {
3560 }
3561 
bpf_prog_report_arena_violation(bool write,unsigned long addr,unsigned long fault_ip)3562 static inline void bpf_prog_report_arena_violation(bool write, unsigned long addr,
3563 						   unsigned long fault_ip)
3564 {
3565 }
3566 #endif /* CONFIG_BPF_SYSCALL */
3567 
bpf_net_capable(void)3568 static inline bool bpf_net_capable(void)
3569 {
3570 	return capable(CAP_NET_ADMIN) || capable(CAP_SYS_ADMIN);
3571 }
3572 
3573 static __always_inline int
bpf_probe_read_kernel_common(void * dst,u32 size,const void * unsafe_ptr)3574 bpf_probe_read_kernel_common(void *dst, u32 size, const void *unsafe_ptr)
3575 {
3576 	int ret = -EFAULT;
3577 
3578 	if (IS_ENABLED(CONFIG_BPF_EVENTS))
3579 		ret = copy_from_kernel_nofault(dst, unsafe_ptr, size);
3580 	if (unlikely(ret < 0))
3581 		memset(dst, 0, size);
3582 	return ret;
3583 }
3584 
3585 void __bpf_free_used_btfs(struct btf_mod_pair *used_btfs, u32 len);
3586 
bpf_prog_get_type(u32 ufd,enum bpf_prog_type type)3587 static inline struct bpf_prog *bpf_prog_get_type(u32 ufd,
3588 						 enum bpf_prog_type type)
3589 {
3590 	return bpf_prog_get_type_dev(ufd, type, false);
3591 }
3592 
3593 void __bpf_free_used_maps(struct bpf_prog_aux *aux,
3594 			  struct bpf_map **used_maps, u32 len);
3595 
3596 bool bpf_prog_get_ok(struct bpf_prog *, enum bpf_prog_type *, bool);
3597 
3598 int bpf_prog_offload_compile(struct bpf_prog *prog);
3599 void bpf_prog_dev_bound_destroy(struct bpf_prog *prog);
3600 int bpf_prog_offload_info_fill(struct bpf_prog_info *info,
3601 			       struct bpf_prog *prog);
3602 
3603 int bpf_map_offload_info_fill(struct bpf_map_info *info, struct bpf_map *map);
3604 
3605 int bpf_map_offload_lookup_elem(struct bpf_map *map, void *key, void *value);
3606 int bpf_map_offload_update_elem(struct bpf_map *map,
3607 				void *key, void *value, u64 flags);
3608 int bpf_map_offload_delete_elem(struct bpf_map *map, void *key);
3609 int bpf_map_offload_get_next_key(struct bpf_map *map,
3610 				 void *key, void *next_key);
3611 
3612 bool bpf_offload_prog_map_match(struct bpf_prog *prog, struct bpf_map *map);
3613 
3614 struct bpf_offload_dev *
3615 bpf_offload_dev_create(const struct bpf_prog_offload_ops *ops, void *priv);
3616 void bpf_offload_dev_destroy(struct bpf_offload_dev *offdev);
3617 void *bpf_offload_dev_priv(struct bpf_offload_dev *offdev);
3618 int bpf_offload_dev_netdev_register(struct bpf_offload_dev *offdev,
3619 				    struct net_device *netdev);
3620 void bpf_offload_dev_netdev_unregister(struct bpf_offload_dev *offdev,
3621 				       struct net_device *netdev);
3622 bool bpf_offload_dev_match(struct bpf_prog *prog, struct net_device *netdev);
3623 
3624 void unpriv_ebpf_notify(int new_state);
3625 
3626 #if defined(CONFIG_NET) && defined(CONFIG_BPF_SYSCALL)
3627 int bpf_dev_bound_kfunc_check(struct bpf_verifier_log *log,
3628 			      struct bpf_prog_aux *prog_aux);
3629 void *bpf_dev_bound_resolve_kfunc(struct bpf_prog *prog, u32 func_id);
3630 int bpf_prog_dev_bound_init(struct bpf_prog *prog, union bpf_attr *attr);
3631 int bpf_prog_dev_bound_inherit(struct bpf_prog *new_prog, struct bpf_prog *old_prog);
3632 void bpf_dev_bound_netdev_unregister(struct net_device *dev);
3633 
bpf_prog_is_dev_bound(const struct bpf_prog_aux * aux)3634 static inline bool bpf_prog_is_dev_bound(const struct bpf_prog_aux *aux)
3635 {
3636 	return aux->dev_bound;
3637 }
3638 
bpf_prog_is_offloaded(const struct bpf_prog_aux * aux)3639 static inline bool bpf_prog_is_offloaded(const struct bpf_prog_aux *aux)
3640 {
3641 	return aux->offload_requested;
3642 }
3643 
3644 bool bpf_prog_dev_bound_match(const struct bpf_prog *lhs, const struct bpf_prog *rhs);
3645 
bpf_map_is_offloaded(struct bpf_map * map)3646 static inline bool bpf_map_is_offloaded(struct bpf_map *map)
3647 {
3648 	return unlikely(map->ops == &bpf_map_offload_ops);
3649 }
3650 
3651 struct bpf_map *bpf_map_offload_map_alloc(union bpf_attr *attr);
3652 void bpf_map_offload_map_free(struct bpf_map *map);
3653 u64 bpf_map_offload_map_mem_usage(const struct bpf_map *map);
3654 int bpf_prog_test_run_syscall(struct bpf_prog *prog,
3655 			      const union bpf_attr *kattr,
3656 			      union bpf_attr __user *uattr);
3657 
3658 int sock_map_get_from_fd(const union bpf_attr *attr, struct bpf_prog *prog);
3659 int sock_map_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype);
3660 int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value, u64 flags);
3661 int sock_map_bpf_prog_query(const union bpf_attr *attr,
3662 			    union bpf_attr __user *uattr);
3663 int sock_map_link_create(const union bpf_attr *attr, struct bpf_prog *prog);
3664 
3665 void sock_map_unhash(struct sock *sk);
3666 void sock_map_destroy(struct sock *sk);
3667 void sock_map_close(struct sock *sk, long timeout);
3668 #else
bpf_dev_bound_kfunc_check(struct bpf_verifier_log * log,struct bpf_prog_aux * prog_aux)3669 static inline int bpf_dev_bound_kfunc_check(struct bpf_verifier_log *log,
3670 					    struct bpf_prog_aux *prog_aux)
3671 {
3672 	return -EOPNOTSUPP;
3673 }
3674 
bpf_dev_bound_resolve_kfunc(struct bpf_prog * prog,u32 func_id)3675 static inline void *bpf_dev_bound_resolve_kfunc(struct bpf_prog *prog,
3676 						u32 func_id)
3677 {
3678 	return NULL;
3679 }
3680 
bpf_prog_dev_bound_init(struct bpf_prog * prog,union bpf_attr * attr)3681 static inline int bpf_prog_dev_bound_init(struct bpf_prog *prog,
3682 					  union bpf_attr *attr)
3683 {
3684 	return -EOPNOTSUPP;
3685 }
3686 
bpf_prog_dev_bound_inherit(struct bpf_prog * new_prog,struct bpf_prog * old_prog)3687 static inline int bpf_prog_dev_bound_inherit(struct bpf_prog *new_prog,
3688 					     struct bpf_prog *old_prog)
3689 {
3690 	return -EOPNOTSUPP;
3691 }
3692 
bpf_dev_bound_netdev_unregister(struct net_device * dev)3693 static inline void bpf_dev_bound_netdev_unregister(struct net_device *dev)
3694 {
3695 }
3696 
bpf_prog_is_dev_bound(const struct bpf_prog_aux * aux)3697 static inline bool bpf_prog_is_dev_bound(const struct bpf_prog_aux *aux)
3698 {
3699 	return false;
3700 }
3701 
bpf_prog_is_offloaded(struct bpf_prog_aux * aux)3702 static inline bool bpf_prog_is_offloaded(struct bpf_prog_aux *aux)
3703 {
3704 	return false;
3705 }
3706 
bpf_prog_dev_bound_match(const struct bpf_prog * lhs,const struct bpf_prog * rhs)3707 static inline bool bpf_prog_dev_bound_match(const struct bpf_prog *lhs, const struct bpf_prog *rhs)
3708 {
3709 	return false;
3710 }
3711 
bpf_map_is_offloaded(struct bpf_map * map)3712 static inline bool bpf_map_is_offloaded(struct bpf_map *map)
3713 {
3714 	return false;
3715 }
3716 
bpf_map_offload_map_alloc(union bpf_attr * attr)3717 static inline struct bpf_map *bpf_map_offload_map_alloc(union bpf_attr *attr)
3718 {
3719 	return ERR_PTR(-EOPNOTSUPP);
3720 }
3721 
bpf_map_offload_map_free(struct bpf_map * map)3722 static inline void bpf_map_offload_map_free(struct bpf_map *map)
3723 {
3724 }
3725 
bpf_map_offload_map_mem_usage(const struct bpf_map * map)3726 static inline u64 bpf_map_offload_map_mem_usage(const struct bpf_map *map)
3727 {
3728 	return 0;
3729 }
3730 
bpf_prog_test_run_syscall(struct bpf_prog * prog,const union bpf_attr * kattr,union bpf_attr __user * uattr)3731 static inline int bpf_prog_test_run_syscall(struct bpf_prog *prog,
3732 					    const union bpf_attr *kattr,
3733 					    union bpf_attr __user *uattr)
3734 {
3735 	return -ENOTSUPP;
3736 }
3737 
3738 #ifdef CONFIG_BPF_SYSCALL
sock_map_get_from_fd(const union bpf_attr * attr,struct bpf_prog * prog)3739 static inline int sock_map_get_from_fd(const union bpf_attr *attr,
3740 				       struct bpf_prog *prog)
3741 {
3742 	return -EINVAL;
3743 }
3744 
sock_map_prog_detach(const union bpf_attr * attr,enum bpf_prog_type ptype)3745 static inline int sock_map_prog_detach(const union bpf_attr *attr,
3746 				       enum bpf_prog_type ptype)
3747 {
3748 	return -EOPNOTSUPP;
3749 }
3750 
sock_map_update_elem_sys(struct bpf_map * map,void * key,void * value,u64 flags)3751 static inline int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value,
3752 					   u64 flags)
3753 {
3754 	return -EOPNOTSUPP;
3755 }
3756 
sock_map_bpf_prog_query(const union bpf_attr * attr,union bpf_attr __user * uattr)3757 static inline int sock_map_bpf_prog_query(const union bpf_attr *attr,
3758 					  union bpf_attr __user *uattr)
3759 {
3760 	return -EINVAL;
3761 }
3762 
sock_map_link_create(const union bpf_attr * attr,struct bpf_prog * prog)3763 static inline int sock_map_link_create(const union bpf_attr *attr, struct bpf_prog *prog)
3764 {
3765 	return -EOPNOTSUPP;
3766 }
3767 #endif /* CONFIG_BPF_SYSCALL */
3768 #endif /* CONFIG_NET && CONFIG_BPF_SYSCALL */
3769 
3770 static __always_inline void
bpf_prog_inc_misses_counters(const struct bpf_prog_array * array)3771 bpf_prog_inc_misses_counters(const struct bpf_prog_array *array)
3772 {
3773 	const struct bpf_prog_array_item *item;
3774 	struct bpf_prog *prog;
3775 
3776 	if (unlikely(!array))
3777 		return;
3778 
3779 	item = &array->items[0];
3780 	while ((prog = READ_ONCE(item->prog))) {
3781 		bpf_prog_inc_misses_counter(prog);
3782 		item++;
3783 	}
3784 }
3785 
3786 #if defined(CONFIG_INET) && defined(CONFIG_BPF_SYSCALL)
3787 void bpf_sk_reuseport_detach(struct sock *sk);
3788 int bpf_fd_reuseport_array_lookup_elem(struct bpf_map *map, void *key,
3789 				       void *value);
3790 int bpf_fd_reuseport_array_update_elem(struct bpf_map *map, void *key,
3791 				       void *value, u64 map_flags);
3792 #else
bpf_sk_reuseport_detach(struct sock * sk)3793 static inline void bpf_sk_reuseport_detach(struct sock *sk)
3794 {
3795 }
3796 
3797 #ifdef CONFIG_BPF_SYSCALL
bpf_fd_reuseport_array_lookup_elem(struct bpf_map * map,void * key,void * value)3798 static inline int bpf_fd_reuseport_array_lookup_elem(struct bpf_map *map,
3799 						     void *key, void *value)
3800 {
3801 	return -EOPNOTSUPP;
3802 }
3803 
bpf_fd_reuseport_array_update_elem(struct bpf_map * map,void * key,void * value,u64 map_flags)3804 static inline int bpf_fd_reuseport_array_update_elem(struct bpf_map *map,
3805 						     void *key, void *value,
3806 						     u64 map_flags)
3807 {
3808 	return -EOPNOTSUPP;
3809 }
3810 #endif /* CONFIG_BPF_SYSCALL */
3811 #endif /* defined(CONFIG_INET) && defined(CONFIG_BPF_SYSCALL) */
3812 
3813 #ifdef CONFIG_KEYS
3814 struct bpf_key {
3815 	struct key *key;
3816 	bool has_ref;
3817 };
3818 #endif /* CONFIG_KEYS */
3819 
3820 #if defined(CONFIG_KEYS) && defined(CONFIG_BPF_SYSCALL)
3821 struct bpf_key *bpf_lookup_user_key(s32 serial, u64 flags);
3822 struct bpf_key *bpf_lookup_system_key(u64 id);
3823 void bpf_key_put(struct bpf_key *bkey);
3824 int bpf_verify_pkcs7_signature(const struct bpf_dynptr *data_p,
3825 			       const struct bpf_dynptr *sig_p,
3826 			       struct bpf_key *trusted_keyring);
3827 
bpf_key_serial(const struct bpf_key * key)3828 static inline s32 bpf_key_serial(const struct bpf_key *key)
3829 {
3830 	return key->has_ref ? key->key->serial : 0;
3831 }
3832 #else
bpf_lookup_user_key(u32 serial,u64 flags)3833 static inline struct bpf_key *bpf_lookup_user_key(u32 serial, u64 flags)
3834 {
3835 	return NULL;
3836 }
3837 
bpf_lookup_system_key(u64 id)3838 static inline struct bpf_key *bpf_lookup_system_key(u64 id)
3839 {
3840 	return NULL;
3841 }
3842 
bpf_key_put(struct bpf_key * bkey)3843 static inline void bpf_key_put(struct bpf_key *bkey)
3844 {
3845 }
3846 
bpf_verify_pkcs7_signature(const struct bpf_dynptr * data_p,const struct bpf_dynptr * sig_p,struct bpf_key * trusted_keyring)3847 static inline int bpf_verify_pkcs7_signature(const struct bpf_dynptr *data_p,
3848 					     const struct bpf_dynptr *sig_p,
3849 					     struct bpf_key *trusted_keyring)
3850 {
3851 	return -EOPNOTSUPP;
3852 }
3853 
bpf_key_serial(const struct bpf_key * key)3854 static inline s32 bpf_key_serial(const struct bpf_key *key)
3855 {
3856 	return 0;
3857 }
3858 #endif /* defined(CONFIG_KEYS) && defined(CONFIG_BPF_SYSCALL) */
3859 
3860 /* verifier prototypes for helper functions called from eBPF programs */
3861 extern const struct bpf_func_proto bpf_map_lookup_elem_proto;
3862 extern const struct bpf_func_proto bpf_map_update_elem_proto;
3863 extern const struct bpf_func_proto bpf_map_delete_elem_proto;
3864 extern const struct bpf_func_proto bpf_map_push_elem_proto;
3865 extern const struct bpf_func_proto bpf_map_pop_elem_proto;
3866 extern const struct bpf_func_proto bpf_map_peek_elem_proto;
3867 extern const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto;
3868 
3869 extern const struct bpf_func_proto bpf_get_prandom_u32_proto;
3870 extern const struct bpf_func_proto bpf_get_smp_processor_id_proto;
3871 extern const struct bpf_func_proto bpf_get_numa_node_id_proto;
3872 extern const struct bpf_func_proto bpf_tail_call_proto;
3873 extern const struct bpf_func_proto bpf_ktime_get_ns_proto;
3874 extern const struct bpf_func_proto bpf_ktime_get_boot_ns_proto;
3875 extern const struct bpf_func_proto bpf_ktime_get_tai_ns_proto;
3876 extern const struct bpf_func_proto bpf_get_current_pid_tgid_proto;
3877 extern const struct bpf_func_proto bpf_get_current_uid_gid_proto;
3878 extern const struct bpf_func_proto bpf_get_current_comm_proto;
3879 extern const struct bpf_func_proto bpf_get_stackid_proto;
3880 extern const struct bpf_func_proto bpf_get_stack_proto;
3881 extern const struct bpf_func_proto bpf_get_stack_sleepable_proto;
3882 extern const struct bpf_func_proto bpf_get_task_stack_proto;
3883 extern const struct bpf_func_proto bpf_get_task_stack_sleepable_proto;
3884 extern const struct bpf_func_proto bpf_get_stackid_proto_pe;
3885 extern const struct bpf_func_proto bpf_get_stack_proto_pe;
3886 extern const struct bpf_func_proto bpf_sock_map_update_proto;
3887 extern const struct bpf_func_proto bpf_sock_hash_update_proto;
3888 extern const struct bpf_func_proto bpf_get_current_cgroup_id_proto;
3889 extern const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto;
3890 extern const struct bpf_func_proto bpf_get_cgroup_classid_curr_proto;
3891 extern const struct bpf_func_proto bpf_current_task_under_cgroup_proto;
3892 extern const struct bpf_func_proto bpf_msg_redirect_hash_proto;
3893 extern const struct bpf_func_proto bpf_msg_redirect_map_proto;
3894 extern const struct bpf_func_proto bpf_sk_redirect_hash_proto;
3895 extern const struct bpf_func_proto bpf_sk_redirect_map_proto;
3896 extern const struct bpf_func_proto bpf_spin_lock_proto;
3897 extern const struct bpf_func_proto bpf_spin_unlock_proto;
3898 extern const struct bpf_func_proto bpf_get_local_storage_proto;
3899 extern const struct bpf_func_proto bpf_strtol_proto;
3900 extern const struct bpf_func_proto bpf_strtoul_proto;
3901 extern const struct bpf_func_proto bpf_tcp_sock_proto;
3902 extern const struct bpf_func_proto bpf_jiffies64_proto;
3903 extern const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto;
3904 extern const struct bpf_func_proto bpf_event_output_data_proto;
3905 extern const struct bpf_func_proto bpf_ringbuf_output_proto;
3906 extern const struct bpf_func_proto bpf_ringbuf_reserve_proto;
3907 extern const struct bpf_func_proto bpf_ringbuf_submit_proto;
3908 extern const struct bpf_func_proto bpf_ringbuf_discard_proto;
3909 extern const struct bpf_func_proto bpf_ringbuf_query_proto;
3910 extern const struct bpf_func_proto bpf_ringbuf_reserve_dynptr_proto;
3911 extern const struct bpf_func_proto bpf_ringbuf_submit_dynptr_proto;
3912 extern const struct bpf_func_proto bpf_ringbuf_discard_dynptr_proto;
3913 extern const struct bpf_func_proto bpf_skc_to_tcp6_sock_proto;
3914 extern const struct bpf_func_proto bpf_skc_to_tcp_sock_proto;
3915 extern const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto;
3916 extern const struct bpf_func_proto bpf_skc_to_tcp_request_sock_proto;
3917 extern const struct bpf_func_proto bpf_skc_to_udp6_sock_proto;
3918 extern const struct bpf_func_proto bpf_skc_to_unix_sock_proto;
3919 extern const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto;
3920 extern const struct bpf_func_proto bpf_copy_from_user_proto;
3921 extern const struct bpf_func_proto bpf_snprintf_btf_proto;
3922 extern const struct bpf_func_proto bpf_snprintf_proto;
3923 extern const struct bpf_func_proto bpf_per_cpu_ptr_proto;
3924 extern const struct bpf_func_proto bpf_this_cpu_ptr_proto;
3925 extern const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto;
3926 extern const struct bpf_func_proto bpf_sock_from_file_proto;
3927 extern const struct bpf_func_proto bpf_get_socket_ptr_cookie_proto;
3928 extern const struct bpf_func_proto bpf_task_storage_get_recur_proto;
3929 extern const struct bpf_func_proto bpf_task_storage_get_proto;
3930 extern const struct bpf_func_proto bpf_task_storage_delete_recur_proto;
3931 extern const struct bpf_func_proto bpf_task_storage_delete_proto;
3932 extern const struct bpf_func_proto bpf_for_each_map_elem_proto;
3933 extern const struct bpf_func_proto bpf_btf_find_by_name_kind_proto;
3934 extern const struct bpf_func_proto bpf_sk_setsockopt_proto;
3935 extern const struct bpf_func_proto bpf_sk_getsockopt_proto;
3936 extern const struct bpf_func_proto bpf_sk_setsockopt_nodelay_proto;
3937 extern const struct bpf_func_proto bpf_unlocked_sk_setsockopt_proto;
3938 extern const struct bpf_func_proto bpf_unlocked_sk_getsockopt_proto;
3939 extern const struct bpf_func_proto bpf_find_vma_proto;
3940 extern const struct bpf_func_proto bpf_loop_proto;
3941 extern const struct bpf_func_proto bpf_copy_from_user_task_proto;
3942 extern const struct bpf_func_proto bpf_set_retval_proto;
3943 extern const struct bpf_func_proto bpf_get_retval_proto;
3944 extern const struct bpf_func_proto bpf_user_ringbuf_drain_proto;
3945 extern const struct bpf_func_proto bpf_cgrp_storage_get_proto;
3946 extern const struct bpf_func_proto bpf_cgrp_storage_delete_proto;
3947 
3948 const struct bpf_func_proto *tracing_prog_func_proto(
3949   enum bpf_func_id func_id, const struct bpf_prog *prog);
3950 
3951 /* Shared helpers among cBPF and eBPF. */
3952 void bpf_user_rnd_init_once(void);
3953 u64 bpf_user_rnd_u32(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
3954 u64 bpf_get_raw_cpu_id(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
3955 
3956 #if defined(CONFIG_NET)
3957 bool bpf_sock_common_is_valid_access(int off, int size,
3958 				     enum bpf_access_type type,
3959 				     struct bpf_insn_access_aux *info);
3960 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
3961 			      struct bpf_insn_access_aux *info);
3962 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
3963 				const struct bpf_insn *si,
3964 				struct bpf_insn *insn_buf,
3965 				struct bpf_prog *prog,
3966 				u32 *target_size);
3967 int bpf_dynptr_from_skb_rdonly(struct __sk_buff *skb, u64 flags,
3968 			       struct bpf_dynptr *ptr);
3969 #else
bpf_sock_common_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)3970 static inline bool bpf_sock_common_is_valid_access(int off, int size,
3971 						   enum bpf_access_type type,
3972 						   struct bpf_insn_access_aux *info)
3973 {
3974 	return false;
3975 }
bpf_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)3976 static inline bool bpf_sock_is_valid_access(int off, int size,
3977 					    enum bpf_access_type type,
3978 					    struct bpf_insn_access_aux *info)
3979 {
3980 	return false;
3981 }
bpf_sock_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)3982 static inline u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
3983 					      const struct bpf_insn *si,
3984 					      struct bpf_insn *insn_buf,
3985 					      struct bpf_prog *prog,
3986 					      u32 *target_size)
3987 {
3988 	return 0;
3989 }
bpf_dynptr_from_skb_rdonly(struct __sk_buff * skb,u64 flags,struct bpf_dynptr * ptr)3990 static inline int bpf_dynptr_from_skb_rdonly(struct __sk_buff *skb, u64 flags,
3991 					     struct bpf_dynptr *ptr)
3992 {
3993 	return -EOPNOTSUPP;
3994 }
3995 #endif
3996 
3997 #ifdef CONFIG_INET
3998 struct sk_reuseport_kern {
3999 	struct sk_buff *skb;
4000 	struct sock *sk;
4001 	struct sock *selected_sk;
4002 	struct sock *migrating_sk;
4003 	void *data_end;
4004 	u32 hash;
4005 	u32 reuseport_id;
4006 	bool bind_inany;
4007 };
4008 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
4009 				  struct bpf_insn_access_aux *info);
4010 
4011 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
4012 				    const struct bpf_insn *si,
4013 				    struct bpf_insn *insn_buf,
4014 				    struct bpf_prog *prog,
4015 				    u32 *target_size);
4016 
4017 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
4018 				  struct bpf_insn_access_aux *info);
4019 
4020 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
4021 				    const struct bpf_insn *si,
4022 				    struct bpf_insn *insn_buf,
4023 				    struct bpf_prog *prog,
4024 				    u32 *target_size);
4025 #else
bpf_tcp_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)4026 static inline bool bpf_tcp_sock_is_valid_access(int off, int size,
4027 						enum bpf_access_type type,
4028 						struct bpf_insn_access_aux *info)
4029 {
4030 	return false;
4031 }
4032 
bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)4033 static inline u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
4034 						  const struct bpf_insn *si,
4035 						  struct bpf_insn *insn_buf,
4036 						  struct bpf_prog *prog,
4037 						  u32 *target_size)
4038 {
4039 	return 0;
4040 }
bpf_xdp_sock_is_valid_access(int off,int size,enum bpf_access_type type,struct bpf_insn_access_aux * info)4041 static inline bool bpf_xdp_sock_is_valid_access(int off, int size,
4042 						enum bpf_access_type type,
4043 						struct bpf_insn_access_aux *info)
4044 {
4045 	return false;
4046 }
4047 
bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,const struct bpf_insn * si,struct bpf_insn * insn_buf,struct bpf_prog * prog,u32 * target_size)4048 static inline u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
4049 						  const struct bpf_insn *si,
4050 						  struct bpf_insn *insn_buf,
4051 						  struct bpf_prog *prog,
4052 						  u32 *target_size)
4053 {
4054 	return 0;
4055 }
4056 #endif /* CONFIG_INET */
4057 
4058 enum bpf_text_poke_type {
4059 	BPF_MOD_NOP,
4060 	BPF_MOD_CALL,
4061 	BPF_MOD_JUMP,
4062 };
4063 
4064 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t,
4065 		       enum bpf_text_poke_type new_t, void *old_addr,
4066 		       void *new_addr);
4067 
4068 void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
4069 			       struct bpf_prog *new, struct bpf_prog *old);
4070 
4071 void *bpf_arch_text_copy(void *dst, void *src, size_t len);
4072 int bpf_arch_text_invalidate(void *dst, size_t len);
4073 
4074 struct btf_id_set;
4075 bool btf_id_set_contains(const struct btf_id_set *set, u32 id);
4076 
4077 #define MAX_BPRINTF_VARARGS		12
4078 #define MAX_BPRINTF_BUF			1024
4079 
4080 /* Per-cpu temp buffers used by printf-like helpers to store the bprintf binary
4081  * arguments representation.
4082  */
4083 #define MAX_BPRINTF_BIN_ARGS	512
4084 
4085 struct bpf_bprintf_buffers {
4086 	char bin_args[MAX_BPRINTF_BIN_ARGS];
4087 	char buf[MAX_BPRINTF_BUF];
4088 };
4089 
4090 struct bpf_bprintf_data {
4091 	u32 *bin_args;
4092 	char *buf;
4093 	bool get_bin_args;
4094 	bool get_buf;
4095 };
4096 
4097 int bpf_bprintf_prepare(const char *fmt, u32 fmt_size, const u64 *raw_args,
4098 			u32 num_args, struct bpf_bprintf_data *data);
4099 void bpf_bprintf_cleanup(struct bpf_bprintf_data *data);
4100 int bpf_try_get_buffers(struct bpf_bprintf_buffers **bufs);
4101 void bpf_put_buffers(void);
4102 
4103 void bpf_prog_stream_init(struct bpf_prog *prog);
4104 void bpf_prog_stream_free(struct bpf_prog *prog);
4105 int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, void __user *buf, int len);
4106 void bpf_stream_stage_init(struct bpf_stream_stage *ss);
4107 void bpf_stream_stage_free(struct bpf_stream_stage *ss);
4108 __printf(2, 3)
4109 int bpf_stream_stage_printk(struct bpf_stream_stage *ss, const char *fmt, ...);
4110 int bpf_stream_stage_commit(struct bpf_stream_stage *ss, struct bpf_prog *prog,
4111 			    enum bpf_stream_id stream_id);
4112 int bpf_stream_stage_dump_stack(struct bpf_stream_stage *ss);
4113 
4114 #define bpf_stream_printk(ss, ...) bpf_stream_stage_printk(&ss, __VA_ARGS__)
4115 #define bpf_stream_dump_stack(ss) bpf_stream_stage_dump_stack(&ss)
4116 
4117 #define bpf_stream_stage(ss, prog, stream_id, expr)            \
4118 	({                                                     \
4119 		bpf_stream_stage_init(&ss);                    \
4120 		(expr);                                        \
4121 		bpf_stream_stage_commit(&ss, prog, stream_id); \
4122 		bpf_stream_stage_free(&ss);                    \
4123 	})
4124 
4125 #ifdef CONFIG_BPF_LSM
4126 void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype);
4127 void bpf_cgroup_atype_put(int cgroup_atype);
4128 #else
bpf_cgroup_atype_get(u32 attach_btf_id,int cgroup_atype)4129 static inline void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype) {}
bpf_cgroup_atype_put(int cgroup_atype)4130 static inline void bpf_cgroup_atype_put(int cgroup_atype) {}
4131 #endif /* CONFIG_BPF_LSM */
4132 
type_is_alloc(u32 type)4133 static inline bool type_is_alloc(u32 type)
4134 {
4135 	return type & MEM_ALLOC;
4136 }
4137 
bpf_memcg_flags(gfp_t flags)4138 static inline gfp_t bpf_memcg_flags(gfp_t flags)
4139 {
4140 	if (memcg_bpf_enabled())
4141 		return flags | __GFP_ACCOUNT;
4142 	return flags;
4143 }
4144 
bpf_is_subprog(const struct bpf_prog * prog)4145 static inline bool bpf_is_subprog(const struct bpf_prog *prog)
4146 {
4147 	return prog->aux->func_idx != 0;
4148 }
4149 
4150 const struct bpf_line_info *bpf_find_linfo(const struct bpf_prog *prog, u32 insn_off);
4151 struct bpf_linfo_source {
4152 	const char *file;
4153 	const char *line;
4154 	u32 file_name_off;
4155 	int line_num;
4156 	int line_col;
4157 };
4158 
4159 void bpf_get_linfo_source(struct btf *btf, const struct bpf_line_info *linfo,
4160 			  struct bpf_linfo_source *src);
4161 int bpf_prog_get_file_line(struct bpf_prog *prog, unsigned long ip, const char **filep,
4162 			   const char **linep, int *nump);
4163 struct bpf_prog *bpf_prog_find_from_stack(void);
4164 
4165 int bpf_insn_array_init(struct bpf_map *map, const struct bpf_prog *prog);
4166 int bpf_insn_array_ready(struct bpf_map *map);
4167 void bpf_insn_array_release(struct bpf_map *map);
4168 void bpf_insn_array_adjust(struct bpf_map *map, u32 off, u32 len);
4169 void bpf_insn_array_adjust_after_remove(struct bpf_map *map, u32 off, u32 len);
4170 
4171 #ifdef CONFIG_BPF_SYSCALL
4172 void bpf_prog_update_insn_ptrs(struct bpf_prog *prog, u32 *offsets, void *image);
4173 #else
4174 static inline void
bpf_prog_update_insn_ptrs(struct bpf_prog * prog,u32 * offsets,void * image)4175 bpf_prog_update_insn_ptrs(struct bpf_prog *prog, u32 *offsets, void *image)
4176 {
4177 }
4178 #endif
4179 
bpf_map_is_percpu_map(enum bpf_map_type map_type)4180 static inline bool bpf_map_is_percpu_map(enum bpf_map_type map_type)
4181 {
4182 	switch (map_type) {
4183 	case BPF_MAP_TYPE_PERCPU_ARRAY:
4184 	case BPF_MAP_TYPE_PERCPU_HASH:
4185 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
4186 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4187 		return true;
4188 	default:
4189 		return false;
4190 	}
4191 }
4192 
bpf_map_check_op_flags(struct bpf_map * map,u64 flags,u64 allowed_flags)4193 static inline int bpf_map_check_op_flags(struct bpf_map *map, u64 flags, u64 allowed_flags)
4194 {
4195 	u32 cpu;
4196 
4197 	if ((u32)flags & ~allowed_flags)
4198 		return -EINVAL;
4199 
4200 	if ((flags & BPF_F_LOCK) && !btf_record_has_field(map->record, BPF_SPIN_LOCK))
4201 		return -EINVAL;
4202 
4203 	if (!(flags & BPF_F_CPU) && flags >> 32)
4204 		return -EINVAL;
4205 
4206 	if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
4207 		if (!bpf_map_is_percpu_map(map->map_type))
4208 			return -EINVAL;
4209 		if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS))
4210 			return -EINVAL;
4211 
4212 		cpu = flags >> 32;
4213 		if ((flags & BPF_F_CPU) && (cpu >= nr_cpu_ids || !cpu_possible(cpu)))
4214 			return -ERANGE;
4215 	}
4216 
4217 	return 0;
4218 }
4219 
4220 #endif /* _LINUX_BPF_H */
4221