xref: /linux/kernel/bpf/btf.c (revision 7efe1d4e11395e31c49122f0052b57f0513c7e83)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2018 Facebook */
3 
4 #include <uapi/linux/btf.h>
5 #include <uapi/linux/bpf.h>
6 #include <uapi/linux/bpf_perf_event.h>
7 #include <uapi/linux/types.h>
8 #include <linux/seq_file.h>
9 #include <linux/compiler.h>
10 #include <linux/ctype.h>
11 #include <linux/errno.h>
12 #include <linux/slab.h>
13 #include <linux/anon_inodes.h>
14 #include <linux/file.h>
15 #include <linux/uaccess.h>
16 #include <linux/kernel.h>
17 #include <linux/idr.h>
18 #include <linux/sort.h>
19 #include <linux/bpf_verifier.h>
20 #include <linux/btf.h>
21 #include <linux/btf_ids.h>
22 #include <linux/bpf.h>
23 #include <linux/bpf-cgroup.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/skmsg.h>
26 #include <linux/perf_event.h>
27 #include <linux/bsearch.h>
28 #include <linux/string.h>
29 #include <linux/overflow.h>
30 #include <linux/bitops.h>
31 #include <linux/unaligned.h>
32 #include <linux/vmalloc.h>
33 #include <crypto/sha2.h>
34 
35 #include <net/netfilter/nf_bpf_link.h>
36 
37 #include <net/sock.h>
38 #include <net/xdp.h>
39 #include "../tools/lib/bpf/relo_core.h"
40 
41 /* BTF (BPF Type Format) is the meta data format which describes
42  * the data types of BPF program/map.  Hence, it basically focus
43  * on the C programming language which the modern BPF is primary
44  * using.
45  *
46  * ELF Section:
47  * ~~~~~~~~~~~
48  * The BTF data is stored under the ".BTF" ELF section
49  *
50  * struct btf_type:
51  * ~~~~~~~~~~~~~~~
52  * Each 'struct btf_type' object describes a C data type.
53  * Depending on the type it is describing, a 'struct btf_type'
54  * object may be followed by more data.  F.e.
55  * To describe an array, 'struct btf_type' is followed by
56  * 'struct btf_array'.
57  *
58  * 'struct btf_type' and any extra data following it are
59  * 4 bytes aligned.
60  *
61  * Type section:
62  * ~~~~~~~~~~~~~
63  * The BTF type section contains a list of 'struct btf_type' objects.
64  * Each one describes a C type.  Recall from the above section
65  * that a 'struct btf_type' object could be immediately followed by extra
66  * data in order to describe some particular C types.
67  *
68  * type_id:
69  * ~~~~~~~
70  * Each btf_type object is identified by a type_id.  The type_id
71  * is implicitly implied by the location of the btf_type object in
72  * the BTF type section.  The first one has type_id 1.  The second
73  * one has type_id 2...etc.  Hence, an earlier btf_type has
74  * a smaller type_id.
75  *
76  * A btf_type object may refer to another btf_type object by using
77  * type_id (i.e. the "type" in the "struct btf_type").
78  *
79  * NOTE that we cannot assume any reference-order.
80  * A btf_type object can refer to an earlier btf_type object
81  * but it can also refer to a later btf_type object.
82  *
83  * For example, to describe "const void *".  A btf_type
84  * object describing "const" may refer to another btf_type
85  * object describing "void *".  This type-reference is done
86  * by specifying type_id:
87  *
88  * [1] CONST (anon) type_id=2
89  * [2] PTR (anon) type_id=0
90  *
91  * The above is the btf_verifier debug log:
92  *   - Each line started with "[?]" is a btf_type object
93  *   - [?] is the type_id of the btf_type object.
94  *   - CONST/PTR is the BTF_KIND_XXX
95  *   - "(anon)" is the name of the type.  It just
96  *     happens that CONST and PTR has no name.
97  *   - type_id=XXX is the 'u32 type' in btf_type
98  *
99  * NOTE: "void" has type_id 0
100  *
101  * String section:
102  * ~~~~~~~~~~~~~~
103  * The BTF string section contains the names used by the type section.
104  * Each string is referred by an "offset" from the beginning of the
105  * string section.
106  *
107  * Each string is '\0' terminated.
108  *
109  * The first character in the string section must be '\0'
110  * which is used to mean 'anonymous'. Some btf_type may not
111  * have a name.
112  */
113 
114 /* BTF verification:
115  *
116  * To verify BTF data, two passes are needed.
117  *
118  * Pass #1
119  * ~~~~~~~
120  * The first pass is to collect all btf_type objects to
121  * an array: "btf->types".
122  *
123  * Depending on the C type that a btf_type is describing,
124  * a btf_type may be followed by extra data.  We don't know
125  * how many btf_type is there, and more importantly we don't
126  * know where each btf_type is located in the type section.
127  *
128  * Without knowing the location of each type_id, most verifications
129  * cannot be done.  e.g. an earlier btf_type may refer to a later
130  * btf_type (recall the "const void *" above), so we cannot
131  * check this type-reference in the first pass.
132  *
133  * In the first pass, it still does some verifications (e.g.
134  * checking the name is a valid offset to the string section).
135  *
136  * Pass #2
137  * ~~~~~~~
138  * The main focus is to resolve a btf_type that is referring
139  * to another type.
140  *
141  * We have to ensure the referring type:
142  * 1) does exist in the BTF (i.e. in btf->types[])
143  * 2) does not cause a loop:
144  *	struct A {
145  *		struct B b;
146  *	};
147  *
148  *	struct B {
149  *		struct A a;
150  *	};
151  *
152  * btf_type_needs_resolve() decides if a btf_type needs
153  * to be resolved.
154  *
155  * The needs_resolve type implements the "resolve()" ops which
156  * essentially does a DFS and detects backedge.
157  *
158  * During resolve (or DFS), different C types have different
159  * "RESOLVED" conditions.
160  *
161  * When resolving a BTF_KIND_STRUCT, we need to resolve all its
162  * members because a member is always referring to another
163  * type.  A struct's member can be treated as "RESOLVED" if
164  * it is referring to a BTF_KIND_PTR.  Otherwise, the
165  * following valid C struct would be rejected:
166  *
167  *	struct A {
168  *		int m;
169  *		struct A *a;
170  *	};
171  *
172  * When resolving a BTF_KIND_PTR, it needs to keep resolving if
173  * it is referring to another BTF_KIND_PTR.  Otherwise, we cannot
174  * detect a pointer loop, e.g.:
175  * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
176  *                        ^                                         |
177  *                        +-----------------------------------------+
178  *
179  */
180 
181 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
182 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
183 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
184 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
185 #define BITS_ROUNDUP_BYTES(bits) \
186 	(BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
187 
188 #define BTF_INT_MASK 0x0fffffff
189 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
190 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
191 
192 /* 16MB for 64k structs and each has 16 members and
193  * a few MB spaces for the string section.
194  * The hard limit is S32_MAX.
195  */
196 #define BTF_MAX_SIZE (16 * 1024 * 1024)
197 
198 #define for_each_member_from(i, from, struct_type, member)		\
199 	for (i = from, member = btf_type_member(struct_type) + from;	\
200 	     i < btf_type_vlen(struct_type);				\
201 	     i++, member++)
202 
203 #define for_each_vsi_from(i, from, struct_type, member)				\
204 	for (i = from, member = btf_type_var_secinfo(struct_type) + from;	\
205 	     i < btf_type_vlen(struct_type);					\
206 	     i++, member++)
207 
208 DEFINE_IDR(btf_idr);
209 DEFINE_SPINLOCK(btf_idr_lock);
210 
211 enum btf_kfunc_hook {
212 	BTF_KFUNC_HOOK_COMMON,
213 	BTF_KFUNC_HOOK_XDP,
214 	BTF_KFUNC_HOOK_TC,
215 	BTF_KFUNC_HOOK_STRUCT_OPS,
216 	BTF_KFUNC_HOOK_TRACING,
217 	BTF_KFUNC_HOOK_SYSCALL,
218 	BTF_KFUNC_HOOK_FMODRET,
219 	BTF_KFUNC_HOOK_CGROUP,
220 	BTF_KFUNC_HOOK_SCHED_ACT,
221 	BTF_KFUNC_HOOK_SK_SKB,
222 	BTF_KFUNC_HOOK_SOCKET_FILTER,
223 	BTF_KFUNC_HOOK_LWT,
224 	BTF_KFUNC_HOOK_NETFILTER,
225 	BTF_KFUNC_HOOK_KPROBE,
226 	BTF_KFUNC_HOOK_MAX,
227 };
228 
229 enum {
230 	BTF_KFUNC_SET_MAX_CNT = 256,
231 	BTF_DTOR_KFUNC_MAX_CNT = 256,
232 	BTF_KFUNC_FILTER_MAX_CNT = 16,
233 };
234 
235 struct btf_kfunc_hook_filter {
236 	btf_kfunc_filter_t filters[BTF_KFUNC_FILTER_MAX_CNT];
237 	u32 nr_filters;
238 };
239 
240 struct btf_kfunc_set_tab {
241 	struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
242 	struct btf_kfunc_hook_filter hook_filters[BTF_KFUNC_HOOK_MAX];
243 };
244 
245 struct btf_id_dtor_kfunc_tab {
246 	u32 cnt;
247 	struct btf_id_dtor_kfunc dtors[];
248 };
249 
250 struct btf_struct_ops_tab {
251 	u32 cnt;
252 	u32 capacity;
253 	struct bpf_struct_ops_desc ops[];
254 };
255 
256 struct btf {
257 	void *data;
258 	struct btf_type **types;
259 	u32 *resolved_ids;
260 	u32 *resolved_sizes;
261 	const char *strings;
262 	void *nohdr_data;
263 	struct btf_header hdr;
264 	u32 nr_types; /* includes VOID for base BTF */
265 	u32 named_start_id;
266 	u32 types_size;
267 	u32 data_size;
268 	refcount_t refcnt;
269 	u32 id;
270 	struct rcu_head rcu;
271 	struct btf_kfunc_set_tab *kfunc_set_tab;
272 	struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
273 	struct btf_struct_metas *struct_meta_tab;
274 	struct btf_struct_ops_tab *struct_ops_tab;
275 	struct btf_layout *layout;
276 
277 	/* split BTF support */
278 	struct btf *base_btf;
279 	u32 start_id; /* first type ID in this BTF (0 for base BTF) */
280 	u32 start_str_off; /* first string offset (0 for base BTF) */
281 	char name[MODULE_NAME_LEN];
282 	bool kernel_btf;
283 	__u32 *base_id_map; /* map from distilled base BTF -> vmlinux BTF ids */
284 };
285 
286 enum verifier_phase {
287 	CHECK_META,
288 	CHECK_TYPE,
289 };
290 
291 struct resolve_vertex {
292 	const struct btf_type *t;
293 	u32 type_id;
294 	u32 next_member;
295 };
296 
297 enum visit_state {
298 	NOT_VISITED,
299 	VISITED,
300 	RESOLVED,
301 };
302 
303 enum resolve_mode {
304 	RESOLVE_TBD,	/* To Be Determined */
305 	RESOLVE_PTR,	/* Resolving for Pointer */
306 	RESOLVE_STRUCT_OR_ARRAY,	/* Resolving for struct/union
307 					 * or array
308 					 */
309 };
310 
311 #define MAX_RESOLVE_DEPTH 32
312 
313 struct btf_sec_info {
314 	u32 off;
315 	u32 len;
316 };
317 
318 struct btf_verifier_env {
319 	struct btf *btf;
320 	u8 *visit_states;
321 	struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
322 	struct bpf_verifier_log log;
323 	u32 log_type_id;
324 	u32 top_stack;
325 	enum verifier_phase phase;
326 	enum resolve_mode resolve_mode;
327 };
328 
329 static const char * const btf_kind_str[NR_BTF_KINDS] = {
330 	[BTF_KIND_UNKN]		= "UNKNOWN",
331 	[BTF_KIND_INT]		= "INT",
332 	[BTF_KIND_PTR]		= "PTR",
333 	[BTF_KIND_ARRAY]	= "ARRAY",
334 	[BTF_KIND_STRUCT]	= "STRUCT",
335 	[BTF_KIND_UNION]	= "UNION",
336 	[BTF_KIND_ENUM]		= "ENUM",
337 	[BTF_KIND_FWD]		= "FWD",
338 	[BTF_KIND_TYPEDEF]	= "TYPEDEF",
339 	[BTF_KIND_VOLATILE]	= "VOLATILE",
340 	[BTF_KIND_CONST]	= "CONST",
341 	[BTF_KIND_RESTRICT]	= "RESTRICT",
342 	[BTF_KIND_FUNC]		= "FUNC",
343 	[BTF_KIND_FUNC_PROTO]	= "FUNC_PROTO",
344 	[BTF_KIND_VAR]		= "VAR",
345 	[BTF_KIND_DATASEC]	= "DATASEC",
346 	[BTF_KIND_FLOAT]	= "FLOAT",
347 	[BTF_KIND_DECL_TAG]	= "DECL_TAG",
348 	[BTF_KIND_TYPE_TAG]	= "TYPE_TAG",
349 	[BTF_KIND_ENUM64]	= "ENUM64",
350 	[BTF_KIND_LOC_PARAM]	= "LOC_PARAM",
351 	[BTF_KIND_LOC_PROTO]	= "LOC_PROTO",
352 	[BTF_KIND_LOCSEC]	= "LOCSEC",
353 };
354 
355 const char *btf_type_str(const struct btf_type *t)
356 {
357 	return btf_kind_str[BTF_INFO_KIND(t->info)];
358 }
359 
360 /* Chunk size we use in safe copy of data to be shown. */
361 #define BTF_SHOW_OBJ_SAFE_SIZE		32
362 
363 /*
364  * This is the maximum size of a base type value (equivalent to a
365  * 128-bit int); if we are at the end of our safe buffer and have
366  * less than 16 bytes space we can't be assured of being able
367  * to copy the next type safely, so in such cases we will initiate
368  * a new copy.
369  */
370 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE	16
371 
372 /* Type name size */
373 #define BTF_SHOW_NAME_SIZE		80
374 
375 /*
376  * The suffix of a type that indicates it cannot alias another type when
377  * comparing BTF IDs for kfunc invocations.
378  */
379 #define NOCAST_ALIAS_SUFFIX		"___init"
380 
381 /*
382  * Common data to all BTF show operations. Private show functions can add
383  * their own data to a structure containing a struct btf_show and consult it
384  * in the show callback.  See btf_type_show() below.
385  *
386  * One challenge with showing nested data is we want to skip 0-valued
387  * data, but in order to figure out whether a nested object is all zeros
388  * we need to walk through it.  As a result, we need to make two passes
389  * when handling structs, unions and arrays; the first path simply looks
390  * for nonzero data, while the second actually does the display.  The first
391  * pass is signalled by show->state.depth_check being set, and if we
392  * encounter a non-zero value we set show->state.depth_to_show to
393  * the depth at which we encountered it.  When we have completed the
394  * first pass, we will know if anything needs to be displayed if
395  * depth_to_show > depth.  See btf_[struct,array]_show() for the
396  * implementation of this.
397  *
398  * Another problem is we want to ensure the data for display is safe to
399  * access.  To support this, the anonymous "struct {} obj" tracks the data
400  * object and our safe copy of it.  We copy portions of the data needed
401  * to the object "copy" buffer, but because its size is limited to
402  * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
403  * traverse larger objects for display.
404  *
405  * The various data type show functions all start with a call to
406  * btf_show_start_type() which returns a pointer to the safe copy
407  * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
408  * raw data itself).  btf_show_obj_safe() is responsible for
409  * using copy_from_kernel_nofault() to update the safe data if necessary
410  * as we traverse the object's data.  skbuff-like semantics are
411  * used:
412  *
413  * - obj.head points to the start of the toplevel object for display
414  * - obj.size is the size of the toplevel object
415  * - obj.data points to the current point in the original data at
416  *   which our safe data starts.  obj.data will advance as we copy
417  *   portions of the data.
418  *
419  * In most cases a single copy will suffice, but larger data structures
420  * such as "struct task_struct" will require many copies.  The logic in
421  * btf_show_obj_safe() handles the logic that determines if a new
422  * copy_from_kernel_nofault() is needed.
423  */
424 struct btf_show {
425 	u64 flags;
426 	void *target;	/* target of show operation (seq file, buffer) */
427 	__printf(2, 0) void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
428 	const struct btf *btf;
429 	/* below are used during iteration */
430 	struct {
431 		u8 depth;
432 		u8 depth_to_show;
433 		u8 depth_check;
434 		u8 array_member:1,
435 		   array_terminated:1;
436 		u16 array_encoding;
437 		u32 type_id;
438 		int status;			/* non-zero for error */
439 		const struct btf_type *type;
440 		const struct btf_member *member;
441 		char name[BTF_SHOW_NAME_SIZE];	/* space for member name/type */
442 	} state;
443 	struct {
444 		u32 size;
445 		void *head;
446 		void *data;
447 		u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
448 	} obj;
449 };
450 
451 struct btf_kind_operations {
452 	s32 (*check_meta)(struct btf_verifier_env *env,
453 			  const struct btf_type *t,
454 			  u32 meta_left);
455 	int (*resolve)(struct btf_verifier_env *env,
456 		       const struct resolve_vertex *v);
457 	int (*check_member)(struct btf_verifier_env *env,
458 			    const struct btf_type *struct_type,
459 			    const struct btf_member *member,
460 			    const struct btf_type *member_type);
461 	int (*check_kflag_member)(struct btf_verifier_env *env,
462 				  const struct btf_type *struct_type,
463 				  const struct btf_member *member,
464 				  const struct btf_type *member_type);
465 	void (*log_details)(struct btf_verifier_env *env,
466 			    const struct btf_type *t);
467 	void (*show)(const struct btf *btf, const struct btf_type *t,
468 			 u32 type_id, void *data, u8 bits_offsets,
469 			 struct btf_show *show);
470 };
471 
472 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
473 static struct btf_type btf_void;
474 
475 static int btf_resolve(struct btf_verifier_env *env,
476 		       const struct btf_type *t, u32 type_id);
477 
478 static int btf_func_check(struct btf_verifier_env *env,
479 			  const struct btf_type *t);
480 
481 static bool btf_type_is_modifier(const struct btf_type *t)
482 {
483 	/* Some of them is not strictly a C modifier
484 	 * but they are grouped into the same bucket
485 	 * for BTF concern:
486 	 *   A type (t) that refers to another
487 	 *   type through t->type AND its size cannot
488 	 *   be determined without following the t->type.
489 	 *
490 	 * ptr does not fall into this bucket
491 	 * because its size is always sizeof(void *).
492 	 */
493 	switch (BTF_INFO_KIND(t->info)) {
494 	case BTF_KIND_TYPEDEF:
495 	case BTF_KIND_VOLATILE:
496 	case BTF_KIND_CONST:
497 	case BTF_KIND_RESTRICT:
498 	case BTF_KIND_TYPE_TAG:
499 		return true;
500 	}
501 
502 	return false;
503 }
504 
505 static int btf_start_id(const struct btf *btf)
506 {
507 	return btf->start_id + (btf->base_btf ? 0 : 1);
508 }
509 
510 bool btf_type_is_void(const struct btf_type *t)
511 {
512 	return t == &btf_void;
513 }
514 
515 static bool btf_type_is_datasec(const struct btf_type *t)
516 {
517 	return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
518 }
519 
520 static bool btf_type_is_decl_tag(const struct btf_type *t)
521 {
522 	return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
523 }
524 
525 static bool btf_type_is_loc_param(const struct btf_type *t)
526 {
527 	return BTF_INFO_KIND(t->info) == BTF_KIND_LOC_PARAM;
528 }
529 
530 static bool btf_type_is_loc_proto(const struct btf_type *t)
531 {
532 	return BTF_INFO_KIND(t->info) == BTF_KIND_LOC_PROTO;
533 }
534 
535 static bool btf_type_is_locsec(const struct btf_type *t)
536 {
537 	return BTF_INFO_KIND(t->info) == BTF_KIND_LOCSEC;
538 }
539 
540 static bool btf_type_nosize(const struct btf_type *t)
541 {
542 	return btf_type_is_void(t) || btf_type_is_fwd(t) ||
543 	       btf_type_is_func(t) || btf_type_is_func_proto(t) ||
544 	       btf_type_is_decl_tag(t) || btf_type_is_loc_param(t) ||
545 	       btf_type_is_loc_proto(t) || btf_type_is_locsec(t);
546 }
547 
548 static bool btf_type_nosize_or_null(const struct btf_type *t)
549 {
550 	return !t || btf_type_nosize(t);
551 }
552 
553 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
554 {
555 	return btf_type_is_func(t) || btf_type_is_struct(t) ||
556 	       btf_type_is_var(t) || btf_type_is_typedef(t);
557 }
558 
559 bool btf_is_vmlinux(const struct btf *btf)
560 {
561 	return btf->kernel_btf && !btf->base_btf;
562 }
563 
564 u32 btf_nr_types(const struct btf *btf)
565 {
566 	u32 total = 0;
567 
568 	while (btf) {
569 		total += btf->nr_types;
570 		btf = btf->base_btf;
571 	}
572 
573 	return total;
574 }
575 
576 /*
577  * Note that vmlinux and kernel module BTFs are always sorted
578  * during the building phase.
579  */
580 static void btf_check_sorted(struct btf *btf)
581 {
582 	u32 i, n, named_start_id = 0;
583 
584 	n = btf_nr_types(btf);
585 	if (btf_is_vmlinux(btf)) {
586 		for (i = btf_start_id(btf); i < n; i++) {
587 			const struct btf_type *t = btf_type_by_id(btf, i);
588 			const char *n = btf_name_by_offset(btf, t->name_off);
589 
590 			if (n[0] != '\0') {
591 				btf->named_start_id = i;
592 				return;
593 			}
594 		}
595 		return;
596 	}
597 
598 	for (i = btf_start_id(btf) + 1; i < n; i++) {
599 		const struct btf_type *ta = btf_type_by_id(btf, i - 1);
600 		const struct btf_type *tb = btf_type_by_id(btf, i);
601 		const char *na = btf_name_by_offset(btf, ta->name_off);
602 		const char *nb = btf_name_by_offset(btf, tb->name_off);
603 
604 		if (strcmp(na, nb) > 0)
605 			return;
606 
607 		if (named_start_id == 0 && na[0] != '\0')
608 			named_start_id = i - 1;
609 		if (named_start_id == 0 && nb[0] != '\0')
610 			named_start_id = i;
611 	}
612 
613 	if (named_start_id)
614 		btf->named_start_id = named_start_id;
615 }
616 
617 /*
618  * btf_named_start_id - Get the named starting ID for the BTF
619  * @btf: Pointer to the target BTF object
620  * @own: Flag indicating whether to query only the current BTF (true = current BTF only,
621  *       false = recursively traverse the base BTF chain)
622  *
623  * Return value rules:
624  * 1. For a sorted btf, return its named_start_id
625  * 2. Else for a split BTF, return its start_id
626  * 3. Else for a base BTF, return 1
627  */
628 u32 btf_named_start_id(const struct btf *btf, bool own)
629 {
630 	const struct btf *base_btf = btf;
631 
632 	while (!own && base_btf->base_btf)
633 		base_btf = base_btf->base_btf;
634 
635 	return base_btf->named_start_id ?: (base_btf->start_id ?: 1);
636 }
637 
638 static s32 btf_find_by_name_kind_bsearch(const struct btf *btf, const char *name)
639 {
640 	const struct btf_type *t;
641 	const char *tname;
642 	s32 l, r, m;
643 
644 	l = btf_named_start_id(btf, true);
645 	r = btf_nr_types(btf) - 1;
646 	while (l <= r) {
647 		m = l + (r - l) / 2;
648 		t = btf_type_by_id(btf, m);
649 		tname = btf_name_by_offset(btf, t->name_off);
650 		if (strcmp(tname, name) >= 0) {
651 			if (l == r)
652 				return r;
653 			r = m;
654 		} else {
655 			l = m + 1;
656 		}
657 	}
658 
659 	return btf_nr_types(btf);
660 }
661 
662 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
663 {
664 	const struct btf *base_btf = btf_base_btf(btf);
665 	const struct btf_type *t;
666 	const char *tname;
667 	s32 id, total;
668 
669 	if (base_btf) {
670 		id = btf_find_by_name_kind(base_btf, name, kind);
671 		if (id > 0)
672 			return id;
673 	}
674 
675 	total = btf_nr_types(btf);
676 	if (btf->named_start_id > 0 && name[0]) {
677 		id = btf_find_by_name_kind_bsearch(btf, name);
678 		for (; id < total; id++) {
679 			t = btf_type_by_id(btf, id);
680 			tname = btf_name_by_offset(btf, t->name_off);
681 			if (strcmp(tname, name) != 0)
682 				return -ENOENT;
683 			if (BTF_INFO_KIND(t->info) == kind)
684 				return id;
685 		}
686 	} else {
687 		for (id = btf_start_id(btf); id < total; id++) {
688 			t = btf_type_by_id(btf, id);
689 			if (BTF_INFO_KIND(t->info) != kind)
690 				continue;
691 			tname = btf_name_by_offset(btf, t->name_off);
692 			if (strcmp(tname, name) == 0)
693 				return id;
694 		}
695 	}
696 
697 	return -ENOENT;
698 }
699 
700 s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
701 {
702 	struct btf *btf;
703 	s32 ret;
704 	int id;
705 
706 	btf = bpf_get_btf_vmlinux();
707 	if (IS_ERR(btf))
708 		return PTR_ERR(btf);
709 	if (!btf)
710 		return -EINVAL;
711 
712 	ret = btf_find_by_name_kind(btf, name, kind);
713 	/* ret is never zero, since btf_find_by_name_kind returns
714 	 * positive btf_id or negative error.
715 	 */
716 	if (ret > 0) {
717 		btf_get(btf);
718 		*btf_p = btf;
719 		return ret;
720 	}
721 
722 	/* If name is not found in vmlinux's BTF then search in module's BTFs */
723 	spin_lock_bh(&btf_idr_lock);
724 	idr_for_each_entry(&btf_idr, btf, id) {
725 		if (!btf_is_module(btf))
726 			continue;
727 		/* linear search could be slow hence unlock/lock
728 		 * the IDR to avoiding holding it for too long
729 		 */
730 		btf_get(btf);
731 		spin_unlock_bh(&btf_idr_lock);
732 		ret = btf_find_by_name_kind(btf, name, kind);
733 		if (ret > 0) {
734 			*btf_p = btf;
735 			return ret;
736 		}
737 		btf_put(btf);
738 		spin_lock_bh(&btf_idr_lock);
739 	}
740 	spin_unlock_bh(&btf_idr_lock);
741 	return ret;
742 }
743 EXPORT_SYMBOL_GPL(bpf_find_btf_id);
744 
745 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
746 					       u32 id, u32 *res_id)
747 {
748 	const struct btf_type *t = btf_type_by_id(btf, id);
749 
750 	while (btf_type_is_modifier(t)) {
751 		id = t->type;
752 		t = btf_type_by_id(btf, t->type);
753 	}
754 
755 	if (res_id)
756 		*res_id = id;
757 
758 	return t;
759 }
760 
761 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
762 					    u32 id, u32 *res_id)
763 {
764 	const struct btf_type *t;
765 
766 	t = btf_type_skip_modifiers(btf, id, NULL);
767 	if (!btf_type_is_ptr(t))
768 		return NULL;
769 
770 	return btf_type_skip_modifiers(btf, t->type, res_id);
771 }
772 
773 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
774 						 u32 id, u32 *res_id)
775 {
776 	const struct btf_type *ptype;
777 
778 	ptype = btf_type_resolve_ptr(btf, id, res_id);
779 	if (ptype && btf_type_is_func_proto(ptype))
780 		return ptype;
781 
782 	return NULL;
783 }
784 
785 /* Types that act only as a source, not sink or intermediate
786  * type when resolving.
787  */
788 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
789 {
790 	return btf_type_is_var(t) ||
791 	       btf_type_is_decl_tag(t) ||
792 	       btf_type_is_datasec(t) ||
793 	       btf_type_is_loc_proto(t) ||
794 	       btf_type_is_locsec(t);
795 }
796 
797 /* What types need to be resolved?
798  *
799  * btf_type_is_modifier() is an obvious one.
800  *
801  * btf_type_is_struct() because its member refers to
802  * another type (through member->type).
803  *
804  * btf_type_is_var() because the variable refers to
805  * another type. btf_type_is_datasec() holds multiple
806  * btf_type_is_var() types that need resolving.
807  *
808  * btf_type_is_array() because its element (array->type)
809  * refers to another type.  Array can be thought of a
810  * special case of struct while array just has the same
811  * member-type repeated by array->nelems of times.
812  */
813 static bool btf_type_needs_resolve(const struct btf_type *t)
814 {
815 	return btf_type_is_modifier(t) ||
816 	       btf_type_is_ptr(t) ||
817 	       btf_type_is_struct(t) ||
818 	       btf_type_is_array(t) ||
819 	       btf_type_is_var(t) ||
820 	       btf_type_is_func(t) ||
821 	       btf_type_is_decl_tag(t) ||
822 	       btf_type_is_datasec(t) ||
823 	       btf_type_is_loc_proto(t) ||
824 	       btf_type_is_locsec(t);
825 }
826 
827 /* t->size can be used */
828 static bool btf_type_has_size(const struct btf_type *t)
829 {
830 	switch (BTF_INFO_KIND(t->info)) {
831 	case BTF_KIND_INT:
832 	case BTF_KIND_STRUCT:
833 	case BTF_KIND_UNION:
834 	case BTF_KIND_ENUM:
835 	case BTF_KIND_DATASEC:
836 	case BTF_KIND_FLOAT:
837 	case BTF_KIND_ENUM64:
838 		return true;
839 	}
840 
841 	return false;
842 }
843 
844 static const char *btf_int_encoding_str(u8 encoding)
845 {
846 	if (encoding == 0)
847 		return "(none)";
848 	else if (encoding == BTF_INT_SIGNED)
849 		return "SIGNED";
850 	else if (encoding == BTF_INT_CHAR)
851 		return "CHAR";
852 	else if (encoding == BTF_INT_BOOL)
853 		return "BOOL";
854 	else
855 		return "UNKN";
856 }
857 
858 static u32 btf_type_int(const struct btf_type *t)
859 {
860 	return *(u32 *)(t + 1);
861 }
862 
863 static const struct btf_array *btf_type_array(const struct btf_type *t)
864 {
865 	return (const struct btf_array *)(t + 1);
866 }
867 
868 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
869 {
870 	return (const struct btf_enum *)(t + 1);
871 }
872 
873 static const struct btf_var *btf_type_var(const struct btf_type *t)
874 {
875 	return (const struct btf_var *)(t + 1);
876 }
877 
878 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
879 {
880 	return (const struct btf_decl_tag *)(t + 1);
881 }
882 
883 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
884 {
885 	return (const struct btf_enum64 *)(t + 1);
886 }
887 
888 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
889 {
890 	return kind_ops[BTF_INFO_KIND(t->info)];
891 }
892 
893 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
894 {
895 	if (!BTF_STR_OFFSET_VALID(offset))
896 		return false;
897 
898 	while (offset < btf->start_str_off)
899 		btf = btf->base_btf;
900 
901 	offset -= btf->start_str_off;
902 	return offset < btf->hdr.str_len;
903 }
904 
905 const char *btf_str_by_offset(const struct btf *btf, u32 offset)
906 {
907 	while (offset < btf->start_str_off)
908 		btf = btf->base_btf;
909 
910 	offset -= btf->start_str_off;
911 	if (offset < btf->hdr.str_len)
912 		return &btf->strings[offset];
913 
914 	return NULL;
915 }
916 
917 /* Names in BTF of Rust are not C identifiers. Allow any printable character */
918 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
919 {
920 	/* offset must be valid */
921 	const char *src = btf_str_by_offset(btf, offset);
922 	const char *src_limit;
923 
924 	if (!isprint(*src))
925 		return false;
926 
927 	/* set a limit on identifier length */
928 	src_limit = src + KSYM_NAME_LEN;
929 	src++;
930 	while (*src && src < src_limit) {
931 		if (!isprint(*src))
932 			return false;
933 		src++;
934 	}
935 
936 	return !*src;
937 }
938 
939 /* Allow any printable character in DATASEC names */
940 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
941 {
942 	/* offset must be valid */
943 	const char *src = btf_str_by_offset(btf, offset);
944 	const char *src_limit;
945 
946 	if (!*src)
947 		return false;
948 
949 	/* set a limit on identifier length */
950 	src_limit = src + KSYM_NAME_LEN;
951 	while (*src && src < src_limit) {
952 		if (!isprint(*src))
953 			return false;
954 		src++;
955 	}
956 
957 	return !*src;
958 }
959 
960 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
961 {
962 	const char *name;
963 
964 	if (!offset)
965 		return "(anon)";
966 
967 	name = btf_str_by_offset(btf, offset);
968 	return name ?: "(invalid-name-offset)";
969 }
970 
971 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
972 {
973 	return btf_str_by_offset(btf, offset);
974 }
975 
976 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
977 {
978 	while (type_id < btf->start_id)
979 		btf = btf->base_btf;
980 
981 	type_id -= btf->start_id;
982 	if (type_id >= btf->nr_types)
983 		return NULL;
984 	return btf->types[type_id];
985 }
986 EXPORT_SYMBOL_GPL(btf_type_by_id);
987 
988 /*
989  * Check that the type @t is a regular int. This means that @t is not
990  * a bit field and it has the same size as either of u8/u16/u32/u64
991  * or __int128. If @expected_size is not zero, then size of @t should
992  * be the same. A caller should already have checked that the type @t
993  * is an integer.
994  */
995 static bool __btf_type_int_is_regular(const struct btf_type *t, size_t expected_size)
996 {
997 	u32 int_data = btf_type_int(t);
998 	u8 nr_bits = BTF_INT_BITS(int_data);
999 	u8 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
1000 
1001 	return BITS_PER_BYTE_MASKED(nr_bits) == 0 &&
1002 	       BTF_INT_OFFSET(int_data) == 0 &&
1003 	       (nr_bytes <= 16 && is_power_of_2(nr_bytes)) &&
1004 	       (expected_size == 0 || nr_bytes == expected_size);
1005 }
1006 
1007 static bool btf_type_int_is_regular(const struct btf_type *t)
1008 {
1009 	return __btf_type_int_is_regular(t, 0);
1010 }
1011 
1012 bool btf_type_is_i32(const struct btf_type *t)
1013 {
1014 	return btf_type_is_int(t) && __btf_type_int_is_regular(t, 4);
1015 }
1016 
1017 bool btf_type_is_i64(const struct btf_type *t)
1018 {
1019 	return btf_type_is_int(t) && __btf_type_int_is_regular(t, 8);
1020 }
1021 
1022 bool btf_type_is_primitive(const struct btf_type *t)
1023 {
1024 	return (btf_type_is_int(t) && btf_type_int_is_regular(t)) ||
1025 	       btf_is_any_enum(t);
1026 }
1027 
1028 /*
1029  * Check that given struct member is a regular int with expected
1030  * offset and size.
1031  */
1032 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
1033 			   const struct btf_member *m,
1034 			   u32 expected_offset, u32 expected_size)
1035 {
1036 	const struct btf_type *t;
1037 	u32 id, int_data;
1038 	u8 nr_bits;
1039 
1040 	id = m->type;
1041 	t = btf_type_id_size(btf, &id, NULL);
1042 	if (!t || !btf_type_is_int(t))
1043 		return false;
1044 
1045 	int_data = btf_type_int(t);
1046 	nr_bits = BTF_INT_BITS(int_data);
1047 	if (btf_type_kflag(s)) {
1048 		u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
1049 		u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
1050 
1051 		/* if kflag set, int should be a regular int and
1052 		 * bit offset should be at byte boundary.
1053 		 */
1054 		return !bitfield_size &&
1055 		       BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
1056 		       BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
1057 	}
1058 
1059 	if (BTF_INT_OFFSET(int_data) ||
1060 	    BITS_PER_BYTE_MASKED(m->offset) ||
1061 	    BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
1062 	    BITS_PER_BYTE_MASKED(nr_bits) ||
1063 	    BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
1064 		return false;
1065 
1066 	return true;
1067 }
1068 
1069 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
1070 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
1071 						       u32 id)
1072 {
1073 	const struct btf_type *t = btf_type_by_id(btf, id);
1074 
1075 	while (btf_type_is_modifier(t) &&
1076 	       BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
1077 		t = btf_type_by_id(btf, t->type);
1078 	}
1079 
1080 	return t;
1081 }
1082 
1083 #define BTF_SHOW_MAX_ITER	10
1084 /* nested structs and arrays shown; __btf_show_indent() has as many columns */
1085 #define BTF_SHOW_MAX_DEPTH	32
1086 
1087 #define BTF_KIND_BIT(kind)	(1ULL << kind)
1088 
1089 /*
1090  * Populate show->state.name with type name information.
1091  * Format of type name is
1092  *
1093  * [.member_name = ] (type_name)
1094  */
1095 static const char *btf_show_name(struct btf_show *show)
1096 {
1097 	/* BTF_MAX_ITER array suffixes "[]" */
1098 	const char *array_suffixes = "[][][][][][][][][][]";
1099 	const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
1100 	/* BTF_MAX_ITER pointer suffixes "*" */
1101 	const char *ptr_suffixes = "**********";
1102 	const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
1103 	const char *name = NULL, *prefix = "", *parens = "";
1104 	const struct btf_member *m = show->state.member;
1105 	const struct btf_type *t;
1106 	const struct btf_array *array;
1107 	u32 id = show->state.type_id;
1108 	const char *member = NULL;
1109 	bool show_member = false;
1110 	u64 kinds = 0;
1111 	int i;
1112 
1113 	show->state.name[0] = '\0';
1114 
1115 	/*
1116 	 * Don't show type name if we're showing an array member;
1117 	 * in that case we show the array type so don't need to repeat
1118 	 * ourselves for each member.
1119 	 */
1120 	if (show->state.array_member)
1121 		return "";
1122 
1123 	/* Retrieve member name, if any. */
1124 	if (m) {
1125 		member = btf_name_by_offset(show->btf, m->name_off);
1126 		show_member = strlen(member) > 0;
1127 		id = m->type;
1128 	}
1129 
1130 	/*
1131 	 * Start with type_id, as we have resolved the struct btf_type *
1132 	 * via btf_modifier_show() past the parent typedef to the child
1133 	 * struct, int etc it is defined as.  In such cases, the type_id
1134 	 * still represents the starting type while the struct btf_type *
1135 	 * in our show->state points at the resolved type of the typedef.
1136 	 */
1137 	t = btf_type_by_id(show->btf, id);
1138 	if (!t)
1139 		return "";
1140 
1141 	/*
1142 	 * The goal here is to build up the right number of pointer and
1143 	 * array suffixes while ensuring the type name for a typedef
1144 	 * is represented.  Along the way we accumulate a list of
1145 	 * BTF kinds we have encountered, since these will inform later
1146 	 * display; for example, pointer types will not require an
1147 	 * opening "{" for struct, we will just display the pointer value.
1148 	 *
1149 	 * We also want to accumulate the right number of pointer or array
1150 	 * indices in the format string while iterating until we get to
1151 	 * the typedef/pointee/array member target type.
1152 	 *
1153 	 * We start by pointing at the end of pointer and array suffix
1154 	 * strings; as we accumulate pointers and arrays we move the pointer
1155 	 * or array string backwards so it will show the expected number of
1156 	 * '*' or '[]' for the type.  BTF_SHOW_MAX_ITER of nesting of pointers
1157 	 * and/or arrays and typedefs are supported as a precaution.
1158 	 *
1159 	 * We also want to get typedef name while proceeding to resolve
1160 	 * type it points to so that we can add parentheses if it is a
1161 	 * "typedef struct" etc.
1162 	 */
1163 	for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
1164 
1165 		switch (BTF_INFO_KIND(t->info)) {
1166 		case BTF_KIND_TYPEDEF:
1167 			if (!name)
1168 				name = btf_name_by_offset(show->btf,
1169 							       t->name_off);
1170 			kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
1171 			id = t->type;
1172 			break;
1173 		case BTF_KIND_ARRAY:
1174 			kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
1175 			parens = "[";
1176 			if (!t)
1177 				return "";
1178 			array = btf_type_array(t);
1179 			if (array_suffix > array_suffixes)
1180 				array_suffix -= 2;
1181 			id = array->type;
1182 			break;
1183 		case BTF_KIND_PTR:
1184 			kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1185 			if (ptr_suffix > ptr_suffixes)
1186 				ptr_suffix -= 1;
1187 			id = t->type;
1188 			break;
1189 		default:
1190 			goto resolved;
1191 		}
1192 		t = btf_type_skip_qualifiers(show->btf, id);
1193 		if (!id)
1194 			break;
1195 	}
1196 	/* We may not be able to represent this type; bail to be safe */
1197 	if (i == BTF_SHOW_MAX_ITER)
1198 		return "";
1199 
1200 resolved:
1201 	if (!name)
1202 		name = btf_type_is_void(t) ? "void" : btf_name_by_offset(show->btf, t->name_off);
1203 
1204 	switch (BTF_INFO_KIND(t->info)) {
1205 	case BTF_KIND_STRUCT:
1206 	case BTF_KIND_UNION:
1207 		prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1208 			 "struct" : "union";
1209 		/* if it's an array of struct/union, parens is already set */
1210 		if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1211 			parens = "{";
1212 		break;
1213 	case BTF_KIND_ENUM:
1214 	case BTF_KIND_ENUM64:
1215 		prefix = "enum";
1216 		break;
1217 	default:
1218 		break;
1219 	}
1220 
1221 	/* pointer does not require parens */
1222 	if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1223 		parens = "";
1224 	/* typedef does not require struct/union/enum prefix */
1225 	if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1226 		prefix = "";
1227 
1228 	if (!name)
1229 		name = "";
1230 
1231 	/* Even if we don't want type name info, we want parentheses etc */
1232 	if (show->flags & BTF_SHOW_NONAME)
1233 		snprintf(show->state.name, sizeof(show->state.name), "%s",
1234 			 parens);
1235 	else
1236 		snprintf(show->state.name, sizeof(show->state.name),
1237 			 "%s%s%s(%s%s%s%s%s%s)%s",
1238 			 /* first 3 strings comprise ".member = " */
1239 			 show_member ? "." : "",
1240 			 show_member ? member : "",
1241 			 show_member ? " = " : "",
1242 			 /* ...next is our prefix (struct, enum, etc) */
1243 			 prefix,
1244 			 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1245 			 /* ...this is the type name itself */
1246 			 name,
1247 			 /* ...suffixed by the appropriate '*', '[]' suffixes */
1248 			 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1249 			 array_suffix, parens);
1250 
1251 	return show->state.name;
1252 }
1253 
1254 static const char *__btf_show_indent(struct btf_show *show)
1255 {
1256 	const char *indents = "                                ";
1257 	const char *indent = &indents[strlen(indents)];
1258 
1259 	if ((indent - show->state.depth) >= indents)
1260 		return indent - show->state.depth;
1261 	return indents;
1262 }
1263 
1264 static const char *btf_show_indent(struct btf_show *show)
1265 {
1266 	return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1267 }
1268 
1269 static const char *btf_show_newline(struct btf_show *show)
1270 {
1271 	return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1272 }
1273 
1274 static const char *btf_show_delim(struct btf_show *show)
1275 {
1276 	if (show->state.depth == 0)
1277 		return "";
1278 
1279 	if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1280 		BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1281 		return "|";
1282 
1283 	return ",";
1284 }
1285 
1286 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1287 {
1288 	va_list args;
1289 
1290 	if (!show->state.depth_check) {
1291 		va_start(args, fmt);
1292 		show->showfn(show, fmt, args);
1293 		va_end(args);
1294 	}
1295 }
1296 
1297 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1298  * format specifiers to the format specifier passed in; these do the work of
1299  * adding indentation, delimiters etc while the caller simply has to specify
1300  * the type value(s) in the format specifier + value(s).
1301  */
1302 #define btf_show_type_value(show, fmt, value)				       \
1303 	do {								       \
1304 		if ((value) != (__typeof__(value))0 ||			       \
1305 		    (show->flags & BTF_SHOW_ZERO) ||			       \
1306 		    show->state.depth == 0) {				       \
1307 			btf_show(show, "%s%s" fmt "%s%s",		       \
1308 				 btf_show_indent(show),			       \
1309 				 btf_show_name(show),			       \
1310 				 value, btf_show_delim(show),		       \
1311 				 btf_show_newline(show));		       \
1312 			if (show->state.depth > show->state.depth_to_show)     \
1313 				show->state.depth_to_show = show->state.depth; \
1314 		}							       \
1315 	} while (0)
1316 
1317 #define btf_show_type_values(show, fmt, ...)				       \
1318 	do {								       \
1319 		btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show),       \
1320 			 btf_show_name(show),				       \
1321 			 __VA_ARGS__, btf_show_delim(show),		       \
1322 			 btf_show_newline(show));			       \
1323 		if (show->state.depth > show->state.depth_to_show)	       \
1324 			show->state.depth_to_show = show->state.depth;	       \
1325 	} while (0)
1326 
1327 /* How much is left to copy to safe buffer after @data? */
1328 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1329 {
1330 	return show->obj.head + show->obj.size - data;
1331 }
1332 
1333 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1334 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1335 {
1336 	return data >= show->obj.data &&
1337 	       (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1338 }
1339 
1340 /*
1341  * If object pointed to by @data of @size falls within our safe buffer, return
1342  * the equivalent pointer to the same safe data.  Assumes
1343  * copy_from_kernel_nofault() has already happened and our safe buffer is
1344  * populated.
1345  */
1346 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1347 {
1348 	if (btf_show_obj_is_safe(show, data, size))
1349 		return show->obj.safe + (data - show->obj.data);
1350 	return NULL;
1351 }
1352 
1353 /*
1354  * Return a safe-to-access version of data pointed to by @data.
1355  * We do this by copying the relevant amount of information
1356  * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1357  *
1358  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1359  * safe copy is needed.
1360  *
1361  * Otherwise we need to determine if we have the required amount
1362  * of data (determined by the @data pointer and the size of the
1363  * largest base type we can encounter (represented by
1364  * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1365  * that we will be able to print some of the current object,
1366  * and if more is needed a copy will be triggered.
1367  * Some objects such as structs will not fit into the buffer;
1368  * in such cases additional copies when we iterate over their
1369  * members may be needed.
1370  *
1371  * btf_show_obj_safe() is used to return a safe buffer for
1372  * btf_show_start_type(); this ensures that as we recurse into
1373  * nested types we always have safe data for the given type.
1374  * This approach is somewhat wasteful; it's possible for example
1375  * that when iterating over a large union we'll end up copying the
1376  * same data repeatedly, but the goal is safety not performance.
1377  * We use stack data as opposed to per-CPU buffers because the
1378  * iteration over a type can take some time, and preemption handling
1379  * would greatly complicate use of the safe buffer.
1380  */
1381 static void *btf_show_obj_safe(struct btf_show *show,
1382 			       const struct btf_type *t,
1383 			       void *data)
1384 {
1385 	const struct btf_type *rt;
1386 	int size_left, size;
1387 	void *safe = NULL;
1388 
1389 	if (show->flags & BTF_SHOW_UNSAFE)
1390 		return data;
1391 
1392 	rt = btf_resolve_size(show->btf, t, &size);
1393 	if (IS_ERR(rt)) {
1394 		show->state.status = PTR_ERR(rt);
1395 		return NULL;
1396 	}
1397 
1398 	/*
1399 	 * Is this toplevel object? If so, set total object size and
1400 	 * initialize pointers.  Otherwise check if we still fall within
1401 	 * our safe object data.
1402 	 */
1403 	if (show->state.depth == 0) {
1404 		show->obj.size = size;
1405 		show->obj.head = data;
1406 	} else {
1407 		/*
1408 		 * If the size of the current object is > our remaining
1409 		 * safe buffer we _may_ need to do a new copy.  However
1410 		 * consider the case of a nested struct; it's size pushes
1411 		 * us over the safe buffer limit, but showing any individual
1412 		 * struct members does not.  In such cases, we don't need
1413 		 * to initiate a fresh copy yet; however we definitely need
1414 		 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1415 		 * in our buffer, regardless of the current object size.
1416 		 * The logic here is that as we resolve types we will
1417 		 * hit a base type at some point, and we need to be sure
1418 		 * the next chunk of data is safely available to display
1419 		 * that type info safely.  We cannot rely on the size of
1420 		 * the current object here because it may be much larger
1421 		 * than our current buffer (e.g. task_struct is 8k).
1422 		 * All we want to do here is ensure that we can print the
1423 		 * next basic type, which we can if either
1424 		 * - the current type size is within the safe buffer; or
1425 		 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1426 		 *   the safe buffer.
1427 		 */
1428 		safe = __btf_show_obj_safe(show, data,
1429 					   min(size,
1430 					       BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1431 	}
1432 
1433 	/*
1434 	 * We need a new copy to our safe object, either because we haven't
1435 	 * yet copied and are initializing safe data, or because the data
1436 	 * we want falls outside the boundaries of the safe object.
1437 	 */
1438 	if (!safe) {
1439 		size_left = btf_show_obj_size_left(show, data);
1440 		if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1441 			size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1442 		show->state.status = copy_from_kernel_nofault(show->obj.safe,
1443 							      data, size_left);
1444 		if (!show->state.status) {
1445 			show->obj.data = data;
1446 			safe = show->obj.safe;
1447 		}
1448 	}
1449 
1450 	return safe;
1451 }
1452 
1453 /*
1454  * Set the type we are starting to show and return a safe data pointer
1455  * to be used for showing the associated data.
1456  */
1457 static void *btf_show_start_type(struct btf_show *show,
1458 				 const struct btf_type *t,
1459 				 u32 type_id, void *data)
1460 {
1461 	show->state.type = t;
1462 	show->state.type_id = type_id;
1463 	show->state.name[0] = '\0';
1464 
1465 	return btf_show_obj_safe(show, t, data);
1466 }
1467 
1468 static void btf_show_end_type(struct btf_show *show)
1469 {
1470 	show->state.type = NULL;
1471 	show->state.type_id = 0;
1472 	show->state.name[0] = '\0';
1473 }
1474 
1475 static void *btf_show_start_aggr_type(struct btf_show *show,
1476 				      const struct btf_type *t,
1477 				      u32 type_id, void *data)
1478 {
1479 	void *safe_data;
1480 
1481 	/*
1482 	 * Structs and arrays are shown by recursion.  BTF loading bounds the
1483 	 * depth of one resolve walk, not how deep resolved types may nest.
1484 	 */
1485 	if (show->state.depth >= BTF_SHOW_MAX_DEPTH) {
1486 		show->state.status = -E2BIG;
1487 		return NULL;
1488 	}
1489 
1490 	safe_data = btf_show_start_type(show, t, type_id, data);
1491 	if (!safe_data)
1492 		return safe_data;
1493 
1494 	btf_show(show, "%s%s%s", btf_show_indent(show),
1495 		 btf_show_name(show),
1496 		 btf_show_newline(show));
1497 	show->state.depth++;
1498 	return safe_data;
1499 }
1500 
1501 static void btf_show_end_aggr_type(struct btf_show *show,
1502 				   const char *suffix)
1503 {
1504 	show->state.depth--;
1505 	btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1506 		 btf_show_delim(show), btf_show_newline(show));
1507 	btf_show_end_type(show);
1508 }
1509 
1510 static void btf_show_start_member(struct btf_show *show,
1511 				  const struct btf_member *m)
1512 {
1513 	show->state.member = m;
1514 }
1515 
1516 static void btf_show_start_array_member(struct btf_show *show)
1517 {
1518 	show->state.array_member = 1;
1519 	btf_show_start_member(show, NULL);
1520 }
1521 
1522 static void btf_show_end_member(struct btf_show *show)
1523 {
1524 	show->state.member = NULL;
1525 }
1526 
1527 static void btf_show_end_array_member(struct btf_show *show)
1528 {
1529 	show->state.array_member = 0;
1530 	btf_show_end_member(show);
1531 }
1532 
1533 static void *btf_show_start_array_type(struct btf_show *show,
1534 				       const struct btf_type *t,
1535 				       u32 type_id,
1536 				       u16 array_encoding,
1537 				       void *data)
1538 {
1539 	show->state.array_encoding = array_encoding;
1540 	show->state.array_terminated = 0;
1541 	return btf_show_start_aggr_type(show, t, type_id, data);
1542 }
1543 
1544 static void btf_show_end_array_type(struct btf_show *show)
1545 {
1546 	show->state.array_encoding = 0;
1547 	show->state.array_terminated = 0;
1548 	btf_show_end_aggr_type(show, "]");
1549 }
1550 
1551 static void *btf_show_start_struct_type(struct btf_show *show,
1552 					const struct btf_type *t,
1553 					u32 type_id,
1554 					void *data)
1555 {
1556 	return btf_show_start_aggr_type(show, t, type_id, data);
1557 }
1558 
1559 static void btf_show_end_struct_type(struct btf_show *show)
1560 {
1561 	btf_show_end_aggr_type(show, "}");
1562 }
1563 
1564 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1565 					      const char *fmt, ...)
1566 {
1567 	va_list args;
1568 
1569 	va_start(args, fmt);
1570 	bpf_verifier_vlog(log, fmt, args);
1571 	va_end(args);
1572 }
1573 
1574 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1575 					    const char *fmt, ...)
1576 {
1577 	struct bpf_verifier_log *log = &env->log;
1578 	va_list args;
1579 
1580 	if (!bpf_verifier_log_needed(log))
1581 		return;
1582 
1583 	va_start(args, fmt);
1584 	bpf_verifier_vlog(log, fmt, args);
1585 	va_end(args);
1586 }
1587 
1588 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1589 						   const struct btf_type *t,
1590 						   bool log_details,
1591 						   const char *fmt, ...)
1592 {
1593 	struct bpf_verifier_log *log = &env->log;
1594 	struct btf *btf = env->btf;
1595 	va_list args;
1596 
1597 	if (!bpf_verifier_log_needed(log))
1598 		return;
1599 
1600 	if (log->level == BPF_LOG_KERNEL) {
1601 		/* btf verifier prints all types it is processing via
1602 		 * btf_verifier_log_type(..., fmt = NULL).
1603 		 * Skip those prints for in-kernel BTF verification.
1604 		 */
1605 		if (!fmt)
1606 			return;
1607 
1608 		/* Skip logging when loading module BTF with mismatches permitted */
1609 		if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1610 			return;
1611 	}
1612 
1613 	__btf_verifier_log(log, "[%u] %s %s%s",
1614 			   env->log_type_id,
1615 			   btf_type_str(t),
1616 			   __btf_name_by_offset(btf, t->name_off),
1617 			   log_details ? " " : "");
1618 
1619 	if (log_details)
1620 		btf_type_ops(t)->log_details(env, t);
1621 
1622 	if (fmt && *fmt) {
1623 		__btf_verifier_log(log, " ");
1624 		va_start(args, fmt);
1625 		bpf_verifier_vlog(log, fmt, args);
1626 		va_end(args);
1627 	}
1628 
1629 	__btf_verifier_log(log, "\n");
1630 }
1631 
1632 #define btf_verifier_log_type(env, t, ...) \
1633 	__btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1634 #define btf_verifier_log_basic(env, t, ...) \
1635 	__btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1636 
1637 __printf(4, 5)
1638 static void btf_verifier_log_member(struct btf_verifier_env *env,
1639 				    const struct btf_type *struct_type,
1640 				    const struct btf_member *member,
1641 				    const char *fmt, ...)
1642 {
1643 	struct bpf_verifier_log *log = &env->log;
1644 	struct btf *btf = env->btf;
1645 	va_list args;
1646 
1647 	if (!bpf_verifier_log_needed(log))
1648 		return;
1649 
1650 	if (log->level == BPF_LOG_KERNEL) {
1651 		if (!fmt)
1652 			return;
1653 
1654 		/* Skip logging when loading module BTF with mismatches permitted */
1655 		if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1656 			return;
1657 	}
1658 
1659 	/* The CHECK_META phase already did a btf dump.
1660 	 *
1661 	 * If member is logged again, it must hit an error in
1662 	 * parsing this member.  It is useful to print out which
1663 	 * struct this member belongs to.
1664 	 */
1665 	if (env->phase != CHECK_META)
1666 		btf_verifier_log_type(env, struct_type, NULL);
1667 
1668 	if (btf_type_kflag(struct_type))
1669 		__btf_verifier_log(log,
1670 				   "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1671 				   __btf_name_by_offset(btf, member->name_off),
1672 				   member->type,
1673 				   BTF_MEMBER_BITFIELD_SIZE(member->offset),
1674 				   BTF_MEMBER_BIT_OFFSET(member->offset));
1675 	else
1676 		__btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1677 				   __btf_name_by_offset(btf, member->name_off),
1678 				   member->type, member->offset);
1679 
1680 	if (fmt && *fmt) {
1681 		__btf_verifier_log(log, " ");
1682 		va_start(args, fmt);
1683 		bpf_verifier_vlog(log, fmt, args);
1684 		va_end(args);
1685 	}
1686 
1687 	__btf_verifier_log(log, "\n");
1688 }
1689 
1690 __printf(4, 5)
1691 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1692 				 const struct btf_type *datasec_type,
1693 				 const struct btf_var_secinfo *vsi,
1694 				 const char *fmt, ...)
1695 {
1696 	struct bpf_verifier_log *log = &env->log;
1697 	va_list args;
1698 
1699 	if (!bpf_verifier_log_needed(log))
1700 		return;
1701 	if (log->level == BPF_LOG_KERNEL && !fmt)
1702 		return;
1703 	if (env->phase != CHECK_META)
1704 		btf_verifier_log_type(env, datasec_type, NULL);
1705 
1706 	__btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1707 			   vsi->type, vsi->offset, vsi->size);
1708 	if (fmt && *fmt) {
1709 		__btf_verifier_log(log, " ");
1710 		va_start(args, fmt);
1711 		bpf_verifier_vlog(log, fmt, args);
1712 		va_end(args);
1713 	}
1714 
1715 	__btf_verifier_log(log, "\n");
1716 }
1717 
1718 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1719 				 u32 btf_data_size)
1720 {
1721 	struct bpf_verifier_log *log = &env->log;
1722 	const struct btf *btf = env->btf;
1723 	const struct btf_header *hdr;
1724 
1725 	if (!bpf_verifier_log_needed(log))
1726 		return;
1727 
1728 	if (log->level == BPF_LOG_KERNEL)
1729 		return;
1730 	hdr = &btf->hdr;
1731 	__btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1732 	__btf_verifier_log(log, "version: %u\n", hdr->version);
1733 	__btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1734 	__btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1735 	__btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1736 	__btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1737 	__btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1738 	__btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1739 	if (hdr->hdr_len >= sizeof(struct btf_header) &&
1740 	    btf_data_size >= hdr->hdr_len) {
1741 		__btf_verifier_log(log, "layout_off: %u\n", hdr->layout_off);
1742 		__btf_verifier_log(log, "layout_len: %u\n", hdr->layout_len);
1743 	}
1744 	__btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1745 }
1746 
1747 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1748 {
1749 	struct btf *btf = env->btf;
1750 
1751 	if (btf->types_size == btf->nr_types) {
1752 		/* Expand 'types' array */
1753 
1754 		struct btf_type **new_types;
1755 		u32 expand_by, new_size;
1756 
1757 		if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1758 			btf_verifier_log(env, "Exceeded max num of types");
1759 			return -E2BIG;
1760 		}
1761 
1762 		expand_by = max_t(u32, btf->types_size >> 2, 16);
1763 		new_size = min_t(u32, BTF_MAX_TYPE,
1764 				 btf->types_size + expand_by);
1765 
1766 		new_types = kvzalloc_objs(*new_types, new_size,
1767 					  GFP_KERNEL | __GFP_NOWARN);
1768 		if (!new_types)
1769 			return -ENOMEM;
1770 
1771 		if (btf->nr_types == 0) {
1772 			if (!btf->base_btf) {
1773 				/* lazily init VOID type */
1774 				new_types[0] = &btf_void;
1775 				btf->nr_types++;
1776 			}
1777 		} else {
1778 			memcpy(new_types, btf->types,
1779 			       sizeof(*btf->types) * btf->nr_types);
1780 		}
1781 
1782 		kvfree(btf->types);
1783 		btf->types = new_types;
1784 		btf->types_size = new_size;
1785 	}
1786 
1787 	btf->types[btf->nr_types++] = t;
1788 
1789 	return 0;
1790 }
1791 
1792 static int btf_alloc_id(struct btf *btf)
1793 {
1794 	int id;
1795 
1796 	idr_preload(GFP_KERNEL);
1797 	spin_lock_bh(&btf_idr_lock);
1798 	id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1799 	if (id > 0)
1800 		btf->id = id;
1801 	spin_unlock_bh(&btf_idr_lock);
1802 	idr_preload_end();
1803 
1804 	if (WARN_ON_ONCE(!id))
1805 		return -ENOSPC;
1806 
1807 	return id > 0 ? 0 : id;
1808 }
1809 
1810 static void btf_free_id(struct btf *btf)
1811 {
1812 	unsigned long flags;
1813 
1814 	/*
1815 	 * In map-in-map, calling map_delete_elem() on outer
1816 	 * map will call bpf_map_put on the inner map.
1817 	 * It will then eventually call btf_free_id()
1818 	 * on the inner map.  Some of the map_delete_elem()
1819 	 * implementation may have irq disabled, so
1820 	 * we need to use the _irqsave() version instead
1821 	 * of the _bh() version.
1822 	 */
1823 	spin_lock_irqsave(&btf_idr_lock, flags);
1824 	if (btf->id) {
1825 		idr_remove(&btf_idr, btf->id);
1826 		/*
1827 		 * Clear the id here to make this function idempotent, since it will get
1828 		 * called a couple of times for module BTFs: on module unload, and then
1829 		 * the final btf_put(). btf_alloc_id() starts IDs with 1, so we can use
1830 		 * 0 as sentinel value.
1831 		 */
1832 		WRITE_ONCE(btf->id, 0);
1833 	}
1834 	spin_unlock_irqrestore(&btf_idr_lock, flags);
1835 }
1836 
1837 static void btf_free_kfunc_set_tab(struct btf *btf)
1838 {
1839 	struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1840 	int hook;
1841 
1842 	if (!tab)
1843 		return;
1844 	for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1845 		kfree(tab->sets[hook]);
1846 	kfree(tab);
1847 	btf->kfunc_set_tab = NULL;
1848 }
1849 
1850 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1851 {
1852 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1853 
1854 	if (!tab)
1855 		return;
1856 	kfree(tab);
1857 	btf->dtor_kfunc_tab = NULL;
1858 }
1859 
1860 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1861 {
1862 	int i;
1863 
1864 	if (!tab)
1865 		return;
1866 	for (i = 0; i < tab->cnt; i++)
1867 		btf_record_free(tab->types[i].record);
1868 	kfree(tab);
1869 }
1870 
1871 static void btf_free_struct_meta_tab(struct btf *btf)
1872 {
1873 	struct btf_struct_metas *tab = btf->struct_meta_tab;
1874 
1875 	btf_struct_metas_free(tab);
1876 	btf->struct_meta_tab = NULL;
1877 }
1878 
1879 static void btf_free_struct_ops_tab(struct btf *btf)
1880 {
1881 	struct btf_struct_ops_tab *tab = btf->struct_ops_tab;
1882 	u32 i;
1883 
1884 	if (!tab)
1885 		return;
1886 
1887 	for (i = 0; i < tab->cnt; i++)
1888 		bpf_struct_ops_desc_release(&tab->ops[i]);
1889 
1890 	kfree(tab);
1891 	btf->struct_ops_tab = NULL;
1892 }
1893 
1894 static void btf_free(struct btf *btf)
1895 {
1896 	btf_free_struct_meta_tab(btf);
1897 	btf_free_dtor_kfunc_tab(btf);
1898 	btf_free_kfunc_set_tab(btf);
1899 	btf_free_struct_ops_tab(btf);
1900 	kvfree(btf->types);
1901 	kvfree(btf->resolved_sizes);
1902 	kvfree(btf->resolved_ids);
1903 	/* vmlinux does not allocate btf->data, it simply points it at
1904 	 * __start_BTF.
1905 	 */
1906 	if (!btf_is_vmlinux(btf))
1907 		kvfree(btf->data);
1908 	kvfree(btf->base_id_map);
1909 	kfree(btf);
1910 }
1911 
1912 static void btf_free_rcu(struct rcu_head *rcu)
1913 {
1914 	struct btf *btf = container_of(rcu, struct btf, rcu);
1915 
1916 	btf_free(btf);
1917 }
1918 
1919 const char *btf_get_name(const struct btf *btf)
1920 {
1921 	return btf->name;
1922 }
1923 
1924 void btf_get(struct btf *btf)
1925 {
1926 	refcount_inc(&btf->refcnt);
1927 }
1928 
1929 void btf_put(struct btf *btf)
1930 {
1931 	if (btf && refcount_dec_and_test(&btf->refcnt)) {
1932 		btf_free_id(btf);
1933 		call_rcu(&btf->rcu, btf_free_rcu);
1934 	}
1935 }
1936 
1937 struct btf *btf_base_btf(const struct btf *btf)
1938 {
1939 	return btf->base_btf;
1940 }
1941 
1942 const struct btf_header *btf_header(const struct btf *btf)
1943 {
1944 	return &btf->hdr;
1945 }
1946 
1947 void btf_set_base_btf(struct btf *btf, const struct btf *base_btf)
1948 {
1949 	btf->base_btf = (struct btf *)base_btf;
1950 	btf->start_id = btf_nr_types(base_btf);
1951 	btf->start_str_off = base_btf->start_str_off + base_btf->hdr.str_len;
1952 }
1953 
1954 static int env_resolve_init(struct btf_verifier_env *env)
1955 {
1956 	struct btf *btf = env->btf;
1957 	u32 nr_types = btf->nr_types;
1958 	u32 *resolved_sizes = NULL;
1959 	u32 *resolved_ids = NULL;
1960 	u8 *visit_states = NULL;
1961 
1962 	resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1963 				  GFP_KERNEL | __GFP_NOWARN);
1964 	if (!resolved_sizes)
1965 		goto nomem;
1966 
1967 	resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1968 				GFP_KERNEL | __GFP_NOWARN);
1969 	if (!resolved_ids)
1970 		goto nomem;
1971 
1972 	visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1973 				GFP_KERNEL | __GFP_NOWARN);
1974 	if (!visit_states)
1975 		goto nomem;
1976 
1977 	btf->resolved_sizes = resolved_sizes;
1978 	btf->resolved_ids = resolved_ids;
1979 	env->visit_states = visit_states;
1980 
1981 	return 0;
1982 
1983 nomem:
1984 	kvfree(resolved_sizes);
1985 	kvfree(resolved_ids);
1986 	kvfree(visit_states);
1987 	return -ENOMEM;
1988 }
1989 
1990 static void btf_verifier_env_free(struct btf_verifier_env *env)
1991 {
1992 	kvfree(env->visit_states);
1993 	kfree(env);
1994 }
1995 
1996 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1997 				     const struct btf_type *next_type)
1998 {
1999 	switch (env->resolve_mode) {
2000 	case RESOLVE_TBD:
2001 		/* int, enum or void is a sink */
2002 		return !btf_type_needs_resolve(next_type);
2003 	case RESOLVE_PTR:
2004 		/* int, enum, void, struct, array, func or func_proto is a sink
2005 		 * for ptr
2006 		 */
2007 		return !btf_type_is_modifier(next_type) &&
2008 			!btf_type_is_ptr(next_type);
2009 	case RESOLVE_STRUCT_OR_ARRAY:
2010 		/* int, enum, void, ptr, func or func_proto is a sink
2011 		 * for struct and array
2012 		 */
2013 		return !btf_type_is_modifier(next_type) &&
2014 			!btf_type_is_array(next_type) &&
2015 			!btf_type_is_struct(next_type);
2016 	default:
2017 		BUG();
2018 	}
2019 }
2020 
2021 static bool env_type_is_resolved(const struct btf_verifier_env *env,
2022 				 u32 type_id)
2023 {
2024 	/* base BTF types should be resolved by now */
2025 	if (type_id < env->btf->start_id)
2026 		return true;
2027 
2028 	return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
2029 }
2030 
2031 static int env_stack_push(struct btf_verifier_env *env,
2032 			  const struct btf_type *t, u32 type_id)
2033 {
2034 	const struct btf *btf = env->btf;
2035 	struct resolve_vertex *v;
2036 
2037 	if (env->top_stack == MAX_RESOLVE_DEPTH)
2038 		return -E2BIG;
2039 
2040 	if (type_id < btf->start_id
2041 	    || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
2042 		return -EEXIST;
2043 
2044 	env->visit_states[type_id - btf->start_id] = VISITED;
2045 
2046 	v = &env->stack[env->top_stack++];
2047 	v->t = t;
2048 	v->type_id = type_id;
2049 	v->next_member = 0;
2050 
2051 	if (env->resolve_mode == RESOLVE_TBD) {
2052 		if (btf_type_is_ptr(t))
2053 			env->resolve_mode = RESOLVE_PTR;
2054 		else if (btf_type_is_struct(t) || btf_type_is_array(t))
2055 			env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
2056 	}
2057 
2058 	return 0;
2059 }
2060 
2061 static void env_stack_set_next_member(struct btf_verifier_env *env,
2062 				      u32 next_member)
2063 {
2064 	env->stack[env->top_stack - 1].next_member = next_member;
2065 }
2066 
2067 static void env_stack_pop_resolved(struct btf_verifier_env *env,
2068 				   u32 resolved_type_id,
2069 				   u32 resolved_size)
2070 {
2071 	u32 type_id = env->stack[--(env->top_stack)].type_id;
2072 	struct btf *btf = env->btf;
2073 
2074 	type_id -= btf->start_id; /* adjust to local type id */
2075 	btf->resolved_sizes[type_id] = resolved_size;
2076 	btf->resolved_ids[type_id] = resolved_type_id;
2077 	env->visit_states[type_id] = RESOLVED;
2078 }
2079 
2080 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
2081 {
2082 	return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
2083 }
2084 
2085 /* Resolve the size of a passed-in "type"
2086  *
2087  * type: is an array (e.g. u32 array[x][y])
2088  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
2089  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
2090  *             corresponds to the return type.
2091  * *elem_type: u32
2092  * *elem_id: id of u32
2093  * *total_nelems: (x * y).  Hence, individual elem size is
2094  *                (*type_size / *total_nelems)
2095  * *type_id: ID of the returned type if leading modifiers were stripped;
2096  *           otherwise left unchanged.
2097  *
2098  * type: is not an array (e.g. const struct X)
2099  * return type: type "struct X"
2100  * *type_size: sizeof(struct X)
2101  * *elem_type: same as return type ("struct X")
2102  * *elem_id: 0
2103  * *total_nelems: 1
2104  * *type_id: ID of the returned type if leading modifiers were stripped;
2105  *           otherwise left unchanged.
2106  */
2107 static const struct btf_type *
2108 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
2109 		   u32 *type_size, const struct btf_type **elem_type,
2110 		   u32 *elem_id, u32 *total_nelems, u32 *type_id)
2111 {
2112 	const struct btf_type *array_type = NULL;
2113 	const struct btf_array *array = NULL;
2114 	u32 i, size, nelems = 1, id = 0;
2115 
2116 	for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
2117 		switch (BTF_INFO_KIND(type->info)) {
2118 		/* type->size can be used */
2119 		case BTF_KIND_INT:
2120 		case BTF_KIND_STRUCT:
2121 		case BTF_KIND_UNION:
2122 		case BTF_KIND_ENUM:
2123 		case BTF_KIND_FLOAT:
2124 		case BTF_KIND_ENUM64:
2125 			size = type->size;
2126 			goto resolved;
2127 
2128 		case BTF_KIND_PTR:
2129 			size = sizeof(void *);
2130 			goto resolved;
2131 
2132 		/* Modifiers */
2133 		case BTF_KIND_TYPEDEF:
2134 		case BTF_KIND_VOLATILE:
2135 		case BTF_KIND_CONST:
2136 		case BTF_KIND_RESTRICT:
2137 		case BTF_KIND_TYPE_TAG:
2138 			if (!array_type)
2139 				id = type->type;
2140 			type = btf_type_by_id(btf, type->type);
2141 			break;
2142 
2143 		case BTF_KIND_ARRAY:
2144 			if (!array_type)
2145 				array_type = type;
2146 			array = btf_type_array(type);
2147 			if (nelems && array->nelems > U32_MAX / nelems)
2148 				return ERR_PTR(-EINVAL);
2149 			nelems *= array->nelems;
2150 			type = btf_type_by_id(btf, array->type);
2151 			break;
2152 
2153 		/* type without size */
2154 		default:
2155 			return ERR_PTR(-EINVAL);
2156 		}
2157 	}
2158 
2159 	return ERR_PTR(-EINVAL);
2160 
2161 resolved:
2162 	if (nelems && size > U32_MAX / nelems)
2163 		return ERR_PTR(-EINVAL);
2164 
2165 	*type_size = nelems * size;
2166 	if (total_nelems)
2167 		*total_nelems = nelems;
2168 	if (elem_type)
2169 		*elem_type = type;
2170 	if (elem_id)
2171 		*elem_id = array ? array->type : 0;
2172 	if (type_id && id)
2173 		*type_id = id;
2174 
2175 	return array_type ? : type;
2176 }
2177 
2178 const struct btf_type *
2179 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
2180 		 u32 *type_size)
2181 {
2182 	return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
2183 }
2184 
2185 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
2186 {
2187 	while (type_id < btf->start_id)
2188 		btf = btf->base_btf;
2189 
2190 	return btf->resolved_ids[type_id - btf->start_id];
2191 }
2192 
2193 /* The input param "type_id" must point to a needs_resolve type */
2194 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
2195 						  u32 *type_id)
2196 {
2197 	*type_id = btf_resolved_type_id(btf, *type_id);
2198 	return btf_type_by_id(btf, *type_id);
2199 }
2200 
2201 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
2202 {
2203 	while (type_id < btf->start_id)
2204 		btf = btf->base_btf;
2205 
2206 	return btf->resolved_sizes[type_id - btf->start_id];
2207 }
2208 
2209 const struct btf_type *btf_type_id_size(const struct btf *btf,
2210 					u32 *type_id, u32 *ret_size)
2211 {
2212 	const struct btf_type *size_type;
2213 	u32 size_type_id = *type_id;
2214 	u32 size = 0;
2215 
2216 	size_type = btf_type_by_id(btf, size_type_id);
2217 	if (btf_type_nosize_or_null(size_type))
2218 		return NULL;
2219 
2220 	if (btf_type_has_size(size_type)) {
2221 		size = size_type->size;
2222 	} else if (btf_type_is_array(size_type)) {
2223 		size = btf_resolved_type_size(btf, size_type_id);
2224 	} else if (btf_type_is_ptr(size_type)) {
2225 		size = sizeof(void *);
2226 	} else {
2227 		if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
2228 				 !btf_type_is_var(size_type)))
2229 			return NULL;
2230 
2231 		size_type_id = btf_resolved_type_id(btf, size_type_id);
2232 		size_type = btf_type_by_id(btf, size_type_id);
2233 		if (btf_type_nosize_or_null(size_type))
2234 			return NULL;
2235 		else if (btf_type_has_size(size_type))
2236 			size = size_type->size;
2237 		else if (btf_type_is_array(size_type))
2238 			size = btf_resolved_type_size(btf, size_type_id);
2239 		else if (btf_type_is_ptr(size_type))
2240 			size = sizeof(void *);
2241 		else
2242 			return NULL;
2243 	}
2244 
2245 	*type_id = size_type_id;
2246 	if (ret_size)
2247 		*ret_size = size;
2248 
2249 	return size_type;
2250 }
2251 
2252 static int btf_df_check_member(struct btf_verifier_env *env,
2253 			       const struct btf_type *struct_type,
2254 			       const struct btf_member *member,
2255 			       const struct btf_type *member_type)
2256 {
2257 	btf_verifier_log_basic(env, struct_type,
2258 			       "Unsupported check_member");
2259 	return -EINVAL;
2260 }
2261 
2262 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2263 				     const struct btf_type *struct_type,
2264 				     const struct btf_member *member,
2265 				     const struct btf_type *member_type)
2266 {
2267 	btf_verifier_log_basic(env, struct_type,
2268 			       "Unsupported check_kflag_member");
2269 	return -EINVAL;
2270 }
2271 
2272 /* Used for ptr, array struct/union and float type members.
2273  * int, enum and modifier types have their specific callback functions.
2274  */
2275 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2276 					  const struct btf_type *struct_type,
2277 					  const struct btf_member *member,
2278 					  const struct btf_type *member_type)
2279 {
2280 	if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2281 		btf_verifier_log_member(env, struct_type, member,
2282 					"Invalid member bitfield_size");
2283 		return -EINVAL;
2284 	}
2285 
2286 	/* bitfield size is 0, so member->offset represents bit offset only.
2287 	 * It is safe to call non kflag check_member variants.
2288 	 */
2289 	return btf_type_ops(member_type)->check_member(env, struct_type,
2290 						       member,
2291 						       member_type);
2292 }
2293 
2294 static int btf_df_resolve(struct btf_verifier_env *env,
2295 			  const struct resolve_vertex *v)
2296 {
2297 	btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2298 	return -EINVAL;
2299 }
2300 
2301 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2302 			u32 type_id, void *data, u8 bits_offsets,
2303 			struct btf_show *show)
2304 {
2305 	btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2306 }
2307 
2308 static int btf_int_check_member(struct btf_verifier_env *env,
2309 				const struct btf_type *struct_type,
2310 				const struct btf_member *member,
2311 				const struct btf_type *member_type)
2312 {
2313 	u32 int_data = btf_type_int(member_type);
2314 	u32 struct_bits_off = member->offset;
2315 	u32 struct_size = struct_type->size;
2316 	u32 nr_copy_bits;
2317 	u32 bytes_offset;
2318 
2319 	if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2320 		btf_verifier_log_member(env, struct_type, member,
2321 					"bits_offset exceeds U32_MAX");
2322 		return -EINVAL;
2323 	}
2324 
2325 	struct_bits_off += BTF_INT_OFFSET(int_data);
2326 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2327 	nr_copy_bits = BTF_INT_BITS(int_data) +
2328 		BITS_PER_BYTE_MASKED(struct_bits_off);
2329 
2330 	if (nr_copy_bits > BITS_PER_U128) {
2331 		btf_verifier_log_member(env, struct_type, member,
2332 					"nr_copy_bits exceeds 128");
2333 		return -EINVAL;
2334 	}
2335 
2336 	if (struct_size < bytes_offset ||
2337 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2338 		btf_verifier_log_member(env, struct_type, member,
2339 					"Member exceeds struct_size");
2340 		return -EINVAL;
2341 	}
2342 
2343 	return 0;
2344 }
2345 
2346 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2347 				      const struct btf_type *struct_type,
2348 				      const struct btf_member *member,
2349 				      const struct btf_type *member_type)
2350 {
2351 	u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2352 	u32 int_data = btf_type_int(member_type);
2353 	u32 struct_size = struct_type->size;
2354 	u32 nr_copy_bits;
2355 
2356 	/* a regular int type is required for the kflag int member */
2357 	if (!btf_type_int_is_regular(member_type)) {
2358 		btf_verifier_log_member(env, struct_type, member,
2359 					"Invalid member base type");
2360 		return -EINVAL;
2361 	}
2362 
2363 	/* check sanity of bitfield size */
2364 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2365 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2366 	nr_int_data_bits = BTF_INT_BITS(int_data);
2367 	if (!nr_bits) {
2368 		/* Not a bitfield member, member offset must be at byte
2369 		 * boundary.
2370 		 */
2371 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2372 			btf_verifier_log_member(env, struct_type, member,
2373 						"Invalid member offset");
2374 			return -EINVAL;
2375 		}
2376 
2377 		nr_bits = nr_int_data_bits;
2378 	} else if (nr_bits > nr_int_data_bits) {
2379 		btf_verifier_log_member(env, struct_type, member,
2380 					"Invalid member bitfield_size");
2381 		return -EINVAL;
2382 	}
2383 
2384 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2385 	nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2386 	if (nr_copy_bits > BITS_PER_U128) {
2387 		btf_verifier_log_member(env, struct_type, member,
2388 					"nr_copy_bits exceeds 128");
2389 		return -EINVAL;
2390 	}
2391 
2392 	if (struct_size < bytes_offset ||
2393 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2394 		btf_verifier_log_member(env, struct_type, member,
2395 					"Member exceeds struct_size");
2396 		return -EINVAL;
2397 	}
2398 
2399 	return 0;
2400 }
2401 
2402 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2403 			      const struct btf_type *t,
2404 			      u32 meta_left)
2405 {
2406 	u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2407 	u16 encoding;
2408 
2409 	if (meta_left < meta_needed) {
2410 		btf_verifier_log_basic(env, t,
2411 				       "meta_left:%u meta_needed:%u",
2412 				       meta_left, meta_needed);
2413 		return -EINVAL;
2414 	}
2415 
2416 	if (btf_type_vlen(t)) {
2417 		btf_verifier_log_type(env, t, "vlen != 0");
2418 		return -EINVAL;
2419 	}
2420 
2421 	if (btf_type_kflag(t)) {
2422 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2423 		return -EINVAL;
2424 	}
2425 
2426 	int_data = btf_type_int(t);
2427 	if (int_data & ~BTF_INT_MASK) {
2428 		btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2429 				       int_data);
2430 		return -EINVAL;
2431 	}
2432 
2433 	nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2434 
2435 	if (nr_bits > BITS_PER_U128) {
2436 		btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2437 				      BITS_PER_U128);
2438 		return -EINVAL;
2439 	}
2440 
2441 	if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2442 		btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2443 		return -EINVAL;
2444 	}
2445 
2446 	/*
2447 	 * Only one of the encoding bits is allowed and it
2448 	 * should be sufficient for the pretty print purpose (i.e. decoding).
2449 	 * Multiple bits can be allowed later if it is found
2450 	 * to be insufficient.
2451 	 */
2452 	encoding = BTF_INT_ENCODING(int_data);
2453 	if (encoding &&
2454 	    encoding != BTF_INT_SIGNED &&
2455 	    encoding != BTF_INT_CHAR &&
2456 	    encoding != BTF_INT_BOOL) {
2457 		btf_verifier_log_type(env, t, "Unsupported encoding");
2458 		return -ENOTSUPP;
2459 	}
2460 
2461 	btf_verifier_log_type(env, t, NULL);
2462 
2463 	return meta_needed;
2464 }
2465 
2466 static void btf_int_log(struct btf_verifier_env *env,
2467 			const struct btf_type *t)
2468 {
2469 	int int_data = btf_type_int(t);
2470 
2471 	btf_verifier_log(env,
2472 			 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2473 			 t->size, BTF_INT_OFFSET(int_data),
2474 			 BTF_INT_BITS(int_data),
2475 			 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2476 }
2477 
2478 static void btf_int128_print(struct btf_show *show, void *data)
2479 {
2480 	/* data points to a __int128 number.
2481 	 * Suppose
2482 	 *     int128_num = *(__int128 *)data;
2483 	 * The below formulas shows what upper_num and lower_num represents:
2484 	 *     upper_num = int128_num >> 64;
2485 	 *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2486 	 */
2487 	u64 upper_num, lower_num;
2488 
2489 #ifdef __BIG_ENDIAN_BITFIELD
2490 	upper_num = *(u64 *)data;
2491 	lower_num = *(u64 *)(data + 8);
2492 #else
2493 	upper_num = *(u64 *)(data + 8);
2494 	lower_num = *(u64 *)data;
2495 #endif
2496 	if (upper_num == 0)
2497 		btf_show_type_value(show, "0x%llx", lower_num);
2498 	else
2499 		btf_show_type_values(show, "0x%llx%016llx", upper_num,
2500 				     lower_num);
2501 }
2502 
2503 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2504 			     u16 right_shift_bits)
2505 {
2506 	u64 upper_num, lower_num;
2507 
2508 #ifdef __BIG_ENDIAN_BITFIELD
2509 	upper_num = print_num[0];
2510 	lower_num = print_num[1];
2511 #else
2512 	upper_num = print_num[1];
2513 	lower_num = print_num[0];
2514 #endif
2515 
2516 	/* shake out un-needed bits by shift/or operations */
2517 	if (left_shift_bits >= 64) {
2518 		upper_num = lower_num << (left_shift_bits - 64);
2519 		lower_num = 0;
2520 	} else {
2521 		upper_num = (upper_num << left_shift_bits) |
2522 			    (lower_num >> (64 - left_shift_bits));
2523 		lower_num = lower_num << left_shift_bits;
2524 	}
2525 
2526 	if (right_shift_bits >= 64) {
2527 		lower_num = upper_num >> (right_shift_bits - 64);
2528 		upper_num = 0;
2529 	} else {
2530 		lower_num = (lower_num >> right_shift_bits) |
2531 			    (upper_num << (64 - right_shift_bits));
2532 		upper_num = upper_num >> right_shift_bits;
2533 	}
2534 
2535 #ifdef __BIG_ENDIAN_BITFIELD
2536 	print_num[0] = upper_num;
2537 	print_num[1] = lower_num;
2538 #else
2539 	print_num[0] = lower_num;
2540 	print_num[1] = upper_num;
2541 #endif
2542 }
2543 
2544 static void btf_bitfield_show(void *data, u8 bits_offset,
2545 			      u8 nr_bits, struct btf_show *show)
2546 {
2547 	u16 left_shift_bits, right_shift_bits;
2548 	u8 nr_copy_bytes;
2549 	u8 nr_copy_bits;
2550 	u64 print_num[2] = {};
2551 
2552 	nr_copy_bits = nr_bits + bits_offset;
2553 	nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2554 
2555 	memcpy(print_num, data, nr_copy_bytes);
2556 
2557 #ifdef __BIG_ENDIAN_BITFIELD
2558 	left_shift_bits = bits_offset;
2559 #else
2560 	left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2561 #endif
2562 	right_shift_bits = BITS_PER_U128 - nr_bits;
2563 
2564 	btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2565 	btf_int128_print(show, print_num);
2566 }
2567 
2568 static void btf_int_bits_show(const struct btf *btf,
2569 			      const struct btf_type *t,
2570 			      void *data, u8 bits_offset,
2571 			      struct btf_show *show)
2572 {
2573 	u32 int_data = btf_type_int(t);
2574 	u8 nr_bits = BTF_INT_BITS(int_data);
2575 	u8 total_bits_offset;
2576 
2577 	/*
2578 	 * bits_offset is at most 7.
2579 	 * BTF_INT_OFFSET() cannot exceed 128 bits.
2580 	 */
2581 	total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2582 	data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2583 	bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2584 	btf_bitfield_show(data, bits_offset, nr_bits, show);
2585 }
2586 
2587 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2588 			 u32 type_id, void *data, u8 bits_offset,
2589 			 struct btf_show *show)
2590 {
2591 	u32 int_data = btf_type_int(t);
2592 	u8 encoding = BTF_INT_ENCODING(int_data);
2593 	bool sign = encoding & BTF_INT_SIGNED;
2594 	u8 nr_bits = BTF_INT_BITS(int_data);
2595 	void *safe_data;
2596 
2597 	safe_data = btf_show_start_type(show, t, type_id, data);
2598 	if (!safe_data)
2599 		return;
2600 
2601 	if (bits_offset || BTF_INT_OFFSET(int_data) ||
2602 	    BITS_PER_BYTE_MASKED(nr_bits)) {
2603 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2604 		goto out;
2605 	}
2606 
2607 	switch (nr_bits) {
2608 	case 128:
2609 		btf_int128_print(show, safe_data);
2610 		break;
2611 	case 64:
2612 		if (sign)
2613 			btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2614 		else
2615 			btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2616 		break;
2617 	case 32:
2618 		if (sign)
2619 			btf_show_type_value(show, "%d", *(s32 *)safe_data);
2620 		else
2621 			btf_show_type_value(show, "%u", *(u32 *)safe_data);
2622 		break;
2623 	case 16:
2624 		if (sign)
2625 			btf_show_type_value(show, "%d", *(s16 *)safe_data);
2626 		else
2627 			btf_show_type_value(show, "%u", *(u16 *)safe_data);
2628 		break;
2629 	case 8:
2630 		if (show->state.array_encoding == BTF_INT_CHAR) {
2631 			/* check for null terminator */
2632 			if (show->state.array_terminated)
2633 				break;
2634 			if (*(char *)data == '\0') {
2635 				show->state.array_terminated = 1;
2636 				break;
2637 			}
2638 			if (isprint(*(char *)data)) {
2639 				btf_show_type_value(show, "'%c'",
2640 						    *(char *)safe_data);
2641 				break;
2642 			}
2643 		}
2644 		if (sign)
2645 			btf_show_type_value(show, "%d", *(s8 *)safe_data);
2646 		else
2647 			btf_show_type_value(show, "%u", *(u8 *)safe_data);
2648 		break;
2649 	default:
2650 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2651 		break;
2652 	}
2653 out:
2654 	btf_show_end_type(show);
2655 }
2656 
2657 static const struct btf_kind_operations int_ops = {
2658 	.check_meta = btf_int_check_meta,
2659 	.resolve = btf_df_resolve,
2660 	.check_member = btf_int_check_member,
2661 	.check_kflag_member = btf_int_check_kflag_member,
2662 	.log_details = btf_int_log,
2663 	.show = btf_int_show,
2664 };
2665 
2666 static int btf_modifier_check_member(struct btf_verifier_env *env,
2667 				     const struct btf_type *struct_type,
2668 				     const struct btf_member *member,
2669 				     const struct btf_type *member_type)
2670 {
2671 	const struct btf_type *resolved_type;
2672 	u32 resolved_type_id = member->type;
2673 	struct btf_member resolved_member;
2674 	struct btf *btf = env->btf;
2675 
2676 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2677 	if (!resolved_type) {
2678 		btf_verifier_log_member(env, struct_type, member,
2679 					"Invalid member");
2680 		return -EINVAL;
2681 	}
2682 
2683 	resolved_member = *member;
2684 	resolved_member.type = resolved_type_id;
2685 
2686 	return btf_type_ops(resolved_type)->check_member(env, struct_type,
2687 							 &resolved_member,
2688 							 resolved_type);
2689 }
2690 
2691 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2692 					   const struct btf_type *struct_type,
2693 					   const struct btf_member *member,
2694 					   const struct btf_type *member_type)
2695 {
2696 	const struct btf_type *resolved_type;
2697 	u32 resolved_type_id = member->type;
2698 	struct btf_member resolved_member;
2699 	struct btf *btf = env->btf;
2700 
2701 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2702 	if (!resolved_type) {
2703 		btf_verifier_log_member(env, struct_type, member,
2704 					"Invalid member");
2705 		return -EINVAL;
2706 	}
2707 
2708 	resolved_member = *member;
2709 	resolved_member.type = resolved_type_id;
2710 
2711 	return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2712 							       &resolved_member,
2713 							       resolved_type);
2714 }
2715 
2716 static int btf_ptr_check_member(struct btf_verifier_env *env,
2717 				const struct btf_type *struct_type,
2718 				const struct btf_member *member,
2719 				const struct btf_type *member_type)
2720 {
2721 	u32 struct_size, struct_bits_off, bytes_offset;
2722 
2723 	struct_size = struct_type->size;
2724 	struct_bits_off = member->offset;
2725 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2726 
2727 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2728 		btf_verifier_log_member(env, struct_type, member,
2729 					"Member is not byte aligned");
2730 		return -EINVAL;
2731 	}
2732 
2733 	if (struct_size - bytes_offset < sizeof(void *)) {
2734 		btf_verifier_log_member(env, struct_type, member,
2735 					"Member exceeds struct_size");
2736 		return -EINVAL;
2737 	}
2738 
2739 	return 0;
2740 }
2741 
2742 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2743 				   const struct btf_type *t,
2744 				   u32 meta_left)
2745 {
2746 	const char *value;
2747 
2748 	if (btf_type_vlen(t)) {
2749 		btf_verifier_log_type(env, t, "vlen != 0");
2750 		return -EINVAL;
2751 	}
2752 
2753 	if (btf_type_kflag(t) && !btf_type_is_type_tag(t)) {
2754 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2755 		return -EINVAL;
2756 	}
2757 
2758 	if (!BTF_TYPE_ID_VALID(t->type)) {
2759 		btf_verifier_log_type(env, t, "Invalid type_id");
2760 		return -EINVAL;
2761 	}
2762 
2763 	/* typedef/type_tag type must have a valid name, and other ref types,
2764 	 * volatile, const, restrict, should have a null name.
2765 	 */
2766 	if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2767 		if (!t->name_off ||
2768 		    !btf_name_valid_identifier(env->btf, t->name_off)) {
2769 			btf_verifier_log_type(env, t, "Invalid name");
2770 			return -EINVAL;
2771 		}
2772 	} else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2773 		value = btf_name_by_offset(env->btf, t->name_off);
2774 		if (!value || !value[0]) {
2775 			btf_verifier_log_type(env, t, "Invalid name");
2776 			return -EINVAL;
2777 		}
2778 	} else {
2779 		if (t->name_off) {
2780 			btf_verifier_log_type(env, t, "Invalid name");
2781 			return -EINVAL;
2782 		}
2783 	}
2784 
2785 	btf_verifier_log_type(env, t, NULL);
2786 
2787 	return 0;
2788 }
2789 
2790 static int btf_modifier_resolve(struct btf_verifier_env *env,
2791 				const struct resolve_vertex *v)
2792 {
2793 	const struct btf_type *t = v->t;
2794 	const struct btf_type *next_type;
2795 	u32 next_type_id = t->type;
2796 	struct btf *btf = env->btf;
2797 
2798 	next_type = btf_type_by_id(btf, next_type_id);
2799 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2800 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2801 		return -EINVAL;
2802 	}
2803 
2804 	if (!env_type_is_resolve_sink(env, next_type) &&
2805 	    !env_type_is_resolved(env, next_type_id))
2806 		return env_stack_push(env, next_type, next_type_id);
2807 
2808 	/* Figure out the resolved next_type_id with size.
2809 	 * They will be stored in the current modifier's
2810 	 * resolved_ids and resolved_sizes such that it can
2811 	 * save us a few type-following when we use it later (e.g. in
2812 	 * pretty print).
2813 	 */
2814 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2815 		if (env_type_is_resolved(env, next_type_id))
2816 			next_type = btf_type_id_resolve(btf, &next_type_id);
2817 
2818 		/* "typedef void new_void", "const void"...etc */
2819 		if (!btf_type_is_void(next_type) &&
2820 		    !btf_type_is_fwd(next_type) &&
2821 		    !btf_type_is_func_proto(next_type)) {
2822 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2823 			return -EINVAL;
2824 		}
2825 	}
2826 
2827 	env_stack_pop_resolved(env, next_type_id, 0);
2828 
2829 	return 0;
2830 }
2831 
2832 static int btf_var_resolve(struct btf_verifier_env *env,
2833 			   const struct resolve_vertex *v)
2834 {
2835 	const struct btf_type *next_type;
2836 	const struct btf_type *t = v->t;
2837 	u32 next_type_id = t->type;
2838 	struct btf *btf = env->btf;
2839 
2840 	next_type = btf_type_by_id(btf, next_type_id);
2841 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2842 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2843 		return -EINVAL;
2844 	}
2845 
2846 	if (!env_type_is_resolve_sink(env, next_type) &&
2847 	    !env_type_is_resolved(env, next_type_id))
2848 		return env_stack_push(env, next_type, next_type_id);
2849 
2850 	if (btf_type_is_modifier(next_type)) {
2851 		const struct btf_type *resolved_type;
2852 		u32 resolved_type_id;
2853 
2854 		resolved_type_id = next_type_id;
2855 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2856 
2857 		if (btf_type_is_ptr(resolved_type) &&
2858 		    !env_type_is_resolve_sink(env, resolved_type) &&
2859 		    !env_type_is_resolved(env, resolved_type_id))
2860 			return env_stack_push(env, resolved_type,
2861 					      resolved_type_id);
2862 	}
2863 
2864 	/* We must resolve to something concrete at this point, no
2865 	 * forward types or similar that would resolve to size of
2866 	 * zero is allowed.
2867 	 */
2868 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2869 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2870 		return -EINVAL;
2871 	}
2872 
2873 	env_stack_pop_resolved(env, next_type_id, 0);
2874 
2875 	return 0;
2876 }
2877 
2878 static int btf_ptr_resolve(struct btf_verifier_env *env,
2879 			   const struct resolve_vertex *v)
2880 {
2881 	const struct btf_type *next_type;
2882 	const struct btf_type *t = v->t;
2883 	u32 next_type_id = t->type;
2884 	struct btf *btf = env->btf;
2885 
2886 	next_type = btf_type_by_id(btf, next_type_id);
2887 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2888 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2889 		return -EINVAL;
2890 	}
2891 
2892 	if (!env_type_is_resolve_sink(env, next_type) &&
2893 	    !env_type_is_resolved(env, next_type_id))
2894 		return env_stack_push(env, next_type, next_type_id);
2895 
2896 	/* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2897 	 * the modifier may have stopped resolving when it was resolved
2898 	 * to a ptr (last-resolved-ptr).
2899 	 *
2900 	 * We now need to continue from the last-resolved-ptr to
2901 	 * ensure the last-resolved-ptr will not referring back to
2902 	 * the current ptr (t).
2903 	 */
2904 	if (btf_type_is_modifier(next_type)) {
2905 		const struct btf_type *resolved_type;
2906 		u32 resolved_type_id;
2907 
2908 		resolved_type_id = next_type_id;
2909 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2910 
2911 		if (btf_type_is_ptr(resolved_type) &&
2912 		    !env_type_is_resolve_sink(env, resolved_type) &&
2913 		    !env_type_is_resolved(env, resolved_type_id))
2914 			return env_stack_push(env, resolved_type,
2915 					      resolved_type_id);
2916 	}
2917 
2918 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2919 		if (env_type_is_resolved(env, next_type_id))
2920 			next_type = btf_type_id_resolve(btf, &next_type_id);
2921 
2922 		if (!btf_type_is_void(next_type) &&
2923 		    !btf_type_is_fwd(next_type) &&
2924 		    !btf_type_is_func_proto(next_type)) {
2925 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2926 			return -EINVAL;
2927 		}
2928 	}
2929 
2930 	env_stack_pop_resolved(env, next_type_id, 0);
2931 
2932 	return 0;
2933 }
2934 
2935 static void btf_modifier_show(const struct btf *btf,
2936 			      const struct btf_type *t,
2937 			      u32 type_id, void *data,
2938 			      u8 bits_offset, struct btf_show *show)
2939 {
2940 	if (btf->resolved_ids)
2941 		t = btf_type_id_resolve(btf, &type_id);
2942 	else
2943 		t = btf_type_skip_modifiers(btf, type_id, NULL);
2944 
2945 	/*
2946 	 * A modifier can resolve to void, which has no show op; print a
2947 	 * placeholder rather than dereferencing NULL.
2948 	 */
2949 	if (!btf_type_ops(t))
2950 		btf_df_show(btf, t, type_id, data, bits_offset, show);
2951 	else
2952 		btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2953 }
2954 
2955 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2956 			 u32 type_id, void *data, u8 bits_offset,
2957 			 struct btf_show *show)
2958 {
2959 	/*
2960 	 * btf_type_id_resolve() dereferences btf->resolved_ids, which is NULL
2961 	 * for a base BTF (e.g. the vmlinux BTF that bpf_snprintf_btf() uses).
2962 	 * Resolve the var's type directly in that case.
2963 	 */
2964 	if (btf->resolved_ids)
2965 		t = btf_type_id_resolve(btf, &type_id);
2966 	else
2967 		t = btf_type_skip_modifiers(btf, t->type, &type_id);
2968 
2969 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2970 }
2971 
2972 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2973 			 u32 type_id, void *data, u8 bits_offset,
2974 			 struct btf_show *show)
2975 {
2976 	void *safe_data;
2977 
2978 	safe_data = btf_show_start_type(show, t, type_id, data);
2979 	if (!safe_data)
2980 		return;
2981 
2982 	/* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2983 	if (show->flags & BTF_SHOW_PTR_RAW)
2984 		btf_show_type_value(show, "0x%px", *(void **)safe_data);
2985 	else
2986 		btf_show_type_value(show, "0x%p", *(void **)safe_data);
2987 	btf_show_end_type(show);
2988 }
2989 
2990 static void btf_ref_type_log(struct btf_verifier_env *env,
2991 			     const struct btf_type *t)
2992 {
2993 	btf_verifier_log(env, "type_id=%u", t->type);
2994 }
2995 
2996 static const struct btf_kind_operations modifier_ops = {
2997 	.check_meta = btf_ref_type_check_meta,
2998 	.resolve = btf_modifier_resolve,
2999 	.check_member = btf_modifier_check_member,
3000 	.check_kflag_member = btf_modifier_check_kflag_member,
3001 	.log_details = btf_ref_type_log,
3002 	.show = btf_modifier_show,
3003 };
3004 
3005 static const struct btf_kind_operations ptr_ops = {
3006 	.check_meta = btf_ref_type_check_meta,
3007 	.resolve = btf_ptr_resolve,
3008 	.check_member = btf_ptr_check_member,
3009 	.check_kflag_member = btf_generic_check_kflag_member,
3010 	.log_details = btf_ref_type_log,
3011 	.show = btf_ptr_show,
3012 };
3013 
3014 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
3015 			      const struct btf_type *t,
3016 			      u32 meta_left)
3017 {
3018 	if (btf_type_vlen(t)) {
3019 		btf_verifier_log_type(env, t, "vlen != 0");
3020 		return -EINVAL;
3021 	}
3022 
3023 	if (t->type) {
3024 		btf_verifier_log_type(env, t, "type != 0");
3025 		return -EINVAL;
3026 	}
3027 
3028 	/* fwd type must have a valid name */
3029 	if (!t->name_off ||
3030 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3031 		btf_verifier_log_type(env, t, "Invalid name");
3032 		return -EINVAL;
3033 	}
3034 
3035 	btf_verifier_log_type(env, t, NULL);
3036 
3037 	return 0;
3038 }
3039 
3040 static void btf_fwd_type_log(struct btf_verifier_env *env,
3041 			     const struct btf_type *t)
3042 {
3043 	btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
3044 }
3045 
3046 static const struct btf_kind_operations fwd_ops = {
3047 	.check_meta = btf_fwd_check_meta,
3048 	.resolve = btf_df_resolve,
3049 	.check_member = btf_df_check_member,
3050 	.check_kflag_member = btf_df_check_kflag_member,
3051 	.log_details = btf_fwd_type_log,
3052 	.show = btf_df_show,
3053 };
3054 
3055 static int btf_array_check_member(struct btf_verifier_env *env,
3056 				  const struct btf_type *struct_type,
3057 				  const struct btf_member *member,
3058 				  const struct btf_type *member_type)
3059 {
3060 	u32 struct_bits_off = member->offset;
3061 	u32 struct_size, bytes_offset;
3062 	u32 array_type_id, array_size;
3063 	struct btf *btf = env->btf;
3064 
3065 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3066 		btf_verifier_log_member(env, struct_type, member,
3067 					"Member is not byte aligned");
3068 		return -EINVAL;
3069 	}
3070 
3071 	array_type_id = member->type;
3072 	btf_type_id_size(btf, &array_type_id, &array_size);
3073 	struct_size = struct_type->size;
3074 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3075 	if (struct_size - bytes_offset < array_size) {
3076 		btf_verifier_log_member(env, struct_type, member,
3077 					"Member exceeds struct_size");
3078 		return -EINVAL;
3079 	}
3080 
3081 	return 0;
3082 }
3083 
3084 static s32 btf_array_check_meta(struct btf_verifier_env *env,
3085 				const struct btf_type *t,
3086 				u32 meta_left)
3087 {
3088 	const struct btf_array *array = btf_type_array(t);
3089 	u32 meta_needed = sizeof(*array);
3090 
3091 	if (meta_left < meta_needed) {
3092 		btf_verifier_log_basic(env, t,
3093 				       "meta_left:%u meta_needed:%u",
3094 				       meta_left, meta_needed);
3095 		return -EINVAL;
3096 	}
3097 
3098 	/* array type should not have a name */
3099 	if (t->name_off) {
3100 		btf_verifier_log_type(env, t, "Invalid name");
3101 		return -EINVAL;
3102 	}
3103 
3104 	if (btf_type_vlen(t)) {
3105 		btf_verifier_log_type(env, t, "vlen != 0");
3106 		return -EINVAL;
3107 	}
3108 
3109 	if (btf_type_kflag(t)) {
3110 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3111 		return -EINVAL;
3112 	}
3113 
3114 	if (t->size) {
3115 		btf_verifier_log_type(env, t, "size != 0");
3116 		return -EINVAL;
3117 	}
3118 
3119 	/* Array elem type and index type cannot be in type void,
3120 	 * so !array->type and !array->index_type are not allowed.
3121 	 */
3122 	if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
3123 		btf_verifier_log_type(env, t, "Invalid elem");
3124 		return -EINVAL;
3125 	}
3126 
3127 	if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
3128 		btf_verifier_log_type(env, t, "Invalid index");
3129 		return -EINVAL;
3130 	}
3131 
3132 	btf_verifier_log_type(env, t, NULL);
3133 
3134 	return meta_needed;
3135 }
3136 
3137 static int btf_array_resolve(struct btf_verifier_env *env,
3138 			     const struct resolve_vertex *v)
3139 {
3140 	const struct btf_array *array = btf_type_array(v->t);
3141 	const struct btf_type *elem_type, *index_type;
3142 	u32 elem_type_id, index_type_id;
3143 	struct btf *btf = env->btf;
3144 	u32 elem_size;
3145 
3146 	/* Check array->index_type */
3147 	index_type_id = array->index_type;
3148 	index_type = btf_type_by_id(btf, index_type_id);
3149 	if (btf_type_nosize_or_null(index_type) ||
3150 	    btf_type_is_resolve_source_only(index_type)) {
3151 		btf_verifier_log_type(env, v->t, "Invalid index");
3152 		return -EINVAL;
3153 	}
3154 
3155 	if (!env_type_is_resolve_sink(env, index_type) &&
3156 	    !env_type_is_resolved(env, index_type_id))
3157 		return env_stack_push(env, index_type, index_type_id);
3158 
3159 	index_type = btf_type_id_size(btf, &index_type_id, NULL);
3160 	if (!index_type || !btf_type_is_int(index_type) ||
3161 	    !btf_type_int_is_regular(index_type)) {
3162 		btf_verifier_log_type(env, v->t, "Invalid index");
3163 		return -EINVAL;
3164 	}
3165 
3166 	/* Check array->type */
3167 	elem_type_id = array->type;
3168 	elem_type = btf_type_by_id(btf, elem_type_id);
3169 	if (btf_type_nosize_or_null(elem_type) ||
3170 	    btf_type_is_resolve_source_only(elem_type)) {
3171 		btf_verifier_log_type(env, v->t,
3172 				      "Invalid elem");
3173 		return -EINVAL;
3174 	}
3175 
3176 	if (!env_type_is_resolve_sink(env, elem_type) &&
3177 	    !env_type_is_resolved(env, elem_type_id))
3178 		return env_stack_push(env, elem_type, elem_type_id);
3179 
3180 	elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
3181 	if (!elem_type) {
3182 		btf_verifier_log_type(env, v->t, "Invalid elem");
3183 		return -EINVAL;
3184 	}
3185 
3186 	if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
3187 		btf_verifier_log_type(env, v->t, "Invalid array of int");
3188 		return -EINVAL;
3189 	}
3190 
3191 	if (array->nelems && elem_size > U32_MAX / array->nelems) {
3192 		btf_verifier_log_type(env, v->t,
3193 				      "Array size overflows U32_MAX");
3194 		return -EINVAL;
3195 	}
3196 
3197 	env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
3198 
3199 	return 0;
3200 }
3201 
3202 static void btf_array_log(struct btf_verifier_env *env,
3203 			  const struct btf_type *t)
3204 {
3205 	const struct btf_array *array = btf_type_array(t);
3206 
3207 	btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
3208 			 array->type, array->index_type, array->nelems);
3209 }
3210 
3211 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
3212 			     u32 type_id, void *data, u8 bits_offset,
3213 			     struct btf_show *show)
3214 {
3215 	const struct btf_array *array = btf_type_array(t);
3216 	const struct btf_kind_operations *elem_ops;
3217 	const struct btf_type *elem_type;
3218 	u32 i, elem_size = 0, elem_type_id;
3219 	u16 encoding = 0;
3220 
3221 	elem_type_id = array->type;
3222 	elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
3223 	if (elem_type && btf_type_has_size(elem_type))
3224 		elem_size = elem_type->size;
3225 
3226 	if (elem_type && btf_type_is_int(elem_type)) {
3227 		u32 int_type = btf_type_int(elem_type);
3228 
3229 		encoding = BTF_INT_ENCODING(int_type);
3230 
3231 		/*
3232 		 * BTF_INT_CHAR encoding never seems to be set for
3233 		 * char arrays, so if size is 1 and element is
3234 		 * printable as a char, we'll do that.
3235 		 */
3236 		if (elem_size == 1)
3237 			encoding = BTF_INT_CHAR;
3238 	}
3239 
3240 	if (!btf_show_start_array_type(show, t, type_id, encoding, data))
3241 		return;
3242 
3243 	if (!elem_type)
3244 		goto out;
3245 	elem_ops = btf_type_ops(elem_type);
3246 
3247 	for (i = 0; i < array->nelems; i++) {
3248 
3249 		btf_show_start_array_member(show);
3250 
3251 		elem_ops->show(btf, elem_type, elem_type_id, data,
3252 			       bits_offset, show);
3253 		data += elem_size;
3254 
3255 		btf_show_end_array_member(show);
3256 
3257 		if (show->state.array_terminated)
3258 			break;
3259 	}
3260 out:
3261 	btf_show_end_array_type(show);
3262 }
3263 
3264 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3265 			   u32 type_id, void *data, u8 bits_offset,
3266 			   struct btf_show *show)
3267 {
3268 	const struct btf_member *m = show->state.member;
3269 
3270 	/*
3271 	 * First check if any members would be shown (are non-zero).
3272 	 * See comments above "struct btf_show" definition for more
3273 	 * details on how this works at a high-level.
3274 	 */
3275 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3276 		if (!show->state.depth_check) {
3277 			show->state.depth_check = show->state.depth + 1;
3278 			show->state.depth_to_show = 0;
3279 		}
3280 		__btf_array_show(btf, t, type_id, data, bits_offset, show);
3281 		show->state.member = m;
3282 
3283 		if (show->state.depth_check != show->state.depth + 1)
3284 			return;
3285 		show->state.depth_check = 0;
3286 
3287 		if (show->state.depth_to_show <= show->state.depth)
3288 			return;
3289 		/*
3290 		 * Reaching here indicates we have recursed and found
3291 		 * non-zero array member(s).
3292 		 */
3293 	}
3294 	__btf_array_show(btf, t, type_id, data, bits_offset, show);
3295 }
3296 
3297 static const struct btf_kind_operations array_ops = {
3298 	.check_meta = btf_array_check_meta,
3299 	.resolve = btf_array_resolve,
3300 	.check_member = btf_array_check_member,
3301 	.check_kflag_member = btf_generic_check_kflag_member,
3302 	.log_details = btf_array_log,
3303 	.show = btf_array_show,
3304 };
3305 
3306 static int btf_struct_check_member(struct btf_verifier_env *env,
3307 				   const struct btf_type *struct_type,
3308 				   const struct btf_member *member,
3309 				   const struct btf_type *member_type)
3310 {
3311 	u32 struct_bits_off = member->offset;
3312 	u32 struct_size, bytes_offset;
3313 
3314 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3315 		btf_verifier_log_member(env, struct_type, member,
3316 					"Member is not byte aligned");
3317 		return -EINVAL;
3318 	}
3319 
3320 	struct_size = struct_type->size;
3321 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3322 	if (struct_size - bytes_offset < member_type->size) {
3323 		btf_verifier_log_member(env, struct_type, member,
3324 					"Member exceeds struct_size");
3325 		return -EINVAL;
3326 	}
3327 
3328 	return 0;
3329 }
3330 
3331 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3332 				 const struct btf_type *t,
3333 				 u32 meta_left)
3334 {
3335 	bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3336 	const struct btf_member *member;
3337 	u32 meta_needed, last_offset;
3338 	struct btf *btf = env->btf;
3339 	u32 struct_size = t->size;
3340 	u32 offset;
3341 	u32 i;
3342 
3343 	meta_needed = btf_type_vlen(t) * sizeof(*member);
3344 	if (meta_left < meta_needed) {
3345 		btf_verifier_log_basic(env, t,
3346 				       "meta_left:%u meta_needed:%u",
3347 				       meta_left, meta_needed);
3348 		return -EINVAL;
3349 	}
3350 
3351 	/* struct type either no name or a valid one */
3352 	if (t->name_off &&
3353 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3354 		btf_verifier_log_type(env, t, "Invalid name");
3355 		return -EINVAL;
3356 	}
3357 
3358 	btf_verifier_log_type(env, t, NULL);
3359 
3360 	last_offset = 0;
3361 	for_each_member(i, t, member) {
3362 		if (!btf_name_offset_valid(btf, member->name_off)) {
3363 			btf_verifier_log_member(env, t, member,
3364 						"Invalid member name_offset:%u",
3365 						member->name_off);
3366 			return -EINVAL;
3367 		}
3368 
3369 		/* struct member either no name or a valid one */
3370 		if (member->name_off &&
3371 		    !btf_name_valid_identifier(btf, member->name_off)) {
3372 			btf_verifier_log_member(env, t, member, "Invalid name");
3373 			return -EINVAL;
3374 		}
3375 		/* A member cannot be in type void */
3376 		if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3377 			btf_verifier_log_member(env, t, member,
3378 						"Invalid type_id");
3379 			return -EINVAL;
3380 		}
3381 
3382 		offset = __btf_member_bit_offset(t, member);
3383 		if (is_union && offset) {
3384 			btf_verifier_log_member(env, t, member,
3385 						"Invalid member bits_offset");
3386 			return -EINVAL;
3387 		}
3388 
3389 		/*
3390 		 * ">" instead of ">=" because the last member could be
3391 		 * "char a[0];"
3392 		 */
3393 		if (last_offset > offset) {
3394 			btf_verifier_log_member(env, t, member,
3395 						"Invalid member bits_offset");
3396 			return -EINVAL;
3397 		}
3398 
3399 		if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3400 			btf_verifier_log_member(env, t, member,
3401 						"Member bits_offset exceeds its struct size");
3402 			return -EINVAL;
3403 		}
3404 
3405 		btf_verifier_log_member(env, t, member, NULL);
3406 		last_offset = offset;
3407 	}
3408 
3409 	return meta_needed;
3410 }
3411 
3412 static int btf_struct_resolve(struct btf_verifier_env *env,
3413 			      const struct resolve_vertex *v)
3414 {
3415 	const struct btf_member *member;
3416 	int err;
3417 	u32 i;
3418 
3419 	/* Before continue resolving the next_member,
3420 	 * ensure the last member is indeed resolved to a
3421 	 * type with size info.
3422 	 */
3423 	if (v->next_member) {
3424 		const struct btf_type *last_member_type;
3425 		const struct btf_member *last_member;
3426 		u32 last_member_type_id;
3427 
3428 		last_member = btf_type_member(v->t) + v->next_member - 1;
3429 		last_member_type_id = last_member->type;
3430 		if (WARN_ON_ONCE(!env_type_is_resolved(env,
3431 						       last_member_type_id)))
3432 			return -EINVAL;
3433 
3434 		last_member_type = btf_type_by_id(env->btf,
3435 						  last_member_type_id);
3436 		if (btf_type_kflag(v->t))
3437 			err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3438 								last_member,
3439 								last_member_type);
3440 		else
3441 			err = btf_type_ops(last_member_type)->check_member(env, v->t,
3442 								last_member,
3443 								last_member_type);
3444 		if (err)
3445 			return err;
3446 	}
3447 
3448 	for_each_member_from(i, v->next_member, v->t, member) {
3449 		u32 member_type_id = member->type;
3450 		const struct btf_type *member_type = btf_type_by_id(env->btf,
3451 								member_type_id);
3452 
3453 		if (btf_type_nosize_or_null(member_type) ||
3454 		    btf_type_is_resolve_source_only(member_type)) {
3455 			btf_verifier_log_member(env, v->t, member,
3456 						"Invalid member");
3457 			return -EINVAL;
3458 		}
3459 
3460 		if (!env_type_is_resolve_sink(env, member_type) &&
3461 		    !env_type_is_resolved(env, member_type_id)) {
3462 			env_stack_set_next_member(env, i + 1);
3463 			return env_stack_push(env, member_type, member_type_id);
3464 		}
3465 
3466 		if (btf_type_kflag(v->t))
3467 			err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3468 									    member,
3469 									    member_type);
3470 		else
3471 			err = btf_type_ops(member_type)->check_member(env, v->t,
3472 								      member,
3473 								      member_type);
3474 		if (err)
3475 			return err;
3476 	}
3477 
3478 	env_stack_pop_resolved(env, 0, 0);
3479 
3480 	return 0;
3481 }
3482 
3483 static void btf_struct_log(struct btf_verifier_env *env,
3484 			   const struct btf_type *t)
3485 {
3486 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3487 }
3488 
3489 enum {
3490 	BTF_FIELD_IGNORE = 0,
3491 	BTF_FIELD_FOUND  = 1,
3492 };
3493 
3494 struct btf_field_info {
3495 	enum btf_field_type type;
3496 	u32 off;
3497 	union {
3498 		struct {
3499 			u32 type_id;
3500 		} kptr;
3501 		struct {
3502 			const char *node_name;
3503 			u32 value_btf_id;
3504 		} graph_root;
3505 	};
3506 };
3507 
3508 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3509 			   u32 off, int sz, enum btf_field_type field_type,
3510 			   struct btf_field_info *info)
3511 {
3512 	if (!__btf_type_is_struct(t))
3513 		return BTF_FIELD_IGNORE;
3514 	if (t->size != sz)
3515 		return BTF_FIELD_IGNORE;
3516 	info->type = field_type;
3517 	info->off = off;
3518 	return BTF_FIELD_FOUND;
3519 }
3520 
3521 struct btf_type_tag_match {
3522 	const char *name;
3523 	u32 flag;
3524 };
3525 
3526 struct btf_type_tag_walk_ctx {
3527 	const struct btf_type *t;	/* Input/Output */
3528 	u32 id;				/* Output */
3529 	u32 res;			/* Output */
3530 };
3531 
3532 static int btf_type_tag_walk(const struct btf *btf,
3533 			     struct btf_type_tag_walk_ctx *ctx,
3534 			     const struct btf_type_tag_match *matches,
3535 			     u32 match_cnt)
3536 {
3537 	const struct btf_type *t = ctx->t;
3538 	u32 res = 0;
3539 	const char *tag;
3540 	u32 id, i;
3541 
3542 	do {
3543 		id = t->type;
3544 		t = btf_type_by_id(btf, id);
3545 
3546 		if (!btf_type_is_modifier(t))
3547 			break;
3548 
3549 		if (!btf_type_is_type_tag(t) || btf_type_kflag(t))
3550 			continue;
3551 
3552 		tag = __btf_name_by_offset(btf, t->name_off);
3553 		for (i = 0; i < match_cnt; i++) {
3554 			if (strcmp(tag, matches[i].name))
3555 				continue;
3556 			res |= matches[i].flag;
3557 			break;
3558 		}
3559 	} while (true);
3560 
3561 	/* We only support a single tag. */
3562 	if (hweight32(res) > 1)
3563 		return -EINVAL;
3564 
3565 	ctx->t = t;
3566 	ctx->id = id;
3567 	ctx->res = res;
3568 
3569 	return 0;
3570 }
3571 
3572 /* Whether the pointee of pointer type @t carries the type tag @name */
3573 static bool btf_ptr_has_type_tag(const struct btf *btf, const struct btf_type *t, const char *name)
3574 {
3575 	if (!btf_type_is_ptr(t))
3576 		return false;
3577 
3578 	for (t = btf_type_by_id(btf, t->type); btf_type_is_modifier(t);
3579 	     t = btf_type_by_id(btf, t->type)) {
3580 		if (!btf_type_is_type_tag(t) || btf_type_kflag(t))
3581 			continue;
3582 		if (!strcmp(__btf_name_by_offset(btf, t->name_off), name))
3583 			return true;
3584 	}
3585 
3586 	return false;
3587 }
3588 
3589 bool btf_type_is_arena_ptr(const struct btf *btf, const struct btf_type *t)
3590 {
3591 	return btf_ptr_has_type_tag(btf, t, "arena");
3592 }
3593 
3594 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3595 			 u32 off, int sz, struct btf_field_info *info, u32 field_mask)
3596 {
3597 	static const struct btf_type_tag_match kptr_type_tags[] = {
3598 		{ "kptr_untrusted", BPF_KPTR_UNREF },
3599 		{ "kptr", BPF_KPTR_REF },
3600 		{ "percpu_kptr", BPF_KPTR_PERCPU },
3601 		{ "uptr", BPF_UPTR },
3602 	};
3603 	struct btf_type_tag_walk_ctx ctx;
3604 	enum btf_field_type type = 0;
3605 	int err;
3606 	u32 res_id;
3607 
3608 	/* Permit modifiers on the pointer itself */
3609 	if (btf_type_is_volatile(t))
3610 		t = btf_type_by_id(btf, t->type);
3611 	/* For PTR, sz is always == 8 */
3612 	if (!btf_type_is_ptr(t))
3613 		return BTF_FIELD_IGNORE;
3614 
3615 	ctx.t = t;
3616 	err = btf_type_tag_walk(btf, &ctx, kptr_type_tags,
3617 				ARRAY_SIZE(kptr_type_tags));
3618 	if (err)
3619 		return err;
3620 
3621 	t = ctx.t;
3622 	res_id = ctx.id;
3623 	type = ctx.res;
3624 
3625 	if (!(type & field_mask))
3626 		return BTF_FIELD_IGNORE;
3627 
3628 	/* Only pointer to struct is allowed */
3629 	if (!__btf_type_is_struct(t))
3630 		return -EINVAL;
3631 
3632 	info->type = type;
3633 	info->off = off;
3634 	info->kptr.type_id = res_id;
3635 	return BTF_FIELD_FOUND;
3636 }
3637 
3638 int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
3639 			   int comp_idx, const char *tag_key, int last_id)
3640 {
3641 	int len = strlen(tag_key);
3642 	int i, n;
3643 
3644 	for (i = last_id + 1, n = btf_nr_types(btf); i < n; i++) {
3645 		const struct btf_type *t = btf_type_by_id(btf, i);
3646 
3647 		if (!btf_type_is_decl_tag(t))
3648 			continue;
3649 		if (pt != btf_type_by_id(btf, t->type))
3650 			continue;
3651 		if (btf_type_decl_tag(t)->component_idx != comp_idx)
3652 			continue;
3653 		if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3654 			continue;
3655 		return i;
3656 	}
3657 	return -ENOENT;
3658 }
3659 
3660 const char *btf_find_decl_tag_value(const struct btf *btf, const struct btf_type *pt,
3661 				    int comp_idx, const char *tag_key)
3662 {
3663 	const char *value = NULL;
3664 	const struct btf_type *t;
3665 	int len, id;
3666 
3667 	id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key,
3668 				    btf_named_start_id(btf, false) - 1);
3669 	if (id < 0)
3670 		return ERR_PTR(id);
3671 
3672 	t = btf_type_by_id(btf, id);
3673 	len = strlen(tag_key);
3674 	value = __btf_name_by_offset(btf, t->name_off) + len;
3675 
3676 	/* Prevent duplicate entries for same type */
3677 	id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, id);
3678 	if (id >= 0)
3679 		return ERR_PTR(-EEXIST);
3680 
3681 	return value;
3682 }
3683 
3684 static int
3685 btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
3686 		    const struct btf_type *t, int comp_idx, u32 off,
3687 		    int sz, struct btf_field_info *info,
3688 		    enum btf_field_type head_type)
3689 {
3690 	const char *node_field_name;
3691 	const char *value_type;
3692 	s32 id;
3693 
3694 	if (!__btf_type_is_struct(t))
3695 		return BTF_FIELD_IGNORE;
3696 	if (t->size != sz)
3697 		return BTF_FIELD_IGNORE;
3698 	value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3699 	if (IS_ERR(value_type))
3700 		return -EINVAL;
3701 	node_field_name = strstr(value_type, ":");
3702 	if (!node_field_name)
3703 		return -EINVAL;
3704 	value_type = kstrndup(value_type, node_field_name - value_type,
3705 			      GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
3706 	if (!value_type)
3707 		return -ENOMEM;
3708 	id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3709 	kfree(value_type);
3710 	if (id < 0)
3711 		return id;
3712 	node_field_name++;
3713 	if (str_is_empty(node_field_name))
3714 		return -EINVAL;
3715 	info->type = head_type;
3716 	info->off = off;
3717 	info->graph_root.value_btf_id = id;
3718 	info->graph_root.node_name = node_field_name;
3719 	return BTF_FIELD_FOUND;
3720 }
3721 
3722 static int btf_get_field_type(const struct btf *btf, const struct btf_type *var_type,
3723 			      u32 field_mask, u32 *seen_mask, int *align, int *sz)
3724 {
3725 	const struct {
3726 		enum btf_field_type type;
3727 		const char *const name;
3728 		const bool is_unique;
3729 	} field_types[] = {
3730 		{ BPF_SPIN_LOCK, "bpf_spin_lock", true },
3731 		{ BPF_RES_SPIN_LOCK, "bpf_res_spin_lock", true },
3732 		{ BPF_TIMER, "bpf_timer", true },
3733 		{ BPF_WORKQUEUE, "bpf_wq", true },
3734 		{ BPF_TASK_WORK, "bpf_task_work", true },
3735 		{ BPF_RCU_HEAD, "bpf_rcu_head", true },
3736 		{ BPF_LIST_HEAD, "bpf_list_head", false },
3737 		{ BPF_LIST_NODE, "bpf_list_node", false },
3738 		{ BPF_RB_ROOT, "bpf_rb_root", false },
3739 		{ BPF_RB_NODE, "bpf_rb_node", false },
3740 		{ BPF_REFCOUNT, "bpf_refcount", true },
3741 	};
3742 	int type = 0, i;
3743 	const char *name = __btf_name_by_offset(btf, var_type->name_off);
3744 	const char *field_type_name;
3745 	enum btf_field_type field_type;
3746 	bool is_unique;
3747 
3748 	for (i = 0; i < ARRAY_SIZE(field_types); ++i) {
3749 		field_type = field_types[i].type;
3750 		field_type_name = field_types[i].name;
3751 		is_unique = field_types[i].is_unique;
3752 		if (!(field_mask & field_type) || strcmp(name, field_type_name))
3753 			continue;
3754 		if (is_unique) {
3755 			if (*seen_mask & field_type)
3756 				return -E2BIG;
3757 			*seen_mask |= field_type;
3758 		}
3759 		type = field_type;
3760 		goto end;
3761 	}
3762 
3763 	/* Only return BPF_KPTR when all other types with matchable names fail */
3764 	if (field_mask & (BPF_KPTR | BPF_UPTR) && !__btf_type_is_struct(var_type)) {
3765 		type = BPF_KPTR_REF;
3766 		goto end;
3767 	}
3768 	return 0;
3769 end:
3770 	*sz = btf_field_type_size(type);
3771 	*align = btf_field_type_align(type);
3772 	return type;
3773 }
3774 
3775 /* Repeat a number of fields for a specified number of times.
3776  *
3777  * Copy the fields starting from the first field and repeat them for
3778  * repeat_cnt times. The fields are repeated by adding the offset of each
3779  * field with
3780  *   (i + 1) * elem_size
3781  * where i is the repeat index and elem_size is the size of an element.
3782  */
3783 static int btf_repeat_fields(struct btf_field_info *info, int info_cnt,
3784 			     u32 field_cnt, u32 repeat_cnt, u32 elem_size)
3785 {
3786 	u32 i, j, total_cnt, total_repeats;
3787 	u32 cur;
3788 
3789 	/* Ensure not repeating fields that should not be repeated. */
3790 	for (i = 0; i < field_cnt; i++) {
3791 		switch (info[i].type) {
3792 		case BPF_KPTR_UNREF:
3793 		case BPF_KPTR_REF:
3794 		case BPF_KPTR_PERCPU:
3795 		case BPF_UPTR:
3796 		case BPF_LIST_HEAD:
3797 		case BPF_RB_ROOT:
3798 			break;
3799 		default:
3800 			return -EINVAL;
3801 		}
3802 	}
3803 
3804 	if (check_add_overflow(repeat_cnt, 1, &total_repeats) ||
3805 	    check_mul_overflow(field_cnt, total_repeats, &total_cnt) ||
3806 	    total_cnt > (u32)info_cnt)
3807 		return -E2BIG;
3808 
3809 	cur = field_cnt;
3810 	for (i = 0; i < repeat_cnt; i++) {
3811 		memcpy(&info[cur], &info[0], field_cnt * sizeof(info[0]));
3812 		for (j = 0; j < field_cnt; j++)
3813 			info[cur++].off += (i + 1) * elem_size;
3814 	}
3815 
3816 	return 0;
3817 }
3818 
3819 static int btf_find_struct_field(const struct btf *btf,
3820 				 const struct btf_type *t, u32 field_mask,
3821 				 struct btf_field_info *info, int info_cnt,
3822 				 u32 level, u32 *seen_mask);
3823 
3824 /* Find special fields in the struct type of a field.
3825  *
3826  * This function is used to find fields of special types that is not a
3827  * global variable or a direct field of a struct type. It also handles the
3828  * repetition if it is the element type of an array.
3829  */
3830 static int btf_find_nested_struct(const struct btf *btf, const struct btf_type *t,
3831 				  u32 off, u32 nelems,
3832 				  u32 field_mask, struct btf_field_info *info,
3833 				  int info_cnt, u32 level, u32 *seen_mask)
3834 {
3835 	int ret, err, i;
3836 
3837 	level++;
3838 	if (level >= MAX_RESOLVE_DEPTH)
3839 		return -E2BIG;
3840 
3841 	ret = btf_find_struct_field(btf, t, field_mask, info, info_cnt, level, seen_mask);
3842 
3843 	if (ret <= 0)
3844 		return ret;
3845 
3846 	/* Shift the offsets of the nested struct fields to the offsets
3847 	 * related to the container.
3848 	 */
3849 	for (i = 0; i < ret; i++)
3850 		info[i].off += off;
3851 
3852 	if (nelems > 1) {
3853 		err = btf_repeat_fields(info, info_cnt, ret, nelems - 1, t->size);
3854 		if (err == 0)
3855 			ret *= nelems;
3856 		else
3857 			ret = err;
3858 	}
3859 
3860 	return ret;
3861 }
3862 
3863 static int btf_find_field_one(const struct btf *btf,
3864 			      const struct btf_type *var,
3865 			      const struct btf_type *var_type,
3866 			      int var_idx,
3867 			      u32 off, u32 expected_size,
3868 			      u32 field_mask, u32 *seen_mask,
3869 			      struct btf_field_info *info, int info_cnt,
3870 			      u32 level)
3871 {
3872 	int ret, align, sz, field_type;
3873 	struct btf_field_info tmp;
3874 	const struct btf_array *array;
3875 	u32 i, nelems = 1;
3876 
3877 	/* Walk into array types to find the element type and the number of
3878 	 * elements in the (flattened) array.
3879 	 */
3880 	for (i = 0; i < MAX_RESOLVE_DEPTH && btf_type_is_array(var_type); i++) {
3881 		array = btf_array(var_type);
3882 		nelems *= array->nelems;
3883 		var_type = btf_type_by_id(btf, array->type);
3884 	}
3885 	if (i == MAX_RESOLVE_DEPTH)
3886 		return -E2BIG;
3887 	if (nelems == 0)
3888 		return 0;
3889 
3890 	field_type = btf_get_field_type(btf, var_type,
3891 					field_mask, seen_mask, &align, &sz);
3892 	/* Look into variables of struct types */
3893 	if (!field_type && __btf_type_is_struct(var_type)) {
3894 		sz = var_type->size;
3895 		if (expected_size && expected_size != sz * nelems)
3896 			return 0;
3897 		ret = btf_find_nested_struct(btf, var_type, off, nelems, field_mask,
3898 					     &info[0], info_cnt, level, seen_mask);
3899 		return ret;
3900 	}
3901 
3902 	if (field_type == 0)
3903 		return 0;
3904 	if (field_type < 0)
3905 		return field_type;
3906 
3907 	if (expected_size && expected_size != sz * nelems)
3908 		return 0;
3909 	if (off % align)
3910 		return 0;
3911 
3912 	switch (field_type) {
3913 	case BPF_SPIN_LOCK:
3914 	case BPF_RES_SPIN_LOCK:
3915 	case BPF_TIMER:
3916 	case BPF_WORKQUEUE:
3917 	case BPF_LIST_NODE:
3918 	case BPF_RB_NODE:
3919 	case BPF_REFCOUNT:
3920 	case BPF_TASK_WORK:
3921 	case BPF_RCU_HEAD:
3922 		ret = btf_find_struct(btf, var_type, off, sz, field_type,
3923 				      info_cnt ? &info[0] : &tmp);
3924 		if (ret < 0)
3925 			return ret;
3926 		break;
3927 	case BPF_KPTR_UNREF:
3928 	case BPF_KPTR_REF:
3929 	case BPF_KPTR_PERCPU:
3930 	case BPF_UPTR:
3931 		ret = btf_find_kptr(btf, var_type, off, sz,
3932 				    info_cnt ? &info[0] : &tmp, field_mask);
3933 		if (ret < 0)
3934 			return ret;
3935 		break;
3936 	case BPF_LIST_HEAD:
3937 	case BPF_RB_ROOT:
3938 		ret = btf_find_graph_root(btf, var, var_type,
3939 					  var_idx, off, sz,
3940 					  info_cnt ? &info[0] : &tmp,
3941 					  field_type);
3942 		if (ret < 0)
3943 			return ret;
3944 		break;
3945 	default:
3946 		return -EFAULT;
3947 	}
3948 
3949 	if (ret == BTF_FIELD_IGNORE)
3950 		return 0;
3951 	if (!info_cnt)
3952 		return -E2BIG;
3953 	if (nelems > 1) {
3954 		ret = btf_repeat_fields(info, info_cnt, 1, nelems - 1, sz);
3955 		if (ret < 0)
3956 			return ret;
3957 	}
3958 	return nelems;
3959 }
3960 
3961 static int btf_find_struct_field(const struct btf *btf,
3962 				 const struct btf_type *t, u32 field_mask,
3963 				 struct btf_field_info *info, int info_cnt,
3964 				 u32 level, u32 *seen_mask)
3965 {
3966 	int ret, idx = 0;
3967 	const struct btf_member *member;
3968 	u32 i, off;
3969 
3970 	for_each_member(i, t, member) {
3971 		const struct btf_type *member_type = btf_type_by_id(btf,
3972 								    member->type);
3973 
3974 		off = __btf_member_bit_offset(t, member);
3975 		if (off % 8)
3976 			/* valid C code cannot generate such BTF */
3977 			return -EINVAL;
3978 		off /= 8;
3979 
3980 		ret = btf_find_field_one(btf, t, member_type, i,
3981 					 off, 0,
3982 					 field_mask, seen_mask,
3983 					 &info[idx], info_cnt - idx, level);
3984 		if (ret < 0)
3985 			return ret;
3986 		idx += ret;
3987 	}
3988 	return idx;
3989 }
3990 
3991 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3992 				u32 field_mask, struct btf_field_info *info,
3993 				int info_cnt, u32 level, u32 *seen_mask)
3994 {
3995 	int ret, idx = 0;
3996 	const struct btf_var_secinfo *vsi;
3997 	u32 i, off;
3998 
3999 	for_each_vsi(i, t, vsi) {
4000 		const struct btf_type *var = btf_type_by_id(btf, vsi->type);
4001 		const struct btf_type *var_type = btf_type_by_id(btf, var->type);
4002 
4003 		off = vsi->offset;
4004 		ret = btf_find_field_one(btf, var, var_type, -1, off, vsi->size,
4005 					 field_mask, seen_mask,
4006 					 &info[idx], info_cnt - idx,
4007 					 level);
4008 		if (ret < 0)
4009 			return ret;
4010 		idx += ret;
4011 	}
4012 	return idx;
4013 }
4014 
4015 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
4016 			  u32 field_mask, struct btf_field_info *info,
4017 			  int info_cnt)
4018 {
4019 	u32 seen_mask = 0;
4020 
4021 	if (__btf_type_is_struct(t))
4022 		return btf_find_struct_field(btf, t, field_mask, info, info_cnt, 0, &seen_mask);
4023 	else if (btf_type_is_datasec(t))
4024 		return btf_find_datasec_var(btf, t, field_mask, info, info_cnt, 0, &seen_mask);
4025 	return -EINVAL;
4026 }
4027 
4028 /* Callers have to ensure the life cycle of btf if it is program BTF */
4029 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
4030 			  struct btf_field_info *info)
4031 {
4032 	struct module *mod = NULL;
4033 	const struct btf_type *t;
4034 	/* If a matching btf type is found in kernel or module BTFs, kptr_ref
4035 	 * is that BTF, otherwise it's program BTF
4036 	 */
4037 	struct btf *kptr_btf;
4038 	int ret;
4039 	s32 id;
4040 
4041 	/* Find type in map BTF, and use it to look up the matching type
4042 	 * in vmlinux or module BTFs, by name and kind.
4043 	 */
4044 	t = btf_type_by_id(btf, info->kptr.type_id);
4045 	id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
4046 			     &kptr_btf);
4047 	if (id == -ENOENT) {
4048 		/* btf_parse_kptr should only be called w/ btf = program BTF */
4049 		WARN_ON_ONCE(btf_is_kernel(btf));
4050 
4051 		/* Type exists only in program BTF. Assume that it's a MEM_ALLOC
4052 		 * kptr allocated via bpf_obj_new
4053 		 */
4054 		field->kptr.dtor = NULL;
4055 		id = info->kptr.type_id;
4056 		kptr_btf = (struct btf *)btf;
4057 		goto found_dtor;
4058 	}
4059 	if (id < 0)
4060 		return id;
4061 
4062 	/* Find and stash the function pointer for the destruction function that
4063 	 * needs to be eventually invoked from the map free path.
4064 	 */
4065 	if (info->type == BPF_KPTR_REF) {
4066 		const struct btf_type *dtor_func;
4067 		const char *dtor_func_name;
4068 		unsigned long addr;
4069 		s32 dtor_btf_id;
4070 
4071 		/* This call also serves as a whitelist of allowed objects that
4072 		 * can be used as a referenced pointer and be stored in a map at
4073 		 * the same time.
4074 		 */
4075 		dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
4076 		if (dtor_btf_id < 0) {
4077 			ret = dtor_btf_id;
4078 			goto end_btf;
4079 		}
4080 
4081 		dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
4082 		if (!dtor_func) {
4083 			ret = -ENOENT;
4084 			goto end_btf;
4085 		}
4086 
4087 		if (btf_is_module(kptr_btf)) {
4088 			mod = btf_try_get_module(kptr_btf);
4089 			if (!mod) {
4090 				ret = -ENXIO;
4091 				goto end_btf;
4092 			}
4093 		}
4094 
4095 		/* We already verified dtor_func to be btf_type_is_func
4096 		 * in register_btf_id_dtor_kfuncs.
4097 		 */
4098 		dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
4099 		addr = kallsyms_lookup_name(dtor_func_name);
4100 		if (!addr) {
4101 			ret = -EINVAL;
4102 			goto end_mod;
4103 		}
4104 		field->kptr.dtor = (void *)addr;
4105 	}
4106 
4107 found_dtor:
4108 	field->kptr.btf_id = id;
4109 	field->kptr.btf = kptr_btf;
4110 	field->kptr.module = mod;
4111 	return 0;
4112 end_mod:
4113 	module_put(mod);
4114 end_btf:
4115 	btf_put(kptr_btf);
4116 	return ret;
4117 }
4118 
4119 static int btf_parse_graph_root(const struct btf *btf,
4120 				struct btf_field *field,
4121 				struct btf_field_info *info,
4122 				const char *node_type_name,
4123 				size_t node_type_align)
4124 {
4125 	const struct btf_type *t, *n = NULL;
4126 	const struct btf_member *member;
4127 	u32 offset;
4128 	int i;
4129 
4130 	t = btf_type_by_id(btf, info->graph_root.value_btf_id);
4131 	/* We've already checked that value_btf_id is a struct type. We
4132 	 * just need to figure out the offset of the list_node, and
4133 	 * verify its type.
4134 	 */
4135 	for_each_member(i, t, member) {
4136 		if (strcmp(info->graph_root.node_name,
4137 			   __btf_name_by_offset(btf, member->name_off)))
4138 			continue;
4139 		/* Invalid BTF, two members with same name */
4140 		if (n)
4141 			return -EINVAL;
4142 		n = btf_type_by_id(btf, member->type);
4143 		if (!__btf_type_is_struct(n))
4144 			return -EINVAL;
4145 		if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
4146 			return -EINVAL;
4147 		offset = __btf_member_bit_offset(n, member);
4148 		if (offset % 8)
4149 			return -EINVAL;
4150 		offset /= 8;
4151 		if (offset % node_type_align)
4152 			return -EINVAL;
4153 
4154 		field->graph_root.btf = (struct btf *)btf;
4155 		field->graph_root.value_btf_id = info->graph_root.value_btf_id;
4156 		field->graph_root.node_offset = offset;
4157 	}
4158 	if (!n)
4159 		return -ENOENT;
4160 	return 0;
4161 }
4162 
4163 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
4164 			       struct btf_field_info *info)
4165 {
4166 	return btf_parse_graph_root(btf, field, info, "bpf_list_node",
4167 					    __alignof__(struct bpf_list_node));
4168 }
4169 
4170 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
4171 			     struct btf_field_info *info)
4172 {
4173 	return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
4174 					    __alignof__(struct bpf_rb_node));
4175 }
4176 
4177 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
4178 {
4179 	const struct btf_field *a = (const struct btf_field *)_a;
4180 	const struct btf_field *b = (const struct btf_field *)_b;
4181 
4182 	if (a->offset < b->offset)
4183 		return -1;
4184 	else if (a->offset > b->offset)
4185 		return 1;
4186 	return 0;
4187 }
4188 
4189 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
4190 				    u32 field_mask, u32 value_size)
4191 {
4192 	struct btf_field_info info_arr[BTF_FIELDS_MAX];
4193 	u32 next_off = 0, field_type_size;
4194 	struct btf_record *rec;
4195 	int ret, i, cnt;
4196 
4197 	ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
4198 	if (ret < 0)
4199 		return ERR_PTR(ret);
4200 	if (!ret)
4201 		return NULL;
4202 
4203 	cnt = ret;
4204 	/* This needs to be kzalloc to zero out padding and unused fields, see
4205 	 * comment in btf_record_equal.
4206 	 */
4207 	rec = kzalloc_flex(*rec, fields, cnt, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
4208 	if (!rec)
4209 		return ERR_PTR(-ENOMEM);
4210 
4211 	rec->spin_lock_off = -EINVAL;
4212 	rec->res_spin_lock_off = -EINVAL;
4213 	rec->timer_off = -EINVAL;
4214 	rec->wq_off = -EINVAL;
4215 	rec->refcount_off = -EINVAL;
4216 	rec->task_work_off = -EINVAL;
4217 	rec->rcu_head_off = -EINVAL;
4218 	for (i = 0; i < cnt; i++) {
4219 		field_type_size = btf_field_type_size(info_arr[i].type);
4220 		if (info_arr[i].off + field_type_size > value_size) {
4221 			WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
4222 			ret = -EFAULT;
4223 			goto end;
4224 		}
4225 		if (info_arr[i].off < next_off) {
4226 			ret = -EEXIST;
4227 			goto end;
4228 		}
4229 		next_off = info_arr[i].off + field_type_size;
4230 
4231 		rec->field_mask |= info_arr[i].type;
4232 		rec->fields[i].offset = info_arr[i].off;
4233 		rec->fields[i].type = info_arr[i].type;
4234 		rec->fields[i].size = field_type_size;
4235 
4236 		switch (info_arr[i].type) {
4237 		case BPF_SPIN_LOCK:
4238 			WARN_ON_ONCE(rec->spin_lock_off >= 0);
4239 			/* Cache offset for faster lookup at runtime */
4240 			rec->spin_lock_off = rec->fields[i].offset;
4241 			break;
4242 		case BPF_RES_SPIN_LOCK:
4243 			WARN_ON_ONCE(rec->res_spin_lock_off >= 0);
4244 			/* Cache offset for faster lookup at runtime */
4245 			rec->res_spin_lock_off = rec->fields[i].offset;
4246 			break;
4247 		case BPF_TIMER:
4248 			WARN_ON_ONCE(rec->timer_off >= 0);
4249 			/* Cache offset for faster lookup at runtime */
4250 			rec->timer_off = rec->fields[i].offset;
4251 			break;
4252 		case BPF_WORKQUEUE:
4253 			WARN_ON_ONCE(rec->wq_off >= 0);
4254 			/* Cache offset for faster lookup at runtime */
4255 			rec->wq_off = rec->fields[i].offset;
4256 			break;
4257 		case BPF_TASK_WORK:
4258 			WARN_ON_ONCE(rec->task_work_off >= 0);
4259 			rec->task_work_off = rec->fields[i].offset;
4260 			break;
4261 		case BPF_RCU_HEAD:
4262 			WARN_ON_ONCE(rec->rcu_head_off >= 0);
4263 			rec->rcu_head_off = rec->fields[i].offset;
4264 			break;
4265 		case BPF_REFCOUNT:
4266 			WARN_ON_ONCE(rec->refcount_off >= 0);
4267 			/* Cache offset for faster lookup at runtime */
4268 			rec->refcount_off = rec->fields[i].offset;
4269 			break;
4270 		case BPF_KPTR_UNREF:
4271 		case BPF_KPTR_REF:
4272 		case BPF_KPTR_PERCPU:
4273 		case BPF_UPTR:
4274 			ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
4275 			if (ret < 0)
4276 				goto end;
4277 			break;
4278 		case BPF_LIST_HEAD:
4279 			ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
4280 			if (ret < 0)
4281 				goto end;
4282 			break;
4283 		case BPF_RB_ROOT:
4284 			ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
4285 			if (ret < 0)
4286 				goto end;
4287 			break;
4288 		case BPF_LIST_NODE:
4289 		case BPF_RB_NODE:
4290 			break;
4291 		default:
4292 			ret = -EFAULT;
4293 			goto end;
4294 		}
4295 		rec->cnt++;
4296 	}
4297 
4298 	if (rec->spin_lock_off >= 0 && rec->res_spin_lock_off >= 0) {
4299 		ret = -EINVAL;
4300 		goto end;
4301 	}
4302 
4303 	/* bpf_{list_head, rb_node} require bpf_spin_lock */
4304 	if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
4305 	     btf_record_has_field(rec, BPF_RB_ROOT)) &&
4306 		 (rec->spin_lock_off < 0 && rec->res_spin_lock_off < 0)) {
4307 		ret = -EINVAL;
4308 		goto end;
4309 	}
4310 
4311 	if (rec->refcount_off < 0 &&
4312 	    btf_record_has_field(rec, BPF_LIST_NODE) &&
4313 	    btf_record_has_field(rec, BPF_RB_NODE)) {
4314 		ret = -EINVAL;
4315 		goto end;
4316 	}
4317 
4318 	sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
4319 	       NULL, rec);
4320 
4321 	return rec;
4322 end:
4323 	btf_record_free(rec);
4324 	return ERR_PTR(ret);
4325 }
4326 
4327 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
4328 {
4329 	int i;
4330 
4331 	/*
4332 	 * Check fields which require the complete BTF and initialize runtime
4333 	 * metadata. Ownership relationships are validated after every record has
4334 	 * been fixed up.
4335 	 */
4336 	if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & (BPF_GRAPH_ROOT | BPF_UPTR)))
4337 		return 0;
4338 	for (i = 0; i < rec->cnt; i++) {
4339 		struct btf_struct_meta *meta;
4340 		const struct btf_type *t;
4341 		u32 btf_id;
4342 
4343 		if (rec->fields[i].type == BPF_UPTR) {
4344 			/* The uptr only supports pinning one page and cannot
4345 			 * point to a kernel struct
4346 			 */
4347 			if (btf_is_kernel(rec->fields[i].kptr.btf))
4348 				return -EINVAL;
4349 			t = btf_type_by_id(rec->fields[i].kptr.btf,
4350 					   rec->fields[i].kptr.btf_id);
4351 			if (!t->size)
4352 				return -EINVAL;
4353 			if (t->size > PAGE_SIZE)
4354 				return -E2BIG;
4355 			continue;
4356 		}
4357 
4358 		if (!(rec->fields[i].type & BPF_GRAPH_ROOT))
4359 			continue;
4360 		btf_id = rec->fields[i].graph_root.value_btf_id;
4361 		meta = btf_find_struct_meta(btf, btf_id);
4362 		if (!meta)
4363 			return -EFAULT;
4364 		rec->fields[i].graph_root.value_rec = meta->record;
4365 	}
4366 	return 0;
4367 }
4368 
4369 static int btf_owned_type_idx(const struct btf *btf, struct btf_struct_metas *tab,
4370 			      const struct btf_field *field)
4371 {
4372 	struct btf_struct_meta *meta;
4373 	u32 btf_id;
4374 
4375 	if (field->type & BPF_GRAPH_ROOT) {
4376 		btf_id = field->graph_root.value_btf_id;
4377 	} else if (field->type == BPF_KPTR_REF || field->type == BPF_KPTR_PERCPU) {
4378 		if (btf_is_kernel(field->kptr.btf))
4379 			return -ENOENT;
4380 		btf_id = field->kptr.btf_id;
4381 	} else {
4382 		return -ENOENT;
4383 	}
4384 
4385 	meta = btf_find_struct_meta(btf, btf_id);
4386 	if (!meta)
4387 		return field->type & BPF_GRAPH_ROOT ? -EFAULT : -ENOENT;
4388 	return meta - tab->types;
4389 }
4390 
4391 /*
4392  * Each ownership edge adds kernel frames through bpf_obj_free_fields() and
4393  * __bpf_obj_drop_impl(). Keep the bound deliberately small because object
4394  * destruction can itself run below a BPF call chain. A final pointee without
4395  * special fields is not present in the struct metadata table and adds only a
4396  * non-recursing drop.
4397  */
4398 #define BTF_MAX_OWNERSHIP_DEPTH 8
4399 
4400 static int btf_ownership_depth(const struct btf *btf,
4401 			       struct btf_struct_metas *tab, u8 *depth,
4402 			       int idx, int depth_left)
4403 {
4404 	const struct btf_record *rec = tab->types[idx].record;
4405 	int i, ret, max_depth = 0;
4406 
4407 	if (!depth_left)
4408 		return -ELOOP;
4409 	if (depth[idx])
4410 		goto done;
4411 
4412 	for (i = 0; i < rec->cnt; i++) {
4413 		ret = btf_owned_type_idx(btf, tab, &rec->fields[i]);
4414 		if (ret == -ENOENT)
4415 			continue;
4416 		if (ret < 0)
4417 			return ret;
4418 		ret = btf_ownership_depth(btf, tab, depth, ret, depth_left - 1);
4419 		if (ret < 0)
4420 			return ret;
4421 		max_depth = max(max_depth, ret);
4422 	}
4423 	depth[idx] = max_depth + 1;
4424 done:
4425 	return depth[idx] > depth_left ? -ELOOP : depth[idx];
4426 }
4427 
4428 static int btf_check_ownership_depth(const struct btf *btf,
4429 				     struct btf_struct_metas *tab)
4430 {
4431 	u8 *depth;
4432 	int i, ret = 0;
4433 
4434 	depth = kvcalloc(tab->cnt, sizeof(*depth), GFP_KERNEL | __GFP_NOWARN);
4435 	if (!depth)
4436 		return -ENOMEM;
4437 
4438 	for (i = 0; i < tab->cnt; i++) {
4439 		ret = btf_ownership_depth(btf, tab, depth, i,
4440 					  BTF_MAX_OWNERSHIP_DEPTH);
4441 		if (ret < 0)
4442 			break;
4443 		ret = 0;
4444 	}
4445 	kvfree(depth);
4446 	return ret;
4447 }
4448 
4449 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
4450 			      u32 type_id, void *data, u8 bits_offset,
4451 			      struct btf_show *show)
4452 {
4453 	const struct btf_member *member;
4454 	void *safe_data;
4455 	u32 i;
4456 
4457 	safe_data = btf_show_start_struct_type(show, t, type_id, data);
4458 	if (!safe_data)
4459 		return;
4460 
4461 	for_each_member(i, t, member) {
4462 		const struct btf_type *member_type = btf_type_by_id(btf,
4463 								member->type);
4464 		const struct btf_kind_operations *ops;
4465 		u32 member_offset, bitfield_size;
4466 		u32 bytes_offset;
4467 		u8 bits8_offset;
4468 
4469 		btf_show_start_member(show, member);
4470 
4471 		member_offset = __btf_member_bit_offset(t, member);
4472 		bitfield_size = __btf_member_bitfield_size(t, member);
4473 		bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
4474 		bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
4475 		if (bitfield_size) {
4476 			safe_data = btf_show_start_type(show, member_type,
4477 							member->type,
4478 							data + bytes_offset);
4479 			if (safe_data)
4480 				btf_bitfield_show(safe_data,
4481 						  bits8_offset,
4482 						  bitfield_size, show);
4483 			btf_show_end_type(show);
4484 		} else {
4485 			ops = btf_type_ops(member_type);
4486 			ops->show(btf, member_type, member->type,
4487 				  data + bytes_offset, bits8_offset, show);
4488 		}
4489 
4490 		btf_show_end_member(show);
4491 	}
4492 
4493 	btf_show_end_struct_type(show);
4494 }
4495 
4496 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
4497 			    u32 type_id, void *data, u8 bits_offset,
4498 			    struct btf_show *show)
4499 {
4500 	const struct btf_member *m = show->state.member;
4501 
4502 	/*
4503 	 * First check if any members would be shown (are non-zero).
4504 	 * See comments above "struct btf_show" definition for more
4505 	 * details on how this works at a high-level.
4506 	 */
4507 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
4508 		if (!show->state.depth_check) {
4509 			show->state.depth_check = show->state.depth + 1;
4510 			show->state.depth_to_show = 0;
4511 		}
4512 		__btf_struct_show(btf, t, type_id, data, bits_offset, show);
4513 		/* Restore saved member data here */
4514 		show->state.member = m;
4515 		if (show->state.depth_check != show->state.depth + 1)
4516 			return;
4517 		show->state.depth_check = 0;
4518 
4519 		if (show->state.depth_to_show <= show->state.depth)
4520 			return;
4521 		/*
4522 		 * Reaching here indicates we have recursed and found
4523 		 * non-zero child values.
4524 		 */
4525 	}
4526 
4527 	__btf_struct_show(btf, t, type_id, data, bits_offset, show);
4528 }
4529 
4530 static const struct btf_kind_operations struct_ops = {
4531 	.check_meta = btf_struct_check_meta,
4532 	.resolve = btf_struct_resolve,
4533 	.check_member = btf_struct_check_member,
4534 	.check_kflag_member = btf_generic_check_kflag_member,
4535 	.log_details = btf_struct_log,
4536 	.show = btf_struct_show,
4537 };
4538 
4539 static int btf_enum_check_member(struct btf_verifier_env *env,
4540 				 const struct btf_type *struct_type,
4541 				 const struct btf_member *member,
4542 				 const struct btf_type *member_type)
4543 {
4544 	u32 struct_bits_off = member->offset;
4545 	u32 struct_size, bytes_offset;
4546 
4547 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4548 		btf_verifier_log_member(env, struct_type, member,
4549 					"Member is not byte aligned");
4550 		return -EINVAL;
4551 	}
4552 
4553 	struct_size = struct_type->size;
4554 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4555 	if (struct_size - bytes_offset < member_type->size) {
4556 		btf_verifier_log_member(env, struct_type, member,
4557 					"Member exceeds struct_size");
4558 		return -EINVAL;
4559 	}
4560 
4561 	return 0;
4562 }
4563 
4564 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4565 				       const struct btf_type *struct_type,
4566 				       const struct btf_member *member,
4567 				       const struct btf_type *member_type)
4568 {
4569 	u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4570 	u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4571 
4572 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4573 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4574 	if (!nr_bits) {
4575 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4576 			btf_verifier_log_member(env, struct_type, member,
4577 						"Member is not byte aligned");
4578 			return -EINVAL;
4579 		}
4580 
4581 		nr_bits = int_bitsize;
4582 	} else if (nr_bits > int_bitsize) {
4583 		btf_verifier_log_member(env, struct_type, member,
4584 					"Invalid member bitfield_size");
4585 		return -EINVAL;
4586 	}
4587 
4588 	struct_size = struct_type->size;
4589 	bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4590 	if (struct_size < bytes_end) {
4591 		btf_verifier_log_member(env, struct_type, member,
4592 					"Member exceeds struct_size");
4593 		return -EINVAL;
4594 	}
4595 
4596 	return 0;
4597 }
4598 
4599 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4600 			       const struct btf_type *t,
4601 			       u32 meta_left)
4602 {
4603 	const struct btf_enum *enums = btf_type_enum(t);
4604 	struct btf *btf = env->btf;
4605 	const char *fmt_str;
4606 	u32 i, nr_enums;
4607 	u32 meta_needed;
4608 
4609 	nr_enums = btf_type_vlen(t);
4610 	meta_needed = nr_enums * sizeof(*enums);
4611 
4612 	if (meta_left < meta_needed) {
4613 		btf_verifier_log_basic(env, t,
4614 				       "meta_left:%u meta_needed:%u",
4615 				       meta_left, meta_needed);
4616 		return -EINVAL;
4617 	}
4618 
4619 	if (t->size > 8 || !is_power_of_2(t->size)) {
4620 		btf_verifier_log_type(env, t, "Unexpected size");
4621 		return -EINVAL;
4622 	}
4623 
4624 	/* enum type either no name or a valid one */
4625 	if (t->name_off &&
4626 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4627 		btf_verifier_log_type(env, t, "Invalid name");
4628 		return -EINVAL;
4629 	}
4630 
4631 	btf_verifier_log_type(env, t, NULL);
4632 
4633 	for (i = 0; i < nr_enums; i++) {
4634 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4635 			btf_verifier_log(env, "\tInvalid name_offset:%u",
4636 					 enums[i].name_off);
4637 			return -EINVAL;
4638 		}
4639 
4640 		/* enum member must have a valid name */
4641 		if (!enums[i].name_off ||
4642 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
4643 			btf_verifier_log_type(env, t, "Invalid name");
4644 			return -EINVAL;
4645 		}
4646 
4647 		if (env->log.level == BPF_LOG_KERNEL)
4648 			continue;
4649 		fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4650 		btf_verifier_log(env, fmt_str,
4651 				 __btf_name_by_offset(btf, enums[i].name_off),
4652 				 enums[i].val);
4653 	}
4654 
4655 	return meta_needed;
4656 }
4657 
4658 static void btf_enum_log(struct btf_verifier_env *env,
4659 			 const struct btf_type *t)
4660 {
4661 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4662 }
4663 
4664 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4665 			  u32 type_id, void *data, u8 bits_offset,
4666 			  struct btf_show *show)
4667 {
4668 	const struct btf_enum *enums = btf_type_enum(t);
4669 	u32 i, nr_enums = btf_type_vlen(t);
4670 	void *safe_data;
4671 	int v;
4672 
4673 	safe_data = btf_show_start_type(show, t, type_id, data);
4674 	if (!safe_data)
4675 		return;
4676 
4677 	v = *(int *)safe_data;
4678 
4679 	for (i = 0; i < nr_enums; i++) {
4680 		if (v != enums[i].val)
4681 			continue;
4682 
4683 		btf_show_type_value(show, "%s",
4684 				    __btf_name_by_offset(btf,
4685 							 enums[i].name_off));
4686 
4687 		btf_show_end_type(show);
4688 		return;
4689 	}
4690 
4691 	if (btf_type_kflag(t))
4692 		btf_show_type_value(show, "%d", v);
4693 	else
4694 		btf_show_type_value(show, "%u", v);
4695 	btf_show_end_type(show);
4696 }
4697 
4698 static const struct btf_kind_operations enum_ops = {
4699 	.check_meta = btf_enum_check_meta,
4700 	.resolve = btf_df_resolve,
4701 	.check_member = btf_enum_check_member,
4702 	.check_kflag_member = btf_enum_check_kflag_member,
4703 	.log_details = btf_enum_log,
4704 	.show = btf_enum_show,
4705 };
4706 
4707 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4708 				 const struct btf_type *t,
4709 				 u32 meta_left)
4710 {
4711 	const struct btf_enum64 *enums = btf_type_enum64(t);
4712 	struct btf *btf = env->btf;
4713 	const char *fmt_str;
4714 	u32 i, nr_enums;
4715 	u32 meta_needed;
4716 
4717 	nr_enums = btf_type_vlen(t);
4718 	meta_needed = nr_enums * sizeof(*enums);
4719 
4720 	if (meta_left < meta_needed) {
4721 		btf_verifier_log_basic(env, t,
4722 				       "meta_left:%u meta_needed:%u",
4723 				       meta_left, meta_needed);
4724 		return -EINVAL;
4725 	}
4726 
4727 	if (t->size > 8 || !is_power_of_2(t->size)) {
4728 		btf_verifier_log_type(env, t, "Unexpected size");
4729 		return -EINVAL;
4730 	}
4731 
4732 	/* enum type either no name or a valid one */
4733 	if (t->name_off &&
4734 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4735 		btf_verifier_log_type(env, t, "Invalid name");
4736 		return -EINVAL;
4737 	}
4738 
4739 	btf_verifier_log_type(env, t, NULL);
4740 
4741 	for (i = 0; i < nr_enums; i++) {
4742 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4743 			btf_verifier_log(env, "\tInvalid name_offset:%u",
4744 					 enums[i].name_off);
4745 			return -EINVAL;
4746 		}
4747 
4748 		/* enum member must have a valid name */
4749 		if (!enums[i].name_off ||
4750 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
4751 			btf_verifier_log_type(env, t, "Invalid name");
4752 			return -EINVAL;
4753 		}
4754 
4755 		if (env->log.level == BPF_LOG_KERNEL)
4756 			continue;
4757 
4758 		fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4759 		btf_verifier_log(env, fmt_str,
4760 				 __btf_name_by_offset(btf, enums[i].name_off),
4761 				 btf_enum64_value(enums + i));
4762 	}
4763 
4764 	return meta_needed;
4765 }
4766 
4767 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4768 			    u32 type_id, void *data, u8 bits_offset,
4769 			    struct btf_show *show)
4770 {
4771 	const struct btf_enum64 *enums = btf_type_enum64(t);
4772 	u32 i, nr_enums = btf_type_vlen(t);
4773 	void *safe_data;
4774 	s64 v;
4775 
4776 	safe_data = btf_show_start_type(show, t, type_id, data);
4777 	if (!safe_data)
4778 		return;
4779 
4780 	v = *(u64 *)safe_data;
4781 
4782 	for (i = 0; i < nr_enums; i++) {
4783 		if (v != btf_enum64_value(enums + i))
4784 			continue;
4785 
4786 		btf_show_type_value(show, "%s",
4787 				    __btf_name_by_offset(btf,
4788 							 enums[i].name_off));
4789 
4790 		btf_show_end_type(show);
4791 		return;
4792 	}
4793 
4794 	if (btf_type_kflag(t))
4795 		btf_show_type_value(show, "%lld", v);
4796 	else
4797 		btf_show_type_value(show, "%llu", v);
4798 	btf_show_end_type(show);
4799 }
4800 
4801 static const struct btf_kind_operations enum64_ops = {
4802 	.check_meta = btf_enum64_check_meta,
4803 	.resolve = btf_df_resolve,
4804 	.check_member = btf_enum_check_member,
4805 	.check_kflag_member = btf_enum_check_kflag_member,
4806 	.log_details = btf_enum_log,
4807 	.show = btf_enum64_show,
4808 };
4809 
4810 static s32 btf_loc_param_check_meta(struct btf_verifier_env *env,
4811 				    const struct btf_type *t,
4812 				    u32 meta_left)
4813 {
4814 	const struct btf_loc_param *p = btf_loc_param(t);
4815 	u32 size, meta_needed, vlen = btf_vlen(t);
4816 
4817 	meta_needed = sizeof(*p) + sizeof(__u32) * vlen;
4818 	if (meta_left < meta_needed) {
4819 		btf_verifier_log_basic(env, t,
4820 				       "meta_left:%u meta_needed:%u",
4821 				      meta_left, meta_needed);
4822 		return -EINVAL;
4823 	}
4824 
4825 	if (t->name_off) {
4826 		btf_verifier_log_type(env, t, "Invalid name");
4827 		return -EINVAL;
4828 	}
4829 	size = t->size;
4830 	if (!size || size > 16) {
4831 		btf_verifier_log_type(env, t, "Unexpected size");
4832 		return -EINVAL;
4833 	}
4834 
4835 	if (btf_type_kflag(t)) {
4836 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4837 		return -EINVAL;
4838 	}
4839 	/* All LOC_PARAMs have vlen of at least 1 */
4840 	if (vlen < 1)
4841 		goto invalid_vlen;
4842 
4843 	switch (p->flags) {
4844 	case BTF_LOC_PARAM_CONST:
4845 	case BTF_LOC_PARAM_CONST | BTF_LOC_PARAM_SIGNED:
4846 	case BTF_LOC_PARAM_CONST | BTF_LOC_PARAM_ADDR:
4847 	case BTF_LOC_PARAM_CONST | BTF_LOC_PARAM_ADDR | BTF_LOC_PARAM_SIGNED:
4848 		if (vlen < 1 || vlen > 2)
4849 			goto invalid_vlen;
4850 		if (!size || size > sizeof(__u64))
4851 			goto invalid_vlen;
4852 		/* Ensure size/vlen are consistent */
4853 		if (vlen != (size > sizeof(__u32) ? 2 : 1))
4854 			goto invalid_vlen;
4855 		break;
4856 	case BTF_LOC_PARAM_REG:
4857 		/* Reg or reg/reg pair */
4858 		if (vlen > 2)
4859 			goto invalid_vlen;
4860 		break;
4861 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_DEREF:
4862 		/* A reg deref without offset can only have vlen 1 */
4863 		if (vlen != 1)
4864 			goto invalid_vlen;
4865 		break;
4866 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_OFFSET:
4867 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_OFFSET | BTF_LOC_PARAM_SIGNED:
4868 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_DEREF | BTF_LOC_PARAM_OFFSET:
4869 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_DEREF | BTF_LOC_PARAM_OFFSET |
4870 	     BTF_LOC_PARAM_SIGNED:
4871 		if (vlen < 2 || vlen > 3)
4872 			goto invalid_vlen;
4873 		break;
4874 	default:
4875 		btf_verifier_log_type(env, t, "Invalid flags");
4876 		return -EINVAL;
4877 	}
4878 
4879 	btf_verifier_log_type(env, t, NULL);
4880 
4881 	return meta_needed;
4882 
4883 invalid_vlen:
4884 	btf_verifier_log_type(env, t, "Invalid vlen");
4885 	return -EINVAL;
4886 }
4887 
4888 static void btf_loc_param_log(struct btf_verifier_env *env,
4889 			 const struct btf_type *t)
4890 {
4891 	const struct btf_loc_param *p = btf_loc_param(t);
4892 	u32 i, vlen = btf_vlen(t);
4893 
4894 	btf_verifier_log(env, "size=%u vlen=%u flags=0x%x", t->size, vlen, p->flags);
4895 	for (i = 0; i < vlen; i++)
4896 		btf_verifier_log(env, ", %u", p->values[i]);
4897 }
4898 
4899 static const struct btf_kind_operations loc_param_ops = {
4900 	.check_meta = btf_loc_param_check_meta,
4901 	.resolve = btf_df_resolve,
4902 	.check_member = btf_df_check_member,
4903 	.check_kflag_member = btf_df_check_kflag_member,
4904 	.log_details = btf_loc_param_log,
4905 	.show = btf_df_show,
4906 };
4907 
4908 static s32 btf_loc_proto_check_meta(struct btf_verifier_env *env,
4909 				    const struct btf_type *t,
4910 				    u32 meta_left)
4911 {
4912 	u32 meta_needed;
4913 
4914 	meta_needed = sizeof(__u32) * btf_type_vlen(t);
4915 
4916 	if (meta_left < meta_needed) {
4917 		btf_verifier_log_basic(env, t,
4918 				       "meta_left:%u meta_needed:%u",
4919 				      meta_left, meta_needed);
4920 		return -EINVAL;
4921 	}
4922 
4923 	if (t->name_off) {
4924 		btf_verifier_log_type(env, t, "Invalid name");
4925 		return -EINVAL;
4926 	}
4927 
4928 	if (btf_type_kflag(t)) {
4929 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4930 		return -EINVAL;
4931 	}
4932 
4933 	btf_verifier_log_type(env, t, NULL);
4934 
4935 	return meta_needed;
4936 }
4937 
4938 static void btf_loc_proto_log(struct btf_verifier_env *env,
4939 			      const struct btf_type *t)
4940 {
4941 	const __u32 *params = btf_loc_proto_params(t);
4942 	u32 i, nr_params = btf_type_vlen(t);
4943 
4944 	btf_verifier_log(env, "vlen=%u", nr_params);
4945 	for (i = 0; i < nr_params; i++, params++)
4946 		btf_verifier_log(env, ", %u", *params);
4947 }
4948 
4949 static int btf_loc_proto_resolve(struct btf_verifier_env *env,
4950 				 const struct resolve_vertex *v)
4951 {
4952 	const struct btf_type *t = v->t;
4953 	const __u32 *params = btf_loc_proto_params(t);
4954 	u32 i, nr_params = btf_type_vlen(t);
4955 	struct btf *btf = env->btf;
4956 
4957 	if (t->type) {
4958 		btf_verifier_log_type(env, t, "Invalid loc_proto type");
4959 		return -EINVAL;
4960 	}
4961 
4962 	for (i = 0; i < nr_params; i++) {
4963 		const struct btf_type *param_type;
4964 		u32 param_type_id = params[i];
4965 
4966 		if (!param_type_id)
4967 			continue;
4968 
4969 		param_type = btf_type_by_id(btf, param_type_id);
4970 		if (!param_type || !btf_type_is_loc_param(param_type)) {
4971 			btf_verifier_log_type(env, t,
4972 					      "Invalid loc_param#%u", i + 1);
4973 			return -EINVAL;
4974 		}
4975 	}
4976 
4977 	env_stack_pop_resolved(env, 0, 0);
4978 	return 0;
4979 }
4980 
4981 static const struct btf_kind_operations loc_proto_ops = {
4982 	.check_meta = btf_loc_proto_check_meta,
4983 	.resolve = btf_loc_proto_resolve,
4984 	.check_member = btf_df_check_member,
4985 	.check_kflag_member = btf_df_check_kflag_member,
4986 	.log_details = btf_loc_proto_log,
4987 	.show = btf_df_show,
4988 };
4989 
4990 __printf(4, 5)
4991 static void btf_verifier_log_loc(struct btf_verifier_env *env,
4992 				 const struct btf_type *locsec_type,
4993 				 const struct btf_loc *loc,
4994 				 const char *fmt, ...)
4995 {
4996 	struct bpf_verifier_log *log = &env->log;
4997 	va_list args;
4998 
4999 	if (!bpf_verifier_log_needed(log))
5000 		return;
5001 	if (log->level == BPF_LOG_KERNEL && !fmt)
5002 		return;
5003 	if (env->phase != CHECK_META)
5004 		btf_verifier_log_type(env, locsec_type, NULL);
5005 
5006 	__btf_verifier_log(log, "\t func=%u loc_proto=%u offset=%u",
5007 			   loc->func, loc->loc_proto, loc->offset);
5008 	if (fmt && *fmt) {
5009 		__btf_verifier_log(log, " ");
5010 		va_start(args, fmt);
5011 		bpf_verifier_vlog(log, fmt, args);
5012 		va_end(args);
5013 	}
5014 
5015 	__btf_verifier_log(log, "\n");
5016 }
5017 
5018 static s32 btf_locsec_check_meta(struct btf_verifier_env *env,
5019 				 const struct btf_type *t,
5020 				 u32 meta_left)
5021 {
5022 	u32 i, meta_needed, vlen = btf_type_vlen(t);
5023 	const struct btf_loc *loc;
5024 
5025 	meta_needed = sizeof(struct btf_loc) * vlen;
5026 
5027 	if (meta_left < meta_needed) {
5028 		btf_verifier_log_basic(env, t,
5029 				       "meta_left:%u meta_needed:%u",
5030 				       meta_left, meta_needed);
5031 		return -EINVAL;
5032 	}
5033 
5034 	if (btf_type_kflag(t)) {
5035 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5036 		return -EINVAL;
5037 	}
5038 
5039 	if (!t->name_off ||
5040 	    !btf_name_valid_section(env->btf, t->name_off)) {
5041 		btf_verifier_log_type(env, t, "Invalid name");
5042 		return -EINVAL;
5043 	}
5044 
5045 	for_each_loc(i, t, loc) {
5046 		/* A loc func, loc proto cannot be in type void */
5047 		if (!loc->func || !BTF_TYPE_ID_VALID(loc->func)) {
5048 			btf_verifier_log_loc(env, t, loc, "Invalid func");
5049 			return -EINVAL;
5050 		}
5051 		if (!loc->loc_proto || !BTF_TYPE_ID_VALID(loc->loc_proto)) {
5052 			btf_verifier_log_loc(env, t, loc, "Invalid loc_proto");
5053 			return -EINVAL;
5054 		}
5055 		btf_verifier_log_loc(env, t, loc, NULL);
5056 	}
5057 
5058 	return meta_needed;
5059 }
5060 
5061 static void btf_locsec_log(struct btf_verifier_env *env,
5062 			   const struct btf_type *t)
5063 {
5064 	btf_verifier_log(env, "vlen=%u", btf_type_vlen(t));
5065 }
5066 
5067 static int btf_locsec_resolve(struct btf_verifier_env *env,
5068 			      const struct resolve_vertex *v)
5069 {
5070 	const struct btf_type *t = v->t;
5071 	const struct btf_loc *loc;
5072 	struct btf *btf = env->btf;
5073 	u32 i;
5074 
5075 	if (t->type) {
5076 		btf_verifier_log_type(env, t, "Invalid locsec type");
5077 		return -EINVAL;
5078 	}
5079 
5080 	env->resolve_mode = RESOLVE_TBD;
5081 	for (i = v->next_member, loc = btf_type_loc_secinfo(t) + i;
5082 	     i < btf_type_vlen(t); i++, loc++) {
5083 		const struct btf_type *func_type, *func_proto_type;
5084 		const struct btf_type *loc_proto_type;
5085 		u32 func_type_id = loc->func;
5086 		u32 loc_proto_type_id = loc->loc_proto;
5087 		u32 proto_vlen;
5088 
5089 		func_type = btf_type_by_id(btf, func_type_id);
5090 		if (!func_type || !btf_type_is_func(func_type)) {
5091 			btf_verifier_log_type(env, t,
5092 					      "Invalid func#%u", i + 1);
5093 			return -EINVAL;
5094 		}
5095 		func_proto_type = btf_type_by_id(btf, func_type->type);
5096 		if (!func_proto_type || !btf_type_is_func_proto(func_proto_type)) {
5097 			btf_verifier_log_type(env, t,
5098 					      "Invalid func#%u", i + 1);
5099 			return -EINVAL;
5100 		}
5101 		proto_vlen = btf_vlen(func_proto_type);
5102 
5103 		if (!env_type_is_resolved(env, func_type_id)) {
5104 			env_stack_set_next_member(env, i);
5105 			return env_stack_push(env, func_type, func_type_id);
5106 		}
5107 
5108 		loc_proto_type = btf_type_by_id(btf, loc_proto_type_id);
5109 		if (!loc_proto_type || !btf_type_is_loc_proto(loc_proto_type)) {
5110 			btf_verifier_log_type(env, t,
5111 					      "Invalid loc_proto#%u", i + 1);
5112 			return -EINVAL;
5113 		}
5114 		if (proto_vlen != btf_vlen(loc_proto_type)) {
5115 			btf_verifier_log_type(env, t,
5116 					      "Mismatched vlen for loc_proto#%u", i + 1);
5117 			return -EINVAL;
5118 		}
5119 
5120 		if (!env_type_is_resolved(env, loc_proto_type_id)) {
5121 			env_stack_set_next_member(env, i + 1);
5122 			return env_stack_push(env, loc_proto_type,
5123 					      loc_proto_type_id);
5124 		}
5125 	}
5126 
5127 	env_stack_pop_resolved(env, 0, 0);
5128 	return 0;
5129 }
5130 
5131 static const struct btf_kind_operations locsec_ops = {
5132 	.check_meta = btf_locsec_check_meta,
5133 	.resolve = btf_locsec_resolve,
5134 	.check_member = btf_df_check_member,
5135 	.check_kflag_member = btf_df_check_kflag_member,
5136 	.log_details = btf_locsec_log,
5137 	.show = btf_df_show,
5138 };
5139 
5140 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
5141 				     const struct btf_type *t,
5142 				     u32 meta_left)
5143 {
5144 	u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
5145 
5146 	if (meta_left < meta_needed) {
5147 		btf_verifier_log_basic(env, t,
5148 				       "meta_left:%u meta_needed:%u",
5149 				       meta_left, meta_needed);
5150 		return -EINVAL;
5151 	}
5152 
5153 	if (t->name_off) {
5154 		btf_verifier_log_type(env, t, "Invalid name");
5155 		return -EINVAL;
5156 	}
5157 
5158 	if (btf_type_kflag(t)) {
5159 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5160 		return -EINVAL;
5161 	}
5162 
5163 	btf_verifier_log_type(env, t, NULL);
5164 
5165 	return meta_needed;
5166 }
5167 
5168 static void btf_func_proto_log(struct btf_verifier_env *env,
5169 			       const struct btf_type *t)
5170 {
5171 	const struct btf_param *args = (const struct btf_param *)(t + 1);
5172 	u32 nr_args = btf_type_vlen(t), i;
5173 
5174 	btf_verifier_log(env, "return=%u args=(", t->type);
5175 	if (!nr_args) {
5176 		btf_verifier_log(env, "void");
5177 		goto done;
5178 	}
5179 
5180 	if (nr_args == 1 && !args[0].type) {
5181 		/* Only one vararg */
5182 		btf_verifier_log(env, "vararg");
5183 		goto done;
5184 	}
5185 
5186 	btf_verifier_log(env, "%u %s", args[0].type,
5187 			 __btf_name_by_offset(env->btf,
5188 					      args[0].name_off));
5189 	for (i = 1; i < nr_args - 1; i++)
5190 		btf_verifier_log(env, ", %u %s", args[i].type,
5191 				 __btf_name_by_offset(env->btf,
5192 						      args[i].name_off));
5193 
5194 	if (nr_args > 1) {
5195 		const struct btf_param *last_arg = &args[nr_args - 1];
5196 
5197 		if (last_arg->type)
5198 			btf_verifier_log(env, ", %u %s", last_arg->type,
5199 					 __btf_name_by_offset(env->btf,
5200 							      last_arg->name_off));
5201 		else
5202 			btf_verifier_log(env, ", vararg");
5203 	}
5204 
5205 done:
5206 	btf_verifier_log(env, ")");
5207 }
5208 
5209 static const struct btf_kind_operations func_proto_ops = {
5210 	.check_meta = btf_func_proto_check_meta,
5211 	.resolve = btf_df_resolve,
5212 	/*
5213 	 * BTF_KIND_FUNC_PROTO cannot be directly referred by
5214 	 * a struct's member.
5215 	 *
5216 	 * It should be a function pointer instead.
5217 	 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
5218 	 *
5219 	 * Hence, there is no btf_func_check_member().
5220 	 */
5221 	.check_member = btf_df_check_member,
5222 	.check_kflag_member = btf_df_check_kflag_member,
5223 	.log_details = btf_func_proto_log,
5224 	.show = btf_df_show,
5225 };
5226 
5227 static s32 btf_func_check_meta(struct btf_verifier_env *env,
5228 			       const struct btf_type *t,
5229 			       u32 meta_left)
5230 {
5231 	if (!t->name_off ||
5232 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
5233 		btf_verifier_log_type(env, t, "Invalid name");
5234 		return -EINVAL;
5235 	}
5236 
5237 	if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
5238 		btf_verifier_log_type(env, t, "Invalid func linkage");
5239 		return -EINVAL;
5240 	}
5241 
5242 	if (btf_type_kflag(t)) {
5243 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5244 		return -EINVAL;
5245 	}
5246 
5247 	btf_verifier_log_type(env, t, NULL);
5248 
5249 	return 0;
5250 }
5251 
5252 static int btf_func_resolve(struct btf_verifier_env *env,
5253 			    const struct resolve_vertex *v)
5254 {
5255 	const struct btf_type *t = v->t;
5256 	u32 next_type_id = t->type;
5257 	int err;
5258 
5259 	err = btf_func_check(env, t);
5260 	if (err)
5261 		return err;
5262 
5263 	env_stack_pop_resolved(env, next_type_id, 0);
5264 	return 0;
5265 }
5266 
5267 static const struct btf_kind_operations func_ops = {
5268 	.check_meta = btf_func_check_meta,
5269 	.resolve = btf_func_resolve,
5270 	.check_member = btf_df_check_member,
5271 	.check_kflag_member = btf_df_check_kflag_member,
5272 	.log_details = btf_ref_type_log,
5273 	.show = btf_df_show,
5274 };
5275 
5276 static s32 btf_var_check_meta(struct btf_verifier_env *env,
5277 			      const struct btf_type *t,
5278 			      u32 meta_left)
5279 {
5280 	const struct btf_var *var;
5281 	u32 meta_needed = sizeof(*var);
5282 
5283 	if (meta_left < meta_needed) {
5284 		btf_verifier_log_basic(env, t,
5285 				       "meta_left:%u meta_needed:%u",
5286 				       meta_left, meta_needed);
5287 		return -EINVAL;
5288 	}
5289 
5290 	if (btf_type_vlen(t)) {
5291 		btf_verifier_log_type(env, t, "vlen != 0");
5292 		return -EINVAL;
5293 	}
5294 
5295 	if (btf_type_kflag(t)) {
5296 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5297 		return -EINVAL;
5298 	}
5299 
5300 	if (!t->name_off ||
5301 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
5302 		btf_verifier_log_type(env, t, "Invalid name");
5303 		return -EINVAL;
5304 	}
5305 
5306 	/* A var cannot be in type void */
5307 	if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
5308 		btf_verifier_log_type(env, t, "Invalid type_id");
5309 		return -EINVAL;
5310 	}
5311 
5312 	var = btf_type_var(t);
5313 	if (var->linkage != BTF_VAR_STATIC &&
5314 	    var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
5315 		btf_verifier_log_type(env, t, "Linkage not supported");
5316 		return -EINVAL;
5317 	}
5318 
5319 	btf_verifier_log_type(env, t, NULL);
5320 
5321 	return meta_needed;
5322 }
5323 
5324 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
5325 {
5326 	const struct btf_var *var = btf_type_var(t);
5327 
5328 	btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
5329 }
5330 
5331 static const struct btf_kind_operations var_ops = {
5332 	.check_meta		= btf_var_check_meta,
5333 	.resolve		= btf_var_resolve,
5334 	.check_member		= btf_df_check_member,
5335 	.check_kflag_member	= btf_df_check_kflag_member,
5336 	.log_details		= btf_var_log,
5337 	.show			= btf_var_show,
5338 };
5339 
5340 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
5341 				  const struct btf_type *t,
5342 				  u32 meta_left)
5343 {
5344 	const struct btf_var_secinfo *vsi;
5345 	u64 last_vsi_end_off = 0, sum = 0;
5346 	u32 i, meta_needed;
5347 
5348 	meta_needed = btf_type_vlen(t) * sizeof(*vsi);
5349 	if (meta_left < meta_needed) {
5350 		btf_verifier_log_basic(env, t,
5351 				       "meta_left:%u meta_needed:%u",
5352 				       meta_left, meta_needed);
5353 		return -EINVAL;
5354 	}
5355 
5356 	if (!t->size) {
5357 		btf_verifier_log_type(env, t, "size == 0");
5358 		return -EINVAL;
5359 	}
5360 
5361 	if (btf_type_kflag(t)) {
5362 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5363 		return -EINVAL;
5364 	}
5365 
5366 	if (!t->name_off ||
5367 	    !btf_name_valid_section(env->btf, t->name_off)) {
5368 		btf_verifier_log_type(env, t, "Invalid name");
5369 		return -EINVAL;
5370 	}
5371 
5372 	btf_verifier_log_type(env, t, NULL);
5373 
5374 	for_each_vsi(i, t, vsi) {
5375 		/* A var cannot be in type void */
5376 		if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
5377 			btf_verifier_log_vsi(env, t, vsi,
5378 					     "Invalid type_id");
5379 			return -EINVAL;
5380 		}
5381 
5382 		if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
5383 			btf_verifier_log_vsi(env, t, vsi,
5384 					     "Invalid offset");
5385 			return -EINVAL;
5386 		}
5387 
5388 		if (!vsi->size || vsi->size > t->size) {
5389 			btf_verifier_log_vsi(env, t, vsi,
5390 					     "Invalid size");
5391 			return -EINVAL;
5392 		}
5393 
5394 		last_vsi_end_off = vsi->offset + vsi->size;
5395 		if (last_vsi_end_off > t->size) {
5396 			btf_verifier_log_vsi(env, t, vsi,
5397 					     "Invalid offset+size");
5398 			return -EINVAL;
5399 		}
5400 
5401 		btf_verifier_log_vsi(env, t, vsi, NULL);
5402 		sum += vsi->size;
5403 	}
5404 
5405 	if (t->size < sum) {
5406 		btf_verifier_log_type(env, t, "Invalid btf_info size");
5407 		return -EINVAL;
5408 	}
5409 
5410 	return meta_needed;
5411 }
5412 
5413 static int btf_datasec_resolve(struct btf_verifier_env *env,
5414 			       const struct resolve_vertex *v)
5415 {
5416 	const struct btf_var_secinfo *vsi;
5417 	struct btf *btf = env->btf;
5418 	u32 i;
5419 
5420 	env->resolve_mode = RESOLVE_TBD;
5421 	for_each_vsi_from(i, v->next_member, v->t, vsi) {
5422 		u32 var_type_id = vsi->type, type_id;
5423 		const struct btf_type *var_type = btf_type_by_id(env->btf,
5424 								 var_type_id);
5425 		if (!var_type || !btf_type_is_var(var_type)) {
5426 			btf_verifier_log_vsi(env, v->t, vsi,
5427 					     "Not a VAR kind member");
5428 			return -EINVAL;
5429 		}
5430 
5431 		if (!env_type_is_resolve_sink(env, var_type) &&
5432 		    !env_type_is_resolved(env, var_type_id)) {
5433 			env_stack_set_next_member(env, i + 1);
5434 			return env_stack_push(env, var_type, var_type_id);
5435 		}
5436 
5437 		/*
5438 		 * The variable can be smaller than its type. It's a piece of
5439 		 * a variable that the compiler split then, with the type of
5440 		 * the whole variable.
5441 		 */
5442 		type_id = var_type->type;
5443 		if (!btf_type_id_size(btf, &type_id, NULL)) {
5444 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
5445 			return -EINVAL;
5446 		}
5447 	}
5448 
5449 	env_stack_pop_resolved(env, 0, 0);
5450 	return 0;
5451 }
5452 
5453 static void btf_datasec_log(struct btf_verifier_env *env,
5454 			    const struct btf_type *t)
5455 {
5456 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
5457 }
5458 
5459 /* A piece of a variable is smaller than its type, which is the one of the whole variable */
5460 static bool btf_var_is_piece(const struct btf *btf, const struct btf_type *var,
5461 			     const struct btf_var_secinfo *vsi)
5462 {
5463 	u32 size;
5464 
5465 	return IS_ERR(btf_resolve_size(btf, btf_type_by_id(btf, var->type), &size)) ||
5466 	       vsi->size < size;
5467 }
5468 
5469 static void btf_datasec_show(const struct btf *btf,
5470 			     const struct btf_type *t, u32 type_id,
5471 			     void *data, u8 bits_offset,
5472 			     struct btf_show *show)
5473 {
5474 	const struct btf_var_secinfo *vsi;
5475 	const struct btf_type *var;
5476 	bool comma = false;
5477 	u32 i;
5478 
5479 	if (!btf_show_start_type(show, t, type_id, data))
5480 		return;
5481 
5482 	btf_show_type_value(show, "section (\"%s\") = {",
5483 			    __btf_name_by_offset(btf, t->name_off));
5484 	for_each_vsi(i, t, vsi) {
5485 		var = btf_type_by_id(btf, vsi->type);
5486 		/* there is less data than the type takes */
5487 		if (btf_var_is_piece(btf, var, vsi))
5488 			continue;
5489 		if (comma)
5490 			btf_show(show, ",");
5491 		comma = true;
5492 		btf_type_ops(var)->show(btf, var, vsi->type,
5493 					data + vsi->offset, bits_offset, show);
5494 	}
5495 	btf_show_end_type(show);
5496 }
5497 
5498 static const struct btf_kind_operations datasec_ops = {
5499 	.check_meta		= btf_datasec_check_meta,
5500 	.resolve		= btf_datasec_resolve,
5501 	.check_member		= btf_df_check_member,
5502 	.check_kflag_member	= btf_df_check_kflag_member,
5503 	.log_details		= btf_datasec_log,
5504 	.show			= btf_datasec_show,
5505 };
5506 
5507 static s32 btf_float_check_meta(struct btf_verifier_env *env,
5508 				const struct btf_type *t,
5509 				u32 meta_left)
5510 {
5511 	if (btf_type_vlen(t)) {
5512 		btf_verifier_log_type(env, t, "vlen != 0");
5513 		return -EINVAL;
5514 	}
5515 
5516 	if (btf_type_kflag(t)) {
5517 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5518 		return -EINVAL;
5519 	}
5520 
5521 	if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
5522 	    t->size != 16) {
5523 		btf_verifier_log_type(env, t, "Invalid type_size");
5524 		return -EINVAL;
5525 	}
5526 
5527 	btf_verifier_log_type(env, t, NULL);
5528 
5529 	return 0;
5530 }
5531 
5532 static int btf_float_check_member(struct btf_verifier_env *env,
5533 				  const struct btf_type *struct_type,
5534 				  const struct btf_member *member,
5535 				  const struct btf_type *member_type)
5536 {
5537 	u64 start_offset_bytes;
5538 	u64 end_offset_bytes;
5539 	u64 misalign_bits;
5540 	u64 align_bytes;
5541 	u64 align_bits;
5542 
5543 	/* Different architectures have different alignment requirements, so
5544 	 * here we check only for the reasonable minimum. This way we ensure
5545 	 * that types after CO-RE can pass the kernel BTF verifier.
5546 	 */
5547 	align_bytes = min_t(u64, sizeof(void *), member_type->size);
5548 	align_bits = align_bytes * BITS_PER_BYTE;
5549 	div64_u64_rem(member->offset, align_bits, &misalign_bits);
5550 	if (misalign_bits) {
5551 		btf_verifier_log_member(env, struct_type, member,
5552 					"Member is not properly aligned");
5553 		return -EINVAL;
5554 	}
5555 
5556 	start_offset_bytes = member->offset / BITS_PER_BYTE;
5557 	end_offset_bytes = start_offset_bytes + member_type->size;
5558 	if (end_offset_bytes > struct_type->size) {
5559 		btf_verifier_log_member(env, struct_type, member,
5560 					"Member exceeds struct_size");
5561 		return -EINVAL;
5562 	}
5563 
5564 	return 0;
5565 }
5566 
5567 static void btf_float_log(struct btf_verifier_env *env,
5568 			  const struct btf_type *t)
5569 {
5570 	btf_verifier_log(env, "size=%u", t->size);
5571 }
5572 
5573 static const struct btf_kind_operations float_ops = {
5574 	.check_meta = btf_float_check_meta,
5575 	.resolve = btf_df_resolve,
5576 	.check_member = btf_float_check_member,
5577 	.check_kflag_member = btf_generic_check_kflag_member,
5578 	.log_details = btf_float_log,
5579 	.show = btf_df_show,
5580 };
5581 
5582 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
5583 			      const struct btf_type *t,
5584 			      u32 meta_left)
5585 {
5586 	const struct btf_decl_tag *tag;
5587 	u32 meta_needed = sizeof(*tag);
5588 	s32 component_idx;
5589 	const char *value;
5590 
5591 	if (meta_left < meta_needed) {
5592 		btf_verifier_log_basic(env, t,
5593 				       "meta_left:%u meta_needed:%u",
5594 				       meta_left, meta_needed);
5595 		return -EINVAL;
5596 	}
5597 
5598 	value = btf_name_by_offset(env->btf, t->name_off);
5599 	if (!value || !value[0]) {
5600 		btf_verifier_log_type(env, t, "Invalid value");
5601 		return -EINVAL;
5602 	}
5603 
5604 	if (btf_type_vlen(t)) {
5605 		btf_verifier_log_type(env, t, "vlen != 0");
5606 		return -EINVAL;
5607 	}
5608 
5609 	component_idx = btf_type_decl_tag(t)->component_idx;
5610 	if (component_idx < -1) {
5611 		btf_verifier_log_type(env, t, "Invalid component_idx");
5612 		return -EINVAL;
5613 	}
5614 
5615 	btf_verifier_log_type(env, t, NULL);
5616 
5617 	return meta_needed;
5618 }
5619 
5620 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
5621 			   const struct resolve_vertex *v)
5622 {
5623 	const struct btf_type *next_type;
5624 	const struct btf_type *t = v->t;
5625 	u32 next_type_id = t->type;
5626 	struct btf *btf = env->btf;
5627 	s32 component_idx;
5628 	u32 vlen;
5629 
5630 	next_type = btf_type_by_id(btf, next_type_id);
5631 	if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
5632 		btf_verifier_log_type(env, v->t, "Invalid type_id");
5633 		return -EINVAL;
5634 	}
5635 
5636 	if (!env_type_is_resolve_sink(env, next_type) &&
5637 	    !env_type_is_resolved(env, next_type_id))
5638 		return env_stack_push(env, next_type, next_type_id);
5639 
5640 	component_idx = btf_type_decl_tag(t)->component_idx;
5641 	if (component_idx != -1) {
5642 		if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
5643 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
5644 			return -EINVAL;
5645 		}
5646 
5647 		if (btf_type_is_struct(next_type)) {
5648 			vlen = btf_type_vlen(next_type);
5649 		} else {
5650 			/* next_type should be a function */
5651 			next_type = btf_type_by_id(btf, next_type->type);
5652 			vlen = btf_type_vlen(next_type);
5653 		}
5654 
5655 		if ((u32)component_idx >= vlen) {
5656 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
5657 			return -EINVAL;
5658 		}
5659 	}
5660 
5661 	env_stack_pop_resolved(env, next_type_id, 0);
5662 
5663 	return 0;
5664 }
5665 
5666 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
5667 {
5668 	btf_verifier_log(env, "type=%u component_idx=%d", t->type,
5669 			 btf_type_decl_tag(t)->component_idx);
5670 }
5671 
5672 static const struct btf_kind_operations decl_tag_ops = {
5673 	.check_meta = btf_decl_tag_check_meta,
5674 	.resolve = btf_decl_tag_resolve,
5675 	.check_member = btf_df_check_member,
5676 	.check_kflag_member = btf_df_check_kflag_member,
5677 	.log_details = btf_decl_tag_log,
5678 	.show = btf_df_show,
5679 };
5680 
5681 static int btf_func_proto_check(struct btf_verifier_env *env,
5682 				const struct btf_type *t)
5683 {
5684 	const struct btf_type *ret_type;
5685 	const struct btf_param *args;
5686 	const struct btf *btf;
5687 	u32 nr_args, i;
5688 	int err;
5689 
5690 	btf = env->btf;
5691 	args = (const struct btf_param *)(t + 1);
5692 	nr_args = btf_type_vlen(t);
5693 
5694 	/* Check func return type which could be "void" (t->type == 0) */
5695 	if (t->type) {
5696 		u32 ret_type_id = t->type;
5697 
5698 		ret_type = btf_type_by_id(btf, ret_type_id);
5699 		if (!ret_type) {
5700 			btf_verifier_log_type(env, t, "Invalid return type");
5701 			return -EINVAL;
5702 		}
5703 
5704 		if (btf_type_is_resolve_source_only(ret_type)) {
5705 			btf_verifier_log_type(env, t, "Invalid return type");
5706 			return -EINVAL;
5707 		}
5708 
5709 		if (btf_type_needs_resolve(ret_type) &&
5710 		    !env_type_is_resolved(env, ret_type_id)) {
5711 			err = btf_resolve(env, ret_type, ret_type_id);
5712 			if (err)
5713 				return err;
5714 		}
5715 
5716 		/* Ensure the return type is a type that has a size */
5717 		if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
5718 			btf_verifier_log_type(env, t, "Invalid return type");
5719 			return -EINVAL;
5720 		}
5721 	}
5722 
5723 	if (!nr_args)
5724 		return 0;
5725 
5726 	/* Last func arg type_id could be 0 if it is a vararg */
5727 	if (!args[nr_args - 1].type) {
5728 		if (args[nr_args - 1].name_off) {
5729 			btf_verifier_log_type(env, t, "Invalid arg#%u",
5730 					      nr_args);
5731 			return -EINVAL;
5732 		}
5733 		nr_args--;
5734 	}
5735 
5736 	for (i = 0; i < nr_args; i++) {
5737 		const struct btf_type *arg_type;
5738 		u32 arg_type_id;
5739 
5740 		arg_type_id = args[i].type;
5741 		arg_type = btf_type_by_id(btf, arg_type_id);
5742 		if (!arg_type) {
5743 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5744 			return -EINVAL;
5745 		}
5746 
5747 		if (btf_type_is_resolve_source_only(arg_type)) {
5748 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5749 			return -EINVAL;
5750 		}
5751 
5752 		if (args[i].name_off &&
5753 		    (!btf_name_offset_valid(btf, args[i].name_off) ||
5754 		     !btf_name_valid_identifier(btf, args[i].name_off))) {
5755 			btf_verifier_log_type(env, t,
5756 					      "Invalid arg#%u", i + 1);
5757 			return -EINVAL;
5758 		}
5759 
5760 		if (btf_type_needs_resolve(arg_type) &&
5761 		    !env_type_is_resolved(env, arg_type_id)) {
5762 			err = btf_resolve(env, arg_type, arg_type_id);
5763 			if (err)
5764 				return err;
5765 		}
5766 
5767 		if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
5768 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5769 			return -EINVAL;
5770 		}
5771 	}
5772 
5773 	return 0;
5774 }
5775 
5776 static int btf_func_check(struct btf_verifier_env *env,
5777 			  const struct btf_type *t)
5778 {
5779 	const struct btf_type *proto_type;
5780 	const struct btf_param *args;
5781 	const struct btf *btf;
5782 	u32 nr_args, i;
5783 
5784 	btf = env->btf;
5785 	proto_type = btf_type_by_id(btf, t->type);
5786 
5787 	if (!proto_type || !btf_type_is_func_proto(proto_type)) {
5788 		btf_verifier_log_type(env, t, "Invalid type_id");
5789 		return -EINVAL;
5790 	}
5791 
5792 	/* Rust leaves out names of some arguments of static functions */
5793 	if (btf_func_linkage(t) == BTF_FUNC_STATIC)
5794 		return 0;
5795 
5796 	args = (const struct btf_param *)(proto_type + 1);
5797 	nr_args = btf_type_vlen(proto_type);
5798 	for (i = 0; i < nr_args; i++) {
5799 		if (!args[i].name_off && args[i].type) {
5800 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5801 			return -EINVAL;
5802 		}
5803 	}
5804 
5805 	return 0;
5806 }
5807 
5808 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
5809 	[BTF_KIND_INT] = &int_ops,
5810 	[BTF_KIND_PTR] = &ptr_ops,
5811 	[BTF_KIND_ARRAY] = &array_ops,
5812 	[BTF_KIND_STRUCT] = &struct_ops,
5813 	[BTF_KIND_UNION] = &struct_ops,
5814 	[BTF_KIND_ENUM] = &enum_ops,
5815 	[BTF_KIND_FWD] = &fwd_ops,
5816 	[BTF_KIND_TYPEDEF] = &modifier_ops,
5817 	[BTF_KIND_VOLATILE] = &modifier_ops,
5818 	[BTF_KIND_CONST] = &modifier_ops,
5819 	[BTF_KIND_RESTRICT] = &modifier_ops,
5820 	[BTF_KIND_FUNC] = &func_ops,
5821 	[BTF_KIND_FUNC_PROTO] = &func_proto_ops,
5822 	[BTF_KIND_VAR] = &var_ops,
5823 	[BTF_KIND_DATASEC] = &datasec_ops,
5824 	[BTF_KIND_FLOAT] = &float_ops,
5825 	[BTF_KIND_DECL_TAG] = &decl_tag_ops,
5826 	[BTF_KIND_TYPE_TAG] = &modifier_ops,
5827 	[BTF_KIND_ENUM64] = &enum64_ops,
5828 	[BTF_KIND_LOC_PARAM] = &loc_param_ops,
5829 	[BTF_KIND_LOC_PROTO] = &loc_proto_ops,
5830 	[BTF_KIND_LOCSEC] = &locsec_ops,
5831 };
5832 
5833 static s32 btf_check_meta(struct btf_verifier_env *env,
5834 			  const struct btf_type *t,
5835 			  u32 meta_left)
5836 {
5837 	u32 saved_meta_left = meta_left;
5838 	s32 var_meta_size;
5839 
5840 	if (meta_left < sizeof(*t)) {
5841 		btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
5842 				 env->log_type_id, meta_left, sizeof(*t));
5843 		return -EINVAL;
5844 	}
5845 	meta_left -= sizeof(*t);
5846 
5847 	if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
5848 	    BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
5849 		btf_verifier_log(env, "[%u] Invalid kind:%u",
5850 				 env->log_type_id, BTF_INFO_KIND(t->info));
5851 		return -EINVAL;
5852 	}
5853 
5854 	if (!btf_name_offset_valid(env->btf, t->name_off)) {
5855 		btf_verifier_log(env, "[%u] Invalid name_offset:%u",
5856 				 env->log_type_id, t->name_off);
5857 		return -EINVAL;
5858 	}
5859 
5860 	var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
5861 	if (var_meta_size < 0)
5862 		return var_meta_size;
5863 
5864 	meta_left -= var_meta_size;
5865 
5866 	return saved_meta_left - meta_left;
5867 }
5868 
5869 static int btf_check_all_metas(struct btf_verifier_env *env)
5870 {
5871 	struct btf *btf = env->btf;
5872 	struct btf_header *hdr;
5873 	void *cur, *end;
5874 
5875 	hdr = &btf->hdr;
5876 	cur = btf->nohdr_data + hdr->type_off;
5877 	end = cur + hdr->type_len;
5878 
5879 	env->log_type_id = btf->base_btf ? btf->start_id : 1;
5880 	while (cur < end) {
5881 		struct btf_type *t = cur;
5882 		s32 meta_size;
5883 
5884 		meta_size = btf_check_meta(env, t, end - cur);
5885 		if (meta_size < 0)
5886 			return meta_size;
5887 
5888 		btf_add_type(env, t);
5889 		cur += meta_size;
5890 		env->log_type_id++;
5891 	}
5892 
5893 	return 0;
5894 }
5895 
5896 static bool btf_resolve_valid(struct btf_verifier_env *env,
5897 			      const struct btf_type *t,
5898 			      u32 type_id)
5899 {
5900 	struct btf *btf = env->btf;
5901 
5902 	if (!env_type_is_resolved(env, type_id))
5903 		return false;
5904 
5905 	if (btf_type_is_struct(t) || btf_type_is_datasec(t) ||
5906 	    btf_type_is_loc_proto(t) || btf_type_is_locsec(t))
5907 		return !btf_resolved_type_id(btf, type_id) &&
5908 		       !btf_resolved_type_size(btf, type_id);
5909 
5910 	if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5911 		return btf_resolved_type_id(btf, type_id) &&
5912 		       !btf_resolved_type_size(btf, type_id);
5913 
5914 	if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5915 	    btf_type_is_var(t)) {
5916 		t = btf_type_id_resolve(btf, &type_id);
5917 		return t &&
5918 		       !btf_type_is_modifier(t) &&
5919 		       !btf_type_is_var(t) &&
5920 		       !btf_type_is_datasec(t);
5921 	}
5922 
5923 	if (btf_type_is_array(t)) {
5924 		const struct btf_array *array = btf_type_array(t);
5925 		const struct btf_type *elem_type;
5926 		u32 elem_type_id = array->type;
5927 		u32 elem_size;
5928 
5929 		elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5930 		return elem_type && !btf_type_is_modifier(elem_type) &&
5931 			(array->nelems * elem_size ==
5932 			 btf_resolved_type_size(btf, type_id));
5933 	}
5934 
5935 	return false;
5936 }
5937 
5938 static int btf_resolve(struct btf_verifier_env *env,
5939 		       const struct btf_type *t, u32 type_id)
5940 {
5941 	u32 save_log_type_id = env->log_type_id;
5942 	const struct resolve_vertex *v;
5943 	int err = 0;
5944 
5945 	env->resolve_mode = RESOLVE_TBD;
5946 	env_stack_push(env, t, type_id);
5947 	while (!err && (v = env_stack_peak(env))) {
5948 		env->log_type_id = v->type_id;
5949 		err = btf_type_ops(v->t)->resolve(env, v);
5950 	}
5951 
5952 	env->log_type_id = type_id;
5953 	if (err == -E2BIG) {
5954 		btf_verifier_log_type(env, t,
5955 				      "Exceeded max resolving depth:%u",
5956 				      MAX_RESOLVE_DEPTH);
5957 	} else if (err == -EEXIST) {
5958 		btf_verifier_log_type(env, t, "Loop detected");
5959 	}
5960 
5961 	/* Final sanity check */
5962 	if (!err && !btf_resolve_valid(env, t, type_id)) {
5963 		btf_verifier_log_type(env, t, "Invalid resolve state");
5964 		err = -EINVAL;
5965 	}
5966 
5967 	env->log_type_id = save_log_type_id;
5968 	return err;
5969 }
5970 
5971 static int btf_check_all_types(struct btf_verifier_env *env)
5972 {
5973 	struct btf *btf = env->btf;
5974 	const struct btf_type *t;
5975 	u32 type_id, i;
5976 	int err;
5977 
5978 	err = env_resolve_init(env);
5979 	if (err)
5980 		return err;
5981 
5982 	env->phase++;
5983 	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5984 		type_id = btf->start_id + i;
5985 		t = btf_type_by_id(btf, type_id);
5986 
5987 		env->log_type_id = type_id;
5988 		if (btf_type_needs_resolve(t) &&
5989 		    !env_type_is_resolved(env, type_id)) {
5990 			err = btf_resolve(env, t, type_id);
5991 			if (err)
5992 				return err;
5993 		}
5994 
5995 		if (btf_type_is_func_proto(t)) {
5996 			err = btf_func_proto_check(env, t);
5997 			if (err)
5998 				return err;
5999 		}
6000 	}
6001 
6002 	return 0;
6003 }
6004 
6005 static int btf_parse_type_sec(struct btf_verifier_env *env)
6006 {
6007 	const struct btf_header *hdr = &env->btf->hdr;
6008 	int err;
6009 
6010 	/* Type section must align to 4 bytes */
6011 	if (hdr->type_off & (sizeof(u32) - 1)) {
6012 		btf_verifier_log(env, "Unaligned type_off");
6013 		return -EINVAL;
6014 	}
6015 
6016 	if (!env->btf->base_btf && !hdr->type_len) {
6017 		btf_verifier_log(env, "No type found");
6018 		return -EINVAL;
6019 	}
6020 
6021 	err = btf_check_all_metas(env);
6022 	if (err)
6023 		return err;
6024 
6025 	return btf_check_all_types(env);
6026 }
6027 
6028 static int btf_parse_str_sec(struct btf_verifier_env *env)
6029 {
6030 	const struct btf_header *hdr;
6031 	struct btf *btf = env->btf;
6032 	const char *start, *end;
6033 
6034 	hdr = &btf->hdr;
6035 	start = btf->nohdr_data + hdr->str_off;
6036 	end = start + hdr->str_len;
6037 
6038 	if (hdr->hdr_len < sizeof(struct btf_header) &&
6039 	    end != btf->data + btf->data_size) {
6040 		btf_verifier_log(env, "String section is not at the end");
6041 		return -EINVAL;
6042 	}
6043 
6044 	btf->strings = start;
6045 
6046 	if (btf->base_btf && !hdr->str_len)
6047 		return 0;
6048 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
6049 		btf_verifier_log(env, "Invalid string section");
6050 		return -EINVAL;
6051 	}
6052 	if (!btf->base_btf && start[0]) {
6053 		btf_verifier_log(env, "Invalid string section");
6054 		return -EINVAL;
6055 	}
6056 
6057 	return 0;
6058 }
6059 
6060 static int btf_parse_layout_sec(struct btf_verifier_env *env)
6061 {
6062 	const struct btf_header *hdr = &env->btf->hdr;
6063 	struct btf *btf = env->btf;
6064 	void *start, *end;
6065 
6066 	if (hdr->hdr_len < sizeof(struct btf_header) ||
6067 	    hdr->layout_len == 0)
6068 		return 0;
6069 
6070 	/* Layout section must align to 4 bytes */
6071 	if (hdr->layout_off & (sizeof(u32) - 1)) {
6072 		btf_verifier_log(env, "Unaligned layout_off");
6073 		return -EINVAL;
6074 	}
6075 	start = btf->nohdr_data + hdr->layout_off;
6076 	end = start + hdr->layout_len;
6077 
6078 	if (hdr->layout_len < sizeof(struct btf_layout)) {
6079 		btf_verifier_log(env, "Layout section is too small");
6080 		return -EINVAL;
6081 	}
6082 	if (hdr->layout_len % sizeof(struct btf_layout) != 0) {
6083 		btf_verifier_log(env, "layout_len is not multiple of %zu",
6084 				 sizeof(struct btf_layout));
6085 		return -EINVAL;
6086 	}
6087 	if (end > btf->data + btf->data_size) {
6088 		btf_verifier_log(env, "Layout section is too big");
6089 		return -EINVAL;
6090 	}
6091 	btf->layout = start;
6092 
6093 	return 0;
6094 }
6095 
6096 static const size_t btf_sec_info_offset[] = {
6097 	offsetof(struct btf_header, type_off),
6098 	offsetof(struct btf_header, str_off),
6099 	offsetof(struct btf_header, layout_off)
6100 };
6101 
6102 static int btf_sec_info_cmp(const void *a, const void *b)
6103 {
6104 	const struct btf_sec_info *x = a;
6105 	const struct btf_sec_info *y = b;
6106 
6107 	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
6108 }
6109 
6110 static int btf_check_sec_info(struct btf_verifier_env *env,
6111 			      u32 btf_data_size)
6112 {
6113 	struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
6114 	u32 total, expected_total, i;
6115 	u32 nr_secs = ARRAY_SIZE(btf_sec_info_offset);
6116 	const struct btf_header *hdr;
6117 	const struct btf *btf;
6118 
6119 	btf = env->btf;
6120 	hdr = &btf->hdr;
6121 
6122 	if (hdr->hdr_len < sizeof(struct btf_header) || hdr->layout_len == 0)
6123 		nr_secs--;
6124 
6125 	/* Populate the secs from hdr */
6126 	for (i = 0; i < nr_secs; i++)
6127 		secs[i] = *(struct btf_sec_info *)((void *)hdr +
6128 						   btf_sec_info_offset[i]);
6129 
6130 	sort(secs, nr_secs,
6131 	     sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
6132 
6133 	/* Check for gaps and overlap among sections */
6134 	total = 0;
6135 	expected_total = btf_data_size - hdr->hdr_len;
6136 	for (i = 0; i < nr_secs; i++) {
6137 		if (expected_total < secs[i].off) {
6138 			btf_verifier_log(env, "Invalid section offset");
6139 			return -EINVAL;
6140 		}
6141 		if (total < secs[i].off) {
6142 			/* gap */
6143 			btf_verifier_log(env, "Unsupported section found");
6144 			return -EINVAL;
6145 		}
6146 		if (total > secs[i].off) {
6147 			btf_verifier_log(env, "Section overlap found");
6148 			return -EINVAL;
6149 		}
6150 		if (expected_total - total < secs[i].len) {
6151 			btf_verifier_log(env,
6152 					 "Total section length too long");
6153 			return -EINVAL;
6154 		}
6155 		total += secs[i].len;
6156 	}
6157 
6158 	/* There is data other than hdr and known sections */
6159 	if (expected_total != total) {
6160 		btf_verifier_log(env, "Unsupported section found");
6161 		return -EINVAL;
6162 	}
6163 
6164 	return 0;
6165 }
6166 
6167 static int btf_parse_hdr(struct btf_verifier_env *env)
6168 {
6169 	u32 hdr_len, hdr_copy, btf_data_size;
6170 	const struct btf_header *hdr;
6171 	struct btf *btf;
6172 
6173 	btf = env->btf;
6174 	btf_data_size = btf->data_size;
6175 
6176 	if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
6177 		btf_verifier_log(env, "hdr_len not found");
6178 		return -EINVAL;
6179 	}
6180 
6181 	hdr = btf->data;
6182 	hdr_len = hdr->hdr_len;
6183 	if (btf_data_size < hdr_len) {
6184 		btf_verifier_log(env, "btf_header not found");
6185 		return -EINVAL;
6186 	}
6187 
6188 	/* Ensure the unsupported header fields are zero */
6189 	if (hdr_len > sizeof(btf->hdr)) {
6190 		u8 *expected_zero = btf->data + sizeof(btf->hdr);
6191 		u8 *end = btf->data + hdr_len;
6192 
6193 		for (; expected_zero < end; expected_zero++) {
6194 			if (*expected_zero) {
6195 				btf_verifier_log(env, "Unsupported btf_header");
6196 				return -E2BIG;
6197 			}
6198 		}
6199 	}
6200 
6201 	hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
6202 	memcpy(&btf->hdr, btf->data, hdr_copy);
6203 
6204 	hdr = &btf->hdr;
6205 
6206 	btf_verifier_log_hdr(env, btf_data_size);
6207 
6208 	if (hdr->magic != BTF_MAGIC) {
6209 		btf_verifier_log(env, "Invalid magic");
6210 		return -EINVAL;
6211 	}
6212 
6213 	if (hdr->version != BTF_VERSION) {
6214 		btf_verifier_log(env, "Unsupported version");
6215 		return -ENOTSUPP;
6216 	}
6217 
6218 	if (hdr->flags) {
6219 		btf_verifier_log(env, "Unsupported flags");
6220 		return -ENOTSUPP;
6221 	}
6222 
6223 	if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
6224 		btf_verifier_log(env, "No data");
6225 		return -EINVAL;
6226 	}
6227 
6228 	return btf_check_sec_info(env, btf_data_size);
6229 }
6230 
6231 static const char * const alloc_obj_fields[] = {
6232 	"bpf_spin_lock",
6233 	"bpf_list_head",
6234 	"bpf_list_node",
6235 	"bpf_rb_root",
6236 	"bpf_rb_node",
6237 	"bpf_refcount",
6238 };
6239 
6240 static struct btf_struct_metas *
6241 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
6242 {
6243 	struct btf_struct_metas *tab = NULL;
6244 	struct btf_id_set *aof;
6245 	int i, n, id, ret;
6246 
6247 	BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
6248 	BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
6249 
6250 	aof = kmalloc_obj(*aof, GFP_KERNEL | __GFP_NOWARN);
6251 	if (!aof)
6252 		return ERR_PTR(-ENOMEM);
6253 	aof->cnt = 0;
6254 
6255 	for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
6256 		/* Try to find whether this special type exists in user BTF, and
6257 		 * if so remember its ID so we can easily find it among members
6258 		 * of structs that we iterate in the next loop.
6259 		 */
6260 		struct btf_id_set *new_aof;
6261 
6262 		id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
6263 		if (id < 0)
6264 			continue;
6265 
6266 		new_aof = krealloc(aof, struct_size(new_aof, ids, aof->cnt + 1),
6267 				   GFP_KERNEL | __GFP_NOWARN);
6268 		if (!new_aof) {
6269 			ret = -ENOMEM;
6270 			goto free_aof;
6271 		}
6272 		aof = new_aof;
6273 		aof->ids[aof->cnt++] = id;
6274 	}
6275 
6276 	n = btf_nr_types(btf);
6277 	for (i = 1; i < n; i++) {
6278 		/* Try to find if there are kptrs in user BTF and remember their ID */
6279 		struct btf_id_set *new_aof;
6280 		struct btf_field_info tmp;
6281 		const struct btf_type *t;
6282 
6283 		t = btf_type_by_id(btf, i);
6284 		if (!t) {
6285 			ret = -EINVAL;
6286 			goto free_aof;
6287 		}
6288 
6289 		ret = btf_find_kptr(btf, t, 0, 0, &tmp, BPF_KPTR);
6290 		if (ret != BTF_FIELD_FOUND)
6291 			continue;
6292 
6293 		new_aof = krealloc(aof, struct_size(new_aof, ids, aof->cnt + 1),
6294 				   GFP_KERNEL | __GFP_NOWARN);
6295 		if (!new_aof) {
6296 			ret = -ENOMEM;
6297 			goto free_aof;
6298 		}
6299 		aof = new_aof;
6300 		aof->ids[aof->cnt++] = i;
6301 	}
6302 
6303 	if (!aof->cnt) {
6304 		kfree(aof);
6305 		return NULL;
6306 	}
6307 	sort(&aof->ids, aof->cnt, sizeof(aof->ids[0]), btf_id_cmp_func, NULL);
6308 
6309 	for (i = 1; i < n; i++) {
6310 		struct btf_struct_metas *new_tab;
6311 		const struct btf_member *member;
6312 		struct btf_struct_meta *type;
6313 		struct btf_record *record;
6314 		const struct btf_type *t;
6315 		int j, tab_cnt;
6316 
6317 		t = btf_type_by_id(btf, i);
6318 		if (!__btf_type_is_struct(t))
6319 			continue;
6320 
6321 		cond_resched();
6322 
6323 		for_each_member(j, t, member) {
6324 			if (btf_id_set_contains(aof, member->type))
6325 				goto parse;
6326 		}
6327 		continue;
6328 	parse:
6329 		tab_cnt = tab ? tab->cnt : 0;
6330 		new_tab = krealloc(tab, struct_size(new_tab, types, tab_cnt + 1),
6331 				   GFP_KERNEL | __GFP_NOWARN);
6332 		if (!new_tab) {
6333 			ret = -ENOMEM;
6334 			goto free;
6335 		}
6336 		if (!tab)
6337 			new_tab->cnt = 0;
6338 		tab = new_tab;
6339 
6340 		type = &tab->types[tab->cnt];
6341 		type->btf_id = i;
6342 		record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
6343 						  BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT |
6344 						  BPF_KPTR, t->size);
6345 		/* The record cannot be unset, treat it as an error if so */
6346 		if (IS_ERR_OR_NULL(record)) {
6347 			ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
6348 			goto free;
6349 		}
6350 		type->record = record;
6351 		tab->cnt++;
6352 	}
6353 	kfree(aof);
6354 	return tab;
6355 free:
6356 	btf_struct_metas_free(tab);
6357 free_aof:
6358 	kfree(aof);
6359 	return ERR_PTR(ret);
6360 }
6361 
6362 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
6363 {
6364 	struct btf_struct_metas *tab;
6365 
6366 	BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
6367 	tab = btf->struct_meta_tab;
6368 	if (!tab)
6369 		return NULL;
6370 	return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
6371 }
6372 
6373 static int btf_check_modifier_chain_length(struct btf_verifier_env *env,
6374 					   struct btf *btf, int start_id)
6375 {
6376 	int i, n, good_id = start_id - 1;
6377 
6378 	n = btf_nr_types(btf);
6379 	for (i = start_id; i < n; i++) {
6380 		const struct btf_type *t;
6381 		int chain_limit = 32;
6382 		u32 cur_id = i;
6383 
6384 		t = btf_type_by_id(btf, i);
6385 		if (!t)
6386 			return -EINVAL;
6387 		if (!btf_type_is_modifier(t))
6388 			continue;
6389 
6390 		cond_resched();
6391 
6392 		while (btf_type_is_modifier(t)) {
6393 			if (!chain_limit--) {
6394 				btf_verifier_log(env, "Max chain length or cycle detected");
6395 				return -ELOOP;
6396 			}
6397 
6398 			if (cur_id <= good_id)
6399 				break;
6400 			/* Move to next type */
6401 			cur_id = t->type;
6402 			t = btf_type_by_id(btf, cur_id);
6403 			if (!t)
6404 				return -EINVAL;
6405 		}
6406 		good_id = i;
6407 	}
6408 	return 0;
6409 }
6410 
6411 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,
6412 			     struct bpf_log_attr *attr_log)
6413 {
6414 	bpfptr_t btf_data = make_bpfptr(attr->btf, uattr.is_kernel);
6415 	struct btf_struct_metas *struct_meta_tab;
6416 	struct btf_verifier_env *env = NULL;
6417 	struct btf *btf = NULL;
6418 	u8 *data;
6419 	int err, ret;
6420 
6421 	if (attr->btf_size > BTF_MAX_SIZE)
6422 		return ERR_PTR(-E2BIG);
6423 
6424 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
6425 	if (!env)
6426 		return ERR_PTR(-ENOMEM);
6427 
6428 	/* user could have requested verbose verifier output
6429 	 * and supplied buffer to store the verification trace
6430 	 */
6431 	err = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
6432 	if (err)
6433 		goto errout_free;
6434 
6435 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
6436 	if (!btf) {
6437 		err = -ENOMEM;
6438 		goto errout;
6439 	}
6440 	env->btf = btf;
6441 	btf->named_start_id = 0;
6442 
6443 	data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
6444 	if (!data) {
6445 		err = -ENOMEM;
6446 		goto errout;
6447 	}
6448 
6449 	btf->data = data;
6450 	btf->data_size = attr->btf_size;
6451 
6452 	if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
6453 		err = -EFAULT;
6454 		goto errout;
6455 	}
6456 
6457 	err = btf_parse_hdr(env);
6458 	if (err)
6459 		goto errout;
6460 
6461 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6462 
6463 	err = btf_parse_str_sec(env);
6464 	if (err)
6465 		goto errout;
6466 
6467 	err = btf_parse_layout_sec(env);
6468 	if (err)
6469 		goto errout;
6470 
6471 	err = btf_parse_type_sec(env);
6472 	if (err)
6473 		goto errout;
6474 
6475 	err = btf_check_modifier_chain_length(env, btf, 1);
6476 	if (err)
6477 		goto errout;
6478 
6479 	struct_meta_tab = btf_parse_struct_metas(&env->log, btf);
6480 	if (IS_ERR(struct_meta_tab)) {
6481 		err = PTR_ERR(struct_meta_tab);
6482 		goto errout;
6483 	}
6484 	btf->struct_meta_tab = struct_meta_tab;
6485 
6486 	if (struct_meta_tab) {
6487 		int i;
6488 
6489 		for (i = 0; i < struct_meta_tab->cnt; i++) {
6490 			err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
6491 			if (err < 0)
6492 				goto errout_meta;
6493 		}
6494 
6495 		err = btf_check_ownership_depth(btf, struct_meta_tab);
6496 		if (err < 0)
6497 			goto errout_meta;
6498 	}
6499 
6500 	err = bpf_log_attr_finalize(attr_log, &env->log);
6501 	if (err)
6502 		goto errout_free;
6503 
6504 	btf_verifier_env_free(env);
6505 	refcount_set(&btf->refcnt, 1);
6506 	return btf;
6507 
6508 errout_meta:
6509 	btf_free_struct_meta_tab(btf);
6510 errout:
6511 	/* overwrite err with -ENOSPC or -EFAULT */
6512 	ret = bpf_log_attr_finalize(attr_log, &env->log);
6513 	if (ret)
6514 		err = ret;
6515 errout_free:
6516 	btf_verifier_env_free(env);
6517 	if (btf)
6518 		btf_free(btf);
6519 	return ERR_PTR(err);
6520 }
6521 
6522 extern char __start_BTF[];
6523 extern char __stop_BTF[];
6524 extern struct btf *btf_vmlinux;
6525 
6526 #define BPF_MAP_TYPE(_id, _ops)
6527 #define BPF_LINK_TYPE(_id, _name)
6528 static union {
6529 	struct bpf_ctx_convert {
6530 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
6531 	prog_ctx_type _id##_prog; \
6532 	kern_ctx_type _id##_kern;
6533 #include <linux/bpf_types.h>
6534 #undef BPF_PROG_TYPE
6535 	} *__t;
6536 	/* 't' is written once under lock. Read many times. */
6537 	const struct btf_type *t;
6538 } bpf_ctx_convert;
6539 enum {
6540 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
6541 	__ctx_convert##_id,
6542 #include <linux/bpf_types.h>
6543 #undef BPF_PROG_TYPE
6544 	__ctx_convert_unused, /* to avoid empty enum in extreme .config */
6545 };
6546 static u8 bpf_ctx_convert_map[] = {
6547 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
6548 	[_id] = __ctx_convert##_id,
6549 #include <linux/bpf_types.h>
6550 #undef BPF_PROG_TYPE
6551 	0, /* avoid empty array */
6552 };
6553 #undef BPF_MAP_TYPE
6554 #undef BPF_LINK_TYPE
6555 
6556 static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
6557 {
6558 	const struct btf_type *conv_struct;
6559 	const struct btf_member *ctx_type;
6560 
6561 	conv_struct = bpf_ctx_convert.t;
6562 	if (!conv_struct)
6563 		return NULL;
6564 	/* prog_type is valid bpf program type. No need for bounds check. */
6565 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
6566 	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
6567 	 * Like 'struct __sk_buff'
6568 	 */
6569 	return btf_type_by_id(btf_vmlinux, ctx_type->type);
6570 }
6571 
6572 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
6573 {
6574 	const struct btf_type *conv_struct;
6575 	const struct btf_member *ctx_type;
6576 
6577 	conv_struct = bpf_ctx_convert.t;
6578 	if (!conv_struct)
6579 		return -EFAULT;
6580 	/* prog_type is valid bpf program type. No need for bounds check. */
6581 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6582 	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
6583 	 * Like 'struct sk_buff'
6584 	 */
6585 	return ctx_type->type;
6586 }
6587 
6588 bool btf_is_projection_of(const char *pname, const char *tname)
6589 {
6590 	if (strcmp(pname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
6591 		return true;
6592 	if (strcmp(pname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
6593 		return true;
6594 	return false;
6595 }
6596 
6597 bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
6598 			  const struct btf_type *t, enum bpf_prog_type prog_type,
6599 			  int arg)
6600 {
6601 	const struct btf_type *ctx_type;
6602 	const char *tname, *ctx_tname;
6603 
6604 	t = btf_type_by_id(btf, t->type);
6605 
6606 	/* KPROBE programs allow bpf_user_pt_regs_t typedef, which we need to
6607 	 * check before we skip all the typedef below.
6608 	 */
6609 	if (prog_type == BPF_PROG_TYPE_KPROBE) {
6610 		while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
6611 			t = btf_type_by_id(btf, t->type);
6612 
6613 		if (btf_type_is_typedef(t)) {
6614 			tname = btf_name_by_offset(btf, t->name_off);
6615 			if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
6616 				return true;
6617 		}
6618 	}
6619 
6620 	while (btf_type_is_modifier(t))
6621 		t = btf_type_by_id(btf, t->type);
6622 	if (!btf_type_is_struct(t)) {
6623 		/* Only pointer to struct is supported for now.
6624 		 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
6625 		 * is not supported yet.
6626 		 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
6627 		 */
6628 		return false;
6629 	}
6630 	tname = btf_name_by_offset(btf, t->name_off);
6631 	if (!tname) {
6632 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
6633 		return false;
6634 	}
6635 
6636 	ctx_type = find_canonical_prog_ctx_type(prog_type);
6637 	if (!ctx_type) {
6638 		bpf_log(log, "btf_vmlinux is malformed\n");
6639 		/* should not happen */
6640 		return false;
6641 	}
6642 again:
6643 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6644 	if (!ctx_tname) {
6645 		/* should not happen */
6646 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
6647 		return false;
6648 	}
6649 	/* program types without named context types work only with arg:ctx tag */
6650 	if (ctx_tname[0] == '\0')
6651 		return false;
6652 	/* only compare that prog's ctx type name is the same as
6653 	 * kernel expects. No need to compare field by field.
6654 	 * It's ok for bpf prog to do:
6655 	 * struct __sk_buff {};
6656 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
6657 	 * { // no fields of skb are ever used }
6658 	 */
6659 	if (btf_is_projection_of(ctx_tname, tname))
6660 		return true;
6661 	if (strcmp(ctx_tname, tname)) {
6662 		/* bpf_user_pt_regs_t is a typedef, so resolve it to
6663 		 * underlying struct and check name again
6664 		 */
6665 		if (!btf_type_is_modifier(ctx_type))
6666 			return false;
6667 		while (btf_type_is_modifier(ctx_type))
6668 			ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6669 		goto again;
6670 	}
6671 	return true;
6672 }
6673 
6674 /* forward declarations for arch-specific underlying types of
6675  * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
6676  * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
6677  * works correctly with __builtin_types_compatible_p() on respective
6678  * architectures
6679  */
6680 struct user_regs_struct;
6681 struct user_pt_regs;
6682 
6683 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
6684 				      const struct btf_type *t, int arg,
6685 				      enum bpf_prog_type prog_type,
6686 				      enum bpf_attach_type attach_type)
6687 {
6688 	const struct btf_type *ctx_type;
6689 	const char *tname, *ctx_tname;
6690 
6691 	if (!btf_is_ptr(t)) {
6692 		bpf_log(log, "arg#%d type isn't a pointer\n", arg);
6693 		return -EINVAL;
6694 	}
6695 	t = btf_type_by_id(btf, t->type);
6696 
6697 	/* KPROBE and PERF_EVENT programs allow bpf_user_pt_regs_t typedef */
6698 	if (prog_type == BPF_PROG_TYPE_KPROBE || prog_type == BPF_PROG_TYPE_PERF_EVENT) {
6699 		while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
6700 			t = btf_type_by_id(btf, t->type);
6701 
6702 		if (btf_type_is_typedef(t)) {
6703 			tname = btf_name_by_offset(btf, t->name_off);
6704 			if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
6705 				return 0;
6706 		}
6707 	}
6708 
6709 	/* all other program types don't use typedefs for context type */
6710 	while (btf_type_is_modifier(t))
6711 		t = btf_type_by_id(btf, t->type);
6712 
6713 	/* `void *ctx __arg_ctx` is always valid */
6714 	if (btf_type_is_void(t))
6715 		return 0;
6716 
6717 	tname = btf_name_by_offset(btf, t->name_off);
6718 	if (str_is_empty(tname)) {
6719 		bpf_log(log, "arg#%d type doesn't have a name\n", arg);
6720 		return -EINVAL;
6721 	}
6722 
6723 	/* special cases */
6724 	switch (prog_type) {
6725 	case BPF_PROG_TYPE_KPROBE:
6726 		if (__btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6727 			return 0;
6728 		break;
6729 	case BPF_PROG_TYPE_PERF_EVENT:
6730 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6731 		    __btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6732 			return 0;
6733 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6734 		    __btf_type_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6735 			return 0;
6736 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6737 		    __btf_type_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6738 			return 0;
6739 		break;
6740 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6741 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6742 		/* allow u64* as ctx */
6743 		if (btf_is_int(t) && t->size == 8)
6744 			return 0;
6745 		break;
6746 	case BPF_PROG_TYPE_TRACING:
6747 		switch (attach_type) {
6748 		case BPF_TRACE_RAW_TP:
6749 			/* tp_btf program is TRACING, so need special case here */
6750 			if (__btf_type_is_struct(t) &&
6751 			    strcmp(tname, "bpf_raw_tracepoint_args") == 0)
6752 				return 0;
6753 			/* allow u64* as ctx */
6754 			if (btf_is_int(t) && t->size == 8)
6755 				return 0;
6756 			break;
6757 		case BPF_TRACE_ITER:
6758 			/* allow struct bpf_iter__xxx types only */
6759 			if (__btf_type_is_struct(t) &&
6760 			    strncmp(tname, "bpf_iter__", sizeof("bpf_iter__") - 1) == 0)
6761 				return 0;
6762 			break;
6763 		case BPF_TRACE_FENTRY:
6764 		case BPF_TRACE_FEXIT:
6765 		case BPF_MODIFY_RETURN:
6766 		case BPF_TRACE_FSESSION:
6767 			/* allow u64* as ctx */
6768 			if (btf_is_int(t) && t->size == 8)
6769 				return 0;
6770 			break;
6771 		default:
6772 			break;
6773 		}
6774 		break;
6775 	case BPF_PROG_TYPE_LSM:
6776 	case BPF_PROG_TYPE_STRUCT_OPS:
6777 		/* allow u64* as ctx */
6778 		if (btf_is_int(t) && t->size == 8)
6779 			return 0;
6780 		break;
6781 	case BPF_PROG_TYPE_TRACEPOINT:
6782 	case BPF_PROG_TYPE_SYSCALL:
6783 	case BPF_PROG_TYPE_EXT:
6784 		return 0; /* anything goes */
6785 	default:
6786 		break;
6787 	}
6788 
6789 	ctx_type = find_canonical_prog_ctx_type(prog_type);
6790 	if (!ctx_type) {
6791 		/* should not happen */
6792 		bpf_log(log, "btf_vmlinux is malformed\n");
6793 		return -EINVAL;
6794 	}
6795 
6796 	/* resolve typedefs and check that underlying structs are matching as well */
6797 	while (btf_type_is_modifier(ctx_type))
6798 		ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6799 
6800 	/* if program type doesn't have distinctly named struct type for
6801 	 * context, then __arg_ctx argument can only be `void *`, which we
6802 	 * already checked above
6803 	 */
6804 	if (!__btf_type_is_struct(ctx_type)) {
6805 		bpf_log(log, "arg#%d should be void pointer\n", arg);
6806 		return -EINVAL;
6807 	}
6808 
6809 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6810 	if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
6811 		bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
6812 		return -EINVAL;
6813 	}
6814 
6815 	return 0;
6816 }
6817 
6818 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
6819 				     struct btf *btf,
6820 				     const struct btf_type *t,
6821 				     enum bpf_prog_type prog_type,
6822 				     int arg)
6823 {
6824 	if (!btf_is_prog_ctx_type(log, btf, t, prog_type, arg))
6825 		return -ENOENT;
6826 	return find_kern_ctx_type_id(prog_type);
6827 }
6828 
6829 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
6830 {
6831 	const struct btf_member *kctx_member;
6832 	const struct btf_type *conv_struct;
6833 	const struct btf_type *kctx_type;
6834 	u32 kctx_type_id;
6835 
6836 	conv_struct = bpf_ctx_convert.t;
6837 	/* get member for kernel ctx type */
6838 	kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6839 	kctx_type_id = kctx_member->type;
6840 	kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
6841 	if (!btf_type_is_struct(kctx_type)) {
6842 		bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
6843 		return -EINVAL;
6844 	}
6845 
6846 	return kctx_type_id;
6847 }
6848 
6849 BTF_ID_LIST_SINGLE(bpf_ctx_convert_btf_id, struct, bpf_ctx_convert)
6850 
6851 static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name,
6852 				  void *data, unsigned int data_size)
6853 {
6854 	struct btf *btf = NULL;
6855 	int err;
6856 
6857 	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
6858 		return ERR_PTR(-ENOENT);
6859 
6860 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
6861 	if (!btf) {
6862 		err = -ENOMEM;
6863 		goto errout;
6864 	}
6865 	env->btf = btf;
6866 
6867 	btf->data = data;
6868 	btf->data_size = data_size;
6869 	btf->kernel_btf = true;
6870 	btf->named_start_id = 0;
6871 	strscpy(btf->name, name);
6872 
6873 	err = btf_parse_hdr(env);
6874 	if (err)
6875 		goto errout;
6876 
6877 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6878 
6879 	err = btf_parse_str_sec(env);
6880 	if (err)
6881 		goto errout;
6882 
6883 	err = btf_check_all_metas(env);
6884 	if (err)
6885 		goto errout;
6886 
6887 	err = btf_check_modifier_chain_length(env, btf, 1);
6888 	if (err)
6889 		goto errout;
6890 
6891 	btf_check_sorted(btf);
6892 	refcount_set(&btf->refcnt, 1);
6893 
6894 	return btf;
6895 
6896 errout:
6897 	if (btf) {
6898 		kvfree(btf->types);
6899 		kfree(btf);
6900 	}
6901 	return ERR_PTR(err);
6902 }
6903 
6904 struct btf *btf_parse_vmlinux(void)
6905 {
6906 	struct btf_verifier_env *env = NULL;
6907 	struct bpf_verifier_log *log;
6908 	struct btf *btf;
6909 	int err;
6910 
6911 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
6912 	if (!env)
6913 		return ERR_PTR(-ENOMEM);
6914 
6915 	log = &env->log;
6916 	log->level = BPF_LOG_KERNEL;
6917 	btf = btf_parse_base(env, "vmlinux", __start_BTF, __stop_BTF - __start_BTF);
6918 	if (IS_ERR(btf))
6919 		goto err_out;
6920 
6921 	/* btf_parse_vmlinux() runs under btf_vmlinux_lock */
6922 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
6923 	err = btf_alloc_id(btf);
6924 	if (err) {
6925 		btf_free(btf);
6926 		btf = ERR_PTR(err);
6927 	}
6928 err_out:
6929 	btf_verifier_env_free(env);
6930 	return btf;
6931 }
6932 
6933 /* If .BTF_ids section was created with distilled base BTF, both base and
6934  * split BTF ids will need to be mapped to actual base/split ids for
6935  * BTF now that it has been relocated.
6936  */
6937 __u32 btf_relocate_id(const struct btf *btf, __u32 id)
6938 {
6939 	if (!btf->base_btf || !btf->base_id_map)
6940 		return id;
6941 	return btf->base_id_map[id];
6942 }
6943 
6944 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6945 
6946 static struct btf *btf_parse_split(struct btf_verifier_env *env,
6947 				   const char *name, const void *data,
6948 				   unsigned int data_size, struct btf *base_btf)
6949 {
6950 	struct btf *btf;
6951 	int err;
6952 
6953 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
6954 	if (!btf)
6955 		return ERR_PTR(-ENOMEM);
6956 	env->btf = btf;
6957 
6958 	btf_set_base_btf(btf, base_btf);
6959 	btf->kernel_btf = true;
6960 	btf->named_start_id = 0;
6961 	strscpy(btf->name, name);
6962 
6963 	btf->data = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);
6964 	if (!btf->data) {
6965 		err = -ENOMEM;
6966 		goto errout;
6967 	}
6968 	btf->data_size = data_size;
6969 
6970 	err = btf_parse_hdr(env);
6971 	if (err)
6972 		goto errout;
6973 
6974 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6975 
6976 	err = btf_parse_str_sec(env);
6977 	if (err)
6978 		goto errout;
6979 
6980 	err = btf_check_all_metas(env);
6981 	if (err)
6982 		goto errout;
6983 
6984 	err = btf_check_modifier_chain_length(env, btf, btf_nr_types(base_btf));
6985 	if (err)
6986 		goto errout;
6987 
6988 	return btf;
6989 
6990 errout:
6991 	btf_free(btf);
6992 	return ERR_PTR(err);
6993 }
6994 
6995 static int btf_rebase_inline(struct btf *inline_btf,
6996 			     const struct btf *module_btf,
6997 			     const u32 *module_id_map,
6998 			     const u32 *module_str_map,
6999 			     u32 old_module_type_cnt)
7000 {
7001 	u32 old_start_id = inline_btf->start_id;
7002 	u32 old_start_str_off = inline_btf->start_str_off;
7003 	u32 old_module_start_str_off = old_start_str_off - module_btf->hdr.str_len;
7004 	u32 new_start_id = btf_nr_types(module_btf);
7005 	u32 new_start_str_off = module_btf->start_str_off + module_btf->hdr.str_len;
7006 	s64 id_delta = (s64)new_start_id - old_start_id;
7007 	s64 str_delta = (s64)new_start_str_off - old_start_str_off;
7008 	u32 i;
7009 
7010 	/*
7011 	 * The inline BTF was parsed relative to the original module BTF. Its
7012 	 * base IDs must therefore use the map generated when that BTF was
7013 	 * relocated, while IDs for inline-local types only move by the change
7014 	 * in the module BTF's starting ID.
7015 	 */
7016 	for (i = 0; i < inline_btf->nr_types; i++) {
7017 		struct btf_field_iter it;
7018 		struct btf_type *t = inline_btf->types[i];
7019 		u32 *id, *str_off;
7020 		int err;
7021 
7022 		err = btf_field_iter_init(&it, t, BTF_FIELD_ITER_IDS);
7023 		if (err)
7024 			return err;
7025 		while ((id = btf_field_iter_next(&it))) {
7026 			if (!*id)
7027 				continue;
7028 			if (*id < old_module_type_cnt) {
7029 				if (module_id_map)
7030 					*id = module_id_map[*id];
7031 			} else if (*id >= old_start_id) {
7032 				*id += id_delta;
7033 			} else {
7034 				return -EINVAL;
7035 			}
7036 		}
7037 
7038 		err = btf_field_iter_init(&it, t, BTF_FIELD_ITER_STRS);
7039 		if (err)
7040 			return err;
7041 		while ((str_off = btf_field_iter_next(&it))) {
7042 			if (!*str_off)
7043 				continue;
7044 			if (*str_off < old_module_start_str_off) {
7045 				/* Vmlinux strings retain their offsets for in-tree modules. */
7046 				if (!module_id_map)
7047 					continue;
7048 				if (!module_str_map || !module_str_map[*str_off])
7049 					return -EINVAL;
7050 				*str_off = module_str_map[*str_off];
7051 				continue;
7052 			}
7053 			*str_off += str_delta;
7054 		}
7055 	}
7056 
7057 	btf_set_base_btf(inline_btf, module_btf);
7058 	btf_check_sorted(inline_btf);
7059 	return 0;
7060 }
7061 
7062 static struct btf *btf_parse_module(const char *module_name, const void *data,
7063 				    unsigned int data_size, void *base_data,
7064 				    unsigned int base_data_size,
7065 				    const void *inline_data,
7066 				    unsigned int inline_data_size,
7067 				    void **relocated_inline_data)
7068 {
7069 	struct btf *btf = NULL, *inline_btf = NULL, *vmlinux_btf, *base_btf = NULL;
7070 	struct btf_verifier_env *env = NULL;
7071 	struct bpf_verifier_log *log;
7072 	u32 *module_str_map = NULL;
7073 	u32 old_module_type_cnt;
7074 	int err = 0;
7075 
7076 	*relocated_inline_data = NULL;
7077 	vmlinux_btf = bpf_get_btf_vmlinux();
7078 	if (IS_ERR(vmlinux_btf))
7079 		return vmlinux_btf;
7080 	if (!vmlinux_btf)
7081 		return ERR_PTR(-EINVAL);
7082 
7083 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
7084 	if (!env)
7085 		return ERR_PTR(-ENOMEM);
7086 
7087 	log = &env->log;
7088 	log->level = BPF_LOG_KERNEL;
7089 
7090 	if (base_data) {
7091 		base_btf = btf_parse_base(env, ".BTF.base", base_data, base_data_size);
7092 		if (IS_ERR(base_btf)) {
7093 			err = PTR_ERR(base_btf);
7094 			goto errout;
7095 		}
7096 	} else {
7097 		base_btf = vmlinux_btf;
7098 	}
7099 
7100 	btf = btf_parse_split(env, module_name, data, data_size, base_btf);
7101 	if (IS_ERR(btf)) {
7102 		err = PTR_ERR(btf);
7103 		btf = NULL;
7104 		goto errout;
7105 	}
7106 	old_module_type_cnt = btf_nr_types(btf);
7107 
7108 	if (inline_data_size) {
7109 		inline_btf = btf_parse_split(env, module_name, inline_data,
7110 					     inline_data_size, btf);
7111 		if (IS_ERR(inline_btf)) {
7112 			pr_warn("failed to validate module [%s] inline BTF: %ld\n",
7113 				module_name, PTR_ERR(inline_btf));
7114 			inline_btf = NULL;
7115 		}
7116 	}
7117 
7118 	if (base_btf != vmlinux_btf) {
7119 		err = btf_relocate(btf, vmlinux_btf, &btf->base_id_map,
7120 				   &module_str_map);
7121 		if (err)
7122 			goto errout;
7123 		btf_free(base_btf);
7124 		base_btf = vmlinux_btf;
7125 	}
7126 
7127 	if (inline_btf) {
7128 		err = btf_rebase_inline(inline_btf, btf, btf->base_id_map,
7129 					module_str_map, old_module_type_cnt);
7130 		if (err) {
7131 			pr_warn("failed to relocate module [%s] inline BTF: %d\n",
7132 				module_name, err);
7133 			btf_free(inline_btf);
7134 		} else {
7135 			*relocated_inline_data = inline_btf->data;
7136 			inline_btf->data = NULL;
7137 			btf_free(inline_btf);
7138 		}
7139 	}
7140 
7141 	/*
7142 	 * With a distilled base, btf_relocate() replaces the base BTF and
7143 	 * rewrites string offsets. Check ordering only after that final BTF
7144 	 * view has been established, so named_start_id describes the BTF used
7145 	 * by name lookups.
7146 	 */
7147 	btf_check_sorted(btf);
7148 	btf_verifier_env_free(env);
7149 	kvfree(module_str_map);
7150 	refcount_set(&btf->refcnt, 1);
7151 	return btf;
7152 
7153 errout:
7154 	kvfree(module_str_map);
7155 	btf_verifier_env_free(env);
7156 	if (inline_btf)
7157 		btf_free(inline_btf);
7158 	if (!IS_ERR(base_btf) && base_btf != vmlinux_btf)
7159 		btf_free(base_btf);
7160 	if (btf)
7161 		btf_free(btf);
7162 	return ERR_PTR(err);
7163 }
7164 
7165 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7166 
7167 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
7168 {
7169 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
7170 
7171 	if (tgt_prog)
7172 		return tgt_prog->aux->btf;
7173 	else
7174 		return prog->aux->attach_btf;
7175 }
7176 
7177 u32 btf_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
7178 		    int off)
7179 {
7180 	const struct btf_param *args;
7181 	const struct btf_type *t;
7182 	u32 offset = 0, nr_args;
7183 	int i;
7184 
7185 	if (!func_proto)
7186 		return off / 8;
7187 
7188 	nr_args = btf_type_vlen(func_proto);
7189 	args = (const struct btf_param *)(func_proto + 1);
7190 	for (i = 0; i < nr_args; i++) {
7191 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
7192 		offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
7193 		if (off < offset)
7194 			return i;
7195 	}
7196 
7197 	t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
7198 	offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
7199 	if (off < offset)
7200 		return nr_args;
7201 
7202 	return nr_args + 1;
7203 }
7204 
7205 static bool prog_args_trusted(const struct bpf_prog *prog)
7206 {
7207 	enum bpf_attach_type atype = prog->expected_attach_type;
7208 
7209 	switch (prog->type) {
7210 	case BPF_PROG_TYPE_TRACING:
7211 		return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
7212 	case BPF_PROG_TYPE_LSM:
7213 		return bpf_lsm_is_trusted(prog);
7214 	case BPF_PROG_TYPE_STRUCT_OPS:
7215 		return true;
7216 	default:
7217 		return false;
7218 	}
7219 }
7220 
7221 int btf_ctx_arg_offset(const struct btf *btf, const struct btf_type *func_proto,
7222 		       u32 arg_no)
7223 {
7224 	const struct btf_param *args;
7225 	const struct btf_type *t;
7226 	int off = 0, i;
7227 	u32 sz;
7228 
7229 	args = btf_params(func_proto);
7230 	for (i = 0; i < arg_no; i++) {
7231 		t = btf_type_by_id(btf, args[i].type);
7232 		t = btf_resolve_size(btf, t, &sz);
7233 		if (IS_ERR(t))
7234 			return PTR_ERR(t);
7235 		off += roundup(sz, 8);
7236 	}
7237 
7238 	return off;
7239 }
7240 
7241 struct bpf_raw_tp_null_args {
7242 	const char *func;
7243 	u64 mask;
7244 };
7245 
7246 static const struct bpf_raw_tp_null_args raw_tp_null_args[] = {
7247 	/* sched */
7248 	{ "sched_pi_setprio", 0x10 },
7249 	/*
7250 	 * do_wait() passes NULL for wait4(-1) and waitid(P_ALL).
7251 	 */
7252 	{ "sched_process_wait", 0x1 },
7253 	/* ... from sched_numa_pair_template event class */
7254 	{ "sched_stick_numa", 0x100 },
7255 	{ "sched_swap_numa", 0x100 },
7256 	/* afs */
7257 	{ "afs_make_fs_call", 0x10 },
7258 	{ "afs_make_fs_calli", 0x10 },
7259 	{ "afs_make_fs_call1", 0x10 },
7260 	{ "afs_make_fs_call2", 0x10 },
7261 	{ "afs_protocol_error", 0x1 },
7262 	{ "afs_flock_ev", 0x10 },
7263 	/* cachefiles */
7264 	{ "cachefiles_lookup", 0x1 | 0x200 },
7265 	{ "cachefiles_unlink", 0x1 },
7266 	{ "cachefiles_rename", 0x1 },
7267 	{ "cachefiles_prep_read", 0x1 },
7268 	{ "cachefiles_mark_active", 0x1 },
7269 	{ "cachefiles_mark_failed", 0x1 },
7270 	{ "cachefiles_mark_inactive", 0x1 },
7271 	{ "cachefiles_vfs_error", 0x1 },
7272 	{ "cachefiles_io_error", 0x1 },
7273 	/* ext4, from ext4__mballoc event class */
7274 	{ "ext4_mballoc_discard", 0x10 },
7275 	{ "ext4_mballoc_free", 0x10 },
7276 	/* fib */
7277 	{ "fib_table_lookup", 0x100 },
7278 	/* filelock */
7279 	/* ... from filelock_lock event class */
7280 	{ "posix_lock_inode", 0x10 },
7281 	{ "fcntl_setlk", 0x10 },
7282 	{ "locks_remove_posix", 0x10 },
7283 	{ "flock_lock_inode", 0x10 },
7284 	/* ... from filelock_lease event class */
7285 	{ "break_lease_noblock", 0x10 },
7286 	{ "break_lease_block", 0x10 },
7287 	{ "break_lease_unblock", 0x10 },
7288 	{ "generic_delete_lease", 0x10 },
7289 	{ "time_out_leases", 0x10 },
7290 	/* host1x */
7291 	{ "host1x_cdma_push_gather", 0x10000 },
7292 	/* huge_memory */
7293 	{ "mm_khugepaged_scan_pmd", 0x10 },
7294 	{ "mm_collapse_huge_page_isolate", 0x1 },
7295 	{ "mm_khugepaged_scan_file", 0x10 },
7296 	{ "mm_khugepaged_collapse_file", 0x10 },
7297 	/* kmem */
7298 	{ "mm_page_alloc", 0x1 },
7299 	{ "mm_page_pcpu_drain", 0x1 },
7300 	/* .. from mm_page event class */
7301 	{ "mm_page_alloc_zone_locked", 0x1 },
7302 	/* netfs */
7303 	{ "netfs_failure", 0x10 },
7304 	/* power */
7305 	{ "device_pm_callback_start", 0x10 },
7306 	/* qdisc */
7307 	{ "qdisc_dequeue", 0x1000 },
7308 	/* rxrpc */
7309 	{ "rxrpc_recvdata", 0x1 },
7310 	{ "rxrpc_resend", 0x10 },
7311 	{ "rxrpc_tq", 0x10 },
7312 	{ "rxrpc_client", 0x1 },
7313 	/* signal */
7314 	{ "signal_generate", 0x20 },
7315 	{ "signal_deliver", 0x20 },
7316 	/* skb */
7317 	{"kfree_skb", 0x1000},
7318 	/* sunrpc */
7319 	{ "xs_stream_read_data", 0x1 },
7320 	/* ... from xprt_cong_event event class */
7321 	{ "xprt_reserve_cong", 0x10 },
7322 	{ "xprt_release_cong", 0x10 },
7323 	{ "xprt_get_cong", 0x10 },
7324 	{ "xprt_put_cong", 0x10 },
7325 	/* tcp */
7326 	{ "tcp_send_reset", 0x11 },
7327 	{ "tcp_sendmsg_locked", 0x100 },
7328 	/* tegra_apb_dma */
7329 	{ "tegra_dma_tx_status", 0x100 },
7330 	/* timer_migration */
7331 	{ "tmigr_update_events", 0x1 },
7332 	/* writeback, from writeback_folio_template event class */
7333 	{ "writeback_dirty_folio", 0x10 },
7334 	{ "folio_wait_writeback", 0x10 },
7335 	/* rdma */
7336 	{ "mr_integ_alloc", 0x2000 },
7337 	/* bpf_testmod */
7338 	{ "bpf_testmod_test_read", 0x0 },
7339 	/* amdgpu */
7340 	{ "amdgpu_vm_bo_map", 0x1 },
7341 	{ "amdgpu_vm_bo_unmap", 0x1 },
7342 	/* netfs */
7343 	{ "netfs_folioq", 0x1 },
7344 	/* xfs from xfs_defer_pending_class */
7345 	{ "xfs_defer_create_intent", 0x1 },
7346 	{ "xfs_defer_cancel_list", 0x1 },
7347 	{ "xfs_defer_pending_finish", 0x1 },
7348 	{ "xfs_defer_pending_abort", 0x1 },
7349 	{ "xfs_defer_relog_intent", 0x1 },
7350 	{ "xfs_defer_isolate_paused", 0x1 },
7351 	{ "xfs_defer_item_pause", 0x1 },
7352 	{ "xfs_defer_item_unpause", 0x1 },
7353 	/* xfs from xfs_defer_pending_item_class */
7354 	{ "xfs_defer_add_item", 0x1 },
7355 	{ "xfs_defer_cancel_item", 0x1 },
7356 	{ "xfs_defer_finish_item", 0x1 },
7357 	/* xfs from xfs_icwalk_class */
7358 	{ "xfs_ioc_free_eofblocks", 0x10 },
7359 	{ "xfs_blockgc_free_space", 0x10 },
7360 	/* xfs from xfs_btree_cur_class */
7361 	{ "xfs_btree_updkeys", 0x100 },
7362 	{ "xfs_btree_overlapped_query_range", 0x100 },
7363 	/* xfs from xfs_imap_class*/
7364 	{ "xfs_map_blocks_found", 0x10000 },
7365 	{ "xfs_map_blocks_alloc", 0x10000 },
7366 	{ "xfs_iomap_alloc", 0x1000 },
7367 	{ "xfs_iomap_found", 0x1000 },
7368 	/* xfs from xfs_fs_class */
7369 	{ "xfs_inodegc_flush", 0x1 },
7370 	{ "xfs_inodegc_push", 0x1 },
7371 	{ "xfs_inodegc_start", 0x1 },
7372 	{ "xfs_inodegc_stop", 0x1 },
7373 	{ "xfs_inodegc_queue", 0x1 },
7374 	{ "xfs_inodegc_throttle", 0x1 },
7375 	{ "xfs_fs_sync_fs", 0x1 },
7376 	{ "xfs_blockgc_start", 0x1 },
7377 	{ "xfs_blockgc_stop", 0x1 },
7378 	{ "xfs_blockgc_worker", 0x1 },
7379 	{ "xfs_blockgc_flush_all", 0x1 },
7380 	/* xfs_scrub */
7381 	{ "xchk_nlinks_live_update", 0x10 },
7382 	/* xfs_scrub from xchk_metapath_class */
7383 	{ "xchk_metapath_lookup", 0x100 },
7384 	/* nfsd */
7385 	{ "nfsd_dirent", 0x1 },
7386 	{ "nfsd_file_acquire", 0x1001 },
7387 	{ "nfsd_file_insert_err", 0x1 },
7388 	{ "nfsd_file_cons_err", 0x1 },
7389 	/* nfs4 */
7390 	{ "nfs4_setup_sequence", 0x1 },
7391 	{ "pnfs_update_layout", 0x10000 },
7392 	{ "nfs4_inode_callback_event", 0x200 },
7393 	{ "nfs4_inode_stateid_callback_event", 0x200 },
7394 	/* nfs from pnfs_layout_event */
7395 	{ "pnfs_mds_fallback_pg_init_read", 0x10000 },
7396 	{ "pnfs_mds_fallback_pg_init_write", 0x10000 },
7397 	{ "pnfs_mds_fallback_pg_get_mirror_count", 0x10000 },
7398 	{ "pnfs_mds_fallback_read_done", 0x10000 },
7399 	{ "pnfs_mds_fallback_write_done", 0x10000 },
7400 	{ "pnfs_mds_fallback_read_pagelist", 0x10000 },
7401 	{ "pnfs_mds_fallback_write_pagelist", 0x10000 },
7402 	/* coda */
7403 	{ "coda_dec_pic_run", 0x10 },
7404 	{ "coda_dec_pic_done", 0x10 },
7405 	/* cfg80211 */
7406 	{ "cfg80211_scan_done", 0x11 },
7407 	{ "rdev_set_coalesce", 0x10 },
7408 	{ "cfg80211_report_wowlan_wakeup", 0x100 },
7409 	{ "cfg80211_inform_bss_frame", 0x100 },
7410 	{ "cfg80211_michael_mic_failure", 0x10000 },
7411 	/* cfg80211 from wiphy_work_event */
7412 	{ "wiphy_work_queue", 0x10 },
7413 	{ "wiphy_work_run", 0x10 },
7414 	{ "wiphy_work_cancel", 0x10 },
7415 	{ "wiphy_work_flush", 0x10 },
7416 	/* hugetlbfs */
7417 	{ "hugetlbfs_alloc_inode", 0x10 },
7418 	/* spufs */
7419 	{ "spufs_context", 0x10 },
7420 	/* kvm_hv */
7421 	{ "kvm_page_fault_enter", 0x100 },
7422 	/* dpu */
7423 	{ "dpu_crtc_setup_mixer", 0x100 },
7424 	/* binder */
7425 	{ "binder_transaction", 0x100 },
7426 	/* bcachefs */
7427 	{ "btree_path_free", 0x100 },
7428 	/* hfi1_tx */
7429 	{ "hfi1_sdma_progress", 0x1000 },
7430 	/* iptfs */
7431 	{ "iptfs_ingress_postq_event", 0x1000 },
7432 	/* neigh */
7433 	{ "neigh_update", 0x10 },
7434 	/* snd_firewire_lib */
7435 	{ "amdtp_packet", 0x100 },
7436 };
7437 
7438 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
7439 		    const struct bpf_prog *prog,
7440 		    struct bpf_insn_access_aux *info)
7441 {
7442 	static const struct btf_type_tag_match ctx_type_tags[] = {
7443 		{ "user", MEM_USER },
7444 		{ "percpu", MEM_PERCPU },
7445 	};
7446 	const struct btf_type *t = prog->aux->attach_func_proto;
7447 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
7448 	struct btf *btf = bpf_prog_get_target_btf(prog);
7449 	const char *tname = prog->aux->attach_func_name;
7450 	struct bpf_verifier_log *log = info->log;
7451 	struct btf_type_tag_walk_ctx ctx;
7452 	const struct btf_param *args;
7453 	bool ptr_err_raw_tp = false;
7454 	u32 nr_args, arg;
7455 	int i, ret;
7456 
7457 	if (off % 8) {
7458 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
7459 			tname, off);
7460 		return false;
7461 	}
7462 	arg = btf_ctx_arg_idx(btf, t, off);
7463 	args = (const struct btf_param *)(t + 1);
7464 	/* if (t == NULL) Fall back to default BPF prog with
7465 	 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
7466 	 */
7467 	nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
7468 	if (prog->aux->attach_btf_trace) {
7469 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
7470 		args++;
7471 		nr_args--;
7472 	}
7473 
7474 	if (arg > nr_args) {
7475 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
7476 			tname, arg + 1);
7477 		return false;
7478 	}
7479 
7480 	if (arg == nr_args) {
7481 		switch (prog->expected_attach_type) {
7482 		case BPF_LSM_MAC:
7483 			/* mark we are accessing the return value */
7484 			info->is_retval = true;
7485 			fallthrough;
7486 		case BPF_LSM_CGROUP:
7487 		case BPF_TRACE_FEXIT:
7488 		case BPF_TRACE_FSESSION:
7489 			/* When LSM programs are attached to void LSM hooks
7490 			 * they use FEXIT trampolines and when attached to
7491 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
7492 			 *
7493 			 * While the LSM programs are BPF_MODIFY_RETURN-like
7494 			 * the check:
7495 			 *
7496 			 *	if (ret_type != 'int')
7497 			 *		return -EINVAL;
7498 			 *
7499 			 * is _not_ done here. This is still safe as LSM hooks
7500 			 * have only void and int return types.
7501 			 */
7502 			if (!t)
7503 				return true;
7504 			t = btf_type_by_id(btf, t->type);
7505 			break;
7506 		case BPF_MODIFY_RETURN:
7507 			/* For now the BPF_MODIFY_RETURN can only be attached to
7508 			 * functions that return an int.
7509 			 */
7510 			if (!t)
7511 				return false;
7512 
7513 			t = btf_type_skip_modifiers(btf, t->type, NULL);
7514 			if (!btf_type_is_small_int(t)) {
7515 				bpf_log(log,
7516 					"ret type %s not allowed for fmod_ret\n",
7517 					btf_type_str(t));
7518 				return false;
7519 			}
7520 			break;
7521 		default:
7522 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
7523 				tname, arg + 1);
7524 			return false;
7525 		}
7526 	} else {
7527 		if (!t)
7528 			/* Default prog with MAX_BPF_FUNC_REG_ARGS args */
7529 			return true;
7530 		t = btf_type_by_id(btf, args[arg].type);
7531 	}
7532 
7533 	/* skip modifiers */
7534 	while (btf_type_is_modifier(t))
7535 		t = btf_type_by_id(btf, t->type);
7536 	if (btf_type_is_small_int(t) || btf_is_any_enum(t) || btf_type_is_struct(t))
7537 		/* accessing a scalar */
7538 		return true;
7539 	if (!btf_type_is_ptr(t)) {
7540 		bpf_log(log,
7541 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
7542 			tname, arg,
7543 			__btf_name_by_offset(btf, t->name_off),
7544 			btf_type_str(t));
7545 		return false;
7546 	}
7547 
7548 	if (size != sizeof(u64)) {
7549 		bpf_log(log, "func '%s' size %d must be 8\n",
7550 			tname, size);
7551 		return false;
7552 	}
7553 
7554 	/*
7555 	 * Check for PTR_TO_RDONLY_BUF_OR_NULL, PTR_TO_RDWR_BUF_OR_NULL,
7556 	 * PTR_TO_ARENA (both nullable and non-nullable cases) or fixed-size
7557 	 * PTR_TO_MEM.
7558 	 */
7559 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
7560 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
7561 		u32 type, flag;
7562 
7563 		type = base_type(ctx_arg_info->reg_type);
7564 		flag = type_flag(ctx_arg_info->reg_type);
7565 		if (ctx_arg_info->offset == off &&
7566 		    (type == PTR_TO_ARENA ||
7567 		     type == PTR_TO_MEM ||
7568 		     (type == PTR_TO_BUF && (flag & PTR_MAYBE_NULL)))) {
7569 			info->reg_type = ctx_arg_info->reg_type;
7570 			info->mem_size = ctx_arg_info->mem_size;
7571 			return true;
7572 		}
7573 	}
7574 
7575 	/*
7576 	 * If it's a single or multilevel pointer, except a pointer
7577 	 * to a structure, it's the same as scalar from the verifier
7578 	 * safety POV. Multilevel pointers to structures are treated as
7579 	 * scalars. The verifier lacks the context to infer the size of
7580 	 * their target memory regions. Either way, no further pointer
7581 	 * walking is allowed.
7582 	 */
7583 	if (!btf_type_is_struct_ptr(btf, t))
7584 		return true;
7585 
7586 	/* this is a pointer to another type */
7587 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
7588 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
7589 
7590 		if (ctx_arg_info->offset == off) {
7591 			if (!ctx_arg_info->btf_id) {
7592 				bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
7593 				return false;
7594 			}
7595 
7596 			info->reg_type = ctx_arg_info->reg_type;
7597 			info->btf = ctx_arg_info->btf ? : btf_vmlinux;
7598 			info->btf_id = ctx_arg_info->btf_id;
7599 			info->ref_id = ctx_arg_info->ref_id;
7600 			return true;
7601 		}
7602 	}
7603 
7604 	info->reg_type = PTR_TO_BTF_ID;
7605 	if (prog_args_trusted(prog))
7606 		info->reg_type |= PTR_TRUSTED;
7607 
7608 	if (btf_param_match_suffix(btf, &args[arg], "__nullable"))
7609 		info->reg_type |= PTR_MAYBE_NULL;
7610 
7611 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
7612 		struct btf *btf = prog->aux->attach_btf;
7613 		const struct btf_type *t;
7614 		const char *tname;
7615 
7616 		/* BTF lookups cannot fail, return false on error */
7617 		t = btf_type_by_id(btf, prog->aux->attach_btf_id);
7618 		if (!t)
7619 			return false;
7620 		tname = btf_name_by_offset(btf, t->name_off);
7621 		if (!tname)
7622 			return false;
7623 		/* Checked by bpf_check_attach_target */
7624 		tname += sizeof("btf_trace_") - 1;
7625 		for (i = 0; i < ARRAY_SIZE(raw_tp_null_args); i++) {
7626 			/* Is this a func with potential NULL args? */
7627 			if (strcmp(tname, raw_tp_null_args[i].func))
7628 				continue;
7629 			if (raw_tp_null_args[i].mask & (0x1ULL << (arg * 4)))
7630 				info->reg_type |= PTR_MAYBE_NULL;
7631 			/* Is the current arg IS_ERR? */
7632 			if (raw_tp_null_args[i].mask & (0x2ULL << (arg * 4)))
7633 				ptr_err_raw_tp = true;
7634 			break;
7635 		}
7636 		/* If we don't know NULL-ness specification and the tracepoint
7637 		 * is coming from a loadable module, be conservative and mark
7638 		 * argument as PTR_MAYBE_NULL.
7639 		 */
7640 		if (i == ARRAY_SIZE(raw_tp_null_args) && btf_is_module(btf))
7641 			info->reg_type |= PTR_MAYBE_NULL;
7642 	}
7643 
7644 	if (tgt_prog) {
7645 		enum bpf_prog_type tgt_type;
7646 
7647 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
7648 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
7649 		else
7650 			tgt_type = tgt_prog->type;
7651 
7652 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
7653 		if (ret > 0) {
7654 			info->btf = btf_vmlinux;
7655 			info->btf_id = ret;
7656 			return true;
7657 		} else {
7658 			return false;
7659 		}
7660 	}
7661 
7662 	info->btf = btf;
7663 	ctx.t = t;
7664 	ret = btf_type_tag_walk(btf, &ctx, ctx_type_tags,
7665 				ARRAY_SIZE(ctx_type_tags));
7666 	if (ret) {
7667 		bpf_log(log, "func '%s' arg%d type %s has multiple type tags\n",
7668 			tname, arg, btf_type_str(t));
7669 		return false;
7670 	}
7671 	info->reg_type |= ctx.res;
7672 	info->btf_id = ctx.id;
7673 	t = ctx.t;
7674 
7675 	if (!btf_type_is_struct(t)) {
7676 		bpf_log(log,
7677 			"func '%s' arg%d type %s is not a struct\n",
7678 			tname, arg, btf_type_str(t));
7679 		return false;
7680 	}
7681 	bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
7682 		tname, arg, info->btf_id, btf_type_str(t),
7683 		__btf_name_by_offset(btf, t->name_off));
7684 
7685 	/* Perform all checks on the validity of type for this argument, but if
7686 	 * we know it can be IS_ERR at runtime, scrub pointer type and mark as
7687 	 * scalar.
7688 	 */
7689 	if (ptr_err_raw_tp) {
7690 		bpf_log(log, "marking pointer arg%d as scalar as it may encode error", arg);
7691 		info->reg_type = SCALAR_VALUE;
7692 	}
7693 	return true;
7694 }
7695 EXPORT_SYMBOL_GPL(btf_ctx_access);
7696 
7697 #define MAX_ARRAYS_WALK 16
7698 
7699 /* Description of an array crossed while walking a BTF access chain */
7700 struct array_access {
7701 	u32 id;		/* BTF_KIND_ARRAY type id */
7702 	u32 off;	/* offset of the access within the array */
7703 };
7704 
7705 enum bpf_struct_walk_result {
7706 	/* < 0 error */
7707 	WALK_SCALAR = 0,
7708 	WALK_PTR,
7709 	WALK_PTR_UNTRUSTED,
7710 	WALK_PTR_ARENA,
7711 	WALK_STRUCT,
7712 };
7713 
7714 static const struct btf_member *find_flex_member(const struct btf *btf, const struct btf_type *t)
7715 {
7716 	const struct btf_array *array;
7717 	const struct btf_type *mtype;
7718 	const struct btf_member *member;
7719 	u32 vlen = btf_type_vlen(t);
7720 
7721 	if (vlen == 0)
7722 		return NULL;
7723 
7724 	member = btf_type_member(t) + vlen - 1;
7725 	mtype = btf_type_skip_modifiers(btf, member->type, NULL);
7726 	if (!btf_type_is_array(mtype))
7727 		return NULL;
7728 
7729 	array = (const struct btf_array *)(mtype + 1);
7730 	if (array->nelems != 0)
7731 		return NULL;
7732 
7733 	return member;
7734 }
7735 
7736 static int push_array(struct array_access *arrays, u32 *arrays_cnt, struct array_access item)
7737 {
7738 	if (arrays == NULL)
7739 		return 0;
7740 	if (*arrays_cnt == MAX_ARRAYS_WALK)
7741 		return -1;
7742 	arrays[(*arrays_cnt)++] = item;
7743 	return 0;
7744 }
7745 
7746 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
7747 			   const struct btf_type *t, int off, int size,
7748 			   u32 *next_btf_id, enum bpf_type_flag *flag,
7749 			   const char **field_name, bool walk_flex_arrays,
7750 			   struct array_access *arrays, u32 *arrays_cnt)
7751 {
7752 	u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
7753 	const struct btf_type *mtype, *elem_type = NULL;
7754 	const struct btf_member *member;
7755 	const char *tname, *mname;
7756 	u32 vlen, elem_id, mid;
7757 
7758 again:
7759 	if (btf_type_is_modifier(t))
7760 		t = btf_type_skip_modifiers(btf, t->type, NULL);
7761 	tname = __btf_name_by_offset(btf, t->name_off);
7762 	if (!btf_type_is_struct(t)) {
7763 		bpf_log(log, "Type '%s' is not a struct\n", tname);
7764 		return -EINVAL;
7765 	}
7766 
7767 	vlen = btf_type_vlen(t);
7768 	if (BTF_INFO_KIND(t->info) == BTF_KIND_UNION && vlen != 1 && !(*flag & PTR_UNTRUSTED))
7769 		/*
7770 		 * walking unions yields untrusted pointers
7771 		 * with exception of __bpf_md_ptr and other
7772 		 * unions with a single member
7773 		 */
7774 		*flag |= PTR_UNTRUSTED;
7775 
7776 	if (off + size > t->size) {
7777 		struct btf_array *array_elem;
7778 
7779 		if (!walk_flex_arrays)
7780 			goto error;
7781 
7782 		/* If the last element is a variable size array, we may
7783 		 * need to relax the rule.
7784 		 */
7785 		member = find_flex_member(btf, t);
7786 		if (!member)
7787 			goto error;
7788 
7789 		moff = __btf_member_bit_offset(t, member) / 8;
7790 		if (off < moff)
7791 			goto error;
7792 
7793 		mtype = btf_type_skip_modifiers(btf, member->type, &mid);
7794 		array_elem = (struct btf_array *)(mtype + 1);
7795 
7796 		if (push_array(arrays, arrays_cnt, (struct array_access){ mid, off - moff }))
7797 			return -E2BIG;
7798 
7799 		/* allow structure and integer */
7800 		t = btf_type_skip_modifiers(btf, array_elem->type,
7801 					    NULL);
7802 
7803 		if (btf_type_is_int(t))
7804 			return WALK_SCALAR;
7805 
7806 		if (!btf_type_is_struct(t) || !t->size)
7807 			goto error;
7808 
7809 		off = (off - moff) % t->size;
7810 		goto again;
7811 
7812 error:
7813 		bpf_log(log, "access beyond struct %s at off %u size %u\n",
7814 			tname, off, size);
7815 		return -EACCES;
7816 	}
7817 
7818 	for_each_member(i, t, member) {
7819 		/* offset of the field in bytes */
7820 		moff = __btf_member_bit_offset(t, member) / 8;
7821 		if (off + size <= moff)
7822 			/* won't find anything, field is already too far */
7823 			break;
7824 
7825 		if (__btf_member_bitfield_size(t, member)) {
7826 			u32 end_bit = __btf_member_bit_offset(t, member) +
7827 				__btf_member_bitfield_size(t, member);
7828 
7829 			/* off <= moff instead of off == moff because clang
7830 			 * does not generate a BTF member for anonymous
7831 			 * bitfield like the ":16" here:
7832 			 * struct {
7833 			 *	int :16;
7834 			 *	int x:8;
7835 			 * };
7836 			 */
7837 			if (off <= moff &&
7838 			    BITS_ROUNDUP_BYTES(end_bit) <= off + size)
7839 				return WALK_SCALAR;
7840 
7841 			/* off may be accessing a following member
7842 			 *
7843 			 * or
7844 			 *
7845 			 * Doing partial access at either end of this
7846 			 * bitfield.  Continue on this case also to
7847 			 * treat it as not accessing this bitfield
7848 			 * and eventually error out as field not
7849 			 * found to keep it simple.
7850 			 * It could be relaxed if there was a legit
7851 			 * partial access case later.
7852 			 */
7853 			continue;
7854 		}
7855 
7856 		/* In case of "off" is pointing to holes of a struct */
7857 		if (off < moff)
7858 			break;
7859 
7860 		/* type of the field */
7861 		mid = member->type;
7862 		mtype = btf_type_by_id(btf, member->type);
7863 		mname = __btf_name_by_offset(btf, member->name_off);
7864 
7865 		mtype = __btf_resolve_size(btf, mtype, &msize,
7866 					   &elem_type, &elem_id, &total_nelems,
7867 					   &mid);
7868 		if (IS_ERR(mtype)) {
7869 			bpf_log(log, "field %s doesn't have size\n", mname);
7870 			return -EFAULT;
7871 		}
7872 
7873 		mtrue_end = moff + msize;
7874 		if (off >= mtrue_end)
7875 			/* no overlap with member, keep iterating */
7876 			continue;
7877 
7878 		if (btf_type_is_array(mtype)) {
7879 			u32 elem_idx;
7880 
7881 			/* __btf_resolve_size() above helps to
7882 			 * linearize a multi-dimensional array.
7883 			 *
7884 			 * The logic here is treating an array
7885 			 * in a struct as the following way:
7886 			 *
7887 			 * struct outer {
7888 			 *	struct inner array[2][2];
7889 			 * };
7890 			 *
7891 			 * looks like:
7892 			 *
7893 			 * struct outer {
7894 			 *	struct inner array_elem0;
7895 			 *	struct inner array_elem1;
7896 			 *	struct inner array_elem2;
7897 			 *	struct inner array_elem3;
7898 			 * };
7899 			 *
7900 			 * When accessing outer->array[1][0], it moves
7901 			 * moff to "array_elem2", set mtype to
7902 			 * "struct inner", and msize also becomes
7903 			 * sizeof(struct inner).  Then most of the
7904 			 * remaining logic will fall through without
7905 			 * caring the current member is an array or
7906 			 * not.
7907 			 *
7908 			 * Unlike mtype/msize/moff, mtrue_end does not
7909 			 * change.  The naming difference ("_true") tells
7910 			 * that it is not always corresponding to
7911 			 * the current mtype/msize/moff.
7912 			 * It is the true end of the current
7913 			 * member (i.e. array in this case).  That
7914 			 * will allow an int array to be accessed like
7915 			 * a scratch space,
7916 			 * i.e. allow access beyond the size of
7917 			 *      the array's element as long as it is
7918 			 *      within the mtrue_end boundary.
7919 			 */
7920 			if (push_array(arrays, arrays_cnt,
7921 				       (struct array_access){ mid, off - moff }))
7922 				return -E2BIG;
7923 
7924 			/* skip empty array */
7925 			if (moff == mtrue_end)
7926 				continue;
7927 
7928 			msize /= total_nelems;
7929 			elem_idx = (off - moff) / msize;
7930 			moff += elem_idx * msize;
7931 			mtype = elem_type;
7932 			mid = elem_id;
7933 		}
7934 
7935 		/* the 'off' we're looking for is either equal to start
7936 		 * of this field or inside of this struct
7937 		 */
7938 		if (btf_type_is_struct(mtype)) {
7939 			/* our field must be inside that union or struct */
7940 			t = mtype;
7941 
7942 			/* return if the offset matches the member offset */
7943 			if (off == moff) {
7944 				*next_btf_id = mid;
7945 				return WALK_STRUCT;
7946 			}
7947 
7948 			/* adjust offset we're looking for */
7949 			off -= moff;
7950 			goto again;
7951 		}
7952 
7953 		if (btf_type_is_ptr(mtype)) {
7954 			static const struct btf_type_tag_match walk_type_tags[] = {
7955 				{ "user", MEM_USER },
7956 				{ "percpu", MEM_PERCPU },
7957 				{ "rcu", MEM_RCU },
7958 			};
7959 			enum bpf_type_flag tmp_flag = 0;
7960 			struct btf_type_tag_walk_ctx ctx = { .t = mtype };
7961 			const struct btf_type *stype;
7962 			int err;
7963 			u32 id;
7964 
7965 			if (msize != size || off != moff) {
7966 				bpf_log(log,
7967 					"cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
7968 					mname, moff, tname, off, size);
7969 				return -EACCES;
7970 			}
7971 
7972 			err = btf_type_tag_walk(btf, &ctx, walk_type_tags,
7973 						ARRAY_SIZE(walk_type_tags));
7974 			if (err) {
7975 				bpf_log(log, "type '%s' has multiple type tags\n",
7976 					btf_type_str(mtype));
7977 				return err;
7978 			}
7979 			tmp_flag = ctx.res;
7980 			id = ctx.id;
7981 			stype = ctx.t;
7982 
7983 			/*
7984 			 * __nullable combines with any of the above: it only says
7985 			 * that the pointer may be NULL. The caller decides whether
7986 			 * that matters for the register type it derives.
7987 			 */
7988 			if (btf_ptr_has_type_tag(btf, mtype, "nullable"))
7989 				tmp_flag |= PTR_MAYBE_NULL;
7990 
7991 			/*
7992 			 * An __arena member of a kernel struct holds the kernel
7993 			 * address of arena memory, which the verifier turns into
7994 			 * an arena pointer on load. Program BTF is not affected:
7995 			 * there the tag is what the compiler emits for the arena
7996 			 * address space. An offset into a union resolves to its
7997 			 * first member, so a program reading another member there
7998 			 * would get an arena pointer it did not ask for; the walk
7999 			 * marked such a union untrusted.
8000 			 */
8001 			if (btf_is_kernel(btf) && btf_type_is_arena_ptr(btf, mtype)) {
8002 				if (*flag & PTR_UNTRUSTED) {
8003 					bpf_log(log,
8004 						"arena pointer member %s of %s is inside a union\n",
8005 						mname, tname);
8006 					return -EACCES;
8007 				}
8008 				*next_btf_id = id;
8009 				*flag |= tmp_flag & PTR_MAYBE_NULL;
8010 				if (field_name)
8011 					*field_name = mname;
8012 				return WALK_PTR_ARENA;
8013 			}
8014 
8015 			if (btf_type_is_struct(stype)) {
8016 				*next_btf_id = id;
8017 				*flag |= tmp_flag;
8018 				if (field_name)
8019 					*field_name = mname;
8020 				return WALK_PTR;
8021 			}
8022 
8023 			return WALK_PTR_UNTRUSTED;
8024 		}
8025 
8026 		/* Allow more flexible access within an int as long as
8027 		 * it is within mtrue_end.
8028 		 * Since mtrue_end could be the end of an array,
8029 		 * that also allows using an array of int as a scratch
8030 		 * space. e.g. skb->cb[].
8031 		 */
8032 		if (off + size > mtrue_end && !(*flag & PTR_UNTRUSTED)) {
8033 			bpf_log(log,
8034 				"access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
8035 				mname, mtrue_end, tname, off, size);
8036 			return -EACCES;
8037 		}
8038 
8039 		return WALK_SCALAR;
8040 	}
8041 	bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
8042 	return -EINVAL;
8043 }
8044 
8045 int btf_struct_access(struct bpf_verifier_log *log,
8046 		      const struct bpf_reg_state *reg,
8047 		      int _off, int size, enum bpf_access_type atype __maybe_unused,
8048 		      u32 *next_btf_id, enum bpf_type_flag *flag,
8049 		      const char **field_name)
8050 {
8051 	const struct btf *btf = reg->btf;
8052 	enum bpf_type_flag tmp_flag = 0;
8053 	struct array_access arrays[MAX_ARRAYS_WALK];
8054 	const struct btf_member *member;
8055 	const struct btf_type *t;
8056 	u32 i, arrays_cnt = 0;
8057 	u32 id = reg->btf_id;
8058 	s64 min_off, max_off, flex_off;
8059 	int err, off, ret;
8060 
8061 	if (check_add_overflow(reg_smin(reg), (s64)_off, &min_off) ||
8062 	    check_add_overflow(reg_smax(reg), (s64)_off, &max_off) ||
8063 	    min_off != (int)min_off) {
8064 		bpf_log(log,
8065 			"offset computation overflows: register offset range is [%lld, %lld], instruction offset is %d\n",
8066 			reg_smin(reg), reg_smax(reg), _off);
8067 		return -EINVAL;
8068 	}
8069 	off = min_off;
8070 
8071 	while (type_is_alloc(reg->type)) {
8072 		struct btf_struct_meta *meta;
8073 		struct btf_record *rec;
8074 		int i;
8075 
8076 		meta = btf_find_struct_meta(btf, id);
8077 		if (!meta)
8078 			break;
8079 		rec = meta->record;
8080 		for (i = 0; i < rec->cnt; i++) {
8081 			struct btf_field *field = &rec->fields[i];
8082 			u32 offset = field->offset;
8083 			if (off < offset + field->size && offset < off + size) {
8084 				bpf_log(log,
8085 					"direct access to %s is disallowed\n",
8086 					btf_field_type_name(field->type));
8087 				return -EACCES;
8088 			}
8089 		}
8090 		break;
8091 	}
8092 
8093 	t = btf_type_by_id(btf, id);
8094 	do {
8095 		err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag,
8096 				      field_name, !type_is_alloc(reg->type), arrays, &arrays_cnt);
8097 		switch (err) {
8098 		case WALK_PTR:
8099 			/* For local types, the destination register cannot
8100 			 * become a pointer again.
8101 			 */
8102 			if (type_is_alloc(reg->type)) {
8103 				ret = SCALAR_VALUE;
8104 				goto check_variable_offset;
8105 			}
8106 			/* If we found the pointer or scalar on t+off,
8107 			 * we're done.
8108 			 */
8109 			*next_btf_id = id;
8110 			*flag = tmp_flag;
8111 			ret = PTR_TO_BTF_ID;
8112 			goto check_variable_offset;
8113 		case WALK_PTR_UNTRUSTED:
8114 			*flag = MEM_RDONLY | PTR_UNTRUSTED;
8115 			ret = PTR_TO_MEM;
8116 			goto check_variable_offset;
8117 		case WALK_PTR_ARENA:
8118 			*next_btf_id = id;
8119 			*flag = tmp_flag;
8120 			ret = PTR_TO_ARENA;
8121 			goto check_variable_offset;
8122 		case WALK_SCALAR:
8123 			ret = SCALAR_VALUE;
8124 			goto check_variable_offset;
8125 		case WALK_STRUCT:
8126 			/* We found nested struct, so continue the search
8127 			 * by diving in it. At this point the offset is
8128 			 * aligned with the new type, so set it to 0.
8129 			 */
8130 			t = btf_type_by_id(btf, id);
8131 			off = 0;
8132 			break;
8133 		default:
8134 			/* It's either error or unknown return value..
8135 			 * scream and leave.
8136 			 */
8137 			if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
8138 				return -EINVAL;
8139 			return err;
8140 		}
8141 	} while (t);
8142 
8143 	return -EINVAL;
8144 
8145 check_variable_offset:
8146 	if (min_off == max_off)
8147 		return ret;
8148 
8149 	/* Find an offset at which access would go to a flexible array tail (if any). */
8150 	t = btf_type_skip_modifiers(btf, reg->btf_id, NULL);
8151 	member = find_flex_member(btf, t);
8152 	flex_off = member ? __btf_member_bit_offset(t, member) / 8 : S64_MAX;
8153 
8154 	/*
8155 	 * If this is a varying offset access, the step recorded within a register
8156 	 * should correspond to one of the arrays visited while walking.
8157 	 */
8158 	for (i = 0; i < arrays_cnt; i++) {
8159 		s64 array_start, array_end, access_end;
8160 		u32 asize, esize, elem_id;
8161 
8162 		/*
8163 		 * 'arrays' records top-level arrays only, use __btf_resolve_size()
8164 		 * to get flattened representation.
8165 		 */
8166 		t = btf_type_by_id(btf, arrays[i].id);
8167 		if (IS_ERR(__btf_resolve_size(btf, t, &asize, NULL, &elem_id, NULL, NULL)) ||
8168 		    IS_ERR(btf_resolve_size(btf, btf_type_by_id(btf, elem_id), &esize)))
8169 			continue;
8170 		/* Make sure every accessed offset lands on the same field of some element. */
8171 		if (esize == 0 || reg->step % esize != 0)
8172 			continue;
8173 
8174 		array_start = min_off - arrays[i].off;
8175 		/* An array within the flexible tail has no upper bound to exceed */
8176 		if (array_start >= flex_off && btf_type_is_array(t) &&
8177 		    btf_type_array(t)->nelems == 0)
8178 			return ret;
8179 
8180 		/* the 'size' bytes read at max_off must stay within the array */
8181 		if (check_add_overflow(array_start, (s64)asize, &array_end) ||
8182 		    check_add_overflow(max_off, (s64)size, &access_end) ||
8183 		    access_end > array_end)
8184 			continue;
8185 		return ret;
8186 	}
8187 
8188 	bpf_log(log,
8189 		"invalid variable offset access into struct %s: offsets [%lld, %lld] size %d step %d do not match any array\n",
8190 		btf_name_by_offset(btf, btf_type_by_id(btf, reg->btf_id)->name_off),
8191 		min_off, max_off, size, reg->step);
8192 	return -EINVAL;
8193 }
8194 
8195 /* Check that two BTF types, each specified as an BTF object + id, are exactly
8196  * the same. Trivial ID check is not enough due to module BTFs, because we can
8197  * end up with two different module BTFs, but IDs point to the common type in
8198  * vmlinux BTF.
8199  */
8200 bool btf_types_are_same(const struct btf *btf1, u32 id1,
8201 			const struct btf *btf2, u32 id2)
8202 {
8203 	if (id1 != id2)
8204 		return false;
8205 	if (btf1 == btf2)
8206 		return true;
8207 	return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
8208 }
8209 
8210 bool btf_struct_ids_match(struct bpf_verifier_log *log,
8211 			  const struct btf *btf, u32 id, int off,
8212 			  const struct btf *need_btf, u32 need_type_id,
8213 			  bool strict, bool walk_flex_arrays)
8214 {
8215 	const struct btf_type *type;
8216 	enum bpf_type_flag flag = 0;
8217 	int err;
8218 
8219 	/* Are we already done? */
8220 	if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
8221 		return true;
8222 	/* In case of strict type match, we do not walk struct, the top level
8223 	 * type match must succeed. When strict is true, off should have already
8224 	 * been 0.
8225 	 */
8226 	if (strict)
8227 		return false;
8228 again:
8229 	type = btf_type_by_id(btf, id);
8230 	if (!type)
8231 		return false;
8232 	err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL,
8233 			      walk_flex_arrays, NULL, NULL);
8234 	if (err != WALK_STRUCT)
8235 		return false;
8236 
8237 	/* We found nested struct object. If it matches
8238 	 * the requested ID, we're done. Otherwise let's
8239 	 * continue the search with offset 0 in the new
8240 	 * type.
8241 	 */
8242 	if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
8243 		off = 0;
8244 		goto again;
8245 	}
8246 
8247 	return true;
8248 }
8249 
8250 static int __get_type_size(struct btf *btf, u32 btf_id,
8251 			   const struct btf_type **ret_type)
8252 {
8253 	const struct btf_type *t;
8254 
8255 	*ret_type = btf_type_by_id(btf, 0);
8256 	if (!btf_id)
8257 		/* void */
8258 		return 0;
8259 	t = btf_type_by_id(btf, btf_id);
8260 	while (t && btf_type_is_modifier(t))
8261 		t = btf_type_by_id(btf, t->type);
8262 	if (!t)
8263 		return -EINVAL;
8264 	*ret_type = t;
8265 	if (btf_type_is_ptr(t))
8266 		/* kernel size of pointer. Not BPF's size of pointer*/
8267 		return sizeof(void *);
8268 	if (btf_type_is_int(t) || btf_is_any_enum(t) || btf_type_is_struct(t))
8269 		return t->size;
8270 	return -EINVAL;
8271 }
8272 
8273 static u8 __get_type_fmodel_flags(const struct btf_type *t)
8274 {
8275 	u8 flags = 0;
8276 
8277 	if (btf_type_is_signed_int(t))
8278 		flags |= BTF_FMODEL_SIGNED_ARG;
8279 
8280 	return flags;
8281 }
8282 
8283 static u8 __get_arg_fmodel_flags(const struct btf *btf,
8284 				 const struct btf_param *arg,
8285 				 const struct btf_type *t)
8286 {
8287 	u8 flags = __get_type_fmodel_flags(t);
8288 
8289 	if (btf_func_arg_align(btf, t) > sizeof(u64))
8290 		flags |= BTF_FMODEL_ALIGN16_ARG;
8291 
8292 	if (btf_param_match_suffix(btf, arg, "__arena__nullable"))
8293 		flags |= BTF_FMODEL_ARENA_ARG | BTF_FMODEL_NULLABLE_ARG;
8294 	else if (btf_param_match_suffix(btf, arg, "__arena"))
8295 		flags |= BTF_FMODEL_ARENA_ARG;
8296 	else if (btf_param_match_suffix(btf, arg, "__nullable"))
8297 		flags |= BTF_FMODEL_NULLABLE_ARG;
8298 
8299 	return flags;
8300 }
8301 
8302 int btf_distill_func_proto(struct bpf_verifier_log *log,
8303 			   struct btf *btf,
8304 			   const struct btf_type *func,
8305 			   const char *tname,
8306 			   struct btf_func_model *m)
8307 {
8308 	const struct btf_param *args;
8309 	const struct btf_type *t;
8310 	u32 i, nargs;
8311 	int ret;
8312 
8313 	if (!func) {
8314 		/* BTF function prototype doesn't match the verifier types.
8315 		 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
8316 		 */
8317 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8318 			m->arg_size[i] = 8;
8319 			m->arg_flags[i] = 0;
8320 		}
8321 		m->ret_size = 8;
8322 		m->ret_flags = 0;
8323 		m->nr_args = MAX_BPF_FUNC_REG_ARGS;
8324 		return 0;
8325 	}
8326 	args = (const struct btf_param *)(func + 1);
8327 	nargs = btf_type_vlen(func);
8328 	if (nargs > MAX_BPF_FUNC_ARGS) {
8329 		bpf_log(log,
8330 			"The function %s has %d arguments. Too many.\n",
8331 			tname, nargs);
8332 		return -EINVAL;
8333 	}
8334 	ret = __get_type_size(btf, func->type, &t);
8335 	if (ret < 0 || ret > 16) {
8336 		bpf_log(log,
8337 			"The function %s return type %s is unsupported.\n",
8338 			tname, btf_type_str(t));
8339 		return -EINVAL;
8340 	}
8341 	m->ret_size = ret;
8342 	m->ret_flags = __get_type_fmodel_flags(t);
8343 
8344 	for (i = 0; i < nargs; i++) {
8345 		if (i == nargs - 1 && args[i].type == 0) {
8346 			bpf_log(log,
8347 				"The function %s with variable args is unsupported.\n",
8348 				tname);
8349 			return -EINVAL;
8350 		}
8351 		ret = __get_type_size(btf, args[i].type, &t);
8352 
8353 		/* No support of struct argument size greater than 16 bytes */
8354 		if (ret < 0 || ret > 16) {
8355 			bpf_log(log,
8356 				"The function %s arg%d type %s is unsupported.\n",
8357 				tname, i, btf_type_str(t));
8358 			return -EINVAL;
8359 		}
8360 		if (ret == 0) {
8361 			bpf_log(log,
8362 				"The function %s has malformed void argument.\n",
8363 				tname);
8364 			return -EINVAL;
8365 		}
8366 		m->arg_size[i] = ret;
8367 		m->arg_flags[i] = __get_arg_fmodel_flags(btf, &args[i], t);
8368 	}
8369 	m->nr_args = nargs;
8370 	return 0;
8371 }
8372 
8373 /* Compare BTFs of two functions assuming only scalars and pointers to context.
8374  * t1 points to BTF_KIND_FUNC in btf1
8375  * t2 points to BTF_KIND_FUNC in btf2
8376  * Returns:
8377  * EINVAL - function prototype mismatch
8378  * EFAULT - verifier bug
8379  * 0 - 99% match. The last 1% is validated by the verifier.
8380  */
8381 static int btf_check_func_type_match(struct bpf_verifier_log *log,
8382 				     struct btf *btf1, const struct btf_type *t1,
8383 				     struct btf *btf2, const struct btf_type *t2)
8384 {
8385 	const struct btf_param *args1, *args2;
8386 	const char *fn1, *fn2, *s1, *s2;
8387 	u32 nargs1, nargs2, i;
8388 
8389 	fn1 = btf_name_by_offset(btf1, t1->name_off);
8390 	fn2 = btf_name_by_offset(btf2, t2->name_off);
8391 
8392 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
8393 		bpf_log(log, "%s() is not a global function\n", fn1);
8394 		return -EINVAL;
8395 	}
8396 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
8397 		bpf_log(log, "%s() is not a global function\n", fn2);
8398 		return -EINVAL;
8399 	}
8400 
8401 	t1 = btf_type_by_id(btf1, t1->type);
8402 	if (!t1 || !btf_type_is_func_proto(t1))
8403 		return -EFAULT;
8404 	t2 = btf_type_by_id(btf2, t2->type);
8405 	if (!t2 || !btf_type_is_func_proto(t2))
8406 		return -EFAULT;
8407 
8408 	args1 = (const struct btf_param *)(t1 + 1);
8409 	nargs1 = btf_type_vlen(t1);
8410 	args2 = (const struct btf_param *)(t2 + 1);
8411 	nargs2 = btf_type_vlen(t2);
8412 
8413 	if (nargs1 != nargs2) {
8414 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
8415 			fn1, nargs1, fn2, nargs2);
8416 		return -EINVAL;
8417 	}
8418 
8419 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
8420 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
8421 	if (t1->info != t2->info) {
8422 		bpf_log(log,
8423 			"Return type %s of %s() doesn't match type %s of %s()\n",
8424 			btf_type_str(t1), fn1,
8425 			btf_type_str(t2), fn2);
8426 		return -EINVAL;
8427 	}
8428 	if (btf_type_has_size(t1) && (t1->size > 8 || t2->size > 8)) {
8429 		bpf_log(log,
8430 			"Return type of %s() has size %u and of %s() size %u, and a size above 8 bytes cannot be replaced\n",
8431 			fn1, t1->size, fn2, t2->size);
8432 		return -EINVAL;
8433 	}
8434 
8435 	for (i = 0; i < nargs1; i++) {
8436 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
8437 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
8438 
8439 		if (t1->info != t2->info) {
8440 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
8441 				i, fn1, btf_type_str(t1),
8442 				fn2, btf_type_str(t2));
8443 			return -EINVAL;
8444 		}
8445 		if (btf_type_has_size(t1) && t1->size != t2->size) {
8446 			bpf_log(log,
8447 				"arg%d in %s() has size %d while %s() has %d\n",
8448 				i, fn1, t1->size,
8449 				fn2, t2->size);
8450 			return -EINVAL;
8451 		}
8452 
8453 		/* global functions are validated with scalars and pointers
8454 		 * to context only. And only global functions can be replaced.
8455 		 * Hence type check only those types.
8456 		 */
8457 		if (btf_type_is_int(t1) || btf_is_any_enum(t1))
8458 			continue;
8459 		if (!btf_type_is_ptr(t1)) {
8460 			bpf_log(log,
8461 				"arg%d in %s() has unrecognized type\n",
8462 				i, fn1);
8463 			return -EINVAL;
8464 		}
8465 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
8466 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
8467 		if (!btf_type_is_struct(t1)) {
8468 			bpf_log(log,
8469 				"arg%d in %s() is not a pointer to context\n",
8470 				i, fn1);
8471 			return -EINVAL;
8472 		}
8473 		if (!btf_type_is_struct(t2)) {
8474 			bpf_log(log,
8475 				"arg%d in %s() is not a pointer to context\n",
8476 				i, fn2);
8477 			return -EINVAL;
8478 		}
8479 		/* This is an optional check to make program writing easier.
8480 		 * Compare names of structs and report an error to the user.
8481 		 * btf_prepare_func_args() already checked that t2 struct
8482 		 * is a context type. btf_prepare_func_args() will check
8483 		 * later that t1 struct is a context type as well.
8484 		 */
8485 		s1 = btf_name_by_offset(btf1, t1->name_off);
8486 		s2 = btf_name_by_offset(btf2, t2->name_off);
8487 		if (strcmp(s1, s2)) {
8488 			bpf_log(log,
8489 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
8490 				i, fn1, s1, fn2, s2);
8491 			return -EINVAL;
8492 		}
8493 	}
8494 	return 0;
8495 }
8496 
8497 /* Compare BTFs of given program with BTF of target program */
8498 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
8499 			 struct btf *btf2, const struct btf_type *t2)
8500 {
8501 	struct btf *btf1 = prog->aux->btf;
8502 	const struct btf_type *t1;
8503 	u32 btf_id = 0;
8504 
8505 	if (!prog->aux->func_info) {
8506 		bpf_log(log, "Program extension requires BTF\n");
8507 		return -EINVAL;
8508 	}
8509 
8510 	btf_id = prog->aux->func_info[0].type_id;
8511 	if (!btf_id)
8512 		return -EFAULT;
8513 
8514 	t1 = btf_type_by_id(btf1, btf_id);
8515 	if (!t1 || !btf_type_is_func(t1))
8516 		return -EFAULT;
8517 
8518 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
8519 }
8520 
8521 static bool btf_is_dynptr_ptr(const struct btf *btf, const struct btf_type *t)
8522 {
8523 	const char *name;
8524 
8525 	t = btf_type_by_id(btf, t->type); /* skip PTR */
8526 
8527 	while (btf_type_is_modifier(t))
8528 		t = btf_type_by_id(btf, t->type);
8529 
8530 	/* allow either struct or struct forward declaration */
8531 	if (btf_type_is_struct(t) ||
8532 	    (btf_type_is_fwd(t) && btf_type_kflag(t) == 0)) {
8533 		name = btf_str_by_offset(btf, t->name_off);
8534 		return name && strcmp(name, "bpf_dynptr") == 0;
8535 	}
8536 
8537 	return false;
8538 }
8539 
8540 struct bpf_cand_cache {
8541 	const char *name;
8542 	u32 name_len;
8543 	u16 kind;
8544 	u16 cnt;
8545 	struct {
8546 		const struct btf *btf;
8547 		u32 id;
8548 	} cands[];
8549 };
8550 
8551 static DEFINE_MUTEX(cand_cache_mutex);
8552 
8553 static struct bpf_cand_cache *
8554 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id);
8555 
8556 static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
8557 				 const struct btf *btf, const struct btf_type *t)
8558 {
8559 	struct bpf_cand_cache *cc;
8560 	struct bpf_core_ctx ctx = {
8561 		.btf = btf,
8562 		.log = log,
8563 	};
8564 	u32 kern_type_id, type_id;
8565 	int err = 0;
8566 
8567 	/* skip PTR and modifiers */
8568 	type_id = t->type;
8569 	t = btf_type_by_id(btf, t->type);
8570 	while (btf_type_is_modifier(t)) {
8571 		type_id = t->type;
8572 		t = btf_type_by_id(btf, t->type);
8573 	}
8574 
8575 	mutex_lock(&cand_cache_mutex);
8576 	cc = bpf_core_find_cands(&ctx, type_id);
8577 	if (IS_ERR(cc)) {
8578 		err = PTR_ERR(cc);
8579 		bpf_log(log, "arg#%d reference type('%s %s') candidate matching error: %d\n",
8580 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
8581 			err);
8582 		goto cand_cache_unlock;
8583 	}
8584 	if (cc->cnt != 1) {
8585 		bpf_log(log, "arg#%d reference type('%s %s') %s\n",
8586 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
8587 			cc->cnt == 0 ? "has no matches" : "is ambiguous");
8588 		err = cc->cnt == 0 ? -ENOENT : -ESRCH;
8589 		goto cand_cache_unlock;
8590 	}
8591 	if (btf_is_module(cc->cands[0].btf)) {
8592 		bpf_log(log, "arg#%d reference type('%s %s') points to kernel module type (unsupported)\n",
8593 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
8594 		err = -EOPNOTSUPP;
8595 		goto cand_cache_unlock;
8596 	}
8597 	kern_type_id = cc->cands[0].id;
8598 
8599 cand_cache_unlock:
8600 	mutex_unlock(&cand_cache_mutex);
8601 	if (err)
8602 		return err;
8603 
8604 	return kern_type_id;
8605 }
8606 
8607 enum btf_arg_tag {
8608 	ARG_TAG_CTX	  = BIT_ULL(0),
8609 	ARG_TAG_NONNULL   = BIT_ULL(1),
8610 	ARG_TAG_TRUSTED   = BIT_ULL(2),
8611 	ARG_TAG_UNTRUSTED = BIT_ULL(3),
8612 	ARG_TAG_NULLABLE  = BIT_ULL(4),
8613 	ARG_TAG_ARENA	  = BIT_ULL(5),
8614 };
8615 
8616 static int btf_scan_decl_tags(struct bpf_verifier_env *env,
8617 			      const struct btf *btf,
8618 			      const struct btf_type *fn_t,
8619 			      u32 arg_idx, bool is_global, u32 *tags)
8620 {
8621 	int id = btf_named_start_id(btf, false) - 1;
8622 	const char tag_key[] = "arg:";
8623 	static const struct {
8624 		const char *tag_value;
8625 		enum btf_arg_tag arg_tag;
8626 	} tag_values[] = {
8627 		{ "ctx", ARG_TAG_CTX },
8628 		{ "trusted", ARG_TAG_TRUSTED },
8629 		{ "untrusted", ARG_TAG_UNTRUSTED },
8630 		{ "nonnull", ARG_TAG_NONNULL },
8631 		{ "nullable", ARG_TAG_NULLABLE },
8632 		{ "arena", ARG_TAG_ARENA },
8633 	};
8634 
8635 	/*
8636 	 * The 'arg:<tag>' decl_tag takes precedence over the derivation
8637 	 * of the register type from the BTF type itself.
8638 	 */
8639 	while ((id = btf_find_next_decl_tag(btf, fn_t, arg_idx, tag_key, id)) > 0) {
8640 		const struct btf_type *tag_t;
8641 		const char *tag;
8642 		int i;
8643 		bool found;
8644 
8645 		/* disallow arg tags in static subprogs */
8646 		if (!is_global) {
8647 			bpf_log(&env->log,
8648 				"arg#%d type tag is not supported in static functions\n",
8649 				arg_idx);
8650 			return -EOPNOTSUPP;
8651 		}
8652 
8653 		tag_t = btf_type_by_id(btf, id);
8654 		tag = __btf_name_by_offset(btf, tag_t->name_off) + (sizeof(tag_key) - 1);
8655 
8656 		found = false;
8657 		for (i = 0; i < ARRAY_SIZE(tag_values); ++i) {
8658 			if (!strcmp(tag, tag_values[i].tag_value)) {
8659 				*tags |= tag_values[i].arg_tag;
8660 				found = true;
8661 				break;
8662 			}
8663 		}
8664 
8665 		if (!found) {
8666 			bpf_log(&env->log, "arg#%d has unsupported set of tags\n", arg_idx);
8667 			return -EOPNOTSUPP;
8668 		}
8669 	}
8670 	if (id != -ENOENT) {
8671 		bpf_log(&env->log, "arg#%d type tag fetching failure: %d\n", arg_idx, id);
8672 		return id;
8673 	}
8674 
8675 	return 0;
8676 }
8677 
8678 static void btf_scan_type_tags(const struct btf *btf, u32 type_id, u32 *tags)
8679 {
8680 	/* Find the first pointer type in the chain. */
8681 	const struct btf_type *t = btf_type_skip_modifiers(btf, type_id, NULL);
8682 
8683 	if (btf_type_is_arena_ptr(btf, t))
8684 		*tags |= ARG_TAG_ARENA;
8685 }
8686 
8687 /* Check whether the type is a valid return type. */
8688 static int btf_validate_return_type(struct bpf_verifier_env *env, struct btf *btf,
8689 		const struct btf_type *t, int subprog, bool is_global)
8690 {
8691 	t = btf_type_skip_modifiers(btf, t->type, NULL);
8692 
8693 	/*
8694 	 * We allow all subprogs except for the main one to return any kind of arena pointer.
8695 	 * General arena variables are not allowed, since it makes no sense to return by value
8696 	 * a variable that's on the heap in the first place.
8697 	 */
8698 	if (subprog && btf_type_is_arena_ptr(btf, t))
8699 		return 0;
8700 
8701 	/* We always accept void or scalars. */
8702 	if (btf_type_is_void(t) || btf_type_is_int(t) || btf_is_any_enum(t))
8703 		return 0;
8704 
8705 	if (btf_type_is_struct(t) && t->size <= 16) {
8706 		/*
8707 		 * A global function's caller models the return as an opaque
8708 		 * scalar pair, so a pointer member would be laundered into a
8709 		 * scalar and escape provenance and reference tracking. Only
8710 		 * scalars and arena pointers are allowed: an arena pointer has
8711 		 * no provenance to lose, since a program may already derive one
8712 		 * from any scalar with addr_space_cast(), which confines the
8713 		 * result to the arena. The main program is the exception: it
8714 		 * returns to the kernel, which has no arena to cast the address
8715 		 * back into. A local function is verified inline, so its caller
8716 		 * receives the real register state and any member is fine.
8717 		 */
8718 		bool local_func = subprog && !is_global;
8719 		u32 member_kinds = BTF_MEMBER_SCALAR;
8720 
8721 		if (subprog)
8722 			member_kinds |= BTF_MEMBER_ARENA_PTR;
8723 
8724 		if (local_func || btf_struct_is_composed_of(env, btf, t, member_kinds))
8725 			return 0;
8726 	}
8727 
8728 	return -EOPNOTSUPP;
8729 }
8730 
8731 static int btf_check_arg_slots(struct bpf_verifier_log *log, const char *tname,
8732 			       bool is_global, u32 slot_cnt,
8733 			       struct bpf_subprog_info *sub)
8734 {
8735 	if (slot_cnt <= MAX_BPF_FUNC_REG_ARGS)
8736 		return 0;
8737 
8738 	if (is_global) {
8739 		bpf_log(log,
8740 			"global function %s() needs %d > %d argument slots, "
8741 			"stack args not supported\n",
8742 			tname, slot_cnt, MAX_BPF_FUNC_REG_ARGS);
8743 		return -EINVAL;
8744 	}
8745 	if (!bpf_jit_supports_stack_args()) {
8746 		bpf_log(log, "JIT does not support function %s() with %d argument slots\n",
8747 			tname, slot_cnt);
8748 		return -EFAULT;
8749 	}
8750 	sub->stack_arg_cnt = slot_cnt - MAX_BPF_FUNC_REG_ARGS;
8751 	return 0;
8752 }
8753 
8754 /* Process BTF of a function to produce high-level expectation of function
8755  * arguments (like ARG_PTR_TO_CTX, or ARG_PTR_TO_MEM, etc). This information
8756  * is cached in subprog info for reuse.
8757  * Returns:
8758  * EFAULT - there is a verifier bug. Abort verification.
8759  * EINVAL - cannot convert BTF.
8760  * 0 - Successfully processed BTF and constructed argument expectations.
8761  */
8762 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
8763 {
8764 	bool is_global = subprog_aux(env, subprog)->linkage == BTF_FUNC_GLOBAL;
8765 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
8766 	struct bpf_verifier_log *log = &env->log;
8767 	struct bpf_prog *prog = env->prog;
8768 	enum bpf_prog_type prog_type = prog->type;
8769 	struct btf *btf = prog->aux->btf;
8770 	const struct btf_param *args;
8771 	const struct btf_type *t, *ref_t, *fn_t;
8772 	int err;
8773 	u32 i, slots_used, nargs, btf_id;
8774 	const char *tname;
8775 
8776 	if (sub->args_cached)
8777 		return 0;
8778 
8779 	if (!prog->aux->func_info) {
8780 		verifier_bug(env, "func_info undefined");
8781 		return -EFAULT;
8782 	}
8783 
8784 	btf_id = prog->aux->func_info[subprog].type_id;
8785 	if (!btf_id) {
8786 		if (!is_global) /* not fatal for static funcs */
8787 			return -EINVAL;
8788 		bpf_log(log, "Global functions need valid BTF\n");
8789 		return -EFAULT;
8790 	}
8791 
8792 	fn_t = btf_type_by_id(btf, btf_id);
8793 	if (!fn_t || !btf_type_is_func(fn_t)) {
8794 		/* These checks were already done by the verifier while loading
8795 		 * struct bpf_func_info
8796 		 */
8797 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
8798 			subprog);
8799 		return -EFAULT;
8800 	}
8801 	tname = btf_name_by_offset(btf, fn_t->name_off);
8802 
8803 	if (prog->aux->func_info_aux[subprog].unreliable) {
8804 		verifier_bug(env, "unreliable BTF for function %s()", tname);
8805 		return -EFAULT;
8806 	}
8807 	if (prog_type == BPF_PROG_TYPE_EXT)
8808 		prog_type = prog->aux->dst_prog->type;
8809 
8810 	t = btf_type_by_id(btf, fn_t->type);
8811 	if (!t || !btf_type_is_func_proto(t)) {
8812 		bpf_log(log, "Invalid type of function %s()\n", tname);
8813 		return -EFAULT;
8814 	}
8815 	args = (const struct btf_param *)(t + 1);
8816 	nargs = btf_type_vlen(t);
8817 	sub->arg_slot_cnt = nargs;
8818 	if (nargs > MAX_BPF_FUNC_ARGS) {
8819 		bpf_log(log, "kernel supports at most %d parameters, function %s has %d\n",
8820 			MAX_BPF_FUNC_ARGS, tname, nargs);
8821 		return -EFAULT;
8822 	}
8823 	err = btf_check_arg_slots(log, tname, is_global, nargs, sub);
8824 	if (err)
8825 		return err;
8826 
8827 	err = btf_validate_return_type(env, btf, t, subprog, is_global);
8828 	if (err) {
8829 		if (is_global) {
8830 			/* Only a subprogram may return arena pointers. */
8831 			const char *supported = subprog ?
8832 				"void, scalar, arena pointer, or a struct/union of "
8833 				"scalars and arena pointers" :
8834 				"void, scalar, or a scalar-only struct/union";
8835 
8836 			bpf_log(log,
8837 				"Global function %s() has unsupported return type. "
8838 				"Only %s up to 16 bytes is supported.\n",
8839 				tname, supported);
8840 		}
8841 		return err;
8842 	}
8843 
8844 	/* Convert BTF function arguments into verifier types.
8845 	 * Only PTR_TO_CTX and SCALAR are supported atm.
8846 	 */
8847 	for (i = 0, slots_used = 0; i < nargs; i++) {
8848 		u32 tags = 0;
8849 
8850 		if (slots_used >= MAX_BPF_FUNC_ARGS)
8851 			goto too_many_slots;
8852 
8853 		err = btf_scan_decl_tags(env, btf, fn_t, i, is_global, &tags);
8854 		if (err)
8855 			return err;
8856 
8857 		btf_scan_type_tags(btf, args[i].type, &tags);
8858 
8859 		t = btf_type_by_id(btf, args[i].type);
8860 		while (btf_type_is_modifier(t))
8861 			t = btf_type_by_id(btf, t->type);
8862 		if (!btf_type_is_ptr(t))
8863 			goto skip_pointer;
8864 
8865 		if ((tags & ARG_TAG_CTX) || btf_is_prog_ctx_type(log, btf, t, prog_type, i)) {
8866 			if (tags & ~ARG_TAG_CTX) {
8867 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
8868 				return -EINVAL;
8869 			}
8870 			if ((tags & ARG_TAG_CTX) &&
8871 			    btf_validate_prog_ctx_type(log, btf, t, i, prog_type,
8872 						       prog->expected_attach_type))
8873 				return -EINVAL;
8874 			sub->args[slots_used++].arg_type = ARG_PTR_TO_CTX;
8875 			continue;
8876 		}
8877 		if (btf_is_dynptr_ptr(btf, t)) {
8878 			if (tags) {
8879 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
8880 				return -EINVAL;
8881 			}
8882 			sub->args[slots_used++].arg_type = ARG_PTR_TO_DYNPTR;
8883 			continue;
8884 		}
8885 		if (tags & ARG_TAG_TRUSTED) {
8886 			int kern_type_id;
8887 
8888 			if (tags & ARG_TAG_NONNULL) {
8889 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
8890 				return -EINVAL;
8891 			}
8892 
8893 			kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
8894 			if (kern_type_id < 0)
8895 				return kern_type_id;
8896 
8897 			sub->args[slots_used].arg_type = ARG_PTR_TO_BTF_ID | PTR_TRUSTED;
8898 			if (tags & ARG_TAG_NULLABLE)
8899 				sub->args[slots_used].arg_type |= PTR_MAYBE_NULL;
8900 			sub->args[slots_used].btf_id = kern_type_id;
8901 			slots_used++;
8902 			continue;
8903 		}
8904 		if (tags & ARG_TAG_UNTRUSTED) {
8905 			struct btf *vmlinux_btf;
8906 			int kern_type_id;
8907 
8908 			if (tags & ~ARG_TAG_UNTRUSTED) {
8909 				bpf_log(log, "arg#%d untrusted cannot be combined with any other tags\n", i);
8910 				return -EINVAL;
8911 			}
8912 
8913 			ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
8914 			if (btf_type_is_void(ref_t) || btf_type_is_primitive(ref_t)) {
8915 				sub->args[slots_used].arg_type = ARG_PTR_TO_MEM | MEM_RDONLY |
8916 								 PTR_UNTRUSTED;
8917 				sub->args[slots_used].mem_size = 0;
8918 				slots_used++;
8919 				continue;
8920 			}
8921 
8922 			kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
8923 			if (kern_type_id < 0)
8924 				return kern_type_id;
8925 
8926 			vmlinux_btf = bpf_get_btf_vmlinux();
8927 			ref_t = btf_type_by_id(vmlinux_btf, kern_type_id);
8928 			if (!btf_type_is_struct(ref_t)) {
8929 				tname = __btf_name_by_offset(vmlinux_btf, t->name_off);
8930 				bpf_log(log, "arg#%d has type %s '%s', but only struct or primitive types are allowed\n",
8931 					i, btf_type_str(ref_t), tname);
8932 				return -EINVAL;
8933 			}
8934 			sub->args[slots_used].arg_type = ARG_PTR_TO_BTF_ID | PTR_UNTRUSTED;
8935 			sub->args[slots_used].btf_id = kern_type_id;
8936 			slots_used++;
8937 			continue;
8938 		}
8939 		if (tags & ARG_TAG_ARENA) {
8940 			if (tags & ~ARG_TAG_ARENA) {
8941 				bpf_log(log, "arg#%d arena cannot be combined with any other tags\n", i);
8942 				return -EINVAL;
8943 			}
8944 			sub->args[slots_used++].arg_type = ARG_PTR_TO_ARENA;
8945 			continue;
8946 		}
8947 		if (is_global) { /* generic user data pointer */
8948 			u32 mem_size;
8949 
8950 			if (tags & ARG_TAG_NULLABLE) {
8951 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
8952 				return -EINVAL;
8953 			}
8954 
8955 			t = btf_type_skip_modifiers(btf, t->type, NULL);
8956 			ref_t = btf_resolve_size(btf, t, &mem_size);
8957 			if (IS_ERR(ref_t)) {
8958 				bpf_log(log, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
8959 					i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
8960 					PTR_ERR(ref_t));
8961 				return -EINVAL;
8962 			}
8963 
8964 			sub->args[slots_used].arg_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL;
8965 			if (tags & ARG_TAG_NONNULL)
8966 				sub->args[slots_used].arg_type &= ~PTR_MAYBE_NULL;
8967 			sub->args[slots_used].mem_size = mem_size;
8968 			slots_used++;
8969 			continue;
8970 		}
8971 
8972 skip_pointer:
8973 		if (tags) {
8974 			bpf_log(log, "arg#%d has pointer tag, but is not a pointer type\n", i);
8975 			return -EINVAL;
8976 		}
8977 		if (btf_type_is_int(t) || btf_is_any_enum(t) || btf_type_is_struct(t)) {
8978 			u32 nslots;
8979 
8980 			if (!t->size || t->size > 2 * BPF_REG_SIZE) {
8981 				if (!is_global)
8982 					return -EINVAL;
8983 				bpf_log(log,
8984 					"Arg#%d type %s in %s() has size %u, only 1 to %d bytes "
8985 					"can be passed by value\n",
8986 					i, btf_type_str(t), tname, t->size, 2 * BPF_REG_SIZE);
8987 				return -EINVAL;
8988 			}
8989 			if (btf_type_is_struct(t) &&
8990 			    !btf_struct_is_composed_of(env, btf, t, BTF_MEMBER_SCALAR)) {
8991 				if (!is_global)
8992 					return -EINVAL;
8993 				bpf_log(log, "Arg#%d type %s in %s() is not composed of scalars\n",
8994 					i, btf_type_str(t), tname);
8995 				return -EINVAL;
8996 			}
8997 
8998 			nslots = (t->size + BPF_REG_SIZE - 1) / BPF_REG_SIZE;
8999 			if (slots_used + nslots > MAX_BPF_FUNC_ARGS)
9000 				goto too_many_slots;
9001 			while (nslots--)
9002 				sub->args[slots_used++].arg_type = ARG_SCALAR;
9003 			continue;
9004 		}
9005 		if (!is_global)
9006 			return -EINVAL;
9007 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
9008 			i, btf_type_str(t), tname);
9009 		return -EINVAL;
9010 	}
9011 
9012 	err = btf_check_arg_slots(log, tname, is_global, slots_used, sub);
9013 	if (err)
9014 		return err;
9015 	sub->arg_slot_cnt = slots_used;
9016 
9017 	sub->args_cached = true;
9018 
9019 	return 0;
9020 
9021 too_many_slots:
9022 	if (!is_global)
9023 		return -EINVAL;
9024 	bpf_log(log, "Arguments of %s() need more than %d argument slots\n",
9025 		tname, MAX_BPF_FUNC_ARGS);
9026 	return -EINVAL;
9027 }
9028 
9029 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
9030 			  struct btf_show *show)
9031 {
9032 	const struct btf_type *t = btf_type_by_id(btf, type_id);
9033 
9034 	show->btf = btf;
9035 	memset(&show->state, 0, sizeof(show->state));
9036 	memset(&show->obj, 0, sizeof(show->obj));
9037 
9038 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
9039 }
9040 
9041 __printf(2, 0) static void btf_seq_show(struct btf_show *show, const char *fmt,
9042 					va_list args)
9043 {
9044 	seq_vprintf((struct seq_file *)show->target, fmt, args);
9045 }
9046 
9047 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
9048 			    void *obj, struct seq_file *m, u64 flags)
9049 {
9050 	struct btf_show sseq;
9051 
9052 	sseq.target = m;
9053 	sseq.showfn = btf_seq_show;
9054 	sseq.flags = flags;
9055 
9056 	btf_type_show(btf, type_id, obj, &sseq);
9057 
9058 	return sseq.state.status;
9059 }
9060 
9061 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
9062 		       struct seq_file *m)
9063 {
9064 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
9065 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
9066 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
9067 }
9068 
9069 struct btf_show_snprintf {
9070 	struct btf_show show;
9071 	int len_left;		/* space left in string */
9072 	int len;		/* length we would have written */
9073 };
9074 
9075 __printf(2, 0) static void btf_snprintf_show(struct btf_show *show, const char *fmt,
9076 					     va_list args)
9077 {
9078 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
9079 	int len;
9080 
9081 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
9082 
9083 	if (len < 0) {
9084 		ssnprintf->len_left = 0;
9085 		ssnprintf->len = len;
9086 	} else if (len >= ssnprintf->len_left) {
9087 		/* no space, drive on to get length we would have written */
9088 		ssnprintf->len_left = 0;
9089 		ssnprintf->len += len;
9090 	} else {
9091 		ssnprintf->len_left -= len;
9092 		ssnprintf->len += len;
9093 		show->target += len;
9094 	}
9095 }
9096 
9097 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
9098 			   char *buf, int len, u64 flags)
9099 {
9100 	struct btf_show_snprintf ssnprintf;
9101 
9102 	ssnprintf.show.target = buf;
9103 	ssnprintf.show.flags = flags;
9104 	ssnprintf.show.showfn = btf_snprintf_show;
9105 	ssnprintf.len_left = len;
9106 	ssnprintf.len = 0;
9107 
9108 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
9109 
9110 	/* If we encountered an error, return it. */
9111 	if (ssnprintf.show.state.status)
9112 		return ssnprintf.show.state.status;
9113 
9114 	/* Otherwise return length we would have written */
9115 	return ssnprintf.len;
9116 }
9117 
9118 int btf_type_name_to_buf(const struct btf *btf, u32 type_id, char *buf, int len)
9119 {
9120 	struct btf_show show = {
9121 		.btf = btf,
9122 		.state.type_id = type_id,
9123 	};
9124 
9125 	return snprintf(buf, len, "%s", btf_show_name(&show));
9126 }
9127 
9128 #ifdef CONFIG_PROC_FS
9129 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
9130 {
9131 	const struct btf *btf = filp->private_data;
9132 
9133 	seq_printf(m, "btf_id:\t%u\n", READ_ONCE(btf->id));
9134 }
9135 #endif
9136 
9137 static int btf_release(struct inode *inode, struct file *filp)
9138 {
9139 	btf_put(filp->private_data);
9140 	return 0;
9141 }
9142 
9143 const struct file_operations btf_fops = {
9144 #ifdef CONFIG_PROC_FS
9145 	.show_fdinfo	= bpf_btf_show_fdinfo,
9146 #endif
9147 	.release	= btf_release,
9148 };
9149 
9150 static int __btf_new_fd(struct btf *btf)
9151 {
9152 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
9153 }
9154 
9155 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)
9156 {
9157 	struct btf *btf;
9158 	int ret;
9159 
9160 	btf = btf_parse(attr, uattr, attr_log);
9161 	if (IS_ERR(btf))
9162 		return PTR_ERR(btf);
9163 
9164 	ret = btf_alloc_id(btf);
9165 	if (ret) {
9166 		btf_free(btf);
9167 		return ret;
9168 	}
9169 
9170 	/*
9171 	 * The BTF ID is published to the userspace.
9172 	 * All BTF free must go through call_rcu() from
9173 	 * now on (i.e. free by calling btf_put()).
9174 	 */
9175 
9176 	ret = __btf_new_fd(btf);
9177 	if (ret < 0)
9178 		btf_put(btf);
9179 
9180 	return ret;
9181 }
9182 
9183 struct btf *btf_get_by_fd(int fd)
9184 {
9185 	struct btf *btf;
9186 	CLASS(fd, f)(fd);
9187 
9188 	btf = __btf_get_by_fd(f);
9189 	if (!IS_ERR(btf))
9190 		refcount_inc(&btf->refcnt);
9191 
9192 	return btf;
9193 }
9194 
9195 int btf_get_info_by_fd(const struct btf *btf,
9196 		       const union bpf_attr *attr,
9197 		       union bpf_attr __user *uattr)
9198 {
9199 	struct bpf_btf_info __user *uinfo;
9200 	struct bpf_btf_info info;
9201 	u32 info_copy, btf_copy;
9202 	void __user *ubtf;
9203 	char __user *uname;
9204 	u32 uinfo_len, uname_len, name_len;
9205 	int ret = 0;
9206 
9207 	uinfo = u64_to_user_ptr(attr->info.info);
9208 	uinfo_len = attr->info.info_len;
9209 
9210 	info_copy = min_t(u32, uinfo_len, sizeof(info));
9211 	memset(&info, 0, sizeof(info));
9212 	if (copy_from_user(&info, uinfo, info_copy))
9213 		return -EFAULT;
9214 
9215 	info.id = READ_ONCE(btf->id);
9216 	ubtf = u64_to_user_ptr(info.btf);
9217 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
9218 	if (copy_to_user(ubtf, btf->data, btf_copy))
9219 		return -EFAULT;
9220 	info.btf_size = btf->data_size;
9221 
9222 	info.kernel_btf = btf->kernel_btf;
9223 
9224 	uname = u64_to_user_ptr(info.name);
9225 	uname_len = info.name_len;
9226 	if (!uname ^ !uname_len)
9227 		return -EINVAL;
9228 
9229 	name_len = strlen(btf->name);
9230 	info.name_len = name_len;
9231 
9232 	if (uname) {
9233 		if (uname_len >= name_len + 1) {
9234 			if (copy_to_user(uname, btf->name, name_len + 1))
9235 				return -EFAULT;
9236 		} else {
9237 			char zero = '\0';
9238 
9239 			if (copy_to_user(uname, btf->name, uname_len - 1))
9240 				return -EFAULT;
9241 			if (put_user(zero, uname + uname_len - 1))
9242 				return -EFAULT;
9243 			/* let user-space know about too short buffer */
9244 			ret = -ENOSPC;
9245 		}
9246 	}
9247 
9248 	if (copy_to_user(uinfo, &info, info_copy) ||
9249 	    put_user(info_copy, &uattr->info.info_len))
9250 		return -EFAULT;
9251 
9252 	return ret;
9253 }
9254 
9255 int btf_get_fd_by_id(u32 id)
9256 {
9257 	struct btf *btf;
9258 	int fd;
9259 
9260 	rcu_read_lock();
9261 	btf = idr_find(&btf_idr, id);
9262 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
9263 		btf = ERR_PTR(-ENOENT);
9264 	rcu_read_unlock();
9265 
9266 	if (IS_ERR(btf))
9267 		return PTR_ERR(btf);
9268 
9269 	fd = __btf_new_fd(btf);
9270 	if (fd < 0)
9271 		btf_put(btf);
9272 
9273 	return fd;
9274 }
9275 
9276 u32 btf_obj_id(const struct btf *btf)
9277 {
9278 	return READ_ONCE(btf->id);
9279 }
9280 
9281 bool btf_is_kernel(const struct btf *btf)
9282 {
9283 	return btf->kernel_btf;
9284 }
9285 
9286 bool btf_is_module(const struct btf *btf)
9287 {
9288 	return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
9289 }
9290 
9291 enum {
9292 	BTF_MODULE_F_LIVE = (1 << 0),
9293 };
9294 
9295 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9296 struct btf_module {
9297 	struct list_head list;
9298 	struct module *module;
9299 	struct btf *btf;
9300 	struct bin_attribute *sysfs_attr;
9301 	struct bin_attribute *sysfs_inline_attr;
9302 	void *btf_inline_data;
9303 	int flags;
9304 };
9305 
9306 static LIST_HEAD(btf_modules);
9307 static DEFINE_MUTEX(btf_module_mutex);
9308 
9309 static void purge_cand_cache(struct btf *btf);
9310 
9311 #if IS_MODULE(CONFIG_DEBUG_INFO_BTF_INLINE)
9312 extern char __start_BTF_inline_link[];
9313 extern char __stop_BTF_inline_link[];
9314 
9315 static struct bin_attribute *vmlinux_inline_attr;
9316 static const struct btf_link *vmlinux_inline_link;
9317 
9318 static const struct btf_link *btf_parse_link(void *start, unsigned int size)
9319 {
9320 	const struct btf_link *link = start;
9321 	unsigned int module_name_len;
9322 
9323 	if (!link || size != sizeof(*link) || link->btf_size == 0)
9324 		return NULL;
9325 
9326 	module_name_len = strnlen(link->module_name, sizeof(link->module_name));
9327 	if (!module_name_len || module_name_len == sizeof(link->module_name) ||
9328 	    memchr_inv(link->module_name + module_name_len + 1, 0,
9329 		       sizeof(link->module_name) - module_name_len - 1))
9330 		return NULL;
9331 	return link;
9332 }
9333 
9334 static bool btf_verify_link(const struct btf_link *link, const struct module *mod,
9335 			    const void *data, size_t data_size)
9336 {
9337 	u8 actual_digest[BTF_LINK_SHA256_LEN];
9338 
9339 	if (!link || data_size != link->btf_size) {
9340 		pr_warn(" BTF link from module [%s] missing or has unexpected size\n", mod->name);
9341 		return false;
9342 	}
9343 	sha256(data, data_size, actual_digest);
9344 	if (memcmp(actual_digest, link->sha256, sizeof(actual_digest))) {
9345 		pr_warn("BTF link from module [%s] has unexpected digest\n", mod->name);
9346 		return false;
9347 	}
9348 
9349 	return true;
9350 }
9351 
9352 static void btf_vmlinux_inline_lazy_init(void)
9353 {
9354 	vmlinux_inline_link = btf_parse_link(__start_BTF_inline_link,
9355 					     __stop_BTF_inline_link -
9356 					     __start_BTF_inline_link);
9357 	if (!vmlinux_inline_link) {
9358 		pr_warn("invalid vmlinux inline BTF link\n");
9359 		return;
9360 	}
9361 	vmlinux_inline_attr = sysfs_btf_add("vmlinux.inline", NULL,
9362 					    vmlinux_inline_link->btf_size, true,
9363 					    vmlinux_inline_link->module_name);
9364 	if (IS_ERR(vmlinux_inline_attr)) {
9365 		pr_warn("failed to register vmlinux inline BTF in sysfs: %ld\n",
9366 			PTR_ERR(vmlinux_inline_attr));
9367 		vmlinux_inline_attr = NULL;
9368 	}
9369 }
9370 
9371 static bool btf_module_is_vmlinux_inline(const struct module *mod)
9372 {
9373 	return vmlinux_inline_link && !strcmp(mod->name, vmlinux_inline_link->module_name);
9374 }
9375 
9376 static int btf_module_handle_vmlinux_inline(const struct module *mod)
9377 {
9378 	void *data;
9379 
9380 	if (!mod->btf_inline_data ||
9381 	    mod->btf_inline_data_size != vmlinux_inline_link->btf_size)
9382 		return -EINVAL;
9383 
9384 	data = vmalloc_user(mod->btf_inline_data_size);
9385 	if (!data)
9386 		return -ENOMEM;
9387 	memcpy(data, mod->btf_inline_data, mod->btf_inline_data_size);
9388 
9389 	if (!btf_verify_link(vmlinux_inline_link, mod, data, mod->btf_inline_data_size) ||
9390 	    !sysfs_btf_update(vmlinux_inline_attr, data)) {
9391 		kvfree(data);
9392 		return -EINVAL;
9393 	}
9394 	return 0;
9395 }
9396 
9397 #else
9398 
9399 static bool btf_module_is_vmlinux_inline(const struct module *mod)
9400 {
9401 	return false;
9402 }
9403 
9404 static int btf_module_handle_vmlinux_inline(const struct module *mod)
9405 {
9406 	return 0;
9407 }
9408 
9409 static void btf_vmlinux_inline_lazy_init(void)
9410 {
9411 }
9412 
9413 #endif /* IS_MODULE(CONFIG_DEBUG_INFO_BTF_INLINE) */
9414 
9415 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
9416 			     void *module)
9417 {
9418 	struct btf_module *btf_mod, *tmp;
9419 	struct module *mod = module;
9420 	struct bin_attribute *attr;
9421 	struct btf *btf;
9422 	void *inline_data = NULL, *relocated_inline_data = NULL;
9423 	unsigned int inline_data_size = 0;
9424 	int err = 0;
9425 
9426 	if (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
9427 	    op != MODULE_STATE_GOING)
9428 		goto out;
9429 
9430 	switch (op) {
9431 	case MODULE_STATE_COMING:
9432 		if (btf_module_is_vmlinux_inline(mod)) {
9433 			err = btf_module_handle_vmlinux_inline(mod);
9434 			break;
9435 		}
9436 
9437 #if IS_ENABLED(CONFIG_DEBUG_INFO_BTF_INLINE)
9438 		if (mod->btf_inline_data_size) {
9439 			inline_data = mod->btf_inline_data;
9440 			inline_data_size = mod->btf_inline_data_size;
9441 		}
9442 #endif
9443 		if (!mod->btf_data_size)
9444 			break;
9445 		btf_mod = kzalloc_obj(*btf_mod);
9446 		if (!btf_mod) {
9447 			err = -ENOMEM;
9448 			goto out;
9449 		}
9450 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size,
9451 				       mod->btf_base_data, mod->btf_base_data_size,
9452 				       inline_data, inline_data_size,
9453 				       &relocated_inline_data);
9454 		if (IS_ERR(btf)) {
9455 			kfree(btf_mod);
9456 			if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
9457 				pr_warn("failed to validate module [%s] BTF: %ld\n",
9458 					mod->name, PTR_ERR(btf));
9459 				err = PTR_ERR(btf);
9460 			} else {
9461 				pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
9462 			}
9463 			goto out;
9464 		}
9465 		err = btf_alloc_id(btf);
9466 		if (err) {
9467 			btf_free(btf);
9468 			kvfree(relocated_inline_data);
9469 			kfree(btf_mod);
9470 			goto out;
9471 		}
9472 
9473 		purge_cand_cache(NULL);
9474 		mutex_lock(&btf_module_mutex);
9475 		btf_mod->module = module;
9476 		btf_mod->btf = btf;
9477 		btf_mod->btf_inline_data = relocated_inline_data;
9478 		list_add(&btf_mod->list, &btf_modules);
9479 		mutex_unlock(&btf_module_mutex);
9480 
9481 		attr = sysfs_btf_add(btf->name, btf->data, btf->data_size, false, NULL);
9482 		if (IS_ERR(attr)) {
9483 			err = 0;
9484 			goto out;
9485 		}
9486 		btf_mod->sysfs_attr = attr;
9487 
9488 		if (relocated_inline_data) {
9489 			char name[MODULE_NAME_LEN + sizeof(".inline")];
9490 
9491 			snprintf(name, sizeof(name), "%s.inline", mod->name);
9492 			attr = sysfs_btf_add(name, relocated_inline_data,
9493 					     inline_data_size, false, NULL);
9494 			if (IS_ERR(attr)) {
9495 				kvfree(relocated_inline_data);
9496 				btf_mod->btf_inline_data = NULL;
9497 				err = 0;
9498 				break;
9499 			}
9500 			btf_mod->sysfs_inline_attr = attr;
9501 		}
9502 		break;
9503 	case MODULE_STATE_LIVE:
9504 		if (!mod->btf_data_size)
9505 			break;
9506 		mutex_lock(&btf_module_mutex);
9507 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9508 			if (btf_mod->module != module)
9509 				continue;
9510 
9511 			btf_mod->flags |= BTF_MODULE_F_LIVE;
9512 			break;
9513 		}
9514 		mutex_unlock(&btf_module_mutex);
9515 		break;
9516 	case MODULE_STATE_GOING:
9517 		if (!mod->btf_data_size)
9518 			break;
9519 		mutex_lock(&btf_module_mutex);
9520 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9521 			if (btf_mod->module != module)
9522 				continue;
9523 
9524 			/*
9525 			 * For modules, we do the freeing of BTF IDR as soon as
9526 			 * module goes away to disable BTF discovery, since the
9527 			 * btf_try_get_module() on such BTFs will fail. This may
9528 			 * be called again on btf_put(), but it's ok to do so.
9529 			 */
9530 			btf_free_id(btf_mod->btf);
9531 			list_del(&btf_mod->list);
9532 			if (btf_mod->sysfs_attr)
9533 				sysfs_btf_remove(btf_mod->sysfs_attr);
9534 			if (btf_mod->sysfs_inline_attr)
9535 				sysfs_btf_remove(btf_mod->sysfs_inline_attr);
9536 			kvfree(btf_mod->btf_inline_data);
9537 			purge_cand_cache(btf_mod->btf);
9538 			btf_put(btf_mod->btf);
9539 			kfree(btf_mod);
9540 			break;
9541 		}
9542 		mutex_unlock(&btf_module_mutex);
9543 		break;
9544 	}
9545 out:
9546 	return notifier_from_errno(err);
9547 }
9548 
9549 static struct notifier_block btf_module_nb = {
9550 	.notifier_call = btf_module_notify,
9551 };
9552 
9553 static int __init btf_module_init(void)
9554 {
9555 	btf_vmlinux_inline_lazy_init();
9556 	register_module_notifier(&btf_module_nb);
9557 	return 0;
9558 }
9559 
9560 fs_initcall(btf_module_init);
9561 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
9562 
9563 struct module *btf_try_get_module(const struct btf *btf)
9564 {
9565 	struct module *res = NULL;
9566 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9567 	struct btf_module *btf_mod, *tmp;
9568 
9569 	mutex_lock(&btf_module_mutex);
9570 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9571 		if (btf_mod->btf != btf)
9572 			continue;
9573 
9574 		/* We must only consider module whose __init routine has
9575 		 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
9576 		 * which is set from the notifier callback for
9577 		 * MODULE_STATE_LIVE.
9578 		 */
9579 		if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
9580 			res = btf_mod->module;
9581 
9582 		break;
9583 	}
9584 	mutex_unlock(&btf_module_mutex);
9585 #endif
9586 
9587 	return res;
9588 }
9589 
9590 /* Returns struct btf corresponding to the struct module.
9591  * This function can return NULL or ERR_PTR.
9592  */
9593 struct btf *btf_get_module_btf(const struct module *module)
9594 {
9595 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9596 	struct btf_module *btf_mod, *tmp;
9597 #endif
9598 	struct btf *btf = NULL;
9599 
9600 	if (!module) {
9601 		btf = bpf_get_btf_vmlinux();
9602 		if (!IS_ERR_OR_NULL(btf))
9603 			btf_get(btf);
9604 		return btf;
9605 	}
9606 
9607 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9608 	mutex_lock(&btf_module_mutex);
9609 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9610 		if (btf_mod->module != module)
9611 			continue;
9612 
9613 		btf_get(btf_mod->btf);
9614 		btf = btf_mod->btf;
9615 		break;
9616 	}
9617 	mutex_unlock(&btf_module_mutex);
9618 #endif
9619 
9620 	return btf;
9621 }
9622 
9623 static int check_btf_kconfigs(const struct module *module, const char *feature)
9624 {
9625 	if (!module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
9626 		pr_err("missing vmlinux BTF, cannot register %s\n", feature);
9627 		return -ENOENT;
9628 	}
9629 	if (module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
9630 		pr_warn("missing module BTF, cannot register %s\n", feature);
9631 	return 0;
9632 }
9633 
9634 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
9635 {
9636 	struct btf *btf = NULL;
9637 	int btf_obj_fd = 0;
9638 	long ret;
9639 
9640 	if (flags)
9641 		return -EINVAL;
9642 
9643 	if (name_sz <= 1 || name[name_sz - 1])
9644 		return -EINVAL;
9645 
9646 	ret = bpf_find_btf_id(name, kind, &btf);
9647 	if (ret > 0 && btf_is_module(btf)) {
9648 		btf_obj_fd = __btf_new_fd(btf);
9649 		if (btf_obj_fd < 0) {
9650 			btf_put(btf);
9651 			return btf_obj_fd;
9652 		}
9653 		return ret | (((u64)btf_obj_fd) << 32);
9654 	}
9655 	if (ret > 0)
9656 		btf_put(btf);
9657 	return ret;
9658 }
9659 
9660 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
9661 	.func		= bpf_btf_find_by_name_kind,
9662 	.gpl_only	= false,
9663 	.might_sleep	= true,
9664 	.ret_type	= RET_INTEGER,
9665 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
9666 	.arg2_type	= ARG_MEM_SIZE,
9667 	.arg3_type	= ARG_ANYTHING,
9668 	.arg4_type	= ARG_ANYTHING,
9669 };
9670 
9671 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
9672 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
9673 BTF_TRACING_TYPE_xxx
9674 #undef BTF_TRACING_TYPE
9675 
9676 /* Validate well-formedness of iter argument type.
9677  * On success, return positive BTF ID of iter state's STRUCT type.
9678  * On error, negative error is returned.
9679  */
9680 int btf_check_iter_arg(struct btf *btf, const struct btf_type *func, int arg_idx)
9681 {
9682 	const struct btf_param *arg;
9683 	const struct btf_type *t;
9684 	const char *name;
9685 	int btf_id;
9686 
9687 	if (btf_type_vlen(func) <= arg_idx)
9688 		return -EINVAL;
9689 
9690 	arg = &btf_params(func)[arg_idx];
9691 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9692 	if (!t || !btf_type_is_ptr(t))
9693 		return -EINVAL;
9694 	t = btf_type_skip_modifiers(btf, t->type, &btf_id);
9695 	if (!t || !__btf_type_is_struct(t))
9696 		return -EINVAL;
9697 
9698 	name = btf_name_by_offset(btf, t->name_off);
9699 	if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
9700 		return -EINVAL;
9701 
9702 	return btf_id;
9703 }
9704 
9705 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
9706 				 const struct btf_type *func, u32 func_flags)
9707 {
9708 	u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
9709 	const char *sfx, *iter_name;
9710 	const struct btf_type *t;
9711 	char exp_name[128];
9712 	u32 nr_args;
9713 	int btf_id;
9714 
9715 	/* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
9716 	if (!flags || (flags & (flags - 1)))
9717 		return -EINVAL;
9718 
9719 	/* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
9720 	nr_args = btf_type_vlen(func);
9721 	if (nr_args < 1)
9722 		return -EINVAL;
9723 
9724 	btf_id = btf_check_iter_arg(btf, func, 0);
9725 	if (btf_id < 0)
9726 		return btf_id;
9727 
9728 	/* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
9729 	 * fit nicely in stack slots
9730 	 */
9731 	t = btf_type_by_id(btf, btf_id);
9732 	if (t->size == 0 || (t->size % 8))
9733 		return -EINVAL;
9734 
9735 	/* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
9736 	 * naming pattern
9737 	 */
9738 	iter_name = btf_name_by_offset(btf, t->name_off) + sizeof(ITER_PREFIX) - 1;
9739 	if (flags & KF_ITER_NEW)
9740 		sfx = "new";
9741 	else if (flags & KF_ITER_NEXT)
9742 		sfx = "next";
9743 	else /* (flags & KF_ITER_DESTROY) */
9744 		sfx = "destroy";
9745 
9746 	snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
9747 	if (strcmp(func_name, exp_name))
9748 		return -EINVAL;
9749 
9750 	/* only iter constructor should have extra arguments */
9751 	if (!(flags & KF_ITER_NEW) && nr_args != 1)
9752 		return -EINVAL;
9753 
9754 	if (flags & KF_ITER_NEXT) {
9755 		/* bpf_iter_<type>_next() should return pointer */
9756 		t = btf_type_skip_modifiers(btf, func->type, NULL);
9757 		if (!t || !btf_type_is_ptr(t))
9758 			return -EINVAL;
9759 	}
9760 
9761 	if (flags & KF_ITER_DESTROY) {
9762 		/* bpf_iter_<type>_destroy() should return void */
9763 		t = btf_type_by_id(btf, func->type);
9764 		if (!t || !btf_type_is_void(t))
9765 			return -EINVAL;
9766 	}
9767 
9768 	return 0;
9769 }
9770 
9771 static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind)
9772 {
9773 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9774 	struct btf_module *btf_mod, *tmp;
9775 #endif
9776 	s32 id;
9777 
9778 	if (!btf_is_module(btf))
9779 		return 0;
9780 
9781 	id = btf_find_by_name_kind(bpf_get_btf_vmlinux(), func_name, kind);
9782 	if (id >= 0) {
9783 		pr_err("kfunc %s (id: %d) is already present in vmlinux.\n",
9784 		       func_name, id);
9785 		return -EINVAL;
9786 	}
9787 
9788 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9789 	guard(mutex)(&btf_module_mutex);
9790 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9791 		if (btf_mod->btf == btf)
9792 			continue;
9793 		id = btf_find_by_name_kind(btf_mod->btf, func_name, kind);
9794 		if (id >= 0) {
9795 			pr_err("kfunc %s (id: %d) is already present in module %s.\n",
9796 			       func_name, id, btf_mod->module->name);
9797 			return -EINVAL;
9798 		}
9799 	}
9800 #endif
9801 	return 0;
9802 }
9803 
9804 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
9805 {
9806 	const struct btf_type *func;
9807 	const char *func_name;
9808 	int err;
9809 
9810 	/* any kfunc should be FUNC -> FUNC_PROTO */
9811 	func = btf_type_by_id(btf, func_id);
9812 	if (!func || !btf_type_is_func(func))
9813 		return -EINVAL;
9814 
9815 	/* sanity check kfunc name */
9816 	func_name = btf_name_by_offset(btf, func->name_off);
9817 	if (!func_name || !func_name[0] ||
9818 	    btf_check_kfunc_name(btf, func_name, BTF_INFO_KIND(func->info)))
9819 		return -EINVAL;
9820 
9821 	func = btf_type_by_id(btf, func->type);
9822 	if (!func || !btf_type_is_func_proto(func))
9823 		return -EINVAL;
9824 
9825 	if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
9826 		err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
9827 		if (err)
9828 			return err;
9829 	}
9830 
9831 	return 0;
9832 }
9833 
9834 /* Kernel Function (kfunc) BTF ID set registration API */
9835 
9836 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
9837 				  const struct btf_kfunc_id_set *kset)
9838 {
9839 	struct btf_kfunc_hook_filter *hook_filter;
9840 	struct btf_id_set8 *add_set = kset->set;
9841 	bool vmlinux_set = !btf_is_module(btf);
9842 	bool add_filter = !!kset->filter;
9843 	struct btf_kfunc_set_tab *tab;
9844 	struct btf_id_set8 *set;
9845 	u32 set_cnt, i;
9846 	int ret;
9847 
9848 	if (hook >= BTF_KFUNC_HOOK_MAX) {
9849 		ret = -EINVAL;
9850 		goto end;
9851 	}
9852 
9853 	if (!add_set->cnt)
9854 		return 0;
9855 
9856 	tab = btf->kfunc_set_tab;
9857 
9858 	if (tab && add_filter) {
9859 		u32 i;
9860 
9861 		hook_filter = &tab->hook_filters[hook];
9862 		for (i = 0; i < hook_filter->nr_filters; i++) {
9863 			if (hook_filter->filters[i] == kset->filter) {
9864 				add_filter = false;
9865 				break;
9866 			}
9867 		}
9868 
9869 		if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
9870 			ret = -E2BIG;
9871 			goto end;
9872 		}
9873 	}
9874 
9875 	if (!tab) {
9876 		tab = kzalloc_obj(*tab, GFP_KERNEL | __GFP_NOWARN);
9877 		if (!tab)
9878 			return -ENOMEM;
9879 		btf->kfunc_set_tab = tab;
9880 	}
9881 
9882 	set = tab->sets[hook];
9883 	/* Warn when register_btf_kfunc_id_set is called twice for the same hook
9884 	 * for module sets.
9885 	 */
9886 	if (WARN_ON_ONCE(set && !vmlinux_set)) {
9887 		ret = -EINVAL;
9888 		goto end;
9889 	}
9890 
9891 	/* In case of vmlinux sets, there may be more than one set being
9892 	 * registered per hook. To create a unified set, we allocate a new set
9893 	 * and concatenate all individual sets being registered. While each set
9894 	 * is individually sorted, they may become unsorted when concatenated,
9895 	 * hence re-sorting the final set again is required to make binary
9896 	 * searching the set using btf_id_set8_contains function work.
9897 	 *
9898 	 * For module sets, we need to allocate as we may need to relocate
9899 	 * BTF ids.
9900 	 */
9901 	set_cnt = set ? set->cnt : 0;
9902 
9903 	if (set_cnt > U32_MAX - add_set->cnt) {
9904 		ret = -EOVERFLOW;
9905 		goto end;
9906 	}
9907 
9908 	if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
9909 		ret = -E2BIG;
9910 		goto end;
9911 	}
9912 
9913 	/* Grow set */
9914 	set = krealloc(tab->sets[hook],
9915 		       struct_size(set, pairs, set_cnt + add_set->cnt),
9916 		       GFP_KERNEL | __GFP_NOWARN);
9917 	if (!set) {
9918 		ret = -ENOMEM;
9919 		goto end;
9920 	}
9921 
9922 	/* For newly allocated set, initialize set->cnt to 0 */
9923 	if (!tab->sets[hook])
9924 		set->cnt = 0;
9925 	tab->sets[hook] = set;
9926 
9927 	/* Concatenate the two sets */
9928 	memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
9929 	/* Now that the set is copied, update with relocated BTF ids */
9930 	for (i = set->cnt; i < set->cnt + add_set->cnt; i++)
9931 		set->pairs[i].id = btf_relocate_id(btf, set->pairs[i].id);
9932 
9933 	set->cnt += add_set->cnt;
9934 
9935 	sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
9936 
9937 	if (add_filter) {
9938 		hook_filter = &tab->hook_filters[hook];
9939 		hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
9940 	}
9941 	return 0;
9942 end:
9943 	btf_free_kfunc_set_tab(btf);
9944 	return ret;
9945 }
9946 
9947 static u32 *btf_kfunc_id_set_contains(const struct btf *btf,
9948 				      enum btf_kfunc_hook hook,
9949 				      u32 kfunc_btf_id)
9950 {
9951 	struct btf_id_set8 *set;
9952 	u32 *id;
9953 
9954 	if (hook >= BTF_KFUNC_HOOK_MAX)
9955 		return NULL;
9956 	if (!btf->kfunc_set_tab)
9957 		return NULL;
9958 	set = btf->kfunc_set_tab->sets[hook];
9959 	if (!set)
9960 		return NULL;
9961 	id = btf_id_set8_contains(set, kfunc_btf_id);
9962 	if (!id)
9963 		return NULL;
9964 	/* The flags for BTF ID are located next to it */
9965 	return id + 1;
9966 }
9967 
9968 static bool __btf_kfunc_is_allowed(const struct btf *btf,
9969 				   enum btf_kfunc_hook hook,
9970 				   u32 kfunc_btf_id,
9971 				   const struct bpf_prog *prog)
9972 {
9973 	struct btf_kfunc_hook_filter *hook_filter;
9974 	int i;
9975 
9976 	if (hook >= BTF_KFUNC_HOOK_MAX)
9977 		return false;
9978 	if (!btf->kfunc_set_tab)
9979 		return false;
9980 
9981 	hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
9982 	for (i = 0; i < hook_filter->nr_filters; i++) {
9983 		if (hook_filter->filters[i](prog, kfunc_btf_id))
9984 			return false;
9985 	}
9986 
9987 	return true;
9988 }
9989 
9990 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
9991 {
9992 	switch (prog_type) {
9993 	case BPF_PROG_TYPE_UNSPEC:
9994 		return BTF_KFUNC_HOOK_COMMON;
9995 	case BPF_PROG_TYPE_XDP:
9996 		return BTF_KFUNC_HOOK_XDP;
9997 	case BPF_PROG_TYPE_SCHED_CLS:
9998 		return BTF_KFUNC_HOOK_TC;
9999 	case BPF_PROG_TYPE_STRUCT_OPS:
10000 		return BTF_KFUNC_HOOK_STRUCT_OPS;
10001 	case BPF_PROG_TYPE_TRACING:
10002 	case BPF_PROG_TYPE_TRACEPOINT:
10003 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
10004 	case BPF_PROG_TYPE_PERF_EVENT:
10005 	case BPF_PROG_TYPE_LSM:
10006 		return BTF_KFUNC_HOOK_TRACING;
10007 	case BPF_PROG_TYPE_SYSCALL:
10008 		return BTF_KFUNC_HOOK_SYSCALL;
10009 	case BPF_PROG_TYPE_CGROUP_SKB:
10010 	case BPF_PROG_TYPE_CGROUP_SOCK:
10011 	case BPF_PROG_TYPE_CGROUP_DEVICE:
10012 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
10013 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
10014 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
10015 	case BPF_PROG_TYPE_SOCK_OPS:
10016 		return BTF_KFUNC_HOOK_CGROUP;
10017 	case BPF_PROG_TYPE_SCHED_ACT:
10018 		return BTF_KFUNC_HOOK_SCHED_ACT;
10019 	case BPF_PROG_TYPE_SK_SKB:
10020 		return BTF_KFUNC_HOOK_SK_SKB;
10021 	case BPF_PROG_TYPE_SOCKET_FILTER:
10022 		return BTF_KFUNC_HOOK_SOCKET_FILTER;
10023 	case BPF_PROG_TYPE_LWT_OUT:
10024 	case BPF_PROG_TYPE_LWT_IN:
10025 	case BPF_PROG_TYPE_LWT_XMIT:
10026 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
10027 		return BTF_KFUNC_HOOK_LWT;
10028 	case BPF_PROG_TYPE_NETFILTER:
10029 		return BTF_KFUNC_HOOK_NETFILTER;
10030 	case BPF_PROG_TYPE_KPROBE:
10031 		return BTF_KFUNC_HOOK_KPROBE;
10032 	default:
10033 		return BTF_KFUNC_HOOK_MAX;
10034 	}
10035 }
10036 
10037 bool btf_kfunc_is_allowed(const struct btf *btf,
10038 			  u32 kfunc_btf_id,
10039 			  const struct bpf_prog *prog)
10040 {
10041 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10042 	enum btf_kfunc_hook hook;
10043 	u32 *kfunc_flags;
10044 
10045 	kfunc_flags = btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
10046 	if (kfunc_flags && __btf_kfunc_is_allowed(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog))
10047 		return true;
10048 
10049 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
10050 	kfunc_flags = btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
10051 	if (kfunc_flags && __btf_kfunc_is_allowed(btf, hook, kfunc_btf_id, prog))
10052 		return true;
10053 
10054 	return false;
10055 }
10056 
10057 /* Caution:
10058  * Reference to the module (obtained using btf_try_get_module) corresponding to
10059  * the struct btf *MUST* be held when calling this function from verifier
10060  * context. This is usually true as we stash references in prog's kfunc_btf_tab;
10061  * keeping the reference for the duration of the call provides the necessary
10062  * protection for looking up a well-formed btf->kfunc_set_tab.
10063  */
10064 u32 *btf_kfunc_flags(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog)
10065 {
10066 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
10067 	enum btf_kfunc_hook hook;
10068 	u32 *kfunc_flags;
10069 
10070 	kfunc_flags = btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
10071 	if (kfunc_flags)
10072 		return kfunc_flags;
10073 
10074 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
10075 	return btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
10076 }
10077 
10078 /*
10079  * Check a single KF_* @flag on a kfunc across all of its hook sets.
10080  * Returns:
10081  *   * 1 if @flag is set
10082  *   * 0 if @flag is not set
10083  *   * -EINVAL if @flag is set inconsistently across the sets
10084  *   * -ENOENT if kfunc_btf_id is not a registered kfunc
10085  */
10086 int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag)
10087 {
10088 	enum btf_kfunc_hook hook;
10089 	int res = -ENOENT;
10090 	bool is_set;
10091 	u32 *flags;
10092 
10093 	for (hook = 0; hook < BTF_KFUNC_HOOK_MAX; hook++) {
10094 		flags = btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
10095 		if (!flags)
10096 			continue;
10097 		is_set = *flags & flag;
10098 		if (res < 0)
10099 			res = is_set;
10100 		else if (res != is_set)
10101 			return -EINVAL;
10102 	}
10103 
10104 	return res;
10105 }
10106 
10107 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
10108 				const struct bpf_prog *prog)
10109 {
10110 	if (!__btf_kfunc_is_allowed(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog))
10111 		return NULL;
10112 
10113 	return btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);
10114 }
10115 
10116 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
10117 				       const struct btf_kfunc_id_set *kset)
10118 {
10119 	struct btf *btf;
10120 	int ret, i;
10121 
10122 	btf = btf_get_module_btf(kset->owner);
10123 	if (!btf)
10124 		return check_btf_kconfigs(kset->owner, "kfunc");
10125 	if (IS_ERR(btf))
10126 		return PTR_ERR(btf);
10127 
10128 	for (i = 0; i < kset->set->cnt; i++) {
10129 		ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
10130 					     kset->set->pairs[i].flags);
10131 		if (ret)
10132 			goto err_out;
10133 	}
10134 
10135 	ret = btf_populate_kfunc_set(btf, hook, kset);
10136 
10137 err_out:
10138 	btf_put(btf);
10139 	return ret;
10140 }
10141 
10142 /* This function must be invoked only from initcalls/module init functions */
10143 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
10144 			      const struct btf_kfunc_id_set *kset)
10145 {
10146 	enum btf_kfunc_hook hook;
10147 
10148 	/* All kfuncs need to be tagged as such in BTF.
10149 	 * WARN() for initcall registrations that do not check errors.
10150 	 */
10151 	if (!(kset->set->flags & BTF_SET8_KFUNCS)) {
10152 		WARN_ON(!kset->owner);
10153 		return -EINVAL;
10154 	}
10155 
10156 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
10157 	return __register_btf_kfunc_id_set(hook, kset);
10158 }
10159 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
10160 
10161 /* This function must be invoked only from initcalls/module init functions */
10162 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
10163 {
10164 	return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
10165 }
10166 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
10167 
10168 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
10169 {
10170 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
10171 	struct btf_id_dtor_kfunc *dtor;
10172 
10173 	if (!tab)
10174 		return -ENOENT;
10175 	/* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
10176 	 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
10177 	 */
10178 	BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
10179 	dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
10180 	if (!dtor)
10181 		return -ENOENT;
10182 	return dtor->kfunc_btf_id;
10183 }
10184 
10185 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
10186 {
10187 	const struct btf_type *dtor_func, *dtor_func_proto, *t;
10188 	const struct btf_param *args;
10189 	s32 dtor_btf_id;
10190 	u32 nr_args, i;
10191 
10192 	for (i = 0; i < cnt; i++) {
10193 		dtor_btf_id = btf_relocate_id(btf, dtors[i].kfunc_btf_id);
10194 
10195 		dtor_func = btf_type_by_id(btf, dtor_btf_id);
10196 		if (!dtor_func || !btf_type_is_func(dtor_func))
10197 			return -EINVAL;
10198 
10199 		dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
10200 		if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
10201 			return -EINVAL;
10202 
10203 		/* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
10204 		t = btf_type_by_id(btf, dtor_func_proto->type);
10205 		if (!t || !btf_type_is_void(t))
10206 			return -EINVAL;
10207 
10208 		nr_args = btf_type_vlen(dtor_func_proto);
10209 		if (nr_args != 1)
10210 			return -EINVAL;
10211 		args = btf_params(dtor_func_proto);
10212 		t = btf_type_by_id(btf, args[0].type);
10213 		/* Allow any pointer type, as width on targets Linux supports
10214 		 * will be same for all pointer types (i.e. sizeof(void *))
10215 		 */
10216 		if (!t || !btf_type_is_ptr(t))
10217 			return -EINVAL;
10218 
10219 		if (IS_ENABLED(CONFIG_CFI)) {
10220 			/* Ensure the destructor kfunc type matches btf_dtor_kfunc_t */
10221 			t = btf_type_by_id(btf, t->type);
10222 			if (!btf_type_is_void(t))
10223 				return -EINVAL;
10224 		}
10225 	}
10226 	return 0;
10227 }
10228 
10229 /* This function must be invoked only from initcalls/module init functions */
10230 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
10231 				struct module *owner)
10232 {
10233 	struct btf_id_dtor_kfunc_tab *tab;
10234 	struct btf *btf;
10235 	u32 tab_cnt, i;
10236 	int ret;
10237 
10238 	btf = btf_get_module_btf(owner);
10239 	if (!btf)
10240 		return check_btf_kconfigs(owner, "dtor kfuncs");
10241 	if (IS_ERR(btf))
10242 		return PTR_ERR(btf);
10243 
10244 	if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
10245 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
10246 		ret = -E2BIG;
10247 		goto end;
10248 	}
10249 
10250 	/* Ensure that the prototype of dtor kfuncs being registered is sane */
10251 	ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
10252 	if (ret < 0)
10253 		goto end;
10254 
10255 	tab = btf->dtor_kfunc_tab;
10256 	/* Only one call allowed for modules */
10257 	if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
10258 		ret = -EINVAL;
10259 		goto end;
10260 	}
10261 
10262 	tab_cnt = tab ? tab->cnt : 0;
10263 	if (tab_cnt > U32_MAX - add_cnt) {
10264 		ret = -EOVERFLOW;
10265 		goto end;
10266 	}
10267 	if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
10268 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
10269 		ret = -E2BIG;
10270 		goto end;
10271 	}
10272 
10273 	tab = krealloc(btf->dtor_kfunc_tab,
10274 		       struct_size(tab, dtors, tab_cnt + add_cnt),
10275 		       GFP_KERNEL | __GFP_NOWARN);
10276 	if (!tab) {
10277 		ret = -ENOMEM;
10278 		goto end;
10279 	}
10280 
10281 	if (!btf->dtor_kfunc_tab)
10282 		tab->cnt = 0;
10283 	btf->dtor_kfunc_tab = tab;
10284 
10285 	memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
10286 
10287 	/* remap BTF ids based on BTF relocation (if any) */
10288 	for (i = tab_cnt; i < tab_cnt + add_cnt; i++) {
10289 		tab->dtors[i].btf_id = btf_relocate_id(btf, tab->dtors[i].btf_id);
10290 		tab->dtors[i].kfunc_btf_id = btf_relocate_id(btf, tab->dtors[i].kfunc_btf_id);
10291 	}
10292 
10293 	tab->cnt += add_cnt;
10294 
10295 	sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
10296 
10297 end:
10298 	if (ret)
10299 		btf_free_dtor_kfunc_tab(btf);
10300 	btf_put(btf);
10301 	return ret;
10302 }
10303 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
10304 
10305 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
10306 
10307 /* Check local and target types for compatibility. This check is used for
10308  * type-based CO-RE relocations and follow slightly different rules than
10309  * field-based relocations. This function assumes that root types were already
10310  * checked for name match. Beyond that initial root-level name check, names
10311  * are completely ignored. Compatibility rules are as follows:
10312  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
10313  *     kind should match for local and target types (i.e., STRUCT is not
10314  *     compatible with UNION);
10315  *   - for ENUMs/ENUM64s, the size is ignored;
10316  *   - for INT, size and signedness are ignored;
10317  *   - for ARRAY, dimensionality is ignored, element types are checked for
10318  *     compatibility recursively;
10319  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
10320  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
10321  *   - FUNC_PROTOs are compatible if they have compatible signature: same
10322  *     number of input args and compatible return and argument types.
10323  * These rules are not set in stone and probably will be adjusted as we get
10324  * more experience with using BPF CO-RE relocations.
10325  */
10326 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
10327 			      const struct btf *targ_btf, __u32 targ_id)
10328 {
10329 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
10330 					   MAX_TYPES_ARE_COMPAT_DEPTH);
10331 }
10332 
10333 #define MAX_TYPES_MATCH_DEPTH 2
10334 
10335 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
10336 			 const struct btf *targ_btf, u32 targ_id)
10337 {
10338 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
10339 				      MAX_TYPES_MATCH_DEPTH);
10340 }
10341 
10342 static bool bpf_core_is_flavor_sep(const char *s)
10343 {
10344 	/* check X___Y name pattern, where X and Y are not underscores */
10345 	return s[0] != '_' &&				      /* X */
10346 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
10347 	       s[4] != '_';				      /* Y */
10348 }
10349 
10350 size_t bpf_core_essential_name_len(const char *name)
10351 {
10352 	size_t n = strlen(name);
10353 	int i;
10354 
10355 	for (i = n - 5; i >= 0; i--) {
10356 		if (bpf_core_is_flavor_sep(name + i))
10357 			return i + 1;
10358 	}
10359 	return n;
10360 }
10361 
10362 static void bpf_free_cands(struct bpf_cand_cache *cands)
10363 {
10364 	if (!cands->cnt)
10365 		/* empty candidate array was allocated on stack */
10366 		return;
10367 	kfree(cands);
10368 }
10369 
10370 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
10371 {
10372 	kfree(cands->name);
10373 	kfree(cands);
10374 }
10375 
10376 #define VMLINUX_CAND_CACHE_SIZE 31
10377 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
10378 
10379 #define MODULE_CAND_CACHE_SIZE 31
10380 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
10381 
10382 static void __print_cand_cache(struct bpf_verifier_log *log,
10383 			       struct bpf_cand_cache **cache,
10384 			       int cache_size)
10385 {
10386 	struct bpf_cand_cache *cc;
10387 	int i, j;
10388 
10389 	for (i = 0; i < cache_size; i++) {
10390 		cc = cache[i];
10391 		if (!cc)
10392 			continue;
10393 		bpf_log(log, "[%d]%s(", i, cc->name);
10394 		for (j = 0; j < cc->cnt; j++) {
10395 			bpf_log(log, "%d", cc->cands[j].id);
10396 			if (j < cc->cnt - 1)
10397 				bpf_log(log, " ");
10398 		}
10399 		bpf_log(log, "), ");
10400 	}
10401 }
10402 
10403 static void print_cand_cache(struct bpf_verifier_log *log)
10404 {
10405 	mutex_lock(&cand_cache_mutex);
10406 	bpf_log(log, "vmlinux_cand_cache:");
10407 	__print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
10408 	bpf_log(log, "\nmodule_cand_cache:");
10409 	__print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
10410 	bpf_log(log, "\n");
10411 	mutex_unlock(&cand_cache_mutex);
10412 }
10413 
10414 static u32 hash_cands(struct bpf_cand_cache *cands)
10415 {
10416 	return jhash(cands->name, cands->name_len, 0);
10417 }
10418 
10419 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
10420 					       struct bpf_cand_cache **cache,
10421 					       int cache_size)
10422 {
10423 	struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
10424 
10425 	if (cc && cc->name_len == cands->name_len &&
10426 	    !strncmp(cc->name, cands->name, cands->name_len))
10427 		return cc;
10428 	return NULL;
10429 }
10430 
10431 static size_t sizeof_cands(int cnt)
10432 {
10433 	return offsetof(struct bpf_cand_cache, cands[cnt]);
10434 }
10435 
10436 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
10437 						  struct bpf_cand_cache **cache,
10438 						  int cache_size)
10439 {
10440 	struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
10441 
10442 	if (*cc) {
10443 		bpf_free_cands_from_cache(*cc);
10444 		*cc = NULL;
10445 	}
10446 	new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL_ACCOUNT);
10447 	if (!new_cands) {
10448 		bpf_free_cands(cands);
10449 		return ERR_PTR(-ENOMEM);
10450 	}
10451 	/* strdup the name, since it will stay in cache.
10452 	 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
10453 	 */
10454 	new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL_ACCOUNT);
10455 	bpf_free_cands(cands);
10456 	if (!new_cands->name) {
10457 		kfree(new_cands);
10458 		return ERR_PTR(-ENOMEM);
10459 	}
10460 	*cc = new_cands;
10461 	return new_cands;
10462 }
10463 
10464 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
10465 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
10466 			       int cache_size)
10467 {
10468 	struct bpf_cand_cache *cc;
10469 	int i, j;
10470 
10471 	for (i = 0; i < cache_size; i++) {
10472 		cc = cache[i];
10473 		if (!cc)
10474 			continue;
10475 		if (!btf) {
10476 			/* when new module is loaded purge all of module_cand_cache,
10477 			 * since new module might have candidates with the name
10478 			 * that matches cached cands.
10479 			 */
10480 			bpf_free_cands_from_cache(cc);
10481 			cache[i] = NULL;
10482 			continue;
10483 		}
10484 		/* when module is unloaded purge cache entries
10485 		 * that match module's btf
10486 		 */
10487 		for (j = 0; j < cc->cnt; j++)
10488 			if (cc->cands[j].btf == btf) {
10489 				bpf_free_cands_from_cache(cc);
10490 				cache[i] = NULL;
10491 				break;
10492 			}
10493 	}
10494 
10495 }
10496 
10497 static void purge_cand_cache(struct btf *btf)
10498 {
10499 	mutex_lock(&cand_cache_mutex);
10500 	__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
10501 	mutex_unlock(&cand_cache_mutex);
10502 }
10503 #endif
10504 
10505 static struct bpf_cand_cache *
10506 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
10507 		   int targ_start_id)
10508 {
10509 	struct bpf_cand_cache *new_cands;
10510 	const struct btf_type *t;
10511 	const char *targ_name;
10512 	size_t targ_essent_len;
10513 	int n, i;
10514 
10515 	n = btf_nr_types(targ_btf);
10516 	for (i = targ_start_id; i < n; i++) {
10517 		t = btf_type_by_id(targ_btf, i);
10518 		if (btf_kind(t) != cands->kind)
10519 			continue;
10520 
10521 		targ_name = btf_name_by_offset(targ_btf, t->name_off);
10522 		if (!targ_name)
10523 			continue;
10524 
10525 		/* the resched point is before strncmp to make sure that search
10526 		 * for non-existing name will have a chance to schedule().
10527 		 */
10528 		cond_resched();
10529 
10530 		if (strncmp(cands->name, targ_name, cands->name_len) != 0)
10531 			continue;
10532 
10533 		targ_essent_len = bpf_core_essential_name_len(targ_name);
10534 		if (targ_essent_len != cands->name_len)
10535 			continue;
10536 
10537 		/* most of the time there is only one candidate for a given kind+name pair */
10538 		new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL_ACCOUNT);
10539 		if (!new_cands) {
10540 			bpf_free_cands(cands);
10541 			return ERR_PTR(-ENOMEM);
10542 		}
10543 
10544 		memcpy(new_cands, cands, sizeof_cands(cands->cnt));
10545 		bpf_free_cands(cands);
10546 		cands = new_cands;
10547 		cands->cands[cands->cnt].btf = targ_btf;
10548 		cands->cands[cands->cnt].id = i;
10549 		cands->cnt++;
10550 	}
10551 	return cands;
10552 }
10553 
10554 static struct bpf_cand_cache *
10555 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
10556 {
10557 	struct bpf_cand_cache *cands, *cc, local_cand = {};
10558 	const struct btf *local_btf = ctx->btf;
10559 	const struct btf_type *local_type;
10560 	const struct btf *main_btf;
10561 	size_t local_essent_len;
10562 	struct btf *mod_btf;
10563 	const char *name;
10564 	int id;
10565 
10566 	main_btf = bpf_get_btf_vmlinux();
10567 	if (IS_ERR(main_btf))
10568 		return ERR_CAST(main_btf);
10569 	if (!main_btf)
10570 		return ERR_PTR(-EINVAL);
10571 
10572 	local_type = btf_type_by_id(local_btf, local_type_id);
10573 	if (!local_type)
10574 		return ERR_PTR(-EINVAL);
10575 
10576 	name = btf_name_by_offset(local_btf, local_type->name_off);
10577 	if (str_is_empty(name))
10578 		return ERR_PTR(-EINVAL);
10579 	local_essent_len = bpf_core_essential_name_len(name);
10580 
10581 	cands = &local_cand;
10582 	cands->name = name;
10583 	cands->kind = btf_kind(local_type);
10584 	cands->name_len = local_essent_len;
10585 
10586 	cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
10587 	/* cands is a pointer to stack here */
10588 	if (cc) {
10589 		if (cc->cnt)
10590 			return cc;
10591 		goto check_modules;
10592 	}
10593 
10594 	/* Attempt to find target candidates in vmlinux BTF first */
10595 	cands = bpf_core_add_cands(cands, main_btf, btf_named_start_id(main_btf, true));
10596 	if (IS_ERR(cands))
10597 		return ERR_CAST(cands);
10598 
10599 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
10600 
10601 	/* populate cache even when cands->cnt == 0 */
10602 	cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
10603 	if (IS_ERR(cc))
10604 		return ERR_CAST(cc);
10605 
10606 	/* if vmlinux BTF has any candidate, don't go for module BTFs */
10607 	if (cc->cnt)
10608 		return cc;
10609 
10610 check_modules:
10611 	/* cands is a pointer to stack here and cands->cnt == 0 */
10612 	cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
10613 	if (cc)
10614 		/* if cache has it return it even if cc->cnt == 0 */
10615 		return cc;
10616 
10617 	/* If candidate is not found in vmlinux's BTF then search in module's BTFs */
10618 	spin_lock_bh(&btf_idr_lock);
10619 	idr_for_each_entry(&btf_idr, mod_btf, id) {
10620 		if (!btf_is_module(mod_btf))
10621 			continue;
10622 		/* linear search could be slow hence unlock/lock
10623 		 * the IDR to avoiding holding it for too long
10624 		 */
10625 		btf_get(mod_btf);
10626 		spin_unlock_bh(&btf_idr_lock);
10627 		cands = bpf_core_add_cands(cands, mod_btf, btf_named_start_id(mod_btf, true));
10628 		btf_put(mod_btf);
10629 		if (IS_ERR(cands))
10630 			return ERR_CAST(cands);
10631 		spin_lock_bh(&btf_idr_lock);
10632 	}
10633 	spin_unlock_bh(&btf_idr_lock);
10634 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0
10635 	 * or pointer to stack if cands->cnd == 0.
10636 	 * Copy it into the cache even when cands->cnt == 0 and
10637 	 * return the result.
10638 	 */
10639 	return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
10640 }
10641 
10642 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
10643 		   int relo_idx, void *insn)
10644 {
10645 	bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
10646 	struct bpf_core_cand_list cands = {};
10647 	struct bpf_core_relo_res targ_res;
10648 	struct bpf_core_spec *specs;
10649 	const struct btf_type *type;
10650 	int err;
10651 
10652 	/* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
10653 	 * into arrays of btf_ids of struct fields and array indices.
10654 	 */
10655 	specs = kzalloc_objs(*specs, 3, GFP_KERNEL_ACCOUNT);
10656 	if (!specs)
10657 		return -ENOMEM;
10658 
10659 	type = btf_type_by_id(ctx->btf, relo->type_id);
10660 	if (!type) {
10661 		bpf_log(ctx->log, "relo #%u: bad type id %u\n",
10662 			relo_idx, relo->type_id);
10663 		kfree(specs);
10664 		return -EINVAL;
10665 	}
10666 
10667 	if (need_cands) {
10668 		struct bpf_cand_cache *cc;
10669 		int i;
10670 
10671 		mutex_lock(&cand_cache_mutex);
10672 		cc = bpf_core_find_cands(ctx, relo->type_id);
10673 		if (IS_ERR(cc)) {
10674 			bpf_log(ctx->log, "target candidate search failed for %d\n",
10675 				relo->type_id);
10676 			err = PTR_ERR(cc);
10677 			goto out;
10678 		}
10679 		if (cc->cnt) {
10680 			cands.cands = kzalloc_objs(*cands.cands, cc->cnt,
10681 						   GFP_KERNEL_ACCOUNT);
10682 			if (!cands.cands) {
10683 				err = -ENOMEM;
10684 				goto out;
10685 			}
10686 		}
10687 		for (i = 0; i < cc->cnt; i++) {
10688 			bpf_log(ctx->log,
10689 				"CO-RE relocating %s %s: found target candidate [%d]\n",
10690 				btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
10691 			cands.cands[i].btf = cc->cands[i].btf;
10692 			cands.cands[i].id = cc->cands[i].id;
10693 		}
10694 		cands.len = cc->cnt;
10695 		/* cand_cache_mutex needs to span the cache lookup and
10696 		 * copy of btf pointer into bpf_core_cand_list,
10697 		 * since module can be unloaded while bpf_core_calc_relo_insn
10698 		 * is working with module's btf.
10699 		 */
10700 	}
10701 
10702 	err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
10703 				      &targ_res);
10704 	if (err)
10705 		goto out;
10706 
10707 	err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
10708 				  &targ_res);
10709 
10710 out:
10711 	kfree(specs);
10712 	if (need_cands) {
10713 		kfree(cands.cands);
10714 		mutex_unlock(&cand_cache_mutex);
10715 		if (ctx->log->level & BPF_LOG_LEVEL2)
10716 			print_cand_cache(ctx->log);
10717 	}
10718 	return err;
10719 }
10720 
10721 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
10722 				const struct bpf_reg_state *reg,
10723 				const char *field_name, u32 btf_id, const char *suffix)
10724 {
10725 	struct btf *btf = reg->btf;
10726 	const struct btf_type *walk_type, *safe_type;
10727 	const char *tname;
10728 	char safe_tname[64];
10729 	long ret, safe_id;
10730 	const struct btf_member *member;
10731 	u32 i;
10732 
10733 	walk_type = btf_type_by_id(btf, reg->btf_id);
10734 	if (!walk_type)
10735 		return false;
10736 
10737 	tname = btf_name_by_offset(btf, walk_type->name_off);
10738 
10739 	ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
10740 	if (ret >= sizeof(safe_tname))
10741 		return false;
10742 
10743 	safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
10744 	if (safe_id < 0)
10745 		return false;
10746 
10747 	safe_type = btf_type_by_id(btf, safe_id);
10748 	if (!safe_type)
10749 		return false;
10750 
10751 	for_each_member(i, safe_type, member) {
10752 		const char *m_name = __btf_name_by_offset(btf, member->name_off);
10753 		const struct btf_type *mtype = btf_type_by_id(btf, member->type);
10754 		u32 id;
10755 
10756 		if (!btf_type_is_ptr(mtype))
10757 			continue;
10758 
10759 		btf_type_skip_modifiers(btf, mtype->type, &id);
10760 		/* If we match on both type and name, the field is considered trusted. */
10761 		if (btf_id == id && !strcmp(field_name, m_name))
10762 			return true;
10763 	}
10764 
10765 	return false;
10766 }
10767 
10768 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
10769 			       const struct btf *reg_btf, u32 reg_id,
10770 			       const struct btf *arg_btf, u32 arg_id)
10771 {
10772 	const char *reg_name, *arg_name, *search_needle;
10773 	const struct btf_type *reg_type, *arg_type;
10774 	int reg_len, arg_len, cmp_len;
10775 	size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
10776 
10777 	reg_type = btf_type_by_id(reg_btf, reg_id);
10778 	if (!reg_type)
10779 		return false;
10780 
10781 	arg_type = btf_type_by_id(arg_btf, arg_id);
10782 	if (!arg_type)
10783 		return false;
10784 
10785 	reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
10786 	arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
10787 
10788 	reg_len = strlen(reg_name);
10789 	arg_len = strlen(arg_name);
10790 
10791 	/* Exactly one of the two type names may be suffixed with ___init, so
10792 	 * if the strings are the same size, they can't possibly be no-cast
10793 	 * aliases of one another. If you have two of the same type names, e.g.
10794 	 * they're both nf_conn___init, it would be improper to return true
10795 	 * because they are _not_ no-cast aliases, they are the same type.
10796 	 */
10797 	if (reg_len == arg_len)
10798 		return false;
10799 
10800 	/* Either of the two names must be the other name, suffixed with ___init. */
10801 	if ((reg_len != arg_len + pattern_len) &&
10802 	    (arg_len != reg_len + pattern_len))
10803 		return false;
10804 
10805 	if (reg_len < arg_len) {
10806 		search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
10807 		cmp_len = reg_len;
10808 	} else {
10809 		search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
10810 		cmp_len = arg_len;
10811 	}
10812 
10813 	if (!search_needle)
10814 		return false;
10815 
10816 	/* ___init suffix must come at the end of the name */
10817 	if (*(search_needle + pattern_len) != '\0')
10818 		return false;
10819 
10820 	return !strncmp(reg_name, arg_name, cmp_len);
10821 }
10822 
10823 #ifdef CONFIG_BPF_JIT
10824 static int
10825 btf_add_struct_ops(struct btf *btf, struct bpf_struct_ops *st_ops,
10826 		   struct bpf_verifier_log *log)
10827 {
10828 	struct btf_struct_ops_tab *tab, *new_tab;
10829 	int cgroup_atype;
10830 	int i, err;
10831 
10832 	tab = btf->struct_ops_tab;
10833 	if (!tab) {
10834 		tab = kzalloc_flex(*tab, ops, 4);
10835 		if (!tab)
10836 			return -ENOMEM;
10837 		tab->capacity = 4;
10838 		btf->struct_ops_tab = tab;
10839 	}
10840 
10841 	cgroup_atype = st_ops->cgroup_atype;
10842 	for (i = 0; i < tab->cnt; i++)
10843 		if (tab->ops[i].st_ops == st_ops ||
10844 		    (cgroup_atype && cgroup_atype == tab->ops[i].st_ops->cgroup_atype))
10845 			return -EEXIST;
10846 
10847 	if (tab->cnt == tab->capacity) {
10848 		new_tab = krealloc(tab,
10849 				   struct_size(tab, ops, tab->capacity * 2),
10850 				   GFP_KERNEL);
10851 		if (!new_tab)
10852 			return -ENOMEM;
10853 		tab = new_tab;
10854 		tab->capacity *= 2;
10855 		btf->struct_ops_tab = tab;
10856 	}
10857 
10858 	tab->ops[btf->struct_ops_tab->cnt].st_ops = st_ops;
10859 
10860 	err = bpf_struct_ops_desc_init(&tab->ops[btf->struct_ops_tab->cnt], btf, log);
10861 	if (err)
10862 		return err;
10863 
10864 	if (cgroup_atype) {
10865 		/*
10866 		 * Cgroup struct_ops callers hold the RCU read lock around the
10867 		 * entire trampoline call, including its trailing instructions.
10868 		 * A regular RCU grace period therefore protects both the kdata
10869 		 * and the trampoline image, so a tasks RCU grace period is not
10870 		 * needed.
10871 		 */
10872 		if (!cgroup_bpf_is_struct_ops_atype(cgroup_atype) ||
10873 		    st_ops->reg || st_ops->unreg || st_ops->free_after_tasks_rcu_gp) {
10874 			bpf_struct_ops_desc_release(&tab->ops[btf->struct_ops_tab->cnt]);
10875 			return -EINVAL;
10876 		}
10877 
10878 		/*
10879 		 * There is no need to unregister from the cgroup when btf_free()
10880 		 * runs. No struct_ops map or cgroup link can be created once its
10881 		 * BTF is gone.
10882 		 */
10883 		cgroup_bpf_struct_ops_register(cgroup_atype,
10884 					       tab->ops[btf->struct_ops_tab->cnt].type_id,
10885 					       st_ops->cfi_stubs,
10886 					       st_ops->free_after_mult_rcu_gp);
10887 	}
10888 
10889 	btf->struct_ops_tab->cnt++;
10890 
10891 	return 0;
10892 }
10893 
10894 const struct bpf_struct_ops_desc *
10895 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
10896 {
10897 	const struct bpf_struct_ops_desc *st_ops_list;
10898 	unsigned int i;
10899 	u32 cnt;
10900 
10901 	if (!value_id)
10902 		return NULL;
10903 	if (!btf->struct_ops_tab)
10904 		return NULL;
10905 
10906 	cnt = btf->struct_ops_tab->cnt;
10907 	st_ops_list = btf->struct_ops_tab->ops;
10908 	for (i = 0; i < cnt; i++) {
10909 		if (st_ops_list[i].value_id == value_id)
10910 			return &st_ops_list[i];
10911 	}
10912 
10913 	return NULL;
10914 }
10915 
10916 const struct bpf_struct_ops_desc *
10917 bpf_struct_ops_find(struct btf *btf, u32 type_id)
10918 {
10919 	const struct bpf_struct_ops_desc *st_ops_list;
10920 	unsigned int i;
10921 	u32 cnt;
10922 
10923 	if (!type_id)
10924 		return NULL;
10925 	if (!btf->struct_ops_tab)
10926 		return NULL;
10927 
10928 	cnt = btf->struct_ops_tab->cnt;
10929 	st_ops_list = btf->struct_ops_tab->ops;
10930 	for (i = 0; i < cnt; i++) {
10931 		if (st_ops_list[i].type_id == type_id)
10932 			return &st_ops_list[i];
10933 	}
10934 
10935 	return NULL;
10936 }
10937 
10938 int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
10939 {
10940 	struct bpf_verifier_log *log;
10941 	struct btf *btf;
10942 	int err = 0;
10943 
10944 	btf = btf_get_module_btf(st_ops->owner);
10945 	if (!btf)
10946 		return check_btf_kconfigs(st_ops->owner, "struct_ops");
10947 	if (IS_ERR(btf))
10948 		return PTR_ERR(btf);
10949 
10950 	log = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);
10951 	if (!log) {
10952 		err = -ENOMEM;
10953 		goto errout;
10954 	}
10955 
10956 	log->level = BPF_LOG_KERNEL;
10957 
10958 	err = btf_add_struct_ops(btf, st_ops, log);
10959 
10960 errout:
10961 	kfree(log);
10962 	btf_put(btf);
10963 
10964 	return err;
10965 }
10966 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
10967 #endif
10968 
10969 bool btf_param_match_suffix(const struct btf *btf,
10970 			    const struct btf_param *arg,
10971 			    const char *suffix)
10972 {
10973 	int suffix_len = strlen(suffix), len;
10974 	const char *param_name;
10975 
10976 	/* In the future, this can be ported to use BTF tagging */
10977 	param_name = btf_name_by_offset(btf, arg->name_off);
10978 	if (str_is_empty(param_name))
10979 		return false;
10980 	len = strlen(param_name);
10981 	if (len <= suffix_len)
10982 		return false;
10983 	param_name += len - suffix_len;
10984 	return !strncmp(param_name, suffix, suffix_len);
10985 }
10986