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