xref: /linux/include/linux/bpf.h (revision 40c2096961b4e8f48d1fc17406a90c5a36ac0a8d)
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 
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 
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 
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 
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 
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 
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 
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 
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  */
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  */
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. */
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 
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 
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 
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 
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 
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 
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 
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 
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 
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
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 
726 static inline void bpf_arena_free_pages_non_sleepable(void *p__map, void *ptr__ign, u32 page_cnt)
727 {
728 }
729 
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
1122 bpf_ctx_record_field_size(struct bpf_insn_access_aux *aux, u32 size)
1123 {
1124 	aux->ctx_field_size = size;
1125 }
1126 
1127 static bool bpf_is_ldimm64(const struct bpf_insn *insn)
1128 {
1129 	return insn->code == (BPF_LD | BPF_IMM | BPF_DW);
1130 }
1131 
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
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
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 
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 
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
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 }
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 }
1618 static inline struct bpf_trampoline *bpf_trampoline_get(u64 key,
1619 							struct bpf_attach_target_info *tgt_info)
1620 {
1621 	return NULL;
1622 }
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
1628 static inline void bpf_dispatcher_change_prog(struct bpf_dispatcher *d,
1629 					      struct bpf_prog *from,
1630 					      struct bpf_prog *to) {}
1631 static inline bool is_bpf_image_address(unsigned long address)
1632 {
1633 	return false;
1634 }
1635 static inline bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
1636 {
1637 	return false;
1638 }
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 }
1644 static inline void bpf_trampoline_multi_detach(struct bpf_prog *prog,
1645 					       struct bpf_tracing_multi_link *link)
1646 {
1647 }
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 	/* Indexed by in_sleepable. */
1655 	bool called[2];
1656 	bool verified[2];
1657 };
1658 
1659 enum bpf_jit_poke_reason {
1660 	BPF_POKE_REASON_TAIL_CALL,
1661 };
1662 
1663 /* Descriptor of pokes pointing /into/ the JITed image. */
1664 struct bpf_jit_poke_descriptor {
1665 	void *tailcall_target;
1666 	void *tailcall_bypass;
1667 	void *bypass_addr;
1668 	void *aux;
1669 	union {
1670 		struct {
1671 			struct bpf_map *map;
1672 			u32 key;
1673 		} tail_call;
1674 	};
1675 	bool tailcall_target_stable;
1676 	u8 adj_off;
1677 	u16 reason;
1678 	u32 insn_idx;
1679 };
1680 
1681 /* reg_type info for ctx arguments */
1682 struct bpf_ctx_arg_aux {
1683 	u32 offset;
1684 	enum bpf_reg_type reg_type;
1685 	struct btf *btf;
1686 	u32 btf_id;
1687 	u32 ref_id;
1688 	bool refcounted;
1689 };
1690 
1691 struct btf_mod_pair {
1692 	struct btf *btf;
1693 	struct module *module;
1694 };
1695 
1696 struct bpf_kfunc_desc_tab;
1697 
1698 enum bpf_stream_id {
1699 	BPF_STDOUT = 1,
1700 	BPF_STDERR = 2,
1701 };
1702 
1703 struct bpf_stream_elem {
1704 	struct llist_node node;
1705 	int total_len;
1706 	int consumed_len;
1707 	char str[];
1708 };
1709 
1710 enum {
1711 	/* 100k bytes */
1712 	BPF_STREAM_MAX_CAPACITY = 100000ULL,
1713 };
1714 
1715 struct bpf_stream {
1716 	atomic_t capacity;
1717 	struct llist_head log;	/* list of in-flight stream elements in LIFO order */
1718 
1719 	struct mutex lock;  /* lock protecting backlog_{head,tail} */
1720 	struct llist_node *backlog_head; /* list of in-flight stream elements in FIFO order */
1721 	struct llist_node *backlog_tail; /* tail of the list above */
1722 };
1723 
1724 struct bpf_stream_stage {
1725 	struct llist_head log;
1726 	int len;
1727 };
1728 
1729 enum bpf_sig_verdict {
1730 	BPF_SIG_UNSIGNED = 0,
1731 	BPF_SIG_VERIFIED,
1732 };
1733 
1734 enum bpf_sig_keyring {
1735 	BPF_SIG_KEYRING_NONE = 0,
1736 	BPF_SIG_KEYRING_BUILTIN,
1737 	BPF_SIG_KEYRING_SECONDARY,
1738 	BPF_SIG_KEYRING_PLATFORM,
1739 	BPF_SIG_KEYRING_USER,
1740 };
1741 
1742 struct bpf_prog_aux {
1743 	atomic64_t refcnt;
1744 	u32 used_map_cnt;
1745 	u32 used_btf_cnt;
1746 	u32 max_ctx_offset;
1747 	u32 max_pkt_offset;
1748 	u32 max_tp_access;
1749 	u32 stack_depth;
1750 	u32 id;
1751 	u32 func_cnt; /* used by non-func prog as the number of func progs */
1752 	u32 real_func_cnt; /* includes hidden progs, only used for JIT and freeing progs */
1753 	u32 func_idx; /* 0 for non-func prog, the index in func array for func prog */
1754 	u32 attach_btf_id; /* in-kernel BTF type id to attach to */
1755 	u32 attach_st_ops_member_off;
1756 	u32 ctx_arg_info_size;
1757 	u32 max_rdonly_access;
1758 	u32 max_rdwr_access;
1759 	u32 subprog_start;
1760 	struct btf *attach_btf;
1761 	struct bpf_ctx_arg_aux *ctx_arg_info;
1762 	void __percpu *priv_stack_ptr;
1763 	struct mutex dst_mutex; /* protects dst_* pointers below, *after* prog becomes visible */
1764 	struct bpf_prog *dst_prog;
1765 	struct bpf_trampoline *dst_trampoline;
1766 	enum bpf_prog_type saved_dst_prog_type;
1767 	enum bpf_attach_type saved_dst_attach_type;
1768 	bool verifier_zext; /* Zero extensions has been inserted by verifier. */
1769 	bool dev_bound; /* Program is bound to the netdev. */
1770 	bool offload_requested; /* Program is bound and offloaded to the netdev. */
1771 	bool attach_btf_trace; /* true if attaching to BTF-enabled raw tp */
1772 	bool attach_tracing_prog; /* true if tracing another tracing program */
1773 	bool func_proto_unreliable;
1774 	bool tail_call_reachable;
1775 	bool xdp_has_frags;
1776 	bool exception_cb;
1777 	bool exception_boundary;
1778 	bool is_extended; /* true if extended by freplace program */
1779 	bool jits_use_priv_stack;
1780 	bool priv_stack_requested;
1781 	bool changes_pkt_data;
1782 	bool might_sleep;
1783 	bool kprobe_write_ctx;
1784 	struct {
1785 		s32 keyring_serial;
1786 		u8 keyring_type;
1787 		u8 verdict;
1788 	} sig;
1789 	u64 prog_array_member_cnt; /* counts how many times as member of prog_array */
1790 	struct mutex ext_mutex; /* mutex for is_extended and prog_array_member_cnt */
1791 	struct bpf_arena *arena;
1792 	void (*recursion_detected)(struct bpf_prog *prog); /* callback if recursion is detected */
1793 	/* BTF_KIND_FUNC_PROTO for valid attach_btf_id */
1794 	const struct btf_type *attach_func_proto;
1795 	/* function name for valid attach_btf_id */
1796 	const char *attach_func_name;
1797 	struct bpf_prog **func;
1798 	struct bpf_prog_aux *main_prog_aux;
1799 	void *jit_data; /* JIT specific data. arch dependent */
1800 	struct bpf_jit_poke_descriptor *poke_tab;
1801 	struct bpf_kfunc_desc_tab *kfunc_tab;
1802 	struct bpf_kfunc_btf_tab *kfunc_btf_tab;
1803 	u32 size_poke_tab;
1804 #ifdef CONFIG_FINEIBT
1805 	struct bpf_ksym ksym_prefix;
1806 #endif
1807 	struct bpf_ksym ksym;
1808 	const struct bpf_prog_ops *ops;
1809 	const struct bpf_struct_ops *st_ops;
1810 	struct bpf_map **used_maps;
1811 	struct mutex used_maps_mutex; /* mutex for used_maps and used_map_cnt */
1812 	struct btf_mod_pair *used_btfs;
1813 	struct bpf_prog *prog;
1814 	struct user_struct *user;
1815 	u64 load_time; /* ns since boottime */
1816 	u32 verified_insns;
1817 	int cgroup_atype; /* enum cgroup_bpf_attach_type */
1818 	struct bpf_map *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE];
1819 	char name[BPF_OBJ_NAME_LEN];
1820 	u64 (*bpf_exception_cb)(u64 cookie, u64 sp, u64 bp, u64, u64);
1821 	u16 stack_arg_sp_adjust;
1822 #ifdef CONFIG_SECURITY
1823 	void *security;
1824 #endif
1825 	struct bpf_token *token;
1826 	struct bpf_prog_offload *offload;
1827 	struct btf *btf;
1828 	struct bpf_func_info *func_info;
1829 	struct bpf_func_info_aux *func_info_aux;
1830 	/* bpf_line_info loaded from userspace.  linfo->insn_off
1831 	 * has the xlated insn offset.
1832 	 * Both the main and sub prog share the same linfo.
1833 	 * The subprog can access its first linfo by
1834 	 * using the linfo_idx.
1835 	 */
1836 	struct bpf_line_info *linfo;
1837 	/* jited_linfo is the jited addr of the linfo.  It has a
1838 	 * one to one mapping to linfo:
1839 	 * jited_linfo[i] is the jited addr for the linfo[i]->insn_off.
1840 	 * Both the main and sub prog share the same jited_linfo.
1841 	 * The subprog can access its first jited_linfo by
1842 	 * using the linfo_idx.
1843 	 */
1844 	void **jited_linfo;
1845 	u32 func_info_cnt;
1846 	u32 nr_linfo;
1847 	/* subprog can use linfo_idx to access its first linfo and
1848 	 * jited_linfo.
1849 	 * main prog always has linfo_idx == 0
1850 	 */
1851 	u32 linfo_idx;
1852 	struct module *mod;
1853 	u32 num_exentries;
1854 	struct exception_table_entry *extable;
1855 	union {
1856 		struct work_struct work;
1857 		struct rcu_head	rcu;
1858 	};
1859 	struct bpf_stream stream[2];
1860 	struct mutex st_ops_assoc_mutex;
1861 	struct bpf_map __rcu *st_ops_assoc;
1862 };
1863 
1864 #define BPF_NR_CONTEXTS        4       /* normal, softirq, hardirq, NMI */
1865 
1866 struct bpf_prog {
1867 	u16			pages;		/* Number of allocated pages */
1868 	u32			jited:1,	/* Is our filter JIT'ed? */
1869 				jit_requested:1,/* archs need to JIT the prog */
1870 				jit_required:1,	/* program strictly requires JIT compiler */
1871 				gpl_compatible:1, /* Is filter GPL compatible? */
1872 				cb_access:1,	/* Is control block accessed? */
1873 				dst_needed:1,	/* Do we need dst entry? */
1874 				blinding_requested:1, /* needs constant blinding */
1875 				blinded:1,	/* Was blinded */
1876 				is_func:1,	/* program is a bpf function */
1877 				kprobe_override:1, /* Do we override a kprobe? */
1878 				has_callchain_buf:1, /* callchain buffer allocated? */
1879 				enforce_expected_attach_type:1, /* Enforce expected_attach_type checking at attach time */
1880 				call_get_stack:1, /* Do we call bpf_get_stack() or bpf_get_stackid() */
1881 				call_get_func_ip:1, /* Do we call get_func_ip() */
1882 				call_session_cookie:1, /* Do we call bpf_session_cookie() */
1883 				tstamp_type_access:1, /* Accessed __sk_buff->tstamp_type */
1884 				sleepable:1;	/* BPF program is sleepable */
1885 	enum bpf_prog_type	type;		/* Type of BPF program */
1886 	enum bpf_attach_type	expected_attach_type; /* For some prog types */
1887 	u32			len;		/* Number of filter blocks */
1888 	u32			jited_len;	/* Size of jited insns in bytes */
1889 	union {
1890 		u8 digest[SHA256_DIGEST_SIZE];
1891 		u8 tag[BPF_TAG_SIZE];
1892 	};
1893 	struct bpf_prog_stats __percpu *stats;
1894 	u8 __percpu		*active;	/* u8[BPF_NR_CONTEXTS] for recursion protection */
1895 	unsigned int		(*bpf_func)(const void *ctx,
1896 					    const struct bpf_insn *insn);
1897 	struct bpf_prog_aux	*aux;		/* Auxiliary fields */
1898 	struct sock_fprog_kern	*orig_prog;	/* Original BPF program */
1899 	/* Instructions for interpreter */
1900 	union {
1901 		DECLARE_FLEX_ARRAY(struct sock_filter, insns);
1902 		DECLARE_FLEX_ARRAY(struct bpf_insn, insnsi);
1903 	};
1904 };
1905 
1906 struct bpf_array_aux {
1907 	/* Programs with direct jumps into programs part of this array. */
1908 	struct list_head poke_progs;
1909 	struct bpf_map *map;
1910 	struct mutex poke_mutex;
1911 	struct work_struct work;
1912 };
1913 
1914 struct bpf_link {
1915 	atomic64_t refcnt;
1916 	u32 id;
1917 	enum bpf_link_type type;
1918 	const struct bpf_link_ops *ops;
1919 	struct bpf_prog *prog;
1920 
1921 	u32 flags;
1922 	enum bpf_attach_type attach_type;
1923 
1924 	/* rcu is used before freeing, work can be used to schedule that
1925 	 * RCU-based freeing before that, so they never overlap
1926 	 */
1927 	union {
1928 		struct rcu_head rcu;
1929 		struct work_struct work;
1930 	};
1931 	/* whether BPF link itself has "sleepable" semantics, which can differ
1932 	 * from underlying BPF program having a "sleepable" semantics, as BPF
1933 	 * link's semantics is determined by target attach hook
1934 	 */
1935 	bool sleepable;
1936 };
1937 
1938 struct bpf_link_ops {
1939 	void (*release)(struct bpf_link *link);
1940 	/* deallocate link resources callback, called without RCU grace period
1941 	 * waiting
1942 	 */
1943 	void (*dealloc)(struct bpf_link *link);
1944 	/* deallocate link resources callback, called after RCU grace period;
1945 	 * if either the underlying BPF program is sleepable or BPF link's
1946 	 * target hook is sleepable, we'll go through tasks trace RCU GP and
1947 	 * then "classic" RCU GP; this need for chaining tasks trace and
1948 	 * classic RCU GPs is designated by setting bpf_link->sleepable flag
1949 	 *
1950 	 * For non-sleepable tracepoint links we go through SRCU gp instead,
1951 	 * since RCU is not used in that case. Sleepable tracepoints still
1952 	 * follow the scheme above.
1953 	 */
1954 	void (*dealloc_deferred)(struct bpf_link *link);
1955 	int (*detach)(struct bpf_link *link);
1956 	int (*update_prog)(struct bpf_link *link, struct bpf_prog *new_prog,
1957 			   struct bpf_prog *old_prog);
1958 	void (*show_fdinfo)(const struct bpf_link *link, struct seq_file *seq);
1959 	int (*fill_link_info)(const struct bpf_link *link,
1960 			      struct bpf_link_info *info);
1961 	int (*update_map)(struct bpf_link *link, struct bpf_map *new_map,
1962 			  struct bpf_map *old_map);
1963 	__poll_t (*poll)(struct file *file, struct poll_table_struct *pts);
1964 };
1965 
1966 struct bpf_tramp_node {
1967 	struct bpf_link *link;
1968 	struct hlist_node tramp_hlist;
1969 	u64 cookie;
1970 };
1971 
1972 struct bpf_tramp_link {
1973 	struct bpf_link link;
1974 	struct bpf_tramp_node node;
1975 };
1976 
1977 struct bpf_shim_tramp_link {
1978 	struct bpf_tramp_link link;
1979 	struct bpf_trampoline *trampoline;
1980 };
1981 
1982 struct bpf_tracing_link {
1983 	struct bpf_tramp_link link;
1984 	struct bpf_tramp_node fexit;
1985 	struct bpf_trampoline *trampoline;
1986 	struct bpf_prog *tgt_prog;
1987 };
1988 
1989 struct bpf_tracing_multi_node {
1990 	struct bpf_tramp_node node;
1991 	struct bpf_trampoline *trampoline;
1992 	struct ftrace_func_entry entry;
1993 };
1994 
1995 struct bpf_tracing_multi_data {
1996 	struct ftrace_hash *unreg;
1997 	struct ftrace_hash *modify;
1998 	struct ftrace_hash *reg;
1999 	struct ftrace_func_entry *entry;
2000 };
2001 
2002 struct bpf_tracing_multi_link {
2003 	struct bpf_link link;
2004 	struct bpf_tracing_multi_data data;
2005 	u64 *cookies;
2006 	struct bpf_tramp_node *fexits;
2007 	int nodes_cnt;
2008 	struct bpf_tracing_multi_node nodes[] __counted_by(nodes_cnt);
2009 };
2010 
2011 struct bpf_raw_tp_link {
2012 	struct bpf_link link;
2013 	struct bpf_raw_event_map *btp;
2014 	u64 cookie;
2015 };
2016 
2017 struct bpf_link_primer {
2018 	struct bpf_link *link;
2019 	struct file *file;
2020 	int fd;
2021 	u32 id;
2022 };
2023 
2024 struct bpf_mount_opts {
2025 	kuid_t uid;
2026 	kgid_t gid;
2027 	umode_t mode;
2028 
2029 	/* BPF token-related delegation options */
2030 	u64 delegate_cmds;
2031 	u64 delegate_maps;
2032 	u64 delegate_progs;
2033 	u64 delegate_attachs;
2034 
2035 	struct simple_xattr_cache xa_cache;
2036 };
2037 
2038 struct bpf_token {
2039 	struct work_struct work;
2040 	atomic64_t refcnt;
2041 	struct user_namespace *userns;
2042 	u64 allowed_cmds;
2043 	u64 allowed_maps;
2044 	u64 allowed_progs;
2045 	u64 allowed_attachs;
2046 #ifdef CONFIG_SECURITY
2047 	void *security;
2048 #endif
2049 };
2050 
2051 struct bpf_struct_ops_value;
2052 struct btf_member;
2053 
2054 #define BPF_STRUCT_OPS_MAX_NR_MEMBERS 64
2055 /**
2056  * struct bpf_struct_ops - A structure of callbacks allowing a subsystem to
2057  *			   define a BPF_MAP_TYPE_STRUCT_OPS map type composed
2058  *			   of BPF_PROG_TYPE_STRUCT_OPS progs.
2059  * @verifier_ops: A structure of callbacks that are invoked by the verifier
2060  *		  when determining whether the struct_ops progs in the
2061  *		  struct_ops map are valid.
2062  * @init: A callback that is invoked a single time, and before any other
2063  *	  callback, to initialize the structure. A nonzero return value means
2064  *	  the subsystem could not be initialized.
2065  * @check_member: When defined, a callback invoked by the verifier to allow
2066  *		  the subsystem to determine if an entry in the struct_ops map
2067  *		  is valid. A nonzero return value means that the map is
2068  *		  invalid and should be rejected by the verifier.
2069  * @init_member: A callback that is invoked for each member of the struct_ops
2070  *		 map to allow the subsystem to initialize the member. A nonzero
2071  *		 value means the member could not be initialized. This callback
2072  *		 is exclusive with the @type, @type_id, @value_type, and
2073  *		 @value_id fields.
2074  * @reg: A callback that is invoked when the struct_ops map has been
2075  *	 initialized and is being attached to. Zero means the struct_ops map
2076  *	 has been successfully registered and is live. A nonzero return value
2077  *	 means the struct_ops map could not be registered.
2078  * @unreg: A callback that is invoked when the struct_ops map should be
2079  *	   unregistered.
2080  * @update: A callback that is invoked when the live struct_ops map is being
2081  *	    updated to contain new values. This callback is only invoked when
2082  *	    the struct_ops map is loaded with BPF_F_LINK. If not defined, the
2083  *	    it is assumed that the struct_ops map cannot be updated.
2084  * @validate: A callback that is invoked after all of the members have been
2085  *	      initialized. This callback should perform static checks on the
2086  *	      map, meaning that it should either fail or succeed
2087  *	      deterministically. A struct_ops map that has been validated may
2088  *	      not necessarily succeed in being registered if the call to @reg
2089  *	      fails. For example, a valid struct_ops map may be loaded, but
2090  *	      then fail to be registered due to there being another active
2091  *	      struct_ops map on the system in the subsystem already. For this
2092  *	      reason, if this callback is not defined, the check is skipped as
2093  *	      the struct_ops map will have final verification performed in
2094  *	      @reg.
2095  * @cfi_stubs: Pointer to a structure of stub functions for CFI. These stubs
2096  *	       provide the correct Control Flow Integrity hashes for the
2097  *	       trampolines generated by BPF struct_ops.
2098  * @owner: The module that owns this struct_ops. Used for module reference
2099  *	   counting to ensure the module providing the struct_ops cannot be
2100  *	   unloaded while in use.
2101  * @name: The name of the struct bpf_struct_ops object.
2102  * @func_models: Func models
2103  */
2104 struct bpf_struct_ops {
2105 	const struct bpf_verifier_ops *verifier_ops;
2106 	int (*init)(struct btf *btf);
2107 	int (*check_member)(const struct btf_type *t,
2108 			    const struct btf_member *member,
2109 			    const struct bpf_prog *prog);
2110 	int (*init_member)(const struct btf_type *t,
2111 			   const struct btf_member *member,
2112 			   void *kdata, const void *udata);
2113 	int (*reg)(void *kdata, struct bpf_link *link);
2114 	void (*unreg)(void *kdata, struct bpf_link *link);
2115 	int (*update)(void *kdata, void *old_kdata, struct bpf_link *link);
2116 	int (*validate)(void *kdata);
2117 	void *cfi_stubs;
2118 	struct module *owner;
2119 	const char *name;
2120 	struct btf_func_model func_models[BPF_STRUCT_OPS_MAX_NR_MEMBERS];
2121 };
2122 
2123 /* Every member of a struct_ops type has an instance even a member is not
2124  * an operator (function pointer). The "info" field will be assigned to
2125  * prog->aux->ctx_arg_info of BPF struct_ops programs to provide the
2126  * argument information required by the verifier to verify the program.
2127  *
2128  * btf_ctx_access() will lookup prog->aux->ctx_arg_info to find the
2129  * corresponding entry for an given argument.
2130  */
2131 struct bpf_struct_ops_arg_info {
2132 	struct bpf_ctx_arg_aux *info;
2133 	u32 cnt;
2134 };
2135 
2136 struct bpf_struct_ops_desc {
2137 	struct bpf_struct_ops *st_ops;
2138 
2139 	const struct btf_type *type;
2140 	const struct btf_type *value_type;
2141 	u32 type_id;
2142 	u32 value_id;
2143 
2144 	/* Collection of argument information for each member */
2145 	struct bpf_struct_ops_arg_info *arg_info;
2146 };
2147 
2148 enum bpf_struct_ops_state {
2149 	BPF_STRUCT_OPS_STATE_INIT,
2150 	BPF_STRUCT_OPS_STATE_INUSE,
2151 	BPF_STRUCT_OPS_STATE_TOBEFREE,
2152 	BPF_STRUCT_OPS_STATE_READY,
2153 };
2154 
2155 struct bpf_struct_ops_common_value {
2156 	refcount_t refcnt;
2157 	enum bpf_struct_ops_state state;
2158 };
2159 
2160 static inline bool bpf_prog_get_recursion_context(struct bpf_prog *prog)
2161 {
2162 #ifdef CONFIG_ARM64
2163 	u8 rctx = interrupt_context_level();
2164 	u8 *active = this_cpu_ptr(prog->active);
2165 	u32 val;
2166 
2167 	preempt_disable();
2168 	active[rctx]++;
2169 	val = le32_to_cpu(*(__le32 *)active);
2170 	preempt_enable();
2171 	if (val != BIT(rctx * 8))
2172 		return false;
2173 
2174 	return true;
2175 #else
2176 	return this_cpu_inc_return(*(int __percpu *)(prog->active)) == 1;
2177 #endif
2178 }
2179 
2180 static inline void bpf_prog_put_recursion_context(struct bpf_prog *prog)
2181 {
2182 #ifdef CONFIG_ARM64
2183 	u8 rctx = interrupt_context_level();
2184 	u8 *active = this_cpu_ptr(prog->active);
2185 
2186 	preempt_disable();
2187 	active[rctx]--;
2188 	preempt_enable();
2189 #else
2190 	this_cpu_dec(*(int __percpu *)(prog->active));
2191 #endif
2192 }
2193 
2194 static inline bool is_tracing_multi(enum bpf_attach_type type)
2195 {
2196 	return type == BPF_TRACE_FENTRY_MULTI || type == BPF_TRACE_FEXIT_MULTI ||
2197 	       type == BPF_TRACE_FSESSION_MULTI;
2198 }
2199 
2200 static inline bool is_struct_ops_tramp(const struct bpf_tramp_nodes *fentry_nodes)
2201 {
2202 	return fentry_nodes->nr_nodes == 1 &&
2203 	       fentry_nodes->nodes[0]->link->type == BPF_LINK_TYPE_STRUCT_OPS;
2204 }
2205 
2206 #if defined(CONFIG_BPF_JIT) && defined(CONFIG_BPF_SYSCALL)
2207 /* This macro helps developer to register a struct_ops type and generate
2208  * type information correctly. Developers should use this macro to register
2209  * a struct_ops type instead of calling __register_bpf_struct_ops() directly.
2210  */
2211 #define register_bpf_struct_ops(st_ops, type)				\
2212 	({								\
2213 		struct bpf_struct_ops_##type {				\
2214 			struct bpf_struct_ops_common_value common;	\
2215 			struct type data ____cacheline_aligned_in_smp;	\
2216 		};							\
2217 		BTF_TYPE_EMIT(struct bpf_struct_ops_##type);		\
2218 		__register_bpf_struct_ops(st_ops);			\
2219 	})
2220 #define BPF_MODULE_OWNER ((void *)((0xeB9FUL << 2) + POISON_POINTER_DELTA))
2221 bool bpf_struct_ops_get(const void *kdata);
2222 void bpf_struct_ops_put(const void *kdata);
2223 int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff);
2224 int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map, void *key,
2225 				       void *value);
2226 int bpf_struct_ops_prepare_trampoline(struct bpf_tramp_nodes *tnodes,
2227 				      struct bpf_tramp_node *node,
2228 				      const struct btf_func_model *model,
2229 				      void *stub_func,
2230 				      void **image, u32 *image_off,
2231 				      bool allow_alloc);
2232 void bpf_struct_ops_image_free(void *image);
2233 static inline bool bpf_try_module_get(const void *data, struct module *owner)
2234 {
2235 	if (owner == BPF_MODULE_OWNER)
2236 		return bpf_struct_ops_get(data);
2237 	else
2238 		return try_module_get(owner);
2239 }
2240 static inline void bpf_module_put(const void *data, struct module *owner)
2241 {
2242 	if (owner == BPF_MODULE_OWNER)
2243 		bpf_struct_ops_put(data);
2244 	else
2245 		module_put(owner);
2246 }
2247 int bpf_struct_ops_link_create(union bpf_attr *attr);
2248 int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map);
2249 void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog);
2250 void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux);
2251 u32 bpf_struct_ops_id(const void *kdata);
2252 int bpf_struct_ops_for_each_prog(const void *kdata,
2253 				 int (*cb)(struct bpf_prog *prog, void *data),
2254 				 void *data);
2255 
2256 #ifdef CONFIG_NET
2257 /* Define it here to avoid the use of forward declaration */
2258 struct bpf_dummy_ops_state {
2259 	int val;
2260 };
2261 
2262 struct bpf_dummy_ops {
2263 	int (*test_1)(struct bpf_dummy_ops_state *cb);
2264 	int (*test_2)(struct bpf_dummy_ops_state *cb, int a1, unsigned short a2,
2265 		      char a3, unsigned long a4);
2266 	int (*test_sleepable)(struct bpf_dummy_ops_state *cb);
2267 };
2268 
2269 int bpf_struct_ops_test_run(struct bpf_prog *prog, const union bpf_attr *kattr,
2270 			    union bpf_attr __user *uattr);
2271 #endif
2272 int bpf_struct_ops_desc_init(struct bpf_struct_ops_desc *st_ops_desc,
2273 			     struct btf *btf,
2274 			     struct bpf_verifier_log *log);
2275 void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map);
2276 void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc);
2277 #else
2278 #define register_bpf_struct_ops(st_ops, type) ({ (void *)(st_ops); 0; })
2279 static inline bool bpf_try_module_get(const void *data, struct module *owner)
2280 {
2281 	return try_module_get(owner);
2282 }
2283 static inline void bpf_module_put(const void *data, struct module *owner)
2284 {
2285 	module_put(owner);
2286 }
2287 static inline int bpf_struct_ops_supported(const struct bpf_struct_ops *st_ops, u32 moff)
2288 {
2289 	return -ENOTSUPP;
2290 }
2291 static inline int bpf_struct_ops_map_sys_lookup_elem(struct bpf_map *map,
2292 						     void *key,
2293 						     void *value)
2294 {
2295 	return -EINVAL;
2296 }
2297 static inline int bpf_struct_ops_link_create(union bpf_attr *attr)
2298 {
2299 	return -EOPNOTSUPP;
2300 }
2301 static inline int bpf_prog_assoc_struct_ops(struct bpf_prog *prog, struct bpf_map *map)
2302 {
2303 	return -EOPNOTSUPP;
2304 }
2305 static inline void bpf_prog_disassoc_struct_ops(struct bpf_prog *prog)
2306 {
2307 }
2308 static inline void *bpf_prog_get_assoc_struct_ops(const struct bpf_prog_aux *aux)
2309 {
2310 	return NULL;
2311 }
2312 static inline void bpf_map_struct_ops_info_fill(struct bpf_map_info *info, struct bpf_map *map)
2313 {
2314 }
2315 
2316 static inline void bpf_struct_ops_desc_release(struct bpf_struct_ops_desc *st_ops_desc)
2317 {
2318 }
2319 
2320 #endif
2321 
2322 static inline int bpf_fsession_cnt(struct bpf_tramp_nodes *nodes)
2323 {
2324 	struct bpf_tramp_nodes fentries = nodes[BPF_TRAMP_FENTRY];
2325 	int cnt = 0;
2326 
2327 	for (int i = 0; i < nodes[BPF_TRAMP_FENTRY].nr_nodes; i++) {
2328 		if (fentries.nodes[i]->link->prog->expected_attach_type == BPF_TRACE_FSESSION)
2329 			cnt++;
2330 		if (fentries.nodes[i]->link->prog->expected_attach_type == BPF_TRACE_FSESSION_MULTI)
2331 			cnt++;
2332 	}
2333 
2334 	return cnt;
2335 }
2336 
2337 static inline bool bpf_prog_calls_session_cookie(struct bpf_tramp_node *node)
2338 {
2339 	return node->link->prog->call_session_cookie;
2340 }
2341 
2342 static inline int bpf_fsession_cookie_cnt(struct bpf_tramp_nodes *nodes)
2343 {
2344 	struct bpf_tramp_nodes fentries = nodes[BPF_TRAMP_FENTRY];
2345 	int cnt = 0;
2346 
2347 	for (int i = 0; i < nodes[BPF_TRAMP_FENTRY].nr_nodes; i++) {
2348 		if (bpf_prog_calls_session_cookie(fentries.nodes[i]))
2349 			cnt++;
2350 	}
2351 
2352 	return cnt;
2353 }
2354 
2355 int bpf_prog_ctx_arg_info_init(struct bpf_prog *prog,
2356 			       const struct bpf_ctx_arg_aux *info, u32 cnt);
2357 
2358 #if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_BPF_LSM)
2359 int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
2360 				    int cgroup_atype,
2361 				    enum bpf_attach_type attach_type);
2362 void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog);
2363 #else
2364 static inline int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
2365 						  int cgroup_atype,
2366 						  enum bpf_attach_type attach_type)
2367 {
2368 	return -EOPNOTSUPP;
2369 }
2370 static inline void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog)
2371 {
2372 }
2373 #endif
2374 
2375 struct bpf_array {
2376 	struct bpf_map map;
2377 	u32 elem_size;
2378 	u32 index_mask;
2379 	struct bpf_array_aux *aux;
2380 	union {
2381 		DECLARE_FLEX_ARRAY(char, value) __aligned(8);
2382 		DECLARE_FLEX_ARRAY(void *, ptrs) __aligned(8);
2383 		DECLARE_FLEX_ARRAY(void __percpu *, pptrs) __aligned(8);
2384 	};
2385 };
2386 
2387 /*
2388  * The bpf_array_get_next_key() function may be used for all array-like
2389  * maps, i.e., maps with u32 keys with range [0 ,..., max_entries)
2390  */
2391 int bpf_array_get_next_key(struct bpf_map *map, void *key, void *next_key);
2392 
2393 #define BPF_COMPLEXITY_LIMIT_INSNS      1000000 /* yes. 1M insns */
2394 #define MAX_TAIL_CALL_CNT 33
2395 
2396 /* Maximum number of loops for bpf_loop and bpf_iter_num.
2397  * It's enum to expose it (and thus make it discoverable) through BTF.
2398  */
2399 enum {
2400 	BPF_MAX_LOOPS = 8 * 1024 * 1024,
2401 	BPF_MAX_TIMED_LOOPS = 0xffff,
2402 };
2403 
2404 #define BPF_F_ACCESS_MASK	(BPF_F_RDONLY |		\
2405 				 BPF_F_RDONLY_PROG |	\
2406 				 BPF_F_WRONLY |		\
2407 				 BPF_F_WRONLY_PROG)
2408 
2409 #define BPF_MAP_CAN_READ	BIT(0)
2410 #define BPF_MAP_CAN_WRITE	BIT(1)
2411 
2412 /* Maximum number of user-producer ring buffer samples that can be drained in
2413  * a call to bpf_user_ringbuf_drain().
2414  */
2415 #define BPF_MAX_USER_RINGBUF_SAMPLES (128 * 1024)
2416 
2417 static inline u32 bpf_map_flags_to_cap(struct bpf_map *map)
2418 {
2419 	u32 access_flags = map->map_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG);
2420 
2421 	/* Combination of BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG is
2422 	 * not possible.
2423 	 */
2424 	if (access_flags & BPF_F_RDONLY_PROG)
2425 		return BPF_MAP_CAN_READ;
2426 	else if (access_flags & BPF_F_WRONLY_PROG)
2427 		return BPF_MAP_CAN_WRITE;
2428 	else
2429 		return BPF_MAP_CAN_READ | BPF_MAP_CAN_WRITE;
2430 }
2431 
2432 static inline bool bpf_map_flags_access_ok(u32 access_flags)
2433 {
2434 	return (access_flags & (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG)) !=
2435 	       (BPF_F_RDONLY_PROG | BPF_F_WRONLY_PROG);
2436 }
2437 
2438 static inline struct bpf_map_owner *bpf_map_owner_alloc(struct bpf_map *map)
2439 {
2440 	return kzalloc_obj(*map->owner, GFP_ATOMIC);
2441 }
2442 
2443 static inline void bpf_map_owner_free(struct bpf_map *map)
2444 {
2445 	kfree(map->owner);
2446 }
2447 
2448 struct bpf_event_entry {
2449 	struct perf_event *event;
2450 	struct file *perf_file;
2451 	struct file *map_file;
2452 	struct rcu_head rcu;
2453 };
2454 
2455 static inline bool map_type_contains_progs(struct bpf_map *map)
2456 {
2457 	return map->map_type == BPF_MAP_TYPE_PROG_ARRAY ||
2458 	       map->map_type == BPF_MAP_TYPE_DEVMAP ||
2459 	       map->map_type == BPF_MAP_TYPE_CPUMAP;
2460 }
2461 
2462 bool bpf_prog_map_compatible(struct bpf_map *map, const struct bpf_prog *fp);
2463 int bpf_prog_calc_tag(struct bpf_prog *fp);
2464 
2465 const struct bpf_func_proto *bpf_get_trace_printk_proto(void);
2466 const struct bpf_func_proto *bpf_get_trace_vprintk_proto(void);
2467 
2468 const struct bpf_func_proto *bpf_get_perf_event_read_value_proto(void);
2469 
2470 typedef unsigned long (*bpf_ctx_copy_t)(void *dst, const void *src,
2471 					unsigned long off, unsigned long len);
2472 typedef u32 (*bpf_convert_ctx_access_t)(enum bpf_access_type type,
2473 					const struct bpf_insn *src,
2474 					struct bpf_insn *dst,
2475 					struct bpf_prog *prog,
2476 					u32 *target_size);
2477 
2478 u64 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
2479 		     void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy);
2480 
2481 /* an array of programs to be executed under rcu_lock.
2482  *
2483  * Typical usage:
2484  * ret = bpf_prog_run_array(rcu_dereference(&bpf_prog_array), ctx, bpf_prog_run);
2485  *
2486  * the structure returned by bpf_prog_array_alloc() should be populated
2487  * with program pointers and the last pointer must be NULL.
2488  * The user has to keep refcnt on the program and make sure the program
2489  * is removed from the array before bpf_prog_put().
2490  * The 'struct bpf_prog_array *' should only be replaced with xchg()
2491  * since other cpus are walking the array of pointers in parallel.
2492  */
2493 struct bpf_prog_array_item {
2494 	struct bpf_prog *prog;
2495 	union {
2496 		struct bpf_cgroup_storage *cgroup_storage[MAX_BPF_CGROUP_STORAGE_TYPE];
2497 		u64 bpf_cookie;
2498 	};
2499 };
2500 
2501 struct bpf_prog_array {
2502 	struct rcu_head rcu;
2503 	struct bpf_prog_array_item items[];
2504 };
2505 
2506 /* to avoid allocating empty bpf_prog_array for cgroups that
2507  * don't have bpf program attached use one global 'bpf_empty_prog_array'
2508  * It will not be modified the caller of bpf_prog_array_alloc()
2509  * (since caller requested prog_cnt == 0)
2510  * that pointer should be 'freed' by bpf_prog_array_free()
2511  */
2512 extern struct bpf_prog_array bpf_empty_prog_array;
2513 
2514 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags);
2515 void bpf_prog_array_free(struct bpf_prog_array *progs);
2516 /* Use when traversal over the bpf_prog_array uses tasks_trace rcu */
2517 void bpf_prog_array_free_sleepable(struct bpf_prog_array *progs);
2518 int bpf_prog_array_length(struct bpf_prog_array *progs);
2519 bool bpf_prog_array_is_empty(struct bpf_prog_array *array);
2520 int bpf_prog_array_copy_to_user(struct bpf_prog_array *progs,
2521 				__u32 __user *prog_ids, u32 cnt);
2522 
2523 void bpf_prog_array_delete_safe(struct bpf_prog_array *progs,
2524 				struct bpf_prog *old_prog);
2525 int bpf_prog_array_delete_safe_at(struct bpf_prog_array *array, int index);
2526 int bpf_prog_array_update_at(struct bpf_prog_array *array, int index,
2527 			     struct bpf_prog *prog);
2528 int bpf_prog_array_copy_info(struct bpf_prog_array *array,
2529 			     u32 *prog_ids, u32 request_cnt,
2530 			     u32 *prog_cnt);
2531 int bpf_prog_array_copy(struct bpf_prog_array *old_array,
2532 			struct bpf_prog *exclude_prog,
2533 			struct bpf_prog *include_prog,
2534 			u64 bpf_cookie,
2535 			struct bpf_prog_array **new_array);
2536 
2537 struct bpf_run_ctx {};
2538 
2539 struct bpf_cg_run_ctx {
2540 	struct bpf_run_ctx run_ctx;
2541 	const struct bpf_prog_array_item *prog_item;
2542 	int retval;
2543 };
2544 
2545 struct bpf_trace_run_ctx {
2546 	struct bpf_run_ctx run_ctx;
2547 	u64 bpf_cookie;
2548 	bool is_uprobe;
2549 };
2550 
2551 struct bpf_tramp_run_ctx {
2552 	struct bpf_run_ctx run_ctx;
2553 	u64 bpf_cookie;
2554 	struct bpf_run_ctx *saved_run_ctx;
2555 };
2556 
2557 static inline struct bpf_run_ctx *bpf_set_run_ctx(struct bpf_run_ctx *new_ctx)
2558 {
2559 	struct bpf_run_ctx *old_ctx = NULL;
2560 
2561 #ifdef CONFIG_BPF_SYSCALL
2562 	old_ctx = current->bpf_ctx;
2563 	current->bpf_ctx = new_ctx;
2564 #endif
2565 	return old_ctx;
2566 }
2567 
2568 static inline void bpf_reset_run_ctx(struct bpf_run_ctx *old_ctx)
2569 {
2570 #ifdef CONFIG_BPF_SYSCALL
2571 	current->bpf_ctx = old_ctx;
2572 #endif
2573 }
2574 
2575 /* BPF program asks to bypass CAP_NET_BIND_SERVICE in bind. */
2576 #define BPF_RET_BIND_NO_CAP_NET_BIND_SERVICE			(1 << 0)
2577 /* BPF program asks to set CN on the packet. */
2578 #define BPF_RET_SET_CN						(1 << 0)
2579 
2580 typedef u32 (*bpf_prog_run_fn)(const struct bpf_prog *prog, const void *ctx);
2581 
2582 static __always_inline u32
2583 bpf_prog_run_array(const struct bpf_prog_array *array,
2584 		   const void *ctx, bpf_prog_run_fn run_prog)
2585 {
2586 	const struct bpf_prog_array_item *item;
2587 	const struct bpf_prog *prog;
2588 	struct bpf_run_ctx *old_run_ctx;
2589 	struct bpf_trace_run_ctx run_ctx;
2590 	u32 ret = 1;
2591 
2592 	RCU_LOCKDEP_WARN(!rcu_read_lock_held(), "no rcu lock held");
2593 
2594 	if (unlikely(!array))
2595 		return ret;
2596 
2597 	run_ctx.is_uprobe = false;
2598 
2599 	migrate_disable();
2600 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2601 	item = &array->items[0];
2602 	while ((prog = READ_ONCE(item->prog))) {
2603 		run_ctx.bpf_cookie = item->bpf_cookie;
2604 		ret &= run_prog(prog, ctx);
2605 		item++;
2606 	}
2607 	bpf_reset_run_ctx(old_run_ctx);
2608 	migrate_enable();
2609 	return ret;
2610 }
2611 
2612 /* Notes on RCU design for bpf_prog_arrays containing sleepable programs:
2613  *
2614  * We use the tasks_trace rcu flavor read section to protect the bpf_prog_array
2615  * overall. As a result, we must use the bpf_prog_array_free_sleepable
2616  * in order to use the tasks_trace rcu grace period.
2617  *
2618  * When a non-sleepable program is inside the array, we take the rcu read
2619  * section and disable preemption for that program alone, so it can access
2620  * rcu-protected dynamically sized maps.
2621  */
2622 static __always_inline u32
2623 bpf_prog_run_array_uprobe(const struct bpf_prog_array *array,
2624 			  const void *ctx, bpf_prog_run_fn run_prog)
2625 {
2626 	const struct bpf_prog_array_item *item;
2627 	const struct bpf_prog *prog;
2628 	struct bpf_run_ctx *old_run_ctx;
2629 	struct bpf_trace_run_ctx run_ctx;
2630 	u32 ret = 1;
2631 
2632 	might_fault();
2633 	RCU_LOCKDEP_WARN(!rcu_read_lock_trace_held(), "no rcu lock held");
2634 
2635 	if (unlikely(!array))
2636 		return ret;
2637 
2638 	migrate_disable();
2639 
2640 	run_ctx.is_uprobe = true;
2641 
2642 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
2643 	item = &array->items[0];
2644 	while ((prog = READ_ONCE(item->prog))) {
2645 		if (!prog->sleepable)
2646 			rcu_read_lock();
2647 
2648 		run_ctx.bpf_cookie = item->bpf_cookie;
2649 		ret &= run_prog(prog, ctx);
2650 		item++;
2651 
2652 		if (!prog->sleepable)
2653 			rcu_read_unlock();
2654 	}
2655 	bpf_reset_run_ctx(old_run_ctx);
2656 	migrate_enable();
2657 	return ret;
2658 }
2659 
2660 bool bpf_jit_bypass_spec_v1(void);
2661 bool bpf_jit_bypass_spec_v4(void);
2662 
2663 #define bpf_rcu_lock_held() \
2664 	(rcu_read_lock_held() || rcu_read_lock_trace_held() || rcu_read_lock_bh_held())
2665 
2666 #ifdef CONFIG_BPF_SYSCALL
2667 DECLARE_PER_CPU(int, bpf_prog_active);
2668 extern struct mutex bpf_stats_enabled_mutex;
2669 
2670 /*
2671  * Block execution of BPF programs attached to instrumentation (perf,
2672  * kprobes, tracepoints) to prevent deadlocks on map operations as any of
2673  * these events can happen inside a region which holds a map bucket lock
2674  * and can deadlock on it.
2675  */
2676 static inline void bpf_disable_instrumentation(void)
2677 {
2678 	migrate_disable();
2679 	this_cpu_inc(bpf_prog_active);
2680 }
2681 
2682 static inline void bpf_enable_instrumentation(void)
2683 {
2684 	this_cpu_dec(bpf_prog_active);
2685 	migrate_enable();
2686 }
2687 
2688 extern const struct super_operations bpf_super_ops;
2689 extern const struct file_operations bpf_map_fops;
2690 extern const struct file_operations bpf_prog_fops;
2691 extern const struct file_operations bpf_iter_fops;
2692 extern const struct file_operations bpf_token_fops;
2693 
2694 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
2695 	extern const struct bpf_prog_ops _name ## _prog_ops; \
2696 	extern const struct bpf_verifier_ops _name ## _verifier_ops;
2697 #define BPF_MAP_TYPE(_id, _ops) \
2698 	extern const struct bpf_map_ops _ops;
2699 #define BPF_LINK_TYPE(_id, _name)
2700 #include <linux/bpf_types.h>
2701 #undef BPF_PROG_TYPE
2702 #undef BPF_MAP_TYPE
2703 #undef BPF_LINK_TYPE
2704 
2705 extern const struct bpf_prog_ops bpf_offload_prog_ops;
2706 extern const struct bpf_verifier_ops tc_cls_act_analyzer_ops;
2707 extern const struct bpf_verifier_ops xdp_analyzer_ops;
2708 
2709 struct bpf_prog *bpf_prog_get(u32 ufd);
2710 struct bpf_prog *bpf_prog_get_type_dev(u32 ufd, enum bpf_prog_type type,
2711 				       bool attach_drv);
2712 void bpf_prog_add(struct bpf_prog *prog, int i);
2713 void bpf_prog_sub(struct bpf_prog *prog, int i);
2714 void bpf_prog_inc(struct bpf_prog *prog);
2715 struct bpf_prog * __must_check bpf_prog_inc_not_zero(struct bpf_prog *prog);
2716 void bpf_prog_put(struct bpf_prog *prog);
2717 
2718 void bpf_prog_free_id(struct bpf_prog *prog);
2719 void bpf_map_free_id(struct bpf_map *map);
2720 
2721 struct btf_field *btf_record_find(const struct btf_record *rec,
2722 				  u32 offset, u32 field_mask);
2723 void btf_record_free(struct btf_record *rec);
2724 void bpf_map_free_record(struct bpf_map *map);
2725 struct btf_record *btf_record_dup(const struct btf_record *rec);
2726 bool btf_record_equal(const struct btf_record *rec_a, const struct btf_record *rec_b);
2727 void bpf_obj_free_timer(const struct btf_record *rec, void *obj);
2728 void bpf_obj_free_workqueue(const struct btf_record *rec, void *obj);
2729 void bpf_obj_free_task_work(const struct btf_record *rec, void *obj);
2730 void bpf_obj_cancel_fields(struct bpf_map *map, void *obj);
2731 void bpf_obj_free_fields(const struct btf_record *rec, void *obj);
2732 void __bpf_obj_drop_impl(void *p, const struct btf_record *rec, bool percpu);
2733 
2734 struct bpf_map *bpf_map_get(u32 ufd);
2735 struct bpf_map *bpf_map_get_with_uref(u32 ufd);
2736 
2737 /*
2738  * The __bpf_map_get() and __btf_get_by_fd() functions parse a file
2739  * descriptor and return a corresponding map or btf object.
2740  * Their names are double underscored to emphasize the fact that they
2741  * do not increase refcnt. To also increase refcnt use corresponding
2742  * bpf_map_get() and btf_get_by_fd() functions.
2743  */
2744 
2745 static inline struct bpf_map *__bpf_map_get(struct fd f)
2746 {
2747 	if (fd_empty(f))
2748 		return ERR_PTR(-EBADF);
2749 	if (unlikely(fd_file(f)->f_op != &bpf_map_fops))
2750 		return ERR_PTR(-EINVAL);
2751 	return fd_file(f)->private_data;
2752 }
2753 
2754 static inline struct btf *__btf_get_by_fd(struct fd f)
2755 {
2756 	if (fd_empty(f))
2757 		return ERR_PTR(-EBADF);
2758 	if (unlikely(fd_file(f)->f_op != &btf_fops))
2759 		return ERR_PTR(-EINVAL);
2760 	return fd_file(f)->private_data;
2761 }
2762 
2763 void bpf_map_inc(struct bpf_map *map);
2764 void bpf_map_inc_with_uref(struct bpf_map *map);
2765 struct bpf_map *__bpf_map_inc_not_zero(struct bpf_map *map, bool uref);
2766 struct bpf_map * __must_check bpf_map_inc_not_zero(struct bpf_map *map);
2767 void bpf_map_put_with_uref(struct bpf_map *map);
2768 void bpf_map_put(struct bpf_map *map);
2769 void *bpf_map_area_alloc(u64 size, int numa_node);
2770 void *bpf_map_area_mmapable_alloc(u64 size, int numa_node);
2771 void bpf_map_area_free(void *base);
2772 bool bpf_map_write_active(const struct bpf_map *map);
2773 void bpf_map_init_from_attr(struct bpf_map *map, union bpf_attr *attr);
2774 int  generic_map_lookup_batch(struct bpf_map *map,
2775 			      const union bpf_attr *attr,
2776 			      union bpf_attr __user *uattr);
2777 int  generic_map_update_batch(struct bpf_map *map, struct file *map_file,
2778 			      const union bpf_attr *attr,
2779 			      union bpf_attr __user *uattr);
2780 int  generic_map_delete_batch(struct bpf_map *map,
2781 			      const union bpf_attr *attr,
2782 			      union bpf_attr __user *uattr);
2783 struct bpf_map *bpf_map_get_curr_or_next(u32 *id);
2784 struct bpf_prog *bpf_prog_get_curr_or_next(u32 *id);
2785 
2786 
2787 int bpf_map_alloc_pages(const struct bpf_map *map, int nid,
2788 			unsigned long nr_pages, struct page **page_array);
2789 #ifdef CONFIG_MEMCG
2790 void bpf_map_memcg_enter(const struct bpf_map *map, struct mem_cgroup **old_memcg,
2791 			 struct mem_cgroup **new_memcg);
2792 void bpf_map_memcg_exit(struct mem_cgroup *old_memcg,
2793 			struct mem_cgroup *memcg);
2794 void *bpf_map_kmalloc_node(const struct bpf_map *map, size_t size, gfp_t flags,
2795 			   int node);
2796 void *bpf_map_kmalloc_nolock(const struct bpf_map *map, size_t size, gfp_t flags,
2797 			     int node);
2798 void *bpf_map_kzalloc(const struct bpf_map *map, size_t size, gfp_t flags);
2799 void *bpf_map_kvcalloc(struct bpf_map *map, size_t n, size_t size,
2800 		       gfp_t flags);
2801 void __percpu *bpf_map_alloc_percpu(const struct bpf_map *map, size_t size,
2802 				    size_t align, gfp_t flags);
2803 #else
2804 /*
2805  * These specialized allocators have to be macros for their allocations to be
2806  * accounted separately (to have separate alloc_tag).
2807  */
2808 #define bpf_map_kmalloc_node(_map, _size, _flags, _node)	\
2809 		kmalloc_node(_size, _flags, _node)
2810 #define bpf_map_kmalloc_nolock(_map, _size, _flags, _node)	\
2811 		kmalloc_nolock(_size, _flags, _node)
2812 #define bpf_map_kzalloc(_map, _size, _flags)			\
2813 		kzalloc(_size, _flags)
2814 #define bpf_map_kvcalloc(_map, _n, _size, _flags)		\
2815 		kvcalloc(_n, _size, _flags)
2816 #define bpf_map_alloc_percpu(_map, _size, _align, _flags)	\
2817 		__alloc_percpu_gfp(_size, _align, _flags)
2818 static inline void bpf_map_memcg_enter(const struct bpf_map *map, struct mem_cgroup **old_memcg,
2819 				       struct mem_cgroup **new_memcg)
2820 {
2821 	*new_memcg = NULL;
2822 	*old_memcg = NULL;
2823 }
2824 
2825 static inline void bpf_map_memcg_exit(struct mem_cgroup *old_memcg,
2826 				      struct mem_cgroup *memcg)
2827 {
2828 }
2829 #endif
2830 
2831 static inline int
2832 bpf_map_init_elem_count(struct bpf_map *map)
2833 {
2834 	size_t size = sizeof(*map->elem_count), align = size;
2835 	gfp_t flags = GFP_USER | __GFP_NOWARN;
2836 
2837 	map->elem_count = bpf_map_alloc_percpu(map, size, align, flags);
2838 	if (!map->elem_count)
2839 		return -ENOMEM;
2840 
2841 	return 0;
2842 }
2843 
2844 static inline void
2845 bpf_map_free_elem_count(struct bpf_map *map)
2846 {
2847 	free_percpu(map->elem_count);
2848 }
2849 
2850 static inline void bpf_map_inc_elem_count(struct bpf_map *map)
2851 {
2852 	this_cpu_inc(*map->elem_count);
2853 }
2854 
2855 static inline void bpf_map_dec_elem_count(struct bpf_map *map)
2856 {
2857 	this_cpu_dec(*map->elem_count);
2858 }
2859 
2860 extern int sysctl_unprivileged_bpf_disabled;
2861 
2862 bool bpf_token_capable(const struct bpf_token *token, int cap);
2863 
2864 static inline bool bpf_allow_ptr_leaks(const struct bpf_token *token)
2865 {
2866 	return bpf_token_capable(token, CAP_PERFMON);
2867 }
2868 
2869 static inline bool bpf_allow_uninit_stack(const struct bpf_token *token)
2870 {
2871 	return bpf_token_capable(token, CAP_PERFMON);
2872 }
2873 
2874 static inline bool bpf_bypass_spec_v1(const struct bpf_token *token)
2875 {
2876 	return bpf_jit_bypass_spec_v1() ||
2877 		cpu_mitigations_off() ||
2878 		bpf_token_capable(token, CAP_PERFMON);
2879 }
2880 
2881 static inline bool bpf_bypass_spec_v4(const struct bpf_token *token)
2882 {
2883 	return bpf_jit_bypass_spec_v4() ||
2884 		cpu_mitigations_off() ||
2885 		bpf_token_capable(token, CAP_PERFMON);
2886 }
2887 
2888 int bpf_map_new_fd(struct bpf_map *map, int flags);
2889 int bpf_prog_new_fd(struct bpf_prog *prog);
2890 
2891 void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
2892 		   const struct bpf_link_ops *ops, struct bpf_prog *prog,
2893 		   enum bpf_attach_type attach_type);
2894 void bpf_link_init_sleepable(struct bpf_link *link, enum bpf_link_type type,
2895 			     const struct bpf_link_ops *ops, struct bpf_prog *prog,
2896 			     enum bpf_attach_type attach_type, bool sleepable);
2897 void bpf_tramp_link_init(struct bpf_tramp_link *link, enum bpf_link_type type,
2898 			 const struct bpf_link_ops *ops, struct bpf_prog *prog,
2899 			 enum bpf_attach_type attach_type, u64 cookie);
2900 int bpf_link_prime(struct bpf_link *link, struct bpf_link_primer *primer);
2901 int bpf_link_settle(struct bpf_link_primer *primer);
2902 void bpf_link_cleanup(struct bpf_link_primer *primer);
2903 void bpf_link_inc(struct bpf_link *link);
2904 struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link);
2905 void bpf_link_put(struct bpf_link *link);
2906 int bpf_link_new_fd(struct bpf_link *link);
2907 struct bpf_link *bpf_link_get_from_fd(u32 ufd);
2908 struct bpf_link *bpf_link_get_curr_or_next(u32 *id);
2909 
2910 void bpf_token_inc(struct bpf_token *token);
2911 void bpf_token_put(struct bpf_token *token);
2912 int bpf_token_create(union bpf_attr *attr);
2913 struct bpf_token *bpf_token_get_from_fd(u32 ufd);
2914 int bpf_token_get_info_by_fd(struct bpf_token *token,
2915 			     const union bpf_attr *attr,
2916 			     union bpf_attr __user *uattr);
2917 
2918 bool bpf_token_allow_cmd(const struct bpf_token *token, enum bpf_cmd cmd);
2919 bool bpf_token_allow_map_type(const struct bpf_token *token, enum bpf_map_type type);
2920 bool bpf_token_allow_prog_type(const struct bpf_token *token,
2921 			       enum bpf_prog_type prog_type,
2922 			       enum bpf_attach_type attach_type);
2923 
2924 int bpf_obj_pin_user(u32 ufd, int path_fd, const char __user *pathname);
2925 int bpf_obj_get_user(int path_fd, const char __user *pathname, int flags);
2926 struct inode *bpf_get_inode(struct super_block *sb, const struct inode *dir,
2927 			    umode_t mode);
2928 
2929 #define BPF_ITER_FUNC_PREFIX "bpf_iter_"
2930 #define DEFINE_BPF_ITER_FUNC(target, args...)			\
2931 	extern int bpf_iter_ ## target(args);			\
2932 	int __init bpf_iter_ ## target(args) { return 0; }
2933 
2934 /*
2935  * The task type of iterators.
2936  *
2937  * For BPF task iterators, they can be parameterized with various
2938  * parameters to visit only some of tasks.
2939  *
2940  * BPF_TASK_ITER_ALL (default)
2941  *	Iterate over resources of every task.
2942  *
2943  * BPF_TASK_ITER_TID
2944  *	Iterate over resources of a task/tid.
2945  *
2946  * BPF_TASK_ITER_TGID
2947  *	Iterate over resources of every task of a process / task group.
2948  */
2949 enum bpf_iter_task_type {
2950 	BPF_TASK_ITER_ALL = 0,
2951 	BPF_TASK_ITER_TID,
2952 	BPF_TASK_ITER_TGID,
2953 };
2954 
2955 struct bpf_iter_aux_info {
2956 	/* for map_elem iter */
2957 	struct bpf_map *map;
2958 
2959 	/* for cgroup iter */
2960 	struct {
2961 		struct cgroup *start; /* starting cgroup */
2962 		enum bpf_cgroup_iter_order order;
2963 	} cgroup;
2964 	struct {
2965 		enum bpf_iter_task_type	type;
2966 		u32 pid;
2967 	} task;
2968 };
2969 
2970 typedef int (*bpf_iter_attach_target_t)(struct bpf_prog *prog,
2971 					union bpf_iter_link_info *linfo,
2972 					struct bpf_iter_aux_info *aux);
2973 typedef void (*bpf_iter_detach_target_t)(struct bpf_iter_aux_info *aux);
2974 typedef void (*bpf_iter_show_fdinfo_t) (const struct bpf_iter_aux_info *aux,
2975 					struct seq_file *seq);
2976 typedef int (*bpf_iter_fill_link_info_t)(const struct bpf_iter_aux_info *aux,
2977 					 struct bpf_link_info *info);
2978 typedef const struct bpf_func_proto *
2979 (*bpf_iter_get_func_proto_t)(enum bpf_func_id func_id,
2980 			     const struct bpf_prog *prog);
2981 
2982 enum bpf_iter_feature {
2983 	BPF_ITER_RESCHED	= BIT(0),
2984 };
2985 
2986 #define BPF_ITER_CTX_ARG_MAX 2
2987 struct bpf_iter_reg {
2988 	const char *target;
2989 	bpf_iter_attach_target_t attach_target;
2990 	bpf_iter_detach_target_t detach_target;
2991 	bpf_iter_show_fdinfo_t show_fdinfo;
2992 	bpf_iter_fill_link_info_t fill_link_info;
2993 	bpf_iter_get_func_proto_t get_func_proto;
2994 	u32 ctx_arg_info_size;
2995 	u32 feature;
2996 	struct bpf_ctx_arg_aux ctx_arg_info[BPF_ITER_CTX_ARG_MAX];
2997 	const struct bpf_iter_seq_info *seq_info;
2998 };
2999 
3000 struct bpf_iter_meta {
3001 	__bpf_md_ptr(struct seq_file *, seq);
3002 	u64 session_id;
3003 	u64 seq_num;
3004 };
3005 
3006 struct bpf_iter__bpf_map_elem {
3007 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
3008 	__bpf_md_ptr(struct bpf_map *, map);
3009 	__bpf_md_ptr(void *, key);
3010 	__bpf_md_ptr(void *, value);
3011 };
3012 
3013 int bpf_iter_reg_target(const struct bpf_iter_reg *reg_info);
3014 void bpf_iter_unreg_target(const struct bpf_iter_reg *reg_info);
3015 int bpf_iter_prog_supported(struct bpf_prog *prog);
3016 const struct bpf_func_proto *
3017 bpf_iter_get_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog);
3018 int bpf_iter_link_attach(const union bpf_attr *attr, bpfptr_t uattr, struct bpf_prog *prog);
3019 int bpf_iter_new_fd(struct bpf_link *link);
3020 bool bpf_link_is_iter(struct bpf_link *link);
3021 struct bpf_prog *bpf_iter_get_info(struct bpf_iter_meta *meta, bool in_stop);
3022 int bpf_iter_run_prog(struct bpf_prog *prog, void *ctx);
3023 void bpf_iter_map_show_fdinfo(const struct bpf_iter_aux_info *aux,
3024 			      struct seq_file *seq);
3025 int bpf_iter_map_fill_link_info(const struct bpf_iter_aux_info *aux,
3026 				struct bpf_link_info *info);
3027 
3028 int map_set_for_each_callback_args(struct bpf_verifier_env *env,
3029 				   struct bpf_func_state *caller,
3030 				   struct bpf_func_state *callee);
3031 
3032 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value, u64 flags);
3033 int bpf_percpu_array_copy(struct bpf_map *map, void *key, void *value, u64 flags);
3034 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value,
3035 			   u64 flags);
3036 int bpf_percpu_array_update(struct bpf_map *map, void *key, void *value,
3037 			    u64 flags);
3038 
3039 int bpf_stackmap_extract(struct bpf_map *map, void *key, void *value, bool delete);
3040 
3041 int bpf_fd_array_map_update_elem(struct bpf_map *map, struct file *map_file,
3042 				 void *key, void *value, u64 map_flags);
3043 int bpf_fd_array_map_lookup_elem(struct bpf_map *map, void *key, u32 *value);
3044 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file,
3045 				void *key, void *value, u64 map_flags);
3046 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value);
3047 
3048 int bpf_get_file_flag(int flags);
3049 int bpf_check_uarg_tail_zero(bpfptr_t uaddr, size_t expected_size,
3050 			     size_t actual_size);
3051 
3052 /* verify correctness of eBPF program */
3053 struct bpf_log_attr;
3054 int bpf_check(struct bpf_prog **fp, union bpf_attr *attr, bpfptr_t uattr,
3055 	      struct bpf_log_attr *attr_log);
3056 
3057 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
3058 int bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth);
3059 s32 bpf_call_args_imm(s16 idx);
3060 #else
3061 static inline s32 bpf_call_args_imm(s16 idx)
3062 {
3063 	return 0;
3064 }
3065 #endif
3066 
3067 struct btf *bpf_get_btf_vmlinux(void);
3068 
3069 /* Map specifics */
3070 struct xdp_frame;
3071 struct sk_buff;
3072 struct bpf_dtab_netdev;
3073 struct bpf_cpu_map_entry;
3074 
3075 void __dev_flush(struct list_head *flush_list);
3076 int dev_xdp_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
3077 		    struct net_device *dev_rx);
3078 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_frame *xdpf,
3079 		    struct net_device *dev_rx);
3080 int dev_map_enqueue_multi(struct xdp_frame *xdpf, struct net_device *dev_rx,
3081 			  struct bpf_map *map, bool exclude_ingress);
3082 int dev_map_generic_redirect(struct bpf_dtab_netdev *dst, struct sk_buff *skb,
3083 			     const struct bpf_prog *xdp_prog);
3084 int dev_map_redirect_multi(struct net_device *dev, struct sk_buff *skb,
3085 			   const struct bpf_prog *xdp_prog,
3086 			   struct bpf_map *map, bool exclude_ingress);
3087 
3088 void __cpu_map_flush(struct list_head *flush_list);
3089 int cpu_map_enqueue(struct bpf_cpu_map_entry *rcpu, struct xdp_frame *xdpf,
3090 		    struct net_device *dev_rx);
3091 int cpu_map_generic_redirect(struct bpf_cpu_map_entry *rcpu,
3092 			     struct sk_buff *skb);
3093 
3094 /* Return map's numa specified by userspace */
3095 static inline int bpf_map_attr_numa_node(const union bpf_attr *attr)
3096 {
3097 	return (attr->map_flags & BPF_F_NUMA_NODE) ?
3098 		attr->numa_node : NUMA_NO_NODE;
3099 }
3100 
3101 struct bpf_prog *bpf_prog_get_type_path(const char *name, enum bpf_prog_type type);
3102 int array_map_alloc_check(union bpf_attr *attr);
3103 
3104 int bpf_prog_test_run_xdp(struct bpf_prog *prog, const union bpf_attr *kattr,
3105 			  union bpf_attr __user *uattr);
3106 int bpf_prog_test_run_skb(struct bpf_prog *prog, const union bpf_attr *kattr,
3107 			  union bpf_attr __user *uattr);
3108 int bpf_prog_test_run_tracing(struct bpf_prog *prog,
3109 			      const union bpf_attr *kattr,
3110 			      union bpf_attr __user *uattr);
3111 int bpf_prog_test_run_flow_dissector(struct bpf_prog *prog,
3112 				     const union bpf_attr *kattr,
3113 				     union bpf_attr __user *uattr);
3114 int bpf_prog_test_run_raw_tp(struct bpf_prog *prog,
3115 			     const union bpf_attr *kattr,
3116 			     union bpf_attr __user *uattr);
3117 int bpf_prog_test_run_sk_lookup(struct bpf_prog *prog,
3118 				const union bpf_attr *kattr,
3119 				union bpf_attr __user *uattr);
3120 int bpf_prog_test_run_nf(struct bpf_prog *prog,
3121 			 const union bpf_attr *kattr,
3122 			 union bpf_attr __user *uattr);
3123 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
3124 		    const struct bpf_prog *prog,
3125 		    struct bpf_insn_access_aux *info);
3126 
3127 static inline bool bpf_tracing_ctx_access(int off, int size,
3128 					  enum bpf_access_type type)
3129 {
3130 	if (off < 0 || off >= sizeof(__u64) * MAX_BPF_FUNC_ARGS)
3131 		return false;
3132 	if (type != BPF_READ)
3133 		return false;
3134 	if (off % size != 0)
3135 		return false;
3136 	return true;
3137 }
3138 
3139 static inline bool bpf_tracing_btf_ctx_access(int off, int size,
3140 					      enum bpf_access_type type,
3141 					      const struct bpf_prog *prog,
3142 					      struct bpf_insn_access_aux *info)
3143 {
3144 	if (!bpf_tracing_ctx_access(off, size, type))
3145 		return false;
3146 	return btf_ctx_access(off, size, type, prog, info);
3147 }
3148 
3149 int btf_struct_access(struct bpf_verifier_log *log,
3150 		      const struct bpf_reg_state *reg,
3151 		      int off, int size, enum bpf_access_type atype,
3152 		      u32 *next_btf_id, enum bpf_type_flag *flag, const char **field_name);
3153 bool btf_struct_ids_match(struct bpf_verifier_log *log,
3154 			  const struct btf *btf, u32 id, int off,
3155 			  const struct btf *need_btf, u32 need_type_id,
3156 			  bool strict, bool walk_flex_arrays);
3157 
3158 int btf_distill_func_proto(struct bpf_verifier_log *log,
3159 			   struct btf *btf,
3160 			   const struct btf_type *func_proto,
3161 			   const char *func_name,
3162 			   struct btf_func_model *m);
3163 
3164 struct bpf_reg_state;
3165 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog);
3166 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
3167 			 struct btf *btf, const struct btf_type *t);
3168 const char *btf_find_decl_tag_value(const struct btf *btf, const struct btf_type *pt,
3169 				    int comp_idx, const char *tag_key);
3170 int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
3171 			   int comp_idx, const char *tag_key, int last_id);
3172 
3173 struct bpf_prog *bpf_prog_by_id(u32 id);
3174 struct bpf_link *bpf_link_by_id(u32 id);
3175 
3176 const struct bpf_func_proto *bpf_base_func_proto(enum bpf_func_id func_id,
3177 						 const struct bpf_prog *prog);
3178 void bpf_task_storage_free(struct task_struct *task);
3179 void bpf_cgrp_storage_free(struct cgroup *cgroup);
3180 const struct btf_func_model *
3181 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3182 			 const struct bpf_insn *insn);
3183 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3184 		       u16 btf_fd_idx, u8 **func_addr);
3185 
3186 struct bpf_core_ctx {
3187 	struct bpf_verifier_log *log;
3188 	const struct btf *btf;
3189 };
3190 
3191 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
3192 				const struct bpf_reg_state *reg,
3193 				const char *field_name, u32 btf_id, const char *suffix);
3194 
3195 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
3196 			       const struct btf *reg_btf, u32 reg_id,
3197 			       const struct btf *arg_btf, u32 arg_id);
3198 
3199 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
3200 		   int relo_idx, void *insn);
3201 
3202 static inline bool unprivileged_ebpf_enabled(void)
3203 {
3204 	return !sysctl_unprivileged_bpf_disabled;
3205 }
3206 
3207 /* Not all bpf prog type has the bpf_ctx.
3208  * For the bpf prog type that has initialized the bpf_ctx,
3209  * this function can be used to decide if a kernel function
3210  * is called by a bpf program.
3211  */
3212 static inline bool has_current_bpf_ctx(void)
3213 {
3214 	return !!current->bpf_ctx;
3215 }
3216 
3217 void notrace bpf_prog_inc_misses_counter(struct bpf_prog *prog);
3218 
3219 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
3220 		     enum bpf_dynptr_type type, u32 offset, u32 size);
3221 void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr);
3222 void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr);
3223 void bpf_prog_report_arena_violation(bool write, unsigned long addr, unsigned long fault_ip);
3224 
3225 static __always_inline u32
3226 bpf_prog_run_array_sleepable(const struct bpf_prog_array *array,
3227 			     const void *ctx, bpf_prog_run_fn run_prog)
3228 {
3229 	const struct bpf_prog_array_item *item;
3230 	struct bpf_prog *prog;
3231 	struct bpf_run_ctx *old_run_ctx;
3232 	struct bpf_trace_run_ctx run_ctx;
3233 	u32 ret = 1;
3234 
3235 	if (unlikely(!array))
3236 		return ret;
3237 
3238 	migrate_disable();
3239 
3240 	run_ctx.is_uprobe = false;
3241 
3242 	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
3243 	item = &array->items[0];
3244 	while ((prog = READ_ONCE(item->prog))) {
3245 		/* Skip dummy_bpf_prog placeholder (len == 0) */
3246 		if (unlikely(!prog->len)) {
3247 			item++;
3248 			continue;
3249 		}
3250 
3251 		if (unlikely(!bpf_prog_get_recursion_context(prog))) {
3252 			bpf_prog_inc_misses_counter(prog);
3253 			bpf_prog_put_recursion_context(prog);
3254 			item++;
3255 			continue;
3256 		}
3257 
3258 		run_ctx.bpf_cookie = item->bpf_cookie;
3259 
3260 		if (!prog->sleepable) {
3261 			guard(rcu)();
3262 			ret &= run_prog(prog, ctx);
3263 		} else {
3264 			ret &= run_prog(prog, ctx);
3265 		}
3266 
3267 		bpf_prog_put_recursion_context(prog);
3268 		item++;
3269 	}
3270 	bpf_reset_run_ctx(old_run_ctx);
3271 	migrate_enable();
3272 	return ret;
3273 }
3274 
3275 #else /* !CONFIG_BPF_SYSCALL */
3276 static inline struct bpf_prog *bpf_prog_get(u32 ufd)
3277 {
3278 	return ERR_PTR(-EOPNOTSUPP);
3279 }
3280 
3281 static inline struct bpf_prog *bpf_prog_get_type_dev(u32 ufd,
3282 						     enum bpf_prog_type type,
3283 						     bool attach_drv)
3284 {
3285 	return ERR_PTR(-EOPNOTSUPP);
3286 }
3287 
3288 static inline void bpf_prog_add(struct bpf_prog *prog, int i)
3289 {
3290 }
3291 
3292 static inline void bpf_prog_sub(struct bpf_prog *prog, int i)
3293 {
3294 }
3295 
3296 static inline void bpf_prog_put(struct bpf_prog *prog)
3297 {
3298 }
3299 
3300 static inline void bpf_prog_inc(struct bpf_prog *prog)
3301 {
3302 }
3303 
3304 static inline struct bpf_prog *__must_check
3305 bpf_prog_inc_not_zero(struct bpf_prog *prog)
3306 {
3307 	return ERR_PTR(-EOPNOTSUPP);
3308 }
3309 
3310 static inline void bpf_link_init(struct bpf_link *link, enum bpf_link_type type,
3311 				 const struct bpf_link_ops *ops,
3312 				 struct bpf_prog *prog, enum bpf_attach_type attach_type)
3313 {
3314 }
3315 
3316 static inline void bpf_link_init_sleepable(struct bpf_link *link, enum bpf_link_type type,
3317 					   const struct bpf_link_ops *ops, struct bpf_prog *prog,
3318 					   enum bpf_attach_type attach_type, bool sleepable)
3319 {
3320 }
3321 
3322 static inline void bpf_tramp_link_init(struct bpf_tramp_link *link, enum bpf_link_type type,
3323 				       const struct bpf_link_ops *ops, struct bpf_prog *prog,
3324 				       enum bpf_attach_type attach_type, u64 cookie)
3325 {
3326 }
3327 
3328 static inline int bpf_link_prime(struct bpf_link *link,
3329 				 struct bpf_link_primer *primer)
3330 {
3331 	return -EOPNOTSUPP;
3332 }
3333 
3334 static inline int bpf_link_settle(struct bpf_link_primer *primer)
3335 {
3336 	return -EOPNOTSUPP;
3337 }
3338 
3339 static inline void bpf_link_cleanup(struct bpf_link_primer *primer)
3340 {
3341 }
3342 
3343 static inline void bpf_link_inc(struct bpf_link *link)
3344 {
3345 }
3346 
3347 static inline struct bpf_link *bpf_link_inc_not_zero(struct bpf_link *link)
3348 {
3349 	return NULL;
3350 }
3351 
3352 static inline void bpf_link_put(struct bpf_link *link)
3353 {
3354 }
3355 
3356 static inline int bpf_obj_get_user(const char __user *pathname, int flags)
3357 {
3358 	return -EOPNOTSUPP;
3359 }
3360 
3361 static inline bool bpf_token_capable(const struct bpf_token *token, int cap)
3362 {
3363 	return capable(cap) || (cap != CAP_SYS_ADMIN && capable(CAP_SYS_ADMIN));
3364 }
3365 
3366 static inline void bpf_token_inc(struct bpf_token *token)
3367 {
3368 }
3369 
3370 static inline void bpf_token_put(struct bpf_token *token)
3371 {
3372 }
3373 
3374 static inline struct bpf_token *bpf_token_get_from_fd(u32 ufd)
3375 {
3376 	return ERR_PTR(-EOPNOTSUPP);
3377 }
3378 
3379 static inline int bpf_token_get_info_by_fd(struct bpf_token *token,
3380 					   const union bpf_attr *attr,
3381 					   union bpf_attr __user *uattr)
3382 {
3383 	return -EOPNOTSUPP;
3384 }
3385 
3386 static inline void __dev_flush(struct list_head *flush_list)
3387 {
3388 }
3389 
3390 struct xdp_frame;
3391 struct bpf_dtab_netdev;
3392 struct bpf_cpu_map_entry;
3393 
3394 static inline
3395 int dev_xdp_enqueue(struct net_device *dev, struct xdp_frame *xdpf,
3396 		    struct net_device *dev_rx)
3397 {
3398 	return 0;
3399 }
3400 
3401 static inline
3402 int dev_map_enqueue(struct bpf_dtab_netdev *dst, struct xdp_frame *xdpf,
3403 		    struct net_device *dev_rx)
3404 {
3405 	return 0;
3406 }
3407 
3408 static inline
3409 int dev_map_enqueue_multi(struct xdp_frame *xdpf, struct net_device *dev_rx,
3410 			  struct bpf_map *map, bool exclude_ingress)
3411 {
3412 	return 0;
3413 }
3414 
3415 struct sk_buff;
3416 
3417 static inline int dev_map_generic_redirect(struct bpf_dtab_netdev *dst,
3418 					   struct sk_buff *skb,
3419 					   const struct bpf_prog *xdp_prog)
3420 {
3421 	return 0;
3422 }
3423 
3424 static inline
3425 int dev_map_redirect_multi(struct net_device *dev, struct sk_buff *skb,
3426 			   const struct bpf_prog *xdp_prog,
3427 			   struct bpf_map *map, bool exclude_ingress)
3428 {
3429 	return 0;
3430 }
3431 
3432 static inline void __cpu_map_flush(struct list_head *flush_list)
3433 {
3434 }
3435 
3436 static inline int cpu_map_enqueue(struct bpf_cpu_map_entry *rcpu,
3437 				  struct xdp_frame *xdpf,
3438 				  struct net_device *dev_rx)
3439 {
3440 	return 0;
3441 }
3442 
3443 static inline int cpu_map_generic_redirect(struct bpf_cpu_map_entry *rcpu,
3444 					   struct sk_buff *skb)
3445 {
3446 	return -EOPNOTSUPP;
3447 }
3448 
3449 static inline struct bpf_prog *bpf_prog_get_type_path(const char *name,
3450 				enum bpf_prog_type type)
3451 {
3452 	return ERR_PTR(-EOPNOTSUPP);
3453 }
3454 
3455 static inline int bpf_prog_test_run_xdp(struct bpf_prog *prog,
3456 					const union bpf_attr *kattr,
3457 					union bpf_attr __user *uattr)
3458 {
3459 	return -ENOTSUPP;
3460 }
3461 
3462 static inline int bpf_prog_test_run_skb(struct bpf_prog *prog,
3463 					const union bpf_attr *kattr,
3464 					union bpf_attr __user *uattr)
3465 {
3466 	return -ENOTSUPP;
3467 }
3468 
3469 static inline int bpf_prog_test_run_tracing(struct bpf_prog *prog,
3470 					    const union bpf_attr *kattr,
3471 					    union bpf_attr __user *uattr)
3472 {
3473 	return -ENOTSUPP;
3474 }
3475 
3476 static inline int bpf_prog_test_run_flow_dissector(struct bpf_prog *prog,
3477 						   const union bpf_attr *kattr,
3478 						   union bpf_attr __user *uattr)
3479 {
3480 	return -ENOTSUPP;
3481 }
3482 
3483 static inline int bpf_prog_test_run_sk_lookup(struct bpf_prog *prog,
3484 					      const union bpf_attr *kattr,
3485 					      union bpf_attr __user *uattr)
3486 {
3487 	return -ENOTSUPP;
3488 }
3489 
3490 static inline void bpf_map_put(struct bpf_map *map)
3491 {
3492 }
3493 
3494 static inline struct bpf_prog *bpf_prog_by_id(u32 id)
3495 {
3496 	return ERR_PTR(-ENOTSUPP);
3497 }
3498 
3499 static inline int btf_struct_access(struct bpf_verifier_log *log,
3500 				    const struct bpf_reg_state *reg,
3501 				    int off, int size, enum bpf_access_type atype,
3502 				    u32 *next_btf_id, enum bpf_type_flag *flag,
3503 				    const char **field_name)
3504 {
3505 	return -EACCES;
3506 }
3507 
3508 static inline const struct bpf_func_proto *
3509 bpf_base_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
3510 {
3511 	return NULL;
3512 }
3513 
3514 static inline void bpf_task_storage_free(struct task_struct *task)
3515 {
3516 }
3517 
3518 static inline const struct btf_func_model *
3519 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
3520 			 const struct bpf_insn *insn)
3521 {
3522 	return NULL;
3523 }
3524 
3525 static inline int
3526 bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id,
3527 		   u16 btf_fd_idx, u8 **func_addr)
3528 {
3529 	return -ENOTSUPP;
3530 }
3531 
3532 static inline bool unprivileged_ebpf_enabled(void)
3533 {
3534 	return false;
3535 }
3536 
3537 static inline bool has_current_bpf_ctx(void)
3538 {
3539 	return false;
3540 }
3541 
3542 static inline void bpf_prog_inc_misses_counter(struct bpf_prog *prog)
3543 {
3544 }
3545 
3546 static inline void bpf_cgrp_storage_free(struct cgroup *cgroup)
3547 {
3548 }
3549 
3550 static inline void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
3551 				   enum bpf_dynptr_type type, u32 offset, u32 size)
3552 {
3553 }
3554 
3555 static inline void bpf_dynptr_set_null(struct bpf_dynptr_kern *ptr)
3556 {
3557 }
3558 
3559 static inline void bpf_dynptr_set_rdonly(struct bpf_dynptr_kern *ptr)
3560 {
3561 }
3562 
3563 static inline void bpf_prog_report_arena_violation(bool write, unsigned long addr,
3564 						   unsigned long fault_ip)
3565 {
3566 }
3567 #endif /* CONFIG_BPF_SYSCALL */
3568 
3569 static inline bool bpf_net_capable(void)
3570 {
3571 	return capable(CAP_NET_ADMIN) || capable(CAP_SYS_ADMIN);
3572 }
3573 
3574 static __always_inline int
3575 bpf_probe_read_kernel_common(void *dst, u32 size, const void *unsafe_ptr)
3576 {
3577 	int ret = -EFAULT;
3578 
3579 	if (IS_ENABLED(CONFIG_BPF_EVENTS))
3580 		ret = copy_from_kernel_nofault(dst, unsafe_ptr, size);
3581 	if (unlikely(ret < 0))
3582 		memset(dst, 0, size);
3583 	return ret;
3584 }
3585 
3586 void __bpf_free_used_btfs(struct btf_mod_pair *used_btfs, u32 len);
3587 
3588 static inline struct bpf_prog *bpf_prog_get_type(u32 ufd,
3589 						 enum bpf_prog_type type)
3590 {
3591 	return bpf_prog_get_type_dev(ufd, type, false);
3592 }
3593 
3594 void __bpf_free_used_maps(struct bpf_prog_aux *aux,
3595 			  struct bpf_map **used_maps, u32 len);
3596 
3597 bool bpf_prog_get_ok(struct bpf_prog *, enum bpf_prog_type *, bool);
3598 
3599 int bpf_prog_offload_compile(struct bpf_prog *prog);
3600 void bpf_prog_dev_bound_destroy(struct bpf_prog *prog);
3601 int bpf_prog_offload_info_fill(struct bpf_prog_info *info,
3602 			       struct bpf_prog *prog);
3603 
3604 int bpf_map_offload_info_fill(struct bpf_map_info *info, struct bpf_map *map);
3605 
3606 int bpf_map_offload_lookup_elem(struct bpf_map *map, void *key, void *value);
3607 int bpf_map_offload_update_elem(struct bpf_map *map,
3608 				void *key, void *value, u64 flags);
3609 int bpf_map_offload_delete_elem(struct bpf_map *map, void *key);
3610 int bpf_map_offload_get_next_key(struct bpf_map *map,
3611 				 void *key, void *next_key);
3612 
3613 bool bpf_offload_prog_map_match(struct bpf_prog *prog, struct bpf_map *map);
3614 
3615 struct bpf_offload_dev *
3616 bpf_offload_dev_create(const struct bpf_prog_offload_ops *ops, void *priv);
3617 void bpf_offload_dev_destroy(struct bpf_offload_dev *offdev);
3618 void *bpf_offload_dev_priv(struct bpf_offload_dev *offdev);
3619 int bpf_offload_dev_netdev_register(struct bpf_offload_dev *offdev,
3620 				    struct net_device *netdev);
3621 void bpf_offload_dev_netdev_unregister(struct bpf_offload_dev *offdev,
3622 				       struct net_device *netdev);
3623 bool bpf_offload_dev_match(struct bpf_prog *prog, struct net_device *netdev);
3624 
3625 void unpriv_ebpf_notify(int new_state);
3626 
3627 #if defined(CONFIG_NET) && defined(CONFIG_BPF_SYSCALL)
3628 int bpf_dev_bound_kfunc_check(struct bpf_verifier_log *log,
3629 			      struct bpf_prog_aux *prog_aux);
3630 void *bpf_dev_bound_resolve_kfunc(struct bpf_prog *prog, u32 func_id);
3631 int bpf_prog_dev_bound_init(struct bpf_prog *prog, union bpf_attr *attr);
3632 int bpf_prog_dev_bound_inherit(struct bpf_prog *new_prog, struct bpf_prog *old_prog);
3633 void bpf_dev_bound_netdev_unregister(struct net_device *dev);
3634 
3635 static inline bool bpf_prog_is_dev_bound(const struct bpf_prog_aux *aux)
3636 {
3637 	return aux->dev_bound;
3638 }
3639 
3640 static inline bool bpf_prog_is_offloaded(const struct bpf_prog_aux *aux)
3641 {
3642 	return aux->offload_requested;
3643 }
3644 
3645 bool bpf_prog_dev_bound_match(const struct bpf_prog *lhs, const struct bpf_prog *rhs);
3646 
3647 static inline bool bpf_map_is_offloaded(struct bpf_map *map)
3648 {
3649 	return unlikely(map->ops == &bpf_map_offload_ops);
3650 }
3651 
3652 struct bpf_map *bpf_map_offload_map_alloc(union bpf_attr *attr);
3653 void bpf_map_offload_map_free(struct bpf_map *map);
3654 u64 bpf_map_offload_map_mem_usage(const struct bpf_map *map);
3655 int bpf_prog_test_run_syscall(struct bpf_prog *prog,
3656 			      const union bpf_attr *kattr,
3657 			      union bpf_attr __user *uattr);
3658 
3659 int sock_map_get_from_fd(const union bpf_attr *attr, struct bpf_prog *prog);
3660 int sock_map_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype);
3661 int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value, u64 flags);
3662 int sock_map_bpf_prog_query(const union bpf_attr *attr,
3663 			    union bpf_attr __user *uattr);
3664 int sock_map_link_create(const union bpf_attr *attr, struct bpf_prog *prog);
3665 
3666 void sock_map_unhash(struct sock *sk);
3667 void sock_map_destroy(struct sock *sk);
3668 void sock_map_close(struct sock *sk, long timeout);
3669 #else
3670 static inline int bpf_dev_bound_kfunc_check(struct bpf_verifier_log *log,
3671 					    struct bpf_prog_aux *prog_aux)
3672 {
3673 	return -EOPNOTSUPP;
3674 }
3675 
3676 static inline void *bpf_dev_bound_resolve_kfunc(struct bpf_prog *prog,
3677 						u32 func_id)
3678 {
3679 	return NULL;
3680 }
3681 
3682 static inline int bpf_prog_dev_bound_init(struct bpf_prog *prog,
3683 					  union bpf_attr *attr)
3684 {
3685 	return -EOPNOTSUPP;
3686 }
3687 
3688 static inline int bpf_prog_dev_bound_inherit(struct bpf_prog *new_prog,
3689 					     struct bpf_prog *old_prog)
3690 {
3691 	return -EOPNOTSUPP;
3692 }
3693 
3694 static inline void bpf_dev_bound_netdev_unregister(struct net_device *dev)
3695 {
3696 }
3697 
3698 static inline bool bpf_prog_is_dev_bound(const struct bpf_prog_aux *aux)
3699 {
3700 	return false;
3701 }
3702 
3703 static inline bool bpf_prog_is_offloaded(struct bpf_prog_aux *aux)
3704 {
3705 	return false;
3706 }
3707 
3708 static inline bool bpf_prog_dev_bound_match(const struct bpf_prog *lhs, const struct bpf_prog *rhs)
3709 {
3710 	return false;
3711 }
3712 
3713 static inline bool bpf_map_is_offloaded(struct bpf_map *map)
3714 {
3715 	return false;
3716 }
3717 
3718 static inline struct bpf_map *bpf_map_offload_map_alloc(union bpf_attr *attr)
3719 {
3720 	return ERR_PTR(-EOPNOTSUPP);
3721 }
3722 
3723 static inline void bpf_map_offload_map_free(struct bpf_map *map)
3724 {
3725 }
3726 
3727 static inline u64 bpf_map_offload_map_mem_usage(const struct bpf_map *map)
3728 {
3729 	return 0;
3730 }
3731 
3732 static inline int bpf_prog_test_run_syscall(struct bpf_prog *prog,
3733 					    const union bpf_attr *kattr,
3734 					    union bpf_attr __user *uattr)
3735 {
3736 	return -ENOTSUPP;
3737 }
3738 
3739 #ifdef CONFIG_BPF_SYSCALL
3740 static inline int sock_map_get_from_fd(const union bpf_attr *attr,
3741 				       struct bpf_prog *prog)
3742 {
3743 	return -EINVAL;
3744 }
3745 
3746 static inline int sock_map_prog_detach(const union bpf_attr *attr,
3747 				       enum bpf_prog_type ptype)
3748 {
3749 	return -EOPNOTSUPP;
3750 }
3751 
3752 static inline int sock_map_update_elem_sys(struct bpf_map *map, void *key, void *value,
3753 					   u64 flags)
3754 {
3755 	return -EOPNOTSUPP;
3756 }
3757 
3758 static inline int sock_map_bpf_prog_query(const union bpf_attr *attr,
3759 					  union bpf_attr __user *uattr)
3760 {
3761 	return -EINVAL;
3762 }
3763 
3764 static inline int sock_map_link_create(const union bpf_attr *attr, struct bpf_prog *prog)
3765 {
3766 	return -EOPNOTSUPP;
3767 }
3768 #endif /* CONFIG_BPF_SYSCALL */
3769 #endif /* CONFIG_NET && CONFIG_BPF_SYSCALL */
3770 
3771 static __always_inline void
3772 bpf_prog_inc_misses_counters(const struct bpf_prog_array *array)
3773 {
3774 	const struct bpf_prog_array_item *item;
3775 	struct bpf_prog *prog;
3776 
3777 	if (unlikely(!array))
3778 		return;
3779 
3780 	item = &array->items[0];
3781 	while ((prog = READ_ONCE(item->prog))) {
3782 		bpf_prog_inc_misses_counter(prog);
3783 		item++;
3784 	}
3785 }
3786 
3787 #if defined(CONFIG_INET) && defined(CONFIG_BPF_SYSCALL)
3788 void bpf_sk_reuseport_detach(struct sock *sk);
3789 int bpf_fd_reuseport_array_lookup_elem(struct bpf_map *map, void *key,
3790 				       void *value);
3791 int bpf_fd_reuseport_array_update_elem(struct bpf_map *map, void *key,
3792 				       void *value, u64 map_flags);
3793 #else
3794 static inline void bpf_sk_reuseport_detach(struct sock *sk)
3795 {
3796 }
3797 
3798 #ifdef CONFIG_BPF_SYSCALL
3799 static inline int bpf_fd_reuseport_array_lookup_elem(struct bpf_map *map,
3800 						     void *key, void *value)
3801 {
3802 	return -EOPNOTSUPP;
3803 }
3804 
3805 static inline int bpf_fd_reuseport_array_update_elem(struct bpf_map *map,
3806 						     void *key, void *value,
3807 						     u64 map_flags)
3808 {
3809 	return -EOPNOTSUPP;
3810 }
3811 #endif /* CONFIG_BPF_SYSCALL */
3812 #endif /* defined(CONFIG_INET) && defined(CONFIG_BPF_SYSCALL) */
3813 
3814 #ifdef CONFIG_KEYS
3815 struct bpf_key {
3816 	struct key *key;
3817 	bool has_ref;
3818 };
3819 #endif /* CONFIG_KEYS */
3820 
3821 #if defined(CONFIG_KEYS) && defined(CONFIG_BPF_SYSCALL)
3822 struct bpf_key *bpf_lookup_user_key(s32 serial, u64 flags);
3823 struct bpf_key *bpf_lookup_system_key(u64 id);
3824 void bpf_key_put(struct bpf_key *bkey);
3825 int bpf_verify_pkcs7_signature(const struct bpf_dynptr *data_p,
3826 			       const struct bpf_dynptr *sig_p,
3827 			       struct bpf_key *trusted_keyring);
3828 
3829 static inline s32 bpf_key_serial(const struct bpf_key *key)
3830 {
3831 	return key->has_ref ? key->key->serial : 0;
3832 }
3833 #else
3834 static inline struct bpf_key *bpf_lookup_user_key(u32 serial, u64 flags)
3835 {
3836 	return NULL;
3837 }
3838 
3839 static inline struct bpf_key *bpf_lookup_system_key(u64 id)
3840 {
3841 	return NULL;
3842 }
3843 
3844 static inline void bpf_key_put(struct bpf_key *bkey)
3845 {
3846 }
3847 
3848 static inline int bpf_verify_pkcs7_signature(const struct bpf_dynptr *data_p,
3849 					     const struct bpf_dynptr *sig_p,
3850 					     struct bpf_key *trusted_keyring)
3851 {
3852 	return -EOPNOTSUPP;
3853 }
3854 
3855 static inline s32 bpf_key_serial(const struct bpf_key *key)
3856 {
3857 	return 0;
3858 }
3859 #endif /* defined(CONFIG_KEYS) && defined(CONFIG_BPF_SYSCALL) */
3860 
3861 /* verifier prototypes for helper functions called from eBPF programs */
3862 extern const struct bpf_func_proto bpf_map_lookup_elem_proto;
3863 extern const struct bpf_func_proto bpf_map_update_elem_proto;
3864 extern const struct bpf_func_proto bpf_map_delete_elem_proto;
3865 extern const struct bpf_func_proto bpf_map_push_elem_proto;
3866 extern const struct bpf_func_proto bpf_map_pop_elem_proto;
3867 extern const struct bpf_func_proto bpf_map_peek_elem_proto;
3868 extern const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto;
3869 
3870 extern const struct bpf_func_proto bpf_get_prandom_u32_proto;
3871 extern const struct bpf_func_proto bpf_get_smp_processor_id_proto;
3872 extern const struct bpf_func_proto bpf_get_numa_node_id_proto;
3873 extern const struct bpf_func_proto bpf_tail_call_proto;
3874 extern const struct bpf_func_proto bpf_ktime_get_ns_proto;
3875 extern const struct bpf_func_proto bpf_ktime_get_boot_ns_proto;
3876 extern const struct bpf_func_proto bpf_ktime_get_tai_ns_proto;
3877 extern const struct bpf_func_proto bpf_get_current_pid_tgid_proto;
3878 extern const struct bpf_func_proto bpf_get_current_uid_gid_proto;
3879 extern const struct bpf_func_proto bpf_get_current_comm_proto;
3880 extern const struct bpf_func_proto bpf_get_stackid_proto;
3881 extern const struct bpf_func_proto bpf_get_stack_proto;
3882 extern const struct bpf_func_proto bpf_get_stack_sleepable_proto;
3883 extern const struct bpf_func_proto bpf_get_task_stack_proto;
3884 extern const struct bpf_func_proto bpf_get_task_stack_sleepable_proto;
3885 extern const struct bpf_func_proto bpf_get_stackid_proto_pe;
3886 extern const struct bpf_func_proto bpf_get_stack_proto_pe;
3887 extern const struct bpf_func_proto bpf_sock_map_update_proto;
3888 extern const struct bpf_func_proto bpf_sock_hash_update_proto;
3889 extern const struct bpf_func_proto bpf_get_current_cgroup_id_proto;
3890 extern const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto;
3891 extern const struct bpf_func_proto bpf_get_cgroup_classid_curr_proto;
3892 extern const struct bpf_func_proto bpf_current_task_under_cgroup_proto;
3893 extern const struct bpf_func_proto bpf_msg_redirect_hash_proto;
3894 extern const struct bpf_func_proto bpf_msg_redirect_map_proto;
3895 extern const struct bpf_func_proto bpf_sk_redirect_hash_proto;
3896 extern const struct bpf_func_proto bpf_sk_redirect_map_proto;
3897 extern const struct bpf_func_proto bpf_spin_lock_proto;
3898 extern const struct bpf_func_proto bpf_spin_unlock_proto;
3899 extern const struct bpf_func_proto bpf_get_local_storage_proto;
3900 extern const struct bpf_func_proto bpf_strtol_proto;
3901 extern const struct bpf_func_proto bpf_strtoul_proto;
3902 extern const struct bpf_func_proto bpf_tcp_sock_proto;
3903 extern const struct bpf_func_proto bpf_jiffies64_proto;
3904 extern const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto;
3905 extern const struct bpf_func_proto bpf_event_output_data_proto;
3906 extern const struct bpf_func_proto bpf_ringbuf_output_proto;
3907 extern const struct bpf_func_proto bpf_ringbuf_reserve_proto;
3908 extern const struct bpf_func_proto bpf_ringbuf_submit_proto;
3909 extern const struct bpf_func_proto bpf_ringbuf_discard_proto;
3910 extern const struct bpf_func_proto bpf_ringbuf_query_proto;
3911 extern const struct bpf_func_proto bpf_ringbuf_reserve_dynptr_proto;
3912 extern const struct bpf_func_proto bpf_ringbuf_submit_dynptr_proto;
3913 extern const struct bpf_func_proto bpf_ringbuf_discard_dynptr_proto;
3914 extern const struct bpf_func_proto bpf_skc_to_tcp6_sock_proto;
3915 extern const struct bpf_func_proto bpf_skc_to_tcp_sock_proto;
3916 extern const struct bpf_func_proto bpf_skc_to_tcp_timewait_sock_proto;
3917 extern const struct bpf_func_proto bpf_skc_to_tcp_request_sock_proto;
3918 extern const struct bpf_func_proto bpf_skc_to_udp6_sock_proto;
3919 extern const struct bpf_func_proto bpf_skc_to_unix_sock_proto;
3920 extern const struct bpf_func_proto bpf_skc_to_mptcp_sock_proto;
3921 extern const struct bpf_func_proto bpf_copy_from_user_proto;
3922 extern const struct bpf_func_proto bpf_snprintf_btf_proto;
3923 extern const struct bpf_func_proto bpf_snprintf_proto;
3924 extern const struct bpf_func_proto bpf_per_cpu_ptr_proto;
3925 extern const struct bpf_func_proto bpf_this_cpu_ptr_proto;
3926 extern const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto;
3927 extern const struct bpf_func_proto bpf_sock_from_file_proto;
3928 extern const struct bpf_func_proto bpf_get_socket_ptr_cookie_proto;
3929 extern const struct bpf_func_proto bpf_task_storage_get_recur_proto;
3930 extern const struct bpf_func_proto bpf_task_storage_get_proto;
3931 extern const struct bpf_func_proto bpf_task_storage_delete_recur_proto;
3932 extern const struct bpf_func_proto bpf_task_storage_delete_proto;
3933 extern const struct bpf_func_proto bpf_for_each_map_elem_proto;
3934 extern const struct bpf_func_proto bpf_btf_find_by_name_kind_proto;
3935 extern const struct bpf_func_proto bpf_sk_setsockopt_proto;
3936 extern const struct bpf_func_proto bpf_sk_getsockopt_proto;
3937 extern const struct bpf_func_proto bpf_sk_setsockopt_nodelay_proto;
3938 extern const struct bpf_func_proto bpf_unlocked_sk_setsockopt_proto;
3939 extern const struct bpf_func_proto bpf_unlocked_sk_getsockopt_proto;
3940 extern const struct bpf_func_proto bpf_find_vma_proto;
3941 extern const struct bpf_func_proto bpf_loop_proto;
3942 extern const struct bpf_func_proto bpf_copy_from_user_task_proto;
3943 extern const struct bpf_func_proto bpf_set_retval_proto;
3944 extern const struct bpf_func_proto bpf_get_retval_proto;
3945 extern const struct bpf_func_proto bpf_user_ringbuf_drain_proto;
3946 extern const struct bpf_func_proto bpf_cgrp_storage_get_proto;
3947 extern const struct bpf_func_proto bpf_cgrp_storage_delete_proto;
3948 
3949 const struct bpf_func_proto *tracing_prog_func_proto(
3950   enum bpf_func_id func_id, const struct bpf_prog *prog);
3951 
3952 /* Shared helpers among cBPF and eBPF. */
3953 void bpf_user_rnd_init_once(void);
3954 u64 bpf_user_rnd_u32(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
3955 u64 bpf_get_raw_cpu_id(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5);
3956 
3957 #if defined(CONFIG_NET)
3958 bool bpf_sock_common_is_valid_access(int off, int size,
3959 				     enum bpf_access_type type,
3960 				     struct bpf_insn_access_aux *info);
3961 bool bpf_sock_is_valid_access(int off, int size, enum bpf_access_type type,
3962 			      struct bpf_insn_access_aux *info);
3963 u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
3964 				const struct bpf_insn *si,
3965 				struct bpf_insn *insn_buf,
3966 				struct bpf_prog *prog,
3967 				u32 *target_size);
3968 int bpf_dynptr_from_skb_rdonly(struct __sk_buff *skb, u64 flags,
3969 			       struct bpf_dynptr *ptr);
3970 #else
3971 static inline bool bpf_sock_common_is_valid_access(int off, int size,
3972 						   enum bpf_access_type type,
3973 						   struct bpf_insn_access_aux *info)
3974 {
3975 	return false;
3976 }
3977 static inline bool bpf_sock_is_valid_access(int off, int size,
3978 					    enum bpf_access_type type,
3979 					    struct bpf_insn_access_aux *info)
3980 {
3981 	return false;
3982 }
3983 static inline u32 bpf_sock_convert_ctx_access(enum bpf_access_type type,
3984 					      const struct bpf_insn *si,
3985 					      struct bpf_insn *insn_buf,
3986 					      struct bpf_prog *prog,
3987 					      u32 *target_size)
3988 {
3989 	return 0;
3990 }
3991 static inline int bpf_dynptr_from_skb_rdonly(struct __sk_buff *skb, u64 flags,
3992 					     struct bpf_dynptr *ptr)
3993 {
3994 	return -EOPNOTSUPP;
3995 }
3996 #endif
3997 
3998 #ifdef CONFIG_INET
3999 struct sk_reuseport_kern {
4000 	struct sk_buff *skb;
4001 	struct sock *sk;
4002 	struct sock *selected_sk;
4003 	struct sock *migrating_sk;
4004 	void *data_end;
4005 	u32 hash;
4006 	u32 reuseport_id;
4007 	bool bind_inany;
4008 };
4009 bool bpf_tcp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
4010 				  struct bpf_insn_access_aux *info);
4011 
4012 u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
4013 				    const struct bpf_insn *si,
4014 				    struct bpf_insn *insn_buf,
4015 				    struct bpf_prog *prog,
4016 				    u32 *target_size);
4017 
4018 bool bpf_xdp_sock_is_valid_access(int off, int size, enum bpf_access_type type,
4019 				  struct bpf_insn_access_aux *info);
4020 
4021 u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
4022 				    const struct bpf_insn *si,
4023 				    struct bpf_insn *insn_buf,
4024 				    struct bpf_prog *prog,
4025 				    u32 *target_size);
4026 #else
4027 static inline bool bpf_tcp_sock_is_valid_access(int off, int size,
4028 						enum bpf_access_type type,
4029 						struct bpf_insn_access_aux *info)
4030 {
4031 	return false;
4032 }
4033 
4034 static inline u32 bpf_tcp_sock_convert_ctx_access(enum bpf_access_type type,
4035 						  const struct bpf_insn *si,
4036 						  struct bpf_insn *insn_buf,
4037 						  struct bpf_prog *prog,
4038 						  u32 *target_size)
4039 {
4040 	return 0;
4041 }
4042 static inline bool bpf_xdp_sock_is_valid_access(int off, int size,
4043 						enum bpf_access_type type,
4044 						struct bpf_insn_access_aux *info)
4045 {
4046 	return false;
4047 }
4048 
4049 static inline u32 bpf_xdp_sock_convert_ctx_access(enum bpf_access_type type,
4050 						  const struct bpf_insn *si,
4051 						  struct bpf_insn *insn_buf,
4052 						  struct bpf_prog *prog,
4053 						  u32 *target_size)
4054 {
4055 	return 0;
4056 }
4057 #endif /* CONFIG_INET */
4058 
4059 enum bpf_text_poke_type {
4060 	BPF_MOD_NOP,
4061 	BPF_MOD_CALL,
4062 	BPF_MOD_JUMP,
4063 };
4064 
4065 int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t,
4066 		       enum bpf_text_poke_type new_t, void *old_addr,
4067 		       void *new_addr);
4068 
4069 void bpf_arch_poke_desc_update(struct bpf_jit_poke_descriptor *poke,
4070 			       struct bpf_prog *new, struct bpf_prog *old);
4071 
4072 void *bpf_arch_text_copy(void *dst, void *src, size_t len);
4073 int bpf_arch_text_invalidate(void *dst, size_t len);
4074 
4075 struct btf_id_set;
4076 bool btf_id_set_contains(const struct btf_id_set *set, u32 id);
4077 
4078 #define MAX_BPRINTF_VARARGS		12
4079 #define MAX_BPRINTF_BUF			1024
4080 
4081 /* Per-cpu temp buffers used by printf-like helpers to store the bprintf binary
4082  * arguments representation.
4083  */
4084 #define MAX_BPRINTF_BIN_ARGS	512
4085 
4086 struct bpf_bprintf_buffers {
4087 	char bin_args[MAX_BPRINTF_BIN_ARGS];
4088 	char buf[MAX_BPRINTF_BUF];
4089 };
4090 
4091 struct bpf_bprintf_data {
4092 	u32 *bin_args;
4093 	char *buf;
4094 	bool get_bin_args;
4095 	bool get_buf;
4096 };
4097 
4098 int bpf_bprintf_prepare(const char *fmt, u32 fmt_size, const u64 *raw_args,
4099 			u32 num_args, struct bpf_bprintf_data *data);
4100 void bpf_bprintf_cleanup(struct bpf_bprintf_data *data);
4101 int bpf_try_get_buffers(struct bpf_bprintf_buffers **bufs);
4102 void bpf_put_buffers(void);
4103 
4104 void bpf_prog_stream_init(struct bpf_prog *prog);
4105 void bpf_prog_stream_free(struct bpf_prog *prog);
4106 int bpf_prog_stream_read(struct bpf_prog *prog, enum bpf_stream_id stream_id, void __user *buf, int len);
4107 void bpf_stream_stage_init(struct bpf_stream_stage *ss);
4108 void bpf_stream_stage_free(struct bpf_stream_stage *ss);
4109 __printf(2, 3)
4110 int bpf_stream_stage_printk(struct bpf_stream_stage *ss, const char *fmt, ...);
4111 int bpf_stream_stage_commit(struct bpf_stream_stage *ss, struct bpf_prog *prog,
4112 			    enum bpf_stream_id stream_id);
4113 int bpf_stream_stage_dump_stack(struct bpf_stream_stage *ss);
4114 
4115 #define bpf_stream_printk(ss, ...) bpf_stream_stage_printk(&ss, __VA_ARGS__)
4116 #define bpf_stream_dump_stack(ss) bpf_stream_stage_dump_stack(&ss)
4117 
4118 #define bpf_stream_stage(ss, prog, stream_id, expr)            \
4119 	({                                                     \
4120 		bpf_stream_stage_init(&ss);                    \
4121 		(expr);                                        \
4122 		bpf_stream_stage_commit(&ss, prog, stream_id); \
4123 		bpf_stream_stage_free(&ss);                    \
4124 	})
4125 
4126 #ifdef CONFIG_BPF_LSM
4127 void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype);
4128 void bpf_cgroup_atype_put(int cgroup_atype);
4129 #else
4130 static inline void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype) {}
4131 static inline void bpf_cgroup_atype_put(int cgroup_atype) {}
4132 #endif /* CONFIG_BPF_LSM */
4133 
4134 static inline bool type_is_alloc(u32 type)
4135 {
4136 	return type & MEM_ALLOC;
4137 }
4138 
4139 static inline gfp_t bpf_memcg_flags(gfp_t flags)
4140 {
4141 	if (memcg_bpf_enabled())
4142 		return flags | __GFP_ACCOUNT;
4143 	return flags;
4144 }
4145 
4146 static inline bool bpf_is_subprog(const struct bpf_prog *prog)
4147 {
4148 	return prog->aux->func_idx != 0;
4149 }
4150 
4151 const struct bpf_line_info *bpf_find_linfo(const struct bpf_prog *prog, u32 insn_off);
4152 struct bpf_linfo_source {
4153 	const char *file;
4154 	const char *line;
4155 	u32 file_name_off;
4156 	int line_num;
4157 	int line_col;
4158 };
4159 
4160 void bpf_get_linfo_source(struct btf *btf, const struct bpf_line_info *linfo,
4161 			  struct bpf_linfo_source *src);
4162 int bpf_prog_get_file_line(struct bpf_prog *prog, unsigned long ip, const char **filep,
4163 			   const char **linep, int *nump);
4164 struct bpf_prog *bpf_prog_find_from_stack(void);
4165 
4166 int bpf_insn_array_init(struct bpf_map *map, const struct bpf_prog *prog);
4167 int bpf_insn_array_ready(struct bpf_map *map);
4168 void bpf_insn_array_release(struct bpf_map *map);
4169 void bpf_insn_array_adjust(struct bpf_map *map, u32 off, u32 len);
4170 void bpf_insn_array_adjust_after_remove(struct bpf_map *map, u32 off, u32 len);
4171 
4172 #ifdef CONFIG_BPF_SYSCALL
4173 void bpf_prog_update_insn_ptrs(struct bpf_prog *prog, u32 *offsets, void *image);
4174 #else
4175 static inline void
4176 bpf_prog_update_insn_ptrs(struct bpf_prog *prog, u32 *offsets, void *image)
4177 {
4178 }
4179 #endif
4180 
4181 static inline bool bpf_map_is_percpu_map(enum bpf_map_type map_type)
4182 {
4183 	switch (map_type) {
4184 	case BPF_MAP_TYPE_PERCPU_ARRAY:
4185 	case BPF_MAP_TYPE_PERCPU_HASH:
4186 	case BPF_MAP_TYPE_LRU_PERCPU_HASH:
4187 	case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE:
4188 		return true;
4189 	default:
4190 		return false;
4191 	}
4192 }
4193 
4194 static inline int bpf_map_check_op_flags(struct bpf_map *map, u64 flags, u64 allowed_flags)
4195 {
4196 	u32 cpu;
4197 
4198 	if ((u32)flags & ~allowed_flags)
4199 		return -EINVAL;
4200 
4201 	if ((flags & BPF_F_LOCK) && !btf_record_has_field(map->record, BPF_SPIN_LOCK))
4202 		return -EINVAL;
4203 
4204 	if (!(flags & BPF_F_CPU) && flags >> 32)
4205 		return -EINVAL;
4206 
4207 	if (flags & (BPF_F_CPU | BPF_F_ALL_CPUS)) {
4208 		if (!bpf_map_is_percpu_map(map->map_type))
4209 			return -EINVAL;
4210 		if ((flags & BPF_F_CPU) && (flags & BPF_F_ALL_CPUS))
4211 			return -EINVAL;
4212 
4213 		cpu = flags >> 32;
4214 		if ((flags & BPF_F_CPU) && (cpu >= nr_cpu_ids || !cpu_possible(cpu)))
4215 			return -ERANGE;
4216 	}
4217 
4218 	return 0;
4219 }
4220 
4221 #endif /* _LINUX_BPF_H */
4222