xref: /openbmc/linux/kernel/bpf/btf.c (revision a266ef69b890f099069cf51bb40572611c435a54)
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_lsm.h>
23 #include <linux/skmsg.h>
24 #include <linux/perf_event.h>
25 #include <linux/bsearch.h>
26 #include <linux/kobject.h>
27 #include <linux/sysfs.h>
28 #include <net/sock.h>
29 #include "../tools/lib/bpf/relo_core.h"
30 
31 /* BTF (BPF Type Format) is the meta data format which describes
32  * the data types of BPF program/map.  Hence, it basically focus
33  * on the C programming language which the modern BPF is primary
34  * using.
35  *
36  * ELF Section:
37  * ~~~~~~~~~~~
38  * The BTF data is stored under the ".BTF" ELF section
39  *
40  * struct btf_type:
41  * ~~~~~~~~~~~~~~~
42  * Each 'struct btf_type' object describes a C data type.
43  * Depending on the type it is describing, a 'struct btf_type'
44  * object may be followed by more data.  F.e.
45  * To describe an array, 'struct btf_type' is followed by
46  * 'struct btf_array'.
47  *
48  * 'struct btf_type' and any extra data following it are
49  * 4 bytes aligned.
50  *
51  * Type section:
52  * ~~~~~~~~~~~~~
53  * The BTF type section contains a list of 'struct btf_type' objects.
54  * Each one describes a C type.  Recall from the above section
55  * that a 'struct btf_type' object could be immediately followed by extra
56  * data in order to describe some particular C types.
57  *
58  * type_id:
59  * ~~~~~~~
60  * Each btf_type object is identified by a type_id.  The type_id
61  * is implicitly implied by the location of the btf_type object in
62  * the BTF type section.  The first one has type_id 1.  The second
63  * one has type_id 2...etc.  Hence, an earlier btf_type has
64  * a smaller type_id.
65  *
66  * A btf_type object may refer to another btf_type object by using
67  * type_id (i.e. the "type" in the "struct btf_type").
68  *
69  * NOTE that we cannot assume any reference-order.
70  * A btf_type object can refer to an earlier btf_type object
71  * but it can also refer to a later btf_type object.
72  *
73  * For example, to describe "const void *".  A btf_type
74  * object describing "const" may refer to another btf_type
75  * object describing "void *".  This type-reference is done
76  * by specifying type_id:
77  *
78  * [1] CONST (anon) type_id=2
79  * [2] PTR (anon) type_id=0
80  *
81  * The above is the btf_verifier debug log:
82  *   - Each line started with "[?]" is a btf_type object
83  *   - [?] is the type_id of the btf_type object.
84  *   - CONST/PTR is the BTF_KIND_XXX
85  *   - "(anon)" is the name of the type.  It just
86  *     happens that CONST and PTR has no name.
87  *   - type_id=XXX is the 'u32 type' in btf_type
88  *
89  * NOTE: "void" has type_id 0
90  *
91  * String section:
92  * ~~~~~~~~~~~~~~
93  * The BTF string section contains the names used by the type section.
94  * Each string is referred by an "offset" from the beginning of the
95  * string section.
96  *
97  * Each string is '\0' terminated.
98  *
99  * The first character in the string section must be '\0'
100  * which is used to mean 'anonymous'. Some btf_type may not
101  * have a name.
102  */
103 
104 /* BTF verification:
105  *
106  * To verify BTF data, two passes are needed.
107  *
108  * Pass #1
109  * ~~~~~~~
110  * The first pass is to collect all btf_type objects to
111  * an array: "btf->types".
112  *
113  * Depending on the C type that a btf_type is describing,
114  * a btf_type may be followed by extra data.  We don't know
115  * how many btf_type is there, and more importantly we don't
116  * know where each btf_type is located in the type section.
117  *
118  * Without knowing the location of each type_id, most verifications
119  * cannot be done.  e.g. an earlier btf_type may refer to a later
120  * btf_type (recall the "const void *" above), so we cannot
121  * check this type-reference in the first pass.
122  *
123  * In the first pass, it still does some verifications (e.g.
124  * checking the name is a valid offset to the string section).
125  *
126  * Pass #2
127  * ~~~~~~~
128  * The main focus is to resolve a btf_type that is referring
129  * to another type.
130  *
131  * We have to ensure the referring type:
132  * 1) does exist in the BTF (i.e. in btf->types[])
133  * 2) does not cause a loop:
134  *	struct A {
135  *		struct B b;
136  *	};
137  *
138  *	struct B {
139  *		struct A a;
140  *	};
141  *
142  * btf_type_needs_resolve() decides if a btf_type needs
143  * to be resolved.
144  *
145  * The needs_resolve type implements the "resolve()" ops which
146  * essentially does a DFS and detects backedge.
147  *
148  * During resolve (or DFS), different C types have different
149  * "RESOLVED" conditions.
150  *
151  * When resolving a BTF_KIND_STRUCT, we need to resolve all its
152  * members because a member is always referring to another
153  * type.  A struct's member can be treated as "RESOLVED" if
154  * it is referring to a BTF_KIND_PTR.  Otherwise, the
155  * following valid C struct would be rejected:
156  *
157  *	struct A {
158  *		int m;
159  *		struct A *a;
160  *	};
161  *
162  * When resolving a BTF_KIND_PTR, it needs to keep resolving if
163  * it is referring to another BTF_KIND_PTR.  Otherwise, we cannot
164  * detect a pointer loop, e.g.:
165  * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
166  *                        ^                                         |
167  *                        +-----------------------------------------+
168  *
169  */
170 
171 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
172 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
173 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
174 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
175 #define BITS_ROUNDUP_BYTES(bits) \
176 	(BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
177 
178 #define BTF_INFO_MASK 0x9f00ffff
179 #define BTF_INT_MASK 0x0fffffff
180 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
181 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
182 
183 /* 16MB for 64k structs and each has 16 members and
184  * a few MB spaces for the string section.
185  * The hard limit is S32_MAX.
186  */
187 #define BTF_MAX_SIZE (16 * 1024 * 1024)
188 
189 #define for_each_member_from(i, from, struct_type, member)		\
190 	for (i = from, member = btf_type_member(struct_type) + from;	\
191 	     i < btf_type_vlen(struct_type);				\
192 	     i++, member++)
193 
194 #define for_each_vsi_from(i, from, struct_type, member)				\
195 	for (i = from, member = btf_type_var_secinfo(struct_type) + from;	\
196 	     i < btf_type_vlen(struct_type);					\
197 	     i++, member++)
198 
199 DEFINE_IDR(btf_idr);
200 DEFINE_SPINLOCK(btf_idr_lock);
201 
202 enum btf_kfunc_hook {
203 	BTF_KFUNC_HOOK_COMMON,
204 	BTF_KFUNC_HOOK_XDP,
205 	BTF_KFUNC_HOOK_TC,
206 	BTF_KFUNC_HOOK_STRUCT_OPS,
207 	BTF_KFUNC_HOOK_TRACING,
208 	BTF_KFUNC_HOOK_SYSCALL,
209 	BTF_KFUNC_HOOK_FMODRET,
210 	BTF_KFUNC_HOOK_MAX,
211 };
212 
213 enum {
214 	BTF_KFUNC_SET_MAX_CNT = 256,
215 	BTF_DTOR_KFUNC_MAX_CNT = 256,
216 };
217 
218 struct btf_kfunc_set_tab {
219 	struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
220 };
221 
222 struct btf_id_dtor_kfunc_tab {
223 	u32 cnt;
224 	struct btf_id_dtor_kfunc dtors[];
225 };
226 
227 struct btf {
228 	void *data;
229 	struct btf_type **types;
230 	u32 *resolved_ids;
231 	u32 *resolved_sizes;
232 	const char *strings;
233 	void *nohdr_data;
234 	struct btf_header hdr;
235 	u32 nr_types; /* includes VOID for base BTF */
236 	u32 types_size;
237 	u32 data_size;
238 	refcount_t refcnt;
239 	u32 id;
240 	struct rcu_head rcu;
241 	struct btf_kfunc_set_tab *kfunc_set_tab;
242 	struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
243 	struct btf_struct_metas *struct_meta_tab;
244 
245 	/* split BTF support */
246 	struct btf *base_btf;
247 	u32 start_id; /* first type ID in this BTF (0 for base BTF) */
248 	u32 start_str_off; /* first string offset (0 for base BTF) */
249 	char name[MODULE_NAME_LEN];
250 	bool kernel_btf;
251 };
252 
253 enum verifier_phase {
254 	CHECK_META,
255 	CHECK_TYPE,
256 };
257 
258 struct resolve_vertex {
259 	const struct btf_type *t;
260 	u32 type_id;
261 	u16 next_member;
262 };
263 
264 enum visit_state {
265 	NOT_VISITED,
266 	VISITED,
267 	RESOLVED,
268 };
269 
270 enum resolve_mode {
271 	RESOLVE_TBD,	/* To Be Determined */
272 	RESOLVE_PTR,	/* Resolving for Pointer */
273 	RESOLVE_STRUCT_OR_ARRAY,	/* Resolving for struct/union
274 					 * or array
275 					 */
276 };
277 
278 #define MAX_RESOLVE_DEPTH 32
279 
280 struct btf_sec_info {
281 	u32 off;
282 	u32 len;
283 };
284 
285 struct btf_verifier_env {
286 	struct btf *btf;
287 	u8 *visit_states;
288 	struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
289 	struct bpf_verifier_log log;
290 	u32 log_type_id;
291 	u32 top_stack;
292 	enum verifier_phase phase;
293 	enum resolve_mode resolve_mode;
294 };
295 
296 static const char * const btf_kind_str[NR_BTF_KINDS] = {
297 	[BTF_KIND_UNKN]		= "UNKNOWN",
298 	[BTF_KIND_INT]		= "INT",
299 	[BTF_KIND_PTR]		= "PTR",
300 	[BTF_KIND_ARRAY]	= "ARRAY",
301 	[BTF_KIND_STRUCT]	= "STRUCT",
302 	[BTF_KIND_UNION]	= "UNION",
303 	[BTF_KIND_ENUM]		= "ENUM",
304 	[BTF_KIND_FWD]		= "FWD",
305 	[BTF_KIND_TYPEDEF]	= "TYPEDEF",
306 	[BTF_KIND_VOLATILE]	= "VOLATILE",
307 	[BTF_KIND_CONST]	= "CONST",
308 	[BTF_KIND_RESTRICT]	= "RESTRICT",
309 	[BTF_KIND_FUNC]		= "FUNC",
310 	[BTF_KIND_FUNC_PROTO]	= "FUNC_PROTO",
311 	[BTF_KIND_VAR]		= "VAR",
312 	[BTF_KIND_DATASEC]	= "DATASEC",
313 	[BTF_KIND_FLOAT]	= "FLOAT",
314 	[BTF_KIND_DECL_TAG]	= "DECL_TAG",
315 	[BTF_KIND_TYPE_TAG]	= "TYPE_TAG",
316 	[BTF_KIND_ENUM64]	= "ENUM64",
317 };
318 
319 const char *btf_type_str(const struct btf_type *t)
320 {
321 	return btf_kind_str[BTF_INFO_KIND(t->info)];
322 }
323 
324 /* Chunk size we use in safe copy of data to be shown. */
325 #define BTF_SHOW_OBJ_SAFE_SIZE		32
326 
327 /*
328  * This is the maximum size of a base type value (equivalent to a
329  * 128-bit int); if we are at the end of our safe buffer and have
330  * less than 16 bytes space we can't be assured of being able
331  * to copy the next type safely, so in such cases we will initiate
332  * a new copy.
333  */
334 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE	16
335 
336 /* Type name size */
337 #define BTF_SHOW_NAME_SIZE		80
338 
339 /*
340  * The suffix of a type that indicates it cannot alias another type when
341  * comparing BTF IDs for kfunc invocations.
342  */
343 #define NOCAST_ALIAS_SUFFIX		"___init"
344 
345 /*
346  * Common data to all BTF show operations. Private show functions can add
347  * their own data to a structure containing a struct btf_show and consult it
348  * in the show callback.  See btf_type_show() below.
349  *
350  * One challenge with showing nested data is we want to skip 0-valued
351  * data, but in order to figure out whether a nested object is all zeros
352  * we need to walk through it.  As a result, we need to make two passes
353  * when handling structs, unions and arrays; the first path simply looks
354  * for nonzero data, while the second actually does the display.  The first
355  * pass is signalled by show->state.depth_check being set, and if we
356  * encounter a non-zero value we set show->state.depth_to_show to
357  * the depth at which we encountered it.  When we have completed the
358  * first pass, we will know if anything needs to be displayed if
359  * depth_to_show > depth.  See btf_[struct,array]_show() for the
360  * implementation of this.
361  *
362  * Another problem is we want to ensure the data for display is safe to
363  * access.  To support this, the anonymous "struct {} obj" tracks the data
364  * object and our safe copy of it.  We copy portions of the data needed
365  * to the object "copy" buffer, but because its size is limited to
366  * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
367  * traverse larger objects for display.
368  *
369  * The various data type show functions all start with a call to
370  * btf_show_start_type() which returns a pointer to the safe copy
371  * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
372  * raw data itself).  btf_show_obj_safe() is responsible for
373  * using copy_from_kernel_nofault() to update the safe data if necessary
374  * as we traverse the object's data.  skbuff-like semantics are
375  * used:
376  *
377  * - obj.head points to the start of the toplevel object for display
378  * - obj.size is the size of the toplevel object
379  * - obj.data points to the current point in the original data at
380  *   which our safe data starts.  obj.data will advance as we copy
381  *   portions of the data.
382  *
383  * In most cases a single copy will suffice, but larger data structures
384  * such as "struct task_struct" will require many copies.  The logic in
385  * btf_show_obj_safe() handles the logic that determines if a new
386  * copy_from_kernel_nofault() is needed.
387  */
388 struct btf_show {
389 	u64 flags;
390 	void *target;	/* target of show operation (seq file, buffer) */
391 	void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
392 	const struct btf *btf;
393 	/* below are used during iteration */
394 	struct {
395 		u8 depth;
396 		u8 depth_to_show;
397 		u8 depth_check;
398 		u8 array_member:1,
399 		   array_terminated:1;
400 		u16 array_encoding;
401 		u32 type_id;
402 		int status;			/* non-zero for error */
403 		const struct btf_type *type;
404 		const struct btf_member *member;
405 		char name[BTF_SHOW_NAME_SIZE];	/* space for member name/type */
406 	} state;
407 	struct {
408 		u32 size;
409 		void *head;
410 		void *data;
411 		u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
412 	} obj;
413 };
414 
415 struct btf_kind_operations {
416 	s32 (*check_meta)(struct btf_verifier_env *env,
417 			  const struct btf_type *t,
418 			  u32 meta_left);
419 	int (*resolve)(struct btf_verifier_env *env,
420 		       const struct resolve_vertex *v);
421 	int (*check_member)(struct btf_verifier_env *env,
422 			    const struct btf_type *struct_type,
423 			    const struct btf_member *member,
424 			    const struct btf_type *member_type);
425 	int (*check_kflag_member)(struct btf_verifier_env *env,
426 				  const struct btf_type *struct_type,
427 				  const struct btf_member *member,
428 				  const struct btf_type *member_type);
429 	void (*log_details)(struct btf_verifier_env *env,
430 			    const struct btf_type *t);
431 	void (*show)(const struct btf *btf, const struct btf_type *t,
432 			 u32 type_id, void *data, u8 bits_offsets,
433 			 struct btf_show *show);
434 };
435 
436 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
437 static struct btf_type btf_void;
438 
439 static int btf_resolve(struct btf_verifier_env *env,
440 		       const struct btf_type *t, u32 type_id);
441 
442 static int btf_func_check(struct btf_verifier_env *env,
443 			  const struct btf_type *t);
444 
445 static bool btf_type_is_modifier(const struct btf_type *t)
446 {
447 	/* Some of them is not strictly a C modifier
448 	 * but they are grouped into the same bucket
449 	 * for BTF concern:
450 	 *   A type (t) that refers to another
451 	 *   type through t->type AND its size cannot
452 	 *   be determined without following the t->type.
453 	 *
454 	 * ptr does not fall into this bucket
455 	 * because its size is always sizeof(void *).
456 	 */
457 	switch (BTF_INFO_KIND(t->info)) {
458 	case BTF_KIND_TYPEDEF:
459 	case BTF_KIND_VOLATILE:
460 	case BTF_KIND_CONST:
461 	case BTF_KIND_RESTRICT:
462 	case BTF_KIND_TYPE_TAG:
463 		return true;
464 	}
465 
466 	return false;
467 }
468 
469 bool btf_type_is_void(const struct btf_type *t)
470 {
471 	return t == &btf_void;
472 }
473 
474 static bool btf_type_is_fwd(const struct btf_type *t)
475 {
476 	return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
477 }
478 
479 static bool btf_type_nosize(const struct btf_type *t)
480 {
481 	return btf_type_is_void(t) || btf_type_is_fwd(t) ||
482 	       btf_type_is_func(t) || btf_type_is_func_proto(t);
483 }
484 
485 static bool btf_type_nosize_or_null(const struct btf_type *t)
486 {
487 	return !t || btf_type_nosize(t);
488 }
489 
490 static bool btf_type_is_datasec(const struct btf_type *t)
491 {
492 	return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
493 }
494 
495 static bool btf_type_is_decl_tag(const struct btf_type *t)
496 {
497 	return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
498 }
499 
500 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
501 {
502 	return btf_type_is_func(t) || btf_type_is_struct(t) ||
503 	       btf_type_is_var(t) || btf_type_is_typedef(t);
504 }
505 
506 u32 btf_nr_types(const struct btf *btf)
507 {
508 	u32 total = 0;
509 
510 	while (btf) {
511 		total += btf->nr_types;
512 		btf = btf->base_btf;
513 	}
514 
515 	return total;
516 }
517 
518 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
519 {
520 	const struct btf_type *t;
521 	const char *tname;
522 	u32 i, total;
523 
524 	total = btf_nr_types(btf);
525 	for (i = 1; i < total; i++) {
526 		t = btf_type_by_id(btf, i);
527 		if (BTF_INFO_KIND(t->info) != kind)
528 			continue;
529 
530 		tname = btf_name_by_offset(btf, t->name_off);
531 		if (!strcmp(tname, name))
532 			return i;
533 	}
534 
535 	return -ENOENT;
536 }
537 
538 static s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
539 {
540 	struct btf *btf;
541 	s32 ret;
542 	int id;
543 
544 	btf = bpf_get_btf_vmlinux();
545 	if (IS_ERR(btf))
546 		return PTR_ERR(btf);
547 	if (!btf)
548 		return -EINVAL;
549 
550 	ret = btf_find_by_name_kind(btf, name, kind);
551 	/* ret is never zero, since btf_find_by_name_kind returns
552 	 * positive btf_id or negative error.
553 	 */
554 	if (ret > 0) {
555 		btf_get(btf);
556 		*btf_p = btf;
557 		return ret;
558 	}
559 
560 	/* If name is not found in vmlinux's BTF then search in module's BTFs */
561 	spin_lock_bh(&btf_idr_lock);
562 	idr_for_each_entry(&btf_idr, btf, id) {
563 		if (!btf_is_module(btf))
564 			continue;
565 		/* linear search could be slow hence unlock/lock
566 		 * the IDR to avoiding holding it for too long
567 		 */
568 		btf_get(btf);
569 		spin_unlock_bh(&btf_idr_lock);
570 		ret = btf_find_by_name_kind(btf, name, kind);
571 		if (ret > 0) {
572 			*btf_p = btf;
573 			return ret;
574 		}
575 		spin_lock_bh(&btf_idr_lock);
576 		btf_put(btf);
577 	}
578 	spin_unlock_bh(&btf_idr_lock);
579 	return ret;
580 }
581 
582 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
583 					       u32 id, u32 *res_id)
584 {
585 	const struct btf_type *t = btf_type_by_id(btf, id);
586 
587 	while (btf_type_is_modifier(t)) {
588 		id = t->type;
589 		t = btf_type_by_id(btf, t->type);
590 	}
591 
592 	if (res_id)
593 		*res_id = id;
594 
595 	return t;
596 }
597 
598 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
599 					    u32 id, u32 *res_id)
600 {
601 	const struct btf_type *t;
602 
603 	t = btf_type_skip_modifiers(btf, id, NULL);
604 	if (!btf_type_is_ptr(t))
605 		return NULL;
606 
607 	return btf_type_skip_modifiers(btf, t->type, res_id);
608 }
609 
610 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
611 						 u32 id, u32 *res_id)
612 {
613 	const struct btf_type *ptype;
614 
615 	ptype = btf_type_resolve_ptr(btf, id, res_id);
616 	if (ptype && btf_type_is_func_proto(ptype))
617 		return ptype;
618 
619 	return NULL;
620 }
621 
622 /* Types that act only as a source, not sink or intermediate
623  * type when resolving.
624  */
625 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
626 {
627 	return btf_type_is_var(t) ||
628 	       btf_type_is_decl_tag(t) ||
629 	       btf_type_is_datasec(t);
630 }
631 
632 /* What types need to be resolved?
633  *
634  * btf_type_is_modifier() is an obvious one.
635  *
636  * btf_type_is_struct() because its member refers to
637  * another type (through member->type).
638  *
639  * btf_type_is_var() because the variable refers to
640  * another type. btf_type_is_datasec() holds multiple
641  * btf_type_is_var() types that need resolving.
642  *
643  * btf_type_is_array() because its element (array->type)
644  * refers to another type.  Array can be thought of a
645  * special case of struct while array just has the same
646  * member-type repeated by array->nelems of times.
647  */
648 static bool btf_type_needs_resolve(const struct btf_type *t)
649 {
650 	return btf_type_is_modifier(t) ||
651 	       btf_type_is_ptr(t) ||
652 	       btf_type_is_struct(t) ||
653 	       btf_type_is_array(t) ||
654 	       btf_type_is_var(t) ||
655 	       btf_type_is_func(t) ||
656 	       btf_type_is_decl_tag(t) ||
657 	       btf_type_is_datasec(t);
658 }
659 
660 /* t->size can be used */
661 static bool btf_type_has_size(const struct btf_type *t)
662 {
663 	switch (BTF_INFO_KIND(t->info)) {
664 	case BTF_KIND_INT:
665 	case BTF_KIND_STRUCT:
666 	case BTF_KIND_UNION:
667 	case BTF_KIND_ENUM:
668 	case BTF_KIND_DATASEC:
669 	case BTF_KIND_FLOAT:
670 	case BTF_KIND_ENUM64:
671 		return true;
672 	}
673 
674 	return false;
675 }
676 
677 static const char *btf_int_encoding_str(u8 encoding)
678 {
679 	if (encoding == 0)
680 		return "(none)";
681 	else if (encoding == BTF_INT_SIGNED)
682 		return "SIGNED";
683 	else if (encoding == BTF_INT_CHAR)
684 		return "CHAR";
685 	else if (encoding == BTF_INT_BOOL)
686 		return "BOOL";
687 	else
688 		return "UNKN";
689 }
690 
691 static u32 btf_type_int(const struct btf_type *t)
692 {
693 	return *(u32 *)(t + 1);
694 }
695 
696 static const struct btf_array *btf_type_array(const struct btf_type *t)
697 {
698 	return (const struct btf_array *)(t + 1);
699 }
700 
701 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
702 {
703 	return (const struct btf_enum *)(t + 1);
704 }
705 
706 static const struct btf_var *btf_type_var(const struct btf_type *t)
707 {
708 	return (const struct btf_var *)(t + 1);
709 }
710 
711 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
712 {
713 	return (const struct btf_decl_tag *)(t + 1);
714 }
715 
716 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
717 {
718 	return (const struct btf_enum64 *)(t + 1);
719 }
720 
721 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
722 {
723 	return kind_ops[BTF_INFO_KIND(t->info)];
724 }
725 
726 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
727 {
728 	if (!BTF_STR_OFFSET_VALID(offset))
729 		return false;
730 
731 	while (offset < btf->start_str_off)
732 		btf = btf->base_btf;
733 
734 	offset -= btf->start_str_off;
735 	return offset < btf->hdr.str_len;
736 }
737 
738 static bool __btf_name_char_ok(char c, bool first, bool dot_ok)
739 {
740 	if ((first ? !isalpha(c) :
741 		     !isalnum(c)) &&
742 	    c != '_' &&
743 	    ((c == '.' && !dot_ok) ||
744 	      c != '.'))
745 		return false;
746 	return true;
747 }
748 
749 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
750 {
751 	while (offset < btf->start_str_off)
752 		btf = btf->base_btf;
753 
754 	offset -= btf->start_str_off;
755 	if (offset < btf->hdr.str_len)
756 		return &btf->strings[offset];
757 
758 	return NULL;
759 }
760 
761 static bool __btf_name_valid(const struct btf *btf, u32 offset, bool dot_ok)
762 {
763 	/* offset must be valid */
764 	const char *src = btf_str_by_offset(btf, offset);
765 	const char *src_limit;
766 
767 	if (!__btf_name_char_ok(*src, true, dot_ok))
768 		return false;
769 
770 	/* set a limit on identifier length */
771 	src_limit = src + KSYM_NAME_LEN;
772 	src++;
773 	while (*src && src < src_limit) {
774 		if (!__btf_name_char_ok(*src, false, dot_ok))
775 			return false;
776 		src++;
777 	}
778 
779 	return !*src;
780 }
781 
782 /* Only C-style identifier is permitted. This can be relaxed if
783  * necessary.
784  */
785 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
786 {
787 	return __btf_name_valid(btf, offset, false);
788 }
789 
790 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
791 {
792 	return __btf_name_valid(btf, offset, true);
793 }
794 
795 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
796 {
797 	const char *name;
798 
799 	if (!offset)
800 		return "(anon)";
801 
802 	name = btf_str_by_offset(btf, offset);
803 	return name ?: "(invalid-name-offset)";
804 }
805 
806 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
807 {
808 	return btf_str_by_offset(btf, offset);
809 }
810 
811 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
812 {
813 	while (type_id < btf->start_id)
814 		btf = btf->base_btf;
815 
816 	type_id -= btf->start_id;
817 	if (type_id >= btf->nr_types)
818 		return NULL;
819 	return btf->types[type_id];
820 }
821 EXPORT_SYMBOL_GPL(btf_type_by_id);
822 
823 /*
824  * Regular int is not a bit field and it must be either
825  * u8/u16/u32/u64 or __int128.
826  */
827 static bool btf_type_int_is_regular(const struct btf_type *t)
828 {
829 	u8 nr_bits, nr_bytes;
830 	u32 int_data;
831 
832 	int_data = btf_type_int(t);
833 	nr_bits = BTF_INT_BITS(int_data);
834 	nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
835 	if (BITS_PER_BYTE_MASKED(nr_bits) ||
836 	    BTF_INT_OFFSET(int_data) ||
837 	    (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
838 	     nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
839 	     nr_bytes != (2 * sizeof(u64)))) {
840 		return false;
841 	}
842 
843 	return true;
844 }
845 
846 /*
847  * Check that given struct member is a regular int with expected
848  * offset and size.
849  */
850 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
851 			   const struct btf_member *m,
852 			   u32 expected_offset, u32 expected_size)
853 {
854 	const struct btf_type *t;
855 	u32 id, int_data;
856 	u8 nr_bits;
857 
858 	id = m->type;
859 	t = btf_type_id_size(btf, &id, NULL);
860 	if (!t || !btf_type_is_int(t))
861 		return false;
862 
863 	int_data = btf_type_int(t);
864 	nr_bits = BTF_INT_BITS(int_data);
865 	if (btf_type_kflag(s)) {
866 		u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
867 		u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
868 
869 		/* if kflag set, int should be a regular int and
870 		 * bit offset should be at byte boundary.
871 		 */
872 		return !bitfield_size &&
873 		       BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
874 		       BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
875 	}
876 
877 	if (BTF_INT_OFFSET(int_data) ||
878 	    BITS_PER_BYTE_MASKED(m->offset) ||
879 	    BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
880 	    BITS_PER_BYTE_MASKED(nr_bits) ||
881 	    BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
882 		return false;
883 
884 	return true;
885 }
886 
887 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
888 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
889 						       u32 id)
890 {
891 	const struct btf_type *t = btf_type_by_id(btf, id);
892 
893 	while (btf_type_is_modifier(t) &&
894 	       BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
895 		t = btf_type_by_id(btf, t->type);
896 	}
897 
898 	return t;
899 }
900 
901 #define BTF_SHOW_MAX_ITER	10
902 
903 #define BTF_KIND_BIT(kind)	(1ULL << kind)
904 
905 /*
906  * Populate show->state.name with type name information.
907  * Format of type name is
908  *
909  * [.member_name = ] (type_name)
910  */
911 static const char *btf_show_name(struct btf_show *show)
912 {
913 	/* BTF_MAX_ITER array suffixes "[]" */
914 	const char *array_suffixes = "[][][][][][][][][][]";
915 	const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
916 	/* BTF_MAX_ITER pointer suffixes "*" */
917 	const char *ptr_suffixes = "**********";
918 	const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
919 	const char *name = NULL, *prefix = "", *parens = "";
920 	const struct btf_member *m = show->state.member;
921 	const struct btf_type *t;
922 	const struct btf_array *array;
923 	u32 id = show->state.type_id;
924 	const char *member = NULL;
925 	bool show_member = false;
926 	u64 kinds = 0;
927 	int i;
928 
929 	show->state.name[0] = '\0';
930 
931 	/*
932 	 * Don't show type name if we're showing an array member;
933 	 * in that case we show the array type so don't need to repeat
934 	 * ourselves for each member.
935 	 */
936 	if (show->state.array_member)
937 		return "";
938 
939 	/* Retrieve member name, if any. */
940 	if (m) {
941 		member = btf_name_by_offset(show->btf, m->name_off);
942 		show_member = strlen(member) > 0;
943 		id = m->type;
944 	}
945 
946 	/*
947 	 * Start with type_id, as we have resolved the struct btf_type *
948 	 * via btf_modifier_show() past the parent typedef to the child
949 	 * struct, int etc it is defined as.  In such cases, the type_id
950 	 * still represents the starting type while the struct btf_type *
951 	 * in our show->state points at the resolved type of the typedef.
952 	 */
953 	t = btf_type_by_id(show->btf, id);
954 	if (!t)
955 		return "";
956 
957 	/*
958 	 * The goal here is to build up the right number of pointer and
959 	 * array suffixes while ensuring the type name for a typedef
960 	 * is represented.  Along the way we accumulate a list of
961 	 * BTF kinds we have encountered, since these will inform later
962 	 * display; for example, pointer types will not require an
963 	 * opening "{" for struct, we will just display the pointer value.
964 	 *
965 	 * We also want to accumulate the right number of pointer or array
966 	 * indices in the format string while iterating until we get to
967 	 * the typedef/pointee/array member target type.
968 	 *
969 	 * We start by pointing at the end of pointer and array suffix
970 	 * strings; as we accumulate pointers and arrays we move the pointer
971 	 * or array string backwards so it will show the expected number of
972 	 * '*' or '[]' for the type.  BTF_SHOW_MAX_ITER of nesting of pointers
973 	 * and/or arrays and typedefs are supported as a precaution.
974 	 *
975 	 * We also want to get typedef name while proceeding to resolve
976 	 * type it points to so that we can add parentheses if it is a
977 	 * "typedef struct" etc.
978 	 */
979 	for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
980 
981 		switch (BTF_INFO_KIND(t->info)) {
982 		case BTF_KIND_TYPEDEF:
983 			if (!name)
984 				name = btf_name_by_offset(show->btf,
985 							       t->name_off);
986 			kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
987 			id = t->type;
988 			break;
989 		case BTF_KIND_ARRAY:
990 			kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
991 			parens = "[";
992 			if (!t)
993 				return "";
994 			array = btf_type_array(t);
995 			if (array_suffix > array_suffixes)
996 				array_suffix -= 2;
997 			id = array->type;
998 			break;
999 		case BTF_KIND_PTR:
1000 			kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1001 			if (ptr_suffix > ptr_suffixes)
1002 				ptr_suffix -= 1;
1003 			id = t->type;
1004 			break;
1005 		default:
1006 			id = 0;
1007 			break;
1008 		}
1009 		if (!id)
1010 			break;
1011 		t = btf_type_skip_qualifiers(show->btf, id);
1012 	}
1013 	/* We may not be able to represent this type; bail to be safe */
1014 	if (i == BTF_SHOW_MAX_ITER)
1015 		return "";
1016 
1017 	if (!name)
1018 		name = btf_name_by_offset(show->btf, t->name_off);
1019 
1020 	switch (BTF_INFO_KIND(t->info)) {
1021 	case BTF_KIND_STRUCT:
1022 	case BTF_KIND_UNION:
1023 		prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1024 			 "struct" : "union";
1025 		/* if it's an array of struct/union, parens is already set */
1026 		if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1027 			parens = "{";
1028 		break;
1029 	case BTF_KIND_ENUM:
1030 	case BTF_KIND_ENUM64:
1031 		prefix = "enum";
1032 		break;
1033 	default:
1034 		break;
1035 	}
1036 
1037 	/* pointer does not require parens */
1038 	if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1039 		parens = "";
1040 	/* typedef does not require struct/union/enum prefix */
1041 	if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1042 		prefix = "";
1043 
1044 	if (!name)
1045 		name = "";
1046 
1047 	/* Even if we don't want type name info, we want parentheses etc */
1048 	if (show->flags & BTF_SHOW_NONAME)
1049 		snprintf(show->state.name, sizeof(show->state.name), "%s",
1050 			 parens);
1051 	else
1052 		snprintf(show->state.name, sizeof(show->state.name),
1053 			 "%s%s%s(%s%s%s%s%s%s)%s",
1054 			 /* first 3 strings comprise ".member = " */
1055 			 show_member ? "." : "",
1056 			 show_member ? member : "",
1057 			 show_member ? " = " : "",
1058 			 /* ...next is our prefix (struct, enum, etc) */
1059 			 prefix,
1060 			 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1061 			 /* ...this is the type name itself */
1062 			 name,
1063 			 /* ...suffixed by the appropriate '*', '[]' suffixes */
1064 			 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1065 			 array_suffix, parens);
1066 
1067 	return show->state.name;
1068 }
1069 
1070 static const char *__btf_show_indent(struct btf_show *show)
1071 {
1072 	const char *indents = "                                ";
1073 	const char *indent = &indents[strlen(indents)];
1074 
1075 	if ((indent - show->state.depth) >= indents)
1076 		return indent - show->state.depth;
1077 	return indents;
1078 }
1079 
1080 static const char *btf_show_indent(struct btf_show *show)
1081 {
1082 	return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1083 }
1084 
1085 static const char *btf_show_newline(struct btf_show *show)
1086 {
1087 	return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1088 }
1089 
1090 static const char *btf_show_delim(struct btf_show *show)
1091 {
1092 	if (show->state.depth == 0)
1093 		return "";
1094 
1095 	if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1096 		BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1097 		return "|";
1098 
1099 	return ",";
1100 }
1101 
1102 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1103 {
1104 	va_list args;
1105 
1106 	if (!show->state.depth_check) {
1107 		va_start(args, fmt);
1108 		show->showfn(show, fmt, args);
1109 		va_end(args);
1110 	}
1111 }
1112 
1113 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1114  * format specifiers to the format specifier passed in; these do the work of
1115  * adding indentation, delimiters etc while the caller simply has to specify
1116  * the type value(s) in the format specifier + value(s).
1117  */
1118 #define btf_show_type_value(show, fmt, value)				       \
1119 	do {								       \
1120 		if ((value) != (__typeof__(value))0 ||			       \
1121 		    (show->flags & BTF_SHOW_ZERO) ||			       \
1122 		    show->state.depth == 0) {				       \
1123 			btf_show(show, "%s%s" fmt "%s%s",		       \
1124 				 btf_show_indent(show),			       \
1125 				 btf_show_name(show),			       \
1126 				 value, btf_show_delim(show),		       \
1127 				 btf_show_newline(show));		       \
1128 			if (show->state.depth > show->state.depth_to_show)     \
1129 				show->state.depth_to_show = show->state.depth; \
1130 		}							       \
1131 	} while (0)
1132 
1133 #define btf_show_type_values(show, fmt, ...)				       \
1134 	do {								       \
1135 		btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show),       \
1136 			 btf_show_name(show),				       \
1137 			 __VA_ARGS__, btf_show_delim(show),		       \
1138 			 btf_show_newline(show));			       \
1139 		if (show->state.depth > show->state.depth_to_show)	       \
1140 			show->state.depth_to_show = show->state.depth;	       \
1141 	} while (0)
1142 
1143 /* How much is left to copy to safe buffer after @data? */
1144 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1145 {
1146 	return show->obj.head + show->obj.size - data;
1147 }
1148 
1149 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1150 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1151 {
1152 	return data >= show->obj.data &&
1153 	       (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1154 }
1155 
1156 /*
1157  * If object pointed to by @data of @size falls within our safe buffer, return
1158  * the equivalent pointer to the same safe data.  Assumes
1159  * copy_from_kernel_nofault() has already happened and our safe buffer is
1160  * populated.
1161  */
1162 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1163 {
1164 	if (btf_show_obj_is_safe(show, data, size))
1165 		return show->obj.safe + (data - show->obj.data);
1166 	return NULL;
1167 }
1168 
1169 /*
1170  * Return a safe-to-access version of data pointed to by @data.
1171  * We do this by copying the relevant amount of information
1172  * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1173  *
1174  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1175  * safe copy is needed.
1176  *
1177  * Otherwise we need to determine if we have the required amount
1178  * of data (determined by the @data pointer and the size of the
1179  * largest base type we can encounter (represented by
1180  * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1181  * that we will be able to print some of the current object,
1182  * and if more is needed a copy will be triggered.
1183  * Some objects such as structs will not fit into the buffer;
1184  * in such cases additional copies when we iterate over their
1185  * members may be needed.
1186  *
1187  * btf_show_obj_safe() is used to return a safe buffer for
1188  * btf_show_start_type(); this ensures that as we recurse into
1189  * nested types we always have safe data for the given type.
1190  * This approach is somewhat wasteful; it's possible for example
1191  * that when iterating over a large union we'll end up copying the
1192  * same data repeatedly, but the goal is safety not performance.
1193  * We use stack data as opposed to per-CPU buffers because the
1194  * iteration over a type can take some time, and preemption handling
1195  * would greatly complicate use of the safe buffer.
1196  */
1197 static void *btf_show_obj_safe(struct btf_show *show,
1198 			       const struct btf_type *t,
1199 			       void *data)
1200 {
1201 	const struct btf_type *rt;
1202 	int size_left, size;
1203 	void *safe = NULL;
1204 
1205 	if (show->flags & BTF_SHOW_UNSAFE)
1206 		return data;
1207 
1208 	rt = btf_resolve_size(show->btf, t, &size);
1209 	if (IS_ERR(rt)) {
1210 		show->state.status = PTR_ERR(rt);
1211 		return NULL;
1212 	}
1213 
1214 	/*
1215 	 * Is this toplevel object? If so, set total object size and
1216 	 * initialize pointers.  Otherwise check if we still fall within
1217 	 * our safe object data.
1218 	 */
1219 	if (show->state.depth == 0) {
1220 		show->obj.size = size;
1221 		show->obj.head = data;
1222 	} else {
1223 		/*
1224 		 * If the size of the current object is > our remaining
1225 		 * safe buffer we _may_ need to do a new copy.  However
1226 		 * consider the case of a nested struct; it's size pushes
1227 		 * us over the safe buffer limit, but showing any individual
1228 		 * struct members does not.  In such cases, we don't need
1229 		 * to initiate a fresh copy yet; however we definitely need
1230 		 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1231 		 * in our buffer, regardless of the current object size.
1232 		 * The logic here is that as we resolve types we will
1233 		 * hit a base type at some point, and we need to be sure
1234 		 * the next chunk of data is safely available to display
1235 		 * that type info safely.  We cannot rely on the size of
1236 		 * the current object here because it may be much larger
1237 		 * than our current buffer (e.g. task_struct is 8k).
1238 		 * All we want to do here is ensure that we can print the
1239 		 * next basic type, which we can if either
1240 		 * - the current type size is within the safe buffer; or
1241 		 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1242 		 *   the safe buffer.
1243 		 */
1244 		safe = __btf_show_obj_safe(show, data,
1245 					   min(size,
1246 					       BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1247 	}
1248 
1249 	/*
1250 	 * We need a new copy to our safe object, either because we haven't
1251 	 * yet copied and are initializing safe data, or because the data
1252 	 * we want falls outside the boundaries of the safe object.
1253 	 */
1254 	if (!safe) {
1255 		size_left = btf_show_obj_size_left(show, data);
1256 		if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1257 			size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1258 		show->state.status = copy_from_kernel_nofault(show->obj.safe,
1259 							      data, size_left);
1260 		if (!show->state.status) {
1261 			show->obj.data = data;
1262 			safe = show->obj.safe;
1263 		}
1264 	}
1265 
1266 	return safe;
1267 }
1268 
1269 /*
1270  * Set the type we are starting to show and return a safe data pointer
1271  * to be used for showing the associated data.
1272  */
1273 static void *btf_show_start_type(struct btf_show *show,
1274 				 const struct btf_type *t,
1275 				 u32 type_id, void *data)
1276 {
1277 	show->state.type = t;
1278 	show->state.type_id = type_id;
1279 	show->state.name[0] = '\0';
1280 
1281 	return btf_show_obj_safe(show, t, data);
1282 }
1283 
1284 static void btf_show_end_type(struct btf_show *show)
1285 {
1286 	show->state.type = NULL;
1287 	show->state.type_id = 0;
1288 	show->state.name[0] = '\0';
1289 }
1290 
1291 static void *btf_show_start_aggr_type(struct btf_show *show,
1292 				      const struct btf_type *t,
1293 				      u32 type_id, void *data)
1294 {
1295 	void *safe_data = btf_show_start_type(show, t, type_id, data);
1296 
1297 	if (!safe_data)
1298 		return safe_data;
1299 
1300 	btf_show(show, "%s%s%s", btf_show_indent(show),
1301 		 btf_show_name(show),
1302 		 btf_show_newline(show));
1303 	show->state.depth++;
1304 	return safe_data;
1305 }
1306 
1307 static void btf_show_end_aggr_type(struct btf_show *show,
1308 				   const char *suffix)
1309 {
1310 	show->state.depth--;
1311 	btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1312 		 btf_show_delim(show), btf_show_newline(show));
1313 	btf_show_end_type(show);
1314 }
1315 
1316 static void btf_show_start_member(struct btf_show *show,
1317 				  const struct btf_member *m)
1318 {
1319 	show->state.member = m;
1320 }
1321 
1322 static void btf_show_start_array_member(struct btf_show *show)
1323 {
1324 	show->state.array_member = 1;
1325 	btf_show_start_member(show, NULL);
1326 }
1327 
1328 static void btf_show_end_member(struct btf_show *show)
1329 {
1330 	show->state.member = NULL;
1331 }
1332 
1333 static void btf_show_end_array_member(struct btf_show *show)
1334 {
1335 	show->state.array_member = 0;
1336 	btf_show_end_member(show);
1337 }
1338 
1339 static void *btf_show_start_array_type(struct btf_show *show,
1340 				       const struct btf_type *t,
1341 				       u32 type_id,
1342 				       u16 array_encoding,
1343 				       void *data)
1344 {
1345 	show->state.array_encoding = array_encoding;
1346 	show->state.array_terminated = 0;
1347 	return btf_show_start_aggr_type(show, t, type_id, data);
1348 }
1349 
1350 static void btf_show_end_array_type(struct btf_show *show)
1351 {
1352 	show->state.array_encoding = 0;
1353 	show->state.array_terminated = 0;
1354 	btf_show_end_aggr_type(show, "]");
1355 }
1356 
1357 static void *btf_show_start_struct_type(struct btf_show *show,
1358 					const struct btf_type *t,
1359 					u32 type_id,
1360 					void *data)
1361 {
1362 	return btf_show_start_aggr_type(show, t, type_id, data);
1363 }
1364 
1365 static void btf_show_end_struct_type(struct btf_show *show)
1366 {
1367 	btf_show_end_aggr_type(show, "}");
1368 }
1369 
1370 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1371 					      const char *fmt, ...)
1372 {
1373 	va_list args;
1374 
1375 	va_start(args, fmt);
1376 	bpf_verifier_vlog(log, fmt, args);
1377 	va_end(args);
1378 }
1379 
1380 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1381 					    const char *fmt, ...)
1382 {
1383 	struct bpf_verifier_log *log = &env->log;
1384 	va_list args;
1385 
1386 	if (!bpf_verifier_log_needed(log))
1387 		return;
1388 
1389 	va_start(args, fmt);
1390 	bpf_verifier_vlog(log, fmt, args);
1391 	va_end(args);
1392 }
1393 
1394 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1395 						   const struct btf_type *t,
1396 						   bool log_details,
1397 						   const char *fmt, ...)
1398 {
1399 	struct bpf_verifier_log *log = &env->log;
1400 	struct btf *btf = env->btf;
1401 	va_list args;
1402 
1403 	if (!bpf_verifier_log_needed(log))
1404 		return;
1405 
1406 	if (log->level == BPF_LOG_KERNEL) {
1407 		/* btf verifier prints all types it is processing via
1408 		 * btf_verifier_log_type(..., fmt = NULL).
1409 		 * Skip those prints for in-kernel BTF verification.
1410 		 */
1411 		if (!fmt)
1412 			return;
1413 
1414 		/* Skip logging when loading module BTF with mismatches permitted */
1415 		if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1416 			return;
1417 	}
1418 
1419 	__btf_verifier_log(log, "[%u] %s %s%s",
1420 			   env->log_type_id,
1421 			   btf_type_str(t),
1422 			   __btf_name_by_offset(btf, t->name_off),
1423 			   log_details ? " " : "");
1424 
1425 	if (log_details)
1426 		btf_type_ops(t)->log_details(env, t);
1427 
1428 	if (fmt && *fmt) {
1429 		__btf_verifier_log(log, " ");
1430 		va_start(args, fmt);
1431 		bpf_verifier_vlog(log, fmt, args);
1432 		va_end(args);
1433 	}
1434 
1435 	__btf_verifier_log(log, "\n");
1436 }
1437 
1438 #define btf_verifier_log_type(env, t, ...) \
1439 	__btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1440 #define btf_verifier_log_basic(env, t, ...) \
1441 	__btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1442 
1443 __printf(4, 5)
1444 static void btf_verifier_log_member(struct btf_verifier_env *env,
1445 				    const struct btf_type *struct_type,
1446 				    const struct btf_member *member,
1447 				    const char *fmt, ...)
1448 {
1449 	struct bpf_verifier_log *log = &env->log;
1450 	struct btf *btf = env->btf;
1451 	va_list args;
1452 
1453 	if (!bpf_verifier_log_needed(log))
1454 		return;
1455 
1456 	if (log->level == BPF_LOG_KERNEL) {
1457 		if (!fmt)
1458 			return;
1459 
1460 		/* Skip logging when loading module BTF with mismatches permitted */
1461 		if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1462 			return;
1463 	}
1464 
1465 	/* The CHECK_META phase already did a btf dump.
1466 	 *
1467 	 * If member is logged again, it must hit an error in
1468 	 * parsing this member.  It is useful to print out which
1469 	 * struct this member belongs to.
1470 	 */
1471 	if (env->phase != CHECK_META)
1472 		btf_verifier_log_type(env, struct_type, NULL);
1473 
1474 	if (btf_type_kflag(struct_type))
1475 		__btf_verifier_log(log,
1476 				   "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1477 				   __btf_name_by_offset(btf, member->name_off),
1478 				   member->type,
1479 				   BTF_MEMBER_BITFIELD_SIZE(member->offset),
1480 				   BTF_MEMBER_BIT_OFFSET(member->offset));
1481 	else
1482 		__btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1483 				   __btf_name_by_offset(btf, member->name_off),
1484 				   member->type, member->offset);
1485 
1486 	if (fmt && *fmt) {
1487 		__btf_verifier_log(log, " ");
1488 		va_start(args, fmt);
1489 		bpf_verifier_vlog(log, fmt, args);
1490 		va_end(args);
1491 	}
1492 
1493 	__btf_verifier_log(log, "\n");
1494 }
1495 
1496 __printf(4, 5)
1497 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1498 				 const struct btf_type *datasec_type,
1499 				 const struct btf_var_secinfo *vsi,
1500 				 const char *fmt, ...)
1501 {
1502 	struct bpf_verifier_log *log = &env->log;
1503 	va_list args;
1504 
1505 	if (!bpf_verifier_log_needed(log))
1506 		return;
1507 	if (log->level == BPF_LOG_KERNEL && !fmt)
1508 		return;
1509 	if (env->phase != CHECK_META)
1510 		btf_verifier_log_type(env, datasec_type, NULL);
1511 
1512 	__btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1513 			   vsi->type, vsi->offset, vsi->size);
1514 	if (fmt && *fmt) {
1515 		__btf_verifier_log(log, " ");
1516 		va_start(args, fmt);
1517 		bpf_verifier_vlog(log, fmt, args);
1518 		va_end(args);
1519 	}
1520 
1521 	__btf_verifier_log(log, "\n");
1522 }
1523 
1524 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1525 				 u32 btf_data_size)
1526 {
1527 	struct bpf_verifier_log *log = &env->log;
1528 	const struct btf *btf = env->btf;
1529 	const struct btf_header *hdr;
1530 
1531 	if (!bpf_verifier_log_needed(log))
1532 		return;
1533 
1534 	if (log->level == BPF_LOG_KERNEL)
1535 		return;
1536 	hdr = &btf->hdr;
1537 	__btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1538 	__btf_verifier_log(log, "version: %u\n", hdr->version);
1539 	__btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1540 	__btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1541 	__btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1542 	__btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1543 	__btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1544 	__btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1545 	__btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1546 }
1547 
1548 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1549 {
1550 	struct btf *btf = env->btf;
1551 
1552 	if (btf->types_size == btf->nr_types) {
1553 		/* Expand 'types' array */
1554 
1555 		struct btf_type **new_types;
1556 		u32 expand_by, new_size;
1557 
1558 		if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1559 			btf_verifier_log(env, "Exceeded max num of types");
1560 			return -E2BIG;
1561 		}
1562 
1563 		expand_by = max_t(u32, btf->types_size >> 2, 16);
1564 		new_size = min_t(u32, BTF_MAX_TYPE,
1565 				 btf->types_size + expand_by);
1566 
1567 		new_types = kvcalloc(new_size, sizeof(*new_types),
1568 				     GFP_KERNEL | __GFP_NOWARN);
1569 		if (!new_types)
1570 			return -ENOMEM;
1571 
1572 		if (btf->nr_types == 0) {
1573 			if (!btf->base_btf) {
1574 				/* lazily init VOID type */
1575 				new_types[0] = &btf_void;
1576 				btf->nr_types++;
1577 			}
1578 		} else {
1579 			memcpy(new_types, btf->types,
1580 			       sizeof(*btf->types) * btf->nr_types);
1581 		}
1582 
1583 		kvfree(btf->types);
1584 		btf->types = new_types;
1585 		btf->types_size = new_size;
1586 	}
1587 
1588 	btf->types[btf->nr_types++] = t;
1589 
1590 	return 0;
1591 }
1592 
1593 static int btf_alloc_id(struct btf *btf)
1594 {
1595 	int id;
1596 
1597 	idr_preload(GFP_KERNEL);
1598 	spin_lock_bh(&btf_idr_lock);
1599 	id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1600 	if (id > 0)
1601 		btf->id = id;
1602 	spin_unlock_bh(&btf_idr_lock);
1603 	idr_preload_end();
1604 
1605 	if (WARN_ON_ONCE(!id))
1606 		return -ENOSPC;
1607 
1608 	return id > 0 ? 0 : id;
1609 }
1610 
1611 static void btf_free_id(struct btf *btf)
1612 {
1613 	unsigned long flags;
1614 
1615 	/*
1616 	 * In map-in-map, calling map_delete_elem() on outer
1617 	 * map will call bpf_map_put on the inner map.
1618 	 * It will then eventually call btf_free_id()
1619 	 * on the inner map.  Some of the map_delete_elem()
1620 	 * implementation may have irq disabled, so
1621 	 * we need to use the _irqsave() version instead
1622 	 * of the _bh() version.
1623 	 */
1624 	spin_lock_irqsave(&btf_idr_lock, flags);
1625 	idr_remove(&btf_idr, btf->id);
1626 	spin_unlock_irqrestore(&btf_idr_lock, flags);
1627 }
1628 
1629 static void btf_free_kfunc_set_tab(struct btf *btf)
1630 {
1631 	struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1632 	int hook;
1633 
1634 	if (!tab)
1635 		return;
1636 	/* For module BTF, we directly assign the sets being registered, so
1637 	 * there is nothing to free except kfunc_set_tab.
1638 	 */
1639 	if (btf_is_module(btf))
1640 		goto free_tab;
1641 	for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1642 		kfree(tab->sets[hook]);
1643 free_tab:
1644 	kfree(tab);
1645 	btf->kfunc_set_tab = NULL;
1646 }
1647 
1648 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1649 {
1650 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1651 
1652 	if (!tab)
1653 		return;
1654 	kfree(tab);
1655 	btf->dtor_kfunc_tab = NULL;
1656 }
1657 
1658 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1659 {
1660 	int i;
1661 
1662 	if (!tab)
1663 		return;
1664 	for (i = 0; i < tab->cnt; i++) {
1665 		btf_record_free(tab->types[i].record);
1666 		kfree(tab->types[i].field_offs);
1667 	}
1668 	kfree(tab);
1669 }
1670 
1671 static void btf_free_struct_meta_tab(struct btf *btf)
1672 {
1673 	struct btf_struct_metas *tab = btf->struct_meta_tab;
1674 
1675 	btf_struct_metas_free(tab);
1676 	btf->struct_meta_tab = NULL;
1677 }
1678 
1679 static void btf_free(struct btf *btf)
1680 {
1681 	btf_free_struct_meta_tab(btf);
1682 	btf_free_dtor_kfunc_tab(btf);
1683 	btf_free_kfunc_set_tab(btf);
1684 	kvfree(btf->types);
1685 	kvfree(btf->resolved_sizes);
1686 	kvfree(btf->resolved_ids);
1687 	kvfree(btf->data);
1688 	kfree(btf);
1689 }
1690 
1691 static void btf_free_rcu(struct rcu_head *rcu)
1692 {
1693 	struct btf *btf = container_of(rcu, struct btf, rcu);
1694 
1695 	btf_free(btf);
1696 }
1697 
1698 void btf_get(struct btf *btf)
1699 {
1700 	refcount_inc(&btf->refcnt);
1701 }
1702 
1703 void btf_put(struct btf *btf)
1704 {
1705 	if (btf && refcount_dec_and_test(&btf->refcnt)) {
1706 		btf_free_id(btf);
1707 		call_rcu(&btf->rcu, btf_free_rcu);
1708 	}
1709 }
1710 
1711 static int env_resolve_init(struct btf_verifier_env *env)
1712 {
1713 	struct btf *btf = env->btf;
1714 	u32 nr_types = btf->nr_types;
1715 	u32 *resolved_sizes = NULL;
1716 	u32 *resolved_ids = NULL;
1717 	u8 *visit_states = NULL;
1718 
1719 	resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1720 				  GFP_KERNEL | __GFP_NOWARN);
1721 	if (!resolved_sizes)
1722 		goto nomem;
1723 
1724 	resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1725 				GFP_KERNEL | __GFP_NOWARN);
1726 	if (!resolved_ids)
1727 		goto nomem;
1728 
1729 	visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1730 				GFP_KERNEL | __GFP_NOWARN);
1731 	if (!visit_states)
1732 		goto nomem;
1733 
1734 	btf->resolved_sizes = resolved_sizes;
1735 	btf->resolved_ids = resolved_ids;
1736 	env->visit_states = visit_states;
1737 
1738 	return 0;
1739 
1740 nomem:
1741 	kvfree(resolved_sizes);
1742 	kvfree(resolved_ids);
1743 	kvfree(visit_states);
1744 	return -ENOMEM;
1745 }
1746 
1747 static void btf_verifier_env_free(struct btf_verifier_env *env)
1748 {
1749 	kvfree(env->visit_states);
1750 	kfree(env);
1751 }
1752 
1753 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1754 				     const struct btf_type *next_type)
1755 {
1756 	switch (env->resolve_mode) {
1757 	case RESOLVE_TBD:
1758 		/* int, enum or void is a sink */
1759 		return !btf_type_needs_resolve(next_type);
1760 	case RESOLVE_PTR:
1761 		/* int, enum, void, struct, array, func or func_proto is a sink
1762 		 * for ptr
1763 		 */
1764 		return !btf_type_is_modifier(next_type) &&
1765 			!btf_type_is_ptr(next_type);
1766 	case RESOLVE_STRUCT_OR_ARRAY:
1767 		/* int, enum, void, ptr, func or func_proto is a sink
1768 		 * for struct and array
1769 		 */
1770 		return !btf_type_is_modifier(next_type) &&
1771 			!btf_type_is_array(next_type) &&
1772 			!btf_type_is_struct(next_type);
1773 	default:
1774 		BUG();
1775 	}
1776 }
1777 
1778 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1779 				 u32 type_id)
1780 {
1781 	/* base BTF types should be resolved by now */
1782 	if (type_id < env->btf->start_id)
1783 		return true;
1784 
1785 	return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1786 }
1787 
1788 static int env_stack_push(struct btf_verifier_env *env,
1789 			  const struct btf_type *t, u32 type_id)
1790 {
1791 	const struct btf *btf = env->btf;
1792 	struct resolve_vertex *v;
1793 
1794 	if (env->top_stack == MAX_RESOLVE_DEPTH)
1795 		return -E2BIG;
1796 
1797 	if (type_id < btf->start_id
1798 	    || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1799 		return -EEXIST;
1800 
1801 	env->visit_states[type_id - btf->start_id] = VISITED;
1802 
1803 	v = &env->stack[env->top_stack++];
1804 	v->t = t;
1805 	v->type_id = type_id;
1806 	v->next_member = 0;
1807 
1808 	if (env->resolve_mode == RESOLVE_TBD) {
1809 		if (btf_type_is_ptr(t))
1810 			env->resolve_mode = RESOLVE_PTR;
1811 		else if (btf_type_is_struct(t) || btf_type_is_array(t))
1812 			env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1813 	}
1814 
1815 	return 0;
1816 }
1817 
1818 static void env_stack_set_next_member(struct btf_verifier_env *env,
1819 				      u16 next_member)
1820 {
1821 	env->stack[env->top_stack - 1].next_member = next_member;
1822 }
1823 
1824 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1825 				   u32 resolved_type_id,
1826 				   u32 resolved_size)
1827 {
1828 	u32 type_id = env->stack[--(env->top_stack)].type_id;
1829 	struct btf *btf = env->btf;
1830 
1831 	type_id -= btf->start_id; /* adjust to local type id */
1832 	btf->resolved_sizes[type_id] = resolved_size;
1833 	btf->resolved_ids[type_id] = resolved_type_id;
1834 	env->visit_states[type_id] = RESOLVED;
1835 }
1836 
1837 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1838 {
1839 	return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1840 }
1841 
1842 /* Resolve the size of a passed-in "type"
1843  *
1844  * type: is an array (e.g. u32 array[x][y])
1845  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1846  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
1847  *             corresponds to the return type.
1848  * *elem_type: u32
1849  * *elem_id: id of u32
1850  * *total_nelems: (x * y).  Hence, individual elem size is
1851  *                (*type_size / *total_nelems)
1852  * *type_id: id of type if it's changed within the function, 0 if not
1853  *
1854  * type: is not an array (e.g. const struct X)
1855  * return type: type "struct X"
1856  * *type_size: sizeof(struct X)
1857  * *elem_type: same as return type ("struct X")
1858  * *elem_id: 0
1859  * *total_nelems: 1
1860  * *type_id: id of type if it's changed within the function, 0 if not
1861  */
1862 static const struct btf_type *
1863 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1864 		   u32 *type_size, const struct btf_type **elem_type,
1865 		   u32 *elem_id, u32 *total_nelems, u32 *type_id)
1866 {
1867 	const struct btf_type *array_type = NULL;
1868 	const struct btf_array *array = NULL;
1869 	u32 i, size, nelems = 1, id = 0;
1870 
1871 	for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1872 		switch (BTF_INFO_KIND(type->info)) {
1873 		/* type->size can be used */
1874 		case BTF_KIND_INT:
1875 		case BTF_KIND_STRUCT:
1876 		case BTF_KIND_UNION:
1877 		case BTF_KIND_ENUM:
1878 		case BTF_KIND_FLOAT:
1879 		case BTF_KIND_ENUM64:
1880 			size = type->size;
1881 			goto resolved;
1882 
1883 		case BTF_KIND_PTR:
1884 			size = sizeof(void *);
1885 			goto resolved;
1886 
1887 		/* Modifiers */
1888 		case BTF_KIND_TYPEDEF:
1889 		case BTF_KIND_VOLATILE:
1890 		case BTF_KIND_CONST:
1891 		case BTF_KIND_RESTRICT:
1892 		case BTF_KIND_TYPE_TAG:
1893 			id = type->type;
1894 			type = btf_type_by_id(btf, type->type);
1895 			break;
1896 
1897 		case BTF_KIND_ARRAY:
1898 			if (!array_type)
1899 				array_type = type;
1900 			array = btf_type_array(type);
1901 			if (nelems && array->nelems > U32_MAX / nelems)
1902 				return ERR_PTR(-EINVAL);
1903 			nelems *= array->nelems;
1904 			type = btf_type_by_id(btf, array->type);
1905 			break;
1906 
1907 		/* type without size */
1908 		default:
1909 			return ERR_PTR(-EINVAL);
1910 		}
1911 	}
1912 
1913 	return ERR_PTR(-EINVAL);
1914 
1915 resolved:
1916 	if (nelems && size > U32_MAX / nelems)
1917 		return ERR_PTR(-EINVAL);
1918 
1919 	*type_size = nelems * size;
1920 	if (total_nelems)
1921 		*total_nelems = nelems;
1922 	if (elem_type)
1923 		*elem_type = type;
1924 	if (elem_id)
1925 		*elem_id = array ? array->type : 0;
1926 	if (type_id && id)
1927 		*type_id = id;
1928 
1929 	return array_type ? : type;
1930 }
1931 
1932 const struct btf_type *
1933 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1934 		 u32 *type_size)
1935 {
1936 	return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1937 }
1938 
1939 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1940 {
1941 	while (type_id < btf->start_id)
1942 		btf = btf->base_btf;
1943 
1944 	return btf->resolved_ids[type_id - btf->start_id];
1945 }
1946 
1947 /* The input param "type_id" must point to a needs_resolve type */
1948 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1949 						  u32 *type_id)
1950 {
1951 	*type_id = btf_resolved_type_id(btf, *type_id);
1952 	return btf_type_by_id(btf, *type_id);
1953 }
1954 
1955 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1956 {
1957 	while (type_id < btf->start_id)
1958 		btf = btf->base_btf;
1959 
1960 	return btf->resolved_sizes[type_id - btf->start_id];
1961 }
1962 
1963 const struct btf_type *btf_type_id_size(const struct btf *btf,
1964 					u32 *type_id, u32 *ret_size)
1965 {
1966 	const struct btf_type *size_type;
1967 	u32 size_type_id = *type_id;
1968 	u32 size = 0;
1969 
1970 	size_type = btf_type_by_id(btf, size_type_id);
1971 	if (btf_type_nosize_or_null(size_type))
1972 		return NULL;
1973 
1974 	if (btf_type_has_size(size_type)) {
1975 		size = size_type->size;
1976 	} else if (btf_type_is_array(size_type)) {
1977 		size = btf_resolved_type_size(btf, size_type_id);
1978 	} else if (btf_type_is_ptr(size_type)) {
1979 		size = sizeof(void *);
1980 	} else {
1981 		if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1982 				 !btf_type_is_var(size_type)))
1983 			return NULL;
1984 
1985 		size_type_id = btf_resolved_type_id(btf, size_type_id);
1986 		size_type = btf_type_by_id(btf, size_type_id);
1987 		if (btf_type_nosize_or_null(size_type))
1988 			return NULL;
1989 		else if (btf_type_has_size(size_type))
1990 			size = size_type->size;
1991 		else if (btf_type_is_array(size_type))
1992 			size = btf_resolved_type_size(btf, size_type_id);
1993 		else if (btf_type_is_ptr(size_type))
1994 			size = sizeof(void *);
1995 		else
1996 			return NULL;
1997 	}
1998 
1999 	*type_id = size_type_id;
2000 	if (ret_size)
2001 		*ret_size = size;
2002 
2003 	return size_type;
2004 }
2005 
2006 static int btf_df_check_member(struct btf_verifier_env *env,
2007 			       const struct btf_type *struct_type,
2008 			       const struct btf_member *member,
2009 			       const struct btf_type *member_type)
2010 {
2011 	btf_verifier_log_basic(env, struct_type,
2012 			       "Unsupported check_member");
2013 	return -EINVAL;
2014 }
2015 
2016 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2017 				     const struct btf_type *struct_type,
2018 				     const struct btf_member *member,
2019 				     const struct btf_type *member_type)
2020 {
2021 	btf_verifier_log_basic(env, struct_type,
2022 			       "Unsupported check_kflag_member");
2023 	return -EINVAL;
2024 }
2025 
2026 /* Used for ptr, array struct/union and float type members.
2027  * int, enum and modifier types have their specific callback functions.
2028  */
2029 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2030 					  const struct btf_type *struct_type,
2031 					  const struct btf_member *member,
2032 					  const struct btf_type *member_type)
2033 {
2034 	if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2035 		btf_verifier_log_member(env, struct_type, member,
2036 					"Invalid member bitfield_size");
2037 		return -EINVAL;
2038 	}
2039 
2040 	/* bitfield size is 0, so member->offset represents bit offset only.
2041 	 * It is safe to call non kflag check_member variants.
2042 	 */
2043 	return btf_type_ops(member_type)->check_member(env, struct_type,
2044 						       member,
2045 						       member_type);
2046 }
2047 
2048 static int btf_df_resolve(struct btf_verifier_env *env,
2049 			  const struct resolve_vertex *v)
2050 {
2051 	btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2052 	return -EINVAL;
2053 }
2054 
2055 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2056 			u32 type_id, void *data, u8 bits_offsets,
2057 			struct btf_show *show)
2058 {
2059 	btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2060 }
2061 
2062 static int btf_int_check_member(struct btf_verifier_env *env,
2063 				const struct btf_type *struct_type,
2064 				const struct btf_member *member,
2065 				const struct btf_type *member_type)
2066 {
2067 	u32 int_data = btf_type_int(member_type);
2068 	u32 struct_bits_off = member->offset;
2069 	u32 struct_size = struct_type->size;
2070 	u32 nr_copy_bits;
2071 	u32 bytes_offset;
2072 
2073 	if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2074 		btf_verifier_log_member(env, struct_type, member,
2075 					"bits_offset exceeds U32_MAX");
2076 		return -EINVAL;
2077 	}
2078 
2079 	struct_bits_off += BTF_INT_OFFSET(int_data);
2080 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2081 	nr_copy_bits = BTF_INT_BITS(int_data) +
2082 		BITS_PER_BYTE_MASKED(struct_bits_off);
2083 
2084 	if (nr_copy_bits > BITS_PER_U128) {
2085 		btf_verifier_log_member(env, struct_type, member,
2086 					"nr_copy_bits exceeds 128");
2087 		return -EINVAL;
2088 	}
2089 
2090 	if (struct_size < bytes_offset ||
2091 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2092 		btf_verifier_log_member(env, struct_type, member,
2093 					"Member exceeds struct_size");
2094 		return -EINVAL;
2095 	}
2096 
2097 	return 0;
2098 }
2099 
2100 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2101 				      const struct btf_type *struct_type,
2102 				      const struct btf_member *member,
2103 				      const struct btf_type *member_type)
2104 {
2105 	u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2106 	u32 int_data = btf_type_int(member_type);
2107 	u32 struct_size = struct_type->size;
2108 	u32 nr_copy_bits;
2109 
2110 	/* a regular int type is required for the kflag int member */
2111 	if (!btf_type_int_is_regular(member_type)) {
2112 		btf_verifier_log_member(env, struct_type, member,
2113 					"Invalid member base type");
2114 		return -EINVAL;
2115 	}
2116 
2117 	/* check sanity of bitfield size */
2118 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2119 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2120 	nr_int_data_bits = BTF_INT_BITS(int_data);
2121 	if (!nr_bits) {
2122 		/* Not a bitfield member, member offset must be at byte
2123 		 * boundary.
2124 		 */
2125 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2126 			btf_verifier_log_member(env, struct_type, member,
2127 						"Invalid member offset");
2128 			return -EINVAL;
2129 		}
2130 
2131 		nr_bits = nr_int_data_bits;
2132 	} else if (nr_bits > nr_int_data_bits) {
2133 		btf_verifier_log_member(env, struct_type, member,
2134 					"Invalid member bitfield_size");
2135 		return -EINVAL;
2136 	}
2137 
2138 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2139 	nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2140 	if (nr_copy_bits > BITS_PER_U128) {
2141 		btf_verifier_log_member(env, struct_type, member,
2142 					"nr_copy_bits exceeds 128");
2143 		return -EINVAL;
2144 	}
2145 
2146 	if (struct_size < bytes_offset ||
2147 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2148 		btf_verifier_log_member(env, struct_type, member,
2149 					"Member exceeds struct_size");
2150 		return -EINVAL;
2151 	}
2152 
2153 	return 0;
2154 }
2155 
2156 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2157 			      const struct btf_type *t,
2158 			      u32 meta_left)
2159 {
2160 	u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2161 	u16 encoding;
2162 
2163 	if (meta_left < meta_needed) {
2164 		btf_verifier_log_basic(env, t,
2165 				       "meta_left:%u meta_needed:%u",
2166 				       meta_left, meta_needed);
2167 		return -EINVAL;
2168 	}
2169 
2170 	if (btf_type_vlen(t)) {
2171 		btf_verifier_log_type(env, t, "vlen != 0");
2172 		return -EINVAL;
2173 	}
2174 
2175 	if (btf_type_kflag(t)) {
2176 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2177 		return -EINVAL;
2178 	}
2179 
2180 	int_data = btf_type_int(t);
2181 	if (int_data & ~BTF_INT_MASK) {
2182 		btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2183 				       int_data);
2184 		return -EINVAL;
2185 	}
2186 
2187 	nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2188 
2189 	if (nr_bits > BITS_PER_U128) {
2190 		btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2191 				      BITS_PER_U128);
2192 		return -EINVAL;
2193 	}
2194 
2195 	if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2196 		btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2197 		return -EINVAL;
2198 	}
2199 
2200 	/*
2201 	 * Only one of the encoding bits is allowed and it
2202 	 * should be sufficient for the pretty print purpose (i.e. decoding).
2203 	 * Multiple bits can be allowed later if it is found
2204 	 * to be insufficient.
2205 	 */
2206 	encoding = BTF_INT_ENCODING(int_data);
2207 	if (encoding &&
2208 	    encoding != BTF_INT_SIGNED &&
2209 	    encoding != BTF_INT_CHAR &&
2210 	    encoding != BTF_INT_BOOL) {
2211 		btf_verifier_log_type(env, t, "Unsupported encoding");
2212 		return -ENOTSUPP;
2213 	}
2214 
2215 	btf_verifier_log_type(env, t, NULL);
2216 
2217 	return meta_needed;
2218 }
2219 
2220 static void btf_int_log(struct btf_verifier_env *env,
2221 			const struct btf_type *t)
2222 {
2223 	int int_data = btf_type_int(t);
2224 
2225 	btf_verifier_log(env,
2226 			 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2227 			 t->size, BTF_INT_OFFSET(int_data),
2228 			 BTF_INT_BITS(int_data),
2229 			 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2230 }
2231 
2232 static void btf_int128_print(struct btf_show *show, void *data)
2233 {
2234 	/* data points to a __int128 number.
2235 	 * Suppose
2236 	 *     int128_num = *(__int128 *)data;
2237 	 * The below formulas shows what upper_num and lower_num represents:
2238 	 *     upper_num = int128_num >> 64;
2239 	 *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2240 	 */
2241 	u64 upper_num, lower_num;
2242 
2243 #ifdef __BIG_ENDIAN_BITFIELD
2244 	upper_num = *(u64 *)data;
2245 	lower_num = *(u64 *)(data + 8);
2246 #else
2247 	upper_num = *(u64 *)(data + 8);
2248 	lower_num = *(u64 *)data;
2249 #endif
2250 	if (upper_num == 0)
2251 		btf_show_type_value(show, "0x%llx", lower_num);
2252 	else
2253 		btf_show_type_values(show, "0x%llx%016llx", upper_num,
2254 				     lower_num);
2255 }
2256 
2257 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2258 			     u16 right_shift_bits)
2259 {
2260 	u64 upper_num, lower_num;
2261 
2262 #ifdef __BIG_ENDIAN_BITFIELD
2263 	upper_num = print_num[0];
2264 	lower_num = print_num[1];
2265 #else
2266 	upper_num = print_num[1];
2267 	lower_num = print_num[0];
2268 #endif
2269 
2270 	/* shake out un-needed bits by shift/or operations */
2271 	if (left_shift_bits >= 64) {
2272 		upper_num = lower_num << (left_shift_bits - 64);
2273 		lower_num = 0;
2274 	} else {
2275 		upper_num = (upper_num << left_shift_bits) |
2276 			    (lower_num >> (64 - left_shift_bits));
2277 		lower_num = lower_num << left_shift_bits;
2278 	}
2279 
2280 	if (right_shift_bits >= 64) {
2281 		lower_num = upper_num >> (right_shift_bits - 64);
2282 		upper_num = 0;
2283 	} else {
2284 		lower_num = (lower_num >> right_shift_bits) |
2285 			    (upper_num << (64 - right_shift_bits));
2286 		upper_num = upper_num >> right_shift_bits;
2287 	}
2288 
2289 #ifdef __BIG_ENDIAN_BITFIELD
2290 	print_num[0] = upper_num;
2291 	print_num[1] = lower_num;
2292 #else
2293 	print_num[0] = lower_num;
2294 	print_num[1] = upper_num;
2295 #endif
2296 }
2297 
2298 static void btf_bitfield_show(void *data, u8 bits_offset,
2299 			      u8 nr_bits, struct btf_show *show)
2300 {
2301 	u16 left_shift_bits, right_shift_bits;
2302 	u8 nr_copy_bytes;
2303 	u8 nr_copy_bits;
2304 	u64 print_num[2] = {};
2305 
2306 	nr_copy_bits = nr_bits + bits_offset;
2307 	nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2308 
2309 	memcpy(print_num, data, nr_copy_bytes);
2310 
2311 #ifdef __BIG_ENDIAN_BITFIELD
2312 	left_shift_bits = bits_offset;
2313 #else
2314 	left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2315 #endif
2316 	right_shift_bits = BITS_PER_U128 - nr_bits;
2317 
2318 	btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2319 	btf_int128_print(show, print_num);
2320 }
2321 
2322 
2323 static void btf_int_bits_show(const struct btf *btf,
2324 			      const struct btf_type *t,
2325 			      void *data, u8 bits_offset,
2326 			      struct btf_show *show)
2327 {
2328 	u32 int_data = btf_type_int(t);
2329 	u8 nr_bits = BTF_INT_BITS(int_data);
2330 	u8 total_bits_offset;
2331 
2332 	/*
2333 	 * bits_offset is at most 7.
2334 	 * BTF_INT_OFFSET() cannot exceed 128 bits.
2335 	 */
2336 	total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2337 	data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2338 	bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2339 	btf_bitfield_show(data, bits_offset, nr_bits, show);
2340 }
2341 
2342 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2343 			 u32 type_id, void *data, u8 bits_offset,
2344 			 struct btf_show *show)
2345 {
2346 	u32 int_data = btf_type_int(t);
2347 	u8 encoding = BTF_INT_ENCODING(int_data);
2348 	bool sign = encoding & BTF_INT_SIGNED;
2349 	u8 nr_bits = BTF_INT_BITS(int_data);
2350 	void *safe_data;
2351 
2352 	safe_data = btf_show_start_type(show, t, type_id, data);
2353 	if (!safe_data)
2354 		return;
2355 
2356 	if (bits_offset || BTF_INT_OFFSET(int_data) ||
2357 	    BITS_PER_BYTE_MASKED(nr_bits)) {
2358 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2359 		goto out;
2360 	}
2361 
2362 	switch (nr_bits) {
2363 	case 128:
2364 		btf_int128_print(show, safe_data);
2365 		break;
2366 	case 64:
2367 		if (sign)
2368 			btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2369 		else
2370 			btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2371 		break;
2372 	case 32:
2373 		if (sign)
2374 			btf_show_type_value(show, "%d", *(s32 *)safe_data);
2375 		else
2376 			btf_show_type_value(show, "%u", *(u32 *)safe_data);
2377 		break;
2378 	case 16:
2379 		if (sign)
2380 			btf_show_type_value(show, "%d", *(s16 *)safe_data);
2381 		else
2382 			btf_show_type_value(show, "%u", *(u16 *)safe_data);
2383 		break;
2384 	case 8:
2385 		if (show->state.array_encoding == BTF_INT_CHAR) {
2386 			/* check for null terminator */
2387 			if (show->state.array_terminated)
2388 				break;
2389 			if (*(char *)data == '\0') {
2390 				show->state.array_terminated = 1;
2391 				break;
2392 			}
2393 			if (isprint(*(char *)data)) {
2394 				btf_show_type_value(show, "'%c'",
2395 						    *(char *)safe_data);
2396 				break;
2397 			}
2398 		}
2399 		if (sign)
2400 			btf_show_type_value(show, "%d", *(s8 *)safe_data);
2401 		else
2402 			btf_show_type_value(show, "%u", *(u8 *)safe_data);
2403 		break;
2404 	default:
2405 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2406 		break;
2407 	}
2408 out:
2409 	btf_show_end_type(show);
2410 }
2411 
2412 static const struct btf_kind_operations int_ops = {
2413 	.check_meta = btf_int_check_meta,
2414 	.resolve = btf_df_resolve,
2415 	.check_member = btf_int_check_member,
2416 	.check_kflag_member = btf_int_check_kflag_member,
2417 	.log_details = btf_int_log,
2418 	.show = btf_int_show,
2419 };
2420 
2421 static int btf_modifier_check_member(struct btf_verifier_env *env,
2422 				     const struct btf_type *struct_type,
2423 				     const struct btf_member *member,
2424 				     const struct btf_type *member_type)
2425 {
2426 	const struct btf_type *resolved_type;
2427 	u32 resolved_type_id = member->type;
2428 	struct btf_member resolved_member;
2429 	struct btf *btf = env->btf;
2430 
2431 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2432 	if (!resolved_type) {
2433 		btf_verifier_log_member(env, struct_type, member,
2434 					"Invalid member");
2435 		return -EINVAL;
2436 	}
2437 
2438 	resolved_member = *member;
2439 	resolved_member.type = resolved_type_id;
2440 
2441 	return btf_type_ops(resolved_type)->check_member(env, struct_type,
2442 							 &resolved_member,
2443 							 resolved_type);
2444 }
2445 
2446 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2447 					   const struct btf_type *struct_type,
2448 					   const struct btf_member *member,
2449 					   const struct btf_type *member_type)
2450 {
2451 	const struct btf_type *resolved_type;
2452 	u32 resolved_type_id = member->type;
2453 	struct btf_member resolved_member;
2454 	struct btf *btf = env->btf;
2455 
2456 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2457 	if (!resolved_type) {
2458 		btf_verifier_log_member(env, struct_type, member,
2459 					"Invalid member");
2460 		return -EINVAL;
2461 	}
2462 
2463 	resolved_member = *member;
2464 	resolved_member.type = resolved_type_id;
2465 
2466 	return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2467 							       &resolved_member,
2468 							       resolved_type);
2469 }
2470 
2471 static int btf_ptr_check_member(struct btf_verifier_env *env,
2472 				const struct btf_type *struct_type,
2473 				const struct btf_member *member,
2474 				const struct btf_type *member_type)
2475 {
2476 	u32 struct_size, struct_bits_off, bytes_offset;
2477 
2478 	struct_size = struct_type->size;
2479 	struct_bits_off = member->offset;
2480 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2481 
2482 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2483 		btf_verifier_log_member(env, struct_type, member,
2484 					"Member is not byte aligned");
2485 		return -EINVAL;
2486 	}
2487 
2488 	if (struct_size - bytes_offset < sizeof(void *)) {
2489 		btf_verifier_log_member(env, struct_type, member,
2490 					"Member exceeds struct_size");
2491 		return -EINVAL;
2492 	}
2493 
2494 	return 0;
2495 }
2496 
2497 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2498 				   const struct btf_type *t,
2499 				   u32 meta_left)
2500 {
2501 	const char *value;
2502 
2503 	if (btf_type_vlen(t)) {
2504 		btf_verifier_log_type(env, t, "vlen != 0");
2505 		return -EINVAL;
2506 	}
2507 
2508 	if (btf_type_kflag(t)) {
2509 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2510 		return -EINVAL;
2511 	}
2512 
2513 	if (!BTF_TYPE_ID_VALID(t->type)) {
2514 		btf_verifier_log_type(env, t, "Invalid type_id");
2515 		return -EINVAL;
2516 	}
2517 
2518 	/* typedef/type_tag type must have a valid name, and other ref types,
2519 	 * volatile, const, restrict, should have a null name.
2520 	 */
2521 	if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2522 		if (!t->name_off ||
2523 		    !btf_name_valid_identifier(env->btf, t->name_off)) {
2524 			btf_verifier_log_type(env, t, "Invalid name");
2525 			return -EINVAL;
2526 		}
2527 	} else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2528 		value = btf_name_by_offset(env->btf, t->name_off);
2529 		if (!value || !value[0]) {
2530 			btf_verifier_log_type(env, t, "Invalid name");
2531 			return -EINVAL;
2532 		}
2533 	} else {
2534 		if (t->name_off) {
2535 			btf_verifier_log_type(env, t, "Invalid name");
2536 			return -EINVAL;
2537 		}
2538 	}
2539 
2540 	btf_verifier_log_type(env, t, NULL);
2541 
2542 	return 0;
2543 }
2544 
2545 static int btf_modifier_resolve(struct btf_verifier_env *env,
2546 				const struct resolve_vertex *v)
2547 {
2548 	const struct btf_type *t = v->t;
2549 	const struct btf_type *next_type;
2550 	u32 next_type_id = t->type;
2551 	struct btf *btf = env->btf;
2552 
2553 	next_type = btf_type_by_id(btf, next_type_id);
2554 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2555 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2556 		return -EINVAL;
2557 	}
2558 
2559 	if (!env_type_is_resolve_sink(env, next_type) &&
2560 	    !env_type_is_resolved(env, next_type_id))
2561 		return env_stack_push(env, next_type, next_type_id);
2562 
2563 	/* Figure out the resolved next_type_id with size.
2564 	 * They will be stored in the current modifier's
2565 	 * resolved_ids and resolved_sizes such that it can
2566 	 * save us a few type-following when we use it later (e.g. in
2567 	 * pretty print).
2568 	 */
2569 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2570 		if (env_type_is_resolved(env, next_type_id))
2571 			next_type = btf_type_id_resolve(btf, &next_type_id);
2572 
2573 		/* "typedef void new_void", "const void"...etc */
2574 		if (!btf_type_is_void(next_type) &&
2575 		    !btf_type_is_fwd(next_type) &&
2576 		    !btf_type_is_func_proto(next_type)) {
2577 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2578 			return -EINVAL;
2579 		}
2580 	}
2581 
2582 	env_stack_pop_resolved(env, next_type_id, 0);
2583 
2584 	return 0;
2585 }
2586 
2587 static int btf_var_resolve(struct btf_verifier_env *env,
2588 			   const struct resolve_vertex *v)
2589 {
2590 	const struct btf_type *next_type;
2591 	const struct btf_type *t = v->t;
2592 	u32 next_type_id = t->type;
2593 	struct btf *btf = env->btf;
2594 
2595 	next_type = btf_type_by_id(btf, next_type_id);
2596 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2597 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2598 		return -EINVAL;
2599 	}
2600 
2601 	if (!env_type_is_resolve_sink(env, next_type) &&
2602 	    !env_type_is_resolved(env, next_type_id))
2603 		return env_stack_push(env, next_type, next_type_id);
2604 
2605 	if (btf_type_is_modifier(next_type)) {
2606 		const struct btf_type *resolved_type;
2607 		u32 resolved_type_id;
2608 
2609 		resolved_type_id = next_type_id;
2610 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2611 
2612 		if (btf_type_is_ptr(resolved_type) &&
2613 		    !env_type_is_resolve_sink(env, resolved_type) &&
2614 		    !env_type_is_resolved(env, resolved_type_id))
2615 			return env_stack_push(env, resolved_type,
2616 					      resolved_type_id);
2617 	}
2618 
2619 	/* We must resolve to something concrete at this point, no
2620 	 * forward types or similar that would resolve to size of
2621 	 * zero is allowed.
2622 	 */
2623 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2624 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2625 		return -EINVAL;
2626 	}
2627 
2628 	env_stack_pop_resolved(env, next_type_id, 0);
2629 
2630 	return 0;
2631 }
2632 
2633 static int btf_ptr_resolve(struct btf_verifier_env *env,
2634 			   const struct resolve_vertex *v)
2635 {
2636 	const struct btf_type *next_type;
2637 	const struct btf_type *t = v->t;
2638 	u32 next_type_id = t->type;
2639 	struct btf *btf = env->btf;
2640 
2641 	next_type = btf_type_by_id(btf, next_type_id);
2642 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2643 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2644 		return -EINVAL;
2645 	}
2646 
2647 	if (!env_type_is_resolve_sink(env, next_type) &&
2648 	    !env_type_is_resolved(env, next_type_id))
2649 		return env_stack_push(env, next_type, next_type_id);
2650 
2651 	/* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2652 	 * the modifier may have stopped resolving when it was resolved
2653 	 * to a ptr (last-resolved-ptr).
2654 	 *
2655 	 * We now need to continue from the last-resolved-ptr to
2656 	 * ensure the last-resolved-ptr will not referring back to
2657 	 * the current ptr (t).
2658 	 */
2659 	if (btf_type_is_modifier(next_type)) {
2660 		const struct btf_type *resolved_type;
2661 		u32 resolved_type_id;
2662 
2663 		resolved_type_id = next_type_id;
2664 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2665 
2666 		if (btf_type_is_ptr(resolved_type) &&
2667 		    !env_type_is_resolve_sink(env, resolved_type) &&
2668 		    !env_type_is_resolved(env, resolved_type_id))
2669 			return env_stack_push(env, resolved_type,
2670 					      resolved_type_id);
2671 	}
2672 
2673 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2674 		if (env_type_is_resolved(env, next_type_id))
2675 			next_type = btf_type_id_resolve(btf, &next_type_id);
2676 
2677 		if (!btf_type_is_void(next_type) &&
2678 		    !btf_type_is_fwd(next_type) &&
2679 		    !btf_type_is_func_proto(next_type)) {
2680 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2681 			return -EINVAL;
2682 		}
2683 	}
2684 
2685 	env_stack_pop_resolved(env, next_type_id, 0);
2686 
2687 	return 0;
2688 }
2689 
2690 static void btf_modifier_show(const struct btf *btf,
2691 			      const struct btf_type *t,
2692 			      u32 type_id, void *data,
2693 			      u8 bits_offset, struct btf_show *show)
2694 {
2695 	if (btf->resolved_ids)
2696 		t = btf_type_id_resolve(btf, &type_id);
2697 	else
2698 		t = btf_type_skip_modifiers(btf, type_id, NULL);
2699 
2700 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2701 }
2702 
2703 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2704 			 u32 type_id, void *data, u8 bits_offset,
2705 			 struct btf_show *show)
2706 {
2707 	t = btf_type_id_resolve(btf, &type_id);
2708 
2709 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2710 }
2711 
2712 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2713 			 u32 type_id, void *data, u8 bits_offset,
2714 			 struct btf_show *show)
2715 {
2716 	void *safe_data;
2717 
2718 	safe_data = btf_show_start_type(show, t, type_id, data);
2719 	if (!safe_data)
2720 		return;
2721 
2722 	/* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2723 	if (show->flags & BTF_SHOW_PTR_RAW)
2724 		btf_show_type_value(show, "0x%px", *(void **)safe_data);
2725 	else
2726 		btf_show_type_value(show, "0x%p", *(void **)safe_data);
2727 	btf_show_end_type(show);
2728 }
2729 
2730 static void btf_ref_type_log(struct btf_verifier_env *env,
2731 			     const struct btf_type *t)
2732 {
2733 	btf_verifier_log(env, "type_id=%u", t->type);
2734 }
2735 
2736 static struct btf_kind_operations modifier_ops = {
2737 	.check_meta = btf_ref_type_check_meta,
2738 	.resolve = btf_modifier_resolve,
2739 	.check_member = btf_modifier_check_member,
2740 	.check_kflag_member = btf_modifier_check_kflag_member,
2741 	.log_details = btf_ref_type_log,
2742 	.show = btf_modifier_show,
2743 };
2744 
2745 static struct btf_kind_operations ptr_ops = {
2746 	.check_meta = btf_ref_type_check_meta,
2747 	.resolve = btf_ptr_resolve,
2748 	.check_member = btf_ptr_check_member,
2749 	.check_kflag_member = btf_generic_check_kflag_member,
2750 	.log_details = btf_ref_type_log,
2751 	.show = btf_ptr_show,
2752 };
2753 
2754 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2755 			      const struct btf_type *t,
2756 			      u32 meta_left)
2757 {
2758 	if (btf_type_vlen(t)) {
2759 		btf_verifier_log_type(env, t, "vlen != 0");
2760 		return -EINVAL;
2761 	}
2762 
2763 	if (t->type) {
2764 		btf_verifier_log_type(env, t, "type != 0");
2765 		return -EINVAL;
2766 	}
2767 
2768 	/* fwd type must have a valid name */
2769 	if (!t->name_off ||
2770 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
2771 		btf_verifier_log_type(env, t, "Invalid name");
2772 		return -EINVAL;
2773 	}
2774 
2775 	btf_verifier_log_type(env, t, NULL);
2776 
2777 	return 0;
2778 }
2779 
2780 static void btf_fwd_type_log(struct btf_verifier_env *env,
2781 			     const struct btf_type *t)
2782 {
2783 	btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2784 }
2785 
2786 static struct btf_kind_operations fwd_ops = {
2787 	.check_meta = btf_fwd_check_meta,
2788 	.resolve = btf_df_resolve,
2789 	.check_member = btf_df_check_member,
2790 	.check_kflag_member = btf_df_check_kflag_member,
2791 	.log_details = btf_fwd_type_log,
2792 	.show = btf_df_show,
2793 };
2794 
2795 static int btf_array_check_member(struct btf_verifier_env *env,
2796 				  const struct btf_type *struct_type,
2797 				  const struct btf_member *member,
2798 				  const struct btf_type *member_type)
2799 {
2800 	u32 struct_bits_off = member->offset;
2801 	u32 struct_size, bytes_offset;
2802 	u32 array_type_id, array_size;
2803 	struct btf *btf = env->btf;
2804 
2805 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2806 		btf_verifier_log_member(env, struct_type, member,
2807 					"Member is not byte aligned");
2808 		return -EINVAL;
2809 	}
2810 
2811 	array_type_id = member->type;
2812 	btf_type_id_size(btf, &array_type_id, &array_size);
2813 	struct_size = struct_type->size;
2814 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2815 	if (struct_size - bytes_offset < array_size) {
2816 		btf_verifier_log_member(env, struct_type, member,
2817 					"Member exceeds struct_size");
2818 		return -EINVAL;
2819 	}
2820 
2821 	return 0;
2822 }
2823 
2824 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2825 				const struct btf_type *t,
2826 				u32 meta_left)
2827 {
2828 	const struct btf_array *array = btf_type_array(t);
2829 	u32 meta_needed = sizeof(*array);
2830 
2831 	if (meta_left < meta_needed) {
2832 		btf_verifier_log_basic(env, t,
2833 				       "meta_left:%u meta_needed:%u",
2834 				       meta_left, meta_needed);
2835 		return -EINVAL;
2836 	}
2837 
2838 	/* array type should not have a name */
2839 	if (t->name_off) {
2840 		btf_verifier_log_type(env, t, "Invalid name");
2841 		return -EINVAL;
2842 	}
2843 
2844 	if (btf_type_vlen(t)) {
2845 		btf_verifier_log_type(env, t, "vlen != 0");
2846 		return -EINVAL;
2847 	}
2848 
2849 	if (btf_type_kflag(t)) {
2850 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2851 		return -EINVAL;
2852 	}
2853 
2854 	if (t->size) {
2855 		btf_verifier_log_type(env, t, "size != 0");
2856 		return -EINVAL;
2857 	}
2858 
2859 	/* Array elem type and index type cannot be in type void,
2860 	 * so !array->type and !array->index_type are not allowed.
2861 	 */
2862 	if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2863 		btf_verifier_log_type(env, t, "Invalid elem");
2864 		return -EINVAL;
2865 	}
2866 
2867 	if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2868 		btf_verifier_log_type(env, t, "Invalid index");
2869 		return -EINVAL;
2870 	}
2871 
2872 	btf_verifier_log_type(env, t, NULL);
2873 
2874 	return meta_needed;
2875 }
2876 
2877 static int btf_array_resolve(struct btf_verifier_env *env,
2878 			     const struct resolve_vertex *v)
2879 {
2880 	const struct btf_array *array = btf_type_array(v->t);
2881 	const struct btf_type *elem_type, *index_type;
2882 	u32 elem_type_id, index_type_id;
2883 	struct btf *btf = env->btf;
2884 	u32 elem_size;
2885 
2886 	/* Check array->index_type */
2887 	index_type_id = array->index_type;
2888 	index_type = btf_type_by_id(btf, index_type_id);
2889 	if (btf_type_nosize_or_null(index_type) ||
2890 	    btf_type_is_resolve_source_only(index_type)) {
2891 		btf_verifier_log_type(env, v->t, "Invalid index");
2892 		return -EINVAL;
2893 	}
2894 
2895 	if (!env_type_is_resolve_sink(env, index_type) &&
2896 	    !env_type_is_resolved(env, index_type_id))
2897 		return env_stack_push(env, index_type, index_type_id);
2898 
2899 	index_type = btf_type_id_size(btf, &index_type_id, NULL);
2900 	if (!index_type || !btf_type_is_int(index_type) ||
2901 	    !btf_type_int_is_regular(index_type)) {
2902 		btf_verifier_log_type(env, v->t, "Invalid index");
2903 		return -EINVAL;
2904 	}
2905 
2906 	/* Check array->type */
2907 	elem_type_id = array->type;
2908 	elem_type = btf_type_by_id(btf, elem_type_id);
2909 	if (btf_type_nosize_or_null(elem_type) ||
2910 	    btf_type_is_resolve_source_only(elem_type)) {
2911 		btf_verifier_log_type(env, v->t,
2912 				      "Invalid elem");
2913 		return -EINVAL;
2914 	}
2915 
2916 	if (!env_type_is_resolve_sink(env, elem_type) &&
2917 	    !env_type_is_resolved(env, elem_type_id))
2918 		return env_stack_push(env, elem_type, elem_type_id);
2919 
2920 	elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2921 	if (!elem_type) {
2922 		btf_verifier_log_type(env, v->t, "Invalid elem");
2923 		return -EINVAL;
2924 	}
2925 
2926 	if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2927 		btf_verifier_log_type(env, v->t, "Invalid array of int");
2928 		return -EINVAL;
2929 	}
2930 
2931 	if (array->nelems && elem_size > U32_MAX / array->nelems) {
2932 		btf_verifier_log_type(env, v->t,
2933 				      "Array size overflows U32_MAX");
2934 		return -EINVAL;
2935 	}
2936 
2937 	env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2938 
2939 	return 0;
2940 }
2941 
2942 static void btf_array_log(struct btf_verifier_env *env,
2943 			  const struct btf_type *t)
2944 {
2945 	const struct btf_array *array = btf_type_array(t);
2946 
2947 	btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2948 			 array->type, array->index_type, array->nelems);
2949 }
2950 
2951 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2952 			     u32 type_id, void *data, u8 bits_offset,
2953 			     struct btf_show *show)
2954 {
2955 	const struct btf_array *array = btf_type_array(t);
2956 	const struct btf_kind_operations *elem_ops;
2957 	const struct btf_type *elem_type;
2958 	u32 i, elem_size = 0, elem_type_id;
2959 	u16 encoding = 0;
2960 
2961 	elem_type_id = array->type;
2962 	elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2963 	if (elem_type && btf_type_has_size(elem_type))
2964 		elem_size = elem_type->size;
2965 
2966 	if (elem_type && btf_type_is_int(elem_type)) {
2967 		u32 int_type = btf_type_int(elem_type);
2968 
2969 		encoding = BTF_INT_ENCODING(int_type);
2970 
2971 		/*
2972 		 * BTF_INT_CHAR encoding never seems to be set for
2973 		 * char arrays, so if size is 1 and element is
2974 		 * printable as a char, we'll do that.
2975 		 */
2976 		if (elem_size == 1)
2977 			encoding = BTF_INT_CHAR;
2978 	}
2979 
2980 	if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2981 		return;
2982 
2983 	if (!elem_type)
2984 		goto out;
2985 	elem_ops = btf_type_ops(elem_type);
2986 
2987 	for (i = 0; i < array->nelems; i++) {
2988 
2989 		btf_show_start_array_member(show);
2990 
2991 		elem_ops->show(btf, elem_type, elem_type_id, data,
2992 			       bits_offset, show);
2993 		data += elem_size;
2994 
2995 		btf_show_end_array_member(show);
2996 
2997 		if (show->state.array_terminated)
2998 			break;
2999 	}
3000 out:
3001 	btf_show_end_array_type(show);
3002 }
3003 
3004 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3005 			   u32 type_id, void *data, u8 bits_offset,
3006 			   struct btf_show *show)
3007 {
3008 	const struct btf_member *m = show->state.member;
3009 
3010 	/*
3011 	 * First check if any members would be shown (are non-zero).
3012 	 * See comments above "struct btf_show" definition for more
3013 	 * details on how this works at a high-level.
3014 	 */
3015 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3016 		if (!show->state.depth_check) {
3017 			show->state.depth_check = show->state.depth + 1;
3018 			show->state.depth_to_show = 0;
3019 		}
3020 		__btf_array_show(btf, t, type_id, data, bits_offset, show);
3021 		show->state.member = m;
3022 
3023 		if (show->state.depth_check != show->state.depth + 1)
3024 			return;
3025 		show->state.depth_check = 0;
3026 
3027 		if (show->state.depth_to_show <= show->state.depth)
3028 			return;
3029 		/*
3030 		 * Reaching here indicates we have recursed and found
3031 		 * non-zero array member(s).
3032 		 */
3033 	}
3034 	__btf_array_show(btf, t, type_id, data, bits_offset, show);
3035 }
3036 
3037 static struct btf_kind_operations array_ops = {
3038 	.check_meta = btf_array_check_meta,
3039 	.resolve = btf_array_resolve,
3040 	.check_member = btf_array_check_member,
3041 	.check_kflag_member = btf_generic_check_kflag_member,
3042 	.log_details = btf_array_log,
3043 	.show = btf_array_show,
3044 };
3045 
3046 static int btf_struct_check_member(struct btf_verifier_env *env,
3047 				   const struct btf_type *struct_type,
3048 				   const struct btf_member *member,
3049 				   const struct btf_type *member_type)
3050 {
3051 	u32 struct_bits_off = member->offset;
3052 	u32 struct_size, bytes_offset;
3053 
3054 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3055 		btf_verifier_log_member(env, struct_type, member,
3056 					"Member is not byte aligned");
3057 		return -EINVAL;
3058 	}
3059 
3060 	struct_size = struct_type->size;
3061 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3062 	if (struct_size - bytes_offset < member_type->size) {
3063 		btf_verifier_log_member(env, struct_type, member,
3064 					"Member exceeds struct_size");
3065 		return -EINVAL;
3066 	}
3067 
3068 	return 0;
3069 }
3070 
3071 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3072 				 const struct btf_type *t,
3073 				 u32 meta_left)
3074 {
3075 	bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3076 	const struct btf_member *member;
3077 	u32 meta_needed, last_offset;
3078 	struct btf *btf = env->btf;
3079 	u32 struct_size = t->size;
3080 	u32 offset;
3081 	u16 i;
3082 
3083 	meta_needed = btf_type_vlen(t) * sizeof(*member);
3084 	if (meta_left < meta_needed) {
3085 		btf_verifier_log_basic(env, t,
3086 				       "meta_left:%u meta_needed:%u",
3087 				       meta_left, meta_needed);
3088 		return -EINVAL;
3089 	}
3090 
3091 	/* struct type either no name or a valid one */
3092 	if (t->name_off &&
3093 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3094 		btf_verifier_log_type(env, t, "Invalid name");
3095 		return -EINVAL;
3096 	}
3097 
3098 	btf_verifier_log_type(env, t, NULL);
3099 
3100 	last_offset = 0;
3101 	for_each_member(i, t, member) {
3102 		if (!btf_name_offset_valid(btf, member->name_off)) {
3103 			btf_verifier_log_member(env, t, member,
3104 						"Invalid member name_offset:%u",
3105 						member->name_off);
3106 			return -EINVAL;
3107 		}
3108 
3109 		/* struct member either no name or a valid one */
3110 		if (member->name_off &&
3111 		    !btf_name_valid_identifier(btf, member->name_off)) {
3112 			btf_verifier_log_member(env, t, member, "Invalid name");
3113 			return -EINVAL;
3114 		}
3115 		/* A member cannot be in type void */
3116 		if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3117 			btf_verifier_log_member(env, t, member,
3118 						"Invalid type_id");
3119 			return -EINVAL;
3120 		}
3121 
3122 		offset = __btf_member_bit_offset(t, member);
3123 		if (is_union && offset) {
3124 			btf_verifier_log_member(env, t, member,
3125 						"Invalid member bits_offset");
3126 			return -EINVAL;
3127 		}
3128 
3129 		/*
3130 		 * ">" instead of ">=" because the last member could be
3131 		 * "char a[0];"
3132 		 */
3133 		if (last_offset > offset) {
3134 			btf_verifier_log_member(env, t, member,
3135 						"Invalid member bits_offset");
3136 			return -EINVAL;
3137 		}
3138 
3139 		if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3140 			btf_verifier_log_member(env, t, member,
3141 						"Member bits_offset exceeds its struct size");
3142 			return -EINVAL;
3143 		}
3144 
3145 		btf_verifier_log_member(env, t, member, NULL);
3146 		last_offset = offset;
3147 	}
3148 
3149 	return meta_needed;
3150 }
3151 
3152 static int btf_struct_resolve(struct btf_verifier_env *env,
3153 			      const struct resolve_vertex *v)
3154 {
3155 	const struct btf_member *member;
3156 	int err;
3157 	u16 i;
3158 
3159 	/* Before continue resolving the next_member,
3160 	 * ensure the last member is indeed resolved to a
3161 	 * type with size info.
3162 	 */
3163 	if (v->next_member) {
3164 		const struct btf_type *last_member_type;
3165 		const struct btf_member *last_member;
3166 		u32 last_member_type_id;
3167 
3168 		last_member = btf_type_member(v->t) + v->next_member - 1;
3169 		last_member_type_id = last_member->type;
3170 		if (WARN_ON_ONCE(!env_type_is_resolved(env,
3171 						       last_member_type_id)))
3172 			return -EINVAL;
3173 
3174 		last_member_type = btf_type_by_id(env->btf,
3175 						  last_member_type_id);
3176 		if (btf_type_kflag(v->t))
3177 			err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3178 								last_member,
3179 								last_member_type);
3180 		else
3181 			err = btf_type_ops(last_member_type)->check_member(env, v->t,
3182 								last_member,
3183 								last_member_type);
3184 		if (err)
3185 			return err;
3186 	}
3187 
3188 	for_each_member_from(i, v->next_member, v->t, member) {
3189 		u32 member_type_id = member->type;
3190 		const struct btf_type *member_type = btf_type_by_id(env->btf,
3191 								member_type_id);
3192 
3193 		if (btf_type_nosize_or_null(member_type) ||
3194 		    btf_type_is_resolve_source_only(member_type)) {
3195 			btf_verifier_log_member(env, v->t, member,
3196 						"Invalid member");
3197 			return -EINVAL;
3198 		}
3199 
3200 		if (!env_type_is_resolve_sink(env, member_type) &&
3201 		    !env_type_is_resolved(env, member_type_id)) {
3202 			env_stack_set_next_member(env, i + 1);
3203 			return env_stack_push(env, member_type, member_type_id);
3204 		}
3205 
3206 		if (btf_type_kflag(v->t))
3207 			err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3208 									    member,
3209 									    member_type);
3210 		else
3211 			err = btf_type_ops(member_type)->check_member(env, v->t,
3212 								      member,
3213 								      member_type);
3214 		if (err)
3215 			return err;
3216 	}
3217 
3218 	env_stack_pop_resolved(env, 0, 0);
3219 
3220 	return 0;
3221 }
3222 
3223 static void btf_struct_log(struct btf_verifier_env *env,
3224 			   const struct btf_type *t)
3225 {
3226 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3227 }
3228 
3229 enum btf_field_info_type {
3230 	BTF_FIELD_SPIN_LOCK,
3231 	BTF_FIELD_TIMER,
3232 	BTF_FIELD_KPTR,
3233 };
3234 
3235 enum {
3236 	BTF_FIELD_IGNORE = 0,
3237 	BTF_FIELD_FOUND  = 1,
3238 };
3239 
3240 struct btf_field_info {
3241 	enum btf_field_type type;
3242 	u32 off;
3243 	union {
3244 		struct {
3245 			u32 type_id;
3246 		} kptr;
3247 		struct {
3248 			const char *node_name;
3249 			u32 value_btf_id;
3250 		} graph_root;
3251 	};
3252 };
3253 
3254 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3255 			   u32 off, int sz, enum btf_field_type field_type,
3256 			   struct btf_field_info *info)
3257 {
3258 	if (!__btf_type_is_struct(t))
3259 		return BTF_FIELD_IGNORE;
3260 	if (t->size != sz)
3261 		return BTF_FIELD_IGNORE;
3262 	info->type = field_type;
3263 	info->off = off;
3264 	return BTF_FIELD_FOUND;
3265 }
3266 
3267 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3268 			 u32 off, int sz, struct btf_field_info *info)
3269 {
3270 	enum btf_field_type type;
3271 	u32 res_id;
3272 
3273 	/* Permit modifiers on the pointer itself */
3274 	if (btf_type_is_volatile(t))
3275 		t = btf_type_by_id(btf, t->type);
3276 	/* For PTR, sz is always == 8 */
3277 	if (!btf_type_is_ptr(t))
3278 		return BTF_FIELD_IGNORE;
3279 	t = btf_type_by_id(btf, t->type);
3280 
3281 	if (!btf_type_is_type_tag(t))
3282 		return BTF_FIELD_IGNORE;
3283 	/* Reject extra tags */
3284 	if (btf_type_is_type_tag(btf_type_by_id(btf, t->type)))
3285 		return -EINVAL;
3286 	if (!strcmp("kptr", __btf_name_by_offset(btf, t->name_off)))
3287 		type = BPF_KPTR_UNREF;
3288 	else if (!strcmp("kptr_ref", __btf_name_by_offset(btf, t->name_off)))
3289 		type = BPF_KPTR_REF;
3290 	else
3291 		return -EINVAL;
3292 
3293 	/* Get the base type */
3294 	t = btf_type_skip_modifiers(btf, t->type, &res_id);
3295 	/* Only pointer to struct is allowed */
3296 	if (!__btf_type_is_struct(t))
3297 		return -EINVAL;
3298 
3299 	info->type = type;
3300 	info->off = off;
3301 	info->kptr.type_id = res_id;
3302 	return BTF_FIELD_FOUND;
3303 }
3304 
3305 static const char *btf_find_decl_tag_value(const struct btf *btf,
3306 					   const struct btf_type *pt,
3307 					   int comp_idx, const char *tag_key)
3308 {
3309 	int i;
3310 
3311 	for (i = 1; i < btf_nr_types(btf); i++) {
3312 		const struct btf_type *t = btf_type_by_id(btf, i);
3313 		int len = strlen(tag_key);
3314 
3315 		if (!btf_type_is_decl_tag(t))
3316 			continue;
3317 		if (pt != btf_type_by_id(btf, t->type) ||
3318 		    btf_type_decl_tag(t)->component_idx != comp_idx)
3319 			continue;
3320 		if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3321 			continue;
3322 		return __btf_name_by_offset(btf, t->name_off) + len;
3323 	}
3324 	return NULL;
3325 }
3326 
3327 static int btf_find_list_head(const struct btf *btf, const struct btf_type *pt,
3328 			      const struct btf_type *t, int comp_idx,
3329 			      u32 off, int sz, struct btf_field_info *info)
3330 {
3331 	const char *value_type;
3332 	const char *list_node;
3333 	s32 id;
3334 
3335 	if (!__btf_type_is_struct(t))
3336 		return BTF_FIELD_IGNORE;
3337 	if (t->size != sz)
3338 		return BTF_FIELD_IGNORE;
3339 	value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3340 	if (!value_type)
3341 		return -EINVAL;
3342 	list_node = strstr(value_type, ":");
3343 	if (!list_node)
3344 		return -EINVAL;
3345 	value_type = kstrndup(value_type, list_node - value_type, GFP_KERNEL | __GFP_NOWARN);
3346 	if (!value_type)
3347 		return -ENOMEM;
3348 	id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3349 	kfree(value_type);
3350 	if (id < 0)
3351 		return id;
3352 	list_node++;
3353 	if (str_is_empty(list_node))
3354 		return -EINVAL;
3355 	info->type = BPF_LIST_HEAD;
3356 	info->off = off;
3357 	info->graph_root.value_btf_id = id;
3358 	info->graph_root.node_name = list_node;
3359 	return BTF_FIELD_FOUND;
3360 }
3361 
3362 static int btf_get_field_type(const char *name, u32 field_mask, u32 *seen_mask,
3363 			      int *align, int *sz)
3364 {
3365 	int type = 0;
3366 
3367 	if (field_mask & BPF_SPIN_LOCK) {
3368 		if (!strcmp(name, "bpf_spin_lock")) {
3369 			if (*seen_mask & BPF_SPIN_LOCK)
3370 				return -E2BIG;
3371 			*seen_mask |= BPF_SPIN_LOCK;
3372 			type = BPF_SPIN_LOCK;
3373 			goto end;
3374 		}
3375 	}
3376 	if (field_mask & BPF_TIMER) {
3377 		if (!strcmp(name, "bpf_timer")) {
3378 			if (*seen_mask & BPF_TIMER)
3379 				return -E2BIG;
3380 			*seen_mask |= BPF_TIMER;
3381 			type = BPF_TIMER;
3382 			goto end;
3383 		}
3384 	}
3385 	if (field_mask & BPF_LIST_HEAD) {
3386 		if (!strcmp(name, "bpf_list_head")) {
3387 			type = BPF_LIST_HEAD;
3388 			goto end;
3389 		}
3390 	}
3391 	if (field_mask & BPF_LIST_NODE) {
3392 		if (!strcmp(name, "bpf_list_node")) {
3393 			type = BPF_LIST_NODE;
3394 			goto end;
3395 		}
3396 	}
3397 	/* Only return BPF_KPTR when all other types with matchable names fail */
3398 	if (field_mask & BPF_KPTR) {
3399 		type = BPF_KPTR_REF;
3400 		goto end;
3401 	}
3402 	return 0;
3403 end:
3404 	*sz = btf_field_type_size(type);
3405 	*align = btf_field_type_align(type);
3406 	return type;
3407 }
3408 
3409 static int btf_find_struct_field(const struct btf *btf,
3410 				 const struct btf_type *t, u32 field_mask,
3411 				 struct btf_field_info *info, int info_cnt)
3412 {
3413 	int ret, idx = 0, align, sz, field_type;
3414 	const struct btf_member *member;
3415 	struct btf_field_info tmp;
3416 	u32 i, off, seen_mask = 0;
3417 
3418 	for_each_member(i, t, member) {
3419 		const struct btf_type *member_type = btf_type_by_id(btf,
3420 								    member->type);
3421 
3422 		field_type = btf_get_field_type(__btf_name_by_offset(btf, member_type->name_off),
3423 						field_mask, &seen_mask, &align, &sz);
3424 		if (field_type == 0)
3425 			continue;
3426 		if (field_type < 0)
3427 			return field_type;
3428 
3429 		off = __btf_member_bit_offset(t, member);
3430 		if (off % 8)
3431 			/* valid C code cannot generate such BTF */
3432 			return -EINVAL;
3433 		off /= 8;
3434 		if (off % align)
3435 			continue;
3436 
3437 		switch (field_type) {
3438 		case BPF_SPIN_LOCK:
3439 		case BPF_TIMER:
3440 		case BPF_LIST_NODE:
3441 			ret = btf_find_struct(btf, member_type, off, sz, field_type,
3442 					      idx < info_cnt ? &info[idx] : &tmp);
3443 			if (ret < 0)
3444 				return ret;
3445 			break;
3446 		case BPF_KPTR_UNREF:
3447 		case BPF_KPTR_REF:
3448 			ret = btf_find_kptr(btf, member_type, off, sz,
3449 					    idx < info_cnt ? &info[idx] : &tmp);
3450 			if (ret < 0)
3451 				return ret;
3452 			break;
3453 		case BPF_LIST_HEAD:
3454 			ret = btf_find_list_head(btf, t, member_type, i, off, sz,
3455 						 idx < info_cnt ? &info[idx] : &tmp);
3456 			if (ret < 0)
3457 				return ret;
3458 			break;
3459 		default:
3460 			return -EFAULT;
3461 		}
3462 
3463 		if (ret == BTF_FIELD_IGNORE)
3464 			continue;
3465 		if (idx >= info_cnt)
3466 			return -E2BIG;
3467 		++idx;
3468 	}
3469 	return idx;
3470 }
3471 
3472 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3473 				u32 field_mask, struct btf_field_info *info,
3474 				int info_cnt)
3475 {
3476 	int ret, idx = 0, align, sz, field_type;
3477 	const struct btf_var_secinfo *vsi;
3478 	struct btf_field_info tmp;
3479 	u32 i, off, seen_mask = 0;
3480 
3481 	for_each_vsi(i, t, vsi) {
3482 		const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3483 		const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3484 
3485 		field_type = btf_get_field_type(__btf_name_by_offset(btf, var_type->name_off),
3486 						field_mask, &seen_mask, &align, &sz);
3487 		if (field_type == 0)
3488 			continue;
3489 		if (field_type < 0)
3490 			return field_type;
3491 
3492 		off = vsi->offset;
3493 		if (vsi->size != sz)
3494 			continue;
3495 		if (off % align)
3496 			continue;
3497 
3498 		switch (field_type) {
3499 		case BPF_SPIN_LOCK:
3500 		case BPF_TIMER:
3501 		case BPF_LIST_NODE:
3502 			ret = btf_find_struct(btf, var_type, off, sz, field_type,
3503 					      idx < info_cnt ? &info[idx] : &tmp);
3504 			if (ret < 0)
3505 				return ret;
3506 			break;
3507 		case BPF_KPTR_UNREF:
3508 		case BPF_KPTR_REF:
3509 			ret = btf_find_kptr(btf, var_type, off, sz,
3510 					    idx < info_cnt ? &info[idx] : &tmp);
3511 			if (ret < 0)
3512 				return ret;
3513 			break;
3514 		case BPF_LIST_HEAD:
3515 			ret = btf_find_list_head(btf, var, var_type, -1, off, sz,
3516 						 idx < info_cnt ? &info[idx] : &tmp);
3517 			if (ret < 0)
3518 				return ret;
3519 			break;
3520 		default:
3521 			return -EFAULT;
3522 		}
3523 
3524 		if (ret == BTF_FIELD_IGNORE)
3525 			continue;
3526 		if (idx >= info_cnt)
3527 			return -E2BIG;
3528 		++idx;
3529 	}
3530 	return idx;
3531 }
3532 
3533 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
3534 			  u32 field_mask, struct btf_field_info *info,
3535 			  int info_cnt)
3536 {
3537 	if (__btf_type_is_struct(t))
3538 		return btf_find_struct_field(btf, t, field_mask, info, info_cnt);
3539 	else if (btf_type_is_datasec(t))
3540 		return btf_find_datasec_var(btf, t, field_mask, info, info_cnt);
3541 	return -EINVAL;
3542 }
3543 
3544 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
3545 			  struct btf_field_info *info)
3546 {
3547 	struct module *mod = NULL;
3548 	const struct btf_type *t;
3549 	struct btf *kernel_btf;
3550 	int ret;
3551 	s32 id;
3552 
3553 	/* Find type in map BTF, and use it to look up the matching type
3554 	 * in vmlinux or module BTFs, by name and kind.
3555 	 */
3556 	t = btf_type_by_id(btf, info->kptr.type_id);
3557 	id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
3558 			     &kernel_btf);
3559 	if (id < 0)
3560 		return id;
3561 
3562 	/* Find and stash the function pointer for the destruction function that
3563 	 * needs to be eventually invoked from the map free path.
3564 	 */
3565 	if (info->type == BPF_KPTR_REF) {
3566 		const struct btf_type *dtor_func;
3567 		const char *dtor_func_name;
3568 		unsigned long addr;
3569 		s32 dtor_btf_id;
3570 
3571 		/* This call also serves as a whitelist of allowed objects that
3572 		 * can be used as a referenced pointer and be stored in a map at
3573 		 * the same time.
3574 		 */
3575 		dtor_btf_id = btf_find_dtor_kfunc(kernel_btf, id);
3576 		if (dtor_btf_id < 0) {
3577 			ret = dtor_btf_id;
3578 			goto end_btf;
3579 		}
3580 
3581 		dtor_func = btf_type_by_id(kernel_btf, dtor_btf_id);
3582 		if (!dtor_func) {
3583 			ret = -ENOENT;
3584 			goto end_btf;
3585 		}
3586 
3587 		if (btf_is_module(kernel_btf)) {
3588 			mod = btf_try_get_module(kernel_btf);
3589 			if (!mod) {
3590 				ret = -ENXIO;
3591 				goto end_btf;
3592 			}
3593 		}
3594 
3595 		/* We already verified dtor_func to be btf_type_is_func
3596 		 * in register_btf_id_dtor_kfuncs.
3597 		 */
3598 		dtor_func_name = __btf_name_by_offset(kernel_btf, dtor_func->name_off);
3599 		addr = kallsyms_lookup_name(dtor_func_name);
3600 		if (!addr) {
3601 			ret = -EINVAL;
3602 			goto end_mod;
3603 		}
3604 		field->kptr.dtor = (void *)addr;
3605 	}
3606 
3607 	field->kptr.btf_id = id;
3608 	field->kptr.btf = kernel_btf;
3609 	field->kptr.module = mod;
3610 	return 0;
3611 end_mod:
3612 	module_put(mod);
3613 end_btf:
3614 	btf_put(kernel_btf);
3615 	return ret;
3616 }
3617 
3618 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
3619 			       struct btf_field_info *info)
3620 {
3621 	const struct btf_type *t, *n = NULL;
3622 	const struct btf_member *member;
3623 	u32 offset;
3624 	int i;
3625 
3626 	t = btf_type_by_id(btf, info->graph_root.value_btf_id);
3627 	/* We've already checked that value_btf_id is a struct type. We
3628 	 * just need to figure out the offset of the list_node, and
3629 	 * verify its type.
3630 	 */
3631 	for_each_member(i, t, member) {
3632 		if (strcmp(info->graph_root.node_name,
3633 			   __btf_name_by_offset(btf, member->name_off)))
3634 			continue;
3635 		/* Invalid BTF, two members with same name */
3636 		if (n)
3637 			return -EINVAL;
3638 		n = btf_type_by_id(btf, member->type);
3639 		if (!__btf_type_is_struct(n))
3640 			return -EINVAL;
3641 		if (strcmp("bpf_list_node", __btf_name_by_offset(btf, n->name_off)))
3642 			return -EINVAL;
3643 		offset = __btf_member_bit_offset(n, member);
3644 		if (offset % 8)
3645 			return -EINVAL;
3646 		offset /= 8;
3647 		if (offset % __alignof__(struct bpf_list_node))
3648 			return -EINVAL;
3649 
3650 		field->graph_root.btf = (struct btf *)btf;
3651 		field->graph_root.value_btf_id = info->graph_root.value_btf_id;
3652 		field->graph_root.node_offset = offset;
3653 	}
3654 	if (!n)
3655 		return -ENOENT;
3656 	return 0;
3657 }
3658 
3659 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
3660 				    u32 field_mask, u32 value_size)
3661 {
3662 	struct btf_field_info info_arr[BTF_FIELDS_MAX];
3663 	struct btf_record *rec;
3664 	u32 next_off = 0;
3665 	int ret, i, cnt;
3666 
3667 	ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
3668 	if (ret < 0)
3669 		return ERR_PTR(ret);
3670 	if (!ret)
3671 		return NULL;
3672 
3673 	cnt = ret;
3674 	/* This needs to be kzalloc to zero out padding and unused fields, see
3675 	 * comment in btf_record_equal.
3676 	 */
3677 	rec = kzalloc(offsetof(struct btf_record, fields[cnt]), GFP_KERNEL | __GFP_NOWARN);
3678 	if (!rec)
3679 		return ERR_PTR(-ENOMEM);
3680 
3681 	rec->spin_lock_off = -EINVAL;
3682 	rec->timer_off = -EINVAL;
3683 	for (i = 0; i < cnt; i++) {
3684 		if (info_arr[i].off + btf_field_type_size(info_arr[i].type) > value_size) {
3685 			WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
3686 			ret = -EFAULT;
3687 			goto end;
3688 		}
3689 		if (info_arr[i].off < next_off) {
3690 			ret = -EEXIST;
3691 			goto end;
3692 		}
3693 		next_off = info_arr[i].off + btf_field_type_size(info_arr[i].type);
3694 
3695 		rec->field_mask |= info_arr[i].type;
3696 		rec->fields[i].offset = info_arr[i].off;
3697 		rec->fields[i].type = info_arr[i].type;
3698 
3699 		switch (info_arr[i].type) {
3700 		case BPF_SPIN_LOCK:
3701 			WARN_ON_ONCE(rec->spin_lock_off >= 0);
3702 			/* Cache offset for faster lookup at runtime */
3703 			rec->spin_lock_off = rec->fields[i].offset;
3704 			break;
3705 		case BPF_TIMER:
3706 			WARN_ON_ONCE(rec->timer_off >= 0);
3707 			/* Cache offset for faster lookup at runtime */
3708 			rec->timer_off = rec->fields[i].offset;
3709 			break;
3710 		case BPF_KPTR_UNREF:
3711 		case BPF_KPTR_REF:
3712 			ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
3713 			if (ret < 0)
3714 				goto end;
3715 			break;
3716 		case BPF_LIST_HEAD:
3717 			ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
3718 			if (ret < 0)
3719 				goto end;
3720 			break;
3721 		case BPF_LIST_NODE:
3722 			break;
3723 		default:
3724 			ret = -EFAULT;
3725 			goto end;
3726 		}
3727 		rec->cnt++;
3728 	}
3729 
3730 	/* bpf_list_head requires bpf_spin_lock */
3731 	if (btf_record_has_field(rec, BPF_LIST_HEAD) && rec->spin_lock_off < 0) {
3732 		ret = -EINVAL;
3733 		goto end;
3734 	}
3735 
3736 	return rec;
3737 end:
3738 	btf_record_free(rec);
3739 	return ERR_PTR(ret);
3740 }
3741 
3742 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
3743 {
3744 	int i;
3745 
3746 	/* There are two owning types, kptr_ref and bpf_list_head. The former
3747 	 * only supports storing kernel types, which can never store references
3748 	 * to program allocated local types, atleast not yet. Hence we only need
3749 	 * to ensure that bpf_list_head ownership does not form cycles.
3750 	 */
3751 	if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & BPF_LIST_HEAD))
3752 		return 0;
3753 	for (i = 0; i < rec->cnt; i++) {
3754 		struct btf_struct_meta *meta;
3755 		u32 btf_id;
3756 
3757 		if (!(rec->fields[i].type & BPF_LIST_HEAD))
3758 			continue;
3759 		btf_id = rec->fields[i].graph_root.value_btf_id;
3760 		meta = btf_find_struct_meta(btf, btf_id);
3761 		if (!meta)
3762 			return -EFAULT;
3763 		rec->fields[i].graph_root.value_rec = meta->record;
3764 
3765 		if (!(rec->field_mask & BPF_LIST_NODE))
3766 			continue;
3767 
3768 		/* We need to ensure ownership acyclicity among all types. The
3769 		 * proper way to do it would be to topologically sort all BTF
3770 		 * IDs based on the ownership edges, since there can be multiple
3771 		 * bpf_list_head in a type. Instead, we use the following
3772 		 * reasoning:
3773 		 *
3774 		 * - A type can only be owned by another type in user BTF if it
3775 		 *   has a bpf_list_node.
3776 		 * - A type can only _own_ another type in user BTF if it has a
3777 		 *   bpf_list_head.
3778 		 *
3779 		 * We ensure that if a type has both bpf_list_head and
3780 		 * bpf_list_node, its element types cannot be owning types.
3781 		 *
3782 		 * To ensure acyclicity:
3783 		 *
3784 		 * When A only has bpf_list_head, ownership chain can be:
3785 		 *	A -> B -> C
3786 		 * Where:
3787 		 * - B has both bpf_list_head and bpf_list_node.
3788 		 * - C only has bpf_list_node.
3789 		 *
3790 		 * When A has both bpf_list_head and bpf_list_node, some other
3791 		 * type already owns it in the BTF domain, hence it can not own
3792 		 * another owning type through any of the bpf_list_head edges.
3793 		 *	A -> B
3794 		 * Where:
3795 		 * - B only has bpf_list_node.
3796 		 */
3797 		if (meta->record->field_mask & BPF_LIST_HEAD)
3798 			return -ELOOP;
3799 	}
3800 	return 0;
3801 }
3802 
3803 static int btf_field_offs_cmp(const void *_a, const void *_b, const void *priv)
3804 {
3805 	const u32 a = *(const u32 *)_a;
3806 	const u32 b = *(const u32 *)_b;
3807 
3808 	if (a < b)
3809 		return -1;
3810 	else if (a > b)
3811 		return 1;
3812 	return 0;
3813 }
3814 
3815 static void btf_field_offs_swap(void *_a, void *_b, int size, const void *priv)
3816 {
3817 	struct btf_field_offs *foffs = (void *)priv;
3818 	u32 *off_base = foffs->field_off;
3819 	u32 *a = _a, *b = _b;
3820 	u8 *sz_a, *sz_b;
3821 
3822 	sz_a = foffs->field_sz + (a - off_base);
3823 	sz_b = foffs->field_sz + (b - off_base);
3824 
3825 	swap(*a, *b);
3826 	swap(*sz_a, *sz_b);
3827 }
3828 
3829 struct btf_field_offs *btf_parse_field_offs(struct btf_record *rec)
3830 {
3831 	struct btf_field_offs *foffs;
3832 	u32 i, *off;
3833 	u8 *sz;
3834 
3835 	BUILD_BUG_ON(ARRAY_SIZE(foffs->field_off) != ARRAY_SIZE(foffs->field_sz));
3836 	if (IS_ERR_OR_NULL(rec))
3837 		return NULL;
3838 
3839 	foffs = kzalloc(sizeof(*foffs), GFP_KERNEL | __GFP_NOWARN);
3840 	if (!foffs)
3841 		return ERR_PTR(-ENOMEM);
3842 
3843 	off = foffs->field_off;
3844 	sz = foffs->field_sz;
3845 	for (i = 0; i < rec->cnt; i++) {
3846 		off[i] = rec->fields[i].offset;
3847 		sz[i] = btf_field_type_size(rec->fields[i].type);
3848 	}
3849 	foffs->cnt = rec->cnt;
3850 
3851 	if (foffs->cnt == 1)
3852 		return foffs;
3853 	sort_r(foffs->field_off, foffs->cnt, sizeof(foffs->field_off[0]),
3854 	       btf_field_offs_cmp, btf_field_offs_swap, foffs);
3855 	return foffs;
3856 }
3857 
3858 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3859 			      u32 type_id, void *data, u8 bits_offset,
3860 			      struct btf_show *show)
3861 {
3862 	const struct btf_member *member;
3863 	void *safe_data;
3864 	u32 i;
3865 
3866 	safe_data = btf_show_start_struct_type(show, t, type_id, data);
3867 	if (!safe_data)
3868 		return;
3869 
3870 	for_each_member(i, t, member) {
3871 		const struct btf_type *member_type = btf_type_by_id(btf,
3872 								member->type);
3873 		const struct btf_kind_operations *ops;
3874 		u32 member_offset, bitfield_size;
3875 		u32 bytes_offset;
3876 		u8 bits8_offset;
3877 
3878 		btf_show_start_member(show, member);
3879 
3880 		member_offset = __btf_member_bit_offset(t, member);
3881 		bitfield_size = __btf_member_bitfield_size(t, member);
3882 		bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3883 		bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3884 		if (bitfield_size) {
3885 			safe_data = btf_show_start_type(show, member_type,
3886 							member->type,
3887 							data + bytes_offset);
3888 			if (safe_data)
3889 				btf_bitfield_show(safe_data,
3890 						  bits8_offset,
3891 						  bitfield_size, show);
3892 			btf_show_end_type(show);
3893 		} else {
3894 			ops = btf_type_ops(member_type);
3895 			ops->show(btf, member_type, member->type,
3896 				  data + bytes_offset, bits8_offset, show);
3897 		}
3898 
3899 		btf_show_end_member(show);
3900 	}
3901 
3902 	btf_show_end_struct_type(show);
3903 }
3904 
3905 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3906 			    u32 type_id, void *data, u8 bits_offset,
3907 			    struct btf_show *show)
3908 {
3909 	const struct btf_member *m = show->state.member;
3910 
3911 	/*
3912 	 * First check if any members would be shown (are non-zero).
3913 	 * See comments above "struct btf_show" definition for more
3914 	 * details on how this works at a high-level.
3915 	 */
3916 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3917 		if (!show->state.depth_check) {
3918 			show->state.depth_check = show->state.depth + 1;
3919 			show->state.depth_to_show = 0;
3920 		}
3921 		__btf_struct_show(btf, t, type_id, data, bits_offset, show);
3922 		/* Restore saved member data here */
3923 		show->state.member = m;
3924 		if (show->state.depth_check != show->state.depth + 1)
3925 			return;
3926 		show->state.depth_check = 0;
3927 
3928 		if (show->state.depth_to_show <= show->state.depth)
3929 			return;
3930 		/*
3931 		 * Reaching here indicates we have recursed and found
3932 		 * non-zero child values.
3933 		 */
3934 	}
3935 
3936 	__btf_struct_show(btf, t, type_id, data, bits_offset, show);
3937 }
3938 
3939 static struct btf_kind_operations struct_ops = {
3940 	.check_meta = btf_struct_check_meta,
3941 	.resolve = btf_struct_resolve,
3942 	.check_member = btf_struct_check_member,
3943 	.check_kflag_member = btf_generic_check_kflag_member,
3944 	.log_details = btf_struct_log,
3945 	.show = btf_struct_show,
3946 };
3947 
3948 static int btf_enum_check_member(struct btf_verifier_env *env,
3949 				 const struct btf_type *struct_type,
3950 				 const struct btf_member *member,
3951 				 const struct btf_type *member_type)
3952 {
3953 	u32 struct_bits_off = member->offset;
3954 	u32 struct_size, bytes_offset;
3955 
3956 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3957 		btf_verifier_log_member(env, struct_type, member,
3958 					"Member is not byte aligned");
3959 		return -EINVAL;
3960 	}
3961 
3962 	struct_size = struct_type->size;
3963 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3964 	if (struct_size - bytes_offset < member_type->size) {
3965 		btf_verifier_log_member(env, struct_type, member,
3966 					"Member exceeds struct_size");
3967 		return -EINVAL;
3968 	}
3969 
3970 	return 0;
3971 }
3972 
3973 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
3974 				       const struct btf_type *struct_type,
3975 				       const struct btf_member *member,
3976 				       const struct btf_type *member_type)
3977 {
3978 	u32 struct_bits_off, nr_bits, bytes_end, struct_size;
3979 	u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
3980 
3981 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
3982 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
3983 	if (!nr_bits) {
3984 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3985 			btf_verifier_log_member(env, struct_type, member,
3986 						"Member is not byte aligned");
3987 			return -EINVAL;
3988 		}
3989 
3990 		nr_bits = int_bitsize;
3991 	} else if (nr_bits > int_bitsize) {
3992 		btf_verifier_log_member(env, struct_type, member,
3993 					"Invalid member bitfield_size");
3994 		return -EINVAL;
3995 	}
3996 
3997 	struct_size = struct_type->size;
3998 	bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
3999 	if (struct_size < bytes_end) {
4000 		btf_verifier_log_member(env, struct_type, member,
4001 					"Member exceeds struct_size");
4002 		return -EINVAL;
4003 	}
4004 
4005 	return 0;
4006 }
4007 
4008 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4009 			       const struct btf_type *t,
4010 			       u32 meta_left)
4011 {
4012 	const struct btf_enum *enums = btf_type_enum(t);
4013 	struct btf *btf = env->btf;
4014 	const char *fmt_str;
4015 	u16 i, nr_enums;
4016 	u32 meta_needed;
4017 
4018 	nr_enums = btf_type_vlen(t);
4019 	meta_needed = nr_enums * sizeof(*enums);
4020 
4021 	if (meta_left < meta_needed) {
4022 		btf_verifier_log_basic(env, t,
4023 				       "meta_left:%u meta_needed:%u",
4024 				       meta_left, meta_needed);
4025 		return -EINVAL;
4026 	}
4027 
4028 	if (t->size > 8 || !is_power_of_2(t->size)) {
4029 		btf_verifier_log_type(env, t, "Unexpected size");
4030 		return -EINVAL;
4031 	}
4032 
4033 	/* enum type either no name or a valid one */
4034 	if (t->name_off &&
4035 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4036 		btf_verifier_log_type(env, t, "Invalid name");
4037 		return -EINVAL;
4038 	}
4039 
4040 	btf_verifier_log_type(env, t, NULL);
4041 
4042 	for (i = 0; i < nr_enums; i++) {
4043 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4044 			btf_verifier_log(env, "\tInvalid name_offset:%u",
4045 					 enums[i].name_off);
4046 			return -EINVAL;
4047 		}
4048 
4049 		/* enum member must have a valid name */
4050 		if (!enums[i].name_off ||
4051 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
4052 			btf_verifier_log_type(env, t, "Invalid name");
4053 			return -EINVAL;
4054 		}
4055 
4056 		if (env->log.level == BPF_LOG_KERNEL)
4057 			continue;
4058 		fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4059 		btf_verifier_log(env, fmt_str,
4060 				 __btf_name_by_offset(btf, enums[i].name_off),
4061 				 enums[i].val);
4062 	}
4063 
4064 	return meta_needed;
4065 }
4066 
4067 static void btf_enum_log(struct btf_verifier_env *env,
4068 			 const struct btf_type *t)
4069 {
4070 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4071 }
4072 
4073 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4074 			  u32 type_id, void *data, u8 bits_offset,
4075 			  struct btf_show *show)
4076 {
4077 	const struct btf_enum *enums = btf_type_enum(t);
4078 	u32 i, nr_enums = btf_type_vlen(t);
4079 	void *safe_data;
4080 	int v;
4081 
4082 	safe_data = btf_show_start_type(show, t, type_id, data);
4083 	if (!safe_data)
4084 		return;
4085 
4086 	v = *(int *)safe_data;
4087 
4088 	for (i = 0; i < nr_enums; i++) {
4089 		if (v != enums[i].val)
4090 			continue;
4091 
4092 		btf_show_type_value(show, "%s",
4093 				    __btf_name_by_offset(btf,
4094 							 enums[i].name_off));
4095 
4096 		btf_show_end_type(show);
4097 		return;
4098 	}
4099 
4100 	if (btf_type_kflag(t))
4101 		btf_show_type_value(show, "%d", v);
4102 	else
4103 		btf_show_type_value(show, "%u", v);
4104 	btf_show_end_type(show);
4105 }
4106 
4107 static struct btf_kind_operations enum_ops = {
4108 	.check_meta = btf_enum_check_meta,
4109 	.resolve = btf_df_resolve,
4110 	.check_member = btf_enum_check_member,
4111 	.check_kflag_member = btf_enum_check_kflag_member,
4112 	.log_details = btf_enum_log,
4113 	.show = btf_enum_show,
4114 };
4115 
4116 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4117 				 const struct btf_type *t,
4118 				 u32 meta_left)
4119 {
4120 	const struct btf_enum64 *enums = btf_type_enum64(t);
4121 	struct btf *btf = env->btf;
4122 	const char *fmt_str;
4123 	u16 i, nr_enums;
4124 	u32 meta_needed;
4125 
4126 	nr_enums = btf_type_vlen(t);
4127 	meta_needed = nr_enums * sizeof(*enums);
4128 
4129 	if (meta_left < meta_needed) {
4130 		btf_verifier_log_basic(env, t,
4131 				       "meta_left:%u meta_needed:%u",
4132 				       meta_left, meta_needed);
4133 		return -EINVAL;
4134 	}
4135 
4136 	if (t->size > 8 || !is_power_of_2(t->size)) {
4137 		btf_verifier_log_type(env, t, "Unexpected size");
4138 		return -EINVAL;
4139 	}
4140 
4141 	/* enum type either no name or a valid one */
4142 	if (t->name_off &&
4143 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4144 		btf_verifier_log_type(env, t, "Invalid name");
4145 		return -EINVAL;
4146 	}
4147 
4148 	btf_verifier_log_type(env, t, NULL);
4149 
4150 	for (i = 0; i < nr_enums; i++) {
4151 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4152 			btf_verifier_log(env, "\tInvalid name_offset:%u",
4153 					 enums[i].name_off);
4154 			return -EINVAL;
4155 		}
4156 
4157 		/* enum member must have a valid name */
4158 		if (!enums[i].name_off ||
4159 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
4160 			btf_verifier_log_type(env, t, "Invalid name");
4161 			return -EINVAL;
4162 		}
4163 
4164 		if (env->log.level == BPF_LOG_KERNEL)
4165 			continue;
4166 
4167 		fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4168 		btf_verifier_log(env, fmt_str,
4169 				 __btf_name_by_offset(btf, enums[i].name_off),
4170 				 btf_enum64_value(enums + i));
4171 	}
4172 
4173 	return meta_needed;
4174 }
4175 
4176 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4177 			    u32 type_id, void *data, u8 bits_offset,
4178 			    struct btf_show *show)
4179 {
4180 	const struct btf_enum64 *enums = btf_type_enum64(t);
4181 	u32 i, nr_enums = btf_type_vlen(t);
4182 	void *safe_data;
4183 	s64 v;
4184 
4185 	safe_data = btf_show_start_type(show, t, type_id, data);
4186 	if (!safe_data)
4187 		return;
4188 
4189 	v = *(u64 *)safe_data;
4190 
4191 	for (i = 0; i < nr_enums; i++) {
4192 		if (v != btf_enum64_value(enums + i))
4193 			continue;
4194 
4195 		btf_show_type_value(show, "%s",
4196 				    __btf_name_by_offset(btf,
4197 							 enums[i].name_off));
4198 
4199 		btf_show_end_type(show);
4200 		return;
4201 	}
4202 
4203 	if (btf_type_kflag(t))
4204 		btf_show_type_value(show, "%lld", v);
4205 	else
4206 		btf_show_type_value(show, "%llu", v);
4207 	btf_show_end_type(show);
4208 }
4209 
4210 static struct btf_kind_operations enum64_ops = {
4211 	.check_meta = btf_enum64_check_meta,
4212 	.resolve = btf_df_resolve,
4213 	.check_member = btf_enum_check_member,
4214 	.check_kflag_member = btf_enum_check_kflag_member,
4215 	.log_details = btf_enum_log,
4216 	.show = btf_enum64_show,
4217 };
4218 
4219 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
4220 				     const struct btf_type *t,
4221 				     u32 meta_left)
4222 {
4223 	u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
4224 
4225 	if (meta_left < meta_needed) {
4226 		btf_verifier_log_basic(env, t,
4227 				       "meta_left:%u meta_needed:%u",
4228 				       meta_left, meta_needed);
4229 		return -EINVAL;
4230 	}
4231 
4232 	if (t->name_off) {
4233 		btf_verifier_log_type(env, t, "Invalid name");
4234 		return -EINVAL;
4235 	}
4236 
4237 	if (btf_type_kflag(t)) {
4238 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4239 		return -EINVAL;
4240 	}
4241 
4242 	btf_verifier_log_type(env, t, NULL);
4243 
4244 	return meta_needed;
4245 }
4246 
4247 static void btf_func_proto_log(struct btf_verifier_env *env,
4248 			       const struct btf_type *t)
4249 {
4250 	const struct btf_param *args = (const struct btf_param *)(t + 1);
4251 	u16 nr_args = btf_type_vlen(t), i;
4252 
4253 	btf_verifier_log(env, "return=%u args=(", t->type);
4254 	if (!nr_args) {
4255 		btf_verifier_log(env, "void");
4256 		goto done;
4257 	}
4258 
4259 	if (nr_args == 1 && !args[0].type) {
4260 		/* Only one vararg */
4261 		btf_verifier_log(env, "vararg");
4262 		goto done;
4263 	}
4264 
4265 	btf_verifier_log(env, "%u %s", args[0].type,
4266 			 __btf_name_by_offset(env->btf,
4267 					      args[0].name_off));
4268 	for (i = 1; i < nr_args - 1; i++)
4269 		btf_verifier_log(env, ", %u %s", args[i].type,
4270 				 __btf_name_by_offset(env->btf,
4271 						      args[i].name_off));
4272 
4273 	if (nr_args > 1) {
4274 		const struct btf_param *last_arg = &args[nr_args - 1];
4275 
4276 		if (last_arg->type)
4277 			btf_verifier_log(env, ", %u %s", last_arg->type,
4278 					 __btf_name_by_offset(env->btf,
4279 							      last_arg->name_off));
4280 		else
4281 			btf_verifier_log(env, ", vararg");
4282 	}
4283 
4284 done:
4285 	btf_verifier_log(env, ")");
4286 }
4287 
4288 static struct btf_kind_operations func_proto_ops = {
4289 	.check_meta = btf_func_proto_check_meta,
4290 	.resolve = btf_df_resolve,
4291 	/*
4292 	 * BTF_KIND_FUNC_PROTO cannot be directly referred by
4293 	 * a struct's member.
4294 	 *
4295 	 * It should be a function pointer instead.
4296 	 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
4297 	 *
4298 	 * Hence, there is no btf_func_check_member().
4299 	 */
4300 	.check_member = btf_df_check_member,
4301 	.check_kflag_member = btf_df_check_kflag_member,
4302 	.log_details = btf_func_proto_log,
4303 	.show = btf_df_show,
4304 };
4305 
4306 static s32 btf_func_check_meta(struct btf_verifier_env *env,
4307 			       const struct btf_type *t,
4308 			       u32 meta_left)
4309 {
4310 	if (!t->name_off ||
4311 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4312 		btf_verifier_log_type(env, t, "Invalid name");
4313 		return -EINVAL;
4314 	}
4315 
4316 	if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
4317 		btf_verifier_log_type(env, t, "Invalid func linkage");
4318 		return -EINVAL;
4319 	}
4320 
4321 	if (btf_type_kflag(t)) {
4322 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4323 		return -EINVAL;
4324 	}
4325 
4326 	btf_verifier_log_type(env, t, NULL);
4327 
4328 	return 0;
4329 }
4330 
4331 static int btf_func_resolve(struct btf_verifier_env *env,
4332 			    const struct resolve_vertex *v)
4333 {
4334 	const struct btf_type *t = v->t;
4335 	u32 next_type_id = t->type;
4336 	int err;
4337 
4338 	err = btf_func_check(env, t);
4339 	if (err)
4340 		return err;
4341 
4342 	env_stack_pop_resolved(env, next_type_id, 0);
4343 	return 0;
4344 }
4345 
4346 static struct btf_kind_operations func_ops = {
4347 	.check_meta = btf_func_check_meta,
4348 	.resolve = btf_func_resolve,
4349 	.check_member = btf_df_check_member,
4350 	.check_kflag_member = btf_df_check_kflag_member,
4351 	.log_details = btf_ref_type_log,
4352 	.show = btf_df_show,
4353 };
4354 
4355 static s32 btf_var_check_meta(struct btf_verifier_env *env,
4356 			      const struct btf_type *t,
4357 			      u32 meta_left)
4358 {
4359 	const struct btf_var *var;
4360 	u32 meta_needed = sizeof(*var);
4361 
4362 	if (meta_left < meta_needed) {
4363 		btf_verifier_log_basic(env, t,
4364 				       "meta_left:%u meta_needed:%u",
4365 				       meta_left, meta_needed);
4366 		return -EINVAL;
4367 	}
4368 
4369 	if (btf_type_vlen(t)) {
4370 		btf_verifier_log_type(env, t, "vlen != 0");
4371 		return -EINVAL;
4372 	}
4373 
4374 	if (btf_type_kflag(t)) {
4375 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4376 		return -EINVAL;
4377 	}
4378 
4379 	if (!t->name_off ||
4380 	    !__btf_name_valid(env->btf, t->name_off, true)) {
4381 		btf_verifier_log_type(env, t, "Invalid name");
4382 		return -EINVAL;
4383 	}
4384 
4385 	/* A var cannot be in type void */
4386 	if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
4387 		btf_verifier_log_type(env, t, "Invalid type_id");
4388 		return -EINVAL;
4389 	}
4390 
4391 	var = btf_type_var(t);
4392 	if (var->linkage != BTF_VAR_STATIC &&
4393 	    var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
4394 		btf_verifier_log_type(env, t, "Linkage not supported");
4395 		return -EINVAL;
4396 	}
4397 
4398 	btf_verifier_log_type(env, t, NULL);
4399 
4400 	return meta_needed;
4401 }
4402 
4403 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
4404 {
4405 	const struct btf_var *var = btf_type_var(t);
4406 
4407 	btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
4408 }
4409 
4410 static const struct btf_kind_operations var_ops = {
4411 	.check_meta		= btf_var_check_meta,
4412 	.resolve		= btf_var_resolve,
4413 	.check_member		= btf_df_check_member,
4414 	.check_kflag_member	= btf_df_check_kflag_member,
4415 	.log_details		= btf_var_log,
4416 	.show			= btf_var_show,
4417 };
4418 
4419 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
4420 				  const struct btf_type *t,
4421 				  u32 meta_left)
4422 {
4423 	const struct btf_var_secinfo *vsi;
4424 	u64 last_vsi_end_off = 0, sum = 0;
4425 	u32 i, meta_needed;
4426 
4427 	meta_needed = btf_type_vlen(t) * sizeof(*vsi);
4428 	if (meta_left < meta_needed) {
4429 		btf_verifier_log_basic(env, t,
4430 				       "meta_left:%u meta_needed:%u",
4431 				       meta_left, meta_needed);
4432 		return -EINVAL;
4433 	}
4434 
4435 	if (!t->size) {
4436 		btf_verifier_log_type(env, t, "size == 0");
4437 		return -EINVAL;
4438 	}
4439 
4440 	if (btf_type_kflag(t)) {
4441 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4442 		return -EINVAL;
4443 	}
4444 
4445 	if (!t->name_off ||
4446 	    !btf_name_valid_section(env->btf, t->name_off)) {
4447 		btf_verifier_log_type(env, t, "Invalid name");
4448 		return -EINVAL;
4449 	}
4450 
4451 	btf_verifier_log_type(env, t, NULL);
4452 
4453 	for_each_vsi(i, t, vsi) {
4454 		/* A var cannot be in type void */
4455 		if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
4456 			btf_verifier_log_vsi(env, t, vsi,
4457 					     "Invalid type_id");
4458 			return -EINVAL;
4459 		}
4460 
4461 		if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
4462 			btf_verifier_log_vsi(env, t, vsi,
4463 					     "Invalid offset");
4464 			return -EINVAL;
4465 		}
4466 
4467 		if (!vsi->size || vsi->size > t->size) {
4468 			btf_verifier_log_vsi(env, t, vsi,
4469 					     "Invalid size");
4470 			return -EINVAL;
4471 		}
4472 
4473 		last_vsi_end_off = vsi->offset + vsi->size;
4474 		if (last_vsi_end_off > t->size) {
4475 			btf_verifier_log_vsi(env, t, vsi,
4476 					     "Invalid offset+size");
4477 			return -EINVAL;
4478 		}
4479 
4480 		btf_verifier_log_vsi(env, t, vsi, NULL);
4481 		sum += vsi->size;
4482 	}
4483 
4484 	if (t->size < sum) {
4485 		btf_verifier_log_type(env, t, "Invalid btf_info size");
4486 		return -EINVAL;
4487 	}
4488 
4489 	return meta_needed;
4490 }
4491 
4492 static int btf_datasec_resolve(struct btf_verifier_env *env,
4493 			       const struct resolve_vertex *v)
4494 {
4495 	const struct btf_var_secinfo *vsi;
4496 	struct btf *btf = env->btf;
4497 	u16 i;
4498 
4499 	for_each_vsi_from(i, v->next_member, v->t, vsi) {
4500 		u32 var_type_id = vsi->type, type_id, type_size = 0;
4501 		const struct btf_type *var_type = btf_type_by_id(env->btf,
4502 								 var_type_id);
4503 		if (!var_type || !btf_type_is_var(var_type)) {
4504 			btf_verifier_log_vsi(env, v->t, vsi,
4505 					     "Not a VAR kind member");
4506 			return -EINVAL;
4507 		}
4508 
4509 		if (!env_type_is_resolve_sink(env, var_type) &&
4510 		    !env_type_is_resolved(env, var_type_id)) {
4511 			env_stack_set_next_member(env, i + 1);
4512 			return env_stack_push(env, var_type, var_type_id);
4513 		}
4514 
4515 		type_id = var_type->type;
4516 		if (!btf_type_id_size(btf, &type_id, &type_size)) {
4517 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4518 			return -EINVAL;
4519 		}
4520 
4521 		if (vsi->size < type_size) {
4522 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4523 			return -EINVAL;
4524 		}
4525 	}
4526 
4527 	env_stack_pop_resolved(env, 0, 0);
4528 	return 0;
4529 }
4530 
4531 static void btf_datasec_log(struct btf_verifier_env *env,
4532 			    const struct btf_type *t)
4533 {
4534 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4535 }
4536 
4537 static void btf_datasec_show(const struct btf *btf,
4538 			     const struct btf_type *t, u32 type_id,
4539 			     void *data, u8 bits_offset,
4540 			     struct btf_show *show)
4541 {
4542 	const struct btf_var_secinfo *vsi;
4543 	const struct btf_type *var;
4544 	u32 i;
4545 
4546 	if (!btf_show_start_type(show, t, type_id, data))
4547 		return;
4548 
4549 	btf_show_type_value(show, "section (\"%s\") = {",
4550 			    __btf_name_by_offset(btf, t->name_off));
4551 	for_each_vsi(i, t, vsi) {
4552 		var = btf_type_by_id(btf, vsi->type);
4553 		if (i)
4554 			btf_show(show, ",");
4555 		btf_type_ops(var)->show(btf, var, vsi->type,
4556 					data + vsi->offset, bits_offset, show);
4557 	}
4558 	btf_show_end_type(show);
4559 }
4560 
4561 static const struct btf_kind_operations datasec_ops = {
4562 	.check_meta		= btf_datasec_check_meta,
4563 	.resolve		= btf_datasec_resolve,
4564 	.check_member		= btf_df_check_member,
4565 	.check_kflag_member	= btf_df_check_kflag_member,
4566 	.log_details		= btf_datasec_log,
4567 	.show			= btf_datasec_show,
4568 };
4569 
4570 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4571 				const struct btf_type *t,
4572 				u32 meta_left)
4573 {
4574 	if (btf_type_vlen(t)) {
4575 		btf_verifier_log_type(env, t, "vlen != 0");
4576 		return -EINVAL;
4577 	}
4578 
4579 	if (btf_type_kflag(t)) {
4580 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4581 		return -EINVAL;
4582 	}
4583 
4584 	if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4585 	    t->size != 16) {
4586 		btf_verifier_log_type(env, t, "Invalid type_size");
4587 		return -EINVAL;
4588 	}
4589 
4590 	btf_verifier_log_type(env, t, NULL);
4591 
4592 	return 0;
4593 }
4594 
4595 static int btf_float_check_member(struct btf_verifier_env *env,
4596 				  const struct btf_type *struct_type,
4597 				  const struct btf_member *member,
4598 				  const struct btf_type *member_type)
4599 {
4600 	u64 start_offset_bytes;
4601 	u64 end_offset_bytes;
4602 	u64 misalign_bits;
4603 	u64 align_bytes;
4604 	u64 align_bits;
4605 
4606 	/* Different architectures have different alignment requirements, so
4607 	 * here we check only for the reasonable minimum. This way we ensure
4608 	 * that types after CO-RE can pass the kernel BTF verifier.
4609 	 */
4610 	align_bytes = min_t(u64, sizeof(void *), member_type->size);
4611 	align_bits = align_bytes * BITS_PER_BYTE;
4612 	div64_u64_rem(member->offset, align_bits, &misalign_bits);
4613 	if (misalign_bits) {
4614 		btf_verifier_log_member(env, struct_type, member,
4615 					"Member is not properly aligned");
4616 		return -EINVAL;
4617 	}
4618 
4619 	start_offset_bytes = member->offset / BITS_PER_BYTE;
4620 	end_offset_bytes = start_offset_bytes + member_type->size;
4621 	if (end_offset_bytes > struct_type->size) {
4622 		btf_verifier_log_member(env, struct_type, member,
4623 					"Member exceeds struct_size");
4624 		return -EINVAL;
4625 	}
4626 
4627 	return 0;
4628 }
4629 
4630 static void btf_float_log(struct btf_verifier_env *env,
4631 			  const struct btf_type *t)
4632 {
4633 	btf_verifier_log(env, "size=%u", t->size);
4634 }
4635 
4636 static const struct btf_kind_operations float_ops = {
4637 	.check_meta = btf_float_check_meta,
4638 	.resolve = btf_df_resolve,
4639 	.check_member = btf_float_check_member,
4640 	.check_kflag_member = btf_generic_check_kflag_member,
4641 	.log_details = btf_float_log,
4642 	.show = btf_df_show,
4643 };
4644 
4645 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4646 			      const struct btf_type *t,
4647 			      u32 meta_left)
4648 {
4649 	const struct btf_decl_tag *tag;
4650 	u32 meta_needed = sizeof(*tag);
4651 	s32 component_idx;
4652 	const char *value;
4653 
4654 	if (meta_left < meta_needed) {
4655 		btf_verifier_log_basic(env, t,
4656 				       "meta_left:%u meta_needed:%u",
4657 				       meta_left, meta_needed);
4658 		return -EINVAL;
4659 	}
4660 
4661 	value = btf_name_by_offset(env->btf, t->name_off);
4662 	if (!value || !value[0]) {
4663 		btf_verifier_log_type(env, t, "Invalid value");
4664 		return -EINVAL;
4665 	}
4666 
4667 	if (btf_type_vlen(t)) {
4668 		btf_verifier_log_type(env, t, "vlen != 0");
4669 		return -EINVAL;
4670 	}
4671 
4672 	if (btf_type_kflag(t)) {
4673 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4674 		return -EINVAL;
4675 	}
4676 
4677 	component_idx = btf_type_decl_tag(t)->component_idx;
4678 	if (component_idx < -1) {
4679 		btf_verifier_log_type(env, t, "Invalid component_idx");
4680 		return -EINVAL;
4681 	}
4682 
4683 	btf_verifier_log_type(env, t, NULL);
4684 
4685 	return meta_needed;
4686 }
4687 
4688 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4689 			   const struct resolve_vertex *v)
4690 {
4691 	const struct btf_type *next_type;
4692 	const struct btf_type *t = v->t;
4693 	u32 next_type_id = t->type;
4694 	struct btf *btf = env->btf;
4695 	s32 component_idx;
4696 	u32 vlen;
4697 
4698 	next_type = btf_type_by_id(btf, next_type_id);
4699 	if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
4700 		btf_verifier_log_type(env, v->t, "Invalid type_id");
4701 		return -EINVAL;
4702 	}
4703 
4704 	if (!env_type_is_resolve_sink(env, next_type) &&
4705 	    !env_type_is_resolved(env, next_type_id))
4706 		return env_stack_push(env, next_type, next_type_id);
4707 
4708 	component_idx = btf_type_decl_tag(t)->component_idx;
4709 	if (component_idx != -1) {
4710 		if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
4711 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
4712 			return -EINVAL;
4713 		}
4714 
4715 		if (btf_type_is_struct(next_type)) {
4716 			vlen = btf_type_vlen(next_type);
4717 		} else {
4718 			/* next_type should be a function */
4719 			next_type = btf_type_by_id(btf, next_type->type);
4720 			vlen = btf_type_vlen(next_type);
4721 		}
4722 
4723 		if ((u32)component_idx >= vlen) {
4724 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
4725 			return -EINVAL;
4726 		}
4727 	}
4728 
4729 	env_stack_pop_resolved(env, next_type_id, 0);
4730 
4731 	return 0;
4732 }
4733 
4734 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4735 {
4736 	btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4737 			 btf_type_decl_tag(t)->component_idx);
4738 }
4739 
4740 static const struct btf_kind_operations decl_tag_ops = {
4741 	.check_meta = btf_decl_tag_check_meta,
4742 	.resolve = btf_decl_tag_resolve,
4743 	.check_member = btf_df_check_member,
4744 	.check_kflag_member = btf_df_check_kflag_member,
4745 	.log_details = btf_decl_tag_log,
4746 	.show = btf_df_show,
4747 };
4748 
4749 static int btf_func_proto_check(struct btf_verifier_env *env,
4750 				const struct btf_type *t)
4751 {
4752 	const struct btf_type *ret_type;
4753 	const struct btf_param *args;
4754 	const struct btf *btf;
4755 	u16 nr_args, i;
4756 	int err;
4757 
4758 	btf = env->btf;
4759 	args = (const struct btf_param *)(t + 1);
4760 	nr_args = btf_type_vlen(t);
4761 
4762 	/* Check func return type which could be "void" (t->type == 0) */
4763 	if (t->type) {
4764 		u32 ret_type_id = t->type;
4765 
4766 		ret_type = btf_type_by_id(btf, ret_type_id);
4767 		if (!ret_type) {
4768 			btf_verifier_log_type(env, t, "Invalid return type");
4769 			return -EINVAL;
4770 		}
4771 
4772 		if (btf_type_is_resolve_source_only(ret_type)) {
4773 			btf_verifier_log_type(env, t, "Invalid return type");
4774 			return -EINVAL;
4775 		}
4776 
4777 		if (btf_type_needs_resolve(ret_type) &&
4778 		    !env_type_is_resolved(env, ret_type_id)) {
4779 			err = btf_resolve(env, ret_type, ret_type_id);
4780 			if (err)
4781 				return err;
4782 		}
4783 
4784 		/* Ensure the return type is a type that has a size */
4785 		if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
4786 			btf_verifier_log_type(env, t, "Invalid return type");
4787 			return -EINVAL;
4788 		}
4789 	}
4790 
4791 	if (!nr_args)
4792 		return 0;
4793 
4794 	/* Last func arg type_id could be 0 if it is a vararg */
4795 	if (!args[nr_args - 1].type) {
4796 		if (args[nr_args - 1].name_off) {
4797 			btf_verifier_log_type(env, t, "Invalid arg#%u",
4798 					      nr_args);
4799 			return -EINVAL;
4800 		}
4801 		nr_args--;
4802 	}
4803 
4804 	for (i = 0; i < nr_args; i++) {
4805 		const struct btf_type *arg_type;
4806 		u32 arg_type_id;
4807 
4808 		arg_type_id = args[i].type;
4809 		arg_type = btf_type_by_id(btf, arg_type_id);
4810 		if (!arg_type) {
4811 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4812 			return -EINVAL;
4813 		}
4814 
4815 		if (btf_type_is_resolve_source_only(arg_type)) {
4816 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4817 			return -EINVAL;
4818 		}
4819 
4820 		if (args[i].name_off &&
4821 		    (!btf_name_offset_valid(btf, args[i].name_off) ||
4822 		     !btf_name_valid_identifier(btf, args[i].name_off))) {
4823 			btf_verifier_log_type(env, t,
4824 					      "Invalid arg#%u", i + 1);
4825 			return -EINVAL;
4826 		}
4827 
4828 		if (btf_type_needs_resolve(arg_type) &&
4829 		    !env_type_is_resolved(env, arg_type_id)) {
4830 			err = btf_resolve(env, arg_type, arg_type_id);
4831 			if (err)
4832 				return err;
4833 		}
4834 
4835 		if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4836 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4837 			return -EINVAL;
4838 		}
4839 	}
4840 
4841 	return 0;
4842 }
4843 
4844 static int btf_func_check(struct btf_verifier_env *env,
4845 			  const struct btf_type *t)
4846 {
4847 	const struct btf_type *proto_type;
4848 	const struct btf_param *args;
4849 	const struct btf *btf;
4850 	u16 nr_args, i;
4851 
4852 	btf = env->btf;
4853 	proto_type = btf_type_by_id(btf, t->type);
4854 
4855 	if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4856 		btf_verifier_log_type(env, t, "Invalid type_id");
4857 		return -EINVAL;
4858 	}
4859 
4860 	args = (const struct btf_param *)(proto_type + 1);
4861 	nr_args = btf_type_vlen(proto_type);
4862 	for (i = 0; i < nr_args; i++) {
4863 		if (!args[i].name_off && args[i].type) {
4864 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4865 			return -EINVAL;
4866 		}
4867 	}
4868 
4869 	return 0;
4870 }
4871 
4872 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
4873 	[BTF_KIND_INT] = &int_ops,
4874 	[BTF_KIND_PTR] = &ptr_ops,
4875 	[BTF_KIND_ARRAY] = &array_ops,
4876 	[BTF_KIND_STRUCT] = &struct_ops,
4877 	[BTF_KIND_UNION] = &struct_ops,
4878 	[BTF_KIND_ENUM] = &enum_ops,
4879 	[BTF_KIND_FWD] = &fwd_ops,
4880 	[BTF_KIND_TYPEDEF] = &modifier_ops,
4881 	[BTF_KIND_VOLATILE] = &modifier_ops,
4882 	[BTF_KIND_CONST] = &modifier_ops,
4883 	[BTF_KIND_RESTRICT] = &modifier_ops,
4884 	[BTF_KIND_FUNC] = &func_ops,
4885 	[BTF_KIND_FUNC_PROTO] = &func_proto_ops,
4886 	[BTF_KIND_VAR] = &var_ops,
4887 	[BTF_KIND_DATASEC] = &datasec_ops,
4888 	[BTF_KIND_FLOAT] = &float_ops,
4889 	[BTF_KIND_DECL_TAG] = &decl_tag_ops,
4890 	[BTF_KIND_TYPE_TAG] = &modifier_ops,
4891 	[BTF_KIND_ENUM64] = &enum64_ops,
4892 };
4893 
4894 static s32 btf_check_meta(struct btf_verifier_env *env,
4895 			  const struct btf_type *t,
4896 			  u32 meta_left)
4897 {
4898 	u32 saved_meta_left = meta_left;
4899 	s32 var_meta_size;
4900 
4901 	if (meta_left < sizeof(*t)) {
4902 		btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
4903 				 env->log_type_id, meta_left, sizeof(*t));
4904 		return -EINVAL;
4905 	}
4906 	meta_left -= sizeof(*t);
4907 
4908 	if (t->info & ~BTF_INFO_MASK) {
4909 		btf_verifier_log(env, "[%u] Invalid btf_info:%x",
4910 				 env->log_type_id, t->info);
4911 		return -EINVAL;
4912 	}
4913 
4914 	if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
4915 	    BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
4916 		btf_verifier_log(env, "[%u] Invalid kind:%u",
4917 				 env->log_type_id, BTF_INFO_KIND(t->info));
4918 		return -EINVAL;
4919 	}
4920 
4921 	if (!btf_name_offset_valid(env->btf, t->name_off)) {
4922 		btf_verifier_log(env, "[%u] Invalid name_offset:%u",
4923 				 env->log_type_id, t->name_off);
4924 		return -EINVAL;
4925 	}
4926 
4927 	var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
4928 	if (var_meta_size < 0)
4929 		return var_meta_size;
4930 
4931 	meta_left -= var_meta_size;
4932 
4933 	return saved_meta_left - meta_left;
4934 }
4935 
4936 static int btf_check_all_metas(struct btf_verifier_env *env)
4937 {
4938 	struct btf *btf = env->btf;
4939 	struct btf_header *hdr;
4940 	void *cur, *end;
4941 
4942 	hdr = &btf->hdr;
4943 	cur = btf->nohdr_data + hdr->type_off;
4944 	end = cur + hdr->type_len;
4945 
4946 	env->log_type_id = btf->base_btf ? btf->start_id : 1;
4947 	while (cur < end) {
4948 		struct btf_type *t = cur;
4949 		s32 meta_size;
4950 
4951 		meta_size = btf_check_meta(env, t, end - cur);
4952 		if (meta_size < 0)
4953 			return meta_size;
4954 
4955 		btf_add_type(env, t);
4956 		cur += meta_size;
4957 		env->log_type_id++;
4958 	}
4959 
4960 	return 0;
4961 }
4962 
4963 static bool btf_resolve_valid(struct btf_verifier_env *env,
4964 			      const struct btf_type *t,
4965 			      u32 type_id)
4966 {
4967 	struct btf *btf = env->btf;
4968 
4969 	if (!env_type_is_resolved(env, type_id))
4970 		return false;
4971 
4972 	if (btf_type_is_struct(t) || btf_type_is_datasec(t))
4973 		return !btf_resolved_type_id(btf, type_id) &&
4974 		       !btf_resolved_type_size(btf, type_id);
4975 
4976 	if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
4977 		return btf_resolved_type_id(btf, type_id) &&
4978 		       !btf_resolved_type_size(btf, type_id);
4979 
4980 	if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
4981 	    btf_type_is_var(t)) {
4982 		t = btf_type_id_resolve(btf, &type_id);
4983 		return t &&
4984 		       !btf_type_is_modifier(t) &&
4985 		       !btf_type_is_var(t) &&
4986 		       !btf_type_is_datasec(t);
4987 	}
4988 
4989 	if (btf_type_is_array(t)) {
4990 		const struct btf_array *array = btf_type_array(t);
4991 		const struct btf_type *elem_type;
4992 		u32 elem_type_id = array->type;
4993 		u32 elem_size;
4994 
4995 		elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
4996 		return elem_type && !btf_type_is_modifier(elem_type) &&
4997 			(array->nelems * elem_size ==
4998 			 btf_resolved_type_size(btf, type_id));
4999 	}
5000 
5001 	return false;
5002 }
5003 
5004 static int btf_resolve(struct btf_verifier_env *env,
5005 		       const struct btf_type *t, u32 type_id)
5006 {
5007 	u32 save_log_type_id = env->log_type_id;
5008 	const struct resolve_vertex *v;
5009 	int err = 0;
5010 
5011 	env->resolve_mode = RESOLVE_TBD;
5012 	env_stack_push(env, t, type_id);
5013 	while (!err && (v = env_stack_peak(env))) {
5014 		env->log_type_id = v->type_id;
5015 		err = btf_type_ops(v->t)->resolve(env, v);
5016 	}
5017 
5018 	env->log_type_id = type_id;
5019 	if (err == -E2BIG) {
5020 		btf_verifier_log_type(env, t,
5021 				      "Exceeded max resolving depth:%u",
5022 				      MAX_RESOLVE_DEPTH);
5023 	} else if (err == -EEXIST) {
5024 		btf_verifier_log_type(env, t, "Loop detected");
5025 	}
5026 
5027 	/* Final sanity check */
5028 	if (!err && !btf_resolve_valid(env, t, type_id)) {
5029 		btf_verifier_log_type(env, t, "Invalid resolve state");
5030 		err = -EINVAL;
5031 	}
5032 
5033 	env->log_type_id = save_log_type_id;
5034 	return err;
5035 }
5036 
5037 static int btf_check_all_types(struct btf_verifier_env *env)
5038 {
5039 	struct btf *btf = env->btf;
5040 	const struct btf_type *t;
5041 	u32 type_id, i;
5042 	int err;
5043 
5044 	err = env_resolve_init(env);
5045 	if (err)
5046 		return err;
5047 
5048 	env->phase++;
5049 	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5050 		type_id = btf->start_id + i;
5051 		t = btf_type_by_id(btf, type_id);
5052 
5053 		env->log_type_id = type_id;
5054 		if (btf_type_needs_resolve(t) &&
5055 		    !env_type_is_resolved(env, type_id)) {
5056 			err = btf_resolve(env, t, type_id);
5057 			if (err)
5058 				return err;
5059 		}
5060 
5061 		if (btf_type_is_func_proto(t)) {
5062 			err = btf_func_proto_check(env, t);
5063 			if (err)
5064 				return err;
5065 		}
5066 	}
5067 
5068 	return 0;
5069 }
5070 
5071 static int btf_parse_type_sec(struct btf_verifier_env *env)
5072 {
5073 	const struct btf_header *hdr = &env->btf->hdr;
5074 	int err;
5075 
5076 	/* Type section must align to 4 bytes */
5077 	if (hdr->type_off & (sizeof(u32) - 1)) {
5078 		btf_verifier_log(env, "Unaligned type_off");
5079 		return -EINVAL;
5080 	}
5081 
5082 	if (!env->btf->base_btf && !hdr->type_len) {
5083 		btf_verifier_log(env, "No type found");
5084 		return -EINVAL;
5085 	}
5086 
5087 	err = btf_check_all_metas(env);
5088 	if (err)
5089 		return err;
5090 
5091 	return btf_check_all_types(env);
5092 }
5093 
5094 static int btf_parse_str_sec(struct btf_verifier_env *env)
5095 {
5096 	const struct btf_header *hdr;
5097 	struct btf *btf = env->btf;
5098 	const char *start, *end;
5099 
5100 	hdr = &btf->hdr;
5101 	start = btf->nohdr_data + hdr->str_off;
5102 	end = start + hdr->str_len;
5103 
5104 	if (end != btf->data + btf->data_size) {
5105 		btf_verifier_log(env, "String section is not at the end");
5106 		return -EINVAL;
5107 	}
5108 
5109 	btf->strings = start;
5110 
5111 	if (btf->base_btf && !hdr->str_len)
5112 		return 0;
5113 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5114 		btf_verifier_log(env, "Invalid string section");
5115 		return -EINVAL;
5116 	}
5117 	if (!btf->base_btf && start[0]) {
5118 		btf_verifier_log(env, "Invalid string section");
5119 		return -EINVAL;
5120 	}
5121 
5122 	return 0;
5123 }
5124 
5125 static const size_t btf_sec_info_offset[] = {
5126 	offsetof(struct btf_header, type_off),
5127 	offsetof(struct btf_header, str_off),
5128 };
5129 
5130 static int btf_sec_info_cmp(const void *a, const void *b)
5131 {
5132 	const struct btf_sec_info *x = a;
5133 	const struct btf_sec_info *y = b;
5134 
5135 	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5136 }
5137 
5138 static int btf_check_sec_info(struct btf_verifier_env *env,
5139 			      u32 btf_data_size)
5140 {
5141 	struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5142 	u32 total, expected_total, i;
5143 	const struct btf_header *hdr;
5144 	const struct btf *btf;
5145 
5146 	btf = env->btf;
5147 	hdr = &btf->hdr;
5148 
5149 	/* Populate the secs from hdr */
5150 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5151 		secs[i] = *(struct btf_sec_info *)((void *)hdr +
5152 						   btf_sec_info_offset[i]);
5153 
5154 	sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5155 	     sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5156 
5157 	/* Check for gaps and overlap among sections */
5158 	total = 0;
5159 	expected_total = btf_data_size - hdr->hdr_len;
5160 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5161 		if (expected_total < secs[i].off) {
5162 			btf_verifier_log(env, "Invalid section offset");
5163 			return -EINVAL;
5164 		}
5165 		if (total < secs[i].off) {
5166 			/* gap */
5167 			btf_verifier_log(env, "Unsupported section found");
5168 			return -EINVAL;
5169 		}
5170 		if (total > secs[i].off) {
5171 			btf_verifier_log(env, "Section overlap found");
5172 			return -EINVAL;
5173 		}
5174 		if (expected_total - total < secs[i].len) {
5175 			btf_verifier_log(env,
5176 					 "Total section length too long");
5177 			return -EINVAL;
5178 		}
5179 		total += secs[i].len;
5180 	}
5181 
5182 	/* There is data other than hdr and known sections */
5183 	if (expected_total != total) {
5184 		btf_verifier_log(env, "Unsupported section found");
5185 		return -EINVAL;
5186 	}
5187 
5188 	return 0;
5189 }
5190 
5191 static int btf_parse_hdr(struct btf_verifier_env *env)
5192 {
5193 	u32 hdr_len, hdr_copy, btf_data_size;
5194 	const struct btf_header *hdr;
5195 	struct btf *btf;
5196 
5197 	btf = env->btf;
5198 	btf_data_size = btf->data_size;
5199 
5200 	if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5201 		btf_verifier_log(env, "hdr_len not found");
5202 		return -EINVAL;
5203 	}
5204 
5205 	hdr = btf->data;
5206 	hdr_len = hdr->hdr_len;
5207 	if (btf_data_size < hdr_len) {
5208 		btf_verifier_log(env, "btf_header not found");
5209 		return -EINVAL;
5210 	}
5211 
5212 	/* Ensure the unsupported header fields are zero */
5213 	if (hdr_len > sizeof(btf->hdr)) {
5214 		u8 *expected_zero = btf->data + sizeof(btf->hdr);
5215 		u8 *end = btf->data + hdr_len;
5216 
5217 		for (; expected_zero < end; expected_zero++) {
5218 			if (*expected_zero) {
5219 				btf_verifier_log(env, "Unsupported btf_header");
5220 				return -E2BIG;
5221 			}
5222 		}
5223 	}
5224 
5225 	hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5226 	memcpy(&btf->hdr, btf->data, hdr_copy);
5227 
5228 	hdr = &btf->hdr;
5229 
5230 	btf_verifier_log_hdr(env, btf_data_size);
5231 
5232 	if (hdr->magic != BTF_MAGIC) {
5233 		btf_verifier_log(env, "Invalid magic");
5234 		return -EINVAL;
5235 	}
5236 
5237 	if (hdr->version != BTF_VERSION) {
5238 		btf_verifier_log(env, "Unsupported version");
5239 		return -ENOTSUPP;
5240 	}
5241 
5242 	if (hdr->flags) {
5243 		btf_verifier_log(env, "Unsupported flags");
5244 		return -ENOTSUPP;
5245 	}
5246 
5247 	if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5248 		btf_verifier_log(env, "No data");
5249 		return -EINVAL;
5250 	}
5251 
5252 	return btf_check_sec_info(env, btf_data_size);
5253 }
5254 
5255 static const char *alloc_obj_fields[] = {
5256 	"bpf_spin_lock",
5257 	"bpf_list_head",
5258 	"bpf_list_node",
5259 };
5260 
5261 static struct btf_struct_metas *
5262 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5263 {
5264 	union {
5265 		struct btf_id_set set;
5266 		struct {
5267 			u32 _cnt;
5268 			u32 _ids[ARRAY_SIZE(alloc_obj_fields)];
5269 		} _arr;
5270 	} aof;
5271 	struct btf_struct_metas *tab = NULL;
5272 	int i, n, id, ret;
5273 
5274 	BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5275 	BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5276 
5277 	memset(&aof, 0, sizeof(aof));
5278 	for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5279 		/* Try to find whether this special type exists in user BTF, and
5280 		 * if so remember its ID so we can easily find it among members
5281 		 * of structs that we iterate in the next loop.
5282 		 */
5283 		id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5284 		if (id < 0)
5285 			continue;
5286 		aof.set.ids[aof.set.cnt++] = id;
5287 	}
5288 
5289 	if (!aof.set.cnt)
5290 		return NULL;
5291 	sort(&aof.set.ids, aof.set.cnt, sizeof(aof.set.ids[0]), btf_id_cmp_func, NULL);
5292 
5293 	n = btf_nr_types(btf);
5294 	for (i = 1; i < n; i++) {
5295 		struct btf_struct_metas *new_tab;
5296 		const struct btf_member *member;
5297 		struct btf_field_offs *foffs;
5298 		struct btf_struct_meta *type;
5299 		struct btf_record *record;
5300 		const struct btf_type *t;
5301 		int j, tab_cnt;
5302 
5303 		t = btf_type_by_id(btf, i);
5304 		if (!t) {
5305 			ret = -EINVAL;
5306 			goto free;
5307 		}
5308 		if (!__btf_type_is_struct(t))
5309 			continue;
5310 
5311 		cond_resched();
5312 
5313 		for_each_member(j, t, member) {
5314 			if (btf_id_set_contains(&aof.set, member->type))
5315 				goto parse;
5316 		}
5317 		continue;
5318 	parse:
5319 		tab_cnt = tab ? tab->cnt : 0;
5320 		new_tab = krealloc(tab, offsetof(struct btf_struct_metas, types[tab_cnt + 1]),
5321 				   GFP_KERNEL | __GFP_NOWARN);
5322 		if (!new_tab) {
5323 			ret = -ENOMEM;
5324 			goto free;
5325 		}
5326 		if (!tab)
5327 			new_tab->cnt = 0;
5328 		tab = new_tab;
5329 
5330 		type = &tab->types[tab->cnt];
5331 		type->btf_id = i;
5332 		record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE, t->size);
5333 		/* The record cannot be unset, treat it as an error if so */
5334 		if (IS_ERR_OR_NULL(record)) {
5335 			ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5336 			goto free;
5337 		}
5338 		foffs = btf_parse_field_offs(record);
5339 		/* We need the field_offs to be valid for a valid record,
5340 		 * either both should be set or both should be unset.
5341 		 */
5342 		if (IS_ERR_OR_NULL(foffs)) {
5343 			btf_record_free(record);
5344 			ret = -EFAULT;
5345 			goto free;
5346 		}
5347 		type->record = record;
5348 		type->field_offs = foffs;
5349 		tab->cnt++;
5350 	}
5351 	return tab;
5352 free:
5353 	btf_struct_metas_free(tab);
5354 	return ERR_PTR(ret);
5355 }
5356 
5357 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5358 {
5359 	struct btf_struct_metas *tab;
5360 
5361 	BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5362 	tab = btf->struct_meta_tab;
5363 	if (!tab)
5364 		return NULL;
5365 	return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5366 }
5367 
5368 static int btf_check_type_tags(struct btf_verifier_env *env,
5369 			       struct btf *btf, int start_id)
5370 {
5371 	int i, n, good_id = start_id - 1;
5372 	bool in_tags;
5373 
5374 	n = btf_nr_types(btf);
5375 	for (i = start_id; i < n; i++) {
5376 		const struct btf_type *t;
5377 		int chain_limit = 32;
5378 		u32 cur_id = i;
5379 
5380 		t = btf_type_by_id(btf, i);
5381 		if (!t)
5382 			return -EINVAL;
5383 		if (!btf_type_is_modifier(t))
5384 			continue;
5385 
5386 		cond_resched();
5387 
5388 		in_tags = btf_type_is_type_tag(t);
5389 		while (btf_type_is_modifier(t)) {
5390 			if (!chain_limit--) {
5391 				btf_verifier_log(env, "Max chain length or cycle detected");
5392 				return -ELOOP;
5393 			}
5394 			if (btf_type_is_type_tag(t)) {
5395 				if (!in_tags) {
5396 					btf_verifier_log(env, "Type tags don't precede modifiers");
5397 					return -EINVAL;
5398 				}
5399 			} else if (in_tags) {
5400 				in_tags = false;
5401 			}
5402 			if (cur_id <= good_id)
5403 				break;
5404 			/* Move to next type */
5405 			cur_id = t->type;
5406 			t = btf_type_by_id(btf, cur_id);
5407 			if (!t)
5408 				return -EINVAL;
5409 		}
5410 		good_id = i;
5411 	}
5412 	return 0;
5413 }
5414 
5415 static struct btf *btf_parse(bpfptr_t btf_data, u32 btf_data_size,
5416 			     u32 log_level, char __user *log_ubuf, u32 log_size)
5417 {
5418 	struct btf_struct_metas *struct_meta_tab;
5419 	struct btf_verifier_env *env = NULL;
5420 	struct bpf_verifier_log *log;
5421 	struct btf *btf = NULL;
5422 	u8 *data;
5423 	int err;
5424 
5425 	if (btf_data_size > BTF_MAX_SIZE)
5426 		return ERR_PTR(-E2BIG);
5427 
5428 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5429 	if (!env)
5430 		return ERR_PTR(-ENOMEM);
5431 
5432 	log = &env->log;
5433 	if (log_level || log_ubuf || log_size) {
5434 		/* user requested verbose verifier output
5435 		 * and supplied buffer to store the verification trace
5436 		 */
5437 		log->level = log_level;
5438 		log->ubuf = log_ubuf;
5439 		log->len_total = log_size;
5440 
5441 		/* log attributes have to be sane */
5442 		if (!bpf_verifier_log_attr_valid(log)) {
5443 			err = -EINVAL;
5444 			goto errout;
5445 		}
5446 	}
5447 
5448 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5449 	if (!btf) {
5450 		err = -ENOMEM;
5451 		goto errout;
5452 	}
5453 	env->btf = btf;
5454 
5455 	data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
5456 	if (!data) {
5457 		err = -ENOMEM;
5458 		goto errout;
5459 	}
5460 
5461 	btf->data = data;
5462 	btf->data_size = btf_data_size;
5463 
5464 	if (copy_from_bpfptr(data, btf_data, btf_data_size)) {
5465 		err = -EFAULT;
5466 		goto errout;
5467 	}
5468 
5469 	err = btf_parse_hdr(env);
5470 	if (err)
5471 		goto errout;
5472 
5473 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5474 
5475 	err = btf_parse_str_sec(env);
5476 	if (err)
5477 		goto errout;
5478 
5479 	err = btf_parse_type_sec(env);
5480 	if (err)
5481 		goto errout;
5482 
5483 	err = btf_check_type_tags(env, btf, 1);
5484 	if (err)
5485 		goto errout;
5486 
5487 	struct_meta_tab = btf_parse_struct_metas(log, btf);
5488 	if (IS_ERR(struct_meta_tab)) {
5489 		err = PTR_ERR(struct_meta_tab);
5490 		goto errout;
5491 	}
5492 	btf->struct_meta_tab = struct_meta_tab;
5493 
5494 	if (struct_meta_tab) {
5495 		int i;
5496 
5497 		for (i = 0; i < struct_meta_tab->cnt; i++) {
5498 			err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5499 			if (err < 0)
5500 				goto errout_meta;
5501 		}
5502 	}
5503 
5504 	if (log->level && bpf_verifier_log_full(log)) {
5505 		err = -ENOSPC;
5506 		goto errout_meta;
5507 	}
5508 
5509 	btf_verifier_env_free(env);
5510 	refcount_set(&btf->refcnt, 1);
5511 	return btf;
5512 
5513 errout_meta:
5514 	btf_free_struct_meta_tab(btf);
5515 errout:
5516 	btf_verifier_env_free(env);
5517 	if (btf)
5518 		btf_free(btf);
5519 	return ERR_PTR(err);
5520 }
5521 
5522 extern char __weak __start_BTF[];
5523 extern char __weak __stop_BTF[];
5524 extern struct btf *btf_vmlinux;
5525 
5526 #define BPF_MAP_TYPE(_id, _ops)
5527 #define BPF_LINK_TYPE(_id, _name)
5528 static union {
5529 	struct bpf_ctx_convert {
5530 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5531 	prog_ctx_type _id##_prog; \
5532 	kern_ctx_type _id##_kern;
5533 #include <linux/bpf_types.h>
5534 #undef BPF_PROG_TYPE
5535 	} *__t;
5536 	/* 't' is written once under lock. Read many times. */
5537 	const struct btf_type *t;
5538 } bpf_ctx_convert;
5539 enum {
5540 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5541 	__ctx_convert##_id,
5542 #include <linux/bpf_types.h>
5543 #undef BPF_PROG_TYPE
5544 	__ctx_convert_unused, /* to avoid empty enum in extreme .config */
5545 };
5546 static u8 bpf_ctx_convert_map[] = {
5547 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5548 	[_id] = __ctx_convert##_id,
5549 #include <linux/bpf_types.h>
5550 #undef BPF_PROG_TYPE
5551 	0, /* avoid empty array */
5552 };
5553 #undef BPF_MAP_TYPE
5554 #undef BPF_LINK_TYPE
5555 
5556 const struct btf_member *
5557 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5558 		      const struct btf_type *t, enum bpf_prog_type prog_type,
5559 		      int arg)
5560 {
5561 	const struct btf_type *conv_struct;
5562 	const struct btf_type *ctx_struct;
5563 	const struct btf_member *ctx_type;
5564 	const char *tname, *ctx_tname;
5565 
5566 	conv_struct = bpf_ctx_convert.t;
5567 	if (!conv_struct) {
5568 		bpf_log(log, "btf_vmlinux is malformed\n");
5569 		return NULL;
5570 	}
5571 	t = btf_type_by_id(btf, t->type);
5572 	while (btf_type_is_modifier(t))
5573 		t = btf_type_by_id(btf, t->type);
5574 	if (!btf_type_is_struct(t)) {
5575 		/* Only pointer to struct is supported for now.
5576 		 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5577 		 * is not supported yet.
5578 		 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5579 		 */
5580 		return NULL;
5581 	}
5582 	tname = btf_name_by_offset(btf, t->name_off);
5583 	if (!tname) {
5584 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5585 		return NULL;
5586 	}
5587 	/* prog_type is valid bpf program type. No need for bounds check. */
5588 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5589 	/* ctx_struct is a pointer to prog_ctx_type in vmlinux.
5590 	 * Like 'struct __sk_buff'
5591 	 */
5592 	ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
5593 	if (!ctx_struct)
5594 		/* should not happen */
5595 		return NULL;
5596 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
5597 	if (!ctx_tname) {
5598 		/* should not happen */
5599 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5600 		return NULL;
5601 	}
5602 	/* only compare that prog's ctx type name is the same as
5603 	 * kernel expects. No need to compare field by field.
5604 	 * It's ok for bpf prog to do:
5605 	 * struct __sk_buff {};
5606 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5607 	 * { // no fields of skb are ever used }
5608 	 */
5609 	if (strcmp(ctx_tname, tname))
5610 		return NULL;
5611 	return ctx_type;
5612 }
5613 
5614 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5615 				     struct btf *btf,
5616 				     const struct btf_type *t,
5617 				     enum bpf_prog_type prog_type,
5618 				     int arg)
5619 {
5620 	const struct btf_member *prog_ctx_type, *kern_ctx_type;
5621 
5622 	prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
5623 	if (!prog_ctx_type)
5624 		return -ENOENT;
5625 	kern_ctx_type = prog_ctx_type + 1;
5626 	return kern_ctx_type->type;
5627 }
5628 
5629 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
5630 {
5631 	const struct btf_member *kctx_member;
5632 	const struct btf_type *conv_struct;
5633 	const struct btf_type *kctx_type;
5634 	u32 kctx_type_id;
5635 
5636 	conv_struct = bpf_ctx_convert.t;
5637 	/* get member for kernel ctx type */
5638 	kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5639 	kctx_type_id = kctx_member->type;
5640 	kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
5641 	if (!btf_type_is_struct(kctx_type)) {
5642 		bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
5643 		return -EINVAL;
5644 	}
5645 
5646 	return kctx_type_id;
5647 }
5648 
5649 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5650 BTF_ID(struct, bpf_ctx_convert)
5651 
5652 struct btf *btf_parse_vmlinux(void)
5653 {
5654 	struct btf_verifier_env *env = NULL;
5655 	struct bpf_verifier_log *log;
5656 	struct btf *btf = NULL;
5657 	int err;
5658 
5659 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5660 	if (!env)
5661 		return ERR_PTR(-ENOMEM);
5662 
5663 	log = &env->log;
5664 	log->level = BPF_LOG_KERNEL;
5665 
5666 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5667 	if (!btf) {
5668 		err = -ENOMEM;
5669 		goto errout;
5670 	}
5671 	env->btf = btf;
5672 
5673 	btf->data = __start_BTF;
5674 	btf->data_size = __stop_BTF - __start_BTF;
5675 	btf->kernel_btf = true;
5676 	snprintf(btf->name, sizeof(btf->name), "vmlinux");
5677 
5678 	err = btf_parse_hdr(env);
5679 	if (err)
5680 		goto errout;
5681 
5682 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5683 
5684 	err = btf_parse_str_sec(env);
5685 	if (err)
5686 		goto errout;
5687 
5688 	err = btf_check_all_metas(env);
5689 	if (err)
5690 		goto errout;
5691 
5692 	err = btf_check_type_tags(env, btf, 1);
5693 	if (err)
5694 		goto errout;
5695 
5696 	/* btf_parse_vmlinux() runs under bpf_verifier_lock */
5697 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
5698 
5699 	bpf_struct_ops_init(btf, log);
5700 
5701 	refcount_set(&btf->refcnt, 1);
5702 
5703 	err = btf_alloc_id(btf);
5704 	if (err)
5705 		goto errout;
5706 
5707 	btf_verifier_env_free(env);
5708 	return btf;
5709 
5710 errout:
5711 	btf_verifier_env_free(env);
5712 	if (btf) {
5713 		kvfree(btf->types);
5714 		kfree(btf);
5715 	}
5716 	return ERR_PTR(err);
5717 }
5718 
5719 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5720 
5721 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
5722 {
5723 	struct btf_verifier_env *env = NULL;
5724 	struct bpf_verifier_log *log;
5725 	struct btf *btf = NULL, *base_btf;
5726 	int err;
5727 
5728 	base_btf = bpf_get_btf_vmlinux();
5729 	if (IS_ERR(base_btf))
5730 		return base_btf;
5731 	if (!base_btf)
5732 		return ERR_PTR(-EINVAL);
5733 
5734 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5735 	if (!env)
5736 		return ERR_PTR(-ENOMEM);
5737 
5738 	log = &env->log;
5739 	log->level = BPF_LOG_KERNEL;
5740 
5741 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5742 	if (!btf) {
5743 		err = -ENOMEM;
5744 		goto errout;
5745 	}
5746 	env->btf = btf;
5747 
5748 	btf->base_btf = base_btf;
5749 	btf->start_id = base_btf->nr_types;
5750 	btf->start_str_off = base_btf->hdr.str_len;
5751 	btf->kernel_btf = true;
5752 	snprintf(btf->name, sizeof(btf->name), "%s", module_name);
5753 
5754 	btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
5755 	if (!btf->data) {
5756 		err = -ENOMEM;
5757 		goto errout;
5758 	}
5759 	memcpy(btf->data, data, data_size);
5760 	btf->data_size = data_size;
5761 
5762 	err = btf_parse_hdr(env);
5763 	if (err)
5764 		goto errout;
5765 
5766 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5767 
5768 	err = btf_parse_str_sec(env);
5769 	if (err)
5770 		goto errout;
5771 
5772 	err = btf_check_all_metas(env);
5773 	if (err)
5774 		goto errout;
5775 
5776 	err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
5777 	if (err)
5778 		goto errout;
5779 
5780 	btf_verifier_env_free(env);
5781 	refcount_set(&btf->refcnt, 1);
5782 	return btf;
5783 
5784 errout:
5785 	btf_verifier_env_free(env);
5786 	if (btf) {
5787 		kvfree(btf->data);
5788 		kvfree(btf->types);
5789 		kfree(btf);
5790 	}
5791 	return ERR_PTR(err);
5792 }
5793 
5794 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5795 
5796 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
5797 {
5798 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5799 
5800 	if (tgt_prog)
5801 		return tgt_prog->aux->btf;
5802 	else
5803 		return prog->aux->attach_btf;
5804 }
5805 
5806 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
5807 {
5808 	/* t comes in already as a pointer */
5809 	t = btf_type_by_id(btf, t->type);
5810 
5811 	/* allow const */
5812 	if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
5813 		t = btf_type_by_id(btf, t->type);
5814 
5815 	return btf_type_is_int(t);
5816 }
5817 
5818 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
5819 			   int off)
5820 {
5821 	const struct btf_param *args;
5822 	const struct btf_type *t;
5823 	u32 offset = 0, nr_args;
5824 	int i;
5825 
5826 	if (!func_proto)
5827 		return off / 8;
5828 
5829 	nr_args = btf_type_vlen(func_proto);
5830 	args = (const struct btf_param *)(func_proto + 1);
5831 	for (i = 0; i < nr_args; i++) {
5832 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
5833 		offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5834 		if (off < offset)
5835 			return i;
5836 	}
5837 
5838 	t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
5839 	offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5840 	if (off < offset)
5841 		return nr_args;
5842 
5843 	return nr_args + 1;
5844 }
5845 
5846 static bool prog_args_trusted(const struct bpf_prog *prog)
5847 {
5848 	enum bpf_attach_type atype = prog->expected_attach_type;
5849 
5850 	switch (prog->type) {
5851 	case BPF_PROG_TYPE_TRACING:
5852 		return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
5853 	case BPF_PROG_TYPE_LSM:
5854 		return bpf_lsm_is_trusted(prog);
5855 	case BPF_PROG_TYPE_STRUCT_OPS:
5856 		return true;
5857 	default:
5858 		return false;
5859 	}
5860 }
5861 
5862 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
5863 		    const struct bpf_prog *prog,
5864 		    struct bpf_insn_access_aux *info)
5865 {
5866 	const struct btf_type *t = prog->aux->attach_func_proto;
5867 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5868 	struct btf *btf = bpf_prog_get_target_btf(prog);
5869 	const char *tname = prog->aux->attach_func_name;
5870 	struct bpf_verifier_log *log = info->log;
5871 	const struct btf_param *args;
5872 	const char *tag_value;
5873 	u32 nr_args, arg;
5874 	int i, ret;
5875 
5876 	if (off % 8) {
5877 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
5878 			tname, off);
5879 		return false;
5880 	}
5881 	arg = get_ctx_arg_idx(btf, t, off);
5882 	args = (const struct btf_param *)(t + 1);
5883 	/* if (t == NULL) Fall back to default BPF prog with
5884 	 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
5885 	 */
5886 	nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
5887 	if (prog->aux->attach_btf_trace) {
5888 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
5889 		args++;
5890 		nr_args--;
5891 	}
5892 
5893 	if (arg > nr_args) {
5894 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5895 			tname, arg + 1);
5896 		return false;
5897 	}
5898 
5899 	if (arg == nr_args) {
5900 		switch (prog->expected_attach_type) {
5901 		case BPF_LSM_CGROUP:
5902 		case BPF_LSM_MAC:
5903 		case BPF_TRACE_FEXIT:
5904 			/* When LSM programs are attached to void LSM hooks
5905 			 * they use FEXIT trampolines and when attached to
5906 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
5907 			 *
5908 			 * While the LSM programs are BPF_MODIFY_RETURN-like
5909 			 * the check:
5910 			 *
5911 			 *	if (ret_type != 'int')
5912 			 *		return -EINVAL;
5913 			 *
5914 			 * is _not_ done here. This is still safe as LSM hooks
5915 			 * have only void and int return types.
5916 			 */
5917 			if (!t)
5918 				return true;
5919 			t = btf_type_by_id(btf, t->type);
5920 			break;
5921 		case BPF_MODIFY_RETURN:
5922 			/* For now the BPF_MODIFY_RETURN can only be attached to
5923 			 * functions that return an int.
5924 			 */
5925 			if (!t)
5926 				return false;
5927 
5928 			t = btf_type_skip_modifiers(btf, t->type, NULL);
5929 			if (!btf_type_is_small_int(t)) {
5930 				bpf_log(log,
5931 					"ret type %s not allowed for fmod_ret\n",
5932 					btf_type_str(t));
5933 				return false;
5934 			}
5935 			break;
5936 		default:
5937 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5938 				tname, arg + 1);
5939 			return false;
5940 		}
5941 	} else {
5942 		if (!t)
5943 			/* Default prog with MAX_BPF_FUNC_REG_ARGS args */
5944 			return true;
5945 		t = btf_type_by_id(btf, args[arg].type);
5946 	}
5947 
5948 	/* skip modifiers */
5949 	while (btf_type_is_modifier(t))
5950 		t = btf_type_by_id(btf, t->type);
5951 	if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
5952 		/* accessing a scalar */
5953 		return true;
5954 	if (!btf_type_is_ptr(t)) {
5955 		bpf_log(log,
5956 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
5957 			tname, arg,
5958 			__btf_name_by_offset(btf, t->name_off),
5959 			btf_type_str(t));
5960 		return false;
5961 	}
5962 
5963 	/* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
5964 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
5965 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
5966 		u32 type, flag;
5967 
5968 		type = base_type(ctx_arg_info->reg_type);
5969 		flag = type_flag(ctx_arg_info->reg_type);
5970 		if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
5971 		    (flag & PTR_MAYBE_NULL)) {
5972 			info->reg_type = ctx_arg_info->reg_type;
5973 			return true;
5974 		}
5975 	}
5976 
5977 	if (t->type == 0)
5978 		/* This is a pointer to void.
5979 		 * It is the same as scalar from the verifier safety pov.
5980 		 * No further pointer walking is allowed.
5981 		 */
5982 		return true;
5983 
5984 	if (is_int_ptr(btf, t))
5985 		return true;
5986 
5987 	/* this is a pointer to another type */
5988 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
5989 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
5990 
5991 		if (ctx_arg_info->offset == off) {
5992 			if (!ctx_arg_info->btf_id) {
5993 				bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
5994 				return false;
5995 			}
5996 
5997 			info->reg_type = ctx_arg_info->reg_type;
5998 			info->btf = btf_vmlinux;
5999 			info->btf_id = ctx_arg_info->btf_id;
6000 			return true;
6001 		}
6002 	}
6003 
6004 	info->reg_type = PTR_TO_BTF_ID;
6005 	if (prog_args_trusted(prog))
6006 		info->reg_type |= PTR_TRUSTED;
6007 
6008 	if (tgt_prog) {
6009 		enum bpf_prog_type tgt_type;
6010 
6011 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6012 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
6013 		else
6014 			tgt_type = tgt_prog->type;
6015 
6016 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6017 		if (ret > 0) {
6018 			info->btf = btf_vmlinux;
6019 			info->btf_id = ret;
6020 			return true;
6021 		} else {
6022 			return false;
6023 		}
6024 	}
6025 
6026 	info->btf = btf;
6027 	info->btf_id = t->type;
6028 	t = btf_type_by_id(btf, t->type);
6029 
6030 	if (btf_type_is_type_tag(t)) {
6031 		tag_value = __btf_name_by_offset(btf, t->name_off);
6032 		if (strcmp(tag_value, "user") == 0)
6033 			info->reg_type |= MEM_USER;
6034 		if (strcmp(tag_value, "percpu") == 0)
6035 			info->reg_type |= MEM_PERCPU;
6036 	}
6037 
6038 	/* skip modifiers */
6039 	while (btf_type_is_modifier(t)) {
6040 		info->btf_id = t->type;
6041 		t = btf_type_by_id(btf, t->type);
6042 	}
6043 	if (!btf_type_is_struct(t)) {
6044 		bpf_log(log,
6045 			"func '%s' arg%d type %s is not a struct\n",
6046 			tname, arg, btf_type_str(t));
6047 		return false;
6048 	}
6049 	bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6050 		tname, arg, info->btf_id, btf_type_str(t),
6051 		__btf_name_by_offset(btf, t->name_off));
6052 	return true;
6053 }
6054 
6055 enum bpf_struct_walk_result {
6056 	/* < 0 error */
6057 	WALK_SCALAR = 0,
6058 	WALK_PTR,
6059 	WALK_STRUCT,
6060 };
6061 
6062 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6063 			   const struct btf_type *t, int off, int size,
6064 			   u32 *next_btf_id, enum bpf_type_flag *flag)
6065 {
6066 	u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6067 	const struct btf_type *mtype, *elem_type = NULL;
6068 	const struct btf_member *member;
6069 	const char *tname, *mname, *tag_value;
6070 	u32 vlen, elem_id, mid;
6071 
6072 again:
6073 	tname = __btf_name_by_offset(btf, t->name_off);
6074 	if (!btf_type_is_struct(t)) {
6075 		bpf_log(log, "Type '%s' is not a struct\n", tname);
6076 		return -EINVAL;
6077 	}
6078 
6079 	vlen = btf_type_vlen(t);
6080 	if (off + size > t->size) {
6081 		/* If the last element is a variable size array, we may
6082 		 * need to relax the rule.
6083 		 */
6084 		struct btf_array *array_elem;
6085 
6086 		if (vlen == 0)
6087 			goto error;
6088 
6089 		member = btf_type_member(t) + vlen - 1;
6090 		mtype = btf_type_skip_modifiers(btf, member->type,
6091 						NULL);
6092 		if (!btf_type_is_array(mtype))
6093 			goto error;
6094 
6095 		array_elem = (struct btf_array *)(mtype + 1);
6096 		if (array_elem->nelems != 0)
6097 			goto error;
6098 
6099 		moff = __btf_member_bit_offset(t, member) / 8;
6100 		if (off < moff)
6101 			goto error;
6102 
6103 		/* Only allow structure for now, can be relaxed for
6104 		 * other types later.
6105 		 */
6106 		t = btf_type_skip_modifiers(btf, array_elem->type,
6107 					    NULL);
6108 		if (!btf_type_is_struct(t))
6109 			goto error;
6110 
6111 		off = (off - moff) % t->size;
6112 		goto again;
6113 
6114 error:
6115 		bpf_log(log, "access beyond struct %s at off %u size %u\n",
6116 			tname, off, size);
6117 		return -EACCES;
6118 	}
6119 
6120 	for_each_member(i, t, member) {
6121 		/* offset of the field in bytes */
6122 		moff = __btf_member_bit_offset(t, member) / 8;
6123 		if (off + size <= moff)
6124 			/* won't find anything, field is already too far */
6125 			break;
6126 
6127 		if (__btf_member_bitfield_size(t, member)) {
6128 			u32 end_bit = __btf_member_bit_offset(t, member) +
6129 				__btf_member_bitfield_size(t, member);
6130 
6131 			/* off <= moff instead of off == moff because clang
6132 			 * does not generate a BTF member for anonymous
6133 			 * bitfield like the ":16" here:
6134 			 * struct {
6135 			 *	int :16;
6136 			 *	int x:8;
6137 			 * };
6138 			 */
6139 			if (off <= moff &&
6140 			    BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6141 				return WALK_SCALAR;
6142 
6143 			/* off may be accessing a following member
6144 			 *
6145 			 * or
6146 			 *
6147 			 * Doing partial access at either end of this
6148 			 * bitfield.  Continue on this case also to
6149 			 * treat it as not accessing this bitfield
6150 			 * and eventually error out as field not
6151 			 * found to keep it simple.
6152 			 * It could be relaxed if there was a legit
6153 			 * partial access case later.
6154 			 */
6155 			continue;
6156 		}
6157 
6158 		/* In case of "off" is pointing to holes of a struct */
6159 		if (off < moff)
6160 			break;
6161 
6162 		/* type of the field */
6163 		mid = member->type;
6164 		mtype = btf_type_by_id(btf, member->type);
6165 		mname = __btf_name_by_offset(btf, member->name_off);
6166 
6167 		mtype = __btf_resolve_size(btf, mtype, &msize,
6168 					   &elem_type, &elem_id, &total_nelems,
6169 					   &mid);
6170 		if (IS_ERR(mtype)) {
6171 			bpf_log(log, "field %s doesn't have size\n", mname);
6172 			return -EFAULT;
6173 		}
6174 
6175 		mtrue_end = moff + msize;
6176 		if (off >= mtrue_end)
6177 			/* no overlap with member, keep iterating */
6178 			continue;
6179 
6180 		if (btf_type_is_array(mtype)) {
6181 			u32 elem_idx;
6182 
6183 			/* __btf_resolve_size() above helps to
6184 			 * linearize a multi-dimensional array.
6185 			 *
6186 			 * The logic here is treating an array
6187 			 * in a struct as the following way:
6188 			 *
6189 			 * struct outer {
6190 			 *	struct inner array[2][2];
6191 			 * };
6192 			 *
6193 			 * looks like:
6194 			 *
6195 			 * struct outer {
6196 			 *	struct inner array_elem0;
6197 			 *	struct inner array_elem1;
6198 			 *	struct inner array_elem2;
6199 			 *	struct inner array_elem3;
6200 			 * };
6201 			 *
6202 			 * When accessing outer->array[1][0], it moves
6203 			 * moff to "array_elem2", set mtype to
6204 			 * "struct inner", and msize also becomes
6205 			 * sizeof(struct inner).  Then most of the
6206 			 * remaining logic will fall through without
6207 			 * caring the current member is an array or
6208 			 * not.
6209 			 *
6210 			 * Unlike mtype/msize/moff, mtrue_end does not
6211 			 * change.  The naming difference ("_true") tells
6212 			 * that it is not always corresponding to
6213 			 * the current mtype/msize/moff.
6214 			 * It is the true end of the current
6215 			 * member (i.e. array in this case).  That
6216 			 * will allow an int array to be accessed like
6217 			 * a scratch space,
6218 			 * i.e. allow access beyond the size of
6219 			 *      the array's element as long as it is
6220 			 *      within the mtrue_end boundary.
6221 			 */
6222 
6223 			/* skip empty array */
6224 			if (moff == mtrue_end)
6225 				continue;
6226 
6227 			msize /= total_nelems;
6228 			elem_idx = (off - moff) / msize;
6229 			moff += elem_idx * msize;
6230 			mtype = elem_type;
6231 			mid = elem_id;
6232 		}
6233 
6234 		/* the 'off' we're looking for is either equal to start
6235 		 * of this field or inside of this struct
6236 		 */
6237 		if (btf_type_is_struct(mtype)) {
6238 			/* our field must be inside that union or struct */
6239 			t = mtype;
6240 
6241 			/* return if the offset matches the member offset */
6242 			if (off == moff) {
6243 				*next_btf_id = mid;
6244 				return WALK_STRUCT;
6245 			}
6246 
6247 			/* adjust offset we're looking for */
6248 			off -= moff;
6249 			goto again;
6250 		}
6251 
6252 		if (btf_type_is_ptr(mtype)) {
6253 			const struct btf_type *stype, *t;
6254 			enum bpf_type_flag tmp_flag = 0;
6255 			u32 id;
6256 
6257 			if (msize != size || off != moff) {
6258 				bpf_log(log,
6259 					"cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6260 					mname, moff, tname, off, size);
6261 				return -EACCES;
6262 			}
6263 
6264 			/* check type tag */
6265 			t = btf_type_by_id(btf, mtype->type);
6266 			if (btf_type_is_type_tag(t)) {
6267 				tag_value = __btf_name_by_offset(btf, t->name_off);
6268 				/* check __user tag */
6269 				if (strcmp(tag_value, "user") == 0)
6270 					tmp_flag = MEM_USER;
6271 				/* check __percpu tag */
6272 				if (strcmp(tag_value, "percpu") == 0)
6273 					tmp_flag = MEM_PERCPU;
6274 				/* check __rcu tag */
6275 				if (strcmp(tag_value, "rcu") == 0)
6276 					tmp_flag = MEM_RCU;
6277 			}
6278 
6279 			stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6280 			if (btf_type_is_struct(stype)) {
6281 				*next_btf_id = id;
6282 				*flag = tmp_flag;
6283 				return WALK_PTR;
6284 			}
6285 		}
6286 
6287 		/* Allow more flexible access within an int as long as
6288 		 * it is within mtrue_end.
6289 		 * Since mtrue_end could be the end of an array,
6290 		 * that also allows using an array of int as a scratch
6291 		 * space. e.g. skb->cb[].
6292 		 */
6293 		if (off + size > mtrue_end) {
6294 			bpf_log(log,
6295 				"access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6296 				mname, mtrue_end, tname, off, size);
6297 			return -EACCES;
6298 		}
6299 
6300 		return WALK_SCALAR;
6301 	}
6302 	bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6303 	return -EINVAL;
6304 }
6305 
6306 int btf_struct_access(struct bpf_verifier_log *log,
6307 		      const struct bpf_reg_state *reg,
6308 		      int off, int size, enum bpf_access_type atype __maybe_unused,
6309 		      u32 *next_btf_id, enum bpf_type_flag *flag)
6310 {
6311 	const struct btf *btf = reg->btf;
6312 	enum bpf_type_flag tmp_flag = 0;
6313 	const struct btf_type *t;
6314 	u32 id = reg->btf_id;
6315 	int err;
6316 
6317 	while (type_is_alloc(reg->type)) {
6318 		struct btf_struct_meta *meta;
6319 		struct btf_record *rec;
6320 		int i;
6321 
6322 		meta = btf_find_struct_meta(btf, id);
6323 		if (!meta)
6324 			break;
6325 		rec = meta->record;
6326 		for (i = 0; i < rec->cnt; i++) {
6327 			struct btf_field *field = &rec->fields[i];
6328 			u32 offset = field->offset;
6329 			if (off < offset + btf_field_type_size(field->type) && offset < off + size) {
6330 				bpf_log(log,
6331 					"direct access to %s is disallowed\n",
6332 					btf_field_type_name(field->type));
6333 				return -EACCES;
6334 			}
6335 		}
6336 		break;
6337 	}
6338 
6339 	t = btf_type_by_id(btf, id);
6340 	do {
6341 		err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag);
6342 
6343 		switch (err) {
6344 		case WALK_PTR:
6345 			/* For local types, the destination register cannot
6346 			 * become a pointer again.
6347 			 */
6348 			if (type_is_alloc(reg->type))
6349 				return SCALAR_VALUE;
6350 			/* If we found the pointer or scalar on t+off,
6351 			 * we're done.
6352 			 */
6353 			*next_btf_id = id;
6354 			*flag = tmp_flag;
6355 			return PTR_TO_BTF_ID;
6356 		case WALK_SCALAR:
6357 			return SCALAR_VALUE;
6358 		case WALK_STRUCT:
6359 			/* We found nested struct, so continue the search
6360 			 * by diving in it. At this point the offset is
6361 			 * aligned with the new type, so set it to 0.
6362 			 */
6363 			t = btf_type_by_id(btf, id);
6364 			off = 0;
6365 			break;
6366 		default:
6367 			/* It's either error or unknown return value..
6368 			 * scream and leave.
6369 			 */
6370 			if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6371 				return -EINVAL;
6372 			return err;
6373 		}
6374 	} while (t);
6375 
6376 	return -EINVAL;
6377 }
6378 
6379 /* Check that two BTF types, each specified as an BTF object + id, are exactly
6380  * the same. Trivial ID check is not enough due to module BTFs, because we can
6381  * end up with two different module BTFs, but IDs point to the common type in
6382  * vmlinux BTF.
6383  */
6384 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6385 			const struct btf *btf2, u32 id2)
6386 {
6387 	if (id1 != id2)
6388 		return false;
6389 	if (btf1 == btf2)
6390 		return true;
6391 	return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6392 }
6393 
6394 bool btf_struct_ids_match(struct bpf_verifier_log *log,
6395 			  const struct btf *btf, u32 id, int off,
6396 			  const struct btf *need_btf, u32 need_type_id,
6397 			  bool strict)
6398 {
6399 	const struct btf_type *type;
6400 	enum bpf_type_flag flag;
6401 	int err;
6402 
6403 	/* Are we already done? */
6404 	if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6405 		return true;
6406 	/* In case of strict type match, we do not walk struct, the top level
6407 	 * type match must succeed. When strict is true, off should have already
6408 	 * been 0.
6409 	 */
6410 	if (strict)
6411 		return false;
6412 again:
6413 	type = btf_type_by_id(btf, id);
6414 	if (!type)
6415 		return false;
6416 	err = btf_struct_walk(log, btf, type, off, 1, &id, &flag);
6417 	if (err != WALK_STRUCT)
6418 		return false;
6419 
6420 	/* We found nested struct object. If it matches
6421 	 * the requested ID, we're done. Otherwise let's
6422 	 * continue the search with offset 0 in the new
6423 	 * type.
6424 	 */
6425 	if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6426 		off = 0;
6427 		goto again;
6428 	}
6429 
6430 	return true;
6431 }
6432 
6433 static int __get_type_size(struct btf *btf, u32 btf_id,
6434 			   const struct btf_type **ret_type)
6435 {
6436 	const struct btf_type *t;
6437 
6438 	*ret_type = btf_type_by_id(btf, 0);
6439 	if (!btf_id)
6440 		/* void */
6441 		return 0;
6442 	t = btf_type_by_id(btf, btf_id);
6443 	while (t && btf_type_is_modifier(t))
6444 		t = btf_type_by_id(btf, t->type);
6445 	if (!t)
6446 		return -EINVAL;
6447 	*ret_type = t;
6448 	if (btf_type_is_ptr(t))
6449 		/* kernel size of pointer. Not BPF's size of pointer*/
6450 		return sizeof(void *);
6451 	if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6452 		return t->size;
6453 	return -EINVAL;
6454 }
6455 
6456 int btf_distill_func_proto(struct bpf_verifier_log *log,
6457 			   struct btf *btf,
6458 			   const struct btf_type *func,
6459 			   const char *tname,
6460 			   struct btf_func_model *m)
6461 {
6462 	const struct btf_param *args;
6463 	const struct btf_type *t;
6464 	u32 i, nargs;
6465 	int ret;
6466 
6467 	if (!func) {
6468 		/* BTF function prototype doesn't match the verifier types.
6469 		 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
6470 		 */
6471 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6472 			m->arg_size[i] = 8;
6473 			m->arg_flags[i] = 0;
6474 		}
6475 		m->ret_size = 8;
6476 		m->nr_args = MAX_BPF_FUNC_REG_ARGS;
6477 		return 0;
6478 	}
6479 	args = (const struct btf_param *)(func + 1);
6480 	nargs = btf_type_vlen(func);
6481 	if (nargs > MAX_BPF_FUNC_ARGS) {
6482 		bpf_log(log,
6483 			"The function %s has %d arguments. Too many.\n",
6484 			tname, nargs);
6485 		return -EINVAL;
6486 	}
6487 	ret = __get_type_size(btf, func->type, &t);
6488 	if (ret < 0 || __btf_type_is_struct(t)) {
6489 		bpf_log(log,
6490 			"The function %s return type %s is unsupported.\n",
6491 			tname, btf_type_str(t));
6492 		return -EINVAL;
6493 	}
6494 	m->ret_size = ret;
6495 
6496 	for (i = 0; i < nargs; i++) {
6497 		if (i == nargs - 1 && args[i].type == 0) {
6498 			bpf_log(log,
6499 				"The function %s with variable args is unsupported.\n",
6500 				tname);
6501 			return -EINVAL;
6502 		}
6503 		ret = __get_type_size(btf, args[i].type, &t);
6504 
6505 		/* No support of struct argument size greater than 16 bytes */
6506 		if (ret < 0 || ret > 16) {
6507 			bpf_log(log,
6508 				"The function %s arg%d type %s is unsupported.\n",
6509 				tname, i, btf_type_str(t));
6510 			return -EINVAL;
6511 		}
6512 		if (ret == 0) {
6513 			bpf_log(log,
6514 				"The function %s has malformed void argument.\n",
6515 				tname);
6516 			return -EINVAL;
6517 		}
6518 		m->arg_size[i] = ret;
6519 		m->arg_flags[i] = __btf_type_is_struct(t) ? BTF_FMODEL_STRUCT_ARG : 0;
6520 	}
6521 	m->nr_args = nargs;
6522 	return 0;
6523 }
6524 
6525 /* Compare BTFs of two functions assuming only scalars and pointers to context.
6526  * t1 points to BTF_KIND_FUNC in btf1
6527  * t2 points to BTF_KIND_FUNC in btf2
6528  * Returns:
6529  * EINVAL - function prototype mismatch
6530  * EFAULT - verifier bug
6531  * 0 - 99% match. The last 1% is validated by the verifier.
6532  */
6533 static int btf_check_func_type_match(struct bpf_verifier_log *log,
6534 				     struct btf *btf1, const struct btf_type *t1,
6535 				     struct btf *btf2, const struct btf_type *t2)
6536 {
6537 	const struct btf_param *args1, *args2;
6538 	const char *fn1, *fn2, *s1, *s2;
6539 	u32 nargs1, nargs2, i;
6540 
6541 	fn1 = btf_name_by_offset(btf1, t1->name_off);
6542 	fn2 = btf_name_by_offset(btf2, t2->name_off);
6543 
6544 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
6545 		bpf_log(log, "%s() is not a global function\n", fn1);
6546 		return -EINVAL;
6547 	}
6548 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
6549 		bpf_log(log, "%s() is not a global function\n", fn2);
6550 		return -EINVAL;
6551 	}
6552 
6553 	t1 = btf_type_by_id(btf1, t1->type);
6554 	if (!t1 || !btf_type_is_func_proto(t1))
6555 		return -EFAULT;
6556 	t2 = btf_type_by_id(btf2, t2->type);
6557 	if (!t2 || !btf_type_is_func_proto(t2))
6558 		return -EFAULT;
6559 
6560 	args1 = (const struct btf_param *)(t1 + 1);
6561 	nargs1 = btf_type_vlen(t1);
6562 	args2 = (const struct btf_param *)(t2 + 1);
6563 	nargs2 = btf_type_vlen(t2);
6564 
6565 	if (nargs1 != nargs2) {
6566 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
6567 			fn1, nargs1, fn2, nargs2);
6568 		return -EINVAL;
6569 	}
6570 
6571 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6572 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6573 	if (t1->info != t2->info) {
6574 		bpf_log(log,
6575 			"Return type %s of %s() doesn't match type %s of %s()\n",
6576 			btf_type_str(t1), fn1,
6577 			btf_type_str(t2), fn2);
6578 		return -EINVAL;
6579 	}
6580 
6581 	for (i = 0; i < nargs1; i++) {
6582 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
6583 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
6584 
6585 		if (t1->info != t2->info) {
6586 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
6587 				i, fn1, btf_type_str(t1),
6588 				fn2, btf_type_str(t2));
6589 			return -EINVAL;
6590 		}
6591 		if (btf_type_has_size(t1) && t1->size != t2->size) {
6592 			bpf_log(log,
6593 				"arg%d in %s() has size %d while %s() has %d\n",
6594 				i, fn1, t1->size,
6595 				fn2, t2->size);
6596 			return -EINVAL;
6597 		}
6598 
6599 		/* global functions are validated with scalars and pointers
6600 		 * to context only. And only global functions can be replaced.
6601 		 * Hence type check only those types.
6602 		 */
6603 		if (btf_type_is_int(t1) || btf_is_any_enum(t1))
6604 			continue;
6605 		if (!btf_type_is_ptr(t1)) {
6606 			bpf_log(log,
6607 				"arg%d in %s() has unrecognized type\n",
6608 				i, fn1);
6609 			return -EINVAL;
6610 		}
6611 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6612 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6613 		if (!btf_type_is_struct(t1)) {
6614 			bpf_log(log,
6615 				"arg%d in %s() is not a pointer to context\n",
6616 				i, fn1);
6617 			return -EINVAL;
6618 		}
6619 		if (!btf_type_is_struct(t2)) {
6620 			bpf_log(log,
6621 				"arg%d in %s() is not a pointer to context\n",
6622 				i, fn2);
6623 			return -EINVAL;
6624 		}
6625 		/* This is an optional check to make program writing easier.
6626 		 * Compare names of structs and report an error to the user.
6627 		 * btf_prepare_func_args() already checked that t2 struct
6628 		 * is a context type. btf_prepare_func_args() will check
6629 		 * later that t1 struct is a context type as well.
6630 		 */
6631 		s1 = btf_name_by_offset(btf1, t1->name_off);
6632 		s2 = btf_name_by_offset(btf2, t2->name_off);
6633 		if (strcmp(s1, s2)) {
6634 			bpf_log(log,
6635 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
6636 				i, fn1, s1, fn2, s2);
6637 			return -EINVAL;
6638 		}
6639 	}
6640 	return 0;
6641 }
6642 
6643 /* Compare BTFs of given program with BTF of target program */
6644 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
6645 			 struct btf *btf2, const struct btf_type *t2)
6646 {
6647 	struct btf *btf1 = prog->aux->btf;
6648 	const struct btf_type *t1;
6649 	u32 btf_id = 0;
6650 
6651 	if (!prog->aux->func_info) {
6652 		bpf_log(log, "Program extension requires BTF\n");
6653 		return -EINVAL;
6654 	}
6655 
6656 	btf_id = prog->aux->func_info[0].type_id;
6657 	if (!btf_id)
6658 		return -EFAULT;
6659 
6660 	t1 = btf_type_by_id(btf1, btf_id);
6661 	if (!t1 || !btf_type_is_func(t1))
6662 		return -EFAULT;
6663 
6664 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
6665 }
6666 
6667 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
6668 				    const struct btf *btf, u32 func_id,
6669 				    struct bpf_reg_state *regs,
6670 				    bool ptr_to_mem_ok,
6671 				    bool processing_call)
6672 {
6673 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6674 	struct bpf_verifier_log *log = &env->log;
6675 	const char *func_name, *ref_tname;
6676 	const struct btf_type *t, *ref_t;
6677 	const struct btf_param *args;
6678 	u32 i, nargs, ref_id;
6679 	int ret;
6680 
6681 	t = btf_type_by_id(btf, func_id);
6682 	if (!t || !btf_type_is_func(t)) {
6683 		/* These checks were already done by the verifier while loading
6684 		 * struct bpf_func_info or in add_kfunc_call().
6685 		 */
6686 		bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
6687 			func_id);
6688 		return -EFAULT;
6689 	}
6690 	func_name = btf_name_by_offset(btf, t->name_off);
6691 
6692 	t = btf_type_by_id(btf, t->type);
6693 	if (!t || !btf_type_is_func_proto(t)) {
6694 		bpf_log(log, "Invalid BTF of func %s\n", func_name);
6695 		return -EFAULT;
6696 	}
6697 	args = (const struct btf_param *)(t + 1);
6698 	nargs = btf_type_vlen(t);
6699 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6700 		bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
6701 			MAX_BPF_FUNC_REG_ARGS);
6702 		return -EINVAL;
6703 	}
6704 
6705 	/* check that BTF function arguments match actual types that the
6706 	 * verifier sees.
6707 	 */
6708 	for (i = 0; i < nargs; i++) {
6709 		enum bpf_arg_type arg_type = ARG_DONTCARE;
6710 		u32 regno = i + 1;
6711 		struct bpf_reg_state *reg = &regs[regno];
6712 
6713 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6714 		if (btf_type_is_scalar(t)) {
6715 			if (reg->type == SCALAR_VALUE)
6716 				continue;
6717 			bpf_log(log, "R%d is not a scalar\n", regno);
6718 			return -EINVAL;
6719 		}
6720 
6721 		if (!btf_type_is_ptr(t)) {
6722 			bpf_log(log, "Unrecognized arg#%d type %s\n",
6723 				i, btf_type_str(t));
6724 			return -EINVAL;
6725 		}
6726 
6727 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
6728 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6729 
6730 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
6731 		if (ret < 0)
6732 			return ret;
6733 
6734 		if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6735 			/* If function expects ctx type in BTF check that caller
6736 			 * is passing PTR_TO_CTX.
6737 			 */
6738 			if (reg->type != PTR_TO_CTX) {
6739 				bpf_log(log,
6740 					"arg#%d expected pointer to ctx, but got %s\n",
6741 					i, btf_type_str(t));
6742 				return -EINVAL;
6743 			}
6744 		} else if (ptr_to_mem_ok && processing_call) {
6745 			const struct btf_type *resolve_ret;
6746 			u32 type_size;
6747 
6748 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
6749 			if (IS_ERR(resolve_ret)) {
6750 				bpf_log(log,
6751 					"arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6752 					i, btf_type_str(ref_t), ref_tname,
6753 					PTR_ERR(resolve_ret));
6754 				return -EINVAL;
6755 			}
6756 
6757 			if (check_mem_reg(env, reg, regno, type_size))
6758 				return -EINVAL;
6759 		} else {
6760 			bpf_log(log, "reg type unsupported for arg#%d function %s#%d\n", i,
6761 				func_name, func_id);
6762 			return -EINVAL;
6763 		}
6764 	}
6765 
6766 	return 0;
6767 }
6768 
6769 /* Compare BTF of a function declaration with given bpf_reg_state.
6770  * Returns:
6771  * EFAULT - there is a verifier bug. Abort verification.
6772  * EINVAL - there is a type mismatch or BTF is not available.
6773  * 0 - BTF matches with what bpf_reg_state expects.
6774  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6775  */
6776 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
6777 				struct bpf_reg_state *regs)
6778 {
6779 	struct bpf_prog *prog = env->prog;
6780 	struct btf *btf = prog->aux->btf;
6781 	bool is_global;
6782 	u32 btf_id;
6783 	int err;
6784 
6785 	if (!prog->aux->func_info)
6786 		return -EINVAL;
6787 
6788 	btf_id = prog->aux->func_info[subprog].type_id;
6789 	if (!btf_id)
6790 		return -EFAULT;
6791 
6792 	if (prog->aux->func_info_aux[subprog].unreliable)
6793 		return -EINVAL;
6794 
6795 	is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6796 	err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, false);
6797 
6798 	/* Compiler optimizations can remove arguments from static functions
6799 	 * or mismatched type can be passed into a global function.
6800 	 * In such cases mark the function as unreliable from BTF point of view.
6801 	 */
6802 	if (err)
6803 		prog->aux->func_info_aux[subprog].unreliable = true;
6804 	return err;
6805 }
6806 
6807 /* Compare BTF of a function call with given bpf_reg_state.
6808  * Returns:
6809  * EFAULT - there is a verifier bug. Abort verification.
6810  * EINVAL - there is a type mismatch or BTF is not available.
6811  * 0 - BTF matches with what bpf_reg_state expects.
6812  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6813  *
6814  * NOTE: the code is duplicated from btf_check_subprog_arg_match()
6815  * because btf_check_func_arg_match() is still doing both. Once that
6816  * function is split in 2, we can call from here btf_check_subprog_arg_match()
6817  * first, and then treat the calling part in a new code path.
6818  */
6819 int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
6820 			   struct bpf_reg_state *regs)
6821 {
6822 	struct bpf_prog *prog = env->prog;
6823 	struct btf *btf = prog->aux->btf;
6824 	bool is_global;
6825 	u32 btf_id;
6826 	int err;
6827 
6828 	if (!prog->aux->func_info)
6829 		return -EINVAL;
6830 
6831 	btf_id = prog->aux->func_info[subprog].type_id;
6832 	if (!btf_id)
6833 		return -EFAULT;
6834 
6835 	if (prog->aux->func_info_aux[subprog].unreliable)
6836 		return -EINVAL;
6837 
6838 	is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6839 	err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, true);
6840 
6841 	/* Compiler optimizations can remove arguments from static functions
6842 	 * or mismatched type can be passed into a global function.
6843 	 * In such cases mark the function as unreliable from BTF point of view.
6844 	 */
6845 	if (err)
6846 		prog->aux->func_info_aux[subprog].unreliable = true;
6847 	return err;
6848 }
6849 
6850 /* Convert BTF of a function into bpf_reg_state if possible
6851  * Returns:
6852  * EFAULT - there is a verifier bug. Abort verification.
6853  * EINVAL - cannot convert BTF.
6854  * 0 - Successfully converted BTF into bpf_reg_state
6855  * (either PTR_TO_CTX or SCALAR_VALUE).
6856  */
6857 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
6858 			  struct bpf_reg_state *regs)
6859 {
6860 	struct bpf_verifier_log *log = &env->log;
6861 	struct bpf_prog *prog = env->prog;
6862 	enum bpf_prog_type prog_type = prog->type;
6863 	struct btf *btf = prog->aux->btf;
6864 	const struct btf_param *args;
6865 	const struct btf_type *t, *ref_t;
6866 	u32 i, nargs, btf_id;
6867 	const char *tname;
6868 
6869 	if (!prog->aux->func_info ||
6870 	    prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
6871 		bpf_log(log, "Verifier bug\n");
6872 		return -EFAULT;
6873 	}
6874 
6875 	btf_id = prog->aux->func_info[subprog].type_id;
6876 	if (!btf_id) {
6877 		bpf_log(log, "Global functions need valid BTF\n");
6878 		return -EFAULT;
6879 	}
6880 
6881 	t = btf_type_by_id(btf, btf_id);
6882 	if (!t || !btf_type_is_func(t)) {
6883 		/* These checks were already done by the verifier while loading
6884 		 * struct bpf_func_info
6885 		 */
6886 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
6887 			subprog);
6888 		return -EFAULT;
6889 	}
6890 	tname = btf_name_by_offset(btf, t->name_off);
6891 
6892 	if (log->level & BPF_LOG_LEVEL)
6893 		bpf_log(log, "Validating %s() func#%d...\n",
6894 			tname, subprog);
6895 
6896 	if (prog->aux->func_info_aux[subprog].unreliable) {
6897 		bpf_log(log, "Verifier bug in function %s()\n", tname);
6898 		return -EFAULT;
6899 	}
6900 	if (prog_type == BPF_PROG_TYPE_EXT)
6901 		prog_type = prog->aux->dst_prog->type;
6902 
6903 	t = btf_type_by_id(btf, t->type);
6904 	if (!t || !btf_type_is_func_proto(t)) {
6905 		bpf_log(log, "Invalid type of function %s()\n", tname);
6906 		return -EFAULT;
6907 	}
6908 	args = (const struct btf_param *)(t + 1);
6909 	nargs = btf_type_vlen(t);
6910 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6911 		bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
6912 			tname, nargs, MAX_BPF_FUNC_REG_ARGS);
6913 		return -EINVAL;
6914 	}
6915 	/* check that function returns int */
6916 	t = btf_type_by_id(btf, t->type);
6917 	while (btf_type_is_modifier(t))
6918 		t = btf_type_by_id(btf, t->type);
6919 	if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
6920 		bpf_log(log,
6921 			"Global function %s() doesn't return scalar. Only those are supported.\n",
6922 			tname);
6923 		return -EINVAL;
6924 	}
6925 	/* Convert BTF function arguments into verifier types.
6926 	 * Only PTR_TO_CTX and SCALAR are supported atm.
6927 	 */
6928 	for (i = 0; i < nargs; i++) {
6929 		struct bpf_reg_state *reg = &regs[i + 1];
6930 
6931 		t = btf_type_by_id(btf, args[i].type);
6932 		while (btf_type_is_modifier(t))
6933 			t = btf_type_by_id(btf, t->type);
6934 		if (btf_type_is_int(t) || btf_is_any_enum(t)) {
6935 			reg->type = SCALAR_VALUE;
6936 			continue;
6937 		}
6938 		if (btf_type_is_ptr(t)) {
6939 			if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6940 				reg->type = PTR_TO_CTX;
6941 				continue;
6942 			}
6943 
6944 			t = btf_type_skip_modifiers(btf, t->type, NULL);
6945 
6946 			ref_t = btf_resolve_size(btf, t, &reg->mem_size);
6947 			if (IS_ERR(ref_t)) {
6948 				bpf_log(log,
6949 				    "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6950 				    i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
6951 					PTR_ERR(ref_t));
6952 				return -EINVAL;
6953 			}
6954 
6955 			reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
6956 			reg->id = ++env->id_gen;
6957 
6958 			continue;
6959 		}
6960 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
6961 			i, btf_type_str(t), tname);
6962 		return -EINVAL;
6963 	}
6964 	return 0;
6965 }
6966 
6967 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
6968 			  struct btf_show *show)
6969 {
6970 	const struct btf_type *t = btf_type_by_id(btf, type_id);
6971 
6972 	show->btf = btf;
6973 	memset(&show->state, 0, sizeof(show->state));
6974 	memset(&show->obj, 0, sizeof(show->obj));
6975 
6976 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
6977 }
6978 
6979 static void btf_seq_show(struct btf_show *show, const char *fmt,
6980 			 va_list args)
6981 {
6982 	seq_vprintf((struct seq_file *)show->target, fmt, args);
6983 }
6984 
6985 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
6986 			    void *obj, struct seq_file *m, u64 flags)
6987 {
6988 	struct btf_show sseq;
6989 
6990 	sseq.target = m;
6991 	sseq.showfn = btf_seq_show;
6992 	sseq.flags = flags;
6993 
6994 	btf_type_show(btf, type_id, obj, &sseq);
6995 
6996 	return sseq.state.status;
6997 }
6998 
6999 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7000 		       struct seq_file *m)
7001 {
7002 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
7003 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7004 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7005 }
7006 
7007 struct btf_show_snprintf {
7008 	struct btf_show show;
7009 	int len_left;		/* space left in string */
7010 	int len;		/* length we would have written */
7011 };
7012 
7013 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7014 			      va_list args)
7015 {
7016 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7017 	int len;
7018 
7019 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7020 
7021 	if (len < 0) {
7022 		ssnprintf->len_left = 0;
7023 		ssnprintf->len = len;
7024 	} else if (len >= ssnprintf->len_left) {
7025 		/* no space, drive on to get length we would have written */
7026 		ssnprintf->len_left = 0;
7027 		ssnprintf->len += len;
7028 	} else {
7029 		ssnprintf->len_left -= len;
7030 		ssnprintf->len += len;
7031 		show->target += len;
7032 	}
7033 }
7034 
7035 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7036 			   char *buf, int len, u64 flags)
7037 {
7038 	struct btf_show_snprintf ssnprintf;
7039 
7040 	ssnprintf.show.target = buf;
7041 	ssnprintf.show.flags = flags;
7042 	ssnprintf.show.showfn = btf_snprintf_show;
7043 	ssnprintf.len_left = len;
7044 	ssnprintf.len = 0;
7045 
7046 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7047 
7048 	/* If we encountered an error, return it. */
7049 	if (ssnprintf.show.state.status)
7050 		return ssnprintf.show.state.status;
7051 
7052 	/* Otherwise return length we would have written */
7053 	return ssnprintf.len;
7054 }
7055 
7056 #ifdef CONFIG_PROC_FS
7057 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7058 {
7059 	const struct btf *btf = filp->private_data;
7060 
7061 	seq_printf(m, "btf_id:\t%u\n", btf->id);
7062 }
7063 #endif
7064 
7065 static int btf_release(struct inode *inode, struct file *filp)
7066 {
7067 	btf_put(filp->private_data);
7068 	return 0;
7069 }
7070 
7071 const struct file_operations btf_fops = {
7072 #ifdef CONFIG_PROC_FS
7073 	.show_fdinfo	= bpf_btf_show_fdinfo,
7074 #endif
7075 	.release	= btf_release,
7076 };
7077 
7078 static int __btf_new_fd(struct btf *btf)
7079 {
7080 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7081 }
7082 
7083 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr)
7084 {
7085 	struct btf *btf;
7086 	int ret;
7087 
7088 	btf = btf_parse(make_bpfptr(attr->btf, uattr.is_kernel),
7089 			attr->btf_size, attr->btf_log_level,
7090 			u64_to_user_ptr(attr->btf_log_buf),
7091 			attr->btf_log_size);
7092 	if (IS_ERR(btf))
7093 		return PTR_ERR(btf);
7094 
7095 	ret = btf_alloc_id(btf);
7096 	if (ret) {
7097 		btf_free(btf);
7098 		return ret;
7099 	}
7100 
7101 	/*
7102 	 * The BTF ID is published to the userspace.
7103 	 * All BTF free must go through call_rcu() from
7104 	 * now on (i.e. free by calling btf_put()).
7105 	 */
7106 
7107 	ret = __btf_new_fd(btf);
7108 	if (ret < 0)
7109 		btf_put(btf);
7110 
7111 	return ret;
7112 }
7113 
7114 struct btf *btf_get_by_fd(int fd)
7115 {
7116 	struct btf *btf;
7117 	struct fd f;
7118 
7119 	f = fdget(fd);
7120 
7121 	if (!f.file)
7122 		return ERR_PTR(-EBADF);
7123 
7124 	if (f.file->f_op != &btf_fops) {
7125 		fdput(f);
7126 		return ERR_PTR(-EINVAL);
7127 	}
7128 
7129 	btf = f.file->private_data;
7130 	refcount_inc(&btf->refcnt);
7131 	fdput(f);
7132 
7133 	return btf;
7134 }
7135 
7136 int btf_get_info_by_fd(const struct btf *btf,
7137 		       const union bpf_attr *attr,
7138 		       union bpf_attr __user *uattr)
7139 {
7140 	struct bpf_btf_info __user *uinfo;
7141 	struct bpf_btf_info info;
7142 	u32 info_copy, btf_copy;
7143 	void __user *ubtf;
7144 	char __user *uname;
7145 	u32 uinfo_len, uname_len, name_len;
7146 	int ret = 0;
7147 
7148 	uinfo = u64_to_user_ptr(attr->info.info);
7149 	uinfo_len = attr->info.info_len;
7150 
7151 	info_copy = min_t(u32, uinfo_len, sizeof(info));
7152 	memset(&info, 0, sizeof(info));
7153 	if (copy_from_user(&info, uinfo, info_copy))
7154 		return -EFAULT;
7155 
7156 	info.id = btf->id;
7157 	ubtf = u64_to_user_ptr(info.btf);
7158 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
7159 	if (copy_to_user(ubtf, btf->data, btf_copy))
7160 		return -EFAULT;
7161 	info.btf_size = btf->data_size;
7162 
7163 	info.kernel_btf = btf->kernel_btf;
7164 
7165 	uname = u64_to_user_ptr(info.name);
7166 	uname_len = info.name_len;
7167 	if (!uname ^ !uname_len)
7168 		return -EINVAL;
7169 
7170 	name_len = strlen(btf->name);
7171 	info.name_len = name_len;
7172 
7173 	if (uname) {
7174 		if (uname_len >= name_len + 1) {
7175 			if (copy_to_user(uname, btf->name, name_len + 1))
7176 				return -EFAULT;
7177 		} else {
7178 			char zero = '\0';
7179 
7180 			if (copy_to_user(uname, btf->name, uname_len - 1))
7181 				return -EFAULT;
7182 			if (put_user(zero, uname + uname_len - 1))
7183 				return -EFAULT;
7184 			/* let user-space know about too short buffer */
7185 			ret = -ENOSPC;
7186 		}
7187 	}
7188 
7189 	if (copy_to_user(uinfo, &info, info_copy) ||
7190 	    put_user(info_copy, &uattr->info.info_len))
7191 		return -EFAULT;
7192 
7193 	return ret;
7194 }
7195 
7196 int btf_get_fd_by_id(u32 id)
7197 {
7198 	struct btf *btf;
7199 	int fd;
7200 
7201 	rcu_read_lock();
7202 	btf = idr_find(&btf_idr, id);
7203 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7204 		btf = ERR_PTR(-ENOENT);
7205 	rcu_read_unlock();
7206 
7207 	if (IS_ERR(btf))
7208 		return PTR_ERR(btf);
7209 
7210 	fd = __btf_new_fd(btf);
7211 	if (fd < 0)
7212 		btf_put(btf);
7213 
7214 	return fd;
7215 }
7216 
7217 u32 btf_obj_id(const struct btf *btf)
7218 {
7219 	return btf->id;
7220 }
7221 
7222 bool btf_is_kernel(const struct btf *btf)
7223 {
7224 	return btf->kernel_btf;
7225 }
7226 
7227 bool btf_is_module(const struct btf *btf)
7228 {
7229 	return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7230 }
7231 
7232 enum {
7233 	BTF_MODULE_F_LIVE = (1 << 0),
7234 };
7235 
7236 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7237 struct btf_module {
7238 	struct list_head list;
7239 	struct module *module;
7240 	struct btf *btf;
7241 	struct bin_attribute *sysfs_attr;
7242 	int flags;
7243 };
7244 
7245 static LIST_HEAD(btf_modules);
7246 static DEFINE_MUTEX(btf_module_mutex);
7247 
7248 static ssize_t
7249 btf_module_read(struct file *file, struct kobject *kobj,
7250 		struct bin_attribute *bin_attr,
7251 		char *buf, loff_t off, size_t len)
7252 {
7253 	const struct btf *btf = bin_attr->private;
7254 
7255 	memcpy(buf, btf->data + off, len);
7256 	return len;
7257 }
7258 
7259 static void purge_cand_cache(struct btf *btf);
7260 
7261 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7262 			     void *module)
7263 {
7264 	struct btf_module *btf_mod, *tmp;
7265 	struct module *mod = module;
7266 	struct btf *btf;
7267 	int err = 0;
7268 
7269 	if (mod->btf_data_size == 0 ||
7270 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7271 	     op != MODULE_STATE_GOING))
7272 		goto out;
7273 
7274 	switch (op) {
7275 	case MODULE_STATE_COMING:
7276 		btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7277 		if (!btf_mod) {
7278 			err = -ENOMEM;
7279 			goto out;
7280 		}
7281 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7282 		if (IS_ERR(btf)) {
7283 			kfree(btf_mod);
7284 			if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
7285 				pr_warn("failed to validate module [%s] BTF: %ld\n",
7286 					mod->name, PTR_ERR(btf));
7287 				err = PTR_ERR(btf);
7288 			} else {
7289 				pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7290 			}
7291 			goto out;
7292 		}
7293 		err = btf_alloc_id(btf);
7294 		if (err) {
7295 			btf_free(btf);
7296 			kfree(btf_mod);
7297 			goto out;
7298 		}
7299 
7300 		purge_cand_cache(NULL);
7301 		mutex_lock(&btf_module_mutex);
7302 		btf_mod->module = module;
7303 		btf_mod->btf = btf;
7304 		list_add(&btf_mod->list, &btf_modules);
7305 		mutex_unlock(&btf_module_mutex);
7306 
7307 		if (IS_ENABLED(CONFIG_SYSFS)) {
7308 			struct bin_attribute *attr;
7309 
7310 			attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7311 			if (!attr)
7312 				goto out;
7313 
7314 			sysfs_bin_attr_init(attr);
7315 			attr->attr.name = btf->name;
7316 			attr->attr.mode = 0444;
7317 			attr->size = btf->data_size;
7318 			attr->private = btf;
7319 			attr->read = btf_module_read;
7320 
7321 			err = sysfs_create_bin_file(btf_kobj, attr);
7322 			if (err) {
7323 				pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7324 					mod->name, err);
7325 				kfree(attr);
7326 				err = 0;
7327 				goto out;
7328 			}
7329 
7330 			btf_mod->sysfs_attr = attr;
7331 		}
7332 
7333 		break;
7334 	case MODULE_STATE_LIVE:
7335 		mutex_lock(&btf_module_mutex);
7336 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7337 			if (btf_mod->module != module)
7338 				continue;
7339 
7340 			btf_mod->flags |= BTF_MODULE_F_LIVE;
7341 			break;
7342 		}
7343 		mutex_unlock(&btf_module_mutex);
7344 		break;
7345 	case MODULE_STATE_GOING:
7346 		mutex_lock(&btf_module_mutex);
7347 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7348 			if (btf_mod->module != module)
7349 				continue;
7350 
7351 			list_del(&btf_mod->list);
7352 			if (btf_mod->sysfs_attr)
7353 				sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
7354 			purge_cand_cache(btf_mod->btf);
7355 			btf_put(btf_mod->btf);
7356 			kfree(btf_mod->sysfs_attr);
7357 			kfree(btf_mod);
7358 			break;
7359 		}
7360 		mutex_unlock(&btf_module_mutex);
7361 		break;
7362 	}
7363 out:
7364 	return notifier_from_errno(err);
7365 }
7366 
7367 static struct notifier_block btf_module_nb = {
7368 	.notifier_call = btf_module_notify,
7369 };
7370 
7371 static int __init btf_module_init(void)
7372 {
7373 	register_module_notifier(&btf_module_nb);
7374 	return 0;
7375 }
7376 
7377 fs_initcall(btf_module_init);
7378 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7379 
7380 struct module *btf_try_get_module(const struct btf *btf)
7381 {
7382 	struct module *res = NULL;
7383 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7384 	struct btf_module *btf_mod, *tmp;
7385 
7386 	mutex_lock(&btf_module_mutex);
7387 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7388 		if (btf_mod->btf != btf)
7389 			continue;
7390 
7391 		/* We must only consider module whose __init routine has
7392 		 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7393 		 * which is set from the notifier callback for
7394 		 * MODULE_STATE_LIVE.
7395 		 */
7396 		if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7397 			res = btf_mod->module;
7398 
7399 		break;
7400 	}
7401 	mutex_unlock(&btf_module_mutex);
7402 #endif
7403 
7404 	return res;
7405 }
7406 
7407 /* Returns struct btf corresponding to the struct module.
7408  * This function can return NULL or ERR_PTR.
7409  */
7410 static struct btf *btf_get_module_btf(const struct module *module)
7411 {
7412 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7413 	struct btf_module *btf_mod, *tmp;
7414 #endif
7415 	struct btf *btf = NULL;
7416 
7417 	if (!module) {
7418 		btf = bpf_get_btf_vmlinux();
7419 		if (!IS_ERR_OR_NULL(btf))
7420 			btf_get(btf);
7421 		return btf;
7422 	}
7423 
7424 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7425 	mutex_lock(&btf_module_mutex);
7426 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7427 		if (btf_mod->module != module)
7428 			continue;
7429 
7430 		btf_get(btf_mod->btf);
7431 		btf = btf_mod->btf;
7432 		break;
7433 	}
7434 	mutex_unlock(&btf_module_mutex);
7435 #endif
7436 
7437 	return btf;
7438 }
7439 
7440 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7441 {
7442 	struct btf *btf = NULL;
7443 	int btf_obj_fd = 0;
7444 	long ret;
7445 
7446 	if (flags)
7447 		return -EINVAL;
7448 
7449 	if (name_sz <= 1 || name[name_sz - 1])
7450 		return -EINVAL;
7451 
7452 	ret = bpf_find_btf_id(name, kind, &btf);
7453 	if (ret > 0 && btf_is_module(btf)) {
7454 		btf_obj_fd = __btf_new_fd(btf);
7455 		if (btf_obj_fd < 0) {
7456 			btf_put(btf);
7457 			return btf_obj_fd;
7458 		}
7459 		return ret | (((u64)btf_obj_fd) << 32);
7460 	}
7461 	if (ret > 0)
7462 		btf_put(btf);
7463 	return ret;
7464 }
7465 
7466 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7467 	.func		= bpf_btf_find_by_name_kind,
7468 	.gpl_only	= false,
7469 	.ret_type	= RET_INTEGER,
7470 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7471 	.arg2_type	= ARG_CONST_SIZE,
7472 	.arg3_type	= ARG_ANYTHING,
7473 	.arg4_type	= ARG_ANYTHING,
7474 };
7475 
7476 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
7477 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
7478 BTF_TRACING_TYPE_xxx
7479 #undef BTF_TRACING_TYPE
7480 
7481 /* Kernel Function (kfunc) BTF ID set registration API */
7482 
7483 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7484 				  struct btf_id_set8 *add_set)
7485 {
7486 	bool vmlinux_set = !btf_is_module(btf);
7487 	struct btf_kfunc_set_tab *tab;
7488 	struct btf_id_set8 *set;
7489 	u32 set_cnt;
7490 	int ret;
7491 
7492 	if (hook >= BTF_KFUNC_HOOK_MAX) {
7493 		ret = -EINVAL;
7494 		goto end;
7495 	}
7496 
7497 	if (!add_set->cnt)
7498 		return 0;
7499 
7500 	tab = btf->kfunc_set_tab;
7501 	if (!tab) {
7502 		tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
7503 		if (!tab)
7504 			return -ENOMEM;
7505 		btf->kfunc_set_tab = tab;
7506 	}
7507 
7508 	set = tab->sets[hook];
7509 	/* Warn when register_btf_kfunc_id_set is called twice for the same hook
7510 	 * for module sets.
7511 	 */
7512 	if (WARN_ON_ONCE(set && !vmlinux_set)) {
7513 		ret = -EINVAL;
7514 		goto end;
7515 	}
7516 
7517 	/* We don't need to allocate, concatenate, and sort module sets, because
7518 	 * only one is allowed per hook. Hence, we can directly assign the
7519 	 * pointer and return.
7520 	 */
7521 	if (!vmlinux_set) {
7522 		tab->sets[hook] = add_set;
7523 		return 0;
7524 	}
7525 
7526 	/* In case of vmlinux sets, there may be more than one set being
7527 	 * registered per hook. To create a unified set, we allocate a new set
7528 	 * and concatenate all individual sets being registered. While each set
7529 	 * is individually sorted, they may become unsorted when concatenated,
7530 	 * hence re-sorting the final set again is required to make binary
7531 	 * searching the set using btf_id_set8_contains function work.
7532 	 */
7533 	set_cnt = set ? set->cnt : 0;
7534 
7535 	if (set_cnt > U32_MAX - add_set->cnt) {
7536 		ret = -EOVERFLOW;
7537 		goto end;
7538 	}
7539 
7540 	if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
7541 		ret = -E2BIG;
7542 		goto end;
7543 	}
7544 
7545 	/* Grow set */
7546 	set = krealloc(tab->sets[hook],
7547 		       offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
7548 		       GFP_KERNEL | __GFP_NOWARN);
7549 	if (!set) {
7550 		ret = -ENOMEM;
7551 		goto end;
7552 	}
7553 
7554 	/* For newly allocated set, initialize set->cnt to 0 */
7555 	if (!tab->sets[hook])
7556 		set->cnt = 0;
7557 	tab->sets[hook] = set;
7558 
7559 	/* Concatenate the two sets */
7560 	memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
7561 	set->cnt += add_set->cnt;
7562 
7563 	sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
7564 
7565 	return 0;
7566 end:
7567 	btf_free_kfunc_set_tab(btf);
7568 	return ret;
7569 }
7570 
7571 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
7572 					enum btf_kfunc_hook hook,
7573 					u32 kfunc_btf_id)
7574 {
7575 	struct btf_id_set8 *set;
7576 	u32 *id;
7577 
7578 	if (hook >= BTF_KFUNC_HOOK_MAX)
7579 		return NULL;
7580 	if (!btf->kfunc_set_tab)
7581 		return NULL;
7582 	set = btf->kfunc_set_tab->sets[hook];
7583 	if (!set)
7584 		return NULL;
7585 	id = btf_id_set8_contains(set, kfunc_btf_id);
7586 	if (!id)
7587 		return NULL;
7588 	/* The flags for BTF ID are located next to it */
7589 	return id + 1;
7590 }
7591 
7592 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
7593 {
7594 	switch (prog_type) {
7595 	case BPF_PROG_TYPE_UNSPEC:
7596 		return BTF_KFUNC_HOOK_COMMON;
7597 	case BPF_PROG_TYPE_XDP:
7598 		return BTF_KFUNC_HOOK_XDP;
7599 	case BPF_PROG_TYPE_SCHED_CLS:
7600 		return BTF_KFUNC_HOOK_TC;
7601 	case BPF_PROG_TYPE_STRUCT_OPS:
7602 		return BTF_KFUNC_HOOK_STRUCT_OPS;
7603 	case BPF_PROG_TYPE_TRACING:
7604 	case BPF_PROG_TYPE_LSM:
7605 		return BTF_KFUNC_HOOK_TRACING;
7606 	case BPF_PROG_TYPE_SYSCALL:
7607 		return BTF_KFUNC_HOOK_SYSCALL;
7608 	default:
7609 		return BTF_KFUNC_HOOK_MAX;
7610 	}
7611 }
7612 
7613 /* Caution:
7614  * Reference to the module (obtained using btf_try_get_module) corresponding to
7615  * the struct btf *MUST* be held when calling this function from verifier
7616  * context. This is usually true as we stash references in prog's kfunc_btf_tab;
7617  * keeping the reference for the duration of the call provides the necessary
7618  * protection for looking up a well-formed btf->kfunc_set_tab.
7619  */
7620 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
7621 			       enum bpf_prog_type prog_type,
7622 			       u32 kfunc_btf_id)
7623 {
7624 	enum btf_kfunc_hook hook;
7625 	u32 *kfunc_flags;
7626 
7627 	kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
7628 	if (kfunc_flags)
7629 		return kfunc_flags;
7630 
7631 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
7632 	return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
7633 }
7634 
7635 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id)
7636 {
7637 	return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);
7638 }
7639 
7640 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
7641 				       const struct btf_kfunc_id_set *kset)
7642 {
7643 	struct btf *btf;
7644 	int ret;
7645 
7646 	btf = btf_get_module_btf(kset->owner);
7647 	if (!btf) {
7648 		if (!kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7649 			pr_err("missing vmlinux BTF, cannot register kfuncs\n");
7650 			return -ENOENT;
7651 		}
7652 		if (kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7653 			pr_err("missing module BTF, cannot register kfuncs\n");
7654 			return -ENOENT;
7655 		}
7656 		return 0;
7657 	}
7658 	if (IS_ERR(btf))
7659 		return PTR_ERR(btf);
7660 
7661 	ret = btf_populate_kfunc_set(btf, hook, kset->set);
7662 	btf_put(btf);
7663 	return ret;
7664 }
7665 
7666 /* This function must be invoked only from initcalls/module init functions */
7667 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
7668 			      const struct btf_kfunc_id_set *kset)
7669 {
7670 	enum btf_kfunc_hook hook;
7671 
7672 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
7673 	return __register_btf_kfunc_id_set(hook, kset);
7674 }
7675 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
7676 
7677 /* This function must be invoked only from initcalls/module init functions */
7678 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
7679 {
7680 	return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
7681 }
7682 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
7683 
7684 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
7685 {
7686 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
7687 	struct btf_id_dtor_kfunc *dtor;
7688 
7689 	if (!tab)
7690 		return -ENOENT;
7691 	/* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
7692 	 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
7693 	 */
7694 	BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
7695 	dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
7696 	if (!dtor)
7697 		return -ENOENT;
7698 	return dtor->kfunc_btf_id;
7699 }
7700 
7701 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
7702 {
7703 	const struct btf_type *dtor_func, *dtor_func_proto, *t;
7704 	const struct btf_param *args;
7705 	s32 dtor_btf_id;
7706 	u32 nr_args, i;
7707 
7708 	for (i = 0; i < cnt; i++) {
7709 		dtor_btf_id = dtors[i].kfunc_btf_id;
7710 
7711 		dtor_func = btf_type_by_id(btf, dtor_btf_id);
7712 		if (!dtor_func || !btf_type_is_func(dtor_func))
7713 			return -EINVAL;
7714 
7715 		dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
7716 		if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
7717 			return -EINVAL;
7718 
7719 		/* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
7720 		t = btf_type_by_id(btf, dtor_func_proto->type);
7721 		if (!t || !btf_type_is_void(t))
7722 			return -EINVAL;
7723 
7724 		nr_args = btf_type_vlen(dtor_func_proto);
7725 		if (nr_args != 1)
7726 			return -EINVAL;
7727 		args = btf_params(dtor_func_proto);
7728 		t = btf_type_by_id(btf, args[0].type);
7729 		/* Allow any pointer type, as width on targets Linux supports
7730 		 * will be same for all pointer types (i.e. sizeof(void *))
7731 		 */
7732 		if (!t || !btf_type_is_ptr(t))
7733 			return -EINVAL;
7734 	}
7735 	return 0;
7736 }
7737 
7738 /* This function must be invoked only from initcalls/module init functions */
7739 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
7740 				struct module *owner)
7741 {
7742 	struct btf_id_dtor_kfunc_tab *tab;
7743 	struct btf *btf;
7744 	u32 tab_cnt;
7745 	int ret;
7746 
7747 	btf = btf_get_module_btf(owner);
7748 	if (!btf) {
7749 		if (!owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7750 			pr_err("missing vmlinux BTF, cannot register dtor kfuncs\n");
7751 			return -ENOENT;
7752 		}
7753 		if (owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7754 			pr_err("missing module BTF, cannot register dtor kfuncs\n");
7755 			return -ENOENT;
7756 		}
7757 		return 0;
7758 	}
7759 	if (IS_ERR(btf))
7760 		return PTR_ERR(btf);
7761 
7762 	if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7763 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7764 		ret = -E2BIG;
7765 		goto end;
7766 	}
7767 
7768 	/* Ensure that the prototype of dtor kfuncs being registered is sane */
7769 	ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
7770 	if (ret < 0)
7771 		goto end;
7772 
7773 	tab = btf->dtor_kfunc_tab;
7774 	/* Only one call allowed for modules */
7775 	if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
7776 		ret = -EINVAL;
7777 		goto end;
7778 	}
7779 
7780 	tab_cnt = tab ? tab->cnt : 0;
7781 	if (tab_cnt > U32_MAX - add_cnt) {
7782 		ret = -EOVERFLOW;
7783 		goto end;
7784 	}
7785 	if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7786 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7787 		ret = -E2BIG;
7788 		goto end;
7789 	}
7790 
7791 	tab = krealloc(btf->dtor_kfunc_tab,
7792 		       offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
7793 		       GFP_KERNEL | __GFP_NOWARN);
7794 	if (!tab) {
7795 		ret = -ENOMEM;
7796 		goto end;
7797 	}
7798 
7799 	if (!btf->dtor_kfunc_tab)
7800 		tab->cnt = 0;
7801 	btf->dtor_kfunc_tab = tab;
7802 
7803 	memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
7804 	tab->cnt += add_cnt;
7805 
7806 	sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
7807 
7808 	return 0;
7809 end:
7810 	btf_free_dtor_kfunc_tab(btf);
7811 	btf_put(btf);
7812 	return ret;
7813 }
7814 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
7815 
7816 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
7817 
7818 /* Check local and target types for compatibility. This check is used for
7819  * type-based CO-RE relocations and follow slightly different rules than
7820  * field-based relocations. This function assumes that root types were already
7821  * checked for name match. Beyond that initial root-level name check, names
7822  * are completely ignored. Compatibility rules are as follows:
7823  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
7824  *     kind should match for local and target types (i.e., STRUCT is not
7825  *     compatible with UNION);
7826  *   - for ENUMs/ENUM64s, the size is ignored;
7827  *   - for INT, size and signedness are ignored;
7828  *   - for ARRAY, dimensionality is ignored, element types are checked for
7829  *     compatibility recursively;
7830  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
7831  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
7832  *   - FUNC_PROTOs are compatible if they have compatible signature: same
7833  *     number of input args and compatible return and argument types.
7834  * These rules are not set in stone and probably will be adjusted as we get
7835  * more experience with using BPF CO-RE relocations.
7836  */
7837 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
7838 			      const struct btf *targ_btf, __u32 targ_id)
7839 {
7840 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
7841 					   MAX_TYPES_ARE_COMPAT_DEPTH);
7842 }
7843 
7844 #define MAX_TYPES_MATCH_DEPTH 2
7845 
7846 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
7847 			 const struct btf *targ_btf, u32 targ_id)
7848 {
7849 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
7850 				      MAX_TYPES_MATCH_DEPTH);
7851 }
7852 
7853 static bool bpf_core_is_flavor_sep(const char *s)
7854 {
7855 	/* check X___Y name pattern, where X and Y are not underscores */
7856 	return s[0] != '_' &&				      /* X */
7857 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
7858 	       s[4] != '_';				      /* Y */
7859 }
7860 
7861 size_t bpf_core_essential_name_len(const char *name)
7862 {
7863 	size_t n = strlen(name);
7864 	int i;
7865 
7866 	for (i = n - 5; i >= 0; i--) {
7867 		if (bpf_core_is_flavor_sep(name + i))
7868 			return i + 1;
7869 	}
7870 	return n;
7871 }
7872 
7873 struct bpf_cand_cache {
7874 	const char *name;
7875 	u32 name_len;
7876 	u16 kind;
7877 	u16 cnt;
7878 	struct {
7879 		const struct btf *btf;
7880 		u32 id;
7881 	} cands[];
7882 };
7883 
7884 static void bpf_free_cands(struct bpf_cand_cache *cands)
7885 {
7886 	if (!cands->cnt)
7887 		/* empty candidate array was allocated on stack */
7888 		return;
7889 	kfree(cands);
7890 }
7891 
7892 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
7893 {
7894 	kfree(cands->name);
7895 	kfree(cands);
7896 }
7897 
7898 #define VMLINUX_CAND_CACHE_SIZE 31
7899 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
7900 
7901 #define MODULE_CAND_CACHE_SIZE 31
7902 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
7903 
7904 static DEFINE_MUTEX(cand_cache_mutex);
7905 
7906 static void __print_cand_cache(struct bpf_verifier_log *log,
7907 			       struct bpf_cand_cache **cache,
7908 			       int cache_size)
7909 {
7910 	struct bpf_cand_cache *cc;
7911 	int i, j;
7912 
7913 	for (i = 0; i < cache_size; i++) {
7914 		cc = cache[i];
7915 		if (!cc)
7916 			continue;
7917 		bpf_log(log, "[%d]%s(", i, cc->name);
7918 		for (j = 0; j < cc->cnt; j++) {
7919 			bpf_log(log, "%d", cc->cands[j].id);
7920 			if (j < cc->cnt - 1)
7921 				bpf_log(log, " ");
7922 		}
7923 		bpf_log(log, "), ");
7924 	}
7925 }
7926 
7927 static void print_cand_cache(struct bpf_verifier_log *log)
7928 {
7929 	mutex_lock(&cand_cache_mutex);
7930 	bpf_log(log, "vmlinux_cand_cache:");
7931 	__print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
7932 	bpf_log(log, "\nmodule_cand_cache:");
7933 	__print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
7934 	bpf_log(log, "\n");
7935 	mutex_unlock(&cand_cache_mutex);
7936 }
7937 
7938 static u32 hash_cands(struct bpf_cand_cache *cands)
7939 {
7940 	return jhash(cands->name, cands->name_len, 0);
7941 }
7942 
7943 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
7944 					       struct bpf_cand_cache **cache,
7945 					       int cache_size)
7946 {
7947 	struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
7948 
7949 	if (cc && cc->name_len == cands->name_len &&
7950 	    !strncmp(cc->name, cands->name, cands->name_len))
7951 		return cc;
7952 	return NULL;
7953 }
7954 
7955 static size_t sizeof_cands(int cnt)
7956 {
7957 	return offsetof(struct bpf_cand_cache, cands[cnt]);
7958 }
7959 
7960 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
7961 						  struct bpf_cand_cache **cache,
7962 						  int cache_size)
7963 {
7964 	struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
7965 
7966 	if (*cc) {
7967 		bpf_free_cands_from_cache(*cc);
7968 		*cc = NULL;
7969 	}
7970 	new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
7971 	if (!new_cands) {
7972 		bpf_free_cands(cands);
7973 		return ERR_PTR(-ENOMEM);
7974 	}
7975 	/* strdup the name, since it will stay in cache.
7976 	 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
7977 	 */
7978 	new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
7979 	bpf_free_cands(cands);
7980 	if (!new_cands->name) {
7981 		kfree(new_cands);
7982 		return ERR_PTR(-ENOMEM);
7983 	}
7984 	*cc = new_cands;
7985 	return new_cands;
7986 }
7987 
7988 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7989 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
7990 			       int cache_size)
7991 {
7992 	struct bpf_cand_cache *cc;
7993 	int i, j;
7994 
7995 	for (i = 0; i < cache_size; i++) {
7996 		cc = cache[i];
7997 		if (!cc)
7998 			continue;
7999 		if (!btf) {
8000 			/* when new module is loaded purge all of module_cand_cache,
8001 			 * since new module might have candidates with the name
8002 			 * that matches cached cands.
8003 			 */
8004 			bpf_free_cands_from_cache(cc);
8005 			cache[i] = NULL;
8006 			continue;
8007 		}
8008 		/* when module is unloaded purge cache entries
8009 		 * that match module's btf
8010 		 */
8011 		for (j = 0; j < cc->cnt; j++)
8012 			if (cc->cands[j].btf == btf) {
8013 				bpf_free_cands_from_cache(cc);
8014 				cache[i] = NULL;
8015 				break;
8016 			}
8017 	}
8018 
8019 }
8020 
8021 static void purge_cand_cache(struct btf *btf)
8022 {
8023 	mutex_lock(&cand_cache_mutex);
8024 	__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8025 	mutex_unlock(&cand_cache_mutex);
8026 }
8027 #endif
8028 
8029 static struct bpf_cand_cache *
8030 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8031 		   int targ_start_id)
8032 {
8033 	struct bpf_cand_cache *new_cands;
8034 	const struct btf_type *t;
8035 	const char *targ_name;
8036 	size_t targ_essent_len;
8037 	int n, i;
8038 
8039 	n = btf_nr_types(targ_btf);
8040 	for (i = targ_start_id; i < n; i++) {
8041 		t = btf_type_by_id(targ_btf, i);
8042 		if (btf_kind(t) != cands->kind)
8043 			continue;
8044 
8045 		targ_name = btf_name_by_offset(targ_btf, t->name_off);
8046 		if (!targ_name)
8047 			continue;
8048 
8049 		/* the resched point is before strncmp to make sure that search
8050 		 * for non-existing name will have a chance to schedule().
8051 		 */
8052 		cond_resched();
8053 
8054 		if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8055 			continue;
8056 
8057 		targ_essent_len = bpf_core_essential_name_len(targ_name);
8058 		if (targ_essent_len != cands->name_len)
8059 			continue;
8060 
8061 		/* most of the time there is only one candidate for a given kind+name pair */
8062 		new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8063 		if (!new_cands) {
8064 			bpf_free_cands(cands);
8065 			return ERR_PTR(-ENOMEM);
8066 		}
8067 
8068 		memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8069 		bpf_free_cands(cands);
8070 		cands = new_cands;
8071 		cands->cands[cands->cnt].btf = targ_btf;
8072 		cands->cands[cands->cnt].id = i;
8073 		cands->cnt++;
8074 	}
8075 	return cands;
8076 }
8077 
8078 static struct bpf_cand_cache *
8079 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8080 {
8081 	struct bpf_cand_cache *cands, *cc, local_cand = {};
8082 	const struct btf *local_btf = ctx->btf;
8083 	const struct btf_type *local_type;
8084 	const struct btf *main_btf;
8085 	size_t local_essent_len;
8086 	struct btf *mod_btf;
8087 	const char *name;
8088 	int id;
8089 
8090 	main_btf = bpf_get_btf_vmlinux();
8091 	if (IS_ERR(main_btf))
8092 		return ERR_CAST(main_btf);
8093 	if (!main_btf)
8094 		return ERR_PTR(-EINVAL);
8095 
8096 	local_type = btf_type_by_id(local_btf, local_type_id);
8097 	if (!local_type)
8098 		return ERR_PTR(-EINVAL);
8099 
8100 	name = btf_name_by_offset(local_btf, local_type->name_off);
8101 	if (str_is_empty(name))
8102 		return ERR_PTR(-EINVAL);
8103 	local_essent_len = bpf_core_essential_name_len(name);
8104 
8105 	cands = &local_cand;
8106 	cands->name = name;
8107 	cands->kind = btf_kind(local_type);
8108 	cands->name_len = local_essent_len;
8109 
8110 	cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8111 	/* cands is a pointer to stack here */
8112 	if (cc) {
8113 		if (cc->cnt)
8114 			return cc;
8115 		goto check_modules;
8116 	}
8117 
8118 	/* Attempt to find target candidates in vmlinux BTF first */
8119 	cands = bpf_core_add_cands(cands, main_btf, 1);
8120 	if (IS_ERR(cands))
8121 		return ERR_CAST(cands);
8122 
8123 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8124 
8125 	/* populate cache even when cands->cnt == 0 */
8126 	cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8127 	if (IS_ERR(cc))
8128 		return ERR_CAST(cc);
8129 
8130 	/* if vmlinux BTF has any candidate, don't go for module BTFs */
8131 	if (cc->cnt)
8132 		return cc;
8133 
8134 check_modules:
8135 	/* cands is a pointer to stack here and cands->cnt == 0 */
8136 	cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8137 	if (cc)
8138 		/* if cache has it return it even if cc->cnt == 0 */
8139 		return cc;
8140 
8141 	/* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8142 	spin_lock_bh(&btf_idr_lock);
8143 	idr_for_each_entry(&btf_idr, mod_btf, id) {
8144 		if (!btf_is_module(mod_btf))
8145 			continue;
8146 		/* linear search could be slow hence unlock/lock
8147 		 * the IDR to avoiding holding it for too long
8148 		 */
8149 		btf_get(mod_btf);
8150 		spin_unlock_bh(&btf_idr_lock);
8151 		cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8152 		if (IS_ERR(cands)) {
8153 			btf_put(mod_btf);
8154 			return ERR_CAST(cands);
8155 		}
8156 		spin_lock_bh(&btf_idr_lock);
8157 		btf_put(mod_btf);
8158 	}
8159 	spin_unlock_bh(&btf_idr_lock);
8160 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0
8161 	 * or pointer to stack if cands->cnd == 0.
8162 	 * Copy it into the cache even when cands->cnt == 0 and
8163 	 * return the result.
8164 	 */
8165 	return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8166 }
8167 
8168 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8169 		   int relo_idx, void *insn)
8170 {
8171 	bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8172 	struct bpf_core_cand_list cands = {};
8173 	struct bpf_core_relo_res targ_res;
8174 	struct bpf_core_spec *specs;
8175 	int err;
8176 
8177 	/* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8178 	 * into arrays of btf_ids of struct fields and array indices.
8179 	 */
8180 	specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8181 	if (!specs)
8182 		return -ENOMEM;
8183 
8184 	if (need_cands) {
8185 		struct bpf_cand_cache *cc;
8186 		int i;
8187 
8188 		mutex_lock(&cand_cache_mutex);
8189 		cc = bpf_core_find_cands(ctx, relo->type_id);
8190 		if (IS_ERR(cc)) {
8191 			bpf_log(ctx->log, "target candidate search failed for %d\n",
8192 				relo->type_id);
8193 			err = PTR_ERR(cc);
8194 			goto out;
8195 		}
8196 		if (cc->cnt) {
8197 			cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8198 			if (!cands.cands) {
8199 				err = -ENOMEM;
8200 				goto out;
8201 			}
8202 		}
8203 		for (i = 0; i < cc->cnt; i++) {
8204 			bpf_log(ctx->log,
8205 				"CO-RE relocating %s %s: found target candidate [%d]\n",
8206 				btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8207 			cands.cands[i].btf = cc->cands[i].btf;
8208 			cands.cands[i].id = cc->cands[i].id;
8209 		}
8210 		cands.len = cc->cnt;
8211 		/* cand_cache_mutex needs to span the cache lookup and
8212 		 * copy of btf pointer into bpf_core_cand_list,
8213 		 * since module can be unloaded while bpf_core_calc_relo_insn
8214 		 * is working with module's btf.
8215 		 */
8216 	}
8217 
8218 	err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8219 				      &targ_res);
8220 	if (err)
8221 		goto out;
8222 
8223 	err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8224 				  &targ_res);
8225 
8226 out:
8227 	kfree(specs);
8228 	if (need_cands) {
8229 		kfree(cands.cands);
8230 		mutex_unlock(&cand_cache_mutex);
8231 		if (ctx->log->level & BPF_LOG_LEVEL2)
8232 			print_cand_cache(ctx->log);
8233 	}
8234 	return err;
8235 }
8236 
8237 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
8238 				const struct bpf_reg_state *reg,
8239 				int off)
8240 {
8241 	struct btf *btf = reg->btf;
8242 	const struct btf_type *walk_type, *safe_type;
8243 	const char *tname;
8244 	char safe_tname[64];
8245 	long ret, safe_id;
8246 	const struct btf_member *member, *m_walk = NULL;
8247 	u32 i;
8248 	const char *walk_name;
8249 
8250 	walk_type = btf_type_by_id(btf, reg->btf_id);
8251 	if (!walk_type)
8252 		return false;
8253 
8254 	tname = btf_name_by_offset(btf, walk_type->name_off);
8255 
8256 	ret = snprintf(safe_tname, sizeof(safe_tname), "%s__safe_fields", tname);
8257 	if (ret < 0)
8258 		return false;
8259 
8260 	safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8261 	if (safe_id < 0)
8262 		return false;
8263 
8264 	safe_type = btf_type_by_id(btf, safe_id);
8265 	if (!safe_type)
8266 		return false;
8267 
8268 	for_each_member(i, walk_type, member) {
8269 		u32 moff;
8270 
8271 		/* We're looking for the PTR_TO_BTF_ID member in the struct
8272 		 * type we're walking which matches the specified offset.
8273 		 * Below, we'll iterate over the fields in the safe variant of
8274 		 * the struct and see if any of them has a matching type /
8275 		 * name.
8276 		 */
8277 		moff = __btf_member_bit_offset(walk_type, member) / 8;
8278 		if (off == moff) {
8279 			m_walk = member;
8280 			break;
8281 		}
8282 	}
8283 	if (m_walk == NULL)
8284 		return false;
8285 
8286 	walk_name = __btf_name_by_offset(btf, m_walk->name_off);
8287 	for_each_member(i, safe_type, member) {
8288 		const char *m_name = __btf_name_by_offset(btf, member->name_off);
8289 
8290 		/* If we match on both type and name, the field is considered trusted. */
8291 		if (m_walk->type == member->type && !strcmp(walk_name, m_name))
8292 			return true;
8293 	}
8294 
8295 	return false;
8296 }
8297 
8298 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
8299 			       const struct btf *reg_btf, u32 reg_id,
8300 			       const struct btf *arg_btf, u32 arg_id)
8301 {
8302 	const char *reg_name, *arg_name, *search_needle;
8303 	const struct btf_type *reg_type, *arg_type;
8304 	int reg_len, arg_len, cmp_len;
8305 	size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
8306 
8307 	reg_type = btf_type_by_id(reg_btf, reg_id);
8308 	if (!reg_type)
8309 		return false;
8310 
8311 	arg_type = btf_type_by_id(arg_btf, arg_id);
8312 	if (!arg_type)
8313 		return false;
8314 
8315 	reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
8316 	arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
8317 
8318 	reg_len = strlen(reg_name);
8319 	arg_len = strlen(arg_name);
8320 
8321 	/* Exactly one of the two type names may be suffixed with ___init, so
8322 	 * if the strings are the same size, they can't possibly be no-cast
8323 	 * aliases of one another. If you have two of the same type names, e.g.
8324 	 * they're both nf_conn___init, it would be improper to return true
8325 	 * because they are _not_ no-cast aliases, they are the same type.
8326 	 */
8327 	if (reg_len == arg_len)
8328 		return false;
8329 
8330 	/* Either of the two names must be the other name, suffixed with ___init. */
8331 	if ((reg_len != arg_len + pattern_len) &&
8332 	    (arg_len != reg_len + pattern_len))
8333 		return false;
8334 
8335 	if (reg_len < arg_len) {
8336 		search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
8337 		cmp_len = reg_len;
8338 	} else {
8339 		search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
8340 		cmp_len = arg_len;
8341 	}
8342 
8343 	if (!search_needle)
8344 		return false;
8345 
8346 	/* ___init suffix must come at the end of the name */
8347 	if (*(search_needle + pattern_len) != '\0')
8348 		return false;
8349 
8350 	return !strncmp(reg_name, arg_name, cmp_len);
8351 }
8352