xref: /linux/kernel/bpf/btf.c (revision d8e473182ab9e85708067be81d20424045d939fa)
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 	for_each_vsi_from(i, v->next_member, v->t, vsi) {
4573 		u32 var_type_id = vsi->type, type_id, type_size = 0;
4574 		const struct btf_type *var_type = btf_type_by_id(env->btf,
4575 								 var_type_id);
4576 		if (!var_type || !btf_type_is_var(var_type)) {
4577 			btf_verifier_log_vsi(env, v->t, vsi,
4578 					     "Not a VAR kind member");
4579 			return -EINVAL;
4580 		}
4581 
4582 		if (!env_type_is_resolve_sink(env, var_type) &&
4583 		    !env_type_is_resolved(env, var_type_id)) {
4584 			env_stack_set_next_member(env, i + 1);
4585 			return env_stack_push(env, var_type, var_type_id);
4586 		}
4587 
4588 		type_id = var_type->type;
4589 		if (!btf_type_id_size(btf, &type_id, &type_size)) {
4590 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
4591 			return -EINVAL;
4592 		}
4593 
4594 		if (vsi->size < type_size) {
4595 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
4596 			return -EINVAL;
4597 		}
4598 	}
4599 
4600 	env_stack_pop_resolved(env, 0, 0);
4601 	return 0;
4602 }
4603 
4604 static void btf_datasec_log(struct btf_verifier_env *env,
4605 			    const struct btf_type *t)
4606 {
4607 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4608 }
4609 
4610 static void btf_datasec_show(const struct btf *btf,
4611 			     const struct btf_type *t, u32 type_id,
4612 			     void *data, u8 bits_offset,
4613 			     struct btf_show *show)
4614 {
4615 	const struct btf_var_secinfo *vsi;
4616 	const struct btf_type *var;
4617 	u32 i;
4618 
4619 	if (!btf_show_start_type(show, t, type_id, data))
4620 		return;
4621 
4622 	btf_show_type_value(show, "section (\"%s\") = {",
4623 			    __btf_name_by_offset(btf, t->name_off));
4624 	for_each_vsi(i, t, vsi) {
4625 		var = btf_type_by_id(btf, vsi->type);
4626 		if (i)
4627 			btf_show(show, ",");
4628 		btf_type_ops(var)->show(btf, var, vsi->type,
4629 					data + vsi->offset, bits_offset, show);
4630 	}
4631 	btf_show_end_type(show);
4632 }
4633 
4634 static const struct btf_kind_operations datasec_ops = {
4635 	.check_meta		= btf_datasec_check_meta,
4636 	.resolve		= btf_datasec_resolve,
4637 	.check_member		= btf_df_check_member,
4638 	.check_kflag_member	= btf_df_check_kflag_member,
4639 	.log_details		= btf_datasec_log,
4640 	.show			= btf_datasec_show,
4641 };
4642 
4643 static s32 btf_float_check_meta(struct btf_verifier_env *env,
4644 				const struct btf_type *t,
4645 				u32 meta_left)
4646 {
4647 	if (btf_type_vlen(t)) {
4648 		btf_verifier_log_type(env, t, "vlen != 0");
4649 		return -EINVAL;
4650 	}
4651 
4652 	if (btf_type_kflag(t)) {
4653 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4654 		return -EINVAL;
4655 	}
4656 
4657 	if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
4658 	    t->size != 16) {
4659 		btf_verifier_log_type(env, t, "Invalid type_size");
4660 		return -EINVAL;
4661 	}
4662 
4663 	btf_verifier_log_type(env, t, NULL);
4664 
4665 	return 0;
4666 }
4667 
4668 static int btf_float_check_member(struct btf_verifier_env *env,
4669 				  const struct btf_type *struct_type,
4670 				  const struct btf_member *member,
4671 				  const struct btf_type *member_type)
4672 {
4673 	u64 start_offset_bytes;
4674 	u64 end_offset_bytes;
4675 	u64 misalign_bits;
4676 	u64 align_bytes;
4677 	u64 align_bits;
4678 
4679 	/* Different architectures have different alignment requirements, so
4680 	 * here we check only for the reasonable minimum. This way we ensure
4681 	 * that types after CO-RE can pass the kernel BTF verifier.
4682 	 */
4683 	align_bytes = min_t(u64, sizeof(void *), member_type->size);
4684 	align_bits = align_bytes * BITS_PER_BYTE;
4685 	div64_u64_rem(member->offset, align_bits, &misalign_bits);
4686 	if (misalign_bits) {
4687 		btf_verifier_log_member(env, struct_type, member,
4688 					"Member is not properly aligned");
4689 		return -EINVAL;
4690 	}
4691 
4692 	start_offset_bytes = member->offset / BITS_PER_BYTE;
4693 	end_offset_bytes = start_offset_bytes + member_type->size;
4694 	if (end_offset_bytes > struct_type->size) {
4695 		btf_verifier_log_member(env, struct_type, member,
4696 					"Member exceeds struct_size");
4697 		return -EINVAL;
4698 	}
4699 
4700 	return 0;
4701 }
4702 
4703 static void btf_float_log(struct btf_verifier_env *env,
4704 			  const struct btf_type *t)
4705 {
4706 	btf_verifier_log(env, "size=%u", t->size);
4707 }
4708 
4709 static const struct btf_kind_operations float_ops = {
4710 	.check_meta = btf_float_check_meta,
4711 	.resolve = btf_df_resolve,
4712 	.check_member = btf_float_check_member,
4713 	.check_kflag_member = btf_generic_check_kflag_member,
4714 	.log_details = btf_float_log,
4715 	.show = btf_df_show,
4716 };
4717 
4718 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
4719 			      const struct btf_type *t,
4720 			      u32 meta_left)
4721 {
4722 	const struct btf_decl_tag *tag;
4723 	u32 meta_needed = sizeof(*tag);
4724 	s32 component_idx;
4725 	const char *value;
4726 
4727 	if (meta_left < meta_needed) {
4728 		btf_verifier_log_basic(env, t,
4729 				       "meta_left:%u meta_needed:%u",
4730 				       meta_left, meta_needed);
4731 		return -EINVAL;
4732 	}
4733 
4734 	value = btf_name_by_offset(env->btf, t->name_off);
4735 	if (!value || !value[0]) {
4736 		btf_verifier_log_type(env, t, "Invalid value");
4737 		return -EINVAL;
4738 	}
4739 
4740 	if (btf_type_vlen(t)) {
4741 		btf_verifier_log_type(env, t, "vlen != 0");
4742 		return -EINVAL;
4743 	}
4744 
4745 	if (btf_type_kflag(t)) {
4746 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4747 		return -EINVAL;
4748 	}
4749 
4750 	component_idx = btf_type_decl_tag(t)->component_idx;
4751 	if (component_idx < -1) {
4752 		btf_verifier_log_type(env, t, "Invalid component_idx");
4753 		return -EINVAL;
4754 	}
4755 
4756 	btf_verifier_log_type(env, t, NULL);
4757 
4758 	return meta_needed;
4759 }
4760 
4761 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
4762 			   const struct resolve_vertex *v)
4763 {
4764 	const struct btf_type *next_type;
4765 	const struct btf_type *t = v->t;
4766 	u32 next_type_id = t->type;
4767 	struct btf *btf = env->btf;
4768 	s32 component_idx;
4769 	u32 vlen;
4770 
4771 	next_type = btf_type_by_id(btf, next_type_id);
4772 	if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
4773 		btf_verifier_log_type(env, v->t, "Invalid type_id");
4774 		return -EINVAL;
4775 	}
4776 
4777 	if (!env_type_is_resolve_sink(env, next_type) &&
4778 	    !env_type_is_resolved(env, next_type_id))
4779 		return env_stack_push(env, next_type, next_type_id);
4780 
4781 	component_idx = btf_type_decl_tag(t)->component_idx;
4782 	if (component_idx != -1) {
4783 		if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
4784 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
4785 			return -EINVAL;
4786 		}
4787 
4788 		if (btf_type_is_struct(next_type)) {
4789 			vlen = btf_type_vlen(next_type);
4790 		} else {
4791 			/* next_type should be a function */
4792 			next_type = btf_type_by_id(btf, next_type->type);
4793 			vlen = btf_type_vlen(next_type);
4794 		}
4795 
4796 		if ((u32)component_idx >= vlen) {
4797 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
4798 			return -EINVAL;
4799 		}
4800 	}
4801 
4802 	env_stack_pop_resolved(env, next_type_id, 0);
4803 
4804 	return 0;
4805 }
4806 
4807 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
4808 {
4809 	btf_verifier_log(env, "type=%u component_idx=%d", t->type,
4810 			 btf_type_decl_tag(t)->component_idx);
4811 }
4812 
4813 static const struct btf_kind_operations decl_tag_ops = {
4814 	.check_meta = btf_decl_tag_check_meta,
4815 	.resolve = btf_decl_tag_resolve,
4816 	.check_member = btf_df_check_member,
4817 	.check_kflag_member = btf_df_check_kflag_member,
4818 	.log_details = btf_decl_tag_log,
4819 	.show = btf_df_show,
4820 };
4821 
4822 static int btf_func_proto_check(struct btf_verifier_env *env,
4823 				const struct btf_type *t)
4824 {
4825 	const struct btf_type *ret_type;
4826 	const struct btf_param *args;
4827 	const struct btf *btf;
4828 	u16 nr_args, i;
4829 	int err;
4830 
4831 	btf = env->btf;
4832 	args = (const struct btf_param *)(t + 1);
4833 	nr_args = btf_type_vlen(t);
4834 
4835 	/* Check func return type which could be "void" (t->type == 0) */
4836 	if (t->type) {
4837 		u32 ret_type_id = t->type;
4838 
4839 		ret_type = btf_type_by_id(btf, ret_type_id);
4840 		if (!ret_type) {
4841 			btf_verifier_log_type(env, t, "Invalid return type");
4842 			return -EINVAL;
4843 		}
4844 
4845 		if (btf_type_is_resolve_source_only(ret_type)) {
4846 			btf_verifier_log_type(env, t, "Invalid return type");
4847 			return -EINVAL;
4848 		}
4849 
4850 		if (btf_type_needs_resolve(ret_type) &&
4851 		    !env_type_is_resolved(env, ret_type_id)) {
4852 			err = btf_resolve(env, ret_type, ret_type_id);
4853 			if (err)
4854 				return err;
4855 		}
4856 
4857 		/* Ensure the return type is a type that has a size */
4858 		if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
4859 			btf_verifier_log_type(env, t, "Invalid return type");
4860 			return -EINVAL;
4861 		}
4862 	}
4863 
4864 	if (!nr_args)
4865 		return 0;
4866 
4867 	/* Last func arg type_id could be 0 if it is a vararg */
4868 	if (!args[nr_args - 1].type) {
4869 		if (args[nr_args - 1].name_off) {
4870 			btf_verifier_log_type(env, t, "Invalid arg#%u",
4871 					      nr_args);
4872 			return -EINVAL;
4873 		}
4874 		nr_args--;
4875 	}
4876 
4877 	for (i = 0; i < nr_args; i++) {
4878 		const struct btf_type *arg_type;
4879 		u32 arg_type_id;
4880 
4881 		arg_type_id = args[i].type;
4882 		arg_type = btf_type_by_id(btf, arg_type_id);
4883 		if (!arg_type) {
4884 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4885 			return -EINVAL;
4886 		}
4887 
4888 		if (btf_type_is_resolve_source_only(arg_type)) {
4889 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4890 			return -EINVAL;
4891 		}
4892 
4893 		if (args[i].name_off &&
4894 		    (!btf_name_offset_valid(btf, args[i].name_off) ||
4895 		     !btf_name_valid_identifier(btf, args[i].name_off))) {
4896 			btf_verifier_log_type(env, t,
4897 					      "Invalid arg#%u", i + 1);
4898 			return -EINVAL;
4899 		}
4900 
4901 		if (btf_type_needs_resolve(arg_type) &&
4902 		    !env_type_is_resolved(env, arg_type_id)) {
4903 			err = btf_resolve(env, arg_type, arg_type_id);
4904 			if (err)
4905 				return err;
4906 		}
4907 
4908 		if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
4909 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4910 			return -EINVAL;
4911 		}
4912 	}
4913 
4914 	return 0;
4915 }
4916 
4917 static int btf_func_check(struct btf_verifier_env *env,
4918 			  const struct btf_type *t)
4919 {
4920 	const struct btf_type *proto_type;
4921 	const struct btf_param *args;
4922 	const struct btf *btf;
4923 	u16 nr_args, i;
4924 
4925 	btf = env->btf;
4926 	proto_type = btf_type_by_id(btf, t->type);
4927 
4928 	if (!proto_type || !btf_type_is_func_proto(proto_type)) {
4929 		btf_verifier_log_type(env, t, "Invalid type_id");
4930 		return -EINVAL;
4931 	}
4932 
4933 	args = (const struct btf_param *)(proto_type + 1);
4934 	nr_args = btf_type_vlen(proto_type);
4935 	for (i = 0; i < nr_args; i++) {
4936 		if (!args[i].name_off && args[i].type) {
4937 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
4938 			return -EINVAL;
4939 		}
4940 	}
4941 
4942 	return 0;
4943 }
4944 
4945 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
4946 	[BTF_KIND_INT] = &int_ops,
4947 	[BTF_KIND_PTR] = &ptr_ops,
4948 	[BTF_KIND_ARRAY] = &array_ops,
4949 	[BTF_KIND_STRUCT] = &struct_ops,
4950 	[BTF_KIND_UNION] = &struct_ops,
4951 	[BTF_KIND_ENUM] = &enum_ops,
4952 	[BTF_KIND_FWD] = &fwd_ops,
4953 	[BTF_KIND_TYPEDEF] = &modifier_ops,
4954 	[BTF_KIND_VOLATILE] = &modifier_ops,
4955 	[BTF_KIND_CONST] = &modifier_ops,
4956 	[BTF_KIND_RESTRICT] = &modifier_ops,
4957 	[BTF_KIND_FUNC] = &func_ops,
4958 	[BTF_KIND_FUNC_PROTO] = &func_proto_ops,
4959 	[BTF_KIND_VAR] = &var_ops,
4960 	[BTF_KIND_DATASEC] = &datasec_ops,
4961 	[BTF_KIND_FLOAT] = &float_ops,
4962 	[BTF_KIND_DECL_TAG] = &decl_tag_ops,
4963 	[BTF_KIND_TYPE_TAG] = &modifier_ops,
4964 	[BTF_KIND_ENUM64] = &enum64_ops,
4965 };
4966 
4967 static s32 btf_check_meta(struct btf_verifier_env *env,
4968 			  const struct btf_type *t,
4969 			  u32 meta_left)
4970 {
4971 	u32 saved_meta_left = meta_left;
4972 	s32 var_meta_size;
4973 
4974 	if (meta_left < sizeof(*t)) {
4975 		btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
4976 				 env->log_type_id, meta_left, sizeof(*t));
4977 		return -EINVAL;
4978 	}
4979 	meta_left -= sizeof(*t);
4980 
4981 	if (t->info & ~BTF_INFO_MASK) {
4982 		btf_verifier_log(env, "[%u] Invalid btf_info:%x",
4983 				 env->log_type_id, t->info);
4984 		return -EINVAL;
4985 	}
4986 
4987 	if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
4988 	    BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
4989 		btf_verifier_log(env, "[%u] Invalid kind:%u",
4990 				 env->log_type_id, BTF_INFO_KIND(t->info));
4991 		return -EINVAL;
4992 	}
4993 
4994 	if (!btf_name_offset_valid(env->btf, t->name_off)) {
4995 		btf_verifier_log(env, "[%u] Invalid name_offset:%u",
4996 				 env->log_type_id, t->name_off);
4997 		return -EINVAL;
4998 	}
4999 
5000 	var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
5001 	if (var_meta_size < 0)
5002 		return var_meta_size;
5003 
5004 	meta_left -= var_meta_size;
5005 
5006 	return saved_meta_left - meta_left;
5007 }
5008 
5009 static int btf_check_all_metas(struct btf_verifier_env *env)
5010 {
5011 	struct btf *btf = env->btf;
5012 	struct btf_header *hdr;
5013 	void *cur, *end;
5014 
5015 	hdr = &btf->hdr;
5016 	cur = btf->nohdr_data + hdr->type_off;
5017 	end = cur + hdr->type_len;
5018 
5019 	env->log_type_id = btf->base_btf ? btf->start_id : 1;
5020 	while (cur < end) {
5021 		struct btf_type *t = cur;
5022 		s32 meta_size;
5023 
5024 		meta_size = btf_check_meta(env, t, end - cur);
5025 		if (meta_size < 0)
5026 			return meta_size;
5027 
5028 		btf_add_type(env, t);
5029 		cur += meta_size;
5030 		env->log_type_id++;
5031 	}
5032 
5033 	return 0;
5034 }
5035 
5036 static bool btf_resolve_valid(struct btf_verifier_env *env,
5037 			      const struct btf_type *t,
5038 			      u32 type_id)
5039 {
5040 	struct btf *btf = env->btf;
5041 
5042 	if (!env_type_is_resolved(env, type_id))
5043 		return false;
5044 
5045 	if (btf_type_is_struct(t) || btf_type_is_datasec(t))
5046 		return !btf_resolved_type_id(btf, type_id) &&
5047 		       !btf_resolved_type_size(btf, type_id);
5048 
5049 	if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5050 		return btf_resolved_type_id(btf, type_id) &&
5051 		       !btf_resolved_type_size(btf, type_id);
5052 
5053 	if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5054 	    btf_type_is_var(t)) {
5055 		t = btf_type_id_resolve(btf, &type_id);
5056 		return t &&
5057 		       !btf_type_is_modifier(t) &&
5058 		       !btf_type_is_var(t) &&
5059 		       !btf_type_is_datasec(t);
5060 	}
5061 
5062 	if (btf_type_is_array(t)) {
5063 		const struct btf_array *array = btf_type_array(t);
5064 		const struct btf_type *elem_type;
5065 		u32 elem_type_id = array->type;
5066 		u32 elem_size;
5067 
5068 		elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5069 		return elem_type && !btf_type_is_modifier(elem_type) &&
5070 			(array->nelems * elem_size ==
5071 			 btf_resolved_type_size(btf, type_id));
5072 	}
5073 
5074 	return false;
5075 }
5076 
5077 static int btf_resolve(struct btf_verifier_env *env,
5078 		       const struct btf_type *t, u32 type_id)
5079 {
5080 	u32 save_log_type_id = env->log_type_id;
5081 	const struct resolve_vertex *v;
5082 	int err = 0;
5083 
5084 	env->resolve_mode = RESOLVE_TBD;
5085 	env_stack_push(env, t, type_id);
5086 	while (!err && (v = env_stack_peak(env))) {
5087 		env->log_type_id = v->type_id;
5088 		err = btf_type_ops(v->t)->resolve(env, v);
5089 	}
5090 
5091 	env->log_type_id = type_id;
5092 	if (err == -E2BIG) {
5093 		btf_verifier_log_type(env, t,
5094 				      "Exceeded max resolving depth:%u",
5095 				      MAX_RESOLVE_DEPTH);
5096 	} else if (err == -EEXIST) {
5097 		btf_verifier_log_type(env, t, "Loop detected");
5098 	}
5099 
5100 	/* Final sanity check */
5101 	if (!err && !btf_resolve_valid(env, t, type_id)) {
5102 		btf_verifier_log_type(env, t, "Invalid resolve state");
5103 		err = -EINVAL;
5104 	}
5105 
5106 	env->log_type_id = save_log_type_id;
5107 	return err;
5108 }
5109 
5110 static int btf_check_all_types(struct btf_verifier_env *env)
5111 {
5112 	struct btf *btf = env->btf;
5113 	const struct btf_type *t;
5114 	u32 type_id, i;
5115 	int err;
5116 
5117 	err = env_resolve_init(env);
5118 	if (err)
5119 		return err;
5120 
5121 	env->phase++;
5122 	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5123 		type_id = btf->start_id + i;
5124 		t = btf_type_by_id(btf, type_id);
5125 
5126 		env->log_type_id = type_id;
5127 		if (btf_type_needs_resolve(t) &&
5128 		    !env_type_is_resolved(env, type_id)) {
5129 			err = btf_resolve(env, t, type_id);
5130 			if (err)
5131 				return err;
5132 		}
5133 
5134 		if (btf_type_is_func_proto(t)) {
5135 			err = btf_func_proto_check(env, t);
5136 			if (err)
5137 				return err;
5138 		}
5139 	}
5140 
5141 	return 0;
5142 }
5143 
5144 static int btf_parse_type_sec(struct btf_verifier_env *env)
5145 {
5146 	const struct btf_header *hdr = &env->btf->hdr;
5147 	int err;
5148 
5149 	/* Type section must align to 4 bytes */
5150 	if (hdr->type_off & (sizeof(u32) - 1)) {
5151 		btf_verifier_log(env, "Unaligned type_off");
5152 		return -EINVAL;
5153 	}
5154 
5155 	if (!env->btf->base_btf && !hdr->type_len) {
5156 		btf_verifier_log(env, "No type found");
5157 		return -EINVAL;
5158 	}
5159 
5160 	err = btf_check_all_metas(env);
5161 	if (err)
5162 		return err;
5163 
5164 	return btf_check_all_types(env);
5165 }
5166 
5167 static int btf_parse_str_sec(struct btf_verifier_env *env)
5168 {
5169 	const struct btf_header *hdr;
5170 	struct btf *btf = env->btf;
5171 	const char *start, *end;
5172 
5173 	hdr = &btf->hdr;
5174 	start = btf->nohdr_data + hdr->str_off;
5175 	end = start + hdr->str_len;
5176 
5177 	if (end != btf->data + btf->data_size) {
5178 		btf_verifier_log(env, "String section is not at the end");
5179 		return -EINVAL;
5180 	}
5181 
5182 	btf->strings = start;
5183 
5184 	if (btf->base_btf && !hdr->str_len)
5185 		return 0;
5186 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
5187 		btf_verifier_log(env, "Invalid string section");
5188 		return -EINVAL;
5189 	}
5190 	if (!btf->base_btf && start[0]) {
5191 		btf_verifier_log(env, "Invalid string section");
5192 		return -EINVAL;
5193 	}
5194 
5195 	return 0;
5196 }
5197 
5198 static const size_t btf_sec_info_offset[] = {
5199 	offsetof(struct btf_header, type_off),
5200 	offsetof(struct btf_header, str_off),
5201 };
5202 
5203 static int btf_sec_info_cmp(const void *a, const void *b)
5204 {
5205 	const struct btf_sec_info *x = a;
5206 	const struct btf_sec_info *y = b;
5207 
5208 	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
5209 }
5210 
5211 static int btf_check_sec_info(struct btf_verifier_env *env,
5212 			      u32 btf_data_size)
5213 {
5214 	struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
5215 	u32 total, expected_total, i;
5216 	const struct btf_header *hdr;
5217 	const struct btf *btf;
5218 
5219 	btf = env->btf;
5220 	hdr = &btf->hdr;
5221 
5222 	/* Populate the secs from hdr */
5223 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
5224 		secs[i] = *(struct btf_sec_info *)((void *)hdr +
5225 						   btf_sec_info_offset[i]);
5226 
5227 	sort(secs, ARRAY_SIZE(btf_sec_info_offset),
5228 	     sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
5229 
5230 	/* Check for gaps and overlap among sections */
5231 	total = 0;
5232 	expected_total = btf_data_size - hdr->hdr_len;
5233 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
5234 		if (expected_total < secs[i].off) {
5235 			btf_verifier_log(env, "Invalid section offset");
5236 			return -EINVAL;
5237 		}
5238 		if (total < secs[i].off) {
5239 			/* gap */
5240 			btf_verifier_log(env, "Unsupported section found");
5241 			return -EINVAL;
5242 		}
5243 		if (total > secs[i].off) {
5244 			btf_verifier_log(env, "Section overlap found");
5245 			return -EINVAL;
5246 		}
5247 		if (expected_total - total < secs[i].len) {
5248 			btf_verifier_log(env,
5249 					 "Total section length too long");
5250 			return -EINVAL;
5251 		}
5252 		total += secs[i].len;
5253 	}
5254 
5255 	/* There is data other than hdr and known sections */
5256 	if (expected_total != total) {
5257 		btf_verifier_log(env, "Unsupported section found");
5258 		return -EINVAL;
5259 	}
5260 
5261 	return 0;
5262 }
5263 
5264 static int btf_parse_hdr(struct btf_verifier_env *env)
5265 {
5266 	u32 hdr_len, hdr_copy, btf_data_size;
5267 	const struct btf_header *hdr;
5268 	struct btf *btf;
5269 
5270 	btf = env->btf;
5271 	btf_data_size = btf->data_size;
5272 
5273 	if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
5274 		btf_verifier_log(env, "hdr_len not found");
5275 		return -EINVAL;
5276 	}
5277 
5278 	hdr = btf->data;
5279 	hdr_len = hdr->hdr_len;
5280 	if (btf_data_size < hdr_len) {
5281 		btf_verifier_log(env, "btf_header not found");
5282 		return -EINVAL;
5283 	}
5284 
5285 	/* Ensure the unsupported header fields are zero */
5286 	if (hdr_len > sizeof(btf->hdr)) {
5287 		u8 *expected_zero = btf->data + sizeof(btf->hdr);
5288 		u8 *end = btf->data + hdr_len;
5289 
5290 		for (; expected_zero < end; expected_zero++) {
5291 			if (*expected_zero) {
5292 				btf_verifier_log(env, "Unsupported btf_header");
5293 				return -E2BIG;
5294 			}
5295 		}
5296 	}
5297 
5298 	hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
5299 	memcpy(&btf->hdr, btf->data, hdr_copy);
5300 
5301 	hdr = &btf->hdr;
5302 
5303 	btf_verifier_log_hdr(env, btf_data_size);
5304 
5305 	if (hdr->magic != BTF_MAGIC) {
5306 		btf_verifier_log(env, "Invalid magic");
5307 		return -EINVAL;
5308 	}
5309 
5310 	if (hdr->version != BTF_VERSION) {
5311 		btf_verifier_log(env, "Unsupported version");
5312 		return -ENOTSUPP;
5313 	}
5314 
5315 	if (hdr->flags) {
5316 		btf_verifier_log(env, "Unsupported flags");
5317 		return -ENOTSUPP;
5318 	}
5319 
5320 	if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
5321 		btf_verifier_log(env, "No data");
5322 		return -EINVAL;
5323 	}
5324 
5325 	return btf_check_sec_info(env, btf_data_size);
5326 }
5327 
5328 static const char *alloc_obj_fields[] = {
5329 	"bpf_spin_lock",
5330 	"bpf_list_head",
5331 	"bpf_list_node",
5332 	"bpf_rb_root",
5333 	"bpf_rb_node",
5334 };
5335 
5336 static struct btf_struct_metas *
5337 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
5338 {
5339 	union {
5340 		struct btf_id_set set;
5341 		struct {
5342 			u32 _cnt;
5343 			u32 _ids[ARRAY_SIZE(alloc_obj_fields)];
5344 		} _arr;
5345 	} aof;
5346 	struct btf_struct_metas *tab = NULL;
5347 	int i, n, id, ret;
5348 
5349 	BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
5350 	BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
5351 
5352 	memset(&aof, 0, sizeof(aof));
5353 	for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
5354 		/* Try to find whether this special type exists in user BTF, and
5355 		 * if so remember its ID so we can easily find it among members
5356 		 * of structs that we iterate in the next loop.
5357 		 */
5358 		id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
5359 		if (id < 0)
5360 			continue;
5361 		aof.set.ids[aof.set.cnt++] = id;
5362 	}
5363 
5364 	if (!aof.set.cnt)
5365 		return NULL;
5366 	sort(&aof.set.ids, aof.set.cnt, sizeof(aof.set.ids[0]), btf_id_cmp_func, NULL);
5367 
5368 	n = btf_nr_types(btf);
5369 	for (i = 1; i < n; i++) {
5370 		struct btf_struct_metas *new_tab;
5371 		const struct btf_member *member;
5372 		struct btf_field_offs *foffs;
5373 		struct btf_struct_meta *type;
5374 		struct btf_record *record;
5375 		const struct btf_type *t;
5376 		int j, tab_cnt;
5377 
5378 		t = btf_type_by_id(btf, i);
5379 		if (!t) {
5380 			ret = -EINVAL;
5381 			goto free;
5382 		}
5383 		if (!__btf_type_is_struct(t))
5384 			continue;
5385 
5386 		cond_resched();
5387 
5388 		for_each_member(j, t, member) {
5389 			if (btf_id_set_contains(&aof.set, member->type))
5390 				goto parse;
5391 		}
5392 		continue;
5393 	parse:
5394 		tab_cnt = tab ? tab->cnt : 0;
5395 		new_tab = krealloc(tab, offsetof(struct btf_struct_metas, types[tab_cnt + 1]),
5396 				   GFP_KERNEL | __GFP_NOWARN);
5397 		if (!new_tab) {
5398 			ret = -ENOMEM;
5399 			goto free;
5400 		}
5401 		if (!tab)
5402 			new_tab->cnt = 0;
5403 		tab = new_tab;
5404 
5405 		type = &tab->types[tab->cnt];
5406 		type->btf_id = i;
5407 		record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
5408 						  BPF_RB_ROOT | BPF_RB_NODE, t->size);
5409 		/* The record cannot be unset, treat it as an error if so */
5410 		if (IS_ERR_OR_NULL(record)) {
5411 			ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
5412 			goto free;
5413 		}
5414 		foffs = btf_parse_field_offs(record);
5415 		/* We need the field_offs to be valid for a valid record,
5416 		 * either both should be set or both should be unset.
5417 		 */
5418 		if (IS_ERR_OR_NULL(foffs)) {
5419 			btf_record_free(record);
5420 			ret = -EFAULT;
5421 			goto free;
5422 		}
5423 		type->record = record;
5424 		type->field_offs = foffs;
5425 		tab->cnt++;
5426 	}
5427 	return tab;
5428 free:
5429 	btf_struct_metas_free(tab);
5430 	return ERR_PTR(ret);
5431 }
5432 
5433 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
5434 {
5435 	struct btf_struct_metas *tab;
5436 
5437 	BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
5438 	tab = btf->struct_meta_tab;
5439 	if (!tab)
5440 		return NULL;
5441 	return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
5442 }
5443 
5444 static int btf_check_type_tags(struct btf_verifier_env *env,
5445 			       struct btf *btf, int start_id)
5446 {
5447 	int i, n, good_id = start_id - 1;
5448 	bool in_tags;
5449 
5450 	n = btf_nr_types(btf);
5451 	for (i = start_id; i < n; i++) {
5452 		const struct btf_type *t;
5453 		int chain_limit = 32;
5454 		u32 cur_id = i;
5455 
5456 		t = btf_type_by_id(btf, i);
5457 		if (!t)
5458 			return -EINVAL;
5459 		if (!btf_type_is_modifier(t))
5460 			continue;
5461 
5462 		cond_resched();
5463 
5464 		in_tags = btf_type_is_type_tag(t);
5465 		while (btf_type_is_modifier(t)) {
5466 			if (!chain_limit--) {
5467 				btf_verifier_log(env, "Max chain length or cycle detected");
5468 				return -ELOOP;
5469 			}
5470 			if (btf_type_is_type_tag(t)) {
5471 				if (!in_tags) {
5472 					btf_verifier_log(env, "Type tags don't precede modifiers");
5473 					return -EINVAL;
5474 				}
5475 			} else if (in_tags) {
5476 				in_tags = false;
5477 			}
5478 			if (cur_id <= good_id)
5479 				break;
5480 			/* Move to next type */
5481 			cur_id = t->type;
5482 			t = btf_type_by_id(btf, cur_id);
5483 			if (!t)
5484 				return -EINVAL;
5485 		}
5486 		good_id = i;
5487 	}
5488 	return 0;
5489 }
5490 
5491 static struct btf *btf_parse(bpfptr_t btf_data, u32 btf_data_size,
5492 			     u32 log_level, char __user *log_ubuf, u32 log_size)
5493 {
5494 	struct btf_struct_metas *struct_meta_tab;
5495 	struct btf_verifier_env *env = NULL;
5496 	struct bpf_verifier_log *log;
5497 	struct btf *btf = NULL;
5498 	u8 *data;
5499 	int err;
5500 
5501 	if (btf_data_size > BTF_MAX_SIZE)
5502 		return ERR_PTR(-E2BIG);
5503 
5504 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5505 	if (!env)
5506 		return ERR_PTR(-ENOMEM);
5507 
5508 	log = &env->log;
5509 	if (log_level || log_ubuf || log_size) {
5510 		/* user requested verbose verifier output
5511 		 * and supplied buffer to store the verification trace
5512 		 */
5513 		log->level = log_level;
5514 		log->ubuf = log_ubuf;
5515 		log->len_total = log_size;
5516 
5517 		/* log attributes have to be sane */
5518 		if (!bpf_verifier_log_attr_valid(log)) {
5519 			err = -EINVAL;
5520 			goto errout;
5521 		}
5522 	}
5523 
5524 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5525 	if (!btf) {
5526 		err = -ENOMEM;
5527 		goto errout;
5528 	}
5529 	env->btf = btf;
5530 
5531 	data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
5532 	if (!data) {
5533 		err = -ENOMEM;
5534 		goto errout;
5535 	}
5536 
5537 	btf->data = data;
5538 	btf->data_size = btf_data_size;
5539 
5540 	if (copy_from_bpfptr(data, btf_data, btf_data_size)) {
5541 		err = -EFAULT;
5542 		goto errout;
5543 	}
5544 
5545 	err = btf_parse_hdr(env);
5546 	if (err)
5547 		goto errout;
5548 
5549 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5550 
5551 	err = btf_parse_str_sec(env);
5552 	if (err)
5553 		goto errout;
5554 
5555 	err = btf_parse_type_sec(env);
5556 	if (err)
5557 		goto errout;
5558 
5559 	err = btf_check_type_tags(env, btf, 1);
5560 	if (err)
5561 		goto errout;
5562 
5563 	struct_meta_tab = btf_parse_struct_metas(log, btf);
5564 	if (IS_ERR(struct_meta_tab)) {
5565 		err = PTR_ERR(struct_meta_tab);
5566 		goto errout;
5567 	}
5568 	btf->struct_meta_tab = struct_meta_tab;
5569 
5570 	if (struct_meta_tab) {
5571 		int i;
5572 
5573 		for (i = 0; i < struct_meta_tab->cnt; i++) {
5574 			err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
5575 			if (err < 0)
5576 				goto errout_meta;
5577 		}
5578 	}
5579 
5580 	if (log->level && bpf_verifier_log_full(log)) {
5581 		err = -ENOSPC;
5582 		goto errout_meta;
5583 	}
5584 
5585 	btf_verifier_env_free(env);
5586 	refcount_set(&btf->refcnt, 1);
5587 	return btf;
5588 
5589 errout_meta:
5590 	btf_free_struct_meta_tab(btf);
5591 errout:
5592 	btf_verifier_env_free(env);
5593 	if (btf)
5594 		btf_free(btf);
5595 	return ERR_PTR(err);
5596 }
5597 
5598 extern char __weak __start_BTF[];
5599 extern char __weak __stop_BTF[];
5600 extern struct btf *btf_vmlinux;
5601 
5602 #define BPF_MAP_TYPE(_id, _ops)
5603 #define BPF_LINK_TYPE(_id, _name)
5604 static union {
5605 	struct bpf_ctx_convert {
5606 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5607 	prog_ctx_type _id##_prog; \
5608 	kern_ctx_type _id##_kern;
5609 #include <linux/bpf_types.h>
5610 #undef BPF_PROG_TYPE
5611 	} *__t;
5612 	/* 't' is written once under lock. Read many times. */
5613 	const struct btf_type *t;
5614 } bpf_ctx_convert;
5615 enum {
5616 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5617 	__ctx_convert##_id,
5618 #include <linux/bpf_types.h>
5619 #undef BPF_PROG_TYPE
5620 	__ctx_convert_unused, /* to avoid empty enum in extreme .config */
5621 };
5622 static u8 bpf_ctx_convert_map[] = {
5623 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
5624 	[_id] = __ctx_convert##_id,
5625 #include <linux/bpf_types.h>
5626 #undef BPF_PROG_TYPE
5627 	0, /* avoid empty array */
5628 };
5629 #undef BPF_MAP_TYPE
5630 #undef BPF_LINK_TYPE
5631 
5632 const struct btf_member *
5633 btf_get_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5634 		      const struct btf_type *t, enum bpf_prog_type prog_type,
5635 		      int arg)
5636 {
5637 	const struct btf_type *conv_struct;
5638 	const struct btf_type *ctx_struct;
5639 	const struct btf_member *ctx_type;
5640 	const char *tname, *ctx_tname;
5641 
5642 	conv_struct = bpf_ctx_convert.t;
5643 	if (!conv_struct) {
5644 		bpf_log(log, "btf_vmlinux is malformed\n");
5645 		return NULL;
5646 	}
5647 	t = btf_type_by_id(btf, t->type);
5648 	while (btf_type_is_modifier(t))
5649 		t = btf_type_by_id(btf, t->type);
5650 	if (!btf_type_is_struct(t)) {
5651 		/* Only pointer to struct is supported for now.
5652 		 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5653 		 * is not supported yet.
5654 		 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5655 		 */
5656 		return NULL;
5657 	}
5658 	tname = btf_name_by_offset(btf, t->name_off);
5659 	if (!tname) {
5660 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5661 		return NULL;
5662 	}
5663 	/* prog_type is valid bpf program type. No need for bounds check. */
5664 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
5665 	/* ctx_struct is a pointer to prog_ctx_type in vmlinux.
5666 	 * Like 'struct __sk_buff'
5667 	 */
5668 	ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
5669 	if (!ctx_struct)
5670 		/* should not happen */
5671 		return NULL;
5672 again:
5673 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
5674 	if (!ctx_tname) {
5675 		/* should not happen */
5676 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5677 		return NULL;
5678 	}
5679 	/* only compare that prog's ctx type name is the same as
5680 	 * kernel expects. No need to compare field by field.
5681 	 * It's ok for bpf prog to do:
5682 	 * struct __sk_buff {};
5683 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5684 	 * { // no fields of skb are ever used }
5685 	 */
5686 	if (strcmp(ctx_tname, tname)) {
5687 		/* bpf_user_pt_regs_t is a typedef, so resolve it to
5688 		 * underlying struct and check name again
5689 		 */
5690 		if (!btf_type_is_modifier(ctx_struct))
5691 			return NULL;
5692 		while (btf_type_is_modifier(ctx_struct))
5693 			ctx_struct = btf_type_by_id(btf_vmlinux, ctx_struct->type);
5694 		goto again;
5695 	}
5696 	return ctx_type;
5697 }
5698 
5699 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
5700 				     struct btf *btf,
5701 				     const struct btf_type *t,
5702 				     enum bpf_prog_type prog_type,
5703 				     int arg)
5704 {
5705 	const struct btf_member *prog_ctx_type, *kern_ctx_type;
5706 
5707 	prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
5708 	if (!prog_ctx_type)
5709 		return -ENOENT;
5710 	kern_ctx_type = prog_ctx_type + 1;
5711 	return kern_ctx_type->type;
5712 }
5713 
5714 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
5715 {
5716 	const struct btf_member *kctx_member;
5717 	const struct btf_type *conv_struct;
5718 	const struct btf_type *kctx_type;
5719 	u32 kctx_type_id;
5720 
5721 	conv_struct = bpf_ctx_convert.t;
5722 	/* get member for kernel ctx type */
5723 	kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
5724 	kctx_type_id = kctx_member->type;
5725 	kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
5726 	if (!btf_type_is_struct(kctx_type)) {
5727 		bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
5728 		return -EINVAL;
5729 	}
5730 
5731 	return kctx_type_id;
5732 }
5733 
5734 BTF_ID_LIST(bpf_ctx_convert_btf_id)
5735 BTF_ID(struct, bpf_ctx_convert)
5736 
5737 struct btf *btf_parse_vmlinux(void)
5738 {
5739 	struct btf_verifier_env *env = NULL;
5740 	struct bpf_verifier_log *log;
5741 	struct btf *btf = NULL;
5742 	int err;
5743 
5744 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5745 	if (!env)
5746 		return ERR_PTR(-ENOMEM);
5747 
5748 	log = &env->log;
5749 	log->level = BPF_LOG_KERNEL;
5750 
5751 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5752 	if (!btf) {
5753 		err = -ENOMEM;
5754 		goto errout;
5755 	}
5756 	env->btf = btf;
5757 
5758 	btf->data = __start_BTF;
5759 	btf->data_size = __stop_BTF - __start_BTF;
5760 	btf->kernel_btf = true;
5761 	snprintf(btf->name, sizeof(btf->name), "vmlinux");
5762 
5763 	err = btf_parse_hdr(env);
5764 	if (err)
5765 		goto errout;
5766 
5767 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5768 
5769 	err = btf_parse_str_sec(env);
5770 	if (err)
5771 		goto errout;
5772 
5773 	err = btf_check_all_metas(env);
5774 	if (err)
5775 		goto errout;
5776 
5777 	err = btf_check_type_tags(env, btf, 1);
5778 	if (err)
5779 		goto errout;
5780 
5781 	/* btf_parse_vmlinux() runs under bpf_verifier_lock */
5782 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
5783 
5784 	bpf_struct_ops_init(btf, log);
5785 
5786 	refcount_set(&btf->refcnt, 1);
5787 
5788 	err = btf_alloc_id(btf);
5789 	if (err)
5790 		goto errout;
5791 
5792 	btf_verifier_env_free(env);
5793 	return btf;
5794 
5795 errout:
5796 	btf_verifier_env_free(env);
5797 	if (btf) {
5798 		kvfree(btf->types);
5799 		kfree(btf);
5800 	}
5801 	return ERR_PTR(err);
5802 }
5803 
5804 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5805 
5806 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
5807 {
5808 	struct btf_verifier_env *env = NULL;
5809 	struct bpf_verifier_log *log;
5810 	struct btf *btf = NULL, *base_btf;
5811 	int err;
5812 
5813 	base_btf = bpf_get_btf_vmlinux();
5814 	if (IS_ERR(base_btf))
5815 		return base_btf;
5816 	if (!base_btf)
5817 		return ERR_PTR(-EINVAL);
5818 
5819 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
5820 	if (!env)
5821 		return ERR_PTR(-ENOMEM);
5822 
5823 	log = &env->log;
5824 	log->level = BPF_LOG_KERNEL;
5825 
5826 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
5827 	if (!btf) {
5828 		err = -ENOMEM;
5829 		goto errout;
5830 	}
5831 	env->btf = btf;
5832 
5833 	btf->base_btf = base_btf;
5834 	btf->start_id = base_btf->nr_types;
5835 	btf->start_str_off = base_btf->hdr.str_len;
5836 	btf->kernel_btf = true;
5837 	snprintf(btf->name, sizeof(btf->name), "%s", module_name);
5838 
5839 	btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
5840 	if (!btf->data) {
5841 		err = -ENOMEM;
5842 		goto errout;
5843 	}
5844 	memcpy(btf->data, data, data_size);
5845 	btf->data_size = data_size;
5846 
5847 	err = btf_parse_hdr(env);
5848 	if (err)
5849 		goto errout;
5850 
5851 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
5852 
5853 	err = btf_parse_str_sec(env);
5854 	if (err)
5855 		goto errout;
5856 
5857 	err = btf_check_all_metas(env);
5858 	if (err)
5859 		goto errout;
5860 
5861 	err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
5862 	if (err)
5863 		goto errout;
5864 
5865 	btf_verifier_env_free(env);
5866 	refcount_set(&btf->refcnt, 1);
5867 	return btf;
5868 
5869 errout:
5870 	btf_verifier_env_free(env);
5871 	if (btf) {
5872 		kvfree(btf->data);
5873 		kvfree(btf->types);
5874 		kfree(btf);
5875 	}
5876 	return ERR_PTR(err);
5877 }
5878 
5879 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5880 
5881 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
5882 {
5883 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5884 
5885 	if (tgt_prog)
5886 		return tgt_prog->aux->btf;
5887 	else
5888 		return prog->aux->attach_btf;
5889 }
5890 
5891 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
5892 {
5893 	/* t comes in already as a pointer */
5894 	t = btf_type_by_id(btf, t->type);
5895 
5896 	/* allow const */
5897 	if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
5898 		t = btf_type_by_id(btf, t->type);
5899 
5900 	return btf_type_is_int(t);
5901 }
5902 
5903 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
5904 			   int off)
5905 {
5906 	const struct btf_param *args;
5907 	const struct btf_type *t;
5908 	u32 offset = 0, nr_args;
5909 	int i;
5910 
5911 	if (!func_proto)
5912 		return off / 8;
5913 
5914 	nr_args = btf_type_vlen(func_proto);
5915 	args = (const struct btf_param *)(func_proto + 1);
5916 	for (i = 0; i < nr_args; i++) {
5917 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
5918 		offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5919 		if (off < offset)
5920 			return i;
5921 	}
5922 
5923 	t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
5924 	offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
5925 	if (off < offset)
5926 		return nr_args;
5927 
5928 	return nr_args + 1;
5929 }
5930 
5931 static bool prog_args_trusted(const struct bpf_prog *prog)
5932 {
5933 	enum bpf_attach_type atype = prog->expected_attach_type;
5934 
5935 	switch (prog->type) {
5936 	case BPF_PROG_TYPE_TRACING:
5937 		return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
5938 	case BPF_PROG_TYPE_LSM:
5939 		return bpf_lsm_is_trusted(prog);
5940 	case BPF_PROG_TYPE_STRUCT_OPS:
5941 		return true;
5942 	default:
5943 		return false;
5944 	}
5945 }
5946 
5947 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
5948 		    const struct bpf_prog *prog,
5949 		    struct bpf_insn_access_aux *info)
5950 {
5951 	const struct btf_type *t = prog->aux->attach_func_proto;
5952 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
5953 	struct btf *btf = bpf_prog_get_target_btf(prog);
5954 	const char *tname = prog->aux->attach_func_name;
5955 	struct bpf_verifier_log *log = info->log;
5956 	const struct btf_param *args;
5957 	const char *tag_value;
5958 	u32 nr_args, arg;
5959 	int i, ret;
5960 
5961 	if (off % 8) {
5962 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
5963 			tname, off);
5964 		return false;
5965 	}
5966 	arg = get_ctx_arg_idx(btf, t, off);
5967 	args = (const struct btf_param *)(t + 1);
5968 	/* if (t == NULL) Fall back to default BPF prog with
5969 	 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
5970 	 */
5971 	nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
5972 	if (prog->aux->attach_btf_trace) {
5973 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
5974 		args++;
5975 		nr_args--;
5976 	}
5977 
5978 	if (arg > nr_args) {
5979 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
5980 			tname, arg + 1);
5981 		return false;
5982 	}
5983 
5984 	if (arg == nr_args) {
5985 		switch (prog->expected_attach_type) {
5986 		case BPF_LSM_CGROUP:
5987 		case BPF_LSM_MAC:
5988 		case BPF_TRACE_FEXIT:
5989 			/* When LSM programs are attached to void LSM hooks
5990 			 * they use FEXIT trampolines and when attached to
5991 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
5992 			 *
5993 			 * While the LSM programs are BPF_MODIFY_RETURN-like
5994 			 * the check:
5995 			 *
5996 			 *	if (ret_type != 'int')
5997 			 *		return -EINVAL;
5998 			 *
5999 			 * is _not_ done here. This is still safe as LSM hooks
6000 			 * have only void and int return types.
6001 			 */
6002 			if (!t)
6003 				return true;
6004 			t = btf_type_by_id(btf, t->type);
6005 			break;
6006 		case BPF_MODIFY_RETURN:
6007 			/* For now the BPF_MODIFY_RETURN can only be attached to
6008 			 * functions that return an int.
6009 			 */
6010 			if (!t)
6011 				return false;
6012 
6013 			t = btf_type_skip_modifiers(btf, t->type, NULL);
6014 			if (!btf_type_is_small_int(t)) {
6015 				bpf_log(log,
6016 					"ret type %s not allowed for fmod_ret\n",
6017 					btf_type_str(t));
6018 				return false;
6019 			}
6020 			break;
6021 		default:
6022 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6023 				tname, arg + 1);
6024 			return false;
6025 		}
6026 	} else {
6027 		if (!t)
6028 			/* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6029 			return true;
6030 		t = btf_type_by_id(btf, args[arg].type);
6031 	}
6032 
6033 	/* skip modifiers */
6034 	while (btf_type_is_modifier(t))
6035 		t = btf_type_by_id(btf, t->type);
6036 	if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6037 		/* accessing a scalar */
6038 		return true;
6039 	if (!btf_type_is_ptr(t)) {
6040 		bpf_log(log,
6041 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6042 			tname, arg,
6043 			__btf_name_by_offset(btf, t->name_off),
6044 			btf_type_str(t));
6045 		return false;
6046 	}
6047 
6048 	/* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6049 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6050 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6051 		u32 type, flag;
6052 
6053 		type = base_type(ctx_arg_info->reg_type);
6054 		flag = type_flag(ctx_arg_info->reg_type);
6055 		if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6056 		    (flag & PTR_MAYBE_NULL)) {
6057 			info->reg_type = ctx_arg_info->reg_type;
6058 			return true;
6059 		}
6060 	}
6061 
6062 	if (t->type == 0)
6063 		/* This is a pointer to void.
6064 		 * It is the same as scalar from the verifier safety pov.
6065 		 * No further pointer walking is allowed.
6066 		 */
6067 		return true;
6068 
6069 	if (is_int_ptr(btf, t))
6070 		return true;
6071 
6072 	/* this is a pointer to another type */
6073 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6074 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6075 
6076 		if (ctx_arg_info->offset == off) {
6077 			if (!ctx_arg_info->btf_id) {
6078 				bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6079 				return false;
6080 			}
6081 
6082 			info->reg_type = ctx_arg_info->reg_type;
6083 			info->btf = btf_vmlinux;
6084 			info->btf_id = ctx_arg_info->btf_id;
6085 			return true;
6086 		}
6087 	}
6088 
6089 	info->reg_type = PTR_TO_BTF_ID;
6090 	if (prog_args_trusted(prog))
6091 		info->reg_type |= PTR_TRUSTED;
6092 
6093 	if (tgt_prog) {
6094 		enum bpf_prog_type tgt_type;
6095 
6096 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6097 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
6098 		else
6099 			tgt_type = tgt_prog->type;
6100 
6101 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6102 		if (ret > 0) {
6103 			info->btf = btf_vmlinux;
6104 			info->btf_id = ret;
6105 			return true;
6106 		} else {
6107 			return false;
6108 		}
6109 	}
6110 
6111 	info->btf = btf;
6112 	info->btf_id = t->type;
6113 	t = btf_type_by_id(btf, t->type);
6114 
6115 	if (btf_type_is_type_tag(t)) {
6116 		tag_value = __btf_name_by_offset(btf, t->name_off);
6117 		if (strcmp(tag_value, "user") == 0)
6118 			info->reg_type |= MEM_USER;
6119 		if (strcmp(tag_value, "percpu") == 0)
6120 			info->reg_type |= MEM_PERCPU;
6121 	}
6122 
6123 	/* skip modifiers */
6124 	while (btf_type_is_modifier(t)) {
6125 		info->btf_id = t->type;
6126 		t = btf_type_by_id(btf, t->type);
6127 	}
6128 	if (!btf_type_is_struct(t)) {
6129 		bpf_log(log,
6130 			"func '%s' arg%d type %s is not a struct\n",
6131 			tname, arg, btf_type_str(t));
6132 		return false;
6133 	}
6134 	bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6135 		tname, arg, info->btf_id, btf_type_str(t),
6136 		__btf_name_by_offset(btf, t->name_off));
6137 	return true;
6138 }
6139 
6140 enum bpf_struct_walk_result {
6141 	/* < 0 error */
6142 	WALK_SCALAR = 0,
6143 	WALK_PTR,
6144 	WALK_STRUCT,
6145 };
6146 
6147 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6148 			   const struct btf_type *t, int off, int size,
6149 			   u32 *next_btf_id, enum bpf_type_flag *flag)
6150 {
6151 	u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6152 	const struct btf_type *mtype, *elem_type = NULL;
6153 	const struct btf_member *member;
6154 	const char *tname, *mname, *tag_value;
6155 	u32 vlen, elem_id, mid;
6156 
6157 again:
6158 	tname = __btf_name_by_offset(btf, t->name_off);
6159 	if (!btf_type_is_struct(t)) {
6160 		bpf_log(log, "Type '%s' is not a struct\n", tname);
6161 		return -EINVAL;
6162 	}
6163 
6164 	vlen = btf_type_vlen(t);
6165 	if (off + size > t->size) {
6166 		/* If the last element is a variable size array, we may
6167 		 * need to relax the rule.
6168 		 */
6169 		struct btf_array *array_elem;
6170 
6171 		if (vlen == 0)
6172 			goto error;
6173 
6174 		member = btf_type_member(t) + vlen - 1;
6175 		mtype = btf_type_skip_modifiers(btf, member->type,
6176 						NULL);
6177 		if (!btf_type_is_array(mtype))
6178 			goto error;
6179 
6180 		array_elem = (struct btf_array *)(mtype + 1);
6181 		if (array_elem->nelems != 0)
6182 			goto error;
6183 
6184 		moff = __btf_member_bit_offset(t, member) / 8;
6185 		if (off < moff)
6186 			goto error;
6187 
6188 		/* Only allow structure for now, can be relaxed for
6189 		 * other types later.
6190 		 */
6191 		t = btf_type_skip_modifiers(btf, array_elem->type,
6192 					    NULL);
6193 		if (!btf_type_is_struct(t))
6194 			goto error;
6195 
6196 		off = (off - moff) % t->size;
6197 		goto again;
6198 
6199 error:
6200 		bpf_log(log, "access beyond struct %s at off %u size %u\n",
6201 			tname, off, size);
6202 		return -EACCES;
6203 	}
6204 
6205 	for_each_member(i, t, member) {
6206 		/* offset of the field in bytes */
6207 		moff = __btf_member_bit_offset(t, member) / 8;
6208 		if (off + size <= moff)
6209 			/* won't find anything, field is already too far */
6210 			break;
6211 
6212 		if (__btf_member_bitfield_size(t, member)) {
6213 			u32 end_bit = __btf_member_bit_offset(t, member) +
6214 				__btf_member_bitfield_size(t, member);
6215 
6216 			/* off <= moff instead of off == moff because clang
6217 			 * does not generate a BTF member for anonymous
6218 			 * bitfield like the ":16" here:
6219 			 * struct {
6220 			 *	int :16;
6221 			 *	int x:8;
6222 			 * };
6223 			 */
6224 			if (off <= moff &&
6225 			    BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6226 				return WALK_SCALAR;
6227 
6228 			/* off may be accessing a following member
6229 			 *
6230 			 * or
6231 			 *
6232 			 * Doing partial access at either end of this
6233 			 * bitfield.  Continue on this case also to
6234 			 * treat it as not accessing this bitfield
6235 			 * and eventually error out as field not
6236 			 * found to keep it simple.
6237 			 * It could be relaxed if there was a legit
6238 			 * partial access case later.
6239 			 */
6240 			continue;
6241 		}
6242 
6243 		/* In case of "off" is pointing to holes of a struct */
6244 		if (off < moff)
6245 			break;
6246 
6247 		/* type of the field */
6248 		mid = member->type;
6249 		mtype = btf_type_by_id(btf, member->type);
6250 		mname = __btf_name_by_offset(btf, member->name_off);
6251 
6252 		mtype = __btf_resolve_size(btf, mtype, &msize,
6253 					   &elem_type, &elem_id, &total_nelems,
6254 					   &mid);
6255 		if (IS_ERR(mtype)) {
6256 			bpf_log(log, "field %s doesn't have size\n", mname);
6257 			return -EFAULT;
6258 		}
6259 
6260 		mtrue_end = moff + msize;
6261 		if (off >= mtrue_end)
6262 			/* no overlap with member, keep iterating */
6263 			continue;
6264 
6265 		if (btf_type_is_array(mtype)) {
6266 			u32 elem_idx;
6267 
6268 			/* __btf_resolve_size() above helps to
6269 			 * linearize a multi-dimensional array.
6270 			 *
6271 			 * The logic here is treating an array
6272 			 * in a struct as the following way:
6273 			 *
6274 			 * struct outer {
6275 			 *	struct inner array[2][2];
6276 			 * };
6277 			 *
6278 			 * looks like:
6279 			 *
6280 			 * struct outer {
6281 			 *	struct inner array_elem0;
6282 			 *	struct inner array_elem1;
6283 			 *	struct inner array_elem2;
6284 			 *	struct inner array_elem3;
6285 			 * };
6286 			 *
6287 			 * When accessing outer->array[1][0], it moves
6288 			 * moff to "array_elem2", set mtype to
6289 			 * "struct inner", and msize also becomes
6290 			 * sizeof(struct inner).  Then most of the
6291 			 * remaining logic will fall through without
6292 			 * caring the current member is an array or
6293 			 * not.
6294 			 *
6295 			 * Unlike mtype/msize/moff, mtrue_end does not
6296 			 * change.  The naming difference ("_true") tells
6297 			 * that it is not always corresponding to
6298 			 * the current mtype/msize/moff.
6299 			 * It is the true end of the current
6300 			 * member (i.e. array in this case).  That
6301 			 * will allow an int array to be accessed like
6302 			 * a scratch space,
6303 			 * i.e. allow access beyond the size of
6304 			 *      the array's element as long as it is
6305 			 *      within the mtrue_end boundary.
6306 			 */
6307 
6308 			/* skip empty array */
6309 			if (moff == mtrue_end)
6310 				continue;
6311 
6312 			msize /= total_nelems;
6313 			elem_idx = (off - moff) / msize;
6314 			moff += elem_idx * msize;
6315 			mtype = elem_type;
6316 			mid = elem_id;
6317 		}
6318 
6319 		/* the 'off' we're looking for is either equal to start
6320 		 * of this field or inside of this struct
6321 		 */
6322 		if (btf_type_is_struct(mtype)) {
6323 			/* our field must be inside that union or struct */
6324 			t = mtype;
6325 
6326 			/* return if the offset matches the member offset */
6327 			if (off == moff) {
6328 				*next_btf_id = mid;
6329 				return WALK_STRUCT;
6330 			}
6331 
6332 			/* adjust offset we're looking for */
6333 			off -= moff;
6334 			goto again;
6335 		}
6336 
6337 		if (btf_type_is_ptr(mtype)) {
6338 			const struct btf_type *stype, *t;
6339 			enum bpf_type_flag tmp_flag = 0;
6340 			u32 id;
6341 
6342 			if (msize != size || off != moff) {
6343 				bpf_log(log,
6344 					"cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6345 					mname, moff, tname, off, size);
6346 				return -EACCES;
6347 			}
6348 
6349 			/* check type tag */
6350 			t = btf_type_by_id(btf, mtype->type);
6351 			if (btf_type_is_type_tag(t)) {
6352 				tag_value = __btf_name_by_offset(btf, t->name_off);
6353 				/* check __user tag */
6354 				if (strcmp(tag_value, "user") == 0)
6355 					tmp_flag = MEM_USER;
6356 				/* check __percpu tag */
6357 				if (strcmp(tag_value, "percpu") == 0)
6358 					tmp_flag = MEM_PERCPU;
6359 				/* check __rcu tag */
6360 				if (strcmp(tag_value, "rcu") == 0)
6361 					tmp_flag = MEM_RCU;
6362 			}
6363 
6364 			stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6365 			if (btf_type_is_struct(stype)) {
6366 				*next_btf_id = id;
6367 				*flag = tmp_flag;
6368 				return WALK_PTR;
6369 			}
6370 		}
6371 
6372 		/* Allow more flexible access within an int as long as
6373 		 * it is within mtrue_end.
6374 		 * Since mtrue_end could be the end of an array,
6375 		 * that also allows using an array of int as a scratch
6376 		 * space. e.g. skb->cb[].
6377 		 */
6378 		if (off + size > mtrue_end) {
6379 			bpf_log(log,
6380 				"access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6381 				mname, mtrue_end, tname, off, size);
6382 			return -EACCES;
6383 		}
6384 
6385 		return WALK_SCALAR;
6386 	}
6387 	bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6388 	return -EINVAL;
6389 }
6390 
6391 int btf_struct_access(struct bpf_verifier_log *log,
6392 		      const struct bpf_reg_state *reg,
6393 		      int off, int size, enum bpf_access_type atype __maybe_unused,
6394 		      u32 *next_btf_id, enum bpf_type_flag *flag)
6395 {
6396 	const struct btf *btf = reg->btf;
6397 	enum bpf_type_flag tmp_flag = 0;
6398 	const struct btf_type *t;
6399 	u32 id = reg->btf_id;
6400 	int err;
6401 
6402 	while (type_is_alloc(reg->type)) {
6403 		struct btf_struct_meta *meta;
6404 		struct btf_record *rec;
6405 		int i;
6406 
6407 		meta = btf_find_struct_meta(btf, id);
6408 		if (!meta)
6409 			break;
6410 		rec = meta->record;
6411 		for (i = 0; i < rec->cnt; i++) {
6412 			struct btf_field *field = &rec->fields[i];
6413 			u32 offset = field->offset;
6414 			if (off < offset + btf_field_type_size(field->type) && offset < off + size) {
6415 				bpf_log(log,
6416 					"direct access to %s is disallowed\n",
6417 					btf_field_type_name(field->type));
6418 				return -EACCES;
6419 			}
6420 		}
6421 		break;
6422 	}
6423 
6424 	t = btf_type_by_id(btf, id);
6425 	do {
6426 		err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag);
6427 
6428 		switch (err) {
6429 		case WALK_PTR:
6430 			/* For local types, the destination register cannot
6431 			 * become a pointer again.
6432 			 */
6433 			if (type_is_alloc(reg->type))
6434 				return SCALAR_VALUE;
6435 			/* If we found the pointer or scalar on t+off,
6436 			 * we're done.
6437 			 */
6438 			*next_btf_id = id;
6439 			*flag = tmp_flag;
6440 			return PTR_TO_BTF_ID;
6441 		case WALK_SCALAR:
6442 			return SCALAR_VALUE;
6443 		case WALK_STRUCT:
6444 			/* We found nested struct, so continue the search
6445 			 * by diving in it. At this point the offset is
6446 			 * aligned with the new type, so set it to 0.
6447 			 */
6448 			t = btf_type_by_id(btf, id);
6449 			off = 0;
6450 			break;
6451 		default:
6452 			/* It's either error or unknown return value..
6453 			 * scream and leave.
6454 			 */
6455 			if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6456 				return -EINVAL;
6457 			return err;
6458 		}
6459 	} while (t);
6460 
6461 	return -EINVAL;
6462 }
6463 
6464 /* Check that two BTF types, each specified as an BTF object + id, are exactly
6465  * the same. Trivial ID check is not enough due to module BTFs, because we can
6466  * end up with two different module BTFs, but IDs point to the common type in
6467  * vmlinux BTF.
6468  */
6469 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6470 			const struct btf *btf2, u32 id2)
6471 {
6472 	if (id1 != id2)
6473 		return false;
6474 	if (btf1 == btf2)
6475 		return true;
6476 	return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6477 }
6478 
6479 bool btf_struct_ids_match(struct bpf_verifier_log *log,
6480 			  const struct btf *btf, u32 id, int off,
6481 			  const struct btf *need_btf, u32 need_type_id,
6482 			  bool strict)
6483 {
6484 	const struct btf_type *type;
6485 	enum bpf_type_flag flag;
6486 	int err;
6487 
6488 	/* Are we already done? */
6489 	if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6490 		return true;
6491 	/* In case of strict type match, we do not walk struct, the top level
6492 	 * type match must succeed. When strict is true, off should have already
6493 	 * been 0.
6494 	 */
6495 	if (strict)
6496 		return false;
6497 again:
6498 	type = btf_type_by_id(btf, id);
6499 	if (!type)
6500 		return false;
6501 	err = btf_struct_walk(log, btf, type, off, 1, &id, &flag);
6502 	if (err != WALK_STRUCT)
6503 		return false;
6504 
6505 	/* We found nested struct object. If it matches
6506 	 * the requested ID, we're done. Otherwise let's
6507 	 * continue the search with offset 0 in the new
6508 	 * type.
6509 	 */
6510 	if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6511 		off = 0;
6512 		goto again;
6513 	}
6514 
6515 	return true;
6516 }
6517 
6518 static int __get_type_size(struct btf *btf, u32 btf_id,
6519 			   const struct btf_type **ret_type)
6520 {
6521 	const struct btf_type *t;
6522 
6523 	*ret_type = btf_type_by_id(btf, 0);
6524 	if (!btf_id)
6525 		/* void */
6526 		return 0;
6527 	t = btf_type_by_id(btf, btf_id);
6528 	while (t && btf_type_is_modifier(t))
6529 		t = btf_type_by_id(btf, t->type);
6530 	if (!t)
6531 		return -EINVAL;
6532 	*ret_type = t;
6533 	if (btf_type_is_ptr(t))
6534 		/* kernel size of pointer. Not BPF's size of pointer*/
6535 		return sizeof(void *);
6536 	if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6537 		return t->size;
6538 	return -EINVAL;
6539 }
6540 
6541 static u8 __get_type_fmodel_flags(const struct btf_type *t)
6542 {
6543 	u8 flags = 0;
6544 
6545 	if (__btf_type_is_struct(t))
6546 		flags |= BTF_FMODEL_STRUCT_ARG;
6547 	if (btf_type_is_signed_int(t))
6548 		flags |= BTF_FMODEL_SIGNED_ARG;
6549 
6550 	return flags;
6551 }
6552 
6553 int btf_distill_func_proto(struct bpf_verifier_log *log,
6554 			   struct btf *btf,
6555 			   const struct btf_type *func,
6556 			   const char *tname,
6557 			   struct btf_func_model *m)
6558 {
6559 	const struct btf_param *args;
6560 	const struct btf_type *t;
6561 	u32 i, nargs;
6562 	int ret;
6563 
6564 	if (!func) {
6565 		/* BTF function prototype doesn't match the verifier types.
6566 		 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
6567 		 */
6568 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6569 			m->arg_size[i] = 8;
6570 			m->arg_flags[i] = 0;
6571 		}
6572 		m->ret_size = 8;
6573 		m->ret_flags = 0;
6574 		m->nr_args = MAX_BPF_FUNC_REG_ARGS;
6575 		return 0;
6576 	}
6577 	args = (const struct btf_param *)(func + 1);
6578 	nargs = btf_type_vlen(func);
6579 	if (nargs > MAX_BPF_FUNC_ARGS) {
6580 		bpf_log(log,
6581 			"The function %s has %d arguments. Too many.\n",
6582 			tname, nargs);
6583 		return -EINVAL;
6584 	}
6585 	ret = __get_type_size(btf, func->type, &t);
6586 	if (ret < 0 || __btf_type_is_struct(t)) {
6587 		bpf_log(log,
6588 			"The function %s return type %s is unsupported.\n",
6589 			tname, btf_type_str(t));
6590 		return -EINVAL;
6591 	}
6592 	m->ret_size = ret;
6593 	m->ret_flags = __get_type_fmodel_flags(t);
6594 
6595 	for (i = 0; i < nargs; i++) {
6596 		if (i == nargs - 1 && args[i].type == 0) {
6597 			bpf_log(log,
6598 				"The function %s with variable args is unsupported.\n",
6599 				tname);
6600 			return -EINVAL;
6601 		}
6602 		ret = __get_type_size(btf, args[i].type, &t);
6603 
6604 		/* No support of struct argument size greater than 16 bytes */
6605 		if (ret < 0 || ret > 16) {
6606 			bpf_log(log,
6607 				"The function %s arg%d type %s is unsupported.\n",
6608 				tname, i, btf_type_str(t));
6609 			return -EINVAL;
6610 		}
6611 		if (ret == 0) {
6612 			bpf_log(log,
6613 				"The function %s has malformed void argument.\n",
6614 				tname);
6615 			return -EINVAL;
6616 		}
6617 		m->arg_size[i] = ret;
6618 		m->arg_flags[i] = __get_type_fmodel_flags(t);
6619 	}
6620 	m->nr_args = nargs;
6621 	return 0;
6622 }
6623 
6624 /* Compare BTFs of two functions assuming only scalars and pointers to context.
6625  * t1 points to BTF_KIND_FUNC in btf1
6626  * t2 points to BTF_KIND_FUNC in btf2
6627  * Returns:
6628  * EINVAL - function prototype mismatch
6629  * EFAULT - verifier bug
6630  * 0 - 99% match. The last 1% is validated by the verifier.
6631  */
6632 static int btf_check_func_type_match(struct bpf_verifier_log *log,
6633 				     struct btf *btf1, const struct btf_type *t1,
6634 				     struct btf *btf2, const struct btf_type *t2)
6635 {
6636 	const struct btf_param *args1, *args2;
6637 	const char *fn1, *fn2, *s1, *s2;
6638 	u32 nargs1, nargs2, i;
6639 
6640 	fn1 = btf_name_by_offset(btf1, t1->name_off);
6641 	fn2 = btf_name_by_offset(btf2, t2->name_off);
6642 
6643 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
6644 		bpf_log(log, "%s() is not a global function\n", fn1);
6645 		return -EINVAL;
6646 	}
6647 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
6648 		bpf_log(log, "%s() is not a global function\n", fn2);
6649 		return -EINVAL;
6650 	}
6651 
6652 	t1 = btf_type_by_id(btf1, t1->type);
6653 	if (!t1 || !btf_type_is_func_proto(t1))
6654 		return -EFAULT;
6655 	t2 = btf_type_by_id(btf2, t2->type);
6656 	if (!t2 || !btf_type_is_func_proto(t2))
6657 		return -EFAULT;
6658 
6659 	args1 = (const struct btf_param *)(t1 + 1);
6660 	nargs1 = btf_type_vlen(t1);
6661 	args2 = (const struct btf_param *)(t2 + 1);
6662 	nargs2 = btf_type_vlen(t2);
6663 
6664 	if (nargs1 != nargs2) {
6665 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
6666 			fn1, nargs1, fn2, nargs2);
6667 		return -EINVAL;
6668 	}
6669 
6670 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6671 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6672 	if (t1->info != t2->info) {
6673 		bpf_log(log,
6674 			"Return type %s of %s() doesn't match type %s of %s()\n",
6675 			btf_type_str(t1), fn1,
6676 			btf_type_str(t2), fn2);
6677 		return -EINVAL;
6678 	}
6679 
6680 	for (i = 0; i < nargs1; i++) {
6681 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
6682 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
6683 
6684 		if (t1->info != t2->info) {
6685 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
6686 				i, fn1, btf_type_str(t1),
6687 				fn2, btf_type_str(t2));
6688 			return -EINVAL;
6689 		}
6690 		if (btf_type_has_size(t1) && t1->size != t2->size) {
6691 			bpf_log(log,
6692 				"arg%d in %s() has size %d while %s() has %d\n",
6693 				i, fn1, t1->size,
6694 				fn2, t2->size);
6695 			return -EINVAL;
6696 		}
6697 
6698 		/* global functions are validated with scalars and pointers
6699 		 * to context only. And only global functions can be replaced.
6700 		 * Hence type check only those types.
6701 		 */
6702 		if (btf_type_is_int(t1) || btf_is_any_enum(t1))
6703 			continue;
6704 		if (!btf_type_is_ptr(t1)) {
6705 			bpf_log(log,
6706 				"arg%d in %s() has unrecognized type\n",
6707 				i, fn1);
6708 			return -EINVAL;
6709 		}
6710 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
6711 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
6712 		if (!btf_type_is_struct(t1)) {
6713 			bpf_log(log,
6714 				"arg%d in %s() is not a pointer to context\n",
6715 				i, fn1);
6716 			return -EINVAL;
6717 		}
6718 		if (!btf_type_is_struct(t2)) {
6719 			bpf_log(log,
6720 				"arg%d in %s() is not a pointer to context\n",
6721 				i, fn2);
6722 			return -EINVAL;
6723 		}
6724 		/* This is an optional check to make program writing easier.
6725 		 * Compare names of structs and report an error to the user.
6726 		 * btf_prepare_func_args() already checked that t2 struct
6727 		 * is a context type. btf_prepare_func_args() will check
6728 		 * later that t1 struct is a context type as well.
6729 		 */
6730 		s1 = btf_name_by_offset(btf1, t1->name_off);
6731 		s2 = btf_name_by_offset(btf2, t2->name_off);
6732 		if (strcmp(s1, s2)) {
6733 			bpf_log(log,
6734 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
6735 				i, fn1, s1, fn2, s2);
6736 			return -EINVAL;
6737 		}
6738 	}
6739 	return 0;
6740 }
6741 
6742 /* Compare BTFs of given program with BTF of target program */
6743 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
6744 			 struct btf *btf2, const struct btf_type *t2)
6745 {
6746 	struct btf *btf1 = prog->aux->btf;
6747 	const struct btf_type *t1;
6748 	u32 btf_id = 0;
6749 
6750 	if (!prog->aux->func_info) {
6751 		bpf_log(log, "Program extension requires BTF\n");
6752 		return -EINVAL;
6753 	}
6754 
6755 	btf_id = prog->aux->func_info[0].type_id;
6756 	if (!btf_id)
6757 		return -EFAULT;
6758 
6759 	t1 = btf_type_by_id(btf1, btf_id);
6760 	if (!t1 || !btf_type_is_func(t1))
6761 		return -EFAULT;
6762 
6763 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
6764 }
6765 
6766 static int btf_check_func_arg_match(struct bpf_verifier_env *env,
6767 				    const struct btf *btf, u32 func_id,
6768 				    struct bpf_reg_state *regs,
6769 				    bool ptr_to_mem_ok,
6770 				    bool processing_call)
6771 {
6772 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
6773 	struct bpf_verifier_log *log = &env->log;
6774 	const char *func_name, *ref_tname;
6775 	const struct btf_type *t, *ref_t;
6776 	const struct btf_param *args;
6777 	u32 i, nargs, ref_id;
6778 	int ret;
6779 
6780 	t = btf_type_by_id(btf, func_id);
6781 	if (!t || !btf_type_is_func(t)) {
6782 		/* These checks were already done by the verifier while loading
6783 		 * struct bpf_func_info or in add_kfunc_call().
6784 		 */
6785 		bpf_log(log, "BTF of func_id %u doesn't point to KIND_FUNC\n",
6786 			func_id);
6787 		return -EFAULT;
6788 	}
6789 	func_name = btf_name_by_offset(btf, t->name_off);
6790 
6791 	t = btf_type_by_id(btf, t->type);
6792 	if (!t || !btf_type_is_func_proto(t)) {
6793 		bpf_log(log, "Invalid BTF of func %s\n", func_name);
6794 		return -EFAULT;
6795 	}
6796 	args = (const struct btf_param *)(t + 1);
6797 	nargs = btf_type_vlen(t);
6798 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
6799 		bpf_log(log, "Function %s has %d > %d args\n", func_name, nargs,
6800 			MAX_BPF_FUNC_REG_ARGS);
6801 		return -EINVAL;
6802 	}
6803 
6804 	/* check that BTF function arguments match actual types that the
6805 	 * verifier sees.
6806 	 */
6807 	for (i = 0; i < nargs; i++) {
6808 		enum bpf_arg_type arg_type = ARG_DONTCARE;
6809 		u32 regno = i + 1;
6810 		struct bpf_reg_state *reg = &regs[regno];
6811 
6812 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6813 		if (btf_type_is_scalar(t)) {
6814 			if (reg->type == SCALAR_VALUE)
6815 				continue;
6816 			bpf_log(log, "R%d is not a scalar\n", regno);
6817 			return -EINVAL;
6818 		}
6819 
6820 		if (!btf_type_is_ptr(t)) {
6821 			bpf_log(log, "Unrecognized arg#%d type %s\n",
6822 				i, btf_type_str(t));
6823 			return -EINVAL;
6824 		}
6825 
6826 		ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id);
6827 		ref_tname = btf_name_by_offset(btf, ref_t->name_off);
6828 
6829 		ret = check_func_arg_reg_off(env, reg, regno, arg_type);
6830 		if (ret < 0)
6831 			return ret;
6832 
6833 		if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
6834 			/* If function expects ctx type in BTF check that caller
6835 			 * is passing PTR_TO_CTX.
6836 			 */
6837 			if (reg->type != PTR_TO_CTX) {
6838 				bpf_log(log,
6839 					"arg#%d expected pointer to ctx, but got %s\n",
6840 					i, btf_type_str(t));
6841 				return -EINVAL;
6842 			}
6843 		} else if (ptr_to_mem_ok && processing_call) {
6844 			const struct btf_type *resolve_ret;
6845 			u32 type_size;
6846 
6847 			resolve_ret = btf_resolve_size(btf, ref_t, &type_size);
6848 			if (IS_ERR(resolve_ret)) {
6849 				bpf_log(log,
6850 					"arg#%d reference type('%s %s') size cannot be determined: %ld\n",
6851 					i, btf_type_str(ref_t), ref_tname,
6852 					PTR_ERR(resolve_ret));
6853 				return -EINVAL;
6854 			}
6855 
6856 			if (check_mem_reg(env, reg, regno, type_size))
6857 				return -EINVAL;
6858 		} else {
6859 			bpf_log(log, "reg type unsupported for arg#%d function %s#%d\n", i,
6860 				func_name, func_id);
6861 			return -EINVAL;
6862 		}
6863 	}
6864 
6865 	return 0;
6866 }
6867 
6868 /* Compare BTF of a function declaration with given bpf_reg_state.
6869  * Returns:
6870  * EFAULT - there is a verifier bug. Abort verification.
6871  * EINVAL - there is a type mismatch or BTF is not available.
6872  * 0 - BTF matches with what bpf_reg_state expects.
6873  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6874  */
6875 int btf_check_subprog_arg_match(struct bpf_verifier_env *env, int subprog,
6876 				struct bpf_reg_state *regs)
6877 {
6878 	struct bpf_prog *prog = env->prog;
6879 	struct btf *btf = prog->aux->btf;
6880 	bool is_global;
6881 	u32 btf_id;
6882 	int err;
6883 
6884 	if (!prog->aux->func_info)
6885 		return -EINVAL;
6886 
6887 	btf_id = prog->aux->func_info[subprog].type_id;
6888 	if (!btf_id)
6889 		return -EFAULT;
6890 
6891 	if (prog->aux->func_info_aux[subprog].unreliable)
6892 		return -EINVAL;
6893 
6894 	is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6895 	err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, false);
6896 
6897 	/* Compiler optimizations can remove arguments from static functions
6898 	 * or mismatched type can be passed into a global function.
6899 	 * In such cases mark the function as unreliable from BTF point of view.
6900 	 */
6901 	if (err)
6902 		prog->aux->func_info_aux[subprog].unreliable = true;
6903 	return err;
6904 }
6905 
6906 /* Compare BTF of a function call with given bpf_reg_state.
6907  * Returns:
6908  * EFAULT - there is a verifier bug. Abort verification.
6909  * EINVAL - there is a type mismatch or BTF is not available.
6910  * 0 - BTF matches with what bpf_reg_state expects.
6911  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
6912  *
6913  * NOTE: the code is duplicated from btf_check_subprog_arg_match()
6914  * because btf_check_func_arg_match() is still doing both. Once that
6915  * function is split in 2, we can call from here btf_check_subprog_arg_match()
6916  * first, and then treat the calling part in a new code path.
6917  */
6918 int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog,
6919 			   struct bpf_reg_state *regs)
6920 {
6921 	struct bpf_prog *prog = env->prog;
6922 	struct btf *btf = prog->aux->btf;
6923 	bool is_global;
6924 	u32 btf_id;
6925 	int err;
6926 
6927 	if (!prog->aux->func_info)
6928 		return -EINVAL;
6929 
6930 	btf_id = prog->aux->func_info[subprog].type_id;
6931 	if (!btf_id)
6932 		return -EFAULT;
6933 
6934 	if (prog->aux->func_info_aux[subprog].unreliable)
6935 		return -EINVAL;
6936 
6937 	is_global = prog->aux->func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL;
6938 	err = btf_check_func_arg_match(env, btf, btf_id, regs, is_global, true);
6939 
6940 	/* Compiler optimizations can remove arguments from static functions
6941 	 * or mismatched type can be passed into a global function.
6942 	 * In such cases mark the function as unreliable from BTF point of view.
6943 	 */
6944 	if (err)
6945 		prog->aux->func_info_aux[subprog].unreliable = true;
6946 	return err;
6947 }
6948 
6949 /* Convert BTF of a function into bpf_reg_state if possible
6950  * Returns:
6951  * EFAULT - there is a verifier bug. Abort verification.
6952  * EINVAL - cannot convert BTF.
6953  * 0 - Successfully converted BTF into bpf_reg_state
6954  * (either PTR_TO_CTX or SCALAR_VALUE).
6955  */
6956 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
6957 			  struct bpf_reg_state *regs)
6958 {
6959 	struct bpf_verifier_log *log = &env->log;
6960 	struct bpf_prog *prog = env->prog;
6961 	enum bpf_prog_type prog_type = prog->type;
6962 	struct btf *btf = prog->aux->btf;
6963 	const struct btf_param *args;
6964 	const struct btf_type *t, *ref_t;
6965 	u32 i, nargs, btf_id;
6966 	const char *tname;
6967 
6968 	if (!prog->aux->func_info ||
6969 	    prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
6970 		bpf_log(log, "Verifier bug\n");
6971 		return -EFAULT;
6972 	}
6973 
6974 	btf_id = prog->aux->func_info[subprog].type_id;
6975 	if (!btf_id) {
6976 		bpf_log(log, "Global functions need valid BTF\n");
6977 		return -EFAULT;
6978 	}
6979 
6980 	t = btf_type_by_id(btf, btf_id);
6981 	if (!t || !btf_type_is_func(t)) {
6982 		/* These checks were already done by the verifier while loading
6983 		 * struct bpf_func_info
6984 		 */
6985 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
6986 			subprog);
6987 		return -EFAULT;
6988 	}
6989 	tname = btf_name_by_offset(btf, t->name_off);
6990 
6991 	if (log->level & BPF_LOG_LEVEL)
6992 		bpf_log(log, "Validating %s() func#%d...\n",
6993 			tname, subprog);
6994 
6995 	if (prog->aux->func_info_aux[subprog].unreliable) {
6996 		bpf_log(log, "Verifier bug in function %s()\n", tname);
6997 		return -EFAULT;
6998 	}
6999 	if (prog_type == BPF_PROG_TYPE_EXT)
7000 		prog_type = prog->aux->dst_prog->type;
7001 
7002 	t = btf_type_by_id(btf, t->type);
7003 	if (!t || !btf_type_is_func_proto(t)) {
7004 		bpf_log(log, "Invalid type of function %s()\n", tname);
7005 		return -EFAULT;
7006 	}
7007 	args = (const struct btf_param *)(t + 1);
7008 	nargs = btf_type_vlen(t);
7009 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7010 		bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7011 			tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7012 		return -EINVAL;
7013 	}
7014 	/* check that function returns int */
7015 	t = btf_type_by_id(btf, t->type);
7016 	while (btf_type_is_modifier(t))
7017 		t = btf_type_by_id(btf, t->type);
7018 	if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7019 		bpf_log(log,
7020 			"Global function %s() doesn't return scalar. Only those are supported.\n",
7021 			tname);
7022 		return -EINVAL;
7023 	}
7024 	/* Convert BTF function arguments into verifier types.
7025 	 * Only PTR_TO_CTX and SCALAR are supported atm.
7026 	 */
7027 	for (i = 0; i < nargs; i++) {
7028 		struct bpf_reg_state *reg = &regs[i + 1];
7029 
7030 		t = btf_type_by_id(btf, args[i].type);
7031 		while (btf_type_is_modifier(t))
7032 			t = btf_type_by_id(btf, t->type);
7033 		if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7034 			reg->type = SCALAR_VALUE;
7035 			continue;
7036 		}
7037 		if (btf_type_is_ptr(t)) {
7038 			if (btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
7039 				reg->type = PTR_TO_CTX;
7040 				continue;
7041 			}
7042 
7043 			t = btf_type_skip_modifiers(btf, t->type, NULL);
7044 
7045 			ref_t = btf_resolve_size(btf, t, &reg->mem_size);
7046 			if (IS_ERR(ref_t)) {
7047 				bpf_log(log,
7048 				    "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7049 				    i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
7050 					PTR_ERR(ref_t));
7051 				return -EINVAL;
7052 			}
7053 
7054 			reg->type = PTR_TO_MEM | PTR_MAYBE_NULL;
7055 			reg->id = ++env->id_gen;
7056 
7057 			continue;
7058 		}
7059 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7060 			i, btf_type_str(t), tname);
7061 		return -EINVAL;
7062 	}
7063 	return 0;
7064 }
7065 
7066 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7067 			  struct btf_show *show)
7068 {
7069 	const struct btf_type *t = btf_type_by_id(btf, type_id);
7070 
7071 	show->btf = btf;
7072 	memset(&show->state, 0, sizeof(show->state));
7073 	memset(&show->obj, 0, sizeof(show->obj));
7074 
7075 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7076 }
7077 
7078 static void btf_seq_show(struct btf_show *show, const char *fmt,
7079 			 va_list args)
7080 {
7081 	seq_vprintf((struct seq_file *)show->target, fmt, args);
7082 }
7083 
7084 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7085 			    void *obj, struct seq_file *m, u64 flags)
7086 {
7087 	struct btf_show sseq;
7088 
7089 	sseq.target = m;
7090 	sseq.showfn = btf_seq_show;
7091 	sseq.flags = flags;
7092 
7093 	btf_type_show(btf, type_id, obj, &sseq);
7094 
7095 	return sseq.state.status;
7096 }
7097 
7098 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7099 		       struct seq_file *m)
7100 {
7101 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
7102 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7103 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7104 }
7105 
7106 struct btf_show_snprintf {
7107 	struct btf_show show;
7108 	int len_left;		/* space left in string */
7109 	int len;		/* length we would have written */
7110 };
7111 
7112 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7113 			      va_list args)
7114 {
7115 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7116 	int len;
7117 
7118 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7119 
7120 	if (len < 0) {
7121 		ssnprintf->len_left = 0;
7122 		ssnprintf->len = len;
7123 	} else if (len >= ssnprintf->len_left) {
7124 		/* no space, drive on to get length we would have written */
7125 		ssnprintf->len_left = 0;
7126 		ssnprintf->len += len;
7127 	} else {
7128 		ssnprintf->len_left -= len;
7129 		ssnprintf->len += len;
7130 		show->target += len;
7131 	}
7132 }
7133 
7134 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7135 			   char *buf, int len, u64 flags)
7136 {
7137 	struct btf_show_snprintf ssnprintf;
7138 
7139 	ssnprintf.show.target = buf;
7140 	ssnprintf.show.flags = flags;
7141 	ssnprintf.show.showfn = btf_snprintf_show;
7142 	ssnprintf.len_left = len;
7143 	ssnprintf.len = 0;
7144 
7145 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7146 
7147 	/* If we encountered an error, return it. */
7148 	if (ssnprintf.show.state.status)
7149 		return ssnprintf.show.state.status;
7150 
7151 	/* Otherwise return length we would have written */
7152 	return ssnprintf.len;
7153 }
7154 
7155 #ifdef CONFIG_PROC_FS
7156 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7157 {
7158 	const struct btf *btf = filp->private_data;
7159 
7160 	seq_printf(m, "btf_id:\t%u\n", btf->id);
7161 }
7162 #endif
7163 
7164 static int btf_release(struct inode *inode, struct file *filp)
7165 {
7166 	btf_put(filp->private_data);
7167 	return 0;
7168 }
7169 
7170 const struct file_operations btf_fops = {
7171 #ifdef CONFIG_PROC_FS
7172 	.show_fdinfo	= bpf_btf_show_fdinfo,
7173 #endif
7174 	.release	= btf_release,
7175 };
7176 
7177 static int __btf_new_fd(struct btf *btf)
7178 {
7179 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7180 }
7181 
7182 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr)
7183 {
7184 	struct btf *btf;
7185 	int ret;
7186 
7187 	btf = btf_parse(make_bpfptr(attr->btf, uattr.is_kernel),
7188 			attr->btf_size, attr->btf_log_level,
7189 			u64_to_user_ptr(attr->btf_log_buf),
7190 			attr->btf_log_size);
7191 	if (IS_ERR(btf))
7192 		return PTR_ERR(btf);
7193 
7194 	ret = btf_alloc_id(btf);
7195 	if (ret) {
7196 		btf_free(btf);
7197 		return ret;
7198 	}
7199 
7200 	/*
7201 	 * The BTF ID is published to the userspace.
7202 	 * All BTF free must go through call_rcu() from
7203 	 * now on (i.e. free by calling btf_put()).
7204 	 */
7205 
7206 	ret = __btf_new_fd(btf);
7207 	if (ret < 0)
7208 		btf_put(btf);
7209 
7210 	return ret;
7211 }
7212 
7213 struct btf *btf_get_by_fd(int fd)
7214 {
7215 	struct btf *btf;
7216 	struct fd f;
7217 
7218 	f = fdget(fd);
7219 
7220 	if (!f.file)
7221 		return ERR_PTR(-EBADF);
7222 
7223 	if (f.file->f_op != &btf_fops) {
7224 		fdput(f);
7225 		return ERR_PTR(-EINVAL);
7226 	}
7227 
7228 	btf = f.file->private_data;
7229 	refcount_inc(&btf->refcnt);
7230 	fdput(f);
7231 
7232 	return btf;
7233 }
7234 
7235 int btf_get_info_by_fd(const struct btf *btf,
7236 		       const union bpf_attr *attr,
7237 		       union bpf_attr __user *uattr)
7238 {
7239 	struct bpf_btf_info __user *uinfo;
7240 	struct bpf_btf_info info;
7241 	u32 info_copy, btf_copy;
7242 	void __user *ubtf;
7243 	char __user *uname;
7244 	u32 uinfo_len, uname_len, name_len;
7245 	int ret = 0;
7246 
7247 	uinfo = u64_to_user_ptr(attr->info.info);
7248 	uinfo_len = attr->info.info_len;
7249 
7250 	info_copy = min_t(u32, uinfo_len, sizeof(info));
7251 	memset(&info, 0, sizeof(info));
7252 	if (copy_from_user(&info, uinfo, info_copy))
7253 		return -EFAULT;
7254 
7255 	info.id = btf->id;
7256 	ubtf = u64_to_user_ptr(info.btf);
7257 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
7258 	if (copy_to_user(ubtf, btf->data, btf_copy))
7259 		return -EFAULT;
7260 	info.btf_size = btf->data_size;
7261 
7262 	info.kernel_btf = btf->kernel_btf;
7263 
7264 	uname = u64_to_user_ptr(info.name);
7265 	uname_len = info.name_len;
7266 	if (!uname ^ !uname_len)
7267 		return -EINVAL;
7268 
7269 	name_len = strlen(btf->name);
7270 	info.name_len = name_len;
7271 
7272 	if (uname) {
7273 		if (uname_len >= name_len + 1) {
7274 			if (copy_to_user(uname, btf->name, name_len + 1))
7275 				return -EFAULT;
7276 		} else {
7277 			char zero = '\0';
7278 
7279 			if (copy_to_user(uname, btf->name, uname_len - 1))
7280 				return -EFAULT;
7281 			if (put_user(zero, uname + uname_len - 1))
7282 				return -EFAULT;
7283 			/* let user-space know about too short buffer */
7284 			ret = -ENOSPC;
7285 		}
7286 	}
7287 
7288 	if (copy_to_user(uinfo, &info, info_copy) ||
7289 	    put_user(info_copy, &uattr->info.info_len))
7290 		return -EFAULT;
7291 
7292 	return ret;
7293 }
7294 
7295 int btf_get_fd_by_id(u32 id)
7296 {
7297 	struct btf *btf;
7298 	int fd;
7299 
7300 	rcu_read_lock();
7301 	btf = idr_find(&btf_idr, id);
7302 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7303 		btf = ERR_PTR(-ENOENT);
7304 	rcu_read_unlock();
7305 
7306 	if (IS_ERR(btf))
7307 		return PTR_ERR(btf);
7308 
7309 	fd = __btf_new_fd(btf);
7310 	if (fd < 0)
7311 		btf_put(btf);
7312 
7313 	return fd;
7314 }
7315 
7316 u32 btf_obj_id(const struct btf *btf)
7317 {
7318 	return btf->id;
7319 }
7320 
7321 bool btf_is_kernel(const struct btf *btf)
7322 {
7323 	return btf->kernel_btf;
7324 }
7325 
7326 bool btf_is_module(const struct btf *btf)
7327 {
7328 	return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7329 }
7330 
7331 enum {
7332 	BTF_MODULE_F_LIVE = (1 << 0),
7333 };
7334 
7335 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7336 struct btf_module {
7337 	struct list_head list;
7338 	struct module *module;
7339 	struct btf *btf;
7340 	struct bin_attribute *sysfs_attr;
7341 	int flags;
7342 };
7343 
7344 static LIST_HEAD(btf_modules);
7345 static DEFINE_MUTEX(btf_module_mutex);
7346 
7347 static ssize_t
7348 btf_module_read(struct file *file, struct kobject *kobj,
7349 		struct bin_attribute *bin_attr,
7350 		char *buf, loff_t off, size_t len)
7351 {
7352 	const struct btf *btf = bin_attr->private;
7353 
7354 	memcpy(buf, btf->data + off, len);
7355 	return len;
7356 }
7357 
7358 static void purge_cand_cache(struct btf *btf);
7359 
7360 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7361 			     void *module)
7362 {
7363 	struct btf_module *btf_mod, *tmp;
7364 	struct module *mod = module;
7365 	struct btf *btf;
7366 	int err = 0;
7367 
7368 	if (mod->btf_data_size == 0 ||
7369 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7370 	     op != MODULE_STATE_GOING))
7371 		goto out;
7372 
7373 	switch (op) {
7374 	case MODULE_STATE_COMING:
7375 		btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7376 		if (!btf_mod) {
7377 			err = -ENOMEM;
7378 			goto out;
7379 		}
7380 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7381 		if (IS_ERR(btf)) {
7382 			kfree(btf_mod);
7383 			if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
7384 				pr_warn("failed to validate module [%s] BTF: %ld\n",
7385 					mod->name, PTR_ERR(btf));
7386 				err = PTR_ERR(btf);
7387 			} else {
7388 				pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7389 			}
7390 			goto out;
7391 		}
7392 		err = btf_alloc_id(btf);
7393 		if (err) {
7394 			btf_free(btf);
7395 			kfree(btf_mod);
7396 			goto out;
7397 		}
7398 
7399 		purge_cand_cache(NULL);
7400 		mutex_lock(&btf_module_mutex);
7401 		btf_mod->module = module;
7402 		btf_mod->btf = btf;
7403 		list_add(&btf_mod->list, &btf_modules);
7404 		mutex_unlock(&btf_module_mutex);
7405 
7406 		if (IS_ENABLED(CONFIG_SYSFS)) {
7407 			struct bin_attribute *attr;
7408 
7409 			attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7410 			if (!attr)
7411 				goto out;
7412 
7413 			sysfs_bin_attr_init(attr);
7414 			attr->attr.name = btf->name;
7415 			attr->attr.mode = 0444;
7416 			attr->size = btf->data_size;
7417 			attr->private = btf;
7418 			attr->read = btf_module_read;
7419 
7420 			err = sysfs_create_bin_file(btf_kobj, attr);
7421 			if (err) {
7422 				pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7423 					mod->name, err);
7424 				kfree(attr);
7425 				err = 0;
7426 				goto out;
7427 			}
7428 
7429 			btf_mod->sysfs_attr = attr;
7430 		}
7431 
7432 		break;
7433 	case MODULE_STATE_LIVE:
7434 		mutex_lock(&btf_module_mutex);
7435 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7436 			if (btf_mod->module != module)
7437 				continue;
7438 
7439 			btf_mod->flags |= BTF_MODULE_F_LIVE;
7440 			break;
7441 		}
7442 		mutex_unlock(&btf_module_mutex);
7443 		break;
7444 	case MODULE_STATE_GOING:
7445 		mutex_lock(&btf_module_mutex);
7446 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7447 			if (btf_mod->module != module)
7448 				continue;
7449 
7450 			list_del(&btf_mod->list);
7451 			if (btf_mod->sysfs_attr)
7452 				sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
7453 			purge_cand_cache(btf_mod->btf);
7454 			btf_put(btf_mod->btf);
7455 			kfree(btf_mod->sysfs_attr);
7456 			kfree(btf_mod);
7457 			break;
7458 		}
7459 		mutex_unlock(&btf_module_mutex);
7460 		break;
7461 	}
7462 out:
7463 	return notifier_from_errno(err);
7464 }
7465 
7466 static struct notifier_block btf_module_nb = {
7467 	.notifier_call = btf_module_notify,
7468 };
7469 
7470 static int __init btf_module_init(void)
7471 {
7472 	register_module_notifier(&btf_module_nb);
7473 	return 0;
7474 }
7475 
7476 fs_initcall(btf_module_init);
7477 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7478 
7479 struct module *btf_try_get_module(const struct btf *btf)
7480 {
7481 	struct module *res = NULL;
7482 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7483 	struct btf_module *btf_mod, *tmp;
7484 
7485 	mutex_lock(&btf_module_mutex);
7486 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7487 		if (btf_mod->btf != btf)
7488 			continue;
7489 
7490 		/* We must only consider module whose __init routine has
7491 		 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7492 		 * which is set from the notifier callback for
7493 		 * MODULE_STATE_LIVE.
7494 		 */
7495 		if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7496 			res = btf_mod->module;
7497 
7498 		break;
7499 	}
7500 	mutex_unlock(&btf_module_mutex);
7501 #endif
7502 
7503 	return res;
7504 }
7505 
7506 /* Returns struct btf corresponding to the struct module.
7507  * This function can return NULL or ERR_PTR.
7508  */
7509 static struct btf *btf_get_module_btf(const struct module *module)
7510 {
7511 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7512 	struct btf_module *btf_mod, *tmp;
7513 #endif
7514 	struct btf *btf = NULL;
7515 
7516 	if (!module) {
7517 		btf = bpf_get_btf_vmlinux();
7518 		if (!IS_ERR_OR_NULL(btf))
7519 			btf_get(btf);
7520 		return btf;
7521 	}
7522 
7523 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7524 	mutex_lock(&btf_module_mutex);
7525 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7526 		if (btf_mod->module != module)
7527 			continue;
7528 
7529 		btf_get(btf_mod->btf);
7530 		btf = btf_mod->btf;
7531 		break;
7532 	}
7533 	mutex_unlock(&btf_module_mutex);
7534 #endif
7535 
7536 	return btf;
7537 }
7538 
7539 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7540 {
7541 	struct btf *btf = NULL;
7542 	int btf_obj_fd = 0;
7543 	long ret;
7544 
7545 	if (flags)
7546 		return -EINVAL;
7547 
7548 	if (name_sz <= 1 || name[name_sz - 1])
7549 		return -EINVAL;
7550 
7551 	ret = bpf_find_btf_id(name, kind, &btf);
7552 	if (ret > 0 && btf_is_module(btf)) {
7553 		btf_obj_fd = __btf_new_fd(btf);
7554 		if (btf_obj_fd < 0) {
7555 			btf_put(btf);
7556 			return btf_obj_fd;
7557 		}
7558 		return ret | (((u64)btf_obj_fd) << 32);
7559 	}
7560 	if (ret > 0)
7561 		btf_put(btf);
7562 	return ret;
7563 }
7564 
7565 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7566 	.func		= bpf_btf_find_by_name_kind,
7567 	.gpl_only	= false,
7568 	.ret_type	= RET_INTEGER,
7569 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7570 	.arg2_type	= ARG_CONST_SIZE,
7571 	.arg3_type	= ARG_ANYTHING,
7572 	.arg4_type	= ARG_ANYTHING,
7573 };
7574 
7575 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
7576 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
7577 BTF_TRACING_TYPE_xxx
7578 #undef BTF_TRACING_TYPE
7579 
7580 /* Kernel Function (kfunc) BTF ID set registration API */
7581 
7582 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
7583 				  struct btf_id_set8 *add_set)
7584 {
7585 	bool vmlinux_set = !btf_is_module(btf);
7586 	struct btf_kfunc_set_tab *tab;
7587 	struct btf_id_set8 *set;
7588 	u32 set_cnt;
7589 	int ret;
7590 
7591 	if (hook >= BTF_KFUNC_HOOK_MAX) {
7592 		ret = -EINVAL;
7593 		goto end;
7594 	}
7595 
7596 	if (!add_set->cnt)
7597 		return 0;
7598 
7599 	tab = btf->kfunc_set_tab;
7600 	if (!tab) {
7601 		tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
7602 		if (!tab)
7603 			return -ENOMEM;
7604 		btf->kfunc_set_tab = tab;
7605 	}
7606 
7607 	set = tab->sets[hook];
7608 	/* Warn when register_btf_kfunc_id_set is called twice for the same hook
7609 	 * for module sets.
7610 	 */
7611 	if (WARN_ON_ONCE(set && !vmlinux_set)) {
7612 		ret = -EINVAL;
7613 		goto end;
7614 	}
7615 
7616 	/* We don't need to allocate, concatenate, and sort module sets, because
7617 	 * only one is allowed per hook. Hence, we can directly assign the
7618 	 * pointer and return.
7619 	 */
7620 	if (!vmlinux_set) {
7621 		tab->sets[hook] = add_set;
7622 		return 0;
7623 	}
7624 
7625 	/* In case of vmlinux sets, there may be more than one set being
7626 	 * registered per hook. To create a unified set, we allocate a new set
7627 	 * and concatenate all individual sets being registered. While each set
7628 	 * is individually sorted, they may become unsorted when concatenated,
7629 	 * hence re-sorting the final set again is required to make binary
7630 	 * searching the set using btf_id_set8_contains function work.
7631 	 */
7632 	set_cnt = set ? set->cnt : 0;
7633 
7634 	if (set_cnt > U32_MAX - add_set->cnt) {
7635 		ret = -EOVERFLOW;
7636 		goto end;
7637 	}
7638 
7639 	if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
7640 		ret = -E2BIG;
7641 		goto end;
7642 	}
7643 
7644 	/* Grow set */
7645 	set = krealloc(tab->sets[hook],
7646 		       offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
7647 		       GFP_KERNEL | __GFP_NOWARN);
7648 	if (!set) {
7649 		ret = -ENOMEM;
7650 		goto end;
7651 	}
7652 
7653 	/* For newly allocated set, initialize set->cnt to 0 */
7654 	if (!tab->sets[hook])
7655 		set->cnt = 0;
7656 	tab->sets[hook] = set;
7657 
7658 	/* Concatenate the two sets */
7659 	memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
7660 	set->cnt += add_set->cnt;
7661 
7662 	sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
7663 
7664 	return 0;
7665 end:
7666 	btf_free_kfunc_set_tab(btf);
7667 	return ret;
7668 }
7669 
7670 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
7671 					enum btf_kfunc_hook hook,
7672 					u32 kfunc_btf_id)
7673 {
7674 	struct btf_id_set8 *set;
7675 	u32 *id;
7676 
7677 	if (hook >= BTF_KFUNC_HOOK_MAX)
7678 		return NULL;
7679 	if (!btf->kfunc_set_tab)
7680 		return NULL;
7681 	set = btf->kfunc_set_tab->sets[hook];
7682 	if (!set)
7683 		return NULL;
7684 	id = btf_id_set8_contains(set, kfunc_btf_id);
7685 	if (!id)
7686 		return NULL;
7687 	/* The flags for BTF ID are located next to it */
7688 	return id + 1;
7689 }
7690 
7691 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
7692 {
7693 	switch (prog_type) {
7694 	case BPF_PROG_TYPE_UNSPEC:
7695 		return BTF_KFUNC_HOOK_COMMON;
7696 	case BPF_PROG_TYPE_XDP:
7697 		return BTF_KFUNC_HOOK_XDP;
7698 	case BPF_PROG_TYPE_SCHED_CLS:
7699 		return BTF_KFUNC_HOOK_TC;
7700 	case BPF_PROG_TYPE_STRUCT_OPS:
7701 		return BTF_KFUNC_HOOK_STRUCT_OPS;
7702 	case BPF_PROG_TYPE_TRACING:
7703 	case BPF_PROG_TYPE_LSM:
7704 		return BTF_KFUNC_HOOK_TRACING;
7705 	case BPF_PROG_TYPE_SYSCALL:
7706 		return BTF_KFUNC_HOOK_SYSCALL;
7707 	default:
7708 		return BTF_KFUNC_HOOK_MAX;
7709 	}
7710 }
7711 
7712 /* Caution:
7713  * Reference to the module (obtained using btf_try_get_module) corresponding to
7714  * the struct btf *MUST* be held when calling this function from verifier
7715  * context. This is usually true as we stash references in prog's kfunc_btf_tab;
7716  * keeping the reference for the duration of the call provides the necessary
7717  * protection for looking up a well-formed btf->kfunc_set_tab.
7718  */
7719 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
7720 			       enum bpf_prog_type prog_type,
7721 			       u32 kfunc_btf_id)
7722 {
7723 	enum btf_kfunc_hook hook;
7724 	u32 *kfunc_flags;
7725 
7726 	kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
7727 	if (kfunc_flags)
7728 		return kfunc_flags;
7729 
7730 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
7731 	return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
7732 }
7733 
7734 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id)
7735 {
7736 	return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);
7737 }
7738 
7739 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
7740 				       const struct btf_kfunc_id_set *kset)
7741 {
7742 	struct btf *btf;
7743 	int ret;
7744 
7745 	btf = btf_get_module_btf(kset->owner);
7746 	if (!btf) {
7747 		if (!kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7748 			pr_err("missing vmlinux BTF, cannot register kfuncs\n");
7749 			return -ENOENT;
7750 		}
7751 		if (kset->owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7752 			pr_err("missing module BTF, cannot register kfuncs\n");
7753 			return -ENOENT;
7754 		}
7755 		return 0;
7756 	}
7757 	if (IS_ERR(btf))
7758 		return PTR_ERR(btf);
7759 
7760 	ret = btf_populate_kfunc_set(btf, hook, kset->set);
7761 	btf_put(btf);
7762 	return ret;
7763 }
7764 
7765 /* This function must be invoked only from initcalls/module init functions */
7766 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
7767 			      const struct btf_kfunc_id_set *kset)
7768 {
7769 	enum btf_kfunc_hook hook;
7770 
7771 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
7772 	return __register_btf_kfunc_id_set(hook, kset);
7773 }
7774 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
7775 
7776 /* This function must be invoked only from initcalls/module init functions */
7777 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
7778 {
7779 	return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
7780 }
7781 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
7782 
7783 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
7784 {
7785 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
7786 	struct btf_id_dtor_kfunc *dtor;
7787 
7788 	if (!tab)
7789 		return -ENOENT;
7790 	/* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
7791 	 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
7792 	 */
7793 	BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
7794 	dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
7795 	if (!dtor)
7796 		return -ENOENT;
7797 	return dtor->kfunc_btf_id;
7798 }
7799 
7800 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
7801 {
7802 	const struct btf_type *dtor_func, *dtor_func_proto, *t;
7803 	const struct btf_param *args;
7804 	s32 dtor_btf_id;
7805 	u32 nr_args, i;
7806 
7807 	for (i = 0; i < cnt; i++) {
7808 		dtor_btf_id = dtors[i].kfunc_btf_id;
7809 
7810 		dtor_func = btf_type_by_id(btf, dtor_btf_id);
7811 		if (!dtor_func || !btf_type_is_func(dtor_func))
7812 			return -EINVAL;
7813 
7814 		dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
7815 		if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
7816 			return -EINVAL;
7817 
7818 		/* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
7819 		t = btf_type_by_id(btf, dtor_func_proto->type);
7820 		if (!t || !btf_type_is_void(t))
7821 			return -EINVAL;
7822 
7823 		nr_args = btf_type_vlen(dtor_func_proto);
7824 		if (nr_args != 1)
7825 			return -EINVAL;
7826 		args = btf_params(dtor_func_proto);
7827 		t = btf_type_by_id(btf, args[0].type);
7828 		/* Allow any pointer type, as width on targets Linux supports
7829 		 * will be same for all pointer types (i.e. sizeof(void *))
7830 		 */
7831 		if (!t || !btf_type_is_ptr(t))
7832 			return -EINVAL;
7833 	}
7834 	return 0;
7835 }
7836 
7837 /* This function must be invoked only from initcalls/module init functions */
7838 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
7839 				struct module *owner)
7840 {
7841 	struct btf_id_dtor_kfunc_tab *tab;
7842 	struct btf *btf;
7843 	u32 tab_cnt;
7844 	int ret;
7845 
7846 	btf = btf_get_module_btf(owner);
7847 	if (!btf) {
7848 		if (!owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7849 			pr_err("missing vmlinux BTF, cannot register dtor kfuncs\n");
7850 			return -ENOENT;
7851 		}
7852 		if (owner && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES)) {
7853 			pr_err("missing module BTF, cannot register dtor kfuncs\n");
7854 			return -ENOENT;
7855 		}
7856 		return 0;
7857 	}
7858 	if (IS_ERR(btf))
7859 		return PTR_ERR(btf);
7860 
7861 	if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7862 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7863 		ret = -E2BIG;
7864 		goto end;
7865 	}
7866 
7867 	/* Ensure that the prototype of dtor kfuncs being registered is sane */
7868 	ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
7869 	if (ret < 0)
7870 		goto end;
7871 
7872 	tab = btf->dtor_kfunc_tab;
7873 	/* Only one call allowed for modules */
7874 	if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
7875 		ret = -EINVAL;
7876 		goto end;
7877 	}
7878 
7879 	tab_cnt = tab ? tab->cnt : 0;
7880 	if (tab_cnt > U32_MAX - add_cnt) {
7881 		ret = -EOVERFLOW;
7882 		goto end;
7883 	}
7884 	if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
7885 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
7886 		ret = -E2BIG;
7887 		goto end;
7888 	}
7889 
7890 	tab = krealloc(btf->dtor_kfunc_tab,
7891 		       offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
7892 		       GFP_KERNEL | __GFP_NOWARN);
7893 	if (!tab) {
7894 		ret = -ENOMEM;
7895 		goto end;
7896 	}
7897 
7898 	if (!btf->dtor_kfunc_tab)
7899 		tab->cnt = 0;
7900 	btf->dtor_kfunc_tab = tab;
7901 
7902 	memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
7903 	tab->cnt += add_cnt;
7904 
7905 	sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
7906 
7907 end:
7908 	if (ret)
7909 		btf_free_dtor_kfunc_tab(btf);
7910 	btf_put(btf);
7911 	return ret;
7912 }
7913 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
7914 
7915 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
7916 
7917 /* Check local and target types for compatibility. This check is used for
7918  * type-based CO-RE relocations and follow slightly different rules than
7919  * field-based relocations. This function assumes that root types were already
7920  * checked for name match. Beyond that initial root-level name check, names
7921  * are completely ignored. Compatibility rules are as follows:
7922  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
7923  *     kind should match for local and target types (i.e., STRUCT is not
7924  *     compatible with UNION);
7925  *   - for ENUMs/ENUM64s, the size is ignored;
7926  *   - for INT, size and signedness are ignored;
7927  *   - for ARRAY, dimensionality is ignored, element types are checked for
7928  *     compatibility recursively;
7929  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
7930  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
7931  *   - FUNC_PROTOs are compatible if they have compatible signature: same
7932  *     number of input args and compatible return and argument types.
7933  * These rules are not set in stone and probably will be adjusted as we get
7934  * more experience with using BPF CO-RE relocations.
7935  */
7936 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
7937 			      const struct btf *targ_btf, __u32 targ_id)
7938 {
7939 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
7940 					   MAX_TYPES_ARE_COMPAT_DEPTH);
7941 }
7942 
7943 #define MAX_TYPES_MATCH_DEPTH 2
7944 
7945 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
7946 			 const struct btf *targ_btf, u32 targ_id)
7947 {
7948 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
7949 				      MAX_TYPES_MATCH_DEPTH);
7950 }
7951 
7952 static bool bpf_core_is_flavor_sep(const char *s)
7953 {
7954 	/* check X___Y name pattern, where X and Y are not underscores */
7955 	return s[0] != '_' &&				      /* X */
7956 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
7957 	       s[4] != '_';				      /* Y */
7958 }
7959 
7960 size_t bpf_core_essential_name_len(const char *name)
7961 {
7962 	size_t n = strlen(name);
7963 	int i;
7964 
7965 	for (i = n - 5; i >= 0; i--) {
7966 		if (bpf_core_is_flavor_sep(name + i))
7967 			return i + 1;
7968 	}
7969 	return n;
7970 }
7971 
7972 struct bpf_cand_cache {
7973 	const char *name;
7974 	u32 name_len;
7975 	u16 kind;
7976 	u16 cnt;
7977 	struct {
7978 		const struct btf *btf;
7979 		u32 id;
7980 	} cands[];
7981 };
7982 
7983 static void bpf_free_cands(struct bpf_cand_cache *cands)
7984 {
7985 	if (!cands->cnt)
7986 		/* empty candidate array was allocated on stack */
7987 		return;
7988 	kfree(cands);
7989 }
7990 
7991 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
7992 {
7993 	kfree(cands->name);
7994 	kfree(cands);
7995 }
7996 
7997 #define VMLINUX_CAND_CACHE_SIZE 31
7998 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
7999 
8000 #define MODULE_CAND_CACHE_SIZE 31
8001 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
8002 
8003 static DEFINE_MUTEX(cand_cache_mutex);
8004 
8005 static void __print_cand_cache(struct bpf_verifier_log *log,
8006 			       struct bpf_cand_cache **cache,
8007 			       int cache_size)
8008 {
8009 	struct bpf_cand_cache *cc;
8010 	int i, j;
8011 
8012 	for (i = 0; i < cache_size; i++) {
8013 		cc = cache[i];
8014 		if (!cc)
8015 			continue;
8016 		bpf_log(log, "[%d]%s(", i, cc->name);
8017 		for (j = 0; j < cc->cnt; j++) {
8018 			bpf_log(log, "%d", cc->cands[j].id);
8019 			if (j < cc->cnt - 1)
8020 				bpf_log(log, " ");
8021 		}
8022 		bpf_log(log, "), ");
8023 	}
8024 }
8025 
8026 static void print_cand_cache(struct bpf_verifier_log *log)
8027 {
8028 	mutex_lock(&cand_cache_mutex);
8029 	bpf_log(log, "vmlinux_cand_cache:");
8030 	__print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8031 	bpf_log(log, "\nmodule_cand_cache:");
8032 	__print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8033 	bpf_log(log, "\n");
8034 	mutex_unlock(&cand_cache_mutex);
8035 }
8036 
8037 static u32 hash_cands(struct bpf_cand_cache *cands)
8038 {
8039 	return jhash(cands->name, cands->name_len, 0);
8040 }
8041 
8042 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
8043 					       struct bpf_cand_cache **cache,
8044 					       int cache_size)
8045 {
8046 	struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
8047 
8048 	if (cc && cc->name_len == cands->name_len &&
8049 	    !strncmp(cc->name, cands->name, cands->name_len))
8050 		return cc;
8051 	return NULL;
8052 }
8053 
8054 static size_t sizeof_cands(int cnt)
8055 {
8056 	return offsetof(struct bpf_cand_cache, cands[cnt]);
8057 }
8058 
8059 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
8060 						  struct bpf_cand_cache **cache,
8061 						  int cache_size)
8062 {
8063 	struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
8064 
8065 	if (*cc) {
8066 		bpf_free_cands_from_cache(*cc);
8067 		*cc = NULL;
8068 	}
8069 	new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
8070 	if (!new_cands) {
8071 		bpf_free_cands(cands);
8072 		return ERR_PTR(-ENOMEM);
8073 	}
8074 	/* strdup the name, since it will stay in cache.
8075 	 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
8076 	 */
8077 	new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
8078 	bpf_free_cands(cands);
8079 	if (!new_cands->name) {
8080 		kfree(new_cands);
8081 		return ERR_PTR(-ENOMEM);
8082 	}
8083 	*cc = new_cands;
8084 	return new_cands;
8085 }
8086 
8087 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8088 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8089 			       int cache_size)
8090 {
8091 	struct bpf_cand_cache *cc;
8092 	int i, j;
8093 
8094 	for (i = 0; i < cache_size; i++) {
8095 		cc = cache[i];
8096 		if (!cc)
8097 			continue;
8098 		if (!btf) {
8099 			/* when new module is loaded purge all of module_cand_cache,
8100 			 * since new module might have candidates with the name
8101 			 * that matches cached cands.
8102 			 */
8103 			bpf_free_cands_from_cache(cc);
8104 			cache[i] = NULL;
8105 			continue;
8106 		}
8107 		/* when module is unloaded purge cache entries
8108 		 * that match module's btf
8109 		 */
8110 		for (j = 0; j < cc->cnt; j++)
8111 			if (cc->cands[j].btf == btf) {
8112 				bpf_free_cands_from_cache(cc);
8113 				cache[i] = NULL;
8114 				break;
8115 			}
8116 	}
8117 
8118 }
8119 
8120 static void purge_cand_cache(struct btf *btf)
8121 {
8122 	mutex_lock(&cand_cache_mutex);
8123 	__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8124 	mutex_unlock(&cand_cache_mutex);
8125 }
8126 #endif
8127 
8128 static struct bpf_cand_cache *
8129 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8130 		   int targ_start_id)
8131 {
8132 	struct bpf_cand_cache *new_cands;
8133 	const struct btf_type *t;
8134 	const char *targ_name;
8135 	size_t targ_essent_len;
8136 	int n, i;
8137 
8138 	n = btf_nr_types(targ_btf);
8139 	for (i = targ_start_id; i < n; i++) {
8140 		t = btf_type_by_id(targ_btf, i);
8141 		if (btf_kind(t) != cands->kind)
8142 			continue;
8143 
8144 		targ_name = btf_name_by_offset(targ_btf, t->name_off);
8145 		if (!targ_name)
8146 			continue;
8147 
8148 		/* the resched point is before strncmp to make sure that search
8149 		 * for non-existing name will have a chance to schedule().
8150 		 */
8151 		cond_resched();
8152 
8153 		if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8154 			continue;
8155 
8156 		targ_essent_len = bpf_core_essential_name_len(targ_name);
8157 		if (targ_essent_len != cands->name_len)
8158 			continue;
8159 
8160 		/* most of the time there is only one candidate for a given kind+name pair */
8161 		new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8162 		if (!new_cands) {
8163 			bpf_free_cands(cands);
8164 			return ERR_PTR(-ENOMEM);
8165 		}
8166 
8167 		memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8168 		bpf_free_cands(cands);
8169 		cands = new_cands;
8170 		cands->cands[cands->cnt].btf = targ_btf;
8171 		cands->cands[cands->cnt].id = i;
8172 		cands->cnt++;
8173 	}
8174 	return cands;
8175 }
8176 
8177 static struct bpf_cand_cache *
8178 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8179 {
8180 	struct bpf_cand_cache *cands, *cc, local_cand = {};
8181 	const struct btf *local_btf = ctx->btf;
8182 	const struct btf_type *local_type;
8183 	const struct btf *main_btf;
8184 	size_t local_essent_len;
8185 	struct btf *mod_btf;
8186 	const char *name;
8187 	int id;
8188 
8189 	main_btf = bpf_get_btf_vmlinux();
8190 	if (IS_ERR(main_btf))
8191 		return ERR_CAST(main_btf);
8192 	if (!main_btf)
8193 		return ERR_PTR(-EINVAL);
8194 
8195 	local_type = btf_type_by_id(local_btf, local_type_id);
8196 	if (!local_type)
8197 		return ERR_PTR(-EINVAL);
8198 
8199 	name = btf_name_by_offset(local_btf, local_type->name_off);
8200 	if (str_is_empty(name))
8201 		return ERR_PTR(-EINVAL);
8202 	local_essent_len = bpf_core_essential_name_len(name);
8203 
8204 	cands = &local_cand;
8205 	cands->name = name;
8206 	cands->kind = btf_kind(local_type);
8207 	cands->name_len = local_essent_len;
8208 
8209 	cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8210 	/* cands is a pointer to stack here */
8211 	if (cc) {
8212 		if (cc->cnt)
8213 			return cc;
8214 		goto check_modules;
8215 	}
8216 
8217 	/* Attempt to find target candidates in vmlinux BTF first */
8218 	cands = bpf_core_add_cands(cands, main_btf, 1);
8219 	if (IS_ERR(cands))
8220 		return ERR_CAST(cands);
8221 
8222 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8223 
8224 	/* populate cache even when cands->cnt == 0 */
8225 	cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8226 	if (IS_ERR(cc))
8227 		return ERR_CAST(cc);
8228 
8229 	/* if vmlinux BTF has any candidate, don't go for module BTFs */
8230 	if (cc->cnt)
8231 		return cc;
8232 
8233 check_modules:
8234 	/* cands is a pointer to stack here and cands->cnt == 0 */
8235 	cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8236 	if (cc)
8237 		/* if cache has it return it even if cc->cnt == 0 */
8238 		return cc;
8239 
8240 	/* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8241 	spin_lock_bh(&btf_idr_lock);
8242 	idr_for_each_entry(&btf_idr, mod_btf, id) {
8243 		if (!btf_is_module(mod_btf))
8244 			continue;
8245 		/* linear search could be slow hence unlock/lock
8246 		 * the IDR to avoiding holding it for too long
8247 		 */
8248 		btf_get(mod_btf);
8249 		spin_unlock_bh(&btf_idr_lock);
8250 		cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8251 		if (IS_ERR(cands)) {
8252 			btf_put(mod_btf);
8253 			return ERR_CAST(cands);
8254 		}
8255 		spin_lock_bh(&btf_idr_lock);
8256 		btf_put(mod_btf);
8257 	}
8258 	spin_unlock_bh(&btf_idr_lock);
8259 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0
8260 	 * or pointer to stack if cands->cnd == 0.
8261 	 * Copy it into the cache even when cands->cnt == 0 and
8262 	 * return the result.
8263 	 */
8264 	return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8265 }
8266 
8267 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8268 		   int relo_idx, void *insn)
8269 {
8270 	bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8271 	struct bpf_core_cand_list cands = {};
8272 	struct bpf_core_relo_res targ_res;
8273 	struct bpf_core_spec *specs;
8274 	int err;
8275 
8276 	/* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8277 	 * into arrays of btf_ids of struct fields and array indices.
8278 	 */
8279 	specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8280 	if (!specs)
8281 		return -ENOMEM;
8282 
8283 	if (need_cands) {
8284 		struct bpf_cand_cache *cc;
8285 		int i;
8286 
8287 		mutex_lock(&cand_cache_mutex);
8288 		cc = bpf_core_find_cands(ctx, relo->type_id);
8289 		if (IS_ERR(cc)) {
8290 			bpf_log(ctx->log, "target candidate search failed for %d\n",
8291 				relo->type_id);
8292 			err = PTR_ERR(cc);
8293 			goto out;
8294 		}
8295 		if (cc->cnt) {
8296 			cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8297 			if (!cands.cands) {
8298 				err = -ENOMEM;
8299 				goto out;
8300 			}
8301 		}
8302 		for (i = 0; i < cc->cnt; i++) {
8303 			bpf_log(ctx->log,
8304 				"CO-RE relocating %s %s: found target candidate [%d]\n",
8305 				btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8306 			cands.cands[i].btf = cc->cands[i].btf;
8307 			cands.cands[i].id = cc->cands[i].id;
8308 		}
8309 		cands.len = cc->cnt;
8310 		/* cand_cache_mutex needs to span the cache lookup and
8311 		 * copy of btf pointer into bpf_core_cand_list,
8312 		 * since module can be unloaded while bpf_core_calc_relo_insn
8313 		 * is working with module's btf.
8314 		 */
8315 	}
8316 
8317 	err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8318 				      &targ_res);
8319 	if (err)
8320 		goto out;
8321 
8322 	err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8323 				  &targ_res);
8324 
8325 out:
8326 	kfree(specs);
8327 	if (need_cands) {
8328 		kfree(cands.cands);
8329 		mutex_unlock(&cand_cache_mutex);
8330 		if (ctx->log->level & BPF_LOG_LEVEL2)
8331 			print_cand_cache(ctx->log);
8332 	}
8333 	return err;
8334 }
8335 
8336 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
8337 				const struct bpf_reg_state *reg,
8338 				int off)
8339 {
8340 	struct btf *btf = reg->btf;
8341 	const struct btf_type *walk_type, *safe_type;
8342 	const char *tname;
8343 	char safe_tname[64];
8344 	long ret, safe_id;
8345 	const struct btf_member *member, *m_walk = NULL;
8346 	u32 i;
8347 	const char *walk_name;
8348 
8349 	walk_type = btf_type_by_id(btf, reg->btf_id);
8350 	if (!walk_type)
8351 		return false;
8352 
8353 	tname = btf_name_by_offset(btf, walk_type->name_off);
8354 
8355 	ret = snprintf(safe_tname, sizeof(safe_tname), "%s__safe_fields", tname);
8356 	if (ret < 0)
8357 		return false;
8358 
8359 	safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8360 	if (safe_id < 0)
8361 		return false;
8362 
8363 	safe_type = btf_type_by_id(btf, safe_id);
8364 	if (!safe_type)
8365 		return false;
8366 
8367 	for_each_member(i, walk_type, member) {
8368 		u32 moff;
8369 
8370 		/* We're looking for the PTR_TO_BTF_ID member in the struct
8371 		 * type we're walking which matches the specified offset.
8372 		 * Below, we'll iterate over the fields in the safe variant of
8373 		 * the struct and see if any of them has a matching type /
8374 		 * name.
8375 		 */
8376 		moff = __btf_member_bit_offset(walk_type, member) / 8;
8377 		if (off == moff) {
8378 			m_walk = member;
8379 			break;
8380 		}
8381 	}
8382 	if (m_walk == NULL)
8383 		return false;
8384 
8385 	walk_name = __btf_name_by_offset(btf, m_walk->name_off);
8386 	for_each_member(i, safe_type, member) {
8387 		const char *m_name = __btf_name_by_offset(btf, member->name_off);
8388 
8389 		/* If we match on both type and name, the field is considered trusted. */
8390 		if (m_walk->type == member->type && !strcmp(walk_name, m_name))
8391 			return true;
8392 	}
8393 
8394 	return false;
8395 }
8396 
8397 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
8398 			       const struct btf *reg_btf, u32 reg_id,
8399 			       const struct btf *arg_btf, u32 arg_id)
8400 {
8401 	const char *reg_name, *arg_name, *search_needle;
8402 	const struct btf_type *reg_type, *arg_type;
8403 	int reg_len, arg_len, cmp_len;
8404 	size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
8405 
8406 	reg_type = btf_type_by_id(reg_btf, reg_id);
8407 	if (!reg_type)
8408 		return false;
8409 
8410 	arg_type = btf_type_by_id(arg_btf, arg_id);
8411 	if (!arg_type)
8412 		return false;
8413 
8414 	reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
8415 	arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
8416 
8417 	reg_len = strlen(reg_name);
8418 	arg_len = strlen(arg_name);
8419 
8420 	/* Exactly one of the two type names may be suffixed with ___init, so
8421 	 * if the strings are the same size, they can't possibly be no-cast
8422 	 * aliases of one another. If you have two of the same type names, e.g.
8423 	 * they're both nf_conn___init, it would be improper to return true
8424 	 * because they are _not_ no-cast aliases, they are the same type.
8425 	 */
8426 	if (reg_len == arg_len)
8427 		return false;
8428 
8429 	/* Either of the two names must be the other name, suffixed with ___init. */
8430 	if ((reg_len != arg_len + pattern_len) &&
8431 	    (arg_len != reg_len + pattern_len))
8432 		return false;
8433 
8434 	if (reg_len < arg_len) {
8435 		search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
8436 		cmp_len = reg_len;
8437 	} else {
8438 		search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
8439 		cmp_len = arg_len;
8440 	}
8441 
8442 	if (!search_needle)
8443 		return false;
8444 
8445 	/* ___init suffix must come at the end of the name */
8446 	if (*(search_needle + pattern_len) != '\0')
8447 		return false;
8448 
8449 	return !strncmp(reg_name, arg_name, cmp_len);
8450 }
8451