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