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