xref: /linux/kernel/bpf/btf.c (revision 2b5440b31cafad2fb4b4a83efb780a6d7430a385)
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.h>
23 #include <linux/bpf-cgroup.h>
24 #include <linux/bpf_lsm.h>
25 #include <linux/skmsg.h>
26 #include <linux/perf_event.h>
27 #include <linux/bsearch.h>
28 #include <linux/kobject.h>
29 #include <linux/string.h>
30 #include <linux/sysfs.h>
31 #include <linux/overflow.h>
32 #include <linux/bitops.h>
33 
34 #include <net/netfilter/nf_bpf_link.h>
35 
36 #include <net/sock.h>
37 #include <net/xdp.h>
38 #include "../tools/lib/bpf/relo_core.h"
39 
40 /* BTF (BPF Type Format) is the meta data format which describes
41  * the data types of BPF program/map.  Hence, it basically focus
42  * on the C programming language which the modern BPF is primary
43  * using.
44  *
45  * ELF Section:
46  * ~~~~~~~~~~~
47  * The BTF data is stored under the ".BTF" ELF section
48  *
49  * struct btf_type:
50  * ~~~~~~~~~~~~~~~
51  * Each 'struct btf_type' object describes a C data type.
52  * Depending on the type it is describing, a 'struct btf_type'
53  * object may be followed by more data.  F.e.
54  * To describe an array, 'struct btf_type' is followed by
55  * 'struct btf_array'.
56  *
57  * 'struct btf_type' and any extra data following it are
58  * 4 bytes aligned.
59  *
60  * Type section:
61  * ~~~~~~~~~~~~~
62  * The BTF type section contains a list of 'struct btf_type' objects.
63  * Each one describes a C type.  Recall from the above section
64  * that a 'struct btf_type' object could be immediately followed by extra
65  * data in order to describe some particular C types.
66  *
67  * type_id:
68  * ~~~~~~~
69  * Each btf_type object is identified by a type_id.  The type_id
70  * is implicitly implied by the location of the btf_type object in
71  * the BTF type section.  The first one has type_id 1.  The second
72  * one has type_id 2...etc.  Hence, an earlier btf_type has
73  * a smaller type_id.
74  *
75  * A btf_type object may refer to another btf_type object by using
76  * type_id (i.e. the "type" in the "struct btf_type").
77  *
78  * NOTE that we cannot assume any reference-order.
79  * A btf_type object can refer to an earlier btf_type object
80  * but it can also refer to a later btf_type object.
81  *
82  * For example, to describe "const void *".  A btf_type
83  * object describing "const" may refer to another btf_type
84  * object describing "void *".  This type-reference is done
85  * by specifying type_id:
86  *
87  * [1] CONST (anon) type_id=2
88  * [2] PTR (anon) type_id=0
89  *
90  * The above is the btf_verifier debug log:
91  *   - Each line started with "[?]" is a btf_type object
92  *   - [?] is the type_id of the btf_type object.
93  *   - CONST/PTR is the BTF_KIND_XXX
94  *   - "(anon)" is the name of the type.  It just
95  *     happens that CONST and PTR has no name.
96  *   - type_id=XXX is the 'u32 type' in btf_type
97  *
98  * NOTE: "void" has type_id 0
99  *
100  * String section:
101  * ~~~~~~~~~~~~~~
102  * The BTF string section contains the names used by the type section.
103  * Each string is referred by an "offset" from the beginning of the
104  * string section.
105  *
106  * Each string is '\0' terminated.
107  *
108  * The first character in the string section must be '\0'
109  * which is used to mean 'anonymous'. Some btf_type may not
110  * have a name.
111  */
112 
113 /* BTF verification:
114  *
115  * To verify BTF data, two passes are needed.
116  *
117  * Pass #1
118  * ~~~~~~~
119  * The first pass is to collect all btf_type objects to
120  * an array: "btf->types".
121  *
122  * Depending on the C type that a btf_type is describing,
123  * a btf_type may be followed by extra data.  We don't know
124  * how many btf_type is there, and more importantly we don't
125  * know where each btf_type is located in the type section.
126  *
127  * Without knowing the location of each type_id, most verifications
128  * cannot be done.  e.g. an earlier btf_type may refer to a later
129  * btf_type (recall the "const void *" above), so we cannot
130  * check this type-reference in the first pass.
131  *
132  * In the first pass, it still does some verifications (e.g.
133  * checking the name is a valid offset to the string section).
134  *
135  * Pass #2
136  * ~~~~~~~
137  * The main focus is to resolve a btf_type that is referring
138  * to another type.
139  *
140  * We have to ensure the referring type:
141  * 1) does exist in the BTF (i.e. in btf->types[])
142  * 2) does not cause a loop:
143  *	struct A {
144  *		struct B b;
145  *	};
146  *
147  *	struct B {
148  *		struct A a;
149  *	};
150  *
151  * btf_type_needs_resolve() decides if a btf_type needs
152  * to be resolved.
153  *
154  * The needs_resolve type implements the "resolve()" ops which
155  * essentially does a DFS and detects backedge.
156  *
157  * During resolve (or DFS), different C types have different
158  * "RESOLVED" conditions.
159  *
160  * When resolving a BTF_KIND_STRUCT, we need to resolve all its
161  * members because a member is always referring to another
162  * type.  A struct's member can be treated as "RESOLVED" if
163  * it is referring to a BTF_KIND_PTR.  Otherwise, the
164  * following valid C struct would be rejected:
165  *
166  *	struct A {
167  *		int m;
168  *		struct A *a;
169  *	};
170  *
171  * When resolving a BTF_KIND_PTR, it needs to keep resolving if
172  * it is referring to another BTF_KIND_PTR.  Otherwise, we cannot
173  * detect a pointer loop, e.g.:
174  * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
175  *                        ^                                         |
176  *                        +-----------------------------------------+
177  *
178  */
179 
180 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
181 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
182 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
183 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
184 #define BITS_ROUNDUP_BYTES(bits) \
185 	(BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
186 
187 #define BTF_INT_MASK 0x0fffffff
188 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
189 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
190 
191 /* 16MB for 64k structs and each has 16 members and
192  * a few MB spaces for the string section.
193  * The hard limit is S32_MAX.
194  */
195 #define BTF_MAX_SIZE (16 * 1024 * 1024)
196 
197 #define for_each_member_from(i, from, struct_type, member)		\
198 	for (i = from, member = btf_type_member(struct_type) + from;	\
199 	     i < btf_type_vlen(struct_type);				\
200 	     i++, member++)
201 
202 #define for_each_vsi_from(i, from, struct_type, member)				\
203 	for (i = from, member = btf_type_var_secinfo(struct_type) + from;	\
204 	     i < btf_type_vlen(struct_type);					\
205 	     i++, member++)
206 
207 DEFINE_IDR(btf_idr);
208 DEFINE_SPINLOCK(btf_idr_lock);
209 
210 enum btf_kfunc_hook {
211 	BTF_KFUNC_HOOK_COMMON,
212 	BTF_KFUNC_HOOK_XDP,
213 	BTF_KFUNC_HOOK_TC,
214 	BTF_KFUNC_HOOK_STRUCT_OPS,
215 	BTF_KFUNC_HOOK_TRACING,
216 	BTF_KFUNC_HOOK_SYSCALL,
217 	BTF_KFUNC_HOOK_FMODRET,
218 	BTF_KFUNC_HOOK_CGROUP,
219 	BTF_KFUNC_HOOK_SCHED_ACT,
220 	BTF_KFUNC_HOOK_SK_SKB,
221 	BTF_KFUNC_HOOK_SOCKET_FILTER,
222 	BTF_KFUNC_HOOK_LWT,
223 	BTF_KFUNC_HOOK_NETFILTER,
224 	BTF_KFUNC_HOOK_KPROBE,
225 	BTF_KFUNC_HOOK_MAX,
226 };
227 
228 enum {
229 	BTF_KFUNC_SET_MAX_CNT = 256,
230 	BTF_DTOR_KFUNC_MAX_CNT = 256,
231 	BTF_KFUNC_FILTER_MAX_CNT = 16,
232 };
233 
234 struct btf_kfunc_hook_filter {
235 	btf_kfunc_filter_t filters[BTF_KFUNC_FILTER_MAX_CNT];
236 	u32 nr_filters;
237 };
238 
239 struct btf_kfunc_set_tab {
240 	struct btf_id_set8 *sets[BTF_KFUNC_HOOK_MAX];
241 	struct btf_kfunc_hook_filter hook_filters[BTF_KFUNC_HOOK_MAX];
242 };
243 
244 struct btf_id_dtor_kfunc_tab {
245 	u32 cnt;
246 	struct btf_id_dtor_kfunc dtors[];
247 };
248 
249 struct btf_struct_ops_tab {
250 	u32 cnt;
251 	u32 capacity;
252 	struct bpf_struct_ops_desc ops[];
253 };
254 
255 struct btf {
256 	void *data;
257 	struct btf_type **types;
258 	u32 *resolved_ids;
259 	u32 *resolved_sizes;
260 	const char *strings;
261 	void *nohdr_data;
262 	struct btf_header hdr;
263 	u32 nr_types; /* includes VOID for base BTF */
264 	u32 named_start_id;
265 	u32 types_size;
266 	u32 data_size;
267 	refcount_t refcnt;
268 	u32 id;
269 	struct rcu_head rcu;
270 	struct btf_kfunc_set_tab *kfunc_set_tab;
271 	struct btf_id_dtor_kfunc_tab *dtor_kfunc_tab;
272 	struct btf_struct_metas *struct_meta_tab;
273 	struct btf_struct_ops_tab *struct_ops_tab;
274 	struct btf_layout *layout;
275 
276 	/* split BTF support */
277 	struct btf *base_btf;
278 	u32 start_id; /* first type ID in this BTF (0 for base BTF) */
279 	u32 start_str_off; /* first string offset (0 for base BTF) */
280 	char name[MODULE_NAME_LEN];
281 	bool kernel_btf;
282 	__u32 *base_id_map; /* map from distilled base BTF -> vmlinux BTF ids */
283 };
284 
285 enum verifier_phase {
286 	CHECK_META,
287 	CHECK_TYPE,
288 };
289 
290 struct resolve_vertex {
291 	const struct btf_type *t;
292 	u32 type_id;
293 	u32 next_member;
294 };
295 
296 enum visit_state {
297 	NOT_VISITED,
298 	VISITED,
299 	RESOLVED,
300 };
301 
302 enum resolve_mode {
303 	RESOLVE_TBD,	/* To Be Determined */
304 	RESOLVE_PTR,	/* Resolving for Pointer */
305 	RESOLVE_STRUCT_OR_ARRAY,	/* Resolving for struct/union
306 					 * or array
307 					 */
308 };
309 
310 #define MAX_RESOLVE_DEPTH 32
311 
312 struct btf_sec_info {
313 	u32 off;
314 	u32 len;
315 };
316 
317 struct btf_verifier_env {
318 	struct btf *btf;
319 	u8 *visit_states;
320 	struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
321 	struct bpf_verifier_log log;
322 	u32 log_type_id;
323 	u32 top_stack;
324 	enum verifier_phase phase;
325 	enum resolve_mode resolve_mode;
326 };
327 
328 static const char * const btf_kind_str[NR_BTF_KINDS] = {
329 	[BTF_KIND_UNKN]		= "UNKNOWN",
330 	[BTF_KIND_INT]		= "INT",
331 	[BTF_KIND_PTR]		= "PTR",
332 	[BTF_KIND_ARRAY]	= "ARRAY",
333 	[BTF_KIND_STRUCT]	= "STRUCT",
334 	[BTF_KIND_UNION]	= "UNION",
335 	[BTF_KIND_ENUM]		= "ENUM",
336 	[BTF_KIND_FWD]		= "FWD",
337 	[BTF_KIND_TYPEDEF]	= "TYPEDEF",
338 	[BTF_KIND_VOLATILE]	= "VOLATILE",
339 	[BTF_KIND_CONST]	= "CONST",
340 	[BTF_KIND_RESTRICT]	= "RESTRICT",
341 	[BTF_KIND_FUNC]		= "FUNC",
342 	[BTF_KIND_FUNC_PROTO]	= "FUNC_PROTO",
343 	[BTF_KIND_VAR]		= "VAR",
344 	[BTF_KIND_DATASEC]	= "DATASEC",
345 	[BTF_KIND_FLOAT]	= "FLOAT",
346 	[BTF_KIND_DECL_TAG]	= "DECL_TAG",
347 	[BTF_KIND_TYPE_TAG]	= "TYPE_TAG",
348 	[BTF_KIND_ENUM64]	= "ENUM64",
349 	[BTF_KIND_LOC_PARAM]	= "LOC_PARAM",
350 	[BTF_KIND_LOC_PROTO]	= "LOC_PROTO",
351 	[BTF_KIND_LOCSEC]	= "LOCSEC",
352 };
353 
354 const char *btf_type_str(const struct btf_type *t)
355 {
356 	return btf_kind_str[BTF_INFO_KIND(t->info)];
357 }
358 
359 /* Chunk size we use in safe copy of data to be shown. */
360 #define BTF_SHOW_OBJ_SAFE_SIZE		32
361 
362 /*
363  * This is the maximum size of a base type value (equivalent to a
364  * 128-bit int); if we are at the end of our safe buffer and have
365  * less than 16 bytes space we can't be assured of being able
366  * to copy the next type safely, so in such cases we will initiate
367  * a new copy.
368  */
369 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE	16
370 
371 /* Type name size */
372 #define BTF_SHOW_NAME_SIZE		80
373 
374 /*
375  * The suffix of a type that indicates it cannot alias another type when
376  * comparing BTF IDs for kfunc invocations.
377  */
378 #define NOCAST_ALIAS_SUFFIX		"___init"
379 
380 /*
381  * Common data to all BTF show operations. Private show functions can add
382  * their own data to a structure containing a struct btf_show and consult it
383  * in the show callback.  See btf_type_show() below.
384  *
385  * One challenge with showing nested data is we want to skip 0-valued
386  * data, but in order to figure out whether a nested object is all zeros
387  * we need to walk through it.  As a result, we need to make two passes
388  * when handling structs, unions and arrays; the first path simply looks
389  * for nonzero data, while the second actually does the display.  The first
390  * pass is signalled by show->state.depth_check being set, and if we
391  * encounter a non-zero value we set show->state.depth_to_show to
392  * the depth at which we encountered it.  When we have completed the
393  * first pass, we will know if anything needs to be displayed if
394  * depth_to_show > depth.  See btf_[struct,array]_show() for the
395  * implementation of this.
396  *
397  * Another problem is we want to ensure the data for display is safe to
398  * access.  To support this, the anonymous "struct {} obj" tracks the data
399  * object and our safe copy of it.  We copy portions of the data needed
400  * to the object "copy" buffer, but because its size is limited to
401  * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
402  * traverse larger objects for display.
403  *
404  * The various data type show functions all start with a call to
405  * btf_show_start_type() which returns a pointer to the safe copy
406  * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
407  * raw data itself).  btf_show_obj_safe() is responsible for
408  * using copy_from_kernel_nofault() to update the safe data if necessary
409  * as we traverse the object's data.  skbuff-like semantics are
410  * used:
411  *
412  * - obj.head points to the start of the toplevel object for display
413  * - obj.size is the size of the toplevel object
414  * - obj.data points to the current point in the original data at
415  *   which our safe data starts.  obj.data will advance as we copy
416  *   portions of the data.
417  *
418  * In most cases a single copy will suffice, but larger data structures
419  * such as "struct task_struct" will require many copies.  The logic in
420  * btf_show_obj_safe() handles the logic that determines if a new
421  * copy_from_kernel_nofault() is needed.
422  */
423 struct btf_show {
424 	u64 flags;
425 	void *target;	/* target of show operation (seq file, buffer) */
426 	__printf(2, 0) void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
427 	const struct btf *btf;
428 	/* below are used during iteration */
429 	struct {
430 		u8 depth;
431 		u8 depth_to_show;
432 		u8 depth_check;
433 		u8 array_member:1,
434 		   array_terminated:1;
435 		u16 array_encoding;
436 		u32 type_id;
437 		int status;			/* non-zero for error */
438 		const struct btf_type *type;
439 		const struct btf_member *member;
440 		char name[BTF_SHOW_NAME_SIZE];	/* space for member name/type */
441 	} state;
442 	struct {
443 		u32 size;
444 		void *head;
445 		void *data;
446 		u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
447 	} obj;
448 };
449 
450 struct btf_kind_operations {
451 	s32 (*check_meta)(struct btf_verifier_env *env,
452 			  const struct btf_type *t,
453 			  u32 meta_left);
454 	int (*resolve)(struct btf_verifier_env *env,
455 		       const struct resolve_vertex *v);
456 	int (*check_member)(struct btf_verifier_env *env,
457 			    const struct btf_type *struct_type,
458 			    const struct btf_member *member,
459 			    const struct btf_type *member_type);
460 	int (*check_kflag_member)(struct btf_verifier_env *env,
461 				  const struct btf_type *struct_type,
462 				  const struct btf_member *member,
463 				  const struct btf_type *member_type);
464 	void (*log_details)(struct btf_verifier_env *env,
465 			    const struct btf_type *t);
466 	void (*show)(const struct btf *btf, const struct btf_type *t,
467 			 u32 type_id, void *data, u8 bits_offsets,
468 			 struct btf_show *show);
469 };
470 
471 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
472 static struct btf_type btf_void;
473 
474 static int btf_resolve(struct btf_verifier_env *env,
475 		       const struct btf_type *t, u32 type_id);
476 
477 static int btf_func_check(struct btf_verifier_env *env,
478 			  const struct btf_type *t);
479 
480 static bool btf_type_is_modifier(const struct btf_type *t)
481 {
482 	/* Some of them is not strictly a C modifier
483 	 * but they are grouped into the same bucket
484 	 * for BTF concern:
485 	 *   A type (t) that refers to another
486 	 *   type through t->type AND its size cannot
487 	 *   be determined without following the t->type.
488 	 *
489 	 * ptr does not fall into this bucket
490 	 * because its size is always sizeof(void *).
491 	 */
492 	switch (BTF_INFO_KIND(t->info)) {
493 	case BTF_KIND_TYPEDEF:
494 	case BTF_KIND_VOLATILE:
495 	case BTF_KIND_CONST:
496 	case BTF_KIND_RESTRICT:
497 	case BTF_KIND_TYPE_TAG:
498 		return true;
499 	}
500 
501 	return false;
502 }
503 
504 static int btf_start_id(const struct btf *btf)
505 {
506 	return btf->start_id + (btf->base_btf ? 0 : 1);
507 }
508 
509 bool btf_type_is_void(const struct btf_type *t)
510 {
511 	return t == &btf_void;
512 }
513 
514 static bool btf_type_is_datasec(const struct btf_type *t)
515 {
516 	return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
517 }
518 
519 static bool btf_type_is_decl_tag(const struct btf_type *t)
520 {
521 	return BTF_INFO_KIND(t->info) == BTF_KIND_DECL_TAG;
522 }
523 
524 static bool btf_type_is_loc_param(const struct btf_type *t)
525 {
526 	return BTF_INFO_KIND(t->info) == BTF_KIND_LOC_PARAM;
527 }
528 
529 static bool btf_type_is_loc_proto(const struct btf_type *t)
530 {
531 	return BTF_INFO_KIND(t->info) == BTF_KIND_LOC_PROTO;
532 }
533 
534 static bool btf_type_is_locsec(const struct btf_type *t)
535 {
536 	return BTF_INFO_KIND(t->info) == BTF_KIND_LOCSEC;
537 }
538 
539 static bool btf_type_nosize(const struct btf_type *t)
540 {
541 	return btf_type_is_void(t) || btf_type_is_fwd(t) ||
542 	       btf_type_is_func(t) || btf_type_is_func_proto(t) ||
543 	       btf_type_is_decl_tag(t) || btf_type_is_loc_param(t) ||
544 	       btf_type_is_loc_proto(t) || btf_type_is_locsec(t);
545 }
546 
547 static bool btf_type_nosize_or_null(const struct btf_type *t)
548 {
549 	return !t || btf_type_nosize(t);
550 }
551 
552 static bool btf_type_is_decl_tag_target(const struct btf_type *t)
553 {
554 	return btf_type_is_func(t) || btf_type_is_struct(t) ||
555 	       btf_type_is_var(t) || btf_type_is_typedef(t);
556 }
557 
558 bool btf_is_vmlinux(const struct btf *btf)
559 {
560 	return btf->kernel_btf && !btf->base_btf;
561 }
562 
563 u32 btf_nr_types(const struct btf *btf)
564 {
565 	u32 total = 0;
566 
567 	while (btf) {
568 		total += btf->nr_types;
569 		btf = btf->base_btf;
570 	}
571 
572 	return total;
573 }
574 
575 /*
576  * Note that vmlinux and kernel module BTFs are always sorted
577  * during the building phase.
578  */
579 static void btf_check_sorted(struct btf *btf)
580 {
581 	u32 i, n, named_start_id = 0;
582 
583 	n = btf_nr_types(btf);
584 	if (btf_is_vmlinux(btf)) {
585 		for (i = btf_start_id(btf); i < n; i++) {
586 			const struct btf_type *t = btf_type_by_id(btf, i);
587 			const char *n = btf_name_by_offset(btf, t->name_off);
588 
589 			if (n[0] != '\0') {
590 				btf->named_start_id = i;
591 				return;
592 			}
593 		}
594 		return;
595 	}
596 
597 	for (i = btf_start_id(btf) + 1; i < n; i++) {
598 		const struct btf_type *ta = btf_type_by_id(btf, i - 1);
599 		const struct btf_type *tb = btf_type_by_id(btf, i);
600 		const char *na = btf_name_by_offset(btf, ta->name_off);
601 		const char *nb = btf_name_by_offset(btf, tb->name_off);
602 
603 		if (strcmp(na, nb) > 0)
604 			return;
605 
606 		if (named_start_id == 0 && na[0] != '\0')
607 			named_start_id = i - 1;
608 		if (named_start_id == 0 && nb[0] != '\0')
609 			named_start_id = i;
610 	}
611 
612 	if (named_start_id)
613 		btf->named_start_id = named_start_id;
614 }
615 
616 /*
617  * btf_named_start_id - Get the named starting ID for the BTF
618  * @btf: Pointer to the target BTF object
619  * @own: Flag indicating whether to query only the current BTF (true = current BTF only,
620  *       false = recursively traverse the base BTF chain)
621  *
622  * Return value rules:
623  * 1. For a sorted btf, return its named_start_id
624  * 2. Else for a split BTF, return its start_id
625  * 3. Else for a base BTF, return 1
626  */
627 u32 btf_named_start_id(const struct btf *btf, bool own)
628 {
629 	const struct btf *base_btf = btf;
630 
631 	while (!own && base_btf->base_btf)
632 		base_btf = base_btf->base_btf;
633 
634 	return base_btf->named_start_id ?: (base_btf->start_id ?: 1);
635 }
636 
637 static s32 btf_find_by_name_kind_bsearch(const struct btf *btf, const char *name)
638 {
639 	const struct btf_type *t;
640 	const char *tname;
641 	s32 l, r, m;
642 
643 	l = btf_named_start_id(btf, true);
644 	r = btf_nr_types(btf) - 1;
645 	while (l <= r) {
646 		m = l + (r - l) / 2;
647 		t = btf_type_by_id(btf, m);
648 		tname = btf_name_by_offset(btf, t->name_off);
649 		if (strcmp(tname, name) >= 0) {
650 			if (l == r)
651 				return r;
652 			r = m;
653 		} else {
654 			l = m + 1;
655 		}
656 	}
657 
658 	return btf_nr_types(btf);
659 }
660 
661 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
662 {
663 	const struct btf *base_btf = btf_base_btf(btf);
664 	const struct btf_type *t;
665 	const char *tname;
666 	s32 id, total;
667 
668 	if (base_btf) {
669 		id = btf_find_by_name_kind(base_btf, name, kind);
670 		if (id > 0)
671 			return id;
672 	}
673 
674 	total = btf_nr_types(btf);
675 	if (btf->named_start_id > 0 && name[0]) {
676 		id = btf_find_by_name_kind_bsearch(btf, name);
677 		for (; id < total; id++) {
678 			t = btf_type_by_id(btf, id);
679 			tname = btf_name_by_offset(btf, t->name_off);
680 			if (strcmp(tname, name) != 0)
681 				return -ENOENT;
682 			if (BTF_INFO_KIND(t->info) == kind)
683 				return id;
684 		}
685 	} else {
686 		for (id = btf_start_id(btf); id < total; id++) {
687 			t = btf_type_by_id(btf, id);
688 			if (BTF_INFO_KIND(t->info) != kind)
689 				continue;
690 			tname = btf_name_by_offset(btf, t->name_off);
691 			if (strcmp(tname, name) == 0)
692 				return id;
693 		}
694 	}
695 
696 	return -ENOENT;
697 }
698 
699 s32 bpf_find_btf_id(const char *name, u32 kind, struct btf **btf_p)
700 {
701 	struct btf *btf;
702 	s32 ret;
703 	int id;
704 
705 	btf = bpf_get_btf_vmlinux();
706 	if (IS_ERR(btf))
707 		return PTR_ERR(btf);
708 	if (!btf)
709 		return -EINVAL;
710 
711 	ret = btf_find_by_name_kind(btf, name, kind);
712 	/* ret is never zero, since btf_find_by_name_kind returns
713 	 * positive btf_id or negative error.
714 	 */
715 	if (ret > 0) {
716 		btf_get(btf);
717 		*btf_p = btf;
718 		return ret;
719 	}
720 
721 	/* If name is not found in vmlinux's BTF then search in module's BTFs */
722 	spin_lock_bh(&btf_idr_lock);
723 	idr_for_each_entry(&btf_idr, btf, id) {
724 		if (!btf_is_module(btf))
725 			continue;
726 		/* linear search could be slow hence unlock/lock
727 		 * the IDR to avoiding holding it for too long
728 		 */
729 		btf_get(btf);
730 		spin_unlock_bh(&btf_idr_lock);
731 		ret = btf_find_by_name_kind(btf, name, kind);
732 		if (ret > 0) {
733 			*btf_p = btf;
734 			return ret;
735 		}
736 		btf_put(btf);
737 		spin_lock_bh(&btf_idr_lock);
738 	}
739 	spin_unlock_bh(&btf_idr_lock);
740 	return ret;
741 }
742 EXPORT_SYMBOL_GPL(bpf_find_btf_id);
743 
744 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
745 					       u32 id, u32 *res_id)
746 {
747 	const struct btf_type *t = btf_type_by_id(btf, id);
748 
749 	while (btf_type_is_modifier(t)) {
750 		id = t->type;
751 		t = btf_type_by_id(btf, t->type);
752 	}
753 
754 	if (res_id)
755 		*res_id = id;
756 
757 	return t;
758 }
759 
760 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
761 					    u32 id, u32 *res_id)
762 {
763 	const struct btf_type *t;
764 
765 	t = btf_type_skip_modifiers(btf, id, NULL);
766 	if (!btf_type_is_ptr(t))
767 		return NULL;
768 
769 	return btf_type_skip_modifiers(btf, t->type, res_id);
770 }
771 
772 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
773 						 u32 id, u32 *res_id)
774 {
775 	const struct btf_type *ptype;
776 
777 	ptype = btf_type_resolve_ptr(btf, id, res_id);
778 	if (ptype && btf_type_is_func_proto(ptype))
779 		return ptype;
780 
781 	return NULL;
782 }
783 
784 /* Types that act only as a source, not sink or intermediate
785  * type when resolving.
786  */
787 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
788 {
789 	return btf_type_is_var(t) ||
790 	       btf_type_is_decl_tag(t) ||
791 	       btf_type_is_datasec(t) ||
792 	       btf_type_is_loc_proto(t) ||
793 	       btf_type_is_locsec(t);
794 }
795 
796 /* What types need to be resolved?
797  *
798  * btf_type_is_modifier() is an obvious one.
799  *
800  * btf_type_is_struct() because its member refers to
801  * another type (through member->type).
802  *
803  * btf_type_is_var() because the variable refers to
804  * another type. btf_type_is_datasec() holds multiple
805  * btf_type_is_var() types that need resolving.
806  *
807  * btf_type_is_array() because its element (array->type)
808  * refers to another type.  Array can be thought of a
809  * special case of struct while array just has the same
810  * member-type repeated by array->nelems of times.
811  */
812 static bool btf_type_needs_resolve(const struct btf_type *t)
813 {
814 	return btf_type_is_modifier(t) ||
815 	       btf_type_is_ptr(t) ||
816 	       btf_type_is_struct(t) ||
817 	       btf_type_is_array(t) ||
818 	       btf_type_is_var(t) ||
819 	       btf_type_is_func(t) ||
820 	       btf_type_is_decl_tag(t) ||
821 	       btf_type_is_datasec(t) ||
822 	       btf_type_is_loc_proto(t) ||
823 	       btf_type_is_locsec(t);
824 }
825 
826 /* t->size can be used */
827 static bool btf_type_has_size(const struct btf_type *t)
828 {
829 	switch (BTF_INFO_KIND(t->info)) {
830 	case BTF_KIND_INT:
831 	case BTF_KIND_STRUCT:
832 	case BTF_KIND_UNION:
833 	case BTF_KIND_ENUM:
834 	case BTF_KIND_DATASEC:
835 	case BTF_KIND_FLOAT:
836 	case BTF_KIND_ENUM64:
837 		return true;
838 	}
839 
840 	return false;
841 }
842 
843 static const char *btf_int_encoding_str(u8 encoding)
844 {
845 	if (encoding == 0)
846 		return "(none)";
847 	else if (encoding == BTF_INT_SIGNED)
848 		return "SIGNED";
849 	else if (encoding == BTF_INT_CHAR)
850 		return "CHAR";
851 	else if (encoding == BTF_INT_BOOL)
852 		return "BOOL";
853 	else
854 		return "UNKN";
855 }
856 
857 static u32 btf_type_int(const struct btf_type *t)
858 {
859 	return *(u32 *)(t + 1);
860 }
861 
862 static const struct btf_array *btf_type_array(const struct btf_type *t)
863 {
864 	return (const struct btf_array *)(t + 1);
865 }
866 
867 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
868 {
869 	return (const struct btf_enum *)(t + 1);
870 }
871 
872 static const struct btf_var *btf_type_var(const struct btf_type *t)
873 {
874 	return (const struct btf_var *)(t + 1);
875 }
876 
877 static const struct btf_decl_tag *btf_type_decl_tag(const struct btf_type *t)
878 {
879 	return (const struct btf_decl_tag *)(t + 1);
880 }
881 
882 static const struct btf_enum64 *btf_type_enum64(const struct btf_type *t)
883 {
884 	return (const struct btf_enum64 *)(t + 1);
885 }
886 
887 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
888 {
889 	return kind_ops[BTF_INFO_KIND(t->info)];
890 }
891 
892 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
893 {
894 	if (!BTF_STR_OFFSET_VALID(offset))
895 		return false;
896 
897 	while (offset < btf->start_str_off)
898 		btf = btf->base_btf;
899 
900 	offset -= btf->start_str_off;
901 	return offset < btf->hdr.str_len;
902 }
903 
904 static bool __btf_name_char_ok(char c, bool first)
905 {
906 	if ((first ? !isalpha(c) :
907 		     !isalnum(c)) &&
908 	    c != '_' &&
909 	    c != '.')
910 		return false;
911 	return true;
912 }
913 
914 const char *btf_str_by_offset(const struct btf *btf, u32 offset)
915 {
916 	while (offset < btf->start_str_off)
917 		btf = btf->base_btf;
918 
919 	offset -= btf->start_str_off;
920 	if (offset < btf->hdr.str_len)
921 		return &btf->strings[offset];
922 
923 	return NULL;
924 }
925 
926 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
927 {
928 	/* offset must be valid */
929 	const char *src = btf_str_by_offset(btf, offset);
930 	const char *src_limit;
931 
932 	if (!__btf_name_char_ok(*src, true))
933 		return false;
934 
935 	/* set a limit on identifier length */
936 	src_limit = src + KSYM_NAME_LEN;
937 	src++;
938 	while (*src && src < src_limit) {
939 		if (!__btf_name_char_ok(*src, false))
940 			return false;
941 		src++;
942 	}
943 
944 	return !*src;
945 }
946 
947 /* Allow any printable character in DATASEC names */
948 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
949 {
950 	/* offset must be valid */
951 	const char *src = btf_str_by_offset(btf, offset);
952 	const char *src_limit;
953 
954 	if (!*src)
955 		return false;
956 
957 	/* set a limit on identifier length */
958 	src_limit = src + KSYM_NAME_LEN;
959 	while (*src && src < src_limit) {
960 		if (!isprint(*src))
961 			return false;
962 		src++;
963 	}
964 
965 	return !*src;
966 }
967 
968 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
969 {
970 	const char *name;
971 
972 	if (!offset)
973 		return "(anon)";
974 
975 	name = btf_str_by_offset(btf, offset);
976 	return name ?: "(invalid-name-offset)";
977 }
978 
979 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
980 {
981 	return btf_str_by_offset(btf, offset);
982 }
983 
984 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
985 {
986 	while (type_id < btf->start_id)
987 		btf = btf->base_btf;
988 
989 	type_id -= btf->start_id;
990 	if (type_id >= btf->nr_types)
991 		return NULL;
992 	return btf->types[type_id];
993 }
994 EXPORT_SYMBOL_GPL(btf_type_by_id);
995 
996 /*
997  * Check that the type @t is a regular int. This means that @t is not
998  * a bit field and it has the same size as either of u8/u16/u32/u64
999  * or __int128. If @expected_size is not zero, then size of @t should
1000  * be the same. A caller should already have checked that the type @t
1001  * is an integer.
1002  */
1003 static bool __btf_type_int_is_regular(const struct btf_type *t, size_t expected_size)
1004 {
1005 	u32 int_data = btf_type_int(t);
1006 	u8 nr_bits = BTF_INT_BITS(int_data);
1007 	u8 nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
1008 
1009 	return BITS_PER_BYTE_MASKED(nr_bits) == 0 &&
1010 	       BTF_INT_OFFSET(int_data) == 0 &&
1011 	       (nr_bytes <= 16 && is_power_of_2(nr_bytes)) &&
1012 	       (expected_size == 0 || nr_bytes == expected_size);
1013 }
1014 
1015 static bool btf_type_int_is_regular(const struct btf_type *t)
1016 {
1017 	return __btf_type_int_is_regular(t, 0);
1018 }
1019 
1020 bool btf_type_is_i32(const struct btf_type *t)
1021 {
1022 	return btf_type_is_int(t) && __btf_type_int_is_regular(t, 4);
1023 }
1024 
1025 bool btf_type_is_i64(const struct btf_type *t)
1026 {
1027 	return btf_type_is_int(t) && __btf_type_int_is_regular(t, 8);
1028 }
1029 
1030 bool btf_type_is_primitive(const struct btf_type *t)
1031 {
1032 	return (btf_type_is_int(t) && btf_type_int_is_regular(t)) ||
1033 	       btf_is_any_enum(t);
1034 }
1035 
1036 /*
1037  * Check that given struct member is a regular int with expected
1038  * offset and size.
1039  */
1040 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
1041 			   const struct btf_member *m,
1042 			   u32 expected_offset, u32 expected_size)
1043 {
1044 	const struct btf_type *t;
1045 	u32 id, int_data;
1046 	u8 nr_bits;
1047 
1048 	id = m->type;
1049 	t = btf_type_id_size(btf, &id, NULL);
1050 	if (!t || !btf_type_is_int(t))
1051 		return false;
1052 
1053 	int_data = btf_type_int(t);
1054 	nr_bits = BTF_INT_BITS(int_data);
1055 	if (btf_type_kflag(s)) {
1056 		u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
1057 		u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
1058 
1059 		/* if kflag set, int should be a regular int and
1060 		 * bit offset should be at byte boundary.
1061 		 */
1062 		return !bitfield_size &&
1063 		       BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
1064 		       BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
1065 	}
1066 
1067 	if (BTF_INT_OFFSET(int_data) ||
1068 	    BITS_PER_BYTE_MASKED(m->offset) ||
1069 	    BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
1070 	    BITS_PER_BYTE_MASKED(nr_bits) ||
1071 	    BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
1072 		return false;
1073 
1074 	return true;
1075 }
1076 
1077 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
1078 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
1079 						       u32 id)
1080 {
1081 	const struct btf_type *t = btf_type_by_id(btf, id);
1082 
1083 	while (btf_type_is_modifier(t) &&
1084 	       BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
1085 		t = btf_type_by_id(btf, t->type);
1086 	}
1087 
1088 	return t;
1089 }
1090 
1091 #define BTF_SHOW_MAX_ITER	10
1092 
1093 #define BTF_KIND_BIT(kind)	(1ULL << kind)
1094 
1095 /*
1096  * Populate show->state.name with type name information.
1097  * Format of type name is
1098  *
1099  * [.member_name = ] (type_name)
1100  */
1101 static const char *btf_show_name(struct btf_show *show)
1102 {
1103 	/* BTF_MAX_ITER array suffixes "[]" */
1104 	const char *array_suffixes = "[][][][][][][][][][]";
1105 	const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
1106 	/* BTF_MAX_ITER pointer suffixes "*" */
1107 	const char *ptr_suffixes = "**********";
1108 	const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
1109 	const char *name = NULL, *prefix = "", *parens = "";
1110 	const struct btf_member *m = show->state.member;
1111 	const struct btf_type *t;
1112 	const struct btf_array *array;
1113 	u32 id = show->state.type_id;
1114 	const char *member = NULL;
1115 	bool show_member = false;
1116 	u64 kinds = 0;
1117 	int i;
1118 
1119 	show->state.name[0] = '\0';
1120 
1121 	/*
1122 	 * Don't show type name if we're showing an array member;
1123 	 * in that case we show the array type so don't need to repeat
1124 	 * ourselves for each member.
1125 	 */
1126 	if (show->state.array_member)
1127 		return "";
1128 
1129 	/* Retrieve member name, if any. */
1130 	if (m) {
1131 		member = btf_name_by_offset(show->btf, m->name_off);
1132 		show_member = strlen(member) > 0;
1133 		id = m->type;
1134 	}
1135 
1136 	/*
1137 	 * Start with type_id, as we have resolved the struct btf_type *
1138 	 * via btf_modifier_show() past the parent typedef to the child
1139 	 * struct, int etc it is defined as.  In such cases, the type_id
1140 	 * still represents the starting type while the struct btf_type *
1141 	 * in our show->state points at the resolved type of the typedef.
1142 	 */
1143 	t = btf_type_by_id(show->btf, id);
1144 	if (!t)
1145 		return "";
1146 
1147 	/*
1148 	 * The goal here is to build up the right number of pointer and
1149 	 * array suffixes while ensuring the type name for a typedef
1150 	 * is represented.  Along the way we accumulate a list of
1151 	 * BTF kinds we have encountered, since these will inform later
1152 	 * display; for example, pointer types will not require an
1153 	 * opening "{" for struct, we will just display the pointer value.
1154 	 *
1155 	 * We also want to accumulate the right number of pointer or array
1156 	 * indices in the format string while iterating until we get to
1157 	 * the typedef/pointee/array member target type.
1158 	 *
1159 	 * We start by pointing at the end of pointer and array suffix
1160 	 * strings; as we accumulate pointers and arrays we move the pointer
1161 	 * or array string backwards so it will show the expected number of
1162 	 * '*' or '[]' for the type.  BTF_SHOW_MAX_ITER of nesting of pointers
1163 	 * and/or arrays and typedefs are supported as a precaution.
1164 	 *
1165 	 * We also want to get typedef name while proceeding to resolve
1166 	 * type it points to so that we can add parentheses if it is a
1167 	 * "typedef struct" etc.
1168 	 */
1169 	for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
1170 
1171 		switch (BTF_INFO_KIND(t->info)) {
1172 		case BTF_KIND_TYPEDEF:
1173 			if (!name)
1174 				name = btf_name_by_offset(show->btf,
1175 							       t->name_off);
1176 			kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
1177 			id = t->type;
1178 			break;
1179 		case BTF_KIND_ARRAY:
1180 			kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
1181 			parens = "[";
1182 			if (!t)
1183 				return "";
1184 			array = btf_type_array(t);
1185 			if (array_suffix > array_suffixes)
1186 				array_suffix -= 2;
1187 			id = array->type;
1188 			break;
1189 		case BTF_KIND_PTR:
1190 			kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
1191 			if (ptr_suffix > ptr_suffixes)
1192 				ptr_suffix -= 1;
1193 			id = t->type;
1194 			break;
1195 		default:
1196 			goto resolved;
1197 		}
1198 		t = btf_type_skip_qualifiers(show->btf, id);
1199 		if (!id)
1200 			break;
1201 	}
1202 	/* We may not be able to represent this type; bail to be safe */
1203 	if (i == BTF_SHOW_MAX_ITER)
1204 		return "";
1205 
1206 resolved:
1207 	if (!name)
1208 		name = btf_type_is_void(t) ? "void" : btf_name_by_offset(show->btf, t->name_off);
1209 
1210 	switch (BTF_INFO_KIND(t->info)) {
1211 	case BTF_KIND_STRUCT:
1212 	case BTF_KIND_UNION:
1213 		prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
1214 			 "struct" : "union";
1215 		/* if it's an array of struct/union, parens is already set */
1216 		if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
1217 			parens = "{";
1218 		break;
1219 	case BTF_KIND_ENUM:
1220 	case BTF_KIND_ENUM64:
1221 		prefix = "enum";
1222 		break;
1223 	default:
1224 		break;
1225 	}
1226 
1227 	/* pointer does not require parens */
1228 	if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
1229 		parens = "";
1230 	/* typedef does not require struct/union/enum prefix */
1231 	if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
1232 		prefix = "";
1233 
1234 	if (!name)
1235 		name = "";
1236 
1237 	/* Even if we don't want type name info, we want parentheses etc */
1238 	if (show->flags & BTF_SHOW_NONAME)
1239 		snprintf(show->state.name, sizeof(show->state.name), "%s",
1240 			 parens);
1241 	else
1242 		snprintf(show->state.name, sizeof(show->state.name),
1243 			 "%s%s%s(%s%s%s%s%s%s)%s",
1244 			 /* first 3 strings comprise ".member = " */
1245 			 show_member ? "." : "",
1246 			 show_member ? member : "",
1247 			 show_member ? " = " : "",
1248 			 /* ...next is our prefix (struct, enum, etc) */
1249 			 prefix,
1250 			 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
1251 			 /* ...this is the type name itself */
1252 			 name,
1253 			 /* ...suffixed by the appropriate '*', '[]' suffixes */
1254 			 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
1255 			 array_suffix, parens);
1256 
1257 	return show->state.name;
1258 }
1259 
1260 static const char *__btf_show_indent(struct btf_show *show)
1261 {
1262 	const char *indents = "                                ";
1263 	const char *indent = &indents[strlen(indents)];
1264 
1265 	if ((indent - show->state.depth) >= indents)
1266 		return indent - show->state.depth;
1267 	return indents;
1268 }
1269 
1270 static const char *btf_show_indent(struct btf_show *show)
1271 {
1272 	return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
1273 }
1274 
1275 static const char *btf_show_newline(struct btf_show *show)
1276 {
1277 	return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
1278 }
1279 
1280 static const char *btf_show_delim(struct btf_show *show)
1281 {
1282 	if (show->state.depth == 0)
1283 		return "";
1284 
1285 	if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
1286 		BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
1287 		return "|";
1288 
1289 	return ",";
1290 }
1291 
1292 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
1293 {
1294 	va_list args;
1295 
1296 	if (!show->state.depth_check) {
1297 		va_start(args, fmt);
1298 		show->showfn(show, fmt, args);
1299 		va_end(args);
1300 	}
1301 }
1302 
1303 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1304  * format specifiers to the format specifier passed in; these do the work of
1305  * adding indentation, delimiters etc while the caller simply has to specify
1306  * the type value(s) in the format specifier + value(s).
1307  */
1308 #define btf_show_type_value(show, fmt, value)				       \
1309 	do {								       \
1310 		if ((value) != (__typeof__(value))0 ||			       \
1311 		    (show->flags & BTF_SHOW_ZERO) ||			       \
1312 		    show->state.depth == 0) {				       \
1313 			btf_show(show, "%s%s" fmt "%s%s",		       \
1314 				 btf_show_indent(show),			       \
1315 				 btf_show_name(show),			       \
1316 				 value, btf_show_delim(show),		       \
1317 				 btf_show_newline(show));		       \
1318 			if (show->state.depth > show->state.depth_to_show)     \
1319 				show->state.depth_to_show = show->state.depth; \
1320 		}							       \
1321 	} while (0)
1322 
1323 #define btf_show_type_values(show, fmt, ...)				       \
1324 	do {								       \
1325 		btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show),       \
1326 			 btf_show_name(show),				       \
1327 			 __VA_ARGS__, btf_show_delim(show),		       \
1328 			 btf_show_newline(show));			       \
1329 		if (show->state.depth > show->state.depth_to_show)	       \
1330 			show->state.depth_to_show = show->state.depth;	       \
1331 	} while (0)
1332 
1333 /* How much is left to copy to safe buffer after @data? */
1334 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1335 {
1336 	return show->obj.head + show->obj.size - data;
1337 }
1338 
1339 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1340 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1341 {
1342 	return data >= show->obj.data &&
1343 	       (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1344 }
1345 
1346 /*
1347  * If object pointed to by @data of @size falls within our safe buffer, return
1348  * the equivalent pointer to the same safe data.  Assumes
1349  * copy_from_kernel_nofault() has already happened and our safe buffer is
1350  * populated.
1351  */
1352 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1353 {
1354 	if (btf_show_obj_is_safe(show, data, size))
1355 		return show->obj.safe + (data - show->obj.data);
1356 	return NULL;
1357 }
1358 
1359 /*
1360  * Return a safe-to-access version of data pointed to by @data.
1361  * We do this by copying the relevant amount of information
1362  * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1363  *
1364  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1365  * safe copy is needed.
1366  *
1367  * Otherwise we need to determine if we have the required amount
1368  * of data (determined by the @data pointer and the size of the
1369  * largest base type we can encounter (represented by
1370  * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1371  * that we will be able to print some of the current object,
1372  * and if more is needed a copy will be triggered.
1373  * Some objects such as structs will not fit into the buffer;
1374  * in such cases additional copies when we iterate over their
1375  * members may be needed.
1376  *
1377  * btf_show_obj_safe() is used to return a safe buffer for
1378  * btf_show_start_type(); this ensures that as we recurse into
1379  * nested types we always have safe data for the given type.
1380  * This approach is somewhat wasteful; it's possible for example
1381  * that when iterating over a large union we'll end up copying the
1382  * same data repeatedly, but the goal is safety not performance.
1383  * We use stack data as opposed to per-CPU buffers because the
1384  * iteration over a type can take some time, and preemption handling
1385  * would greatly complicate use of the safe buffer.
1386  */
1387 static void *btf_show_obj_safe(struct btf_show *show,
1388 			       const struct btf_type *t,
1389 			       void *data)
1390 {
1391 	const struct btf_type *rt;
1392 	int size_left, size;
1393 	void *safe = NULL;
1394 
1395 	if (show->flags & BTF_SHOW_UNSAFE)
1396 		return data;
1397 
1398 	rt = btf_resolve_size(show->btf, t, &size);
1399 	if (IS_ERR(rt)) {
1400 		show->state.status = PTR_ERR(rt);
1401 		return NULL;
1402 	}
1403 
1404 	/*
1405 	 * Is this toplevel object? If so, set total object size and
1406 	 * initialize pointers.  Otherwise check if we still fall within
1407 	 * our safe object data.
1408 	 */
1409 	if (show->state.depth == 0) {
1410 		show->obj.size = size;
1411 		show->obj.head = data;
1412 	} else {
1413 		/*
1414 		 * If the size of the current object is > our remaining
1415 		 * safe buffer we _may_ need to do a new copy.  However
1416 		 * consider the case of a nested struct; it's size pushes
1417 		 * us over the safe buffer limit, but showing any individual
1418 		 * struct members does not.  In such cases, we don't need
1419 		 * to initiate a fresh copy yet; however we definitely need
1420 		 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1421 		 * in our buffer, regardless of the current object size.
1422 		 * The logic here is that as we resolve types we will
1423 		 * hit a base type at some point, and we need to be sure
1424 		 * the next chunk of data is safely available to display
1425 		 * that type info safely.  We cannot rely on the size of
1426 		 * the current object here because it may be much larger
1427 		 * than our current buffer (e.g. task_struct is 8k).
1428 		 * All we want to do here is ensure that we can print the
1429 		 * next basic type, which we can if either
1430 		 * - the current type size is within the safe buffer; or
1431 		 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1432 		 *   the safe buffer.
1433 		 */
1434 		safe = __btf_show_obj_safe(show, data,
1435 					   min(size,
1436 					       BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1437 	}
1438 
1439 	/*
1440 	 * We need a new copy to our safe object, either because we haven't
1441 	 * yet copied and are initializing safe data, or because the data
1442 	 * we want falls outside the boundaries of the safe object.
1443 	 */
1444 	if (!safe) {
1445 		size_left = btf_show_obj_size_left(show, data);
1446 		if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1447 			size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1448 		show->state.status = copy_from_kernel_nofault(show->obj.safe,
1449 							      data, size_left);
1450 		if (!show->state.status) {
1451 			show->obj.data = data;
1452 			safe = show->obj.safe;
1453 		}
1454 	}
1455 
1456 	return safe;
1457 }
1458 
1459 /*
1460  * Set the type we are starting to show and return a safe data pointer
1461  * to be used for showing the associated data.
1462  */
1463 static void *btf_show_start_type(struct btf_show *show,
1464 				 const struct btf_type *t,
1465 				 u32 type_id, void *data)
1466 {
1467 	show->state.type = t;
1468 	show->state.type_id = type_id;
1469 	show->state.name[0] = '\0';
1470 
1471 	return btf_show_obj_safe(show, t, data);
1472 }
1473 
1474 static void btf_show_end_type(struct btf_show *show)
1475 {
1476 	show->state.type = NULL;
1477 	show->state.type_id = 0;
1478 	show->state.name[0] = '\0';
1479 }
1480 
1481 static void *btf_show_start_aggr_type(struct btf_show *show,
1482 				      const struct btf_type *t,
1483 				      u32 type_id, void *data)
1484 {
1485 	void *safe_data = btf_show_start_type(show, t, type_id, data);
1486 
1487 	if (!safe_data)
1488 		return safe_data;
1489 
1490 	btf_show(show, "%s%s%s", btf_show_indent(show),
1491 		 btf_show_name(show),
1492 		 btf_show_newline(show));
1493 	show->state.depth++;
1494 	return safe_data;
1495 }
1496 
1497 static void btf_show_end_aggr_type(struct btf_show *show,
1498 				   const char *suffix)
1499 {
1500 	show->state.depth--;
1501 	btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1502 		 btf_show_delim(show), btf_show_newline(show));
1503 	btf_show_end_type(show);
1504 }
1505 
1506 static void btf_show_start_member(struct btf_show *show,
1507 				  const struct btf_member *m)
1508 {
1509 	show->state.member = m;
1510 }
1511 
1512 static void btf_show_start_array_member(struct btf_show *show)
1513 {
1514 	show->state.array_member = 1;
1515 	btf_show_start_member(show, NULL);
1516 }
1517 
1518 static void btf_show_end_member(struct btf_show *show)
1519 {
1520 	show->state.member = NULL;
1521 }
1522 
1523 static void btf_show_end_array_member(struct btf_show *show)
1524 {
1525 	show->state.array_member = 0;
1526 	btf_show_end_member(show);
1527 }
1528 
1529 static void *btf_show_start_array_type(struct btf_show *show,
1530 				       const struct btf_type *t,
1531 				       u32 type_id,
1532 				       u16 array_encoding,
1533 				       void *data)
1534 {
1535 	show->state.array_encoding = array_encoding;
1536 	show->state.array_terminated = 0;
1537 	return btf_show_start_aggr_type(show, t, type_id, data);
1538 }
1539 
1540 static void btf_show_end_array_type(struct btf_show *show)
1541 {
1542 	show->state.array_encoding = 0;
1543 	show->state.array_terminated = 0;
1544 	btf_show_end_aggr_type(show, "]");
1545 }
1546 
1547 static void *btf_show_start_struct_type(struct btf_show *show,
1548 					const struct btf_type *t,
1549 					u32 type_id,
1550 					void *data)
1551 {
1552 	return btf_show_start_aggr_type(show, t, type_id, data);
1553 }
1554 
1555 static void btf_show_end_struct_type(struct btf_show *show)
1556 {
1557 	btf_show_end_aggr_type(show, "}");
1558 }
1559 
1560 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1561 					      const char *fmt, ...)
1562 {
1563 	va_list args;
1564 
1565 	va_start(args, fmt);
1566 	bpf_verifier_vlog(log, fmt, args);
1567 	va_end(args);
1568 }
1569 
1570 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1571 					    const char *fmt, ...)
1572 {
1573 	struct bpf_verifier_log *log = &env->log;
1574 	va_list args;
1575 
1576 	if (!bpf_verifier_log_needed(log))
1577 		return;
1578 
1579 	va_start(args, fmt);
1580 	bpf_verifier_vlog(log, fmt, args);
1581 	va_end(args);
1582 }
1583 
1584 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1585 						   const struct btf_type *t,
1586 						   bool log_details,
1587 						   const char *fmt, ...)
1588 {
1589 	struct bpf_verifier_log *log = &env->log;
1590 	struct btf *btf = env->btf;
1591 	va_list args;
1592 
1593 	if (!bpf_verifier_log_needed(log))
1594 		return;
1595 
1596 	if (log->level == BPF_LOG_KERNEL) {
1597 		/* btf verifier prints all types it is processing via
1598 		 * btf_verifier_log_type(..., fmt = NULL).
1599 		 * Skip those prints for in-kernel BTF verification.
1600 		 */
1601 		if (!fmt)
1602 			return;
1603 
1604 		/* Skip logging when loading module BTF with mismatches permitted */
1605 		if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1606 			return;
1607 	}
1608 
1609 	__btf_verifier_log(log, "[%u] %s %s%s",
1610 			   env->log_type_id,
1611 			   btf_type_str(t),
1612 			   __btf_name_by_offset(btf, t->name_off),
1613 			   log_details ? " " : "");
1614 
1615 	if (log_details)
1616 		btf_type_ops(t)->log_details(env, t);
1617 
1618 	if (fmt && *fmt) {
1619 		__btf_verifier_log(log, " ");
1620 		va_start(args, fmt);
1621 		bpf_verifier_vlog(log, fmt, args);
1622 		va_end(args);
1623 	}
1624 
1625 	__btf_verifier_log(log, "\n");
1626 }
1627 
1628 #define btf_verifier_log_type(env, t, ...) \
1629 	__btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1630 #define btf_verifier_log_basic(env, t, ...) \
1631 	__btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1632 
1633 __printf(4, 5)
1634 static void btf_verifier_log_member(struct btf_verifier_env *env,
1635 				    const struct btf_type *struct_type,
1636 				    const struct btf_member *member,
1637 				    const char *fmt, ...)
1638 {
1639 	struct bpf_verifier_log *log = &env->log;
1640 	struct btf *btf = env->btf;
1641 	va_list args;
1642 
1643 	if (!bpf_verifier_log_needed(log))
1644 		return;
1645 
1646 	if (log->level == BPF_LOG_KERNEL) {
1647 		if (!fmt)
1648 			return;
1649 
1650 		/* Skip logging when loading module BTF with mismatches permitted */
1651 		if (env->btf->base_btf && IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH))
1652 			return;
1653 	}
1654 
1655 	/* The CHECK_META phase already did a btf dump.
1656 	 *
1657 	 * If member is logged again, it must hit an error in
1658 	 * parsing this member.  It is useful to print out which
1659 	 * struct this member belongs to.
1660 	 */
1661 	if (env->phase != CHECK_META)
1662 		btf_verifier_log_type(env, struct_type, NULL);
1663 
1664 	if (btf_type_kflag(struct_type))
1665 		__btf_verifier_log(log,
1666 				   "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1667 				   __btf_name_by_offset(btf, member->name_off),
1668 				   member->type,
1669 				   BTF_MEMBER_BITFIELD_SIZE(member->offset),
1670 				   BTF_MEMBER_BIT_OFFSET(member->offset));
1671 	else
1672 		__btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1673 				   __btf_name_by_offset(btf, member->name_off),
1674 				   member->type, member->offset);
1675 
1676 	if (fmt && *fmt) {
1677 		__btf_verifier_log(log, " ");
1678 		va_start(args, fmt);
1679 		bpf_verifier_vlog(log, fmt, args);
1680 		va_end(args);
1681 	}
1682 
1683 	__btf_verifier_log(log, "\n");
1684 }
1685 
1686 __printf(4, 5)
1687 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1688 				 const struct btf_type *datasec_type,
1689 				 const struct btf_var_secinfo *vsi,
1690 				 const char *fmt, ...)
1691 {
1692 	struct bpf_verifier_log *log = &env->log;
1693 	va_list args;
1694 
1695 	if (!bpf_verifier_log_needed(log))
1696 		return;
1697 	if (log->level == BPF_LOG_KERNEL && !fmt)
1698 		return;
1699 	if (env->phase != CHECK_META)
1700 		btf_verifier_log_type(env, datasec_type, NULL);
1701 
1702 	__btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1703 			   vsi->type, vsi->offset, vsi->size);
1704 	if (fmt && *fmt) {
1705 		__btf_verifier_log(log, " ");
1706 		va_start(args, fmt);
1707 		bpf_verifier_vlog(log, fmt, args);
1708 		va_end(args);
1709 	}
1710 
1711 	__btf_verifier_log(log, "\n");
1712 }
1713 
1714 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1715 				 u32 btf_data_size)
1716 {
1717 	struct bpf_verifier_log *log = &env->log;
1718 	const struct btf *btf = env->btf;
1719 	const struct btf_header *hdr;
1720 
1721 	if (!bpf_verifier_log_needed(log))
1722 		return;
1723 
1724 	if (log->level == BPF_LOG_KERNEL)
1725 		return;
1726 	hdr = &btf->hdr;
1727 	__btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1728 	__btf_verifier_log(log, "version: %u\n", hdr->version);
1729 	__btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1730 	__btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1731 	__btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1732 	__btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1733 	__btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1734 	__btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1735 	if (hdr->hdr_len >= sizeof(struct btf_header) &&
1736 	    btf_data_size >= hdr->hdr_len) {
1737 		__btf_verifier_log(log, "layout_off: %u\n", hdr->layout_off);
1738 		__btf_verifier_log(log, "layout_len: %u\n", hdr->layout_len);
1739 	}
1740 	__btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1741 }
1742 
1743 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1744 {
1745 	struct btf *btf = env->btf;
1746 
1747 	if (btf->types_size == btf->nr_types) {
1748 		/* Expand 'types' array */
1749 
1750 		struct btf_type **new_types;
1751 		u32 expand_by, new_size;
1752 
1753 		if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1754 			btf_verifier_log(env, "Exceeded max num of types");
1755 			return -E2BIG;
1756 		}
1757 
1758 		expand_by = max_t(u32, btf->types_size >> 2, 16);
1759 		new_size = min_t(u32, BTF_MAX_TYPE,
1760 				 btf->types_size + expand_by);
1761 
1762 		new_types = kvzalloc_objs(*new_types, new_size,
1763 					  GFP_KERNEL | __GFP_NOWARN);
1764 		if (!new_types)
1765 			return -ENOMEM;
1766 
1767 		if (btf->nr_types == 0) {
1768 			if (!btf->base_btf) {
1769 				/* lazily init VOID type */
1770 				new_types[0] = &btf_void;
1771 				btf->nr_types++;
1772 			}
1773 		} else {
1774 			memcpy(new_types, btf->types,
1775 			       sizeof(*btf->types) * btf->nr_types);
1776 		}
1777 
1778 		kvfree(btf->types);
1779 		btf->types = new_types;
1780 		btf->types_size = new_size;
1781 	}
1782 
1783 	btf->types[btf->nr_types++] = t;
1784 
1785 	return 0;
1786 }
1787 
1788 static int btf_alloc_id(struct btf *btf)
1789 {
1790 	int id;
1791 
1792 	idr_preload(GFP_KERNEL);
1793 	spin_lock_bh(&btf_idr_lock);
1794 	id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1795 	if (id > 0)
1796 		btf->id = id;
1797 	spin_unlock_bh(&btf_idr_lock);
1798 	idr_preload_end();
1799 
1800 	if (WARN_ON_ONCE(!id))
1801 		return -ENOSPC;
1802 
1803 	return id > 0 ? 0 : id;
1804 }
1805 
1806 static void btf_free_id(struct btf *btf)
1807 {
1808 	unsigned long flags;
1809 
1810 	/*
1811 	 * In map-in-map, calling map_delete_elem() on outer
1812 	 * map will call bpf_map_put on the inner map.
1813 	 * It will then eventually call btf_free_id()
1814 	 * on the inner map.  Some of the map_delete_elem()
1815 	 * implementation may have irq disabled, so
1816 	 * we need to use the _irqsave() version instead
1817 	 * of the _bh() version.
1818 	 */
1819 	spin_lock_irqsave(&btf_idr_lock, flags);
1820 	if (btf->id) {
1821 		idr_remove(&btf_idr, btf->id);
1822 		/*
1823 		 * Clear the id here to make this function idempotent, since it will get
1824 		 * called a couple of times for module BTFs: on module unload, and then
1825 		 * the final btf_put(). btf_alloc_id() starts IDs with 1, so we can use
1826 		 * 0 as sentinel value.
1827 		 */
1828 		WRITE_ONCE(btf->id, 0);
1829 	}
1830 	spin_unlock_irqrestore(&btf_idr_lock, flags);
1831 }
1832 
1833 static void btf_free_kfunc_set_tab(struct btf *btf)
1834 {
1835 	struct btf_kfunc_set_tab *tab = btf->kfunc_set_tab;
1836 	int hook;
1837 
1838 	if (!tab)
1839 		return;
1840 	for (hook = 0; hook < ARRAY_SIZE(tab->sets); hook++)
1841 		kfree(tab->sets[hook]);
1842 	kfree(tab);
1843 	btf->kfunc_set_tab = NULL;
1844 }
1845 
1846 static void btf_free_dtor_kfunc_tab(struct btf *btf)
1847 {
1848 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
1849 
1850 	if (!tab)
1851 		return;
1852 	kfree(tab);
1853 	btf->dtor_kfunc_tab = NULL;
1854 }
1855 
1856 static void btf_struct_metas_free(struct btf_struct_metas *tab)
1857 {
1858 	int i;
1859 
1860 	if (!tab)
1861 		return;
1862 	for (i = 0; i < tab->cnt; i++)
1863 		btf_record_free(tab->types[i].record);
1864 	kfree(tab);
1865 }
1866 
1867 static void btf_free_struct_meta_tab(struct btf *btf)
1868 {
1869 	struct btf_struct_metas *tab = btf->struct_meta_tab;
1870 
1871 	btf_struct_metas_free(tab);
1872 	btf->struct_meta_tab = NULL;
1873 }
1874 
1875 static void btf_free_struct_ops_tab(struct btf *btf)
1876 {
1877 	struct btf_struct_ops_tab *tab = btf->struct_ops_tab;
1878 	u32 i;
1879 
1880 	if (!tab)
1881 		return;
1882 
1883 	for (i = 0; i < tab->cnt; i++)
1884 		bpf_struct_ops_desc_release(&tab->ops[i]);
1885 
1886 	kfree(tab);
1887 	btf->struct_ops_tab = NULL;
1888 }
1889 
1890 static void btf_free(struct btf *btf)
1891 {
1892 	btf_free_struct_meta_tab(btf);
1893 	btf_free_dtor_kfunc_tab(btf);
1894 	btf_free_kfunc_set_tab(btf);
1895 	btf_free_struct_ops_tab(btf);
1896 	kvfree(btf->types);
1897 	kvfree(btf->resolved_sizes);
1898 	kvfree(btf->resolved_ids);
1899 	/* vmlinux does not allocate btf->data, it simply points it at
1900 	 * __start_BTF.
1901 	 */
1902 	if (!btf_is_vmlinux(btf))
1903 		kvfree(btf->data);
1904 	kvfree(btf->base_id_map);
1905 	kfree(btf);
1906 }
1907 
1908 static void btf_free_rcu(struct rcu_head *rcu)
1909 {
1910 	struct btf *btf = container_of(rcu, struct btf, rcu);
1911 
1912 	btf_free(btf);
1913 }
1914 
1915 const char *btf_get_name(const struct btf *btf)
1916 {
1917 	return btf->name;
1918 }
1919 
1920 void btf_get(struct btf *btf)
1921 {
1922 	refcount_inc(&btf->refcnt);
1923 }
1924 
1925 void btf_put(struct btf *btf)
1926 {
1927 	if (btf && refcount_dec_and_test(&btf->refcnt)) {
1928 		btf_free_id(btf);
1929 		call_rcu(&btf->rcu, btf_free_rcu);
1930 	}
1931 }
1932 
1933 struct btf *btf_base_btf(const struct btf *btf)
1934 {
1935 	return btf->base_btf;
1936 }
1937 
1938 const struct btf_header *btf_header(const struct btf *btf)
1939 {
1940 	return &btf->hdr;
1941 }
1942 
1943 void btf_set_base_btf(struct btf *btf, const struct btf *base_btf)
1944 {
1945 	btf->base_btf = (struct btf *)base_btf;
1946 	btf->start_id = btf_nr_types(base_btf);
1947 	btf->start_str_off = base_btf->hdr.str_len;
1948 }
1949 
1950 static int env_resolve_init(struct btf_verifier_env *env)
1951 {
1952 	struct btf *btf = env->btf;
1953 	u32 nr_types = btf->nr_types;
1954 	u32 *resolved_sizes = NULL;
1955 	u32 *resolved_ids = NULL;
1956 	u8 *visit_states = NULL;
1957 
1958 	resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1959 				  GFP_KERNEL | __GFP_NOWARN);
1960 	if (!resolved_sizes)
1961 		goto nomem;
1962 
1963 	resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1964 				GFP_KERNEL | __GFP_NOWARN);
1965 	if (!resolved_ids)
1966 		goto nomem;
1967 
1968 	visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1969 				GFP_KERNEL | __GFP_NOWARN);
1970 	if (!visit_states)
1971 		goto nomem;
1972 
1973 	btf->resolved_sizes = resolved_sizes;
1974 	btf->resolved_ids = resolved_ids;
1975 	env->visit_states = visit_states;
1976 
1977 	return 0;
1978 
1979 nomem:
1980 	kvfree(resolved_sizes);
1981 	kvfree(resolved_ids);
1982 	kvfree(visit_states);
1983 	return -ENOMEM;
1984 }
1985 
1986 static void btf_verifier_env_free(struct btf_verifier_env *env)
1987 {
1988 	kvfree(env->visit_states);
1989 	kfree(env);
1990 }
1991 
1992 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1993 				     const struct btf_type *next_type)
1994 {
1995 	switch (env->resolve_mode) {
1996 	case RESOLVE_TBD:
1997 		/* int, enum or void is a sink */
1998 		return !btf_type_needs_resolve(next_type);
1999 	case RESOLVE_PTR:
2000 		/* int, enum, void, struct, array, func or func_proto is a sink
2001 		 * for ptr
2002 		 */
2003 		return !btf_type_is_modifier(next_type) &&
2004 			!btf_type_is_ptr(next_type);
2005 	case RESOLVE_STRUCT_OR_ARRAY:
2006 		/* int, enum, void, ptr, func or func_proto is a sink
2007 		 * for struct and array
2008 		 */
2009 		return !btf_type_is_modifier(next_type) &&
2010 			!btf_type_is_array(next_type) &&
2011 			!btf_type_is_struct(next_type);
2012 	default:
2013 		BUG();
2014 	}
2015 }
2016 
2017 static bool env_type_is_resolved(const struct btf_verifier_env *env,
2018 				 u32 type_id)
2019 {
2020 	/* base BTF types should be resolved by now */
2021 	if (type_id < env->btf->start_id)
2022 		return true;
2023 
2024 	return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
2025 }
2026 
2027 static int env_stack_push(struct btf_verifier_env *env,
2028 			  const struct btf_type *t, u32 type_id)
2029 {
2030 	const struct btf *btf = env->btf;
2031 	struct resolve_vertex *v;
2032 
2033 	if (env->top_stack == MAX_RESOLVE_DEPTH)
2034 		return -E2BIG;
2035 
2036 	if (type_id < btf->start_id
2037 	    || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
2038 		return -EEXIST;
2039 
2040 	env->visit_states[type_id - btf->start_id] = VISITED;
2041 
2042 	v = &env->stack[env->top_stack++];
2043 	v->t = t;
2044 	v->type_id = type_id;
2045 	v->next_member = 0;
2046 
2047 	if (env->resolve_mode == RESOLVE_TBD) {
2048 		if (btf_type_is_ptr(t))
2049 			env->resolve_mode = RESOLVE_PTR;
2050 		else if (btf_type_is_struct(t) || btf_type_is_array(t))
2051 			env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
2052 	}
2053 
2054 	return 0;
2055 }
2056 
2057 static void env_stack_set_next_member(struct btf_verifier_env *env,
2058 				      u32 next_member)
2059 {
2060 	env->stack[env->top_stack - 1].next_member = next_member;
2061 }
2062 
2063 static void env_stack_pop_resolved(struct btf_verifier_env *env,
2064 				   u32 resolved_type_id,
2065 				   u32 resolved_size)
2066 {
2067 	u32 type_id = env->stack[--(env->top_stack)].type_id;
2068 	struct btf *btf = env->btf;
2069 
2070 	type_id -= btf->start_id; /* adjust to local type id */
2071 	btf->resolved_sizes[type_id] = resolved_size;
2072 	btf->resolved_ids[type_id] = resolved_type_id;
2073 	env->visit_states[type_id] = RESOLVED;
2074 }
2075 
2076 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
2077 {
2078 	return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
2079 }
2080 
2081 /* Resolve the size of a passed-in "type"
2082  *
2083  * type: is an array (e.g. u32 array[x][y])
2084  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
2085  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
2086  *             corresponds to the return type.
2087  * *elem_type: u32
2088  * *elem_id: id of u32
2089  * *total_nelems: (x * y).  Hence, individual elem size is
2090  *                (*type_size / *total_nelems)
2091  * *type_id: id of type if it's changed within the function, 0 if not
2092  *
2093  * type: is not an array (e.g. const struct X)
2094  * return type: type "struct X"
2095  * *type_size: sizeof(struct X)
2096  * *elem_type: same as return type ("struct X")
2097  * *elem_id: 0
2098  * *total_nelems: 1
2099  * *type_id: id of type if it's changed within the function, 0 if not
2100  */
2101 static const struct btf_type *
2102 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
2103 		   u32 *type_size, const struct btf_type **elem_type,
2104 		   u32 *elem_id, u32 *total_nelems, u32 *type_id)
2105 {
2106 	const struct btf_type *array_type = NULL;
2107 	const struct btf_array *array = NULL;
2108 	u32 i, size, nelems = 1, id = 0;
2109 
2110 	for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
2111 		switch (BTF_INFO_KIND(type->info)) {
2112 		/* type->size can be used */
2113 		case BTF_KIND_INT:
2114 		case BTF_KIND_STRUCT:
2115 		case BTF_KIND_UNION:
2116 		case BTF_KIND_ENUM:
2117 		case BTF_KIND_FLOAT:
2118 		case BTF_KIND_ENUM64:
2119 			size = type->size;
2120 			goto resolved;
2121 
2122 		case BTF_KIND_PTR:
2123 			size = sizeof(void *);
2124 			goto resolved;
2125 
2126 		/* Modifiers */
2127 		case BTF_KIND_TYPEDEF:
2128 		case BTF_KIND_VOLATILE:
2129 		case BTF_KIND_CONST:
2130 		case BTF_KIND_RESTRICT:
2131 		case BTF_KIND_TYPE_TAG:
2132 			id = type->type;
2133 			type = btf_type_by_id(btf, type->type);
2134 			break;
2135 
2136 		case BTF_KIND_ARRAY:
2137 			if (!array_type)
2138 				array_type = type;
2139 			array = btf_type_array(type);
2140 			if (nelems && array->nelems > U32_MAX / nelems)
2141 				return ERR_PTR(-EINVAL);
2142 			nelems *= array->nelems;
2143 			type = btf_type_by_id(btf, array->type);
2144 			break;
2145 
2146 		/* type without size */
2147 		default:
2148 			return ERR_PTR(-EINVAL);
2149 		}
2150 	}
2151 
2152 	return ERR_PTR(-EINVAL);
2153 
2154 resolved:
2155 	if (nelems && size > U32_MAX / nelems)
2156 		return ERR_PTR(-EINVAL);
2157 
2158 	*type_size = nelems * size;
2159 	if (total_nelems)
2160 		*total_nelems = nelems;
2161 	if (elem_type)
2162 		*elem_type = type;
2163 	if (elem_id)
2164 		*elem_id = array ? array->type : 0;
2165 	if (type_id && id)
2166 		*type_id = id;
2167 
2168 	return array_type ? : type;
2169 }
2170 
2171 const struct btf_type *
2172 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
2173 		 u32 *type_size)
2174 {
2175 	return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
2176 }
2177 
2178 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
2179 {
2180 	while (type_id < btf->start_id)
2181 		btf = btf->base_btf;
2182 
2183 	return btf->resolved_ids[type_id - btf->start_id];
2184 }
2185 
2186 /* The input param "type_id" must point to a needs_resolve type */
2187 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
2188 						  u32 *type_id)
2189 {
2190 	*type_id = btf_resolved_type_id(btf, *type_id);
2191 	return btf_type_by_id(btf, *type_id);
2192 }
2193 
2194 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
2195 {
2196 	while (type_id < btf->start_id)
2197 		btf = btf->base_btf;
2198 
2199 	return btf->resolved_sizes[type_id - btf->start_id];
2200 }
2201 
2202 const struct btf_type *btf_type_id_size(const struct btf *btf,
2203 					u32 *type_id, u32 *ret_size)
2204 {
2205 	const struct btf_type *size_type;
2206 	u32 size_type_id = *type_id;
2207 	u32 size = 0;
2208 
2209 	size_type = btf_type_by_id(btf, size_type_id);
2210 	if (btf_type_nosize_or_null(size_type))
2211 		return NULL;
2212 
2213 	if (btf_type_has_size(size_type)) {
2214 		size = size_type->size;
2215 	} else if (btf_type_is_array(size_type)) {
2216 		size = btf_resolved_type_size(btf, size_type_id);
2217 	} else if (btf_type_is_ptr(size_type)) {
2218 		size = sizeof(void *);
2219 	} else {
2220 		if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
2221 				 !btf_type_is_var(size_type)))
2222 			return NULL;
2223 
2224 		size_type_id = btf_resolved_type_id(btf, size_type_id);
2225 		size_type = btf_type_by_id(btf, size_type_id);
2226 		if (btf_type_nosize_or_null(size_type))
2227 			return NULL;
2228 		else if (btf_type_has_size(size_type))
2229 			size = size_type->size;
2230 		else if (btf_type_is_array(size_type))
2231 			size = btf_resolved_type_size(btf, size_type_id);
2232 		else if (btf_type_is_ptr(size_type))
2233 			size = sizeof(void *);
2234 		else
2235 			return NULL;
2236 	}
2237 
2238 	*type_id = size_type_id;
2239 	if (ret_size)
2240 		*ret_size = size;
2241 
2242 	return size_type;
2243 }
2244 
2245 static int btf_df_check_member(struct btf_verifier_env *env,
2246 			       const struct btf_type *struct_type,
2247 			       const struct btf_member *member,
2248 			       const struct btf_type *member_type)
2249 {
2250 	btf_verifier_log_basic(env, struct_type,
2251 			       "Unsupported check_member");
2252 	return -EINVAL;
2253 }
2254 
2255 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
2256 				     const struct btf_type *struct_type,
2257 				     const struct btf_member *member,
2258 				     const struct btf_type *member_type)
2259 {
2260 	btf_verifier_log_basic(env, struct_type,
2261 			       "Unsupported check_kflag_member");
2262 	return -EINVAL;
2263 }
2264 
2265 /* Used for ptr, array struct/union and float type members.
2266  * int, enum and modifier types have their specific callback functions.
2267  */
2268 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
2269 					  const struct btf_type *struct_type,
2270 					  const struct btf_member *member,
2271 					  const struct btf_type *member_type)
2272 {
2273 	if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
2274 		btf_verifier_log_member(env, struct_type, member,
2275 					"Invalid member bitfield_size");
2276 		return -EINVAL;
2277 	}
2278 
2279 	/* bitfield size is 0, so member->offset represents bit offset only.
2280 	 * It is safe to call non kflag check_member variants.
2281 	 */
2282 	return btf_type_ops(member_type)->check_member(env, struct_type,
2283 						       member,
2284 						       member_type);
2285 }
2286 
2287 static int btf_df_resolve(struct btf_verifier_env *env,
2288 			  const struct resolve_vertex *v)
2289 {
2290 	btf_verifier_log_basic(env, v->t, "Unsupported resolve");
2291 	return -EINVAL;
2292 }
2293 
2294 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
2295 			u32 type_id, void *data, u8 bits_offsets,
2296 			struct btf_show *show)
2297 {
2298 	btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
2299 }
2300 
2301 static int btf_int_check_member(struct btf_verifier_env *env,
2302 				const struct btf_type *struct_type,
2303 				const struct btf_member *member,
2304 				const struct btf_type *member_type)
2305 {
2306 	u32 int_data = btf_type_int(member_type);
2307 	u32 struct_bits_off = member->offset;
2308 	u32 struct_size = struct_type->size;
2309 	u32 nr_copy_bits;
2310 	u32 bytes_offset;
2311 
2312 	if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
2313 		btf_verifier_log_member(env, struct_type, member,
2314 					"bits_offset exceeds U32_MAX");
2315 		return -EINVAL;
2316 	}
2317 
2318 	struct_bits_off += BTF_INT_OFFSET(int_data);
2319 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2320 	nr_copy_bits = BTF_INT_BITS(int_data) +
2321 		BITS_PER_BYTE_MASKED(struct_bits_off);
2322 
2323 	if (nr_copy_bits > BITS_PER_U128) {
2324 		btf_verifier_log_member(env, struct_type, member,
2325 					"nr_copy_bits exceeds 128");
2326 		return -EINVAL;
2327 	}
2328 
2329 	if (struct_size < bytes_offset ||
2330 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2331 		btf_verifier_log_member(env, struct_type, member,
2332 					"Member exceeds struct_size");
2333 		return -EINVAL;
2334 	}
2335 
2336 	return 0;
2337 }
2338 
2339 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
2340 				      const struct btf_type *struct_type,
2341 				      const struct btf_member *member,
2342 				      const struct btf_type *member_type)
2343 {
2344 	u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
2345 	u32 int_data = btf_type_int(member_type);
2346 	u32 struct_size = struct_type->size;
2347 	u32 nr_copy_bits;
2348 
2349 	/* a regular int type is required for the kflag int member */
2350 	if (!btf_type_int_is_regular(member_type)) {
2351 		btf_verifier_log_member(env, struct_type, member,
2352 					"Invalid member base type");
2353 		return -EINVAL;
2354 	}
2355 
2356 	/* check sanity of bitfield size */
2357 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
2358 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
2359 	nr_int_data_bits = BTF_INT_BITS(int_data);
2360 	if (!nr_bits) {
2361 		/* Not a bitfield member, member offset must be at byte
2362 		 * boundary.
2363 		 */
2364 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2365 			btf_verifier_log_member(env, struct_type, member,
2366 						"Invalid member offset");
2367 			return -EINVAL;
2368 		}
2369 
2370 		nr_bits = nr_int_data_bits;
2371 	} else if (nr_bits > nr_int_data_bits) {
2372 		btf_verifier_log_member(env, struct_type, member,
2373 					"Invalid member bitfield_size");
2374 		return -EINVAL;
2375 	}
2376 
2377 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2378 	nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
2379 	if (nr_copy_bits > BITS_PER_U128) {
2380 		btf_verifier_log_member(env, struct_type, member,
2381 					"nr_copy_bits exceeds 128");
2382 		return -EINVAL;
2383 	}
2384 
2385 	if (struct_size < bytes_offset ||
2386 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
2387 		btf_verifier_log_member(env, struct_type, member,
2388 					"Member exceeds struct_size");
2389 		return -EINVAL;
2390 	}
2391 
2392 	return 0;
2393 }
2394 
2395 static s32 btf_int_check_meta(struct btf_verifier_env *env,
2396 			      const struct btf_type *t,
2397 			      u32 meta_left)
2398 {
2399 	u32 int_data, nr_bits, meta_needed = sizeof(int_data);
2400 	u16 encoding;
2401 
2402 	if (meta_left < meta_needed) {
2403 		btf_verifier_log_basic(env, t,
2404 				       "meta_left:%u meta_needed:%u",
2405 				       meta_left, meta_needed);
2406 		return -EINVAL;
2407 	}
2408 
2409 	if (btf_type_vlen(t)) {
2410 		btf_verifier_log_type(env, t, "vlen != 0");
2411 		return -EINVAL;
2412 	}
2413 
2414 	if (btf_type_kflag(t)) {
2415 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2416 		return -EINVAL;
2417 	}
2418 
2419 	int_data = btf_type_int(t);
2420 	if (int_data & ~BTF_INT_MASK) {
2421 		btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2422 				       int_data);
2423 		return -EINVAL;
2424 	}
2425 
2426 	nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2427 
2428 	if (nr_bits > BITS_PER_U128) {
2429 		btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2430 				      BITS_PER_U128);
2431 		return -EINVAL;
2432 	}
2433 
2434 	if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2435 		btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2436 		return -EINVAL;
2437 	}
2438 
2439 	/*
2440 	 * Only one of the encoding bits is allowed and it
2441 	 * should be sufficient for the pretty print purpose (i.e. decoding).
2442 	 * Multiple bits can be allowed later if it is found
2443 	 * to be insufficient.
2444 	 */
2445 	encoding = BTF_INT_ENCODING(int_data);
2446 	if (encoding &&
2447 	    encoding != BTF_INT_SIGNED &&
2448 	    encoding != BTF_INT_CHAR &&
2449 	    encoding != BTF_INT_BOOL) {
2450 		btf_verifier_log_type(env, t, "Unsupported encoding");
2451 		return -ENOTSUPP;
2452 	}
2453 
2454 	btf_verifier_log_type(env, t, NULL);
2455 
2456 	return meta_needed;
2457 }
2458 
2459 static void btf_int_log(struct btf_verifier_env *env,
2460 			const struct btf_type *t)
2461 {
2462 	int int_data = btf_type_int(t);
2463 
2464 	btf_verifier_log(env,
2465 			 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2466 			 t->size, BTF_INT_OFFSET(int_data),
2467 			 BTF_INT_BITS(int_data),
2468 			 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2469 }
2470 
2471 static void btf_int128_print(struct btf_show *show, void *data)
2472 {
2473 	/* data points to a __int128 number.
2474 	 * Suppose
2475 	 *     int128_num = *(__int128 *)data;
2476 	 * The below formulas shows what upper_num and lower_num represents:
2477 	 *     upper_num = int128_num >> 64;
2478 	 *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2479 	 */
2480 	u64 upper_num, lower_num;
2481 
2482 #ifdef __BIG_ENDIAN_BITFIELD
2483 	upper_num = *(u64 *)data;
2484 	lower_num = *(u64 *)(data + 8);
2485 #else
2486 	upper_num = *(u64 *)(data + 8);
2487 	lower_num = *(u64 *)data;
2488 #endif
2489 	if (upper_num == 0)
2490 		btf_show_type_value(show, "0x%llx", lower_num);
2491 	else
2492 		btf_show_type_values(show, "0x%llx%016llx", upper_num,
2493 				     lower_num);
2494 }
2495 
2496 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2497 			     u16 right_shift_bits)
2498 {
2499 	u64 upper_num, lower_num;
2500 
2501 #ifdef __BIG_ENDIAN_BITFIELD
2502 	upper_num = print_num[0];
2503 	lower_num = print_num[1];
2504 #else
2505 	upper_num = print_num[1];
2506 	lower_num = print_num[0];
2507 #endif
2508 
2509 	/* shake out un-needed bits by shift/or operations */
2510 	if (left_shift_bits >= 64) {
2511 		upper_num = lower_num << (left_shift_bits - 64);
2512 		lower_num = 0;
2513 	} else {
2514 		upper_num = (upper_num << left_shift_bits) |
2515 			    (lower_num >> (64 - left_shift_bits));
2516 		lower_num = lower_num << left_shift_bits;
2517 	}
2518 
2519 	if (right_shift_bits >= 64) {
2520 		lower_num = upper_num >> (right_shift_bits - 64);
2521 		upper_num = 0;
2522 	} else {
2523 		lower_num = (lower_num >> right_shift_bits) |
2524 			    (upper_num << (64 - right_shift_bits));
2525 		upper_num = upper_num >> right_shift_bits;
2526 	}
2527 
2528 #ifdef __BIG_ENDIAN_BITFIELD
2529 	print_num[0] = upper_num;
2530 	print_num[1] = lower_num;
2531 #else
2532 	print_num[0] = lower_num;
2533 	print_num[1] = upper_num;
2534 #endif
2535 }
2536 
2537 static void btf_bitfield_show(void *data, u8 bits_offset,
2538 			      u8 nr_bits, struct btf_show *show)
2539 {
2540 	u16 left_shift_bits, right_shift_bits;
2541 	u8 nr_copy_bytes;
2542 	u8 nr_copy_bits;
2543 	u64 print_num[2] = {};
2544 
2545 	nr_copy_bits = nr_bits + bits_offset;
2546 	nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2547 
2548 	memcpy(print_num, data, nr_copy_bytes);
2549 
2550 #ifdef __BIG_ENDIAN_BITFIELD
2551 	left_shift_bits = bits_offset;
2552 #else
2553 	left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2554 #endif
2555 	right_shift_bits = BITS_PER_U128 - nr_bits;
2556 
2557 	btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2558 	btf_int128_print(show, print_num);
2559 }
2560 
2561 static void btf_int_bits_show(const struct btf *btf,
2562 			      const struct btf_type *t,
2563 			      void *data, u8 bits_offset,
2564 			      struct btf_show *show)
2565 {
2566 	u32 int_data = btf_type_int(t);
2567 	u8 nr_bits = BTF_INT_BITS(int_data);
2568 	u8 total_bits_offset;
2569 
2570 	/*
2571 	 * bits_offset is at most 7.
2572 	 * BTF_INT_OFFSET() cannot exceed 128 bits.
2573 	 */
2574 	total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2575 	data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2576 	bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2577 	btf_bitfield_show(data, bits_offset, nr_bits, show);
2578 }
2579 
2580 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2581 			 u32 type_id, void *data, u8 bits_offset,
2582 			 struct btf_show *show)
2583 {
2584 	u32 int_data = btf_type_int(t);
2585 	u8 encoding = BTF_INT_ENCODING(int_data);
2586 	bool sign = encoding & BTF_INT_SIGNED;
2587 	u8 nr_bits = BTF_INT_BITS(int_data);
2588 	void *safe_data;
2589 
2590 	safe_data = btf_show_start_type(show, t, type_id, data);
2591 	if (!safe_data)
2592 		return;
2593 
2594 	if (bits_offset || BTF_INT_OFFSET(int_data) ||
2595 	    BITS_PER_BYTE_MASKED(nr_bits)) {
2596 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2597 		goto out;
2598 	}
2599 
2600 	switch (nr_bits) {
2601 	case 128:
2602 		btf_int128_print(show, safe_data);
2603 		break;
2604 	case 64:
2605 		if (sign)
2606 			btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2607 		else
2608 			btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2609 		break;
2610 	case 32:
2611 		if (sign)
2612 			btf_show_type_value(show, "%d", *(s32 *)safe_data);
2613 		else
2614 			btf_show_type_value(show, "%u", *(u32 *)safe_data);
2615 		break;
2616 	case 16:
2617 		if (sign)
2618 			btf_show_type_value(show, "%d", *(s16 *)safe_data);
2619 		else
2620 			btf_show_type_value(show, "%u", *(u16 *)safe_data);
2621 		break;
2622 	case 8:
2623 		if (show->state.array_encoding == BTF_INT_CHAR) {
2624 			/* check for null terminator */
2625 			if (show->state.array_terminated)
2626 				break;
2627 			if (*(char *)data == '\0') {
2628 				show->state.array_terminated = 1;
2629 				break;
2630 			}
2631 			if (isprint(*(char *)data)) {
2632 				btf_show_type_value(show, "'%c'",
2633 						    *(char *)safe_data);
2634 				break;
2635 			}
2636 		}
2637 		if (sign)
2638 			btf_show_type_value(show, "%d", *(s8 *)safe_data);
2639 		else
2640 			btf_show_type_value(show, "%u", *(u8 *)safe_data);
2641 		break;
2642 	default:
2643 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2644 		break;
2645 	}
2646 out:
2647 	btf_show_end_type(show);
2648 }
2649 
2650 static const struct btf_kind_operations int_ops = {
2651 	.check_meta = btf_int_check_meta,
2652 	.resolve = btf_df_resolve,
2653 	.check_member = btf_int_check_member,
2654 	.check_kflag_member = btf_int_check_kflag_member,
2655 	.log_details = btf_int_log,
2656 	.show = btf_int_show,
2657 };
2658 
2659 static int btf_modifier_check_member(struct btf_verifier_env *env,
2660 				     const struct btf_type *struct_type,
2661 				     const struct btf_member *member,
2662 				     const struct btf_type *member_type)
2663 {
2664 	const struct btf_type *resolved_type;
2665 	u32 resolved_type_id = member->type;
2666 	struct btf_member resolved_member;
2667 	struct btf *btf = env->btf;
2668 
2669 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2670 	if (!resolved_type) {
2671 		btf_verifier_log_member(env, struct_type, member,
2672 					"Invalid member");
2673 		return -EINVAL;
2674 	}
2675 
2676 	resolved_member = *member;
2677 	resolved_member.type = resolved_type_id;
2678 
2679 	return btf_type_ops(resolved_type)->check_member(env, struct_type,
2680 							 &resolved_member,
2681 							 resolved_type);
2682 }
2683 
2684 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2685 					   const struct btf_type *struct_type,
2686 					   const struct btf_member *member,
2687 					   const struct btf_type *member_type)
2688 {
2689 	const struct btf_type *resolved_type;
2690 	u32 resolved_type_id = member->type;
2691 	struct btf_member resolved_member;
2692 	struct btf *btf = env->btf;
2693 
2694 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2695 	if (!resolved_type) {
2696 		btf_verifier_log_member(env, struct_type, member,
2697 					"Invalid member");
2698 		return -EINVAL;
2699 	}
2700 
2701 	resolved_member = *member;
2702 	resolved_member.type = resolved_type_id;
2703 
2704 	return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2705 							       &resolved_member,
2706 							       resolved_type);
2707 }
2708 
2709 static int btf_ptr_check_member(struct btf_verifier_env *env,
2710 				const struct btf_type *struct_type,
2711 				const struct btf_member *member,
2712 				const struct btf_type *member_type)
2713 {
2714 	u32 struct_size, struct_bits_off, bytes_offset;
2715 
2716 	struct_size = struct_type->size;
2717 	struct_bits_off = member->offset;
2718 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2719 
2720 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2721 		btf_verifier_log_member(env, struct_type, member,
2722 					"Member is not byte aligned");
2723 		return -EINVAL;
2724 	}
2725 
2726 	if (struct_size - bytes_offset < sizeof(void *)) {
2727 		btf_verifier_log_member(env, struct_type, member,
2728 					"Member exceeds struct_size");
2729 		return -EINVAL;
2730 	}
2731 
2732 	return 0;
2733 }
2734 
2735 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2736 				   const struct btf_type *t,
2737 				   u32 meta_left)
2738 {
2739 	const char *value;
2740 
2741 	if (btf_type_vlen(t)) {
2742 		btf_verifier_log_type(env, t, "vlen != 0");
2743 		return -EINVAL;
2744 	}
2745 
2746 	if (btf_type_kflag(t) && !btf_type_is_type_tag(t)) {
2747 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2748 		return -EINVAL;
2749 	}
2750 
2751 	if (!BTF_TYPE_ID_VALID(t->type)) {
2752 		btf_verifier_log_type(env, t, "Invalid type_id");
2753 		return -EINVAL;
2754 	}
2755 
2756 	/* typedef/type_tag type must have a valid name, and other ref types,
2757 	 * volatile, const, restrict, should have a null name.
2758 	 */
2759 	if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2760 		if (!t->name_off ||
2761 		    !btf_name_valid_identifier(env->btf, t->name_off)) {
2762 			btf_verifier_log_type(env, t, "Invalid name");
2763 			return -EINVAL;
2764 		}
2765 	} else if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPE_TAG) {
2766 		value = btf_name_by_offset(env->btf, t->name_off);
2767 		if (!value || !value[0]) {
2768 			btf_verifier_log_type(env, t, "Invalid name");
2769 			return -EINVAL;
2770 		}
2771 	} else {
2772 		if (t->name_off) {
2773 			btf_verifier_log_type(env, t, "Invalid name");
2774 			return -EINVAL;
2775 		}
2776 	}
2777 
2778 	btf_verifier_log_type(env, t, NULL);
2779 
2780 	return 0;
2781 }
2782 
2783 static int btf_modifier_resolve(struct btf_verifier_env *env,
2784 				const struct resolve_vertex *v)
2785 {
2786 	const struct btf_type *t = v->t;
2787 	const struct btf_type *next_type;
2788 	u32 next_type_id = t->type;
2789 	struct btf *btf = env->btf;
2790 
2791 	next_type = btf_type_by_id(btf, next_type_id);
2792 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2793 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2794 		return -EINVAL;
2795 	}
2796 
2797 	if (!env_type_is_resolve_sink(env, next_type) &&
2798 	    !env_type_is_resolved(env, next_type_id))
2799 		return env_stack_push(env, next_type, next_type_id);
2800 
2801 	/* Figure out the resolved next_type_id with size.
2802 	 * They will be stored in the current modifier's
2803 	 * resolved_ids and resolved_sizes such that it can
2804 	 * save us a few type-following when we use it later (e.g. in
2805 	 * pretty print).
2806 	 */
2807 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2808 		if (env_type_is_resolved(env, next_type_id))
2809 			next_type = btf_type_id_resolve(btf, &next_type_id);
2810 
2811 		/* "typedef void new_void", "const void"...etc */
2812 		if (!btf_type_is_void(next_type) &&
2813 		    !btf_type_is_fwd(next_type) &&
2814 		    !btf_type_is_func_proto(next_type)) {
2815 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2816 			return -EINVAL;
2817 		}
2818 	}
2819 
2820 	env_stack_pop_resolved(env, next_type_id, 0);
2821 
2822 	return 0;
2823 }
2824 
2825 static int btf_var_resolve(struct btf_verifier_env *env,
2826 			   const struct resolve_vertex *v)
2827 {
2828 	const struct btf_type *next_type;
2829 	const struct btf_type *t = v->t;
2830 	u32 next_type_id = t->type;
2831 	struct btf *btf = env->btf;
2832 
2833 	next_type = btf_type_by_id(btf, next_type_id);
2834 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2835 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2836 		return -EINVAL;
2837 	}
2838 
2839 	if (!env_type_is_resolve_sink(env, next_type) &&
2840 	    !env_type_is_resolved(env, next_type_id))
2841 		return env_stack_push(env, next_type, next_type_id);
2842 
2843 	if (btf_type_is_modifier(next_type)) {
2844 		const struct btf_type *resolved_type;
2845 		u32 resolved_type_id;
2846 
2847 		resolved_type_id = next_type_id;
2848 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2849 
2850 		if (btf_type_is_ptr(resolved_type) &&
2851 		    !env_type_is_resolve_sink(env, resolved_type) &&
2852 		    !env_type_is_resolved(env, resolved_type_id))
2853 			return env_stack_push(env, resolved_type,
2854 					      resolved_type_id);
2855 	}
2856 
2857 	/* We must resolve to something concrete at this point, no
2858 	 * forward types or similar that would resolve to size of
2859 	 * zero is allowed.
2860 	 */
2861 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2862 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2863 		return -EINVAL;
2864 	}
2865 
2866 	env_stack_pop_resolved(env, next_type_id, 0);
2867 
2868 	return 0;
2869 }
2870 
2871 static int btf_ptr_resolve(struct btf_verifier_env *env,
2872 			   const struct resolve_vertex *v)
2873 {
2874 	const struct btf_type *next_type;
2875 	const struct btf_type *t = v->t;
2876 	u32 next_type_id = t->type;
2877 	struct btf *btf = env->btf;
2878 
2879 	next_type = btf_type_by_id(btf, next_type_id);
2880 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2881 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2882 		return -EINVAL;
2883 	}
2884 
2885 	if (!env_type_is_resolve_sink(env, next_type) &&
2886 	    !env_type_is_resolved(env, next_type_id))
2887 		return env_stack_push(env, next_type, next_type_id);
2888 
2889 	/* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2890 	 * the modifier may have stopped resolving when it was resolved
2891 	 * to a ptr (last-resolved-ptr).
2892 	 *
2893 	 * We now need to continue from the last-resolved-ptr to
2894 	 * ensure the last-resolved-ptr will not referring back to
2895 	 * the current ptr (t).
2896 	 */
2897 	if (btf_type_is_modifier(next_type)) {
2898 		const struct btf_type *resolved_type;
2899 		u32 resolved_type_id;
2900 
2901 		resolved_type_id = next_type_id;
2902 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2903 
2904 		if (btf_type_is_ptr(resolved_type) &&
2905 		    !env_type_is_resolve_sink(env, resolved_type) &&
2906 		    !env_type_is_resolved(env, resolved_type_id))
2907 			return env_stack_push(env, resolved_type,
2908 					      resolved_type_id);
2909 	}
2910 
2911 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2912 		if (env_type_is_resolved(env, next_type_id))
2913 			next_type = btf_type_id_resolve(btf, &next_type_id);
2914 
2915 		if (!btf_type_is_void(next_type) &&
2916 		    !btf_type_is_fwd(next_type) &&
2917 		    !btf_type_is_func_proto(next_type)) {
2918 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2919 			return -EINVAL;
2920 		}
2921 	}
2922 
2923 	env_stack_pop_resolved(env, next_type_id, 0);
2924 
2925 	return 0;
2926 }
2927 
2928 static void btf_modifier_show(const struct btf *btf,
2929 			      const struct btf_type *t,
2930 			      u32 type_id, void *data,
2931 			      u8 bits_offset, struct btf_show *show)
2932 {
2933 	if (btf->resolved_ids)
2934 		t = btf_type_id_resolve(btf, &type_id);
2935 	else
2936 		t = btf_type_skip_modifiers(btf, type_id, NULL);
2937 
2938 	/*
2939 	 * A modifier can resolve to void, which has no show op; print a
2940 	 * placeholder rather than dereferencing NULL.
2941 	 */
2942 	if (!btf_type_ops(t))
2943 		btf_df_show(btf, t, type_id, data, bits_offset, show);
2944 	else
2945 		btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2946 }
2947 
2948 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2949 			 u32 type_id, void *data, u8 bits_offset,
2950 			 struct btf_show *show)
2951 {
2952 	/*
2953 	 * btf_type_id_resolve() dereferences btf->resolved_ids, which is NULL
2954 	 * for a base BTF (e.g. the vmlinux BTF that bpf_snprintf_btf() uses).
2955 	 * Resolve the var's type directly in that case.
2956 	 */
2957 	if (btf->resolved_ids)
2958 		t = btf_type_id_resolve(btf, &type_id);
2959 	else
2960 		t = btf_type_skip_modifiers(btf, t->type, &type_id);
2961 
2962 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2963 }
2964 
2965 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2966 			 u32 type_id, void *data, u8 bits_offset,
2967 			 struct btf_show *show)
2968 {
2969 	void *safe_data;
2970 
2971 	safe_data = btf_show_start_type(show, t, type_id, data);
2972 	if (!safe_data)
2973 		return;
2974 
2975 	/* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2976 	if (show->flags & BTF_SHOW_PTR_RAW)
2977 		btf_show_type_value(show, "0x%px", *(void **)safe_data);
2978 	else
2979 		btf_show_type_value(show, "0x%p", *(void **)safe_data);
2980 	btf_show_end_type(show);
2981 }
2982 
2983 static void btf_ref_type_log(struct btf_verifier_env *env,
2984 			     const struct btf_type *t)
2985 {
2986 	btf_verifier_log(env, "type_id=%u", t->type);
2987 }
2988 
2989 static const struct btf_kind_operations modifier_ops = {
2990 	.check_meta = btf_ref_type_check_meta,
2991 	.resolve = btf_modifier_resolve,
2992 	.check_member = btf_modifier_check_member,
2993 	.check_kflag_member = btf_modifier_check_kflag_member,
2994 	.log_details = btf_ref_type_log,
2995 	.show = btf_modifier_show,
2996 };
2997 
2998 static const struct btf_kind_operations ptr_ops = {
2999 	.check_meta = btf_ref_type_check_meta,
3000 	.resolve = btf_ptr_resolve,
3001 	.check_member = btf_ptr_check_member,
3002 	.check_kflag_member = btf_generic_check_kflag_member,
3003 	.log_details = btf_ref_type_log,
3004 	.show = btf_ptr_show,
3005 };
3006 
3007 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
3008 			      const struct btf_type *t,
3009 			      u32 meta_left)
3010 {
3011 	if (btf_type_vlen(t)) {
3012 		btf_verifier_log_type(env, t, "vlen != 0");
3013 		return -EINVAL;
3014 	}
3015 
3016 	if (t->type) {
3017 		btf_verifier_log_type(env, t, "type != 0");
3018 		return -EINVAL;
3019 	}
3020 
3021 	/* fwd type must have a valid name */
3022 	if (!t->name_off ||
3023 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3024 		btf_verifier_log_type(env, t, "Invalid name");
3025 		return -EINVAL;
3026 	}
3027 
3028 	btf_verifier_log_type(env, t, NULL);
3029 
3030 	return 0;
3031 }
3032 
3033 static void btf_fwd_type_log(struct btf_verifier_env *env,
3034 			     const struct btf_type *t)
3035 {
3036 	btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
3037 }
3038 
3039 static const struct btf_kind_operations fwd_ops = {
3040 	.check_meta = btf_fwd_check_meta,
3041 	.resolve = btf_df_resolve,
3042 	.check_member = btf_df_check_member,
3043 	.check_kflag_member = btf_df_check_kflag_member,
3044 	.log_details = btf_fwd_type_log,
3045 	.show = btf_df_show,
3046 };
3047 
3048 static int btf_array_check_member(struct btf_verifier_env *env,
3049 				  const struct btf_type *struct_type,
3050 				  const struct btf_member *member,
3051 				  const struct btf_type *member_type)
3052 {
3053 	u32 struct_bits_off = member->offset;
3054 	u32 struct_size, bytes_offset;
3055 	u32 array_type_id, array_size;
3056 	struct btf *btf = env->btf;
3057 
3058 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3059 		btf_verifier_log_member(env, struct_type, member,
3060 					"Member is not byte aligned");
3061 		return -EINVAL;
3062 	}
3063 
3064 	array_type_id = member->type;
3065 	btf_type_id_size(btf, &array_type_id, &array_size);
3066 	struct_size = struct_type->size;
3067 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3068 	if (struct_size - bytes_offset < array_size) {
3069 		btf_verifier_log_member(env, struct_type, member,
3070 					"Member exceeds struct_size");
3071 		return -EINVAL;
3072 	}
3073 
3074 	return 0;
3075 }
3076 
3077 static s32 btf_array_check_meta(struct btf_verifier_env *env,
3078 				const struct btf_type *t,
3079 				u32 meta_left)
3080 {
3081 	const struct btf_array *array = btf_type_array(t);
3082 	u32 meta_needed = sizeof(*array);
3083 
3084 	if (meta_left < meta_needed) {
3085 		btf_verifier_log_basic(env, t,
3086 				       "meta_left:%u meta_needed:%u",
3087 				       meta_left, meta_needed);
3088 		return -EINVAL;
3089 	}
3090 
3091 	/* array type should not have a name */
3092 	if (t->name_off) {
3093 		btf_verifier_log_type(env, t, "Invalid name");
3094 		return -EINVAL;
3095 	}
3096 
3097 	if (btf_type_vlen(t)) {
3098 		btf_verifier_log_type(env, t, "vlen != 0");
3099 		return -EINVAL;
3100 	}
3101 
3102 	if (btf_type_kflag(t)) {
3103 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3104 		return -EINVAL;
3105 	}
3106 
3107 	if (t->size) {
3108 		btf_verifier_log_type(env, t, "size != 0");
3109 		return -EINVAL;
3110 	}
3111 
3112 	/* Array elem type and index type cannot be in type void,
3113 	 * so !array->type and !array->index_type are not allowed.
3114 	 */
3115 	if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
3116 		btf_verifier_log_type(env, t, "Invalid elem");
3117 		return -EINVAL;
3118 	}
3119 
3120 	if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
3121 		btf_verifier_log_type(env, t, "Invalid index");
3122 		return -EINVAL;
3123 	}
3124 
3125 	btf_verifier_log_type(env, t, NULL);
3126 
3127 	return meta_needed;
3128 }
3129 
3130 static int btf_array_resolve(struct btf_verifier_env *env,
3131 			     const struct resolve_vertex *v)
3132 {
3133 	const struct btf_array *array = btf_type_array(v->t);
3134 	const struct btf_type *elem_type, *index_type;
3135 	u32 elem_type_id, index_type_id;
3136 	struct btf *btf = env->btf;
3137 	u32 elem_size;
3138 
3139 	/* Check array->index_type */
3140 	index_type_id = array->index_type;
3141 	index_type = btf_type_by_id(btf, index_type_id);
3142 	if (btf_type_nosize_or_null(index_type) ||
3143 	    btf_type_is_resolve_source_only(index_type)) {
3144 		btf_verifier_log_type(env, v->t, "Invalid index");
3145 		return -EINVAL;
3146 	}
3147 
3148 	if (!env_type_is_resolve_sink(env, index_type) &&
3149 	    !env_type_is_resolved(env, index_type_id))
3150 		return env_stack_push(env, index_type, index_type_id);
3151 
3152 	index_type = btf_type_id_size(btf, &index_type_id, NULL);
3153 	if (!index_type || !btf_type_is_int(index_type) ||
3154 	    !btf_type_int_is_regular(index_type)) {
3155 		btf_verifier_log_type(env, v->t, "Invalid index");
3156 		return -EINVAL;
3157 	}
3158 
3159 	/* Check array->type */
3160 	elem_type_id = array->type;
3161 	elem_type = btf_type_by_id(btf, elem_type_id);
3162 	if (btf_type_nosize_or_null(elem_type) ||
3163 	    btf_type_is_resolve_source_only(elem_type)) {
3164 		btf_verifier_log_type(env, v->t,
3165 				      "Invalid elem");
3166 		return -EINVAL;
3167 	}
3168 
3169 	if (!env_type_is_resolve_sink(env, elem_type) &&
3170 	    !env_type_is_resolved(env, elem_type_id))
3171 		return env_stack_push(env, elem_type, elem_type_id);
3172 
3173 	elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
3174 	if (!elem_type) {
3175 		btf_verifier_log_type(env, v->t, "Invalid elem");
3176 		return -EINVAL;
3177 	}
3178 
3179 	if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
3180 		btf_verifier_log_type(env, v->t, "Invalid array of int");
3181 		return -EINVAL;
3182 	}
3183 
3184 	if (array->nelems && elem_size > U32_MAX / array->nelems) {
3185 		btf_verifier_log_type(env, v->t,
3186 				      "Array size overflows U32_MAX");
3187 		return -EINVAL;
3188 	}
3189 
3190 	env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
3191 
3192 	return 0;
3193 }
3194 
3195 static void btf_array_log(struct btf_verifier_env *env,
3196 			  const struct btf_type *t)
3197 {
3198 	const struct btf_array *array = btf_type_array(t);
3199 
3200 	btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
3201 			 array->type, array->index_type, array->nelems);
3202 }
3203 
3204 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
3205 			     u32 type_id, void *data, u8 bits_offset,
3206 			     struct btf_show *show)
3207 {
3208 	const struct btf_array *array = btf_type_array(t);
3209 	const struct btf_kind_operations *elem_ops;
3210 	const struct btf_type *elem_type;
3211 	u32 i, elem_size = 0, elem_type_id;
3212 	u16 encoding = 0;
3213 
3214 	elem_type_id = array->type;
3215 	elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
3216 	if (elem_type && btf_type_has_size(elem_type))
3217 		elem_size = elem_type->size;
3218 
3219 	if (elem_type && btf_type_is_int(elem_type)) {
3220 		u32 int_type = btf_type_int(elem_type);
3221 
3222 		encoding = BTF_INT_ENCODING(int_type);
3223 
3224 		/*
3225 		 * BTF_INT_CHAR encoding never seems to be set for
3226 		 * char arrays, so if size is 1 and element is
3227 		 * printable as a char, we'll do that.
3228 		 */
3229 		if (elem_size == 1)
3230 			encoding = BTF_INT_CHAR;
3231 	}
3232 
3233 	if (!btf_show_start_array_type(show, t, type_id, encoding, data))
3234 		return;
3235 
3236 	if (!elem_type)
3237 		goto out;
3238 	elem_ops = btf_type_ops(elem_type);
3239 
3240 	for (i = 0; i < array->nelems; i++) {
3241 
3242 		btf_show_start_array_member(show);
3243 
3244 		elem_ops->show(btf, elem_type, elem_type_id, data,
3245 			       bits_offset, show);
3246 		data += elem_size;
3247 
3248 		btf_show_end_array_member(show);
3249 
3250 		if (show->state.array_terminated)
3251 			break;
3252 	}
3253 out:
3254 	btf_show_end_array_type(show);
3255 }
3256 
3257 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
3258 			   u32 type_id, void *data, u8 bits_offset,
3259 			   struct btf_show *show)
3260 {
3261 	const struct btf_member *m = show->state.member;
3262 
3263 	/*
3264 	 * First check if any members would be shown (are non-zero).
3265 	 * See comments above "struct btf_show" definition for more
3266 	 * details on how this works at a high-level.
3267 	 */
3268 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3269 		if (!show->state.depth_check) {
3270 			show->state.depth_check = show->state.depth + 1;
3271 			show->state.depth_to_show = 0;
3272 		}
3273 		__btf_array_show(btf, t, type_id, data, bits_offset, show);
3274 		show->state.member = m;
3275 
3276 		if (show->state.depth_check != show->state.depth + 1)
3277 			return;
3278 		show->state.depth_check = 0;
3279 
3280 		if (show->state.depth_to_show <= show->state.depth)
3281 			return;
3282 		/*
3283 		 * Reaching here indicates we have recursed and found
3284 		 * non-zero array member(s).
3285 		 */
3286 	}
3287 	__btf_array_show(btf, t, type_id, data, bits_offset, show);
3288 }
3289 
3290 static const struct btf_kind_operations array_ops = {
3291 	.check_meta = btf_array_check_meta,
3292 	.resolve = btf_array_resolve,
3293 	.check_member = btf_array_check_member,
3294 	.check_kflag_member = btf_generic_check_kflag_member,
3295 	.log_details = btf_array_log,
3296 	.show = btf_array_show,
3297 };
3298 
3299 static int btf_struct_check_member(struct btf_verifier_env *env,
3300 				   const struct btf_type *struct_type,
3301 				   const struct btf_member *member,
3302 				   const struct btf_type *member_type)
3303 {
3304 	u32 struct_bits_off = member->offset;
3305 	u32 struct_size, bytes_offset;
3306 
3307 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3308 		btf_verifier_log_member(env, struct_type, member,
3309 					"Member is not byte aligned");
3310 		return -EINVAL;
3311 	}
3312 
3313 	struct_size = struct_type->size;
3314 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3315 	if (struct_size - bytes_offset < member_type->size) {
3316 		btf_verifier_log_member(env, struct_type, member,
3317 					"Member exceeds struct_size");
3318 		return -EINVAL;
3319 	}
3320 
3321 	return 0;
3322 }
3323 
3324 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
3325 				 const struct btf_type *t,
3326 				 u32 meta_left)
3327 {
3328 	bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
3329 	const struct btf_member *member;
3330 	u32 meta_needed, last_offset;
3331 	struct btf *btf = env->btf;
3332 	u32 struct_size = t->size;
3333 	u32 offset;
3334 	u32 i;
3335 
3336 	meta_needed = btf_type_vlen(t) * sizeof(*member);
3337 	if (meta_left < meta_needed) {
3338 		btf_verifier_log_basic(env, t,
3339 				       "meta_left:%u meta_needed:%u",
3340 				       meta_left, meta_needed);
3341 		return -EINVAL;
3342 	}
3343 
3344 	/* struct type either no name or a valid one */
3345 	if (t->name_off &&
3346 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3347 		btf_verifier_log_type(env, t, "Invalid name");
3348 		return -EINVAL;
3349 	}
3350 
3351 	btf_verifier_log_type(env, t, NULL);
3352 
3353 	last_offset = 0;
3354 	for_each_member(i, t, member) {
3355 		if (!btf_name_offset_valid(btf, member->name_off)) {
3356 			btf_verifier_log_member(env, t, member,
3357 						"Invalid member name_offset:%u",
3358 						member->name_off);
3359 			return -EINVAL;
3360 		}
3361 
3362 		/* struct member either no name or a valid one */
3363 		if (member->name_off &&
3364 		    !btf_name_valid_identifier(btf, member->name_off)) {
3365 			btf_verifier_log_member(env, t, member, "Invalid name");
3366 			return -EINVAL;
3367 		}
3368 		/* A member cannot be in type void */
3369 		if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
3370 			btf_verifier_log_member(env, t, member,
3371 						"Invalid type_id");
3372 			return -EINVAL;
3373 		}
3374 
3375 		offset = __btf_member_bit_offset(t, member);
3376 		if (is_union && offset) {
3377 			btf_verifier_log_member(env, t, member,
3378 						"Invalid member bits_offset");
3379 			return -EINVAL;
3380 		}
3381 
3382 		/*
3383 		 * ">" instead of ">=" because the last member could be
3384 		 * "char a[0];"
3385 		 */
3386 		if (last_offset > offset) {
3387 			btf_verifier_log_member(env, t, member,
3388 						"Invalid member bits_offset");
3389 			return -EINVAL;
3390 		}
3391 
3392 		if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
3393 			btf_verifier_log_member(env, t, member,
3394 						"Member bits_offset exceeds its struct size");
3395 			return -EINVAL;
3396 		}
3397 
3398 		btf_verifier_log_member(env, t, member, NULL);
3399 		last_offset = offset;
3400 	}
3401 
3402 	return meta_needed;
3403 }
3404 
3405 static int btf_struct_resolve(struct btf_verifier_env *env,
3406 			      const struct resolve_vertex *v)
3407 {
3408 	const struct btf_member *member;
3409 	int err;
3410 	u32 i;
3411 
3412 	/* Before continue resolving the next_member,
3413 	 * ensure the last member is indeed resolved to a
3414 	 * type with size info.
3415 	 */
3416 	if (v->next_member) {
3417 		const struct btf_type *last_member_type;
3418 		const struct btf_member *last_member;
3419 		u32 last_member_type_id;
3420 
3421 		last_member = btf_type_member(v->t) + v->next_member - 1;
3422 		last_member_type_id = last_member->type;
3423 		if (WARN_ON_ONCE(!env_type_is_resolved(env,
3424 						       last_member_type_id)))
3425 			return -EINVAL;
3426 
3427 		last_member_type = btf_type_by_id(env->btf,
3428 						  last_member_type_id);
3429 		if (btf_type_kflag(v->t))
3430 			err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
3431 								last_member,
3432 								last_member_type);
3433 		else
3434 			err = btf_type_ops(last_member_type)->check_member(env, v->t,
3435 								last_member,
3436 								last_member_type);
3437 		if (err)
3438 			return err;
3439 	}
3440 
3441 	for_each_member_from(i, v->next_member, v->t, member) {
3442 		u32 member_type_id = member->type;
3443 		const struct btf_type *member_type = btf_type_by_id(env->btf,
3444 								member_type_id);
3445 
3446 		if (btf_type_nosize_or_null(member_type) ||
3447 		    btf_type_is_resolve_source_only(member_type)) {
3448 			btf_verifier_log_member(env, v->t, member,
3449 						"Invalid member");
3450 			return -EINVAL;
3451 		}
3452 
3453 		if (!env_type_is_resolve_sink(env, member_type) &&
3454 		    !env_type_is_resolved(env, member_type_id)) {
3455 			env_stack_set_next_member(env, i + 1);
3456 			return env_stack_push(env, member_type, member_type_id);
3457 		}
3458 
3459 		if (btf_type_kflag(v->t))
3460 			err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3461 									    member,
3462 									    member_type);
3463 		else
3464 			err = btf_type_ops(member_type)->check_member(env, v->t,
3465 								      member,
3466 								      member_type);
3467 		if (err)
3468 			return err;
3469 	}
3470 
3471 	env_stack_pop_resolved(env, 0, 0);
3472 
3473 	return 0;
3474 }
3475 
3476 static void btf_struct_log(struct btf_verifier_env *env,
3477 			   const struct btf_type *t)
3478 {
3479 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3480 }
3481 
3482 enum {
3483 	BTF_FIELD_IGNORE = 0,
3484 	BTF_FIELD_FOUND  = 1,
3485 };
3486 
3487 struct btf_field_info {
3488 	enum btf_field_type type;
3489 	u32 off;
3490 	union {
3491 		struct {
3492 			u32 type_id;
3493 		} kptr;
3494 		struct {
3495 			const char *node_name;
3496 			u32 value_btf_id;
3497 		} graph_root;
3498 	};
3499 };
3500 
3501 static int btf_find_struct(const struct btf *btf, const struct btf_type *t,
3502 			   u32 off, int sz, enum btf_field_type field_type,
3503 			   struct btf_field_info *info)
3504 {
3505 	if (!__btf_type_is_struct(t))
3506 		return BTF_FIELD_IGNORE;
3507 	if (t->size != sz)
3508 		return BTF_FIELD_IGNORE;
3509 	info->type = field_type;
3510 	info->off = off;
3511 	return BTF_FIELD_FOUND;
3512 }
3513 
3514 struct btf_type_tag_match {
3515 	const char *name;
3516 	u32 flag;
3517 };
3518 
3519 struct btf_type_tag_walk_ctx {
3520 	const struct btf_type *t;	/* Input/Output */
3521 	u32 id;				/* Output */
3522 	u32 res;			/* Output */
3523 };
3524 
3525 static int btf_type_tag_walk(const struct btf *btf,
3526 			     struct btf_type_tag_walk_ctx *ctx,
3527 			     const struct btf_type_tag_match *matches,
3528 			     u32 match_cnt)
3529 {
3530 	const struct btf_type *t = ctx->t;
3531 	u32 res = 0;
3532 	const char *tag;
3533 	u32 id, i;
3534 
3535 	do {
3536 		id = t->type;
3537 		t = btf_type_by_id(btf, id);
3538 
3539 		if (!btf_type_is_modifier(t))
3540 			break;
3541 
3542 		if (!btf_type_is_type_tag(t) || btf_type_kflag(t))
3543 			continue;
3544 
3545 		tag = __btf_name_by_offset(btf, t->name_off);
3546 		for (i = 0; i < match_cnt; i++) {
3547 			if (strcmp(tag, matches[i].name))
3548 				continue;
3549 			res |= matches[i].flag;
3550 			break;
3551 		}
3552 	} while (true);
3553 
3554 	/* We only support a single tag. */
3555 	if (hweight32(res) > 1)
3556 		return -EINVAL;
3557 
3558 	ctx->t = t;
3559 	ctx->id = id;
3560 	ctx->res = res;
3561 
3562 	return 0;
3563 }
3564 
3565 bool btf_type_is_arena_ptr(const struct btf *btf, const struct btf_type *t)
3566 {
3567 	if (!btf_type_is_ptr(t))
3568 		return false;
3569 
3570 	for (t = btf_type_by_id(btf, t->type); btf_type_is_modifier(t);
3571 	     t = btf_type_by_id(btf, t->type)) {
3572 		if (!btf_type_is_type_tag(t) || btf_type_kflag(t))
3573 			continue;
3574 		if (!strcmp(__btf_name_by_offset(btf, t->name_off), "arena"))
3575 			return true;
3576 	}
3577 
3578 	return false;
3579 }
3580 
3581 static int btf_find_kptr(const struct btf *btf, const struct btf_type *t,
3582 			 u32 off, int sz, struct btf_field_info *info, u32 field_mask)
3583 {
3584 	static const struct btf_type_tag_match kptr_type_tags[] = {
3585 		{ "kptr_untrusted", BPF_KPTR_UNREF },
3586 		{ "kptr", BPF_KPTR_REF },
3587 		{ "percpu_kptr", BPF_KPTR_PERCPU },
3588 		{ "uptr", BPF_UPTR },
3589 	};
3590 	struct btf_type_tag_walk_ctx ctx;
3591 	enum btf_field_type type = 0;
3592 	int err;
3593 	u32 res_id;
3594 
3595 	/* Permit modifiers on the pointer itself */
3596 	if (btf_type_is_volatile(t))
3597 		t = btf_type_by_id(btf, t->type);
3598 	/* For PTR, sz is always == 8 */
3599 	if (!btf_type_is_ptr(t))
3600 		return BTF_FIELD_IGNORE;
3601 
3602 	ctx.t = t;
3603 	err = btf_type_tag_walk(btf, &ctx, kptr_type_tags,
3604 				ARRAY_SIZE(kptr_type_tags));
3605 	if (err)
3606 		return err;
3607 
3608 	t = ctx.t;
3609 	res_id = ctx.id;
3610 	type = ctx.res;
3611 
3612 	if (!(type & field_mask))
3613 		return BTF_FIELD_IGNORE;
3614 
3615 	/* Only pointer to struct is allowed */
3616 	if (!__btf_type_is_struct(t))
3617 		return -EINVAL;
3618 
3619 	info->type = type;
3620 	info->off = off;
3621 	info->kptr.type_id = res_id;
3622 	return BTF_FIELD_FOUND;
3623 }
3624 
3625 int btf_find_next_decl_tag(const struct btf *btf, const struct btf_type *pt,
3626 			   int comp_idx, const char *tag_key, int last_id)
3627 {
3628 	int len = strlen(tag_key);
3629 	int i, n;
3630 
3631 	for (i = last_id + 1, n = btf_nr_types(btf); i < n; i++) {
3632 		const struct btf_type *t = btf_type_by_id(btf, i);
3633 
3634 		if (!btf_type_is_decl_tag(t))
3635 			continue;
3636 		if (pt != btf_type_by_id(btf, t->type))
3637 			continue;
3638 		if (btf_type_decl_tag(t)->component_idx != comp_idx)
3639 			continue;
3640 		if (strncmp(__btf_name_by_offset(btf, t->name_off), tag_key, len))
3641 			continue;
3642 		return i;
3643 	}
3644 	return -ENOENT;
3645 }
3646 
3647 const char *btf_find_decl_tag_value(const struct btf *btf, const struct btf_type *pt,
3648 				    int comp_idx, const char *tag_key)
3649 {
3650 	const char *value = NULL;
3651 	const struct btf_type *t;
3652 	int len, id;
3653 
3654 	id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key,
3655 				    btf_named_start_id(btf, false) - 1);
3656 	if (id < 0)
3657 		return ERR_PTR(id);
3658 
3659 	t = btf_type_by_id(btf, id);
3660 	len = strlen(tag_key);
3661 	value = __btf_name_by_offset(btf, t->name_off) + len;
3662 
3663 	/* Prevent duplicate entries for same type */
3664 	id = btf_find_next_decl_tag(btf, pt, comp_idx, tag_key, id);
3665 	if (id >= 0)
3666 		return ERR_PTR(-EEXIST);
3667 
3668 	return value;
3669 }
3670 
3671 static int
3672 btf_find_graph_root(const struct btf *btf, const struct btf_type *pt,
3673 		    const struct btf_type *t, int comp_idx, u32 off,
3674 		    int sz, struct btf_field_info *info,
3675 		    enum btf_field_type head_type)
3676 {
3677 	const char *node_field_name;
3678 	const char *value_type;
3679 	s32 id;
3680 
3681 	if (!__btf_type_is_struct(t))
3682 		return BTF_FIELD_IGNORE;
3683 	if (t->size != sz)
3684 		return BTF_FIELD_IGNORE;
3685 	value_type = btf_find_decl_tag_value(btf, pt, comp_idx, "contains:");
3686 	if (IS_ERR(value_type))
3687 		return -EINVAL;
3688 	node_field_name = strstr(value_type, ":");
3689 	if (!node_field_name)
3690 		return -EINVAL;
3691 	value_type = kstrndup(value_type, node_field_name - value_type,
3692 			      GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
3693 	if (!value_type)
3694 		return -ENOMEM;
3695 	id = btf_find_by_name_kind(btf, value_type, BTF_KIND_STRUCT);
3696 	kfree(value_type);
3697 	if (id < 0)
3698 		return id;
3699 	node_field_name++;
3700 	if (str_is_empty(node_field_name))
3701 		return -EINVAL;
3702 	info->type = head_type;
3703 	info->off = off;
3704 	info->graph_root.value_btf_id = id;
3705 	info->graph_root.node_name = node_field_name;
3706 	return BTF_FIELD_FOUND;
3707 }
3708 
3709 static int btf_get_field_type(const struct btf *btf, const struct btf_type *var_type,
3710 			      u32 field_mask, u32 *seen_mask, int *align, int *sz)
3711 {
3712 	const struct {
3713 		enum btf_field_type type;
3714 		const char *const name;
3715 		const bool is_unique;
3716 	} field_types[] = {
3717 		{ BPF_SPIN_LOCK, "bpf_spin_lock", true },
3718 		{ BPF_RES_SPIN_LOCK, "bpf_res_spin_lock", true },
3719 		{ BPF_TIMER, "bpf_timer", true },
3720 		{ BPF_WORKQUEUE, "bpf_wq", true },
3721 		{ BPF_TASK_WORK, "bpf_task_work", true },
3722 		{ BPF_RCU_HEAD, "bpf_rcu_head", true },
3723 		{ BPF_LIST_HEAD, "bpf_list_head", false },
3724 		{ BPF_LIST_NODE, "bpf_list_node", false },
3725 		{ BPF_RB_ROOT, "bpf_rb_root", false },
3726 		{ BPF_RB_NODE, "bpf_rb_node", false },
3727 		{ BPF_REFCOUNT, "bpf_refcount", true },
3728 	};
3729 	int type = 0, i;
3730 	const char *name = __btf_name_by_offset(btf, var_type->name_off);
3731 	const char *field_type_name;
3732 	enum btf_field_type field_type;
3733 	bool is_unique;
3734 
3735 	for (i = 0; i < ARRAY_SIZE(field_types); ++i) {
3736 		field_type = field_types[i].type;
3737 		field_type_name = field_types[i].name;
3738 		is_unique = field_types[i].is_unique;
3739 		if (!(field_mask & field_type) || strcmp(name, field_type_name))
3740 			continue;
3741 		if (is_unique) {
3742 			if (*seen_mask & field_type)
3743 				return -E2BIG;
3744 			*seen_mask |= field_type;
3745 		}
3746 		type = field_type;
3747 		goto end;
3748 	}
3749 
3750 	/* Only return BPF_KPTR when all other types with matchable names fail */
3751 	if (field_mask & (BPF_KPTR | BPF_UPTR) && !__btf_type_is_struct(var_type)) {
3752 		type = BPF_KPTR_REF;
3753 		goto end;
3754 	}
3755 	return 0;
3756 end:
3757 	*sz = btf_field_type_size(type);
3758 	*align = btf_field_type_align(type);
3759 	return type;
3760 }
3761 
3762 /* Repeat a number of fields for a specified number of times.
3763  *
3764  * Copy the fields starting from the first field and repeat them for
3765  * repeat_cnt times. The fields are repeated by adding the offset of each
3766  * field with
3767  *   (i + 1) * elem_size
3768  * where i is the repeat index and elem_size is the size of an element.
3769  */
3770 static int btf_repeat_fields(struct btf_field_info *info, int info_cnt,
3771 			     u32 field_cnt, u32 repeat_cnt, u32 elem_size)
3772 {
3773 	u32 i, j, total_cnt, total_repeats;
3774 	u32 cur;
3775 
3776 	/* Ensure not repeating fields that should not be repeated. */
3777 	for (i = 0; i < field_cnt; i++) {
3778 		switch (info[i].type) {
3779 		case BPF_KPTR_UNREF:
3780 		case BPF_KPTR_REF:
3781 		case BPF_KPTR_PERCPU:
3782 		case BPF_UPTR:
3783 		case BPF_LIST_HEAD:
3784 		case BPF_RB_ROOT:
3785 			break;
3786 		default:
3787 			return -EINVAL;
3788 		}
3789 	}
3790 
3791 	if (check_add_overflow(repeat_cnt, 1, &total_repeats) ||
3792 	    check_mul_overflow(field_cnt, total_repeats, &total_cnt) ||
3793 	    total_cnt > (u32)info_cnt)
3794 		return -E2BIG;
3795 
3796 	cur = field_cnt;
3797 	for (i = 0; i < repeat_cnt; i++) {
3798 		memcpy(&info[cur], &info[0], field_cnt * sizeof(info[0]));
3799 		for (j = 0; j < field_cnt; j++)
3800 			info[cur++].off += (i + 1) * elem_size;
3801 	}
3802 
3803 	return 0;
3804 }
3805 
3806 static int btf_find_struct_field(const struct btf *btf,
3807 				 const struct btf_type *t, u32 field_mask,
3808 				 struct btf_field_info *info, int info_cnt,
3809 				 u32 level, u32 *seen_mask);
3810 
3811 /* Find special fields in the struct type of a field.
3812  *
3813  * This function is used to find fields of special types that is not a
3814  * global variable or a direct field of a struct type. It also handles the
3815  * repetition if it is the element type of an array.
3816  */
3817 static int btf_find_nested_struct(const struct btf *btf, const struct btf_type *t,
3818 				  u32 off, u32 nelems,
3819 				  u32 field_mask, struct btf_field_info *info,
3820 				  int info_cnt, u32 level, u32 *seen_mask)
3821 {
3822 	int ret, err, i;
3823 
3824 	level++;
3825 	if (level >= MAX_RESOLVE_DEPTH)
3826 		return -E2BIG;
3827 
3828 	ret = btf_find_struct_field(btf, t, field_mask, info, info_cnt, level, seen_mask);
3829 
3830 	if (ret <= 0)
3831 		return ret;
3832 
3833 	/* Shift the offsets of the nested struct fields to the offsets
3834 	 * related to the container.
3835 	 */
3836 	for (i = 0; i < ret; i++)
3837 		info[i].off += off;
3838 
3839 	if (nelems > 1) {
3840 		err = btf_repeat_fields(info, info_cnt, ret, nelems - 1, t->size);
3841 		if (err == 0)
3842 			ret *= nelems;
3843 		else
3844 			ret = err;
3845 	}
3846 
3847 	return ret;
3848 }
3849 
3850 static int btf_find_field_one(const struct btf *btf,
3851 			      const struct btf_type *var,
3852 			      const struct btf_type *var_type,
3853 			      int var_idx,
3854 			      u32 off, u32 expected_size,
3855 			      u32 field_mask, u32 *seen_mask,
3856 			      struct btf_field_info *info, int info_cnt,
3857 			      u32 level)
3858 {
3859 	int ret, align, sz, field_type;
3860 	struct btf_field_info tmp;
3861 	const struct btf_array *array;
3862 	u32 i, nelems = 1;
3863 
3864 	/* Walk into array types to find the element type and the number of
3865 	 * elements in the (flattened) array.
3866 	 */
3867 	for (i = 0; i < MAX_RESOLVE_DEPTH && btf_type_is_array(var_type); i++) {
3868 		array = btf_array(var_type);
3869 		nelems *= array->nelems;
3870 		var_type = btf_type_by_id(btf, array->type);
3871 	}
3872 	if (i == MAX_RESOLVE_DEPTH)
3873 		return -E2BIG;
3874 	if (nelems == 0)
3875 		return 0;
3876 
3877 	field_type = btf_get_field_type(btf, var_type,
3878 					field_mask, seen_mask, &align, &sz);
3879 	/* Look into variables of struct types */
3880 	if (!field_type && __btf_type_is_struct(var_type)) {
3881 		sz = var_type->size;
3882 		if (expected_size && expected_size != sz * nelems)
3883 			return 0;
3884 		ret = btf_find_nested_struct(btf, var_type, off, nelems, field_mask,
3885 					     &info[0], info_cnt, level, seen_mask);
3886 		return ret;
3887 	}
3888 
3889 	if (field_type == 0)
3890 		return 0;
3891 	if (field_type < 0)
3892 		return field_type;
3893 
3894 	if (expected_size && expected_size != sz * nelems)
3895 		return 0;
3896 	if (off % align)
3897 		return 0;
3898 
3899 	switch (field_type) {
3900 	case BPF_SPIN_LOCK:
3901 	case BPF_RES_SPIN_LOCK:
3902 	case BPF_TIMER:
3903 	case BPF_WORKQUEUE:
3904 	case BPF_LIST_NODE:
3905 	case BPF_RB_NODE:
3906 	case BPF_REFCOUNT:
3907 	case BPF_TASK_WORK:
3908 	case BPF_RCU_HEAD:
3909 		ret = btf_find_struct(btf, var_type, off, sz, field_type,
3910 				      info_cnt ? &info[0] : &tmp);
3911 		if (ret < 0)
3912 			return ret;
3913 		break;
3914 	case BPF_KPTR_UNREF:
3915 	case BPF_KPTR_REF:
3916 	case BPF_KPTR_PERCPU:
3917 	case BPF_UPTR:
3918 		ret = btf_find_kptr(btf, var_type, off, sz,
3919 				    info_cnt ? &info[0] : &tmp, field_mask);
3920 		if (ret < 0)
3921 			return ret;
3922 		break;
3923 	case BPF_LIST_HEAD:
3924 	case BPF_RB_ROOT:
3925 		ret = btf_find_graph_root(btf, var, var_type,
3926 					  var_idx, off, sz,
3927 					  info_cnt ? &info[0] : &tmp,
3928 					  field_type);
3929 		if (ret < 0)
3930 			return ret;
3931 		break;
3932 	default:
3933 		return -EFAULT;
3934 	}
3935 
3936 	if (ret == BTF_FIELD_IGNORE)
3937 		return 0;
3938 	if (!info_cnt)
3939 		return -E2BIG;
3940 	if (nelems > 1) {
3941 		ret = btf_repeat_fields(info, info_cnt, 1, nelems - 1, sz);
3942 		if (ret < 0)
3943 			return ret;
3944 	}
3945 	return nelems;
3946 }
3947 
3948 static int btf_find_struct_field(const struct btf *btf,
3949 				 const struct btf_type *t, u32 field_mask,
3950 				 struct btf_field_info *info, int info_cnt,
3951 				 u32 level, u32 *seen_mask)
3952 {
3953 	int ret, idx = 0;
3954 	const struct btf_member *member;
3955 	u32 i, off;
3956 
3957 	for_each_member(i, t, member) {
3958 		const struct btf_type *member_type = btf_type_by_id(btf,
3959 								    member->type);
3960 
3961 		off = __btf_member_bit_offset(t, member);
3962 		if (off % 8)
3963 			/* valid C code cannot generate such BTF */
3964 			return -EINVAL;
3965 		off /= 8;
3966 
3967 		ret = btf_find_field_one(btf, t, member_type, i,
3968 					 off, 0,
3969 					 field_mask, seen_mask,
3970 					 &info[idx], info_cnt - idx, level);
3971 		if (ret < 0)
3972 			return ret;
3973 		idx += ret;
3974 	}
3975 	return idx;
3976 }
3977 
3978 static int btf_find_datasec_var(const struct btf *btf, const struct btf_type *t,
3979 				u32 field_mask, struct btf_field_info *info,
3980 				int info_cnt, u32 level, u32 *seen_mask)
3981 {
3982 	int ret, idx = 0;
3983 	const struct btf_var_secinfo *vsi;
3984 	u32 i, off;
3985 
3986 	for_each_vsi(i, t, vsi) {
3987 		const struct btf_type *var = btf_type_by_id(btf, vsi->type);
3988 		const struct btf_type *var_type = btf_type_by_id(btf, var->type);
3989 
3990 		off = vsi->offset;
3991 		ret = btf_find_field_one(btf, var, var_type, -1, off, vsi->size,
3992 					 field_mask, seen_mask,
3993 					 &info[idx], info_cnt - idx,
3994 					 level);
3995 		if (ret < 0)
3996 			return ret;
3997 		idx += ret;
3998 	}
3999 	return idx;
4000 }
4001 
4002 static int btf_find_field(const struct btf *btf, const struct btf_type *t,
4003 			  u32 field_mask, struct btf_field_info *info,
4004 			  int info_cnt)
4005 {
4006 	u32 seen_mask = 0;
4007 
4008 	if (__btf_type_is_struct(t))
4009 		return btf_find_struct_field(btf, t, field_mask, info, info_cnt, 0, &seen_mask);
4010 	else if (btf_type_is_datasec(t))
4011 		return btf_find_datasec_var(btf, t, field_mask, info, info_cnt, 0, &seen_mask);
4012 	return -EINVAL;
4013 }
4014 
4015 /* Callers have to ensure the life cycle of btf if it is program BTF */
4016 static int btf_parse_kptr(const struct btf *btf, struct btf_field *field,
4017 			  struct btf_field_info *info)
4018 {
4019 	struct module *mod = NULL;
4020 	const struct btf_type *t;
4021 	/* If a matching btf type is found in kernel or module BTFs, kptr_ref
4022 	 * is that BTF, otherwise it's program BTF
4023 	 */
4024 	struct btf *kptr_btf;
4025 	int ret;
4026 	s32 id;
4027 
4028 	/* Find type in map BTF, and use it to look up the matching type
4029 	 * in vmlinux or module BTFs, by name and kind.
4030 	 */
4031 	t = btf_type_by_id(btf, info->kptr.type_id);
4032 	id = bpf_find_btf_id(__btf_name_by_offset(btf, t->name_off), BTF_INFO_KIND(t->info),
4033 			     &kptr_btf);
4034 	if (id == -ENOENT) {
4035 		/* btf_parse_kptr should only be called w/ btf = program BTF */
4036 		WARN_ON_ONCE(btf_is_kernel(btf));
4037 
4038 		/* Type exists only in program BTF. Assume that it's a MEM_ALLOC
4039 		 * kptr allocated via bpf_obj_new
4040 		 */
4041 		field->kptr.dtor = NULL;
4042 		id = info->kptr.type_id;
4043 		kptr_btf = (struct btf *)btf;
4044 		goto found_dtor;
4045 	}
4046 	if (id < 0)
4047 		return id;
4048 
4049 	/* Find and stash the function pointer for the destruction function that
4050 	 * needs to be eventually invoked from the map free path.
4051 	 */
4052 	if (info->type == BPF_KPTR_REF) {
4053 		const struct btf_type *dtor_func;
4054 		const char *dtor_func_name;
4055 		unsigned long addr;
4056 		s32 dtor_btf_id;
4057 
4058 		/* This call also serves as a whitelist of allowed objects that
4059 		 * can be used as a referenced pointer and be stored in a map at
4060 		 * the same time.
4061 		 */
4062 		dtor_btf_id = btf_find_dtor_kfunc(kptr_btf, id);
4063 		if (dtor_btf_id < 0) {
4064 			ret = dtor_btf_id;
4065 			goto end_btf;
4066 		}
4067 
4068 		dtor_func = btf_type_by_id(kptr_btf, dtor_btf_id);
4069 		if (!dtor_func) {
4070 			ret = -ENOENT;
4071 			goto end_btf;
4072 		}
4073 
4074 		if (btf_is_module(kptr_btf)) {
4075 			mod = btf_try_get_module(kptr_btf);
4076 			if (!mod) {
4077 				ret = -ENXIO;
4078 				goto end_btf;
4079 			}
4080 		}
4081 
4082 		/* We already verified dtor_func to be btf_type_is_func
4083 		 * in register_btf_id_dtor_kfuncs.
4084 		 */
4085 		dtor_func_name = __btf_name_by_offset(kptr_btf, dtor_func->name_off);
4086 		addr = kallsyms_lookup_name(dtor_func_name);
4087 		if (!addr) {
4088 			ret = -EINVAL;
4089 			goto end_mod;
4090 		}
4091 		field->kptr.dtor = (void *)addr;
4092 	}
4093 
4094 found_dtor:
4095 	field->kptr.btf_id = id;
4096 	field->kptr.btf = kptr_btf;
4097 	field->kptr.module = mod;
4098 	return 0;
4099 end_mod:
4100 	module_put(mod);
4101 end_btf:
4102 	btf_put(kptr_btf);
4103 	return ret;
4104 }
4105 
4106 static int btf_parse_graph_root(const struct btf *btf,
4107 				struct btf_field *field,
4108 				struct btf_field_info *info,
4109 				const char *node_type_name,
4110 				size_t node_type_align)
4111 {
4112 	const struct btf_type *t, *n = NULL;
4113 	const struct btf_member *member;
4114 	u32 offset;
4115 	int i;
4116 
4117 	t = btf_type_by_id(btf, info->graph_root.value_btf_id);
4118 	/* We've already checked that value_btf_id is a struct type. We
4119 	 * just need to figure out the offset of the list_node, and
4120 	 * verify its type.
4121 	 */
4122 	for_each_member(i, t, member) {
4123 		if (strcmp(info->graph_root.node_name,
4124 			   __btf_name_by_offset(btf, member->name_off)))
4125 			continue;
4126 		/* Invalid BTF, two members with same name */
4127 		if (n)
4128 			return -EINVAL;
4129 		n = btf_type_by_id(btf, member->type);
4130 		if (!__btf_type_is_struct(n))
4131 			return -EINVAL;
4132 		if (strcmp(node_type_name, __btf_name_by_offset(btf, n->name_off)))
4133 			return -EINVAL;
4134 		offset = __btf_member_bit_offset(n, member);
4135 		if (offset % 8)
4136 			return -EINVAL;
4137 		offset /= 8;
4138 		if (offset % node_type_align)
4139 			return -EINVAL;
4140 
4141 		field->graph_root.btf = (struct btf *)btf;
4142 		field->graph_root.value_btf_id = info->graph_root.value_btf_id;
4143 		field->graph_root.node_offset = offset;
4144 	}
4145 	if (!n)
4146 		return -ENOENT;
4147 	return 0;
4148 }
4149 
4150 static int btf_parse_list_head(const struct btf *btf, struct btf_field *field,
4151 			       struct btf_field_info *info)
4152 {
4153 	return btf_parse_graph_root(btf, field, info, "bpf_list_node",
4154 					    __alignof__(struct bpf_list_node));
4155 }
4156 
4157 static int btf_parse_rb_root(const struct btf *btf, struct btf_field *field,
4158 			     struct btf_field_info *info)
4159 {
4160 	return btf_parse_graph_root(btf, field, info, "bpf_rb_node",
4161 					    __alignof__(struct bpf_rb_node));
4162 }
4163 
4164 static int btf_field_cmp(const void *_a, const void *_b, const void *priv)
4165 {
4166 	const struct btf_field *a = (const struct btf_field *)_a;
4167 	const struct btf_field *b = (const struct btf_field *)_b;
4168 
4169 	if (a->offset < b->offset)
4170 		return -1;
4171 	else if (a->offset > b->offset)
4172 		return 1;
4173 	return 0;
4174 }
4175 
4176 struct btf_record *btf_parse_fields(const struct btf *btf, const struct btf_type *t,
4177 				    u32 field_mask, u32 value_size)
4178 {
4179 	struct btf_field_info info_arr[BTF_FIELDS_MAX];
4180 	u32 next_off = 0, field_type_size;
4181 	struct btf_record *rec;
4182 	int ret, i, cnt;
4183 
4184 	ret = btf_find_field(btf, t, field_mask, info_arr, ARRAY_SIZE(info_arr));
4185 	if (ret < 0)
4186 		return ERR_PTR(ret);
4187 	if (!ret)
4188 		return NULL;
4189 
4190 	cnt = ret;
4191 	/* This needs to be kzalloc to zero out padding and unused fields, see
4192 	 * comment in btf_record_equal.
4193 	 */
4194 	rec = kzalloc_flex(*rec, fields, cnt, GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
4195 	if (!rec)
4196 		return ERR_PTR(-ENOMEM);
4197 
4198 	rec->spin_lock_off = -EINVAL;
4199 	rec->res_spin_lock_off = -EINVAL;
4200 	rec->timer_off = -EINVAL;
4201 	rec->wq_off = -EINVAL;
4202 	rec->refcount_off = -EINVAL;
4203 	rec->task_work_off = -EINVAL;
4204 	rec->rcu_head_off = -EINVAL;
4205 	for (i = 0; i < cnt; i++) {
4206 		field_type_size = btf_field_type_size(info_arr[i].type);
4207 		if (info_arr[i].off + field_type_size > value_size) {
4208 			WARN_ONCE(1, "verifier bug off %d size %d", info_arr[i].off, value_size);
4209 			ret = -EFAULT;
4210 			goto end;
4211 		}
4212 		if (info_arr[i].off < next_off) {
4213 			ret = -EEXIST;
4214 			goto end;
4215 		}
4216 		next_off = info_arr[i].off + field_type_size;
4217 
4218 		rec->field_mask |= info_arr[i].type;
4219 		rec->fields[i].offset = info_arr[i].off;
4220 		rec->fields[i].type = info_arr[i].type;
4221 		rec->fields[i].size = field_type_size;
4222 
4223 		switch (info_arr[i].type) {
4224 		case BPF_SPIN_LOCK:
4225 			WARN_ON_ONCE(rec->spin_lock_off >= 0);
4226 			/* Cache offset for faster lookup at runtime */
4227 			rec->spin_lock_off = rec->fields[i].offset;
4228 			break;
4229 		case BPF_RES_SPIN_LOCK:
4230 			WARN_ON_ONCE(rec->res_spin_lock_off >= 0);
4231 			/* Cache offset for faster lookup at runtime */
4232 			rec->res_spin_lock_off = rec->fields[i].offset;
4233 			break;
4234 		case BPF_TIMER:
4235 			WARN_ON_ONCE(rec->timer_off >= 0);
4236 			/* Cache offset for faster lookup at runtime */
4237 			rec->timer_off = rec->fields[i].offset;
4238 			break;
4239 		case BPF_WORKQUEUE:
4240 			WARN_ON_ONCE(rec->wq_off >= 0);
4241 			/* Cache offset for faster lookup at runtime */
4242 			rec->wq_off = rec->fields[i].offset;
4243 			break;
4244 		case BPF_TASK_WORK:
4245 			WARN_ON_ONCE(rec->task_work_off >= 0);
4246 			rec->task_work_off = rec->fields[i].offset;
4247 			break;
4248 		case BPF_RCU_HEAD:
4249 			WARN_ON_ONCE(rec->rcu_head_off >= 0);
4250 			rec->rcu_head_off = rec->fields[i].offset;
4251 			break;
4252 		case BPF_REFCOUNT:
4253 			WARN_ON_ONCE(rec->refcount_off >= 0);
4254 			/* Cache offset for faster lookup at runtime */
4255 			rec->refcount_off = rec->fields[i].offset;
4256 			break;
4257 		case BPF_KPTR_UNREF:
4258 		case BPF_KPTR_REF:
4259 		case BPF_KPTR_PERCPU:
4260 		case BPF_UPTR:
4261 			ret = btf_parse_kptr(btf, &rec->fields[i], &info_arr[i]);
4262 			if (ret < 0)
4263 				goto end;
4264 			break;
4265 		case BPF_LIST_HEAD:
4266 			ret = btf_parse_list_head(btf, &rec->fields[i], &info_arr[i]);
4267 			if (ret < 0)
4268 				goto end;
4269 			break;
4270 		case BPF_RB_ROOT:
4271 			ret = btf_parse_rb_root(btf, &rec->fields[i], &info_arr[i]);
4272 			if (ret < 0)
4273 				goto end;
4274 			break;
4275 		case BPF_LIST_NODE:
4276 		case BPF_RB_NODE:
4277 			break;
4278 		default:
4279 			ret = -EFAULT;
4280 			goto end;
4281 		}
4282 		rec->cnt++;
4283 	}
4284 
4285 	if (rec->spin_lock_off >= 0 && rec->res_spin_lock_off >= 0) {
4286 		ret = -EINVAL;
4287 		goto end;
4288 	}
4289 
4290 	/* bpf_{list_head, rb_node} require bpf_spin_lock */
4291 	if ((btf_record_has_field(rec, BPF_LIST_HEAD) ||
4292 	     btf_record_has_field(rec, BPF_RB_ROOT)) &&
4293 		 (rec->spin_lock_off < 0 && rec->res_spin_lock_off < 0)) {
4294 		ret = -EINVAL;
4295 		goto end;
4296 	}
4297 
4298 	if (rec->refcount_off < 0 &&
4299 	    btf_record_has_field(rec, BPF_LIST_NODE) &&
4300 	    btf_record_has_field(rec, BPF_RB_NODE)) {
4301 		ret = -EINVAL;
4302 		goto end;
4303 	}
4304 
4305 	sort_r(rec->fields, rec->cnt, sizeof(struct btf_field), btf_field_cmp,
4306 	       NULL, rec);
4307 
4308 	return rec;
4309 end:
4310 	btf_record_free(rec);
4311 	return ERR_PTR(ret);
4312 }
4313 
4314 int btf_check_and_fixup_fields(const struct btf *btf, struct btf_record *rec)
4315 {
4316 	int i;
4317 
4318 	/*
4319 	 * Check fields which require the complete BTF and initialize runtime
4320 	 * metadata. Ownership relationships are validated after every record has
4321 	 * been fixed up.
4322 	 */
4323 	if (IS_ERR_OR_NULL(rec) || !(rec->field_mask & (BPF_GRAPH_ROOT | BPF_UPTR)))
4324 		return 0;
4325 	for (i = 0; i < rec->cnt; i++) {
4326 		struct btf_struct_meta *meta;
4327 		const struct btf_type *t;
4328 		u32 btf_id;
4329 
4330 		if (rec->fields[i].type == BPF_UPTR) {
4331 			/* The uptr only supports pinning one page and cannot
4332 			 * point to a kernel struct
4333 			 */
4334 			if (btf_is_kernel(rec->fields[i].kptr.btf))
4335 				return -EINVAL;
4336 			t = btf_type_by_id(rec->fields[i].kptr.btf,
4337 					   rec->fields[i].kptr.btf_id);
4338 			if (!t->size)
4339 				return -EINVAL;
4340 			if (t->size > PAGE_SIZE)
4341 				return -E2BIG;
4342 			continue;
4343 		}
4344 
4345 		if (!(rec->fields[i].type & BPF_GRAPH_ROOT))
4346 			continue;
4347 		btf_id = rec->fields[i].graph_root.value_btf_id;
4348 		meta = btf_find_struct_meta(btf, btf_id);
4349 		if (!meta)
4350 			return -EFAULT;
4351 		rec->fields[i].graph_root.value_rec = meta->record;
4352 	}
4353 	return 0;
4354 }
4355 
4356 static int btf_owned_type_idx(const struct btf *btf, struct btf_struct_metas *tab,
4357 			      const struct btf_field *field)
4358 {
4359 	struct btf_struct_meta *meta;
4360 	u32 btf_id;
4361 
4362 	if (field->type & BPF_GRAPH_ROOT) {
4363 		btf_id = field->graph_root.value_btf_id;
4364 	} else if (field->type == BPF_KPTR_REF || field->type == BPF_KPTR_PERCPU) {
4365 		if (btf_is_kernel(field->kptr.btf))
4366 			return -ENOENT;
4367 		btf_id = field->kptr.btf_id;
4368 	} else {
4369 		return -ENOENT;
4370 	}
4371 
4372 	meta = btf_find_struct_meta(btf, btf_id);
4373 	if (!meta)
4374 		return field->type & BPF_GRAPH_ROOT ? -EFAULT : -ENOENT;
4375 	return meta - tab->types;
4376 }
4377 
4378 /*
4379  * Each ownership edge adds kernel frames through bpf_obj_free_fields() and
4380  * __bpf_obj_drop_impl(). Keep the bound deliberately small because object
4381  * destruction can itself run below a BPF call chain. A final pointee without
4382  * special fields is not present in the struct metadata table and adds only a
4383  * non-recursing drop.
4384  */
4385 #define BTF_MAX_OWNERSHIP_DEPTH 8
4386 
4387 static int btf_ownership_depth(const struct btf *btf,
4388 			       struct btf_struct_metas *tab, u8 *depth,
4389 			       int idx, int depth_left)
4390 {
4391 	const struct btf_record *rec = tab->types[idx].record;
4392 	int i, ret, max_depth = 0;
4393 
4394 	if (!depth_left)
4395 		return -ELOOP;
4396 	if (depth[idx])
4397 		goto done;
4398 
4399 	for (i = 0; i < rec->cnt; i++) {
4400 		ret = btf_owned_type_idx(btf, tab, &rec->fields[i]);
4401 		if (ret == -ENOENT)
4402 			continue;
4403 		if (ret < 0)
4404 			return ret;
4405 		ret = btf_ownership_depth(btf, tab, depth, ret, depth_left - 1);
4406 		if (ret < 0)
4407 			return ret;
4408 		max_depth = max(max_depth, ret);
4409 	}
4410 	depth[idx] = max_depth + 1;
4411 done:
4412 	return depth[idx] > depth_left ? -ELOOP : depth[idx];
4413 }
4414 
4415 static int btf_check_ownership_depth(const struct btf *btf,
4416 				     struct btf_struct_metas *tab)
4417 {
4418 	u8 *depth;
4419 	int i, ret = 0;
4420 
4421 	depth = kvcalloc(tab->cnt, sizeof(*depth), GFP_KERNEL | __GFP_NOWARN);
4422 	if (!depth)
4423 		return -ENOMEM;
4424 
4425 	for (i = 0; i < tab->cnt; i++) {
4426 		ret = btf_ownership_depth(btf, tab, depth, i,
4427 					  BTF_MAX_OWNERSHIP_DEPTH);
4428 		if (ret < 0)
4429 			break;
4430 		ret = 0;
4431 	}
4432 	kvfree(depth);
4433 	return ret;
4434 }
4435 
4436 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
4437 			      u32 type_id, void *data, u8 bits_offset,
4438 			      struct btf_show *show)
4439 {
4440 	const struct btf_member *member;
4441 	void *safe_data;
4442 	u32 i;
4443 
4444 	safe_data = btf_show_start_struct_type(show, t, type_id, data);
4445 	if (!safe_data)
4446 		return;
4447 
4448 	for_each_member(i, t, member) {
4449 		const struct btf_type *member_type = btf_type_by_id(btf,
4450 								member->type);
4451 		const struct btf_kind_operations *ops;
4452 		u32 member_offset, bitfield_size;
4453 		u32 bytes_offset;
4454 		u8 bits8_offset;
4455 
4456 		btf_show_start_member(show, member);
4457 
4458 		member_offset = __btf_member_bit_offset(t, member);
4459 		bitfield_size = __btf_member_bitfield_size(t, member);
4460 		bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
4461 		bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
4462 		if (bitfield_size) {
4463 			safe_data = btf_show_start_type(show, member_type,
4464 							member->type,
4465 							data + bytes_offset);
4466 			if (safe_data)
4467 				btf_bitfield_show(safe_data,
4468 						  bits8_offset,
4469 						  bitfield_size, show);
4470 			btf_show_end_type(show);
4471 		} else {
4472 			ops = btf_type_ops(member_type);
4473 			ops->show(btf, member_type, member->type,
4474 				  data + bytes_offset, bits8_offset, show);
4475 		}
4476 
4477 		btf_show_end_member(show);
4478 	}
4479 
4480 	btf_show_end_struct_type(show);
4481 }
4482 
4483 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
4484 			    u32 type_id, void *data, u8 bits_offset,
4485 			    struct btf_show *show)
4486 {
4487 	const struct btf_member *m = show->state.member;
4488 
4489 	/*
4490 	 * First check if any members would be shown (are non-zero).
4491 	 * See comments above "struct btf_show" definition for more
4492 	 * details on how this works at a high-level.
4493 	 */
4494 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
4495 		if (!show->state.depth_check) {
4496 			show->state.depth_check = show->state.depth + 1;
4497 			show->state.depth_to_show = 0;
4498 		}
4499 		__btf_struct_show(btf, t, type_id, data, bits_offset, show);
4500 		/* Restore saved member data here */
4501 		show->state.member = m;
4502 		if (show->state.depth_check != show->state.depth + 1)
4503 			return;
4504 		show->state.depth_check = 0;
4505 
4506 		if (show->state.depth_to_show <= show->state.depth)
4507 			return;
4508 		/*
4509 		 * Reaching here indicates we have recursed and found
4510 		 * non-zero child values.
4511 		 */
4512 	}
4513 
4514 	__btf_struct_show(btf, t, type_id, data, bits_offset, show);
4515 }
4516 
4517 static const struct btf_kind_operations struct_ops = {
4518 	.check_meta = btf_struct_check_meta,
4519 	.resolve = btf_struct_resolve,
4520 	.check_member = btf_struct_check_member,
4521 	.check_kflag_member = btf_generic_check_kflag_member,
4522 	.log_details = btf_struct_log,
4523 	.show = btf_struct_show,
4524 };
4525 
4526 static int btf_enum_check_member(struct btf_verifier_env *env,
4527 				 const struct btf_type *struct_type,
4528 				 const struct btf_member *member,
4529 				 const struct btf_type *member_type)
4530 {
4531 	u32 struct_bits_off = member->offset;
4532 	u32 struct_size, bytes_offset;
4533 
4534 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4535 		btf_verifier_log_member(env, struct_type, member,
4536 					"Member is not byte aligned");
4537 		return -EINVAL;
4538 	}
4539 
4540 	struct_size = struct_type->size;
4541 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
4542 	if (struct_size - bytes_offset < member_type->size) {
4543 		btf_verifier_log_member(env, struct_type, member,
4544 					"Member exceeds struct_size");
4545 		return -EINVAL;
4546 	}
4547 
4548 	return 0;
4549 }
4550 
4551 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
4552 				       const struct btf_type *struct_type,
4553 				       const struct btf_member *member,
4554 				       const struct btf_type *member_type)
4555 {
4556 	u32 struct_bits_off, nr_bits, bytes_end, struct_size;
4557 	u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
4558 
4559 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
4560 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
4561 	if (!nr_bits) {
4562 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
4563 			btf_verifier_log_member(env, struct_type, member,
4564 						"Member is not byte aligned");
4565 			return -EINVAL;
4566 		}
4567 
4568 		nr_bits = int_bitsize;
4569 	} else if (nr_bits > int_bitsize) {
4570 		btf_verifier_log_member(env, struct_type, member,
4571 					"Invalid member bitfield_size");
4572 		return -EINVAL;
4573 	}
4574 
4575 	struct_size = struct_type->size;
4576 	bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
4577 	if (struct_size < bytes_end) {
4578 		btf_verifier_log_member(env, struct_type, member,
4579 					"Member exceeds struct_size");
4580 		return -EINVAL;
4581 	}
4582 
4583 	return 0;
4584 }
4585 
4586 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
4587 			       const struct btf_type *t,
4588 			       u32 meta_left)
4589 {
4590 	const struct btf_enum *enums = btf_type_enum(t);
4591 	struct btf *btf = env->btf;
4592 	const char *fmt_str;
4593 	u32 i, nr_enums;
4594 	u32 meta_needed;
4595 
4596 	nr_enums = btf_type_vlen(t);
4597 	meta_needed = nr_enums * sizeof(*enums);
4598 
4599 	if (meta_left < meta_needed) {
4600 		btf_verifier_log_basic(env, t,
4601 				       "meta_left:%u meta_needed:%u",
4602 				       meta_left, meta_needed);
4603 		return -EINVAL;
4604 	}
4605 
4606 	if (t->size > 8 || !is_power_of_2(t->size)) {
4607 		btf_verifier_log_type(env, t, "Unexpected size");
4608 		return -EINVAL;
4609 	}
4610 
4611 	/* enum type either no name or a valid one */
4612 	if (t->name_off &&
4613 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4614 		btf_verifier_log_type(env, t, "Invalid name");
4615 		return -EINVAL;
4616 	}
4617 
4618 	btf_verifier_log_type(env, t, NULL);
4619 
4620 	for (i = 0; i < nr_enums; i++) {
4621 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4622 			btf_verifier_log(env, "\tInvalid name_offset:%u",
4623 					 enums[i].name_off);
4624 			return -EINVAL;
4625 		}
4626 
4627 		/* enum member must have a valid name */
4628 		if (!enums[i].name_off ||
4629 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
4630 			btf_verifier_log_type(env, t, "Invalid name");
4631 			return -EINVAL;
4632 		}
4633 
4634 		if (env->log.level == BPF_LOG_KERNEL)
4635 			continue;
4636 		fmt_str = btf_type_kflag(t) ? "\t%s val=%d\n" : "\t%s val=%u\n";
4637 		btf_verifier_log(env, fmt_str,
4638 				 __btf_name_by_offset(btf, enums[i].name_off),
4639 				 enums[i].val);
4640 	}
4641 
4642 	return meta_needed;
4643 }
4644 
4645 static void btf_enum_log(struct btf_verifier_env *env,
4646 			 const struct btf_type *t)
4647 {
4648 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
4649 }
4650 
4651 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
4652 			  u32 type_id, void *data, u8 bits_offset,
4653 			  struct btf_show *show)
4654 {
4655 	const struct btf_enum *enums = btf_type_enum(t);
4656 	u32 i, nr_enums = btf_type_vlen(t);
4657 	void *safe_data;
4658 	int v;
4659 
4660 	safe_data = btf_show_start_type(show, t, type_id, data);
4661 	if (!safe_data)
4662 		return;
4663 
4664 	v = *(int *)safe_data;
4665 
4666 	for (i = 0; i < nr_enums; i++) {
4667 		if (v != enums[i].val)
4668 			continue;
4669 
4670 		btf_show_type_value(show, "%s",
4671 				    __btf_name_by_offset(btf,
4672 							 enums[i].name_off));
4673 
4674 		btf_show_end_type(show);
4675 		return;
4676 	}
4677 
4678 	if (btf_type_kflag(t))
4679 		btf_show_type_value(show, "%d", v);
4680 	else
4681 		btf_show_type_value(show, "%u", v);
4682 	btf_show_end_type(show);
4683 }
4684 
4685 static const struct btf_kind_operations enum_ops = {
4686 	.check_meta = btf_enum_check_meta,
4687 	.resolve = btf_df_resolve,
4688 	.check_member = btf_enum_check_member,
4689 	.check_kflag_member = btf_enum_check_kflag_member,
4690 	.log_details = btf_enum_log,
4691 	.show = btf_enum_show,
4692 };
4693 
4694 static s32 btf_enum64_check_meta(struct btf_verifier_env *env,
4695 				 const struct btf_type *t,
4696 				 u32 meta_left)
4697 {
4698 	const struct btf_enum64 *enums = btf_type_enum64(t);
4699 	struct btf *btf = env->btf;
4700 	const char *fmt_str;
4701 	u32 i, nr_enums;
4702 	u32 meta_needed;
4703 
4704 	nr_enums = btf_type_vlen(t);
4705 	meta_needed = nr_enums * sizeof(*enums);
4706 
4707 	if (meta_left < meta_needed) {
4708 		btf_verifier_log_basic(env, t,
4709 				       "meta_left:%u meta_needed:%u",
4710 				       meta_left, meta_needed);
4711 		return -EINVAL;
4712 	}
4713 
4714 	if (t->size > 8 || !is_power_of_2(t->size)) {
4715 		btf_verifier_log_type(env, t, "Unexpected size");
4716 		return -EINVAL;
4717 	}
4718 
4719 	/* enum type either no name or a valid one */
4720 	if (t->name_off &&
4721 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
4722 		btf_verifier_log_type(env, t, "Invalid name");
4723 		return -EINVAL;
4724 	}
4725 
4726 	btf_verifier_log_type(env, t, NULL);
4727 
4728 	for (i = 0; i < nr_enums; i++) {
4729 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
4730 			btf_verifier_log(env, "\tInvalid name_offset:%u",
4731 					 enums[i].name_off);
4732 			return -EINVAL;
4733 		}
4734 
4735 		/* enum member must have a valid name */
4736 		if (!enums[i].name_off ||
4737 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
4738 			btf_verifier_log_type(env, t, "Invalid name");
4739 			return -EINVAL;
4740 		}
4741 
4742 		if (env->log.level == BPF_LOG_KERNEL)
4743 			continue;
4744 
4745 		fmt_str = btf_type_kflag(t) ? "\t%s val=%lld\n" : "\t%s val=%llu\n";
4746 		btf_verifier_log(env, fmt_str,
4747 				 __btf_name_by_offset(btf, enums[i].name_off),
4748 				 btf_enum64_value(enums + i));
4749 	}
4750 
4751 	return meta_needed;
4752 }
4753 
4754 static void btf_enum64_show(const struct btf *btf, const struct btf_type *t,
4755 			    u32 type_id, void *data, u8 bits_offset,
4756 			    struct btf_show *show)
4757 {
4758 	const struct btf_enum64 *enums = btf_type_enum64(t);
4759 	u32 i, nr_enums = btf_type_vlen(t);
4760 	void *safe_data;
4761 	s64 v;
4762 
4763 	safe_data = btf_show_start_type(show, t, type_id, data);
4764 	if (!safe_data)
4765 		return;
4766 
4767 	v = *(u64 *)safe_data;
4768 
4769 	for (i = 0; i < nr_enums; i++) {
4770 		if (v != btf_enum64_value(enums + i))
4771 			continue;
4772 
4773 		btf_show_type_value(show, "%s",
4774 				    __btf_name_by_offset(btf,
4775 							 enums[i].name_off));
4776 
4777 		btf_show_end_type(show);
4778 		return;
4779 	}
4780 
4781 	if (btf_type_kflag(t))
4782 		btf_show_type_value(show, "%lld", v);
4783 	else
4784 		btf_show_type_value(show, "%llu", v);
4785 	btf_show_end_type(show);
4786 }
4787 
4788 static const struct btf_kind_operations enum64_ops = {
4789 	.check_meta = btf_enum64_check_meta,
4790 	.resolve = btf_df_resolve,
4791 	.check_member = btf_enum_check_member,
4792 	.check_kflag_member = btf_enum_check_kflag_member,
4793 	.log_details = btf_enum_log,
4794 	.show = btf_enum64_show,
4795 };
4796 
4797 static s32 btf_loc_param_check_meta(struct btf_verifier_env *env,
4798 				    const struct btf_type *t,
4799 				    u32 meta_left)
4800 {
4801 	const struct btf_loc_param *p = btf_loc_param(t);
4802 	u32 size, meta_needed, vlen = btf_vlen(t);
4803 
4804 	meta_needed = sizeof(*p) + sizeof(__u32) * vlen;
4805 	if (meta_left < meta_needed) {
4806 		btf_verifier_log_basic(env, t,
4807 				       "meta_left:%u meta_needed:%u",
4808 				      meta_left, meta_needed);
4809 		return -EINVAL;
4810 	}
4811 
4812 	if (t->name_off) {
4813 		btf_verifier_log_type(env, t, "Invalid name");
4814 		return -EINVAL;
4815 	}
4816 	size = t->size;
4817 	if (!size || size > 16) {
4818 		btf_verifier_log_type(env, t, "Unexpected size");
4819 		return -EINVAL;
4820 	}
4821 
4822 	if (btf_type_kflag(t)) {
4823 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4824 		return -EINVAL;
4825 	}
4826 	/* All LOC_PARAMs have vlen of at least 1 */
4827 	if (vlen < 1)
4828 		goto invalid_vlen;
4829 
4830 	switch (p->flags) {
4831 	case BTF_LOC_PARAM_CONST:
4832 	case BTF_LOC_PARAM_CONST | BTF_LOC_PARAM_SIGNED:
4833 	case BTF_LOC_PARAM_CONST | BTF_LOC_PARAM_ADDR:
4834 	case BTF_LOC_PARAM_CONST | BTF_LOC_PARAM_ADDR | BTF_LOC_PARAM_SIGNED:
4835 		if (vlen > 2)
4836 			goto invalid_vlen;
4837 		/* Ensure size/vlen are consistent */
4838 		if (size > sizeof(__u32) && vlen != 2)
4839 			goto invalid_vlen;
4840 		if (size > sizeof(__u64))
4841 			goto invalid_vlen;
4842 		break;
4843 	case BTF_LOC_PARAM_REG:
4844 		/* Reg or reg/reg pair */
4845 		if (vlen > 2)
4846 			goto invalid_vlen;
4847 		break;
4848 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_DEREF:
4849 		/* A reg deref without offset can only have vlen 1 */
4850 		if (vlen != 1)
4851 			goto invalid_vlen;
4852 		break;
4853 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_OFFSET:
4854 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_OFFSET | BTF_LOC_PARAM_SIGNED:
4855 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_DEREF | BTF_LOC_PARAM_OFFSET:
4856 	case BTF_LOC_PARAM_REG | BTF_LOC_PARAM_DEREF | BTF_LOC_PARAM_OFFSET |
4857 	     BTF_LOC_PARAM_SIGNED:
4858 		if (vlen < 2 || vlen > 3)
4859 			goto invalid_vlen;
4860 		break;
4861 	default:
4862 		btf_verifier_log_type(env, t, "Invalid flags");
4863 		return -EINVAL;
4864 	}
4865 
4866 	btf_verifier_log_type(env, t, NULL);
4867 
4868 	return meta_needed;
4869 
4870 invalid_vlen:
4871 	btf_verifier_log_type(env, t, "Invalid vlen");
4872 	return -EINVAL;
4873 }
4874 
4875 static void btf_loc_param_log(struct btf_verifier_env *env,
4876 			 const struct btf_type *t)
4877 {
4878 	const struct btf_loc_param *p = btf_loc_param(t);
4879 	u32 i, vlen = btf_vlen(t);
4880 
4881 	btf_verifier_log(env, "size=%u vlen=%u flags=0x%x", t->size, vlen, p->flags);
4882 	for (i = 0; i < vlen; i++)
4883 		btf_verifier_log(env, ", %u", p->values[i]);
4884 }
4885 
4886 static const struct btf_kind_operations loc_param_ops = {
4887 	.check_meta = btf_loc_param_check_meta,
4888 	.resolve = btf_df_resolve,
4889 	.check_member = btf_df_check_member,
4890 	.check_kflag_member = btf_df_check_kflag_member,
4891 	.log_details = btf_loc_param_log,
4892 	.show = btf_df_show,
4893 };
4894 
4895 static s32 btf_loc_proto_check_meta(struct btf_verifier_env *env,
4896 				    const struct btf_type *t,
4897 				    u32 meta_left)
4898 {
4899 	u32 meta_needed;
4900 
4901 	meta_needed = sizeof(__u32) * btf_type_vlen(t);
4902 
4903 	if (meta_left < meta_needed) {
4904 		btf_verifier_log_basic(env, t,
4905 				       "meta_left:%u meta_needed:%u",
4906 				      meta_left, meta_needed);
4907 		return -EINVAL;
4908 	}
4909 
4910 	if (t->name_off) {
4911 		btf_verifier_log_type(env, t, "Invalid name");
4912 		return -EINVAL;
4913 	}
4914 
4915 	if (btf_type_kflag(t)) {
4916 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
4917 		return -EINVAL;
4918 	}
4919 
4920 	btf_verifier_log_type(env, t, NULL);
4921 
4922 	return meta_needed;
4923 }
4924 
4925 static void btf_loc_proto_log(struct btf_verifier_env *env,
4926 			      const struct btf_type *t)
4927 {
4928 	const __u32 *params = btf_loc_proto_params(t);
4929 	u32 i, nr_params = btf_type_vlen(t);
4930 
4931 	btf_verifier_log(env, "vlen=%u", nr_params);
4932 	for (i = 0; i < nr_params; i++, params++)
4933 		btf_verifier_log(env, ", %u", *params);
4934 }
4935 
4936 static int btf_loc_proto_resolve(struct btf_verifier_env *env,
4937 				 const struct resolve_vertex *v)
4938 {
4939 	const struct btf_type *t = v->t;
4940 	const __u32 *params = btf_loc_proto_params(t);
4941 	u32 i, nr_params = btf_type_vlen(t);
4942 	struct btf *btf = env->btf;
4943 
4944 	if (t->type) {
4945 		btf_verifier_log_type(env, t, "Invalid loc_proto type");
4946 		return -EINVAL;
4947 	}
4948 
4949 	for (i = 0; i < nr_params; i++) {
4950 		const struct btf_type *param_type;
4951 		u32 param_type_id = params[i];
4952 
4953 		if (!param_type_id)
4954 			continue;
4955 
4956 		param_type = btf_type_by_id(btf, param_type_id);
4957 		if (!param_type || !btf_type_is_loc_param(param_type)) {
4958 			btf_verifier_log_type(env, t,
4959 					      "Invalid loc_param#%u", i + 1);
4960 			return -EINVAL;
4961 		}
4962 	}
4963 
4964 	env_stack_pop_resolved(env, 0, 0);
4965 	return 0;
4966 }
4967 
4968 static const struct btf_kind_operations loc_proto_ops = {
4969 	.check_meta = btf_loc_proto_check_meta,
4970 	.resolve = btf_loc_proto_resolve,
4971 	.check_member = btf_df_check_member,
4972 	.check_kflag_member = btf_df_check_kflag_member,
4973 	.log_details = btf_loc_proto_log,
4974 	.show = btf_df_show,
4975 };
4976 
4977 __printf(4, 5)
4978 static void btf_verifier_log_loc(struct btf_verifier_env *env,
4979 				 const struct btf_type *locsec_type,
4980 				 const struct btf_loc *loc,
4981 				 const char *fmt, ...)
4982 {
4983 	struct bpf_verifier_log *log = &env->log;
4984 	va_list args;
4985 
4986 	if (!bpf_verifier_log_needed(log))
4987 		return;
4988 	if (log->level == BPF_LOG_KERNEL && !fmt)
4989 		return;
4990 	if (env->phase != CHECK_META)
4991 		btf_verifier_log_type(env, locsec_type, NULL);
4992 
4993 	__btf_verifier_log(log, "\t func=%u loc_proto=%u offset=%u",
4994 			   loc->func, loc->loc_proto, loc->offset);
4995 	if (fmt && *fmt) {
4996 		__btf_verifier_log(log, " ");
4997 		va_start(args, fmt);
4998 		bpf_verifier_vlog(log, fmt, args);
4999 		va_end(args);
5000 	}
5001 
5002 	__btf_verifier_log(log, "\n");
5003 }
5004 
5005 static s32 btf_locsec_check_meta(struct btf_verifier_env *env,
5006 				 const struct btf_type *t,
5007 				 u32 meta_left)
5008 {
5009 	u32 i, meta_needed, vlen = btf_type_vlen(t);
5010 	const struct btf_loc *loc;
5011 
5012 	meta_needed = sizeof(struct btf_loc) * vlen;
5013 
5014 	if (meta_left < meta_needed) {
5015 		btf_verifier_log_basic(env, t,
5016 				       "meta_left:%u meta_needed:%u",
5017 				       meta_left, meta_needed);
5018 		return -EINVAL;
5019 	}
5020 
5021 	if (btf_type_kflag(t)) {
5022 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5023 		return -EINVAL;
5024 	}
5025 
5026 	if (!t->name_off ||
5027 	    !btf_name_valid_section(env->btf, t->name_off)) {
5028 		btf_verifier_log_type(env, t, "Invalid name");
5029 		return -EINVAL;
5030 	}
5031 
5032 	for_each_loc(i, t, loc) {
5033 		/* A loc func, loc proto cannot be in type void */
5034 		if (!loc->func || !BTF_TYPE_ID_VALID(loc->func)) {
5035 			btf_verifier_log_loc(env, t, loc, "Invalid func");
5036 			return -EINVAL;
5037 		}
5038 		if (!loc->loc_proto || !BTF_TYPE_ID_VALID(loc->loc_proto)) {
5039 			btf_verifier_log_loc(env, t, loc, "Invalid loc_proto");
5040 			return -EINVAL;
5041 		}
5042 		btf_verifier_log_loc(env, t, loc, NULL);
5043 	}
5044 
5045 	return meta_needed;
5046 }
5047 
5048 static void btf_locsec_log(struct btf_verifier_env *env,
5049 			   const struct btf_type *t)
5050 {
5051 	btf_verifier_log(env, "vlen=%u", btf_type_vlen(t));
5052 }
5053 
5054 static int btf_locsec_resolve(struct btf_verifier_env *env,
5055 			      const struct resolve_vertex *v)
5056 {
5057 	const struct btf_type *t = v->t;
5058 	const struct btf_loc *loc;
5059 	struct btf *btf = env->btf;
5060 	u32 i;
5061 
5062 	if (t->type) {
5063 		btf_verifier_log_type(env, t, "Invalid locsec type");
5064 		return -EINVAL;
5065 	}
5066 
5067 	env->resolve_mode = RESOLVE_TBD;
5068 	for (i = v->next_member, loc = btf_type_loc_secinfo(t) + i;
5069 	     i < btf_type_vlen(t); i++, loc++) {
5070 		const struct btf_type *func_type, *func_proto_type;
5071 		const struct btf_type *loc_proto_type;
5072 		u32 func_type_id = loc->func;
5073 		u32 loc_proto_type_id = loc->loc_proto;
5074 		u32 proto_vlen;
5075 
5076 		func_type = btf_type_by_id(btf, func_type_id);
5077 		if (!func_type || !btf_type_is_func(func_type)) {
5078 			btf_verifier_log_type(env, t,
5079 					      "Invalid func#%u", i + 1);
5080 			return -EINVAL;
5081 		}
5082 		func_proto_type = btf_type_by_id(btf, func_type->type);
5083 		if (!func_proto_type || !btf_type_is_func_proto(func_proto_type)) {
5084 			btf_verifier_log_type(env, t,
5085 					      "Invalid func#%u", i + 1);
5086 			return -EINVAL;
5087 		}
5088 		proto_vlen = btf_vlen(func_proto_type);
5089 
5090 		if (!env_type_is_resolved(env, func_type_id)) {
5091 			env_stack_set_next_member(env, i);
5092 			return env_stack_push(env, func_type, func_type_id);
5093 		}
5094 
5095 		loc_proto_type = btf_type_by_id(btf, loc_proto_type_id);
5096 		if (!loc_proto_type || !btf_type_is_loc_proto(loc_proto_type)) {
5097 			btf_verifier_log_type(env, t,
5098 					      "Invalid loc_proto#%u", i + 1);
5099 			return -EINVAL;
5100 		}
5101 		if (proto_vlen != btf_vlen(loc_proto_type)) {
5102 			btf_verifier_log_type(env, t,
5103 					      "Mismatched vlen for loc_proto#%u", i + 1);
5104 			return -EINVAL;
5105 		}
5106 
5107 		if (!env_type_is_resolved(env, loc_proto_type_id)) {
5108 			env_stack_set_next_member(env, i + 1);
5109 			return env_stack_push(env, loc_proto_type,
5110 					      loc_proto_type_id);
5111 		}
5112 	}
5113 
5114 	env_stack_pop_resolved(env, 0, 0);
5115 	return 0;
5116 }
5117 
5118 static const struct btf_kind_operations locsec_ops = {
5119 	.check_meta = btf_locsec_check_meta,
5120 	.resolve = btf_locsec_resolve,
5121 	.check_member = btf_df_check_member,
5122 	.check_kflag_member = btf_df_check_kflag_member,
5123 	.log_details = btf_locsec_log,
5124 	.show = btf_df_show,
5125 };
5126 
5127 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
5128 				     const struct btf_type *t,
5129 				     u32 meta_left)
5130 {
5131 	u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
5132 
5133 	if (meta_left < meta_needed) {
5134 		btf_verifier_log_basic(env, t,
5135 				       "meta_left:%u meta_needed:%u",
5136 				       meta_left, meta_needed);
5137 		return -EINVAL;
5138 	}
5139 
5140 	if (t->name_off) {
5141 		btf_verifier_log_type(env, t, "Invalid name");
5142 		return -EINVAL;
5143 	}
5144 
5145 	if (btf_type_kflag(t)) {
5146 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5147 		return -EINVAL;
5148 	}
5149 
5150 	btf_verifier_log_type(env, t, NULL);
5151 
5152 	return meta_needed;
5153 }
5154 
5155 static void btf_func_proto_log(struct btf_verifier_env *env,
5156 			       const struct btf_type *t)
5157 {
5158 	const struct btf_param *args = (const struct btf_param *)(t + 1);
5159 	u32 nr_args = btf_type_vlen(t), i;
5160 
5161 	btf_verifier_log(env, "return=%u args=(", t->type);
5162 	if (!nr_args) {
5163 		btf_verifier_log(env, "void");
5164 		goto done;
5165 	}
5166 
5167 	if (nr_args == 1 && !args[0].type) {
5168 		/* Only one vararg */
5169 		btf_verifier_log(env, "vararg");
5170 		goto done;
5171 	}
5172 
5173 	btf_verifier_log(env, "%u %s", args[0].type,
5174 			 __btf_name_by_offset(env->btf,
5175 					      args[0].name_off));
5176 	for (i = 1; i < nr_args - 1; i++)
5177 		btf_verifier_log(env, ", %u %s", args[i].type,
5178 				 __btf_name_by_offset(env->btf,
5179 						      args[i].name_off));
5180 
5181 	if (nr_args > 1) {
5182 		const struct btf_param *last_arg = &args[nr_args - 1];
5183 
5184 		if (last_arg->type)
5185 			btf_verifier_log(env, ", %u %s", last_arg->type,
5186 					 __btf_name_by_offset(env->btf,
5187 							      last_arg->name_off));
5188 		else
5189 			btf_verifier_log(env, ", vararg");
5190 	}
5191 
5192 done:
5193 	btf_verifier_log(env, ")");
5194 }
5195 
5196 static const struct btf_kind_operations func_proto_ops = {
5197 	.check_meta = btf_func_proto_check_meta,
5198 	.resolve = btf_df_resolve,
5199 	/*
5200 	 * BTF_KIND_FUNC_PROTO cannot be directly referred by
5201 	 * a struct's member.
5202 	 *
5203 	 * It should be a function pointer instead.
5204 	 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
5205 	 *
5206 	 * Hence, there is no btf_func_check_member().
5207 	 */
5208 	.check_member = btf_df_check_member,
5209 	.check_kflag_member = btf_df_check_kflag_member,
5210 	.log_details = btf_func_proto_log,
5211 	.show = btf_df_show,
5212 };
5213 
5214 static s32 btf_func_check_meta(struct btf_verifier_env *env,
5215 			       const struct btf_type *t,
5216 			       u32 meta_left)
5217 {
5218 	if (!t->name_off ||
5219 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
5220 		btf_verifier_log_type(env, t, "Invalid name");
5221 		return -EINVAL;
5222 	}
5223 
5224 	if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
5225 		btf_verifier_log_type(env, t, "Invalid func linkage");
5226 		return -EINVAL;
5227 	}
5228 
5229 	if (btf_type_kflag(t)) {
5230 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5231 		return -EINVAL;
5232 	}
5233 
5234 	btf_verifier_log_type(env, t, NULL);
5235 
5236 	return 0;
5237 }
5238 
5239 static int btf_func_resolve(struct btf_verifier_env *env,
5240 			    const struct resolve_vertex *v)
5241 {
5242 	const struct btf_type *t = v->t;
5243 	u32 next_type_id = t->type;
5244 	int err;
5245 
5246 	err = btf_func_check(env, t);
5247 	if (err)
5248 		return err;
5249 
5250 	env_stack_pop_resolved(env, next_type_id, 0);
5251 	return 0;
5252 }
5253 
5254 static const struct btf_kind_operations func_ops = {
5255 	.check_meta = btf_func_check_meta,
5256 	.resolve = btf_func_resolve,
5257 	.check_member = btf_df_check_member,
5258 	.check_kflag_member = btf_df_check_kflag_member,
5259 	.log_details = btf_ref_type_log,
5260 	.show = btf_df_show,
5261 };
5262 
5263 static s32 btf_var_check_meta(struct btf_verifier_env *env,
5264 			      const struct btf_type *t,
5265 			      u32 meta_left)
5266 {
5267 	const struct btf_var *var;
5268 	u32 meta_needed = sizeof(*var);
5269 
5270 	if (meta_left < meta_needed) {
5271 		btf_verifier_log_basic(env, t,
5272 				       "meta_left:%u meta_needed:%u",
5273 				       meta_left, meta_needed);
5274 		return -EINVAL;
5275 	}
5276 
5277 	if (btf_type_vlen(t)) {
5278 		btf_verifier_log_type(env, t, "vlen != 0");
5279 		return -EINVAL;
5280 	}
5281 
5282 	if (btf_type_kflag(t)) {
5283 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5284 		return -EINVAL;
5285 	}
5286 
5287 	if (!t->name_off ||
5288 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
5289 		btf_verifier_log_type(env, t, "Invalid name");
5290 		return -EINVAL;
5291 	}
5292 
5293 	/* A var cannot be in type void */
5294 	if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
5295 		btf_verifier_log_type(env, t, "Invalid type_id");
5296 		return -EINVAL;
5297 	}
5298 
5299 	var = btf_type_var(t);
5300 	if (var->linkage != BTF_VAR_STATIC &&
5301 	    var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
5302 		btf_verifier_log_type(env, t, "Linkage not supported");
5303 		return -EINVAL;
5304 	}
5305 
5306 	btf_verifier_log_type(env, t, NULL);
5307 
5308 	return meta_needed;
5309 }
5310 
5311 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
5312 {
5313 	const struct btf_var *var = btf_type_var(t);
5314 
5315 	btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
5316 }
5317 
5318 static const struct btf_kind_operations var_ops = {
5319 	.check_meta		= btf_var_check_meta,
5320 	.resolve		= btf_var_resolve,
5321 	.check_member		= btf_df_check_member,
5322 	.check_kflag_member	= btf_df_check_kflag_member,
5323 	.log_details		= btf_var_log,
5324 	.show			= btf_var_show,
5325 };
5326 
5327 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
5328 				  const struct btf_type *t,
5329 				  u32 meta_left)
5330 {
5331 	const struct btf_var_secinfo *vsi;
5332 	u64 last_vsi_end_off = 0, sum = 0;
5333 	u32 i, meta_needed;
5334 
5335 	meta_needed = btf_type_vlen(t) * sizeof(*vsi);
5336 	if (meta_left < meta_needed) {
5337 		btf_verifier_log_basic(env, t,
5338 				       "meta_left:%u meta_needed:%u",
5339 				       meta_left, meta_needed);
5340 		return -EINVAL;
5341 	}
5342 
5343 	if (!t->size) {
5344 		btf_verifier_log_type(env, t, "size == 0");
5345 		return -EINVAL;
5346 	}
5347 
5348 	if (btf_type_kflag(t)) {
5349 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5350 		return -EINVAL;
5351 	}
5352 
5353 	if (!t->name_off ||
5354 	    !btf_name_valid_section(env->btf, t->name_off)) {
5355 		btf_verifier_log_type(env, t, "Invalid name");
5356 		return -EINVAL;
5357 	}
5358 
5359 	btf_verifier_log_type(env, t, NULL);
5360 
5361 	for_each_vsi(i, t, vsi) {
5362 		/* A var cannot be in type void */
5363 		if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
5364 			btf_verifier_log_vsi(env, t, vsi,
5365 					     "Invalid type_id");
5366 			return -EINVAL;
5367 		}
5368 
5369 		if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
5370 			btf_verifier_log_vsi(env, t, vsi,
5371 					     "Invalid offset");
5372 			return -EINVAL;
5373 		}
5374 
5375 		if (!vsi->size || vsi->size > t->size) {
5376 			btf_verifier_log_vsi(env, t, vsi,
5377 					     "Invalid size");
5378 			return -EINVAL;
5379 		}
5380 
5381 		last_vsi_end_off = vsi->offset + vsi->size;
5382 		if (last_vsi_end_off > t->size) {
5383 			btf_verifier_log_vsi(env, t, vsi,
5384 					     "Invalid offset+size");
5385 			return -EINVAL;
5386 		}
5387 
5388 		btf_verifier_log_vsi(env, t, vsi, NULL);
5389 		sum += vsi->size;
5390 	}
5391 
5392 	if (t->size < sum) {
5393 		btf_verifier_log_type(env, t, "Invalid btf_info size");
5394 		return -EINVAL;
5395 	}
5396 
5397 	return meta_needed;
5398 }
5399 
5400 static int btf_datasec_resolve(struct btf_verifier_env *env,
5401 			       const struct resolve_vertex *v)
5402 {
5403 	const struct btf_var_secinfo *vsi;
5404 	struct btf *btf = env->btf;
5405 	u32 i;
5406 
5407 	env->resolve_mode = RESOLVE_TBD;
5408 	for_each_vsi_from(i, v->next_member, v->t, vsi) {
5409 		u32 var_type_id = vsi->type, type_id, type_size = 0;
5410 		const struct btf_type *var_type = btf_type_by_id(env->btf,
5411 								 var_type_id);
5412 		if (!var_type || !btf_type_is_var(var_type)) {
5413 			btf_verifier_log_vsi(env, v->t, vsi,
5414 					     "Not a VAR kind member");
5415 			return -EINVAL;
5416 		}
5417 
5418 		if (!env_type_is_resolve_sink(env, var_type) &&
5419 		    !env_type_is_resolved(env, var_type_id)) {
5420 			env_stack_set_next_member(env, i + 1);
5421 			return env_stack_push(env, var_type, var_type_id);
5422 		}
5423 
5424 		type_id = var_type->type;
5425 		if (!btf_type_id_size(btf, &type_id, &type_size)) {
5426 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
5427 			return -EINVAL;
5428 		}
5429 
5430 		if (vsi->size < type_size) {
5431 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
5432 			return -EINVAL;
5433 		}
5434 	}
5435 
5436 	env_stack_pop_resolved(env, 0, 0);
5437 	return 0;
5438 }
5439 
5440 static void btf_datasec_log(struct btf_verifier_env *env,
5441 			    const struct btf_type *t)
5442 {
5443 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
5444 }
5445 
5446 static void btf_datasec_show(const struct btf *btf,
5447 			     const struct btf_type *t, u32 type_id,
5448 			     void *data, u8 bits_offset,
5449 			     struct btf_show *show)
5450 {
5451 	const struct btf_var_secinfo *vsi;
5452 	const struct btf_type *var;
5453 	u32 i;
5454 
5455 	if (!btf_show_start_type(show, t, type_id, data))
5456 		return;
5457 
5458 	btf_show_type_value(show, "section (\"%s\") = {",
5459 			    __btf_name_by_offset(btf, t->name_off));
5460 	for_each_vsi(i, t, vsi) {
5461 		var = btf_type_by_id(btf, vsi->type);
5462 		if (i)
5463 			btf_show(show, ",");
5464 		btf_type_ops(var)->show(btf, var, vsi->type,
5465 					data + vsi->offset, bits_offset, show);
5466 	}
5467 	btf_show_end_type(show);
5468 }
5469 
5470 static const struct btf_kind_operations datasec_ops = {
5471 	.check_meta		= btf_datasec_check_meta,
5472 	.resolve		= btf_datasec_resolve,
5473 	.check_member		= btf_df_check_member,
5474 	.check_kflag_member	= btf_df_check_kflag_member,
5475 	.log_details		= btf_datasec_log,
5476 	.show			= btf_datasec_show,
5477 };
5478 
5479 static s32 btf_float_check_meta(struct btf_verifier_env *env,
5480 				const struct btf_type *t,
5481 				u32 meta_left)
5482 {
5483 	if (btf_type_vlen(t)) {
5484 		btf_verifier_log_type(env, t, "vlen != 0");
5485 		return -EINVAL;
5486 	}
5487 
5488 	if (btf_type_kflag(t)) {
5489 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
5490 		return -EINVAL;
5491 	}
5492 
5493 	if (t->size != 2 && t->size != 4 && t->size != 8 && t->size != 12 &&
5494 	    t->size != 16) {
5495 		btf_verifier_log_type(env, t, "Invalid type_size");
5496 		return -EINVAL;
5497 	}
5498 
5499 	btf_verifier_log_type(env, t, NULL);
5500 
5501 	return 0;
5502 }
5503 
5504 static int btf_float_check_member(struct btf_verifier_env *env,
5505 				  const struct btf_type *struct_type,
5506 				  const struct btf_member *member,
5507 				  const struct btf_type *member_type)
5508 {
5509 	u64 start_offset_bytes;
5510 	u64 end_offset_bytes;
5511 	u64 misalign_bits;
5512 	u64 align_bytes;
5513 	u64 align_bits;
5514 
5515 	/* Different architectures have different alignment requirements, so
5516 	 * here we check only for the reasonable minimum. This way we ensure
5517 	 * that types after CO-RE can pass the kernel BTF verifier.
5518 	 */
5519 	align_bytes = min_t(u64, sizeof(void *), member_type->size);
5520 	align_bits = align_bytes * BITS_PER_BYTE;
5521 	div64_u64_rem(member->offset, align_bits, &misalign_bits);
5522 	if (misalign_bits) {
5523 		btf_verifier_log_member(env, struct_type, member,
5524 					"Member is not properly aligned");
5525 		return -EINVAL;
5526 	}
5527 
5528 	start_offset_bytes = member->offset / BITS_PER_BYTE;
5529 	end_offset_bytes = start_offset_bytes + member_type->size;
5530 	if (end_offset_bytes > struct_type->size) {
5531 		btf_verifier_log_member(env, struct_type, member,
5532 					"Member exceeds struct_size");
5533 		return -EINVAL;
5534 	}
5535 
5536 	return 0;
5537 }
5538 
5539 static void btf_float_log(struct btf_verifier_env *env,
5540 			  const struct btf_type *t)
5541 {
5542 	btf_verifier_log(env, "size=%u", t->size);
5543 }
5544 
5545 static const struct btf_kind_operations float_ops = {
5546 	.check_meta = btf_float_check_meta,
5547 	.resolve = btf_df_resolve,
5548 	.check_member = btf_float_check_member,
5549 	.check_kflag_member = btf_generic_check_kflag_member,
5550 	.log_details = btf_float_log,
5551 	.show = btf_df_show,
5552 };
5553 
5554 static s32 btf_decl_tag_check_meta(struct btf_verifier_env *env,
5555 			      const struct btf_type *t,
5556 			      u32 meta_left)
5557 {
5558 	const struct btf_decl_tag *tag;
5559 	u32 meta_needed = sizeof(*tag);
5560 	s32 component_idx;
5561 	const char *value;
5562 
5563 	if (meta_left < meta_needed) {
5564 		btf_verifier_log_basic(env, t,
5565 				       "meta_left:%u meta_needed:%u",
5566 				       meta_left, meta_needed);
5567 		return -EINVAL;
5568 	}
5569 
5570 	value = btf_name_by_offset(env->btf, t->name_off);
5571 	if (!value || !value[0]) {
5572 		btf_verifier_log_type(env, t, "Invalid value");
5573 		return -EINVAL;
5574 	}
5575 
5576 	if (btf_type_vlen(t)) {
5577 		btf_verifier_log_type(env, t, "vlen != 0");
5578 		return -EINVAL;
5579 	}
5580 
5581 	component_idx = btf_type_decl_tag(t)->component_idx;
5582 	if (component_idx < -1) {
5583 		btf_verifier_log_type(env, t, "Invalid component_idx");
5584 		return -EINVAL;
5585 	}
5586 
5587 	btf_verifier_log_type(env, t, NULL);
5588 
5589 	return meta_needed;
5590 }
5591 
5592 static int btf_decl_tag_resolve(struct btf_verifier_env *env,
5593 			   const struct resolve_vertex *v)
5594 {
5595 	const struct btf_type *next_type;
5596 	const struct btf_type *t = v->t;
5597 	u32 next_type_id = t->type;
5598 	struct btf *btf = env->btf;
5599 	s32 component_idx;
5600 	u32 vlen;
5601 
5602 	next_type = btf_type_by_id(btf, next_type_id);
5603 	if (!next_type || !btf_type_is_decl_tag_target(next_type)) {
5604 		btf_verifier_log_type(env, v->t, "Invalid type_id");
5605 		return -EINVAL;
5606 	}
5607 
5608 	if (!env_type_is_resolve_sink(env, next_type) &&
5609 	    !env_type_is_resolved(env, next_type_id))
5610 		return env_stack_push(env, next_type, next_type_id);
5611 
5612 	component_idx = btf_type_decl_tag(t)->component_idx;
5613 	if (component_idx != -1) {
5614 		if (btf_type_is_var(next_type) || btf_type_is_typedef(next_type)) {
5615 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
5616 			return -EINVAL;
5617 		}
5618 
5619 		if (btf_type_is_struct(next_type)) {
5620 			vlen = btf_type_vlen(next_type);
5621 		} else {
5622 			/* next_type should be a function */
5623 			next_type = btf_type_by_id(btf, next_type->type);
5624 			vlen = btf_type_vlen(next_type);
5625 		}
5626 
5627 		if ((u32)component_idx >= vlen) {
5628 			btf_verifier_log_type(env, v->t, "Invalid component_idx");
5629 			return -EINVAL;
5630 		}
5631 	}
5632 
5633 	env_stack_pop_resolved(env, next_type_id, 0);
5634 
5635 	return 0;
5636 }
5637 
5638 static void btf_decl_tag_log(struct btf_verifier_env *env, const struct btf_type *t)
5639 {
5640 	btf_verifier_log(env, "type=%u component_idx=%d", t->type,
5641 			 btf_type_decl_tag(t)->component_idx);
5642 }
5643 
5644 static const struct btf_kind_operations decl_tag_ops = {
5645 	.check_meta = btf_decl_tag_check_meta,
5646 	.resolve = btf_decl_tag_resolve,
5647 	.check_member = btf_df_check_member,
5648 	.check_kflag_member = btf_df_check_kflag_member,
5649 	.log_details = btf_decl_tag_log,
5650 	.show = btf_df_show,
5651 };
5652 
5653 static int btf_func_proto_check(struct btf_verifier_env *env,
5654 				const struct btf_type *t)
5655 {
5656 	const struct btf_type *ret_type;
5657 	const struct btf_param *args;
5658 	const struct btf *btf;
5659 	u32 nr_args, i;
5660 	int err;
5661 
5662 	btf = env->btf;
5663 	args = (const struct btf_param *)(t + 1);
5664 	nr_args = btf_type_vlen(t);
5665 
5666 	/* Check func return type which could be "void" (t->type == 0) */
5667 	if (t->type) {
5668 		u32 ret_type_id = t->type;
5669 
5670 		ret_type = btf_type_by_id(btf, ret_type_id);
5671 		if (!ret_type) {
5672 			btf_verifier_log_type(env, t, "Invalid return type");
5673 			return -EINVAL;
5674 		}
5675 
5676 		if (btf_type_is_resolve_source_only(ret_type)) {
5677 			btf_verifier_log_type(env, t, "Invalid return type");
5678 			return -EINVAL;
5679 		}
5680 
5681 		if (btf_type_needs_resolve(ret_type) &&
5682 		    !env_type_is_resolved(env, ret_type_id)) {
5683 			err = btf_resolve(env, ret_type, ret_type_id);
5684 			if (err)
5685 				return err;
5686 		}
5687 
5688 		/* Ensure the return type is a type that has a size */
5689 		if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
5690 			btf_verifier_log_type(env, t, "Invalid return type");
5691 			return -EINVAL;
5692 		}
5693 	}
5694 
5695 	if (!nr_args)
5696 		return 0;
5697 
5698 	/* Last func arg type_id could be 0 if it is a vararg */
5699 	if (!args[nr_args - 1].type) {
5700 		if (args[nr_args - 1].name_off) {
5701 			btf_verifier_log_type(env, t, "Invalid arg#%u",
5702 					      nr_args);
5703 			return -EINVAL;
5704 		}
5705 		nr_args--;
5706 	}
5707 
5708 	for (i = 0; i < nr_args; i++) {
5709 		const struct btf_type *arg_type;
5710 		u32 arg_type_id;
5711 
5712 		arg_type_id = args[i].type;
5713 		arg_type = btf_type_by_id(btf, arg_type_id);
5714 		if (!arg_type) {
5715 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5716 			return -EINVAL;
5717 		}
5718 
5719 		if (btf_type_is_resolve_source_only(arg_type)) {
5720 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5721 			return -EINVAL;
5722 		}
5723 
5724 		if (args[i].name_off &&
5725 		    (!btf_name_offset_valid(btf, args[i].name_off) ||
5726 		     !btf_name_valid_identifier(btf, args[i].name_off))) {
5727 			btf_verifier_log_type(env, t,
5728 					      "Invalid arg#%u", i + 1);
5729 			return -EINVAL;
5730 		}
5731 
5732 		if (btf_type_needs_resolve(arg_type) &&
5733 		    !env_type_is_resolved(env, arg_type_id)) {
5734 			err = btf_resolve(env, arg_type, arg_type_id);
5735 			if (err)
5736 				return err;
5737 		}
5738 
5739 		if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
5740 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5741 			return -EINVAL;
5742 		}
5743 	}
5744 
5745 	return 0;
5746 }
5747 
5748 static int btf_func_check(struct btf_verifier_env *env,
5749 			  const struct btf_type *t)
5750 {
5751 	const struct btf_type *proto_type;
5752 	const struct btf_param *args;
5753 	const struct btf *btf;
5754 	u32 nr_args, i;
5755 
5756 	btf = env->btf;
5757 	proto_type = btf_type_by_id(btf, t->type);
5758 
5759 	if (!proto_type || !btf_type_is_func_proto(proto_type)) {
5760 		btf_verifier_log_type(env, t, "Invalid type_id");
5761 		return -EINVAL;
5762 	}
5763 
5764 	args = (const struct btf_param *)(proto_type + 1);
5765 	nr_args = btf_type_vlen(proto_type);
5766 	for (i = 0; i < nr_args; i++) {
5767 		if (!args[i].name_off && args[i].type) {
5768 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
5769 			return -EINVAL;
5770 		}
5771 	}
5772 
5773 	return 0;
5774 }
5775 
5776 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
5777 	[BTF_KIND_INT] = &int_ops,
5778 	[BTF_KIND_PTR] = &ptr_ops,
5779 	[BTF_KIND_ARRAY] = &array_ops,
5780 	[BTF_KIND_STRUCT] = &struct_ops,
5781 	[BTF_KIND_UNION] = &struct_ops,
5782 	[BTF_KIND_ENUM] = &enum_ops,
5783 	[BTF_KIND_FWD] = &fwd_ops,
5784 	[BTF_KIND_TYPEDEF] = &modifier_ops,
5785 	[BTF_KIND_VOLATILE] = &modifier_ops,
5786 	[BTF_KIND_CONST] = &modifier_ops,
5787 	[BTF_KIND_RESTRICT] = &modifier_ops,
5788 	[BTF_KIND_FUNC] = &func_ops,
5789 	[BTF_KIND_FUNC_PROTO] = &func_proto_ops,
5790 	[BTF_KIND_VAR] = &var_ops,
5791 	[BTF_KIND_DATASEC] = &datasec_ops,
5792 	[BTF_KIND_FLOAT] = &float_ops,
5793 	[BTF_KIND_DECL_TAG] = &decl_tag_ops,
5794 	[BTF_KIND_TYPE_TAG] = &modifier_ops,
5795 	[BTF_KIND_ENUM64] = &enum64_ops,
5796 	[BTF_KIND_LOC_PARAM] = &loc_param_ops,
5797 	[BTF_KIND_LOC_PROTO] = &loc_proto_ops,
5798 	[BTF_KIND_LOCSEC] = &locsec_ops,
5799 };
5800 
5801 static s32 btf_check_meta(struct btf_verifier_env *env,
5802 			  const struct btf_type *t,
5803 			  u32 meta_left)
5804 {
5805 	u32 saved_meta_left = meta_left;
5806 	s32 var_meta_size;
5807 
5808 	if (meta_left < sizeof(*t)) {
5809 		btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
5810 				 env->log_type_id, meta_left, sizeof(*t));
5811 		return -EINVAL;
5812 	}
5813 	meta_left -= sizeof(*t);
5814 
5815 	if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
5816 	    BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
5817 		btf_verifier_log(env, "[%u] Invalid kind:%u",
5818 				 env->log_type_id, BTF_INFO_KIND(t->info));
5819 		return -EINVAL;
5820 	}
5821 
5822 	if (!btf_name_offset_valid(env->btf, t->name_off)) {
5823 		btf_verifier_log(env, "[%u] Invalid name_offset:%u",
5824 				 env->log_type_id, t->name_off);
5825 		return -EINVAL;
5826 	}
5827 
5828 	var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
5829 	if (var_meta_size < 0)
5830 		return var_meta_size;
5831 
5832 	meta_left -= var_meta_size;
5833 
5834 	return saved_meta_left - meta_left;
5835 }
5836 
5837 static int btf_check_all_metas(struct btf_verifier_env *env)
5838 {
5839 	struct btf *btf = env->btf;
5840 	struct btf_header *hdr;
5841 	void *cur, *end;
5842 
5843 	hdr = &btf->hdr;
5844 	cur = btf->nohdr_data + hdr->type_off;
5845 	end = cur + hdr->type_len;
5846 
5847 	env->log_type_id = btf->base_btf ? btf->start_id : 1;
5848 	while (cur < end) {
5849 		struct btf_type *t = cur;
5850 		s32 meta_size;
5851 
5852 		meta_size = btf_check_meta(env, t, end - cur);
5853 		if (meta_size < 0)
5854 			return meta_size;
5855 
5856 		btf_add_type(env, t);
5857 		cur += meta_size;
5858 		env->log_type_id++;
5859 	}
5860 
5861 	return 0;
5862 }
5863 
5864 static bool btf_resolve_valid(struct btf_verifier_env *env,
5865 			      const struct btf_type *t,
5866 			      u32 type_id)
5867 {
5868 	struct btf *btf = env->btf;
5869 
5870 	if (!env_type_is_resolved(env, type_id))
5871 		return false;
5872 
5873 	if (btf_type_is_struct(t) || btf_type_is_datasec(t) ||
5874 	    btf_type_is_loc_proto(t) || btf_type_is_locsec(t))
5875 		return !btf_resolved_type_id(btf, type_id) &&
5876 		       !btf_resolved_type_size(btf, type_id);
5877 
5878 	if (btf_type_is_decl_tag(t) || btf_type_is_func(t))
5879 		return btf_resolved_type_id(btf, type_id) &&
5880 		       !btf_resolved_type_size(btf, type_id);
5881 
5882 	if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
5883 	    btf_type_is_var(t)) {
5884 		t = btf_type_id_resolve(btf, &type_id);
5885 		return t &&
5886 		       !btf_type_is_modifier(t) &&
5887 		       !btf_type_is_var(t) &&
5888 		       !btf_type_is_datasec(t);
5889 	}
5890 
5891 	if (btf_type_is_array(t)) {
5892 		const struct btf_array *array = btf_type_array(t);
5893 		const struct btf_type *elem_type;
5894 		u32 elem_type_id = array->type;
5895 		u32 elem_size;
5896 
5897 		elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
5898 		return elem_type && !btf_type_is_modifier(elem_type) &&
5899 			(array->nelems * elem_size ==
5900 			 btf_resolved_type_size(btf, type_id));
5901 	}
5902 
5903 	return false;
5904 }
5905 
5906 static int btf_resolve(struct btf_verifier_env *env,
5907 		       const struct btf_type *t, u32 type_id)
5908 {
5909 	u32 save_log_type_id = env->log_type_id;
5910 	const struct resolve_vertex *v;
5911 	int err = 0;
5912 
5913 	env->resolve_mode = RESOLVE_TBD;
5914 	env_stack_push(env, t, type_id);
5915 	while (!err && (v = env_stack_peak(env))) {
5916 		env->log_type_id = v->type_id;
5917 		err = btf_type_ops(v->t)->resolve(env, v);
5918 	}
5919 
5920 	env->log_type_id = type_id;
5921 	if (err == -E2BIG) {
5922 		btf_verifier_log_type(env, t,
5923 				      "Exceeded max resolving depth:%u",
5924 				      MAX_RESOLVE_DEPTH);
5925 	} else if (err == -EEXIST) {
5926 		btf_verifier_log_type(env, t, "Loop detected");
5927 	}
5928 
5929 	/* Final sanity check */
5930 	if (!err && !btf_resolve_valid(env, t, type_id)) {
5931 		btf_verifier_log_type(env, t, "Invalid resolve state");
5932 		err = -EINVAL;
5933 	}
5934 
5935 	env->log_type_id = save_log_type_id;
5936 	return err;
5937 }
5938 
5939 static int btf_check_all_types(struct btf_verifier_env *env)
5940 {
5941 	struct btf *btf = env->btf;
5942 	const struct btf_type *t;
5943 	u32 type_id, i;
5944 	int err;
5945 
5946 	err = env_resolve_init(env);
5947 	if (err)
5948 		return err;
5949 
5950 	env->phase++;
5951 	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
5952 		type_id = btf->start_id + i;
5953 		t = btf_type_by_id(btf, type_id);
5954 
5955 		env->log_type_id = type_id;
5956 		if (btf_type_needs_resolve(t) &&
5957 		    !env_type_is_resolved(env, type_id)) {
5958 			err = btf_resolve(env, t, type_id);
5959 			if (err)
5960 				return err;
5961 		}
5962 
5963 		if (btf_type_is_func_proto(t)) {
5964 			err = btf_func_proto_check(env, t);
5965 			if (err)
5966 				return err;
5967 		}
5968 	}
5969 
5970 	return 0;
5971 }
5972 
5973 static int btf_parse_type_sec(struct btf_verifier_env *env)
5974 {
5975 	const struct btf_header *hdr = &env->btf->hdr;
5976 	int err;
5977 
5978 	/* Type section must align to 4 bytes */
5979 	if (hdr->type_off & (sizeof(u32) - 1)) {
5980 		btf_verifier_log(env, "Unaligned type_off");
5981 		return -EINVAL;
5982 	}
5983 
5984 	if (!env->btf->base_btf && !hdr->type_len) {
5985 		btf_verifier_log(env, "No type found");
5986 		return -EINVAL;
5987 	}
5988 
5989 	err = btf_check_all_metas(env);
5990 	if (err)
5991 		return err;
5992 
5993 	return btf_check_all_types(env);
5994 }
5995 
5996 static int btf_parse_str_sec(struct btf_verifier_env *env)
5997 {
5998 	const struct btf_header *hdr;
5999 	struct btf *btf = env->btf;
6000 	const char *start, *end;
6001 
6002 	hdr = &btf->hdr;
6003 	start = btf->nohdr_data + hdr->str_off;
6004 	end = start + hdr->str_len;
6005 
6006 	if (hdr->hdr_len < sizeof(struct btf_header) &&
6007 	    end != btf->data + btf->data_size) {
6008 		btf_verifier_log(env, "String section is not at the end");
6009 		return -EINVAL;
6010 	}
6011 
6012 	btf->strings = start;
6013 
6014 	if (btf->base_btf && !hdr->str_len)
6015 		return 0;
6016 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
6017 		btf_verifier_log(env, "Invalid string section");
6018 		return -EINVAL;
6019 	}
6020 	if (!btf->base_btf && start[0]) {
6021 		btf_verifier_log(env, "Invalid string section");
6022 		return -EINVAL;
6023 	}
6024 
6025 	return 0;
6026 }
6027 
6028 static int btf_parse_layout_sec(struct btf_verifier_env *env)
6029 {
6030 	const struct btf_header *hdr = &env->btf->hdr;
6031 	struct btf *btf = env->btf;
6032 	void *start, *end;
6033 
6034 	if (hdr->hdr_len < sizeof(struct btf_header) ||
6035 	    hdr->layout_len == 0)
6036 		return 0;
6037 
6038 	/* Layout section must align to 4 bytes */
6039 	if (hdr->layout_off & (sizeof(u32) - 1)) {
6040 		btf_verifier_log(env, "Unaligned layout_off");
6041 		return -EINVAL;
6042 	}
6043 	start = btf->nohdr_data + hdr->layout_off;
6044 	end = start + hdr->layout_len;
6045 
6046 	if (hdr->layout_len < sizeof(struct btf_layout)) {
6047 		btf_verifier_log(env, "Layout section is too small");
6048 		return -EINVAL;
6049 	}
6050 	if (hdr->layout_len % sizeof(struct btf_layout) != 0) {
6051 		btf_verifier_log(env, "layout_len is not multiple of %zu",
6052 				 sizeof(struct btf_layout));
6053 		return -EINVAL;
6054 	}
6055 	if (end > btf->data + btf->data_size) {
6056 		btf_verifier_log(env, "Layout section is too big");
6057 		return -EINVAL;
6058 	}
6059 	btf->layout = start;
6060 
6061 	return 0;
6062 }
6063 
6064 static const size_t btf_sec_info_offset[] = {
6065 	offsetof(struct btf_header, type_off),
6066 	offsetof(struct btf_header, str_off),
6067 	offsetof(struct btf_header, layout_off)
6068 };
6069 
6070 static int btf_sec_info_cmp(const void *a, const void *b)
6071 {
6072 	const struct btf_sec_info *x = a;
6073 	const struct btf_sec_info *y = b;
6074 
6075 	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
6076 }
6077 
6078 static int btf_check_sec_info(struct btf_verifier_env *env,
6079 			      u32 btf_data_size)
6080 {
6081 	struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
6082 	u32 total, expected_total, i;
6083 	u32 nr_secs = ARRAY_SIZE(btf_sec_info_offset);
6084 	const struct btf_header *hdr;
6085 	const struct btf *btf;
6086 
6087 	btf = env->btf;
6088 	hdr = &btf->hdr;
6089 
6090 	if (hdr->hdr_len < sizeof(struct btf_header) || hdr->layout_len == 0)
6091 		nr_secs--;
6092 
6093 	/* Populate the secs from hdr */
6094 	for (i = 0; i < nr_secs; i++)
6095 		secs[i] = *(struct btf_sec_info *)((void *)hdr +
6096 						   btf_sec_info_offset[i]);
6097 
6098 	sort(secs, nr_secs,
6099 	     sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
6100 
6101 	/* Check for gaps and overlap among sections */
6102 	total = 0;
6103 	expected_total = btf_data_size - hdr->hdr_len;
6104 	for (i = 0; i < nr_secs; i++) {
6105 		if (expected_total < secs[i].off) {
6106 			btf_verifier_log(env, "Invalid section offset");
6107 			return -EINVAL;
6108 		}
6109 		if (total < secs[i].off) {
6110 			/* gap */
6111 			btf_verifier_log(env, "Unsupported section found");
6112 			return -EINVAL;
6113 		}
6114 		if (total > secs[i].off) {
6115 			btf_verifier_log(env, "Section overlap found");
6116 			return -EINVAL;
6117 		}
6118 		if (expected_total - total < secs[i].len) {
6119 			btf_verifier_log(env,
6120 					 "Total section length too long");
6121 			return -EINVAL;
6122 		}
6123 		total += secs[i].len;
6124 	}
6125 
6126 	/* There is data other than hdr and known sections */
6127 	if (expected_total != total) {
6128 		btf_verifier_log(env, "Unsupported section found");
6129 		return -EINVAL;
6130 	}
6131 
6132 	return 0;
6133 }
6134 
6135 static int btf_parse_hdr(struct btf_verifier_env *env)
6136 {
6137 	u32 hdr_len, hdr_copy, btf_data_size;
6138 	const struct btf_header *hdr;
6139 	struct btf *btf;
6140 
6141 	btf = env->btf;
6142 	btf_data_size = btf->data_size;
6143 
6144 	if (btf_data_size < offsetofend(struct btf_header, hdr_len)) {
6145 		btf_verifier_log(env, "hdr_len not found");
6146 		return -EINVAL;
6147 	}
6148 
6149 	hdr = btf->data;
6150 	hdr_len = hdr->hdr_len;
6151 	if (btf_data_size < hdr_len) {
6152 		btf_verifier_log(env, "btf_header not found");
6153 		return -EINVAL;
6154 	}
6155 
6156 	/* Ensure the unsupported header fields are zero */
6157 	if (hdr_len > sizeof(btf->hdr)) {
6158 		u8 *expected_zero = btf->data + sizeof(btf->hdr);
6159 		u8 *end = btf->data + hdr_len;
6160 
6161 		for (; expected_zero < end; expected_zero++) {
6162 			if (*expected_zero) {
6163 				btf_verifier_log(env, "Unsupported btf_header");
6164 				return -E2BIG;
6165 			}
6166 		}
6167 	}
6168 
6169 	hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
6170 	memcpy(&btf->hdr, btf->data, hdr_copy);
6171 
6172 	hdr = &btf->hdr;
6173 
6174 	btf_verifier_log_hdr(env, btf_data_size);
6175 
6176 	if (hdr->magic != BTF_MAGIC) {
6177 		btf_verifier_log(env, "Invalid magic");
6178 		return -EINVAL;
6179 	}
6180 
6181 	if (hdr->version != BTF_VERSION) {
6182 		btf_verifier_log(env, "Unsupported version");
6183 		return -ENOTSUPP;
6184 	}
6185 
6186 	if (hdr->flags) {
6187 		btf_verifier_log(env, "Unsupported flags");
6188 		return -ENOTSUPP;
6189 	}
6190 
6191 	if (!btf->base_btf && btf_data_size == hdr->hdr_len) {
6192 		btf_verifier_log(env, "No data");
6193 		return -EINVAL;
6194 	}
6195 
6196 	return btf_check_sec_info(env, btf_data_size);
6197 }
6198 
6199 static const char * const alloc_obj_fields[] = {
6200 	"bpf_spin_lock",
6201 	"bpf_list_head",
6202 	"bpf_list_node",
6203 	"bpf_rb_root",
6204 	"bpf_rb_node",
6205 	"bpf_refcount",
6206 };
6207 
6208 static struct btf_struct_metas *
6209 btf_parse_struct_metas(struct bpf_verifier_log *log, struct btf *btf)
6210 {
6211 	struct btf_struct_metas *tab = NULL;
6212 	struct btf_id_set *aof;
6213 	int i, n, id, ret;
6214 
6215 	BUILD_BUG_ON(offsetof(struct btf_id_set, cnt) != 0);
6216 	BUILD_BUG_ON(sizeof(struct btf_id_set) != sizeof(u32));
6217 
6218 	aof = kmalloc_obj(*aof, GFP_KERNEL | __GFP_NOWARN);
6219 	if (!aof)
6220 		return ERR_PTR(-ENOMEM);
6221 	aof->cnt = 0;
6222 
6223 	for (i = 0; i < ARRAY_SIZE(alloc_obj_fields); i++) {
6224 		/* Try to find whether this special type exists in user BTF, and
6225 		 * if so remember its ID so we can easily find it among members
6226 		 * of structs that we iterate in the next loop.
6227 		 */
6228 		struct btf_id_set *new_aof;
6229 
6230 		id = btf_find_by_name_kind(btf, alloc_obj_fields[i], BTF_KIND_STRUCT);
6231 		if (id < 0)
6232 			continue;
6233 
6234 		new_aof = krealloc(aof, struct_size(new_aof, ids, aof->cnt + 1),
6235 				   GFP_KERNEL | __GFP_NOWARN);
6236 		if (!new_aof) {
6237 			ret = -ENOMEM;
6238 			goto free_aof;
6239 		}
6240 		aof = new_aof;
6241 		aof->ids[aof->cnt++] = id;
6242 	}
6243 
6244 	n = btf_nr_types(btf);
6245 	for (i = 1; i < n; i++) {
6246 		/* Try to find if there are kptrs in user BTF and remember their ID */
6247 		struct btf_id_set *new_aof;
6248 		struct btf_field_info tmp;
6249 		const struct btf_type *t;
6250 
6251 		t = btf_type_by_id(btf, i);
6252 		if (!t) {
6253 			ret = -EINVAL;
6254 			goto free_aof;
6255 		}
6256 
6257 		ret = btf_find_kptr(btf, t, 0, 0, &tmp, BPF_KPTR);
6258 		if (ret != BTF_FIELD_FOUND)
6259 			continue;
6260 
6261 		new_aof = krealloc(aof, struct_size(new_aof, ids, aof->cnt + 1),
6262 				   GFP_KERNEL | __GFP_NOWARN);
6263 		if (!new_aof) {
6264 			ret = -ENOMEM;
6265 			goto free_aof;
6266 		}
6267 		aof = new_aof;
6268 		aof->ids[aof->cnt++] = i;
6269 	}
6270 
6271 	if (!aof->cnt) {
6272 		kfree(aof);
6273 		return NULL;
6274 	}
6275 	sort(&aof->ids, aof->cnt, sizeof(aof->ids[0]), btf_id_cmp_func, NULL);
6276 
6277 	for (i = 1; i < n; i++) {
6278 		struct btf_struct_metas *new_tab;
6279 		const struct btf_member *member;
6280 		struct btf_struct_meta *type;
6281 		struct btf_record *record;
6282 		const struct btf_type *t;
6283 		int j, tab_cnt;
6284 
6285 		t = btf_type_by_id(btf, i);
6286 		if (!__btf_type_is_struct(t))
6287 			continue;
6288 
6289 		cond_resched();
6290 
6291 		for_each_member(j, t, member) {
6292 			if (btf_id_set_contains(aof, member->type))
6293 				goto parse;
6294 		}
6295 		continue;
6296 	parse:
6297 		tab_cnt = tab ? tab->cnt : 0;
6298 		new_tab = krealloc(tab, struct_size(new_tab, types, tab_cnt + 1),
6299 				   GFP_KERNEL | __GFP_NOWARN);
6300 		if (!new_tab) {
6301 			ret = -ENOMEM;
6302 			goto free;
6303 		}
6304 		if (!tab)
6305 			new_tab->cnt = 0;
6306 		tab = new_tab;
6307 
6308 		type = &tab->types[tab->cnt];
6309 		type->btf_id = i;
6310 		record = btf_parse_fields(btf, t, BPF_SPIN_LOCK | BPF_RES_SPIN_LOCK | BPF_LIST_HEAD | BPF_LIST_NODE |
6311 						  BPF_RB_ROOT | BPF_RB_NODE | BPF_REFCOUNT |
6312 						  BPF_KPTR, t->size);
6313 		/* The record cannot be unset, treat it as an error if so */
6314 		if (IS_ERR_OR_NULL(record)) {
6315 			ret = PTR_ERR_OR_ZERO(record) ?: -EFAULT;
6316 			goto free;
6317 		}
6318 		type->record = record;
6319 		tab->cnt++;
6320 	}
6321 	kfree(aof);
6322 	return tab;
6323 free:
6324 	btf_struct_metas_free(tab);
6325 free_aof:
6326 	kfree(aof);
6327 	return ERR_PTR(ret);
6328 }
6329 
6330 struct btf_struct_meta *btf_find_struct_meta(const struct btf *btf, u32 btf_id)
6331 {
6332 	struct btf_struct_metas *tab;
6333 
6334 	BUILD_BUG_ON(offsetof(struct btf_struct_meta, btf_id) != 0);
6335 	tab = btf->struct_meta_tab;
6336 	if (!tab)
6337 		return NULL;
6338 	return bsearch(&btf_id, tab->types, tab->cnt, sizeof(tab->types[0]), btf_id_cmp_func);
6339 }
6340 
6341 static int btf_check_modifier_chain_length(struct btf_verifier_env *env,
6342 					   struct btf *btf, int start_id)
6343 {
6344 	int i, n, good_id = start_id - 1;
6345 
6346 	n = btf_nr_types(btf);
6347 	for (i = start_id; i < n; i++) {
6348 		const struct btf_type *t;
6349 		int chain_limit = 32;
6350 		u32 cur_id = i;
6351 
6352 		t = btf_type_by_id(btf, i);
6353 		if (!t)
6354 			return -EINVAL;
6355 		if (!btf_type_is_modifier(t))
6356 			continue;
6357 
6358 		cond_resched();
6359 
6360 		while (btf_type_is_modifier(t)) {
6361 			if (!chain_limit--) {
6362 				btf_verifier_log(env, "Max chain length or cycle detected");
6363 				return -ELOOP;
6364 			}
6365 
6366 			if (cur_id <= good_id)
6367 				break;
6368 			/* Move to next type */
6369 			cur_id = t->type;
6370 			t = btf_type_by_id(btf, cur_id);
6371 			if (!t)
6372 				return -EINVAL;
6373 		}
6374 		good_id = i;
6375 	}
6376 	return 0;
6377 }
6378 
6379 static struct btf *btf_parse(const union bpf_attr *attr, bpfptr_t uattr,
6380 			     struct bpf_log_attr *attr_log)
6381 {
6382 	bpfptr_t btf_data = make_bpfptr(attr->btf, uattr.is_kernel);
6383 	struct btf_struct_metas *struct_meta_tab;
6384 	struct btf_verifier_env *env = NULL;
6385 	struct btf *btf = NULL;
6386 	u8 *data;
6387 	int err, ret;
6388 
6389 	if (attr->btf_size > BTF_MAX_SIZE)
6390 		return ERR_PTR(-E2BIG);
6391 
6392 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
6393 	if (!env)
6394 		return ERR_PTR(-ENOMEM);
6395 
6396 	/* user could have requested verbose verifier output
6397 	 * and supplied buffer to store the verification trace
6398 	 */
6399 	err = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
6400 	if (err)
6401 		goto errout_free;
6402 
6403 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
6404 	if (!btf) {
6405 		err = -ENOMEM;
6406 		goto errout;
6407 	}
6408 	env->btf = btf;
6409 	btf->named_start_id = 0;
6410 
6411 	data = kvmalloc(attr->btf_size, GFP_KERNEL | __GFP_NOWARN);
6412 	if (!data) {
6413 		err = -ENOMEM;
6414 		goto errout;
6415 	}
6416 
6417 	btf->data = data;
6418 	btf->data_size = attr->btf_size;
6419 
6420 	if (copy_from_bpfptr(data, btf_data, attr->btf_size)) {
6421 		err = -EFAULT;
6422 		goto errout;
6423 	}
6424 
6425 	err = btf_parse_hdr(env);
6426 	if (err)
6427 		goto errout;
6428 
6429 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6430 
6431 	err = btf_parse_str_sec(env);
6432 	if (err)
6433 		goto errout;
6434 
6435 	err = btf_parse_layout_sec(env);
6436 	if (err)
6437 		goto errout;
6438 
6439 	err = btf_parse_type_sec(env);
6440 	if (err)
6441 		goto errout;
6442 
6443 	err = btf_check_modifier_chain_length(env, btf, 1);
6444 	if (err)
6445 		goto errout;
6446 
6447 	struct_meta_tab = btf_parse_struct_metas(&env->log, btf);
6448 	if (IS_ERR(struct_meta_tab)) {
6449 		err = PTR_ERR(struct_meta_tab);
6450 		goto errout;
6451 	}
6452 	btf->struct_meta_tab = struct_meta_tab;
6453 
6454 	if (struct_meta_tab) {
6455 		int i;
6456 
6457 		for (i = 0; i < struct_meta_tab->cnt; i++) {
6458 			err = btf_check_and_fixup_fields(btf, struct_meta_tab->types[i].record);
6459 			if (err < 0)
6460 				goto errout_meta;
6461 		}
6462 
6463 		err = btf_check_ownership_depth(btf, struct_meta_tab);
6464 		if (err < 0)
6465 			goto errout_meta;
6466 	}
6467 
6468 	err = bpf_log_attr_finalize(attr_log, &env->log);
6469 	if (err)
6470 		goto errout_free;
6471 
6472 	btf_verifier_env_free(env);
6473 	refcount_set(&btf->refcnt, 1);
6474 	return btf;
6475 
6476 errout_meta:
6477 	btf_free_struct_meta_tab(btf);
6478 errout:
6479 	/* overwrite err with -ENOSPC or -EFAULT */
6480 	ret = bpf_log_attr_finalize(attr_log, &env->log);
6481 	if (ret)
6482 		err = ret;
6483 errout_free:
6484 	btf_verifier_env_free(env);
6485 	if (btf)
6486 		btf_free(btf);
6487 	return ERR_PTR(err);
6488 }
6489 
6490 extern char __start_BTF[];
6491 extern char __stop_BTF[];
6492 extern struct btf *btf_vmlinux;
6493 
6494 #define BPF_MAP_TYPE(_id, _ops)
6495 #define BPF_LINK_TYPE(_id, _name)
6496 static union {
6497 	struct bpf_ctx_convert {
6498 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
6499 	prog_ctx_type _id##_prog; \
6500 	kern_ctx_type _id##_kern;
6501 #include <linux/bpf_types.h>
6502 #undef BPF_PROG_TYPE
6503 	} *__t;
6504 	/* 't' is written once under lock. Read many times. */
6505 	const struct btf_type *t;
6506 } bpf_ctx_convert;
6507 enum {
6508 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
6509 	__ctx_convert##_id,
6510 #include <linux/bpf_types.h>
6511 #undef BPF_PROG_TYPE
6512 	__ctx_convert_unused, /* to avoid empty enum in extreme .config */
6513 };
6514 static u8 bpf_ctx_convert_map[] = {
6515 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
6516 	[_id] = __ctx_convert##_id,
6517 #include <linux/bpf_types.h>
6518 #undef BPF_PROG_TYPE
6519 	0, /* avoid empty array */
6520 };
6521 #undef BPF_MAP_TYPE
6522 #undef BPF_LINK_TYPE
6523 
6524 static const struct btf_type *find_canonical_prog_ctx_type(enum bpf_prog_type prog_type)
6525 {
6526 	const struct btf_type *conv_struct;
6527 	const struct btf_member *ctx_type;
6528 
6529 	conv_struct = bpf_ctx_convert.t;
6530 	if (!conv_struct)
6531 		return NULL;
6532 	/* prog_type is valid bpf program type. No need for bounds check. */
6533 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
6534 	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
6535 	 * Like 'struct __sk_buff'
6536 	 */
6537 	return btf_type_by_id(btf_vmlinux, ctx_type->type);
6538 }
6539 
6540 static int find_kern_ctx_type_id(enum bpf_prog_type prog_type)
6541 {
6542 	const struct btf_type *conv_struct;
6543 	const struct btf_member *ctx_type;
6544 
6545 	conv_struct = bpf_ctx_convert.t;
6546 	if (!conv_struct)
6547 		return -EFAULT;
6548 	/* prog_type is valid bpf program type. No need for bounds check. */
6549 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6550 	/* ctx_type is a pointer to prog_ctx_type in vmlinux.
6551 	 * Like 'struct sk_buff'
6552 	 */
6553 	return ctx_type->type;
6554 }
6555 
6556 bool btf_is_projection_of(const char *pname, const char *tname)
6557 {
6558 	if (strcmp(pname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
6559 		return true;
6560 	if (strcmp(pname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
6561 		return true;
6562 	return false;
6563 }
6564 
6565 bool btf_is_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
6566 			  const struct btf_type *t, enum bpf_prog_type prog_type,
6567 			  int arg)
6568 {
6569 	const struct btf_type *ctx_type;
6570 	const char *tname, *ctx_tname;
6571 
6572 	t = btf_type_by_id(btf, t->type);
6573 
6574 	/* KPROBE programs allow bpf_user_pt_regs_t typedef, which we need to
6575 	 * check before we skip all the typedef below.
6576 	 */
6577 	if (prog_type == BPF_PROG_TYPE_KPROBE) {
6578 		while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
6579 			t = btf_type_by_id(btf, t->type);
6580 
6581 		if (btf_type_is_typedef(t)) {
6582 			tname = btf_name_by_offset(btf, t->name_off);
6583 			if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
6584 				return true;
6585 		}
6586 	}
6587 
6588 	while (btf_type_is_modifier(t))
6589 		t = btf_type_by_id(btf, t->type);
6590 	if (!btf_type_is_struct(t)) {
6591 		/* Only pointer to struct is supported for now.
6592 		 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
6593 		 * is not supported yet.
6594 		 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
6595 		 */
6596 		return false;
6597 	}
6598 	tname = btf_name_by_offset(btf, t->name_off);
6599 	if (!tname) {
6600 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
6601 		return false;
6602 	}
6603 
6604 	ctx_type = find_canonical_prog_ctx_type(prog_type);
6605 	if (!ctx_type) {
6606 		bpf_log(log, "btf_vmlinux is malformed\n");
6607 		/* should not happen */
6608 		return false;
6609 	}
6610 again:
6611 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6612 	if (!ctx_tname) {
6613 		/* should not happen */
6614 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
6615 		return false;
6616 	}
6617 	/* program types without named context types work only with arg:ctx tag */
6618 	if (ctx_tname[0] == '\0')
6619 		return false;
6620 	/* only compare that prog's ctx type name is the same as
6621 	 * kernel expects. No need to compare field by field.
6622 	 * It's ok for bpf prog to do:
6623 	 * struct __sk_buff {};
6624 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
6625 	 * { // no fields of skb are ever used }
6626 	 */
6627 	if (btf_is_projection_of(ctx_tname, tname))
6628 		return true;
6629 	if (strcmp(ctx_tname, tname)) {
6630 		/* bpf_user_pt_regs_t is a typedef, so resolve it to
6631 		 * underlying struct and check name again
6632 		 */
6633 		if (!btf_type_is_modifier(ctx_type))
6634 			return false;
6635 		while (btf_type_is_modifier(ctx_type))
6636 			ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6637 		goto again;
6638 	}
6639 	return true;
6640 }
6641 
6642 /* forward declarations for arch-specific underlying types of
6643  * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
6644  * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
6645  * works correctly with __builtin_types_compatible_p() on respective
6646  * architectures
6647  */
6648 struct user_regs_struct;
6649 struct user_pt_regs;
6650 
6651 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
6652 				      const struct btf_type *t, int arg,
6653 				      enum bpf_prog_type prog_type,
6654 				      enum bpf_attach_type attach_type)
6655 {
6656 	const struct btf_type *ctx_type;
6657 	const char *tname, *ctx_tname;
6658 
6659 	if (!btf_is_ptr(t)) {
6660 		bpf_log(log, "arg#%d type isn't a pointer\n", arg);
6661 		return -EINVAL;
6662 	}
6663 	t = btf_type_by_id(btf, t->type);
6664 
6665 	/* KPROBE and PERF_EVENT programs allow bpf_user_pt_regs_t typedef */
6666 	if (prog_type == BPF_PROG_TYPE_KPROBE || prog_type == BPF_PROG_TYPE_PERF_EVENT) {
6667 		while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
6668 			t = btf_type_by_id(btf, t->type);
6669 
6670 		if (btf_type_is_typedef(t)) {
6671 			tname = btf_name_by_offset(btf, t->name_off);
6672 			if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
6673 				return 0;
6674 		}
6675 	}
6676 
6677 	/* all other program types don't use typedefs for context type */
6678 	while (btf_type_is_modifier(t))
6679 		t = btf_type_by_id(btf, t->type);
6680 
6681 	/* `void *ctx __arg_ctx` is always valid */
6682 	if (btf_type_is_void(t))
6683 		return 0;
6684 
6685 	tname = btf_name_by_offset(btf, t->name_off);
6686 	if (str_is_empty(tname)) {
6687 		bpf_log(log, "arg#%d type doesn't have a name\n", arg);
6688 		return -EINVAL;
6689 	}
6690 
6691 	/* special cases */
6692 	switch (prog_type) {
6693 	case BPF_PROG_TYPE_KPROBE:
6694 		if (__btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6695 			return 0;
6696 		break;
6697 	case BPF_PROG_TYPE_PERF_EVENT:
6698 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
6699 		    __btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
6700 			return 0;
6701 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
6702 		    __btf_type_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
6703 			return 0;
6704 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
6705 		    __btf_type_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
6706 			return 0;
6707 		break;
6708 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
6709 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
6710 		/* allow u64* as ctx */
6711 		if (btf_is_int(t) && t->size == 8)
6712 			return 0;
6713 		break;
6714 	case BPF_PROG_TYPE_TRACING:
6715 		switch (attach_type) {
6716 		case BPF_TRACE_RAW_TP:
6717 			/* tp_btf program is TRACING, so need special case here */
6718 			if (__btf_type_is_struct(t) &&
6719 			    strcmp(tname, "bpf_raw_tracepoint_args") == 0)
6720 				return 0;
6721 			/* allow u64* as ctx */
6722 			if (btf_is_int(t) && t->size == 8)
6723 				return 0;
6724 			break;
6725 		case BPF_TRACE_ITER:
6726 			/* allow struct bpf_iter__xxx types only */
6727 			if (__btf_type_is_struct(t) &&
6728 			    strncmp(tname, "bpf_iter__", sizeof("bpf_iter__") - 1) == 0)
6729 				return 0;
6730 			break;
6731 		case BPF_TRACE_FENTRY:
6732 		case BPF_TRACE_FEXIT:
6733 		case BPF_MODIFY_RETURN:
6734 		case BPF_TRACE_FSESSION:
6735 			/* allow u64* as ctx */
6736 			if (btf_is_int(t) && t->size == 8)
6737 				return 0;
6738 			break;
6739 		default:
6740 			break;
6741 		}
6742 		break;
6743 	case BPF_PROG_TYPE_LSM:
6744 	case BPF_PROG_TYPE_STRUCT_OPS:
6745 		/* allow u64* as ctx */
6746 		if (btf_is_int(t) && t->size == 8)
6747 			return 0;
6748 		break;
6749 	case BPF_PROG_TYPE_TRACEPOINT:
6750 	case BPF_PROG_TYPE_SYSCALL:
6751 	case BPF_PROG_TYPE_EXT:
6752 		return 0; /* anything goes */
6753 	default:
6754 		break;
6755 	}
6756 
6757 	ctx_type = find_canonical_prog_ctx_type(prog_type);
6758 	if (!ctx_type) {
6759 		/* should not happen */
6760 		bpf_log(log, "btf_vmlinux is malformed\n");
6761 		return -EINVAL;
6762 	}
6763 
6764 	/* resolve typedefs and check that underlying structs are matching as well */
6765 	while (btf_type_is_modifier(ctx_type))
6766 		ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6767 
6768 	/* if program type doesn't have distinctly named struct type for
6769 	 * context, then __arg_ctx argument can only be `void *`, which we
6770 	 * already checked above
6771 	 */
6772 	if (!__btf_type_is_struct(ctx_type)) {
6773 		bpf_log(log, "arg#%d should be void pointer\n", arg);
6774 		return -EINVAL;
6775 	}
6776 
6777 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6778 	if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
6779 		bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
6780 		return -EINVAL;
6781 	}
6782 
6783 	return 0;
6784 }
6785 
6786 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
6787 				     struct btf *btf,
6788 				     const struct btf_type *t,
6789 				     enum bpf_prog_type prog_type,
6790 				     int arg)
6791 {
6792 	if (!btf_is_prog_ctx_type(log, btf, t, prog_type, arg))
6793 		return -ENOENT;
6794 	return find_kern_ctx_type_id(prog_type);
6795 }
6796 
6797 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
6798 {
6799 	const struct btf_member *kctx_member;
6800 	const struct btf_type *conv_struct;
6801 	const struct btf_type *kctx_type;
6802 	u32 kctx_type_id;
6803 
6804 	conv_struct = bpf_ctx_convert.t;
6805 	/* get member for kernel ctx type */
6806 	kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6807 	kctx_type_id = kctx_member->type;
6808 	kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
6809 	if (!btf_type_is_struct(kctx_type)) {
6810 		bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
6811 		return -EINVAL;
6812 	}
6813 
6814 	return kctx_type_id;
6815 }
6816 
6817 BTF_ID_LIST_SINGLE(bpf_ctx_convert_btf_id, struct, bpf_ctx_convert)
6818 
6819 static struct btf *btf_parse_base(struct btf_verifier_env *env, const char *name,
6820 				  void *data, unsigned int data_size)
6821 {
6822 	struct btf *btf = NULL;
6823 	int err;
6824 
6825 	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
6826 		return ERR_PTR(-ENOENT);
6827 
6828 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
6829 	if (!btf) {
6830 		err = -ENOMEM;
6831 		goto errout;
6832 	}
6833 	env->btf = btf;
6834 
6835 	btf->data = data;
6836 	btf->data_size = data_size;
6837 	btf->kernel_btf = true;
6838 	btf->named_start_id = 0;
6839 	strscpy(btf->name, name);
6840 
6841 	err = btf_parse_hdr(env);
6842 	if (err)
6843 		goto errout;
6844 
6845 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6846 
6847 	err = btf_parse_str_sec(env);
6848 	if (err)
6849 		goto errout;
6850 
6851 	err = btf_check_all_metas(env);
6852 	if (err)
6853 		goto errout;
6854 
6855 	err = btf_check_modifier_chain_length(env, btf, 1);
6856 	if (err)
6857 		goto errout;
6858 
6859 	btf_check_sorted(btf);
6860 	refcount_set(&btf->refcnt, 1);
6861 
6862 	return btf;
6863 
6864 errout:
6865 	if (btf) {
6866 		kvfree(btf->types);
6867 		kfree(btf);
6868 	}
6869 	return ERR_PTR(err);
6870 }
6871 
6872 struct btf *btf_parse_vmlinux(void)
6873 {
6874 	struct btf_verifier_env *env = NULL;
6875 	struct bpf_verifier_log *log;
6876 	struct btf *btf;
6877 	int err;
6878 
6879 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
6880 	if (!env)
6881 		return ERR_PTR(-ENOMEM);
6882 
6883 	log = &env->log;
6884 	log->level = BPF_LOG_KERNEL;
6885 	btf = btf_parse_base(env, "vmlinux", __start_BTF, __stop_BTF - __start_BTF);
6886 	if (IS_ERR(btf))
6887 		goto err_out;
6888 
6889 	/* btf_parse_vmlinux() runs under btf_vmlinux_lock */
6890 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
6891 	err = btf_alloc_id(btf);
6892 	if (err) {
6893 		btf_free(btf);
6894 		btf = ERR_PTR(err);
6895 	}
6896 err_out:
6897 	btf_verifier_env_free(env);
6898 	return btf;
6899 }
6900 
6901 /* If .BTF_ids section was created with distilled base BTF, both base and
6902  * split BTF ids will need to be mapped to actual base/split ids for
6903  * BTF now that it has been relocated.
6904  */
6905 __u32 btf_relocate_id(const struct btf *btf, __u32 id)
6906 {
6907 	if (!btf->base_btf || !btf->base_id_map)
6908 		return id;
6909 	return btf->base_id_map[id];
6910 }
6911 
6912 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6913 
6914 static struct btf *btf_parse_module(const char *module_name, const void *data,
6915 				    unsigned int data_size, void *base_data,
6916 				    unsigned int base_data_size)
6917 {
6918 	struct btf *btf = NULL, *vmlinux_btf, *base_btf = NULL;
6919 	struct btf_verifier_env *env = NULL;
6920 	struct bpf_verifier_log *log;
6921 	int err = 0;
6922 
6923 	vmlinux_btf = bpf_get_btf_vmlinux();
6924 	if (IS_ERR(vmlinux_btf))
6925 		return vmlinux_btf;
6926 	if (!vmlinux_btf)
6927 		return ERR_PTR(-EINVAL);
6928 
6929 	env = kzalloc_obj(*env, GFP_KERNEL | __GFP_NOWARN);
6930 	if (!env)
6931 		return ERR_PTR(-ENOMEM);
6932 
6933 	log = &env->log;
6934 	log->level = BPF_LOG_KERNEL;
6935 
6936 	if (base_data) {
6937 		base_btf = btf_parse_base(env, ".BTF.base", base_data, base_data_size);
6938 		if (IS_ERR(base_btf)) {
6939 			err = PTR_ERR(base_btf);
6940 			goto errout;
6941 		}
6942 	} else {
6943 		base_btf = vmlinux_btf;
6944 	}
6945 
6946 	btf = kzalloc_obj(*btf, GFP_KERNEL | __GFP_NOWARN);
6947 	if (!btf) {
6948 		err = -ENOMEM;
6949 		goto errout;
6950 	}
6951 	env->btf = btf;
6952 
6953 	btf->base_btf = base_btf;
6954 	btf->start_id = base_btf->nr_types;
6955 	btf->start_str_off = base_btf->hdr.str_len;
6956 	btf->kernel_btf = true;
6957 	btf->named_start_id = 0;
6958 	strscpy(btf->name, module_name);
6959 
6960 	btf->data = kvmemdup(data, data_size, GFP_KERNEL | __GFP_NOWARN);
6961 	if (!btf->data) {
6962 		err = -ENOMEM;
6963 		goto errout;
6964 	}
6965 	btf->data_size = data_size;
6966 
6967 	err = btf_parse_hdr(env);
6968 	if (err)
6969 		goto errout;
6970 
6971 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6972 
6973 	err = btf_parse_str_sec(env);
6974 	if (err)
6975 		goto errout;
6976 
6977 	err = btf_check_all_metas(env);
6978 	if (err)
6979 		goto errout;
6980 
6981 	err = btf_check_modifier_chain_length(env, btf, btf_nr_types(base_btf));
6982 	if (err)
6983 		goto errout;
6984 
6985 	if (base_btf != vmlinux_btf) {
6986 		err = btf_relocate(btf, vmlinux_btf, &btf->base_id_map);
6987 		if (err)
6988 			goto errout;
6989 		btf_free(base_btf);
6990 		base_btf = vmlinux_btf;
6991 	}
6992 
6993 	btf_verifier_env_free(env);
6994 	btf_check_sorted(btf);
6995 	refcount_set(&btf->refcnt, 1);
6996 	return btf;
6997 
6998 errout:
6999 	btf_verifier_env_free(env);
7000 	if (!IS_ERR(base_btf) && base_btf != vmlinux_btf)
7001 		btf_free(base_btf);
7002 	if (btf) {
7003 		kvfree(btf->data);
7004 		kvfree(btf->types);
7005 		kfree(btf);
7006 	}
7007 	return ERR_PTR(err);
7008 }
7009 
7010 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7011 
7012 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
7013 {
7014 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
7015 
7016 	if (tgt_prog)
7017 		return tgt_prog->aux->btf;
7018 	else
7019 		return prog->aux->attach_btf;
7020 }
7021 
7022 u32 btf_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
7023 		    int off)
7024 {
7025 	const struct btf_param *args;
7026 	const struct btf_type *t;
7027 	u32 offset = 0, nr_args;
7028 	int i;
7029 
7030 	if (!func_proto)
7031 		return off / 8;
7032 
7033 	nr_args = btf_type_vlen(func_proto);
7034 	args = (const struct btf_param *)(func_proto + 1);
7035 	for (i = 0; i < nr_args; i++) {
7036 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
7037 		offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
7038 		if (off < offset)
7039 			return i;
7040 	}
7041 
7042 	t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
7043 	offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
7044 	if (off < offset)
7045 		return nr_args;
7046 
7047 	return nr_args + 1;
7048 }
7049 
7050 static bool prog_args_trusted(const struct bpf_prog *prog)
7051 {
7052 	enum bpf_attach_type atype = prog->expected_attach_type;
7053 
7054 	switch (prog->type) {
7055 	case BPF_PROG_TYPE_TRACING:
7056 		return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
7057 	case BPF_PROG_TYPE_LSM:
7058 		return bpf_lsm_is_trusted(prog);
7059 	case BPF_PROG_TYPE_STRUCT_OPS:
7060 		return true;
7061 	default:
7062 		return false;
7063 	}
7064 }
7065 
7066 int btf_ctx_arg_offset(const struct btf *btf, const struct btf_type *func_proto,
7067 		       u32 arg_no)
7068 {
7069 	const struct btf_param *args;
7070 	const struct btf_type *t;
7071 	int off = 0, i;
7072 	u32 sz;
7073 
7074 	args = btf_params(func_proto);
7075 	for (i = 0; i < arg_no; i++) {
7076 		t = btf_type_by_id(btf, args[i].type);
7077 		t = btf_resolve_size(btf, t, &sz);
7078 		if (IS_ERR(t))
7079 			return PTR_ERR(t);
7080 		off += roundup(sz, 8);
7081 	}
7082 
7083 	return off;
7084 }
7085 
7086 struct bpf_raw_tp_null_args {
7087 	const char *func;
7088 	u64 mask;
7089 };
7090 
7091 static const struct bpf_raw_tp_null_args raw_tp_null_args[] = {
7092 	/* sched */
7093 	{ "sched_pi_setprio", 0x10 },
7094 	/*
7095 	 * do_wait() passes NULL for wait4(-1) and waitid(P_ALL).
7096 	 */
7097 	{ "sched_process_wait", 0x1 },
7098 	/* ... from sched_numa_pair_template event class */
7099 	{ "sched_stick_numa", 0x100 },
7100 	{ "sched_swap_numa", 0x100 },
7101 	/* afs */
7102 	{ "afs_make_fs_call", 0x10 },
7103 	{ "afs_make_fs_calli", 0x10 },
7104 	{ "afs_make_fs_call1", 0x10 },
7105 	{ "afs_make_fs_call2", 0x10 },
7106 	{ "afs_protocol_error", 0x1 },
7107 	{ "afs_flock_ev", 0x10 },
7108 	/* cachefiles */
7109 	{ "cachefiles_lookup", 0x1 | 0x200 },
7110 	{ "cachefiles_unlink", 0x1 },
7111 	{ "cachefiles_rename", 0x1 },
7112 	{ "cachefiles_prep_read", 0x1 },
7113 	{ "cachefiles_mark_active", 0x1 },
7114 	{ "cachefiles_mark_failed", 0x1 },
7115 	{ "cachefiles_mark_inactive", 0x1 },
7116 	{ "cachefiles_vfs_error", 0x1 },
7117 	{ "cachefiles_io_error", 0x1 },
7118 	/* ext4, from ext4__mballoc event class */
7119 	{ "ext4_mballoc_discard", 0x10 },
7120 	{ "ext4_mballoc_free", 0x10 },
7121 	/* fib */
7122 	{ "fib_table_lookup", 0x100 },
7123 	/* filelock */
7124 	/* ... from filelock_lock event class */
7125 	{ "posix_lock_inode", 0x10 },
7126 	{ "fcntl_setlk", 0x10 },
7127 	{ "locks_remove_posix", 0x10 },
7128 	{ "flock_lock_inode", 0x10 },
7129 	/* ... from filelock_lease event class */
7130 	{ "break_lease_noblock", 0x10 },
7131 	{ "break_lease_block", 0x10 },
7132 	{ "break_lease_unblock", 0x10 },
7133 	{ "generic_delete_lease", 0x10 },
7134 	{ "time_out_leases", 0x10 },
7135 	/* host1x */
7136 	{ "host1x_cdma_push_gather", 0x10000 },
7137 	/* huge_memory */
7138 	{ "mm_khugepaged_scan_pmd", 0x10 },
7139 	{ "mm_collapse_huge_page_isolate", 0x1 },
7140 	{ "mm_khugepaged_scan_file", 0x10 },
7141 	{ "mm_khugepaged_collapse_file", 0x10 },
7142 	/* kmem */
7143 	{ "mm_page_alloc", 0x1 },
7144 	{ "mm_page_pcpu_drain", 0x1 },
7145 	/* .. from mm_page event class */
7146 	{ "mm_page_alloc_zone_locked", 0x1 },
7147 	/* netfs */
7148 	{ "netfs_failure", 0x10 },
7149 	/* power */
7150 	{ "device_pm_callback_start", 0x10 },
7151 	/* qdisc */
7152 	{ "qdisc_dequeue", 0x1000 },
7153 	/* rxrpc */
7154 	{ "rxrpc_recvdata", 0x1 },
7155 	{ "rxrpc_resend", 0x10 },
7156 	{ "rxrpc_tq", 0x10 },
7157 	{ "rxrpc_client", 0x1 },
7158 	/* signal */
7159 	{ "signal_generate", 0x20 },
7160 	{ "signal_deliver", 0x20 },
7161 	/* skb */
7162 	{"kfree_skb", 0x1000},
7163 	/* sunrpc */
7164 	{ "xs_stream_read_data", 0x1 },
7165 	/* ... from xprt_cong_event event class */
7166 	{ "xprt_reserve_cong", 0x10 },
7167 	{ "xprt_release_cong", 0x10 },
7168 	{ "xprt_get_cong", 0x10 },
7169 	{ "xprt_put_cong", 0x10 },
7170 	/* tcp */
7171 	{ "tcp_send_reset", 0x11 },
7172 	{ "tcp_sendmsg_locked", 0x100 },
7173 	/* tegra_apb_dma */
7174 	{ "tegra_dma_tx_status", 0x100 },
7175 	/* timer_migration */
7176 	{ "tmigr_update_events", 0x1 },
7177 	/* writeback, from writeback_folio_template event class */
7178 	{ "writeback_dirty_folio", 0x10 },
7179 	{ "folio_wait_writeback", 0x10 },
7180 	/* rdma */
7181 	{ "mr_integ_alloc", 0x2000 },
7182 	/* bpf_testmod */
7183 	{ "bpf_testmod_test_read", 0x0 },
7184 	/* amdgpu */
7185 	{ "amdgpu_vm_bo_map", 0x1 },
7186 	{ "amdgpu_vm_bo_unmap", 0x1 },
7187 	/* netfs */
7188 	{ "netfs_folioq", 0x1 },
7189 	/* xfs from xfs_defer_pending_class */
7190 	{ "xfs_defer_create_intent", 0x1 },
7191 	{ "xfs_defer_cancel_list", 0x1 },
7192 	{ "xfs_defer_pending_finish", 0x1 },
7193 	{ "xfs_defer_pending_abort", 0x1 },
7194 	{ "xfs_defer_relog_intent", 0x1 },
7195 	{ "xfs_defer_isolate_paused", 0x1 },
7196 	{ "xfs_defer_item_pause", 0x1 },
7197 	{ "xfs_defer_item_unpause", 0x1 },
7198 	/* xfs from xfs_defer_pending_item_class */
7199 	{ "xfs_defer_add_item", 0x1 },
7200 	{ "xfs_defer_cancel_item", 0x1 },
7201 	{ "xfs_defer_finish_item", 0x1 },
7202 	/* xfs from xfs_icwalk_class */
7203 	{ "xfs_ioc_free_eofblocks", 0x10 },
7204 	{ "xfs_blockgc_free_space", 0x10 },
7205 	/* xfs from xfs_btree_cur_class */
7206 	{ "xfs_btree_updkeys", 0x100 },
7207 	{ "xfs_btree_overlapped_query_range", 0x100 },
7208 	/* xfs from xfs_imap_class*/
7209 	{ "xfs_map_blocks_found", 0x10000 },
7210 	{ "xfs_map_blocks_alloc", 0x10000 },
7211 	{ "xfs_iomap_alloc", 0x1000 },
7212 	{ "xfs_iomap_found", 0x1000 },
7213 	/* xfs from xfs_fs_class */
7214 	{ "xfs_inodegc_flush", 0x1 },
7215 	{ "xfs_inodegc_push", 0x1 },
7216 	{ "xfs_inodegc_start", 0x1 },
7217 	{ "xfs_inodegc_stop", 0x1 },
7218 	{ "xfs_inodegc_queue", 0x1 },
7219 	{ "xfs_inodegc_throttle", 0x1 },
7220 	{ "xfs_fs_sync_fs", 0x1 },
7221 	{ "xfs_blockgc_start", 0x1 },
7222 	{ "xfs_blockgc_stop", 0x1 },
7223 	{ "xfs_blockgc_worker", 0x1 },
7224 	{ "xfs_blockgc_flush_all", 0x1 },
7225 	/* xfs_scrub */
7226 	{ "xchk_nlinks_live_update", 0x10 },
7227 	/* xfs_scrub from xchk_metapath_class */
7228 	{ "xchk_metapath_lookup", 0x100 },
7229 	/* nfsd */
7230 	{ "nfsd_dirent", 0x1 },
7231 	{ "nfsd_file_acquire", 0x1001 },
7232 	{ "nfsd_file_insert_err", 0x1 },
7233 	{ "nfsd_file_cons_err", 0x1 },
7234 	/* nfs4 */
7235 	{ "nfs4_setup_sequence", 0x1 },
7236 	{ "pnfs_update_layout", 0x10000 },
7237 	{ "nfs4_inode_callback_event", 0x200 },
7238 	{ "nfs4_inode_stateid_callback_event", 0x200 },
7239 	/* nfs from pnfs_layout_event */
7240 	{ "pnfs_mds_fallback_pg_init_read", 0x10000 },
7241 	{ "pnfs_mds_fallback_pg_init_write", 0x10000 },
7242 	{ "pnfs_mds_fallback_pg_get_mirror_count", 0x10000 },
7243 	{ "pnfs_mds_fallback_read_done", 0x10000 },
7244 	{ "pnfs_mds_fallback_write_done", 0x10000 },
7245 	{ "pnfs_mds_fallback_read_pagelist", 0x10000 },
7246 	{ "pnfs_mds_fallback_write_pagelist", 0x10000 },
7247 	/* coda */
7248 	{ "coda_dec_pic_run", 0x10 },
7249 	{ "coda_dec_pic_done", 0x10 },
7250 	/* cfg80211 */
7251 	{ "cfg80211_scan_done", 0x11 },
7252 	{ "rdev_set_coalesce", 0x10 },
7253 	{ "cfg80211_report_wowlan_wakeup", 0x100 },
7254 	{ "cfg80211_inform_bss_frame", 0x100 },
7255 	{ "cfg80211_michael_mic_failure", 0x10000 },
7256 	/* cfg80211 from wiphy_work_event */
7257 	{ "wiphy_work_queue", 0x10 },
7258 	{ "wiphy_work_run", 0x10 },
7259 	{ "wiphy_work_cancel", 0x10 },
7260 	{ "wiphy_work_flush", 0x10 },
7261 	/* hugetlbfs */
7262 	{ "hugetlbfs_alloc_inode", 0x10 },
7263 	/* spufs */
7264 	{ "spufs_context", 0x10 },
7265 	/* kvm_hv */
7266 	{ "kvm_page_fault_enter", 0x100 },
7267 	/* dpu */
7268 	{ "dpu_crtc_setup_mixer", 0x100 },
7269 	/* binder */
7270 	{ "binder_transaction", 0x100 },
7271 	/* bcachefs */
7272 	{ "btree_path_free", 0x100 },
7273 	/* hfi1_tx */
7274 	{ "hfi1_sdma_progress", 0x1000 },
7275 	/* iptfs */
7276 	{ "iptfs_ingress_postq_event", 0x1000 },
7277 	/* neigh */
7278 	{ "neigh_update", 0x10 },
7279 	/* snd_firewire_lib */
7280 	{ "amdtp_packet", 0x100 },
7281 };
7282 
7283 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
7284 		    const struct bpf_prog *prog,
7285 		    struct bpf_insn_access_aux *info)
7286 {
7287 	static const struct btf_type_tag_match ctx_type_tags[] = {
7288 		{ "user", MEM_USER },
7289 		{ "percpu", MEM_PERCPU },
7290 	};
7291 	const struct btf_type *t = prog->aux->attach_func_proto;
7292 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
7293 	struct btf *btf = bpf_prog_get_target_btf(prog);
7294 	const char *tname = prog->aux->attach_func_name;
7295 	struct bpf_verifier_log *log = info->log;
7296 	struct btf_type_tag_walk_ctx ctx;
7297 	const struct btf_param *args;
7298 	bool ptr_err_raw_tp = false;
7299 	u32 nr_args, arg;
7300 	int i, ret;
7301 
7302 	if (off % 8) {
7303 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
7304 			tname, off);
7305 		return false;
7306 	}
7307 	arg = btf_ctx_arg_idx(btf, t, off);
7308 	args = (const struct btf_param *)(t + 1);
7309 	/* if (t == NULL) Fall back to default BPF prog with
7310 	 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
7311 	 */
7312 	nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
7313 	if (prog->aux->attach_btf_trace) {
7314 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
7315 		args++;
7316 		nr_args--;
7317 	}
7318 
7319 	if (arg > nr_args) {
7320 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
7321 			tname, arg + 1);
7322 		return false;
7323 	}
7324 
7325 	if (arg == nr_args) {
7326 		switch (prog->expected_attach_type) {
7327 		case BPF_LSM_MAC:
7328 			/* mark we are accessing the return value */
7329 			info->is_retval = true;
7330 			fallthrough;
7331 		case BPF_LSM_CGROUP:
7332 		case BPF_TRACE_FEXIT:
7333 		case BPF_TRACE_FSESSION:
7334 			/* When LSM programs are attached to void LSM hooks
7335 			 * they use FEXIT trampolines and when attached to
7336 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
7337 			 *
7338 			 * While the LSM programs are BPF_MODIFY_RETURN-like
7339 			 * the check:
7340 			 *
7341 			 *	if (ret_type != 'int')
7342 			 *		return -EINVAL;
7343 			 *
7344 			 * is _not_ done here. This is still safe as LSM hooks
7345 			 * have only void and int return types.
7346 			 */
7347 			if (!t)
7348 				return true;
7349 			t = btf_type_by_id(btf, t->type);
7350 			break;
7351 		case BPF_MODIFY_RETURN:
7352 			/* For now the BPF_MODIFY_RETURN can only be attached to
7353 			 * functions that return an int.
7354 			 */
7355 			if (!t)
7356 				return false;
7357 
7358 			t = btf_type_skip_modifiers(btf, t->type, NULL);
7359 			if (!btf_type_is_small_int(t)) {
7360 				bpf_log(log,
7361 					"ret type %s not allowed for fmod_ret\n",
7362 					btf_type_str(t));
7363 				return false;
7364 			}
7365 			break;
7366 		default:
7367 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
7368 				tname, arg + 1);
7369 			return false;
7370 		}
7371 	} else {
7372 		if (!t)
7373 			/* Default prog with MAX_BPF_FUNC_REG_ARGS args */
7374 			return true;
7375 		t = btf_type_by_id(btf, args[arg].type);
7376 	}
7377 
7378 	/* skip modifiers */
7379 	while (btf_type_is_modifier(t))
7380 		t = btf_type_by_id(btf, t->type);
7381 	if (btf_type_is_small_int(t) || btf_is_any_enum(t) || btf_type_is_struct(t))
7382 		/* accessing a scalar */
7383 		return true;
7384 	if (!btf_type_is_ptr(t)) {
7385 		bpf_log(log,
7386 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
7387 			tname, arg,
7388 			__btf_name_by_offset(btf, t->name_off),
7389 			btf_type_str(t));
7390 		return false;
7391 	}
7392 
7393 	if (size != sizeof(u64)) {
7394 		bpf_log(log, "func '%s' size %d must be 8\n",
7395 			tname, size);
7396 		return false;
7397 	}
7398 
7399 	/*
7400 	 * Check for PTR_TO_RDONLY_BUF_OR_NULL, PTR_TO_RDWR_BUF_OR_NULL,
7401 	 * PTR_TO_ARENA (both nullable and non-nullable cases) or fixed-size
7402 	 * PTR_TO_MEM.
7403 	 */
7404 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
7405 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
7406 		u32 type, flag;
7407 
7408 		type = base_type(ctx_arg_info->reg_type);
7409 		flag = type_flag(ctx_arg_info->reg_type);
7410 		if (ctx_arg_info->offset == off &&
7411 		    (type == PTR_TO_ARENA ||
7412 		     type == PTR_TO_MEM ||
7413 		     (type == PTR_TO_BUF && (flag & PTR_MAYBE_NULL)))) {
7414 			info->reg_type = ctx_arg_info->reg_type;
7415 			info->mem_size = ctx_arg_info->mem_size;
7416 			return true;
7417 		}
7418 	}
7419 
7420 	/*
7421 	 * If it's a single or multilevel pointer, except a pointer
7422 	 * to a structure, it's the same as scalar from the verifier
7423 	 * safety POV. Multilevel pointers to structures are treated as
7424 	 * scalars. The verifier lacks the context to infer the size of
7425 	 * their target memory regions. Either way, no further pointer
7426 	 * walking is allowed.
7427 	 */
7428 	if (!btf_type_is_struct_ptr(btf, t))
7429 		return true;
7430 
7431 	/* this is a pointer to another type */
7432 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
7433 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
7434 
7435 		if (ctx_arg_info->offset == off) {
7436 			if (!ctx_arg_info->btf_id) {
7437 				bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
7438 				return false;
7439 			}
7440 
7441 			info->reg_type = ctx_arg_info->reg_type;
7442 			info->btf = ctx_arg_info->btf ? : btf_vmlinux;
7443 			info->btf_id = ctx_arg_info->btf_id;
7444 			info->ref_id = ctx_arg_info->ref_id;
7445 			return true;
7446 		}
7447 	}
7448 
7449 	info->reg_type = PTR_TO_BTF_ID;
7450 	if (prog_args_trusted(prog))
7451 		info->reg_type |= PTR_TRUSTED;
7452 
7453 	if (btf_param_match_suffix(btf, &args[arg], "__nullable"))
7454 		info->reg_type |= PTR_MAYBE_NULL;
7455 
7456 	if (prog->expected_attach_type == BPF_TRACE_RAW_TP) {
7457 		struct btf *btf = prog->aux->attach_btf;
7458 		const struct btf_type *t;
7459 		const char *tname;
7460 
7461 		/* BTF lookups cannot fail, return false on error */
7462 		t = btf_type_by_id(btf, prog->aux->attach_btf_id);
7463 		if (!t)
7464 			return false;
7465 		tname = btf_name_by_offset(btf, t->name_off);
7466 		if (!tname)
7467 			return false;
7468 		/* Checked by bpf_check_attach_target */
7469 		tname += sizeof("btf_trace_") - 1;
7470 		for (i = 0; i < ARRAY_SIZE(raw_tp_null_args); i++) {
7471 			/* Is this a func with potential NULL args? */
7472 			if (strcmp(tname, raw_tp_null_args[i].func))
7473 				continue;
7474 			if (raw_tp_null_args[i].mask & (0x1ULL << (arg * 4)))
7475 				info->reg_type |= PTR_MAYBE_NULL;
7476 			/* Is the current arg IS_ERR? */
7477 			if (raw_tp_null_args[i].mask & (0x2ULL << (arg * 4)))
7478 				ptr_err_raw_tp = true;
7479 			break;
7480 		}
7481 		/* If we don't know NULL-ness specification and the tracepoint
7482 		 * is coming from a loadable module, be conservative and mark
7483 		 * argument as PTR_MAYBE_NULL.
7484 		 */
7485 		if (i == ARRAY_SIZE(raw_tp_null_args) && btf_is_module(btf))
7486 			info->reg_type |= PTR_MAYBE_NULL;
7487 	}
7488 
7489 	if (tgt_prog) {
7490 		enum bpf_prog_type tgt_type;
7491 
7492 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
7493 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
7494 		else
7495 			tgt_type = tgt_prog->type;
7496 
7497 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
7498 		if (ret > 0) {
7499 			info->btf = btf_vmlinux;
7500 			info->btf_id = ret;
7501 			return true;
7502 		} else {
7503 			return false;
7504 		}
7505 	}
7506 
7507 	info->btf = btf;
7508 	ctx.t = t;
7509 	ret = btf_type_tag_walk(btf, &ctx, ctx_type_tags,
7510 				ARRAY_SIZE(ctx_type_tags));
7511 	if (ret) {
7512 		bpf_log(log, "func '%s' arg%d type %s has multiple type tags\n",
7513 			tname, arg, btf_type_str(t));
7514 		return false;
7515 	}
7516 	info->reg_type |= ctx.res;
7517 	info->btf_id = ctx.id;
7518 	t = ctx.t;
7519 
7520 	if (!btf_type_is_struct(t)) {
7521 		bpf_log(log,
7522 			"func '%s' arg%d type %s is not a struct\n",
7523 			tname, arg, btf_type_str(t));
7524 		return false;
7525 	}
7526 	bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
7527 		tname, arg, info->btf_id, btf_type_str(t),
7528 		__btf_name_by_offset(btf, t->name_off));
7529 
7530 	/* Perform all checks on the validity of type for this argument, but if
7531 	 * we know it can be IS_ERR at runtime, scrub pointer type and mark as
7532 	 * scalar.
7533 	 */
7534 	if (ptr_err_raw_tp) {
7535 		bpf_log(log, "marking pointer arg%d as scalar as it may encode error", arg);
7536 		info->reg_type = SCALAR_VALUE;
7537 	}
7538 	return true;
7539 }
7540 EXPORT_SYMBOL_GPL(btf_ctx_access);
7541 
7542 enum bpf_struct_walk_result {
7543 	/* < 0 error */
7544 	WALK_SCALAR = 0,
7545 	WALK_PTR,
7546 	WALK_PTR_UNTRUSTED,
7547 	WALK_STRUCT,
7548 };
7549 
7550 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
7551 			   const struct btf_type *t, int off, int size,
7552 			   u32 *next_btf_id, enum bpf_type_flag *flag,
7553 			   const char **field_name, bool walk_flex_arrays)
7554 {
7555 	u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
7556 	const struct btf_type *mtype, *elem_type = NULL;
7557 	const struct btf_member *member;
7558 	const char *tname, *mname;
7559 	u32 vlen, elem_id, mid;
7560 
7561 again:
7562 	if (btf_type_is_modifier(t))
7563 		t = btf_type_skip_modifiers(btf, t->type, NULL);
7564 	tname = __btf_name_by_offset(btf, t->name_off);
7565 	if (!btf_type_is_struct(t)) {
7566 		bpf_log(log, "Type '%s' is not a struct\n", tname);
7567 		return -EINVAL;
7568 	}
7569 
7570 	vlen = btf_type_vlen(t);
7571 	if (BTF_INFO_KIND(t->info) == BTF_KIND_UNION && vlen != 1 && !(*flag & PTR_UNTRUSTED))
7572 		/*
7573 		 * walking unions yields untrusted pointers
7574 		 * with exception of __bpf_md_ptr and other
7575 		 * unions with a single member
7576 		 */
7577 		*flag |= PTR_UNTRUSTED;
7578 
7579 	if (off + size > t->size) {
7580 		struct btf_array *array_elem;
7581 
7582 		if (!walk_flex_arrays)
7583 			goto error;
7584 
7585 		/* If the last element is a variable size array, we may
7586 		 * need to relax the rule.
7587 		 */
7588 		if (vlen == 0)
7589 			goto error;
7590 
7591 		member = btf_type_member(t) + vlen - 1;
7592 		mtype = btf_type_skip_modifiers(btf, member->type,
7593 						NULL);
7594 		if (!btf_type_is_array(mtype))
7595 			goto error;
7596 
7597 		array_elem = (struct btf_array *)(mtype + 1);
7598 		if (array_elem->nelems != 0)
7599 			goto error;
7600 
7601 		moff = __btf_member_bit_offset(t, member) / 8;
7602 		if (off < moff)
7603 			goto error;
7604 
7605 		/* allow structure and integer */
7606 		t = btf_type_skip_modifiers(btf, array_elem->type,
7607 					    NULL);
7608 
7609 		if (btf_type_is_int(t))
7610 			return WALK_SCALAR;
7611 
7612 		if (!btf_type_is_struct(t) || !t->size)
7613 			goto error;
7614 
7615 		off = (off - moff) % t->size;
7616 		goto again;
7617 
7618 error:
7619 		bpf_log(log, "access beyond struct %s at off %u size %u\n",
7620 			tname, off, size);
7621 		return -EACCES;
7622 	}
7623 
7624 	for_each_member(i, t, member) {
7625 		/* offset of the field in bytes */
7626 		moff = __btf_member_bit_offset(t, member) / 8;
7627 		if (off + size <= moff)
7628 			/* won't find anything, field is already too far */
7629 			break;
7630 
7631 		if (__btf_member_bitfield_size(t, member)) {
7632 			u32 end_bit = __btf_member_bit_offset(t, member) +
7633 				__btf_member_bitfield_size(t, member);
7634 
7635 			/* off <= moff instead of off == moff because clang
7636 			 * does not generate a BTF member for anonymous
7637 			 * bitfield like the ":16" here:
7638 			 * struct {
7639 			 *	int :16;
7640 			 *	int x:8;
7641 			 * };
7642 			 */
7643 			if (off <= moff &&
7644 			    BITS_ROUNDUP_BYTES(end_bit) <= off + size)
7645 				return WALK_SCALAR;
7646 
7647 			/* off may be accessing a following member
7648 			 *
7649 			 * or
7650 			 *
7651 			 * Doing partial access at either end of this
7652 			 * bitfield.  Continue on this case also to
7653 			 * treat it as not accessing this bitfield
7654 			 * and eventually error out as field not
7655 			 * found to keep it simple.
7656 			 * It could be relaxed if there was a legit
7657 			 * partial access case later.
7658 			 */
7659 			continue;
7660 		}
7661 
7662 		/* In case of "off" is pointing to holes of a struct */
7663 		if (off < moff)
7664 			break;
7665 
7666 		/* type of the field */
7667 		mid = member->type;
7668 		mtype = btf_type_by_id(btf, member->type);
7669 		mname = __btf_name_by_offset(btf, member->name_off);
7670 
7671 		mtype = __btf_resolve_size(btf, mtype, &msize,
7672 					   &elem_type, &elem_id, &total_nelems,
7673 					   &mid);
7674 		if (IS_ERR(mtype)) {
7675 			bpf_log(log, "field %s doesn't have size\n", mname);
7676 			return -EFAULT;
7677 		}
7678 
7679 		mtrue_end = moff + msize;
7680 		if (off >= mtrue_end)
7681 			/* no overlap with member, keep iterating */
7682 			continue;
7683 
7684 		if (btf_type_is_array(mtype)) {
7685 			u32 elem_idx;
7686 
7687 			/* __btf_resolve_size() above helps to
7688 			 * linearize a multi-dimensional array.
7689 			 *
7690 			 * The logic here is treating an array
7691 			 * in a struct as the following way:
7692 			 *
7693 			 * struct outer {
7694 			 *	struct inner array[2][2];
7695 			 * };
7696 			 *
7697 			 * looks like:
7698 			 *
7699 			 * struct outer {
7700 			 *	struct inner array_elem0;
7701 			 *	struct inner array_elem1;
7702 			 *	struct inner array_elem2;
7703 			 *	struct inner array_elem3;
7704 			 * };
7705 			 *
7706 			 * When accessing outer->array[1][0], it moves
7707 			 * moff to "array_elem2", set mtype to
7708 			 * "struct inner", and msize also becomes
7709 			 * sizeof(struct inner).  Then most of the
7710 			 * remaining logic will fall through without
7711 			 * caring the current member is an array or
7712 			 * not.
7713 			 *
7714 			 * Unlike mtype/msize/moff, mtrue_end does not
7715 			 * change.  The naming difference ("_true") tells
7716 			 * that it is not always corresponding to
7717 			 * the current mtype/msize/moff.
7718 			 * It is the true end of the current
7719 			 * member (i.e. array in this case).  That
7720 			 * will allow an int array to be accessed like
7721 			 * a scratch space,
7722 			 * i.e. allow access beyond the size of
7723 			 *      the array's element as long as it is
7724 			 *      within the mtrue_end boundary.
7725 			 */
7726 
7727 			/* skip empty array */
7728 			if (moff == mtrue_end)
7729 				continue;
7730 
7731 			msize /= total_nelems;
7732 			elem_idx = (off - moff) / msize;
7733 			moff += elem_idx * msize;
7734 			mtype = elem_type;
7735 			mid = elem_id;
7736 		}
7737 
7738 		/* the 'off' we're looking for is either equal to start
7739 		 * of this field or inside of this struct
7740 		 */
7741 		if (btf_type_is_struct(mtype)) {
7742 			/* our field must be inside that union or struct */
7743 			t = mtype;
7744 
7745 			/* return if the offset matches the member offset */
7746 			if (off == moff) {
7747 				*next_btf_id = mid;
7748 				return WALK_STRUCT;
7749 			}
7750 
7751 			/* adjust offset we're looking for */
7752 			off -= moff;
7753 			goto again;
7754 		}
7755 
7756 		if (btf_type_is_ptr(mtype)) {
7757 			static const struct btf_type_tag_match walk_type_tags[] = {
7758 				{ "user", MEM_USER },
7759 				{ "percpu", MEM_PERCPU },
7760 				{ "rcu", MEM_RCU },
7761 			};
7762 			enum bpf_type_flag tmp_flag = 0;
7763 			struct btf_type_tag_walk_ctx ctx = { .t = mtype };
7764 			const struct btf_type *stype;
7765 			int err;
7766 			u32 id;
7767 
7768 			if (msize != size || off != moff) {
7769 				bpf_log(log,
7770 					"cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
7771 					mname, moff, tname, off, size);
7772 				return -EACCES;
7773 			}
7774 
7775 			err = btf_type_tag_walk(btf, &ctx, walk_type_tags,
7776 						ARRAY_SIZE(walk_type_tags));
7777 			if (err) {
7778 				bpf_log(log, "type '%s' has multiple type tags\n",
7779 					btf_type_str(mtype));
7780 				return err;
7781 			}
7782 			tmp_flag = ctx.res;
7783 			id = ctx.id;
7784 			stype = ctx.t;
7785 
7786 			if (btf_type_is_struct(stype)) {
7787 				*next_btf_id = id;
7788 				*flag |= tmp_flag;
7789 				if (field_name)
7790 					*field_name = mname;
7791 				return WALK_PTR;
7792 			}
7793 
7794 			return WALK_PTR_UNTRUSTED;
7795 		}
7796 
7797 		/* Allow more flexible access within an int as long as
7798 		 * it is within mtrue_end.
7799 		 * Since mtrue_end could be the end of an array,
7800 		 * that also allows using an array of int as a scratch
7801 		 * space. e.g. skb->cb[].
7802 		 */
7803 		if (off + size > mtrue_end && !(*flag & PTR_UNTRUSTED)) {
7804 			bpf_log(log,
7805 				"access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
7806 				mname, mtrue_end, tname, off, size);
7807 			return -EACCES;
7808 		}
7809 
7810 		return WALK_SCALAR;
7811 	}
7812 	bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
7813 	return -EINVAL;
7814 }
7815 
7816 int btf_struct_access(struct bpf_verifier_log *log,
7817 		      const struct bpf_reg_state *reg,
7818 		      int off, int size, enum bpf_access_type atype __maybe_unused,
7819 		      u32 *next_btf_id, enum bpf_type_flag *flag,
7820 		      const char **field_name)
7821 {
7822 	const struct btf *btf = reg->btf;
7823 	enum bpf_type_flag tmp_flag = 0;
7824 	const struct btf_type *t;
7825 	u32 id = reg->btf_id;
7826 	int err;
7827 
7828 	while (type_is_alloc(reg->type)) {
7829 		struct btf_struct_meta *meta;
7830 		struct btf_record *rec;
7831 		int i;
7832 
7833 		meta = btf_find_struct_meta(btf, id);
7834 		if (!meta)
7835 			break;
7836 		rec = meta->record;
7837 		for (i = 0; i < rec->cnt; i++) {
7838 			struct btf_field *field = &rec->fields[i];
7839 			u32 offset = field->offset;
7840 			if (off < offset + field->size && offset < off + size) {
7841 				bpf_log(log,
7842 					"direct access to %s is disallowed\n",
7843 					btf_field_type_name(field->type));
7844 				return -EACCES;
7845 			}
7846 		}
7847 		break;
7848 	}
7849 
7850 	t = btf_type_by_id(btf, id);
7851 	do {
7852 		err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag,
7853 				      field_name, !type_is_alloc(reg->type));
7854 
7855 		switch (err) {
7856 		case WALK_PTR:
7857 			/* For local types, the destination register cannot
7858 			 * become a pointer again.
7859 			 */
7860 			if (type_is_alloc(reg->type))
7861 				return SCALAR_VALUE;
7862 			/* If we found the pointer or scalar on t+off,
7863 			 * we're done.
7864 			 */
7865 			*next_btf_id = id;
7866 			*flag = tmp_flag;
7867 			return PTR_TO_BTF_ID;
7868 		case WALK_PTR_UNTRUSTED:
7869 			*flag = MEM_RDONLY | PTR_UNTRUSTED;
7870 			return PTR_TO_MEM;
7871 		case WALK_SCALAR:
7872 			return SCALAR_VALUE;
7873 		case WALK_STRUCT:
7874 			/* We found nested struct, so continue the search
7875 			 * by diving in it. At this point the offset is
7876 			 * aligned with the new type, so set it to 0.
7877 			 */
7878 			t = btf_type_by_id(btf, id);
7879 			off = 0;
7880 			break;
7881 		default:
7882 			/* It's either error or unknown return value..
7883 			 * scream and leave.
7884 			 */
7885 			if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
7886 				return -EINVAL;
7887 			return err;
7888 		}
7889 	} while (t);
7890 
7891 	return -EINVAL;
7892 }
7893 
7894 /* Check that two BTF types, each specified as an BTF object + id, are exactly
7895  * the same. Trivial ID check is not enough due to module BTFs, because we can
7896  * end up with two different module BTFs, but IDs point to the common type in
7897  * vmlinux BTF.
7898  */
7899 bool btf_types_are_same(const struct btf *btf1, u32 id1,
7900 			const struct btf *btf2, u32 id2)
7901 {
7902 	if (id1 != id2)
7903 		return false;
7904 	if (btf1 == btf2)
7905 		return true;
7906 	return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
7907 }
7908 
7909 bool btf_struct_ids_match(struct bpf_verifier_log *log,
7910 			  const struct btf *btf, u32 id, int off,
7911 			  const struct btf *need_btf, u32 need_type_id,
7912 			  bool strict, bool walk_flex_arrays)
7913 {
7914 	const struct btf_type *type;
7915 	enum bpf_type_flag flag = 0;
7916 	int err;
7917 
7918 	/* Are we already done? */
7919 	if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
7920 		return true;
7921 	/* In case of strict type match, we do not walk struct, the top level
7922 	 * type match must succeed. When strict is true, off should have already
7923 	 * been 0.
7924 	 */
7925 	if (strict)
7926 		return false;
7927 again:
7928 	type = btf_type_by_id(btf, id);
7929 	if (!type)
7930 		return false;
7931 	err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL,
7932 			      walk_flex_arrays);
7933 	if (err != WALK_STRUCT)
7934 		return false;
7935 
7936 	/* We found nested struct object. If it matches
7937 	 * the requested ID, we're done. Otherwise let's
7938 	 * continue the search with offset 0 in the new
7939 	 * type.
7940 	 */
7941 	if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
7942 		off = 0;
7943 		goto again;
7944 	}
7945 
7946 	return true;
7947 }
7948 
7949 static int __get_type_size(struct btf *btf, u32 btf_id,
7950 			   const struct btf_type **ret_type)
7951 {
7952 	const struct btf_type *t;
7953 
7954 	*ret_type = btf_type_by_id(btf, 0);
7955 	if (!btf_id)
7956 		/* void */
7957 		return 0;
7958 	t = btf_type_by_id(btf, btf_id);
7959 	while (t && btf_type_is_modifier(t))
7960 		t = btf_type_by_id(btf, t->type);
7961 	if (!t)
7962 		return -EINVAL;
7963 	*ret_type = t;
7964 	if (btf_type_is_ptr(t))
7965 		/* kernel size of pointer. Not BPF's size of pointer*/
7966 		return sizeof(void *);
7967 	if (btf_type_is_int(t) || btf_is_any_enum(t) || btf_type_is_struct(t))
7968 		return t->size;
7969 	return -EINVAL;
7970 }
7971 
7972 static u8 __get_type_fmodel_flags(const struct btf_type *t)
7973 {
7974 	u8 flags = 0;
7975 
7976 	if (btf_type_is_signed_int(t))
7977 		flags |= BTF_FMODEL_SIGNED_ARG;
7978 
7979 	return flags;
7980 }
7981 
7982 static u8 __get_arg_fmodel_flags(const struct btf *btf,
7983 				 const struct btf_param *arg,
7984 				 const struct btf_type *t)
7985 {
7986 	u8 flags = __get_type_fmodel_flags(t);
7987 
7988 	if (btf_func_arg_align(btf, t) > sizeof(u64))
7989 		flags |= BTF_FMODEL_ALIGN16_ARG;
7990 
7991 	if (btf_param_match_suffix(btf, arg, "__arena__nullable"))
7992 		flags |= BTF_FMODEL_ARENA_ARG | BTF_FMODEL_NULLABLE_ARG;
7993 	else if (btf_param_match_suffix(btf, arg, "__arena"))
7994 		flags |= BTF_FMODEL_ARENA_ARG;
7995 	else if (btf_param_match_suffix(btf, arg, "__nullable"))
7996 		flags |= BTF_FMODEL_NULLABLE_ARG;
7997 
7998 	return flags;
7999 }
8000 
8001 int btf_distill_func_proto(struct bpf_verifier_log *log,
8002 			   struct btf *btf,
8003 			   const struct btf_type *func,
8004 			   const char *tname,
8005 			   struct btf_func_model *m)
8006 {
8007 	const struct btf_param *args;
8008 	const struct btf_type *t;
8009 	u32 i, nargs;
8010 	int ret;
8011 
8012 	if (!func) {
8013 		/* BTF function prototype doesn't match the verifier types.
8014 		 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
8015 		 */
8016 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
8017 			m->arg_size[i] = 8;
8018 			m->arg_flags[i] = 0;
8019 		}
8020 		m->ret_size = 8;
8021 		m->ret_flags = 0;
8022 		m->nr_args = MAX_BPF_FUNC_REG_ARGS;
8023 		return 0;
8024 	}
8025 	args = (const struct btf_param *)(func + 1);
8026 	nargs = btf_type_vlen(func);
8027 	if (nargs > MAX_BPF_FUNC_ARGS) {
8028 		bpf_log(log,
8029 			"The function %s has %d arguments. Too many.\n",
8030 			tname, nargs);
8031 		return -EINVAL;
8032 	}
8033 	ret = __get_type_size(btf, func->type, &t);
8034 	if (ret < 0 || ret > 16) {
8035 		bpf_log(log,
8036 			"The function %s return type %s is unsupported.\n",
8037 			tname, btf_type_str(t));
8038 		return -EINVAL;
8039 	}
8040 	m->ret_size = ret;
8041 	m->ret_flags = __get_type_fmodel_flags(t);
8042 
8043 	for (i = 0; i < nargs; i++) {
8044 		if (i == nargs - 1 && args[i].type == 0) {
8045 			bpf_log(log,
8046 				"The function %s with variable args is unsupported.\n",
8047 				tname);
8048 			return -EINVAL;
8049 		}
8050 		ret = __get_type_size(btf, args[i].type, &t);
8051 
8052 		/* No support of struct argument size greater than 16 bytes */
8053 		if (ret < 0 || ret > 16) {
8054 			bpf_log(log,
8055 				"The function %s arg%d type %s is unsupported.\n",
8056 				tname, i, btf_type_str(t));
8057 			return -EINVAL;
8058 		}
8059 		if (ret == 0) {
8060 			bpf_log(log,
8061 				"The function %s has malformed void argument.\n",
8062 				tname);
8063 			return -EINVAL;
8064 		}
8065 		m->arg_size[i] = ret;
8066 		m->arg_flags[i] = __get_arg_fmodel_flags(btf, &args[i], t);
8067 	}
8068 	m->nr_args = nargs;
8069 	return 0;
8070 }
8071 
8072 /* Compare BTFs of two functions assuming only scalars and pointers to context.
8073  * t1 points to BTF_KIND_FUNC in btf1
8074  * t2 points to BTF_KIND_FUNC in btf2
8075  * Returns:
8076  * EINVAL - function prototype mismatch
8077  * EFAULT - verifier bug
8078  * 0 - 99% match. The last 1% is validated by the verifier.
8079  */
8080 static int btf_check_func_type_match(struct bpf_verifier_log *log,
8081 				     struct btf *btf1, const struct btf_type *t1,
8082 				     struct btf *btf2, const struct btf_type *t2)
8083 {
8084 	const struct btf_param *args1, *args2;
8085 	const char *fn1, *fn2, *s1, *s2;
8086 	u32 nargs1, nargs2, i;
8087 
8088 	fn1 = btf_name_by_offset(btf1, t1->name_off);
8089 	fn2 = btf_name_by_offset(btf2, t2->name_off);
8090 
8091 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
8092 		bpf_log(log, "%s() is not a global function\n", fn1);
8093 		return -EINVAL;
8094 	}
8095 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
8096 		bpf_log(log, "%s() is not a global function\n", fn2);
8097 		return -EINVAL;
8098 	}
8099 
8100 	t1 = btf_type_by_id(btf1, t1->type);
8101 	if (!t1 || !btf_type_is_func_proto(t1))
8102 		return -EFAULT;
8103 	t2 = btf_type_by_id(btf2, t2->type);
8104 	if (!t2 || !btf_type_is_func_proto(t2))
8105 		return -EFAULT;
8106 
8107 	args1 = (const struct btf_param *)(t1 + 1);
8108 	nargs1 = btf_type_vlen(t1);
8109 	args2 = (const struct btf_param *)(t2 + 1);
8110 	nargs2 = btf_type_vlen(t2);
8111 
8112 	if (nargs1 != nargs2) {
8113 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
8114 			fn1, nargs1, fn2, nargs2);
8115 		return -EINVAL;
8116 	}
8117 
8118 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
8119 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
8120 	if (t1->info != t2->info) {
8121 		bpf_log(log,
8122 			"Return type %s of %s() doesn't match type %s of %s()\n",
8123 			btf_type_str(t1), fn1,
8124 			btf_type_str(t2), fn2);
8125 		return -EINVAL;
8126 	}
8127 	if (btf_type_has_size(t1) && (t1->size > 8 || t2->size > 8)) {
8128 		bpf_log(log,
8129 			"Return type of %s() has size %u and of %s() size %u, and a size above 8 bytes cannot be replaced\n",
8130 			fn1, t1->size, fn2, t2->size);
8131 		return -EINVAL;
8132 	}
8133 
8134 	for (i = 0; i < nargs1; i++) {
8135 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
8136 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
8137 
8138 		if (t1->info != t2->info) {
8139 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
8140 				i, fn1, btf_type_str(t1),
8141 				fn2, btf_type_str(t2));
8142 			return -EINVAL;
8143 		}
8144 		if (btf_type_has_size(t1) && t1->size != t2->size) {
8145 			bpf_log(log,
8146 				"arg%d in %s() has size %d while %s() has %d\n",
8147 				i, fn1, t1->size,
8148 				fn2, t2->size);
8149 			return -EINVAL;
8150 		}
8151 
8152 		/* global functions are validated with scalars and pointers
8153 		 * to context only. And only global functions can be replaced.
8154 		 * Hence type check only those types.
8155 		 */
8156 		if (btf_type_is_int(t1) || btf_is_any_enum(t1))
8157 			continue;
8158 		if (!btf_type_is_ptr(t1)) {
8159 			bpf_log(log,
8160 				"arg%d in %s() has unrecognized type\n",
8161 				i, fn1);
8162 			return -EINVAL;
8163 		}
8164 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
8165 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
8166 		if (!btf_type_is_struct(t1)) {
8167 			bpf_log(log,
8168 				"arg%d in %s() is not a pointer to context\n",
8169 				i, fn1);
8170 			return -EINVAL;
8171 		}
8172 		if (!btf_type_is_struct(t2)) {
8173 			bpf_log(log,
8174 				"arg%d in %s() is not a pointer to context\n",
8175 				i, fn2);
8176 			return -EINVAL;
8177 		}
8178 		/* This is an optional check to make program writing easier.
8179 		 * Compare names of structs and report an error to the user.
8180 		 * btf_prepare_func_args() already checked that t2 struct
8181 		 * is a context type. btf_prepare_func_args() will check
8182 		 * later that t1 struct is a context type as well.
8183 		 */
8184 		s1 = btf_name_by_offset(btf1, t1->name_off);
8185 		s2 = btf_name_by_offset(btf2, t2->name_off);
8186 		if (strcmp(s1, s2)) {
8187 			bpf_log(log,
8188 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
8189 				i, fn1, s1, fn2, s2);
8190 			return -EINVAL;
8191 		}
8192 	}
8193 	return 0;
8194 }
8195 
8196 /* Compare BTFs of given program with BTF of target program */
8197 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
8198 			 struct btf *btf2, const struct btf_type *t2)
8199 {
8200 	struct btf *btf1 = prog->aux->btf;
8201 	const struct btf_type *t1;
8202 	u32 btf_id = 0;
8203 
8204 	if (!prog->aux->func_info) {
8205 		bpf_log(log, "Program extension requires BTF\n");
8206 		return -EINVAL;
8207 	}
8208 
8209 	btf_id = prog->aux->func_info[0].type_id;
8210 	if (!btf_id)
8211 		return -EFAULT;
8212 
8213 	t1 = btf_type_by_id(btf1, btf_id);
8214 	if (!t1 || !btf_type_is_func(t1))
8215 		return -EFAULT;
8216 
8217 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
8218 }
8219 
8220 static bool btf_is_dynptr_ptr(const struct btf *btf, const struct btf_type *t)
8221 {
8222 	const char *name;
8223 
8224 	t = btf_type_by_id(btf, t->type); /* skip PTR */
8225 
8226 	while (btf_type_is_modifier(t))
8227 		t = btf_type_by_id(btf, t->type);
8228 
8229 	/* allow either struct or struct forward declaration */
8230 	if (btf_type_is_struct(t) ||
8231 	    (btf_type_is_fwd(t) && btf_type_kflag(t) == 0)) {
8232 		name = btf_str_by_offset(btf, t->name_off);
8233 		return name && strcmp(name, "bpf_dynptr") == 0;
8234 	}
8235 
8236 	return false;
8237 }
8238 
8239 struct bpf_cand_cache {
8240 	const char *name;
8241 	u32 name_len;
8242 	u16 kind;
8243 	u16 cnt;
8244 	struct {
8245 		const struct btf *btf;
8246 		u32 id;
8247 	} cands[];
8248 };
8249 
8250 static DEFINE_MUTEX(cand_cache_mutex);
8251 
8252 static struct bpf_cand_cache *
8253 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id);
8254 
8255 static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
8256 				 const struct btf *btf, const struct btf_type *t)
8257 {
8258 	struct bpf_cand_cache *cc;
8259 	struct bpf_core_ctx ctx = {
8260 		.btf = btf,
8261 		.log = log,
8262 	};
8263 	u32 kern_type_id, type_id;
8264 	int err = 0;
8265 
8266 	/* skip PTR and modifiers */
8267 	type_id = t->type;
8268 	t = btf_type_by_id(btf, t->type);
8269 	while (btf_type_is_modifier(t)) {
8270 		type_id = t->type;
8271 		t = btf_type_by_id(btf, t->type);
8272 	}
8273 
8274 	mutex_lock(&cand_cache_mutex);
8275 	cc = bpf_core_find_cands(&ctx, type_id);
8276 	if (IS_ERR(cc)) {
8277 		err = PTR_ERR(cc);
8278 		bpf_log(log, "arg#%d reference type('%s %s') candidate matching error: %d\n",
8279 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
8280 			err);
8281 		goto cand_cache_unlock;
8282 	}
8283 	if (cc->cnt != 1) {
8284 		bpf_log(log, "arg#%d reference type('%s %s') %s\n",
8285 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
8286 			cc->cnt == 0 ? "has no matches" : "is ambiguous");
8287 		err = cc->cnt == 0 ? -ENOENT : -ESRCH;
8288 		goto cand_cache_unlock;
8289 	}
8290 	if (btf_is_module(cc->cands[0].btf)) {
8291 		bpf_log(log, "arg#%d reference type('%s %s') points to kernel module type (unsupported)\n",
8292 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
8293 		err = -EOPNOTSUPP;
8294 		goto cand_cache_unlock;
8295 	}
8296 	kern_type_id = cc->cands[0].id;
8297 
8298 cand_cache_unlock:
8299 	mutex_unlock(&cand_cache_mutex);
8300 	if (err)
8301 		return err;
8302 
8303 	return kern_type_id;
8304 }
8305 
8306 enum btf_arg_tag {
8307 	ARG_TAG_CTX	  = BIT_ULL(0),
8308 	ARG_TAG_NONNULL   = BIT_ULL(1),
8309 	ARG_TAG_TRUSTED   = BIT_ULL(2),
8310 	ARG_TAG_UNTRUSTED = BIT_ULL(3),
8311 	ARG_TAG_NULLABLE  = BIT_ULL(4),
8312 	ARG_TAG_ARENA	  = BIT_ULL(5),
8313 };
8314 
8315 static int btf_scan_decl_tags(struct bpf_verifier_env *env,
8316 			      const struct btf *btf,
8317 			      const struct btf_type *fn_t,
8318 			      u32 arg_idx, bool is_global, u32 *tags)
8319 {
8320 	int id = btf_named_start_id(btf, false) - 1;
8321 	const char tag_key[] = "arg:";
8322 	static const struct {
8323 		const char *tag_value;
8324 		enum btf_arg_tag arg_tag;
8325 	} tag_values[] = {
8326 		{ "ctx", ARG_TAG_CTX },
8327 		{ "trusted", ARG_TAG_TRUSTED },
8328 		{ "untrusted", ARG_TAG_UNTRUSTED },
8329 		{ "nonnull", ARG_TAG_NONNULL },
8330 		{ "nullable", ARG_TAG_NULLABLE },
8331 		{ "arena", ARG_TAG_ARENA },
8332 	};
8333 
8334 	/*
8335 	 * The 'arg:<tag>' decl_tag takes precedence over the derivation
8336 	 * of the register type from the BTF type itself.
8337 	 */
8338 	while ((id = btf_find_next_decl_tag(btf, fn_t, arg_idx, tag_key, id)) > 0) {
8339 		const struct btf_type *tag_t;
8340 		const char *tag;
8341 		int i;
8342 		bool found;
8343 
8344 		/* disallow arg tags in static subprogs */
8345 		if (!is_global) {
8346 			bpf_log(&env->log,
8347 				"arg#%d type tag is not supported in static functions\n",
8348 				arg_idx);
8349 			return -EOPNOTSUPP;
8350 		}
8351 
8352 		tag_t = btf_type_by_id(btf, id);
8353 		tag = __btf_name_by_offset(btf, tag_t->name_off) + (sizeof(tag_key) - 1);
8354 
8355 		found = false;
8356 		for (i = 0; i < ARRAY_SIZE(tag_values); ++i) {
8357 			if (!strcmp(tag, tag_values[i].tag_value)) {
8358 				*tags |= tag_values[i].arg_tag;
8359 				found = true;
8360 				break;
8361 			}
8362 		}
8363 
8364 		if (!found) {
8365 			bpf_log(&env->log, "arg#%d has unsupported set of tags\n", arg_idx);
8366 			return -EOPNOTSUPP;
8367 		}
8368 	}
8369 	if (id != -ENOENT) {
8370 		bpf_log(&env->log, "arg#%d type tag fetching failure: %d\n", arg_idx, id);
8371 		return id;
8372 	}
8373 
8374 	return 0;
8375 }
8376 
8377 static void btf_scan_type_tags(const struct btf *btf, u32 type_id, u32 *tags)
8378 {
8379 	/* Find the first pointer type in the chain. */
8380 	const struct btf_type *t = btf_type_skip_modifiers(btf, type_id, NULL);
8381 
8382 	if (btf_type_is_arena_ptr(btf, t))
8383 		*tags |= ARG_TAG_ARENA;
8384 }
8385 
8386 /* Check whether the type is a valid return type. */
8387 static int btf_validate_return_type(struct bpf_verifier_env *env, struct btf *btf,
8388 		const struct btf_type *t, int subprog, bool is_global)
8389 {
8390 	t = btf_type_skip_modifiers(btf, t->type, NULL);
8391 
8392 	/*
8393 	 * We allow all subprogs except for the main one to return any kind of arena pointer.
8394 	 * General arena variables are not allowed, since it makes no sense to return by value
8395 	 * a variable that's on the heap in the first place.
8396 	 */
8397 	if (subprog && btf_type_is_arena_ptr(btf, t))
8398 		return 0;
8399 
8400 	/* We always accept void or scalars. */
8401 	if (btf_type_is_void(t) || btf_type_is_int(t) || btf_is_any_enum(t))
8402 		return 0;
8403 
8404 	if (btf_type_is_struct(t) && t->size <= 16) {
8405 		/*
8406 		 * A global function's caller models the return as an opaque
8407 		 * scalar pair, so a pointer member would be laundered into a
8408 		 * scalar and escape provenance and reference tracking. Only
8409 		 * scalars and arena pointers are allowed: an arena pointer has
8410 		 * no provenance to lose, since a program may already derive one
8411 		 * from any scalar with addr_space_cast(), which confines the
8412 		 * result to the arena. The main program is the exception: it
8413 		 * returns to the kernel, which has no arena to cast the address
8414 		 * back into. A local function is verified inline, so its caller
8415 		 * receives the real register state and any member is fine.
8416 		 */
8417 		bool local_func = subprog && !is_global;
8418 		u32 member_kinds = BTF_MEMBER_SCALAR;
8419 
8420 		if (subprog)
8421 			member_kinds |= BTF_MEMBER_ARENA_PTR;
8422 
8423 		if (local_func || btf_struct_is_composed_of(env, btf, t, member_kinds))
8424 			return 0;
8425 	}
8426 
8427 	return -EOPNOTSUPP;
8428 }
8429 
8430 static int btf_check_arg_slots(struct bpf_verifier_log *log, const char *tname,
8431 			       bool is_global, u32 slot_cnt,
8432 			       struct bpf_subprog_info *sub)
8433 {
8434 	if (slot_cnt <= MAX_BPF_FUNC_REG_ARGS)
8435 		return 0;
8436 
8437 	if (is_global) {
8438 		bpf_log(log,
8439 			"global function %s() needs %d > %d argument slots, "
8440 			"stack args not supported\n",
8441 			tname, slot_cnt, MAX_BPF_FUNC_REG_ARGS);
8442 		return -EINVAL;
8443 	}
8444 	if (!bpf_jit_supports_stack_args()) {
8445 		bpf_log(log, "JIT does not support function %s() with %d argument slots\n",
8446 			tname, slot_cnt);
8447 		return -EFAULT;
8448 	}
8449 	sub->stack_arg_cnt = slot_cnt - MAX_BPF_FUNC_REG_ARGS;
8450 	return 0;
8451 }
8452 
8453 /* Process BTF of a function to produce high-level expectation of function
8454  * arguments (like ARG_PTR_TO_CTX, or ARG_PTR_TO_MEM, etc). This information
8455  * is cached in subprog info for reuse.
8456  * Returns:
8457  * EFAULT - there is a verifier bug. Abort verification.
8458  * EINVAL - cannot convert BTF.
8459  * 0 - Successfully processed BTF and constructed argument expectations.
8460  */
8461 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
8462 {
8463 	bool is_global = subprog_aux(env, subprog)->linkage == BTF_FUNC_GLOBAL;
8464 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
8465 	struct bpf_verifier_log *log = &env->log;
8466 	struct bpf_prog *prog = env->prog;
8467 	enum bpf_prog_type prog_type = prog->type;
8468 	struct btf *btf = prog->aux->btf;
8469 	const struct btf_param *args;
8470 	const struct btf_type *t, *ref_t, *fn_t;
8471 	int err;
8472 	u32 i, slots_used, nargs, btf_id;
8473 	const char *tname;
8474 
8475 	if (sub->args_cached)
8476 		return 0;
8477 
8478 	if (!prog->aux->func_info) {
8479 		verifier_bug(env, "func_info undefined");
8480 		return -EFAULT;
8481 	}
8482 
8483 	btf_id = prog->aux->func_info[subprog].type_id;
8484 	if (!btf_id) {
8485 		if (!is_global) /* not fatal for static funcs */
8486 			return -EINVAL;
8487 		bpf_log(log, "Global functions need valid BTF\n");
8488 		return -EFAULT;
8489 	}
8490 
8491 	fn_t = btf_type_by_id(btf, btf_id);
8492 	if (!fn_t || !btf_type_is_func(fn_t)) {
8493 		/* These checks were already done by the verifier while loading
8494 		 * struct bpf_func_info
8495 		 */
8496 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
8497 			subprog);
8498 		return -EFAULT;
8499 	}
8500 	tname = btf_name_by_offset(btf, fn_t->name_off);
8501 
8502 	if (prog->aux->func_info_aux[subprog].unreliable) {
8503 		verifier_bug(env, "unreliable BTF for function %s()", tname);
8504 		return -EFAULT;
8505 	}
8506 	if (prog_type == BPF_PROG_TYPE_EXT)
8507 		prog_type = prog->aux->dst_prog->type;
8508 
8509 	t = btf_type_by_id(btf, fn_t->type);
8510 	if (!t || !btf_type_is_func_proto(t)) {
8511 		bpf_log(log, "Invalid type of function %s()\n", tname);
8512 		return -EFAULT;
8513 	}
8514 	args = (const struct btf_param *)(t + 1);
8515 	nargs = btf_type_vlen(t);
8516 	sub->arg_slot_cnt = nargs;
8517 	if (nargs > MAX_BPF_FUNC_ARGS) {
8518 		bpf_log(log, "kernel supports at most %d parameters, function %s has %d\n",
8519 			MAX_BPF_FUNC_ARGS, tname, nargs);
8520 		return -EFAULT;
8521 	}
8522 	err = btf_check_arg_slots(log, tname, is_global, nargs, sub);
8523 	if (err)
8524 		return err;
8525 
8526 	err = btf_validate_return_type(env, btf, t, subprog, is_global);
8527 	if (err) {
8528 		if (is_global) {
8529 			/* Only a subprogram may return arena pointers. */
8530 			const char *supported = subprog ?
8531 				"void, scalar, arena pointer, or a struct/union of "
8532 				"scalars and arena pointers" :
8533 				"void, scalar, or a scalar-only struct/union";
8534 
8535 			bpf_log(log,
8536 				"Global function %s() has unsupported return type. "
8537 				"Only %s up to 16 bytes is supported.\n",
8538 				tname, supported);
8539 		}
8540 		return err;
8541 	}
8542 
8543 	/* Convert BTF function arguments into verifier types.
8544 	 * Only PTR_TO_CTX and SCALAR are supported atm.
8545 	 */
8546 	for (i = 0, slots_used = 0; i < nargs; i++) {
8547 		u32 tags = 0;
8548 
8549 		if (slots_used >= MAX_BPF_FUNC_ARGS)
8550 			goto too_many_slots;
8551 
8552 		err = btf_scan_decl_tags(env, btf, fn_t, i, is_global, &tags);
8553 		if (err)
8554 			return err;
8555 
8556 		btf_scan_type_tags(btf, args[i].type, &tags);
8557 
8558 		t = btf_type_by_id(btf, args[i].type);
8559 		while (btf_type_is_modifier(t))
8560 			t = btf_type_by_id(btf, t->type);
8561 		if (!btf_type_is_ptr(t))
8562 			goto skip_pointer;
8563 
8564 		if ((tags & ARG_TAG_CTX) || btf_is_prog_ctx_type(log, btf, t, prog_type, i)) {
8565 			if (tags & ~ARG_TAG_CTX) {
8566 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
8567 				return -EINVAL;
8568 			}
8569 			if ((tags & ARG_TAG_CTX) &&
8570 			    btf_validate_prog_ctx_type(log, btf, t, i, prog_type,
8571 						       prog->expected_attach_type))
8572 				return -EINVAL;
8573 			sub->args[slots_used++].arg_type = ARG_PTR_TO_CTX;
8574 			continue;
8575 		}
8576 		if (btf_is_dynptr_ptr(btf, t)) {
8577 			if (tags) {
8578 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
8579 				return -EINVAL;
8580 			}
8581 			sub->args[slots_used++].arg_type = ARG_PTR_TO_DYNPTR;
8582 			continue;
8583 		}
8584 		if (tags & ARG_TAG_TRUSTED) {
8585 			int kern_type_id;
8586 
8587 			if (tags & ARG_TAG_NONNULL) {
8588 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
8589 				return -EINVAL;
8590 			}
8591 
8592 			kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
8593 			if (kern_type_id < 0)
8594 				return kern_type_id;
8595 
8596 			sub->args[slots_used].arg_type = ARG_PTR_TO_BTF_ID | PTR_TRUSTED;
8597 			if (tags & ARG_TAG_NULLABLE)
8598 				sub->args[slots_used].arg_type |= PTR_MAYBE_NULL;
8599 			sub->args[slots_used].btf_id = kern_type_id;
8600 			slots_used++;
8601 			continue;
8602 		}
8603 		if (tags & ARG_TAG_UNTRUSTED) {
8604 			struct btf *vmlinux_btf;
8605 			int kern_type_id;
8606 
8607 			if (tags & ~ARG_TAG_UNTRUSTED) {
8608 				bpf_log(log, "arg#%d untrusted cannot be combined with any other tags\n", i);
8609 				return -EINVAL;
8610 			}
8611 
8612 			ref_t = btf_type_skip_modifiers(btf, t->type, NULL);
8613 			if (btf_type_is_void(ref_t) || btf_type_is_primitive(ref_t)) {
8614 				sub->args[slots_used].arg_type = ARG_PTR_TO_MEM | MEM_RDONLY |
8615 								 PTR_UNTRUSTED;
8616 				sub->args[slots_used].mem_size = 0;
8617 				slots_used++;
8618 				continue;
8619 			}
8620 
8621 			kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
8622 			if (kern_type_id < 0)
8623 				return kern_type_id;
8624 
8625 			vmlinux_btf = bpf_get_btf_vmlinux();
8626 			ref_t = btf_type_by_id(vmlinux_btf, kern_type_id);
8627 			if (!btf_type_is_struct(ref_t)) {
8628 				tname = __btf_name_by_offset(vmlinux_btf, t->name_off);
8629 				bpf_log(log, "arg#%d has type %s '%s', but only struct or primitive types are allowed\n",
8630 					i, btf_type_str(ref_t), tname);
8631 				return -EINVAL;
8632 			}
8633 			sub->args[slots_used].arg_type = ARG_PTR_TO_BTF_ID | PTR_UNTRUSTED;
8634 			sub->args[slots_used].btf_id = kern_type_id;
8635 			slots_used++;
8636 			continue;
8637 		}
8638 		if (tags & ARG_TAG_ARENA) {
8639 			if (tags & ~ARG_TAG_ARENA) {
8640 				bpf_log(log, "arg#%d arena cannot be combined with any other tags\n", i);
8641 				return -EINVAL;
8642 			}
8643 			sub->args[slots_used++].arg_type = ARG_PTR_TO_ARENA;
8644 			continue;
8645 		}
8646 		if (is_global) { /* generic user data pointer */
8647 			u32 mem_size;
8648 
8649 			if (tags & ARG_TAG_NULLABLE) {
8650 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
8651 				return -EINVAL;
8652 			}
8653 
8654 			t = btf_type_skip_modifiers(btf, t->type, NULL);
8655 			ref_t = btf_resolve_size(btf, t, &mem_size);
8656 			if (IS_ERR(ref_t)) {
8657 				bpf_log(log, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
8658 					i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
8659 					PTR_ERR(ref_t));
8660 				return -EINVAL;
8661 			}
8662 
8663 			sub->args[slots_used].arg_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL;
8664 			if (tags & ARG_TAG_NONNULL)
8665 				sub->args[slots_used].arg_type &= ~PTR_MAYBE_NULL;
8666 			sub->args[slots_used].mem_size = mem_size;
8667 			slots_used++;
8668 			continue;
8669 		}
8670 
8671 skip_pointer:
8672 		if (tags) {
8673 			bpf_log(log, "arg#%d has pointer tag, but is not a pointer type\n", i);
8674 			return -EINVAL;
8675 		}
8676 		if (btf_type_is_int(t) || btf_is_any_enum(t) || btf_type_is_struct(t)) {
8677 			u32 nslots;
8678 
8679 			if (!t->size || t->size > 2 * BPF_REG_SIZE) {
8680 				if (!is_global)
8681 					return -EINVAL;
8682 				bpf_log(log,
8683 					"Arg#%d type %s in %s() has size %u, only 1 to %d bytes "
8684 					"can be passed by value\n",
8685 					i, btf_type_str(t), tname, t->size, 2 * BPF_REG_SIZE);
8686 				return -EINVAL;
8687 			}
8688 			if (btf_type_is_struct(t) &&
8689 			    !btf_struct_is_composed_of(env, btf, t, BTF_MEMBER_SCALAR)) {
8690 				if (!is_global)
8691 					return -EINVAL;
8692 				bpf_log(log, "Arg#%d type %s in %s() is not composed of scalars\n",
8693 					i, btf_type_str(t), tname);
8694 				return -EINVAL;
8695 			}
8696 
8697 			nslots = (t->size + BPF_REG_SIZE - 1) / BPF_REG_SIZE;
8698 			if (slots_used + nslots > MAX_BPF_FUNC_ARGS)
8699 				goto too_many_slots;
8700 			while (nslots--)
8701 				sub->args[slots_used++].arg_type = ARG_SCALAR;
8702 			continue;
8703 		}
8704 		if (!is_global)
8705 			return -EINVAL;
8706 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
8707 			i, btf_type_str(t), tname);
8708 		return -EINVAL;
8709 	}
8710 
8711 	err = btf_check_arg_slots(log, tname, is_global, slots_used, sub);
8712 	if (err)
8713 		return err;
8714 	sub->arg_slot_cnt = slots_used;
8715 
8716 	sub->args_cached = true;
8717 
8718 	return 0;
8719 
8720 too_many_slots:
8721 	if (!is_global)
8722 		return -EINVAL;
8723 	bpf_log(log, "Arguments of %s() need more than %d argument slots\n",
8724 		tname, MAX_BPF_FUNC_ARGS);
8725 	return -EINVAL;
8726 }
8727 
8728 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
8729 			  struct btf_show *show)
8730 {
8731 	const struct btf_type *t = btf_type_by_id(btf, type_id);
8732 
8733 	show->btf = btf;
8734 	memset(&show->state, 0, sizeof(show->state));
8735 	memset(&show->obj, 0, sizeof(show->obj));
8736 
8737 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
8738 }
8739 
8740 __printf(2, 0) static void btf_seq_show(struct btf_show *show, const char *fmt,
8741 					va_list args)
8742 {
8743 	seq_vprintf((struct seq_file *)show->target, fmt, args);
8744 }
8745 
8746 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
8747 			    void *obj, struct seq_file *m, u64 flags)
8748 {
8749 	struct btf_show sseq;
8750 
8751 	sseq.target = m;
8752 	sseq.showfn = btf_seq_show;
8753 	sseq.flags = flags;
8754 
8755 	btf_type_show(btf, type_id, obj, &sseq);
8756 
8757 	return sseq.state.status;
8758 }
8759 
8760 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
8761 		       struct seq_file *m)
8762 {
8763 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
8764 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
8765 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
8766 }
8767 
8768 struct btf_show_snprintf {
8769 	struct btf_show show;
8770 	int len_left;		/* space left in string */
8771 	int len;		/* length we would have written */
8772 };
8773 
8774 __printf(2, 0) static void btf_snprintf_show(struct btf_show *show, const char *fmt,
8775 					     va_list args)
8776 {
8777 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
8778 	int len;
8779 
8780 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
8781 
8782 	if (len < 0) {
8783 		ssnprintf->len_left = 0;
8784 		ssnprintf->len = len;
8785 	} else if (len >= ssnprintf->len_left) {
8786 		/* no space, drive on to get length we would have written */
8787 		ssnprintf->len_left = 0;
8788 		ssnprintf->len += len;
8789 	} else {
8790 		ssnprintf->len_left -= len;
8791 		ssnprintf->len += len;
8792 		show->target += len;
8793 	}
8794 }
8795 
8796 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
8797 			   char *buf, int len, u64 flags)
8798 {
8799 	struct btf_show_snprintf ssnprintf;
8800 
8801 	ssnprintf.show.target = buf;
8802 	ssnprintf.show.flags = flags;
8803 	ssnprintf.show.showfn = btf_snprintf_show;
8804 	ssnprintf.len_left = len;
8805 	ssnprintf.len = 0;
8806 
8807 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
8808 
8809 	/* If we encountered an error, return it. */
8810 	if (ssnprintf.show.state.status)
8811 		return ssnprintf.show.state.status;
8812 
8813 	/* Otherwise return length we would have written */
8814 	return ssnprintf.len;
8815 }
8816 
8817 int btf_type_name_to_buf(const struct btf *btf, u32 type_id, char *buf, int len)
8818 {
8819 	struct btf_show show = {
8820 		.btf = btf,
8821 		.state.type_id = type_id,
8822 	};
8823 
8824 	return snprintf(buf, len, "%s", btf_show_name(&show));
8825 }
8826 
8827 #ifdef CONFIG_PROC_FS
8828 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
8829 {
8830 	const struct btf *btf = filp->private_data;
8831 
8832 	seq_printf(m, "btf_id:\t%u\n", READ_ONCE(btf->id));
8833 }
8834 #endif
8835 
8836 static int btf_release(struct inode *inode, struct file *filp)
8837 {
8838 	btf_put(filp->private_data);
8839 	return 0;
8840 }
8841 
8842 const struct file_operations btf_fops = {
8843 #ifdef CONFIG_PROC_FS
8844 	.show_fdinfo	= bpf_btf_show_fdinfo,
8845 #endif
8846 	.release	= btf_release,
8847 };
8848 
8849 static int __btf_new_fd(struct btf *btf)
8850 {
8851 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
8852 }
8853 
8854 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, struct bpf_log_attr *attr_log)
8855 {
8856 	struct btf *btf;
8857 	int ret;
8858 
8859 	btf = btf_parse(attr, uattr, attr_log);
8860 	if (IS_ERR(btf))
8861 		return PTR_ERR(btf);
8862 
8863 	ret = btf_alloc_id(btf);
8864 	if (ret) {
8865 		btf_free(btf);
8866 		return ret;
8867 	}
8868 
8869 	/*
8870 	 * The BTF ID is published to the userspace.
8871 	 * All BTF free must go through call_rcu() from
8872 	 * now on (i.e. free by calling btf_put()).
8873 	 */
8874 
8875 	ret = __btf_new_fd(btf);
8876 	if (ret < 0)
8877 		btf_put(btf);
8878 
8879 	return ret;
8880 }
8881 
8882 struct btf *btf_get_by_fd(int fd)
8883 {
8884 	struct btf *btf;
8885 	CLASS(fd, f)(fd);
8886 
8887 	btf = __btf_get_by_fd(f);
8888 	if (!IS_ERR(btf))
8889 		refcount_inc(&btf->refcnt);
8890 
8891 	return btf;
8892 }
8893 
8894 int btf_get_info_by_fd(const struct btf *btf,
8895 		       const union bpf_attr *attr,
8896 		       union bpf_attr __user *uattr)
8897 {
8898 	struct bpf_btf_info __user *uinfo;
8899 	struct bpf_btf_info info;
8900 	u32 info_copy, btf_copy;
8901 	void __user *ubtf;
8902 	char __user *uname;
8903 	u32 uinfo_len, uname_len, name_len;
8904 	int ret = 0;
8905 
8906 	uinfo = u64_to_user_ptr(attr->info.info);
8907 	uinfo_len = attr->info.info_len;
8908 
8909 	info_copy = min_t(u32, uinfo_len, sizeof(info));
8910 	memset(&info, 0, sizeof(info));
8911 	if (copy_from_user(&info, uinfo, info_copy))
8912 		return -EFAULT;
8913 
8914 	info.id = READ_ONCE(btf->id);
8915 	ubtf = u64_to_user_ptr(info.btf);
8916 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
8917 	if (copy_to_user(ubtf, btf->data, btf_copy))
8918 		return -EFAULT;
8919 	info.btf_size = btf->data_size;
8920 
8921 	info.kernel_btf = btf->kernel_btf;
8922 
8923 	uname = u64_to_user_ptr(info.name);
8924 	uname_len = info.name_len;
8925 	if (!uname ^ !uname_len)
8926 		return -EINVAL;
8927 
8928 	name_len = strlen(btf->name);
8929 	info.name_len = name_len;
8930 
8931 	if (uname) {
8932 		if (uname_len >= name_len + 1) {
8933 			if (copy_to_user(uname, btf->name, name_len + 1))
8934 				return -EFAULT;
8935 		} else {
8936 			char zero = '\0';
8937 
8938 			if (copy_to_user(uname, btf->name, uname_len - 1))
8939 				return -EFAULT;
8940 			if (put_user(zero, uname + uname_len - 1))
8941 				return -EFAULT;
8942 			/* let user-space know about too short buffer */
8943 			ret = -ENOSPC;
8944 		}
8945 	}
8946 
8947 	if (copy_to_user(uinfo, &info, info_copy) ||
8948 	    put_user(info_copy, &uattr->info.info_len))
8949 		return -EFAULT;
8950 
8951 	return ret;
8952 }
8953 
8954 int btf_get_fd_by_id(u32 id)
8955 {
8956 	struct btf *btf;
8957 	int fd;
8958 
8959 	rcu_read_lock();
8960 	btf = idr_find(&btf_idr, id);
8961 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
8962 		btf = ERR_PTR(-ENOENT);
8963 	rcu_read_unlock();
8964 
8965 	if (IS_ERR(btf))
8966 		return PTR_ERR(btf);
8967 
8968 	fd = __btf_new_fd(btf);
8969 	if (fd < 0)
8970 		btf_put(btf);
8971 
8972 	return fd;
8973 }
8974 
8975 u32 btf_obj_id(const struct btf *btf)
8976 {
8977 	return READ_ONCE(btf->id);
8978 }
8979 
8980 bool btf_is_kernel(const struct btf *btf)
8981 {
8982 	return btf->kernel_btf;
8983 }
8984 
8985 bool btf_is_module(const struct btf *btf)
8986 {
8987 	return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
8988 }
8989 
8990 enum {
8991 	BTF_MODULE_F_LIVE = (1 << 0),
8992 };
8993 
8994 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8995 struct btf_module {
8996 	struct list_head list;
8997 	struct module *module;
8998 	struct btf *btf;
8999 	struct bin_attribute *sysfs_attr;
9000 	int flags;
9001 };
9002 
9003 static LIST_HEAD(btf_modules);
9004 static DEFINE_MUTEX(btf_module_mutex);
9005 
9006 static void purge_cand_cache(struct btf *btf);
9007 
9008 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
9009 			     void *module)
9010 {
9011 	struct btf_module *btf_mod, *tmp;
9012 	struct module *mod = module;
9013 	struct btf *btf;
9014 	int err = 0;
9015 
9016 	if (mod->btf_data_size == 0 ||
9017 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
9018 	     op != MODULE_STATE_GOING))
9019 		goto out;
9020 
9021 	switch (op) {
9022 	case MODULE_STATE_COMING:
9023 		btf_mod = kzalloc_obj(*btf_mod);
9024 		if (!btf_mod) {
9025 			err = -ENOMEM;
9026 			goto out;
9027 		}
9028 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size,
9029 				       mod->btf_base_data, mod->btf_base_data_size);
9030 		if (IS_ERR(btf)) {
9031 			kfree(btf_mod);
9032 			if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
9033 				pr_warn("failed to validate module [%s] BTF: %ld\n",
9034 					mod->name, PTR_ERR(btf));
9035 				err = PTR_ERR(btf);
9036 			} else {
9037 				pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
9038 			}
9039 			goto out;
9040 		}
9041 		err = btf_alloc_id(btf);
9042 		if (err) {
9043 			btf_free(btf);
9044 			kfree(btf_mod);
9045 			goto out;
9046 		}
9047 
9048 		purge_cand_cache(NULL);
9049 		mutex_lock(&btf_module_mutex);
9050 		btf_mod->module = module;
9051 		btf_mod->btf = btf;
9052 		list_add(&btf_mod->list, &btf_modules);
9053 		mutex_unlock(&btf_module_mutex);
9054 
9055 		if (IS_ENABLED(CONFIG_SYSFS)) {
9056 			struct bin_attribute *attr;
9057 
9058 			attr = kzalloc_obj(*attr);
9059 			if (!attr)
9060 				goto out;
9061 
9062 			sysfs_bin_attr_init(attr);
9063 			attr->attr.name = btf->name;
9064 			attr->attr.mode = 0444;
9065 			attr->size = btf->data_size;
9066 			attr->private = btf->data;
9067 			attr->read = sysfs_bin_attr_simple_read;
9068 
9069 			err = sysfs_create_bin_file(btf_kobj, attr);
9070 			if (err) {
9071 				pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
9072 					mod->name, err);
9073 				kfree(attr);
9074 				err = 0;
9075 				goto out;
9076 			}
9077 
9078 			btf_mod->sysfs_attr = attr;
9079 		}
9080 
9081 		break;
9082 	case MODULE_STATE_LIVE:
9083 		mutex_lock(&btf_module_mutex);
9084 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9085 			if (btf_mod->module != module)
9086 				continue;
9087 
9088 			btf_mod->flags |= BTF_MODULE_F_LIVE;
9089 			break;
9090 		}
9091 		mutex_unlock(&btf_module_mutex);
9092 		break;
9093 	case MODULE_STATE_GOING:
9094 		mutex_lock(&btf_module_mutex);
9095 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9096 			if (btf_mod->module != module)
9097 				continue;
9098 
9099 			/*
9100 			 * For modules, we do the freeing of BTF IDR as soon as
9101 			 * module goes away to disable BTF discovery, since the
9102 			 * btf_try_get_module() on such BTFs will fail. This may
9103 			 * be called again on btf_put(), but it's ok to do so.
9104 			 */
9105 			btf_free_id(btf_mod->btf);
9106 			list_del(&btf_mod->list);
9107 			if (btf_mod->sysfs_attr)
9108 				sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
9109 			purge_cand_cache(btf_mod->btf);
9110 			btf_put(btf_mod->btf);
9111 			kfree(btf_mod->sysfs_attr);
9112 			kfree(btf_mod);
9113 			break;
9114 		}
9115 		mutex_unlock(&btf_module_mutex);
9116 		break;
9117 	}
9118 out:
9119 	return notifier_from_errno(err);
9120 }
9121 
9122 static struct notifier_block btf_module_nb = {
9123 	.notifier_call = btf_module_notify,
9124 };
9125 
9126 static int __init btf_module_init(void)
9127 {
9128 	register_module_notifier(&btf_module_nb);
9129 	return 0;
9130 }
9131 
9132 fs_initcall(btf_module_init);
9133 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
9134 
9135 struct module *btf_try_get_module(const struct btf *btf)
9136 {
9137 	struct module *res = NULL;
9138 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9139 	struct btf_module *btf_mod, *tmp;
9140 
9141 	mutex_lock(&btf_module_mutex);
9142 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9143 		if (btf_mod->btf != btf)
9144 			continue;
9145 
9146 		/* We must only consider module whose __init routine has
9147 		 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
9148 		 * which is set from the notifier callback for
9149 		 * MODULE_STATE_LIVE.
9150 		 */
9151 		if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
9152 			res = btf_mod->module;
9153 
9154 		break;
9155 	}
9156 	mutex_unlock(&btf_module_mutex);
9157 #endif
9158 
9159 	return res;
9160 }
9161 
9162 /* Returns struct btf corresponding to the struct module.
9163  * This function can return NULL or ERR_PTR.
9164  */
9165 struct btf *btf_get_module_btf(const struct module *module)
9166 {
9167 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9168 	struct btf_module *btf_mod, *tmp;
9169 #endif
9170 	struct btf *btf = NULL;
9171 
9172 	if (!module) {
9173 		btf = bpf_get_btf_vmlinux();
9174 		if (!IS_ERR_OR_NULL(btf))
9175 			btf_get(btf);
9176 		return btf;
9177 	}
9178 
9179 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9180 	mutex_lock(&btf_module_mutex);
9181 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9182 		if (btf_mod->module != module)
9183 			continue;
9184 
9185 		btf_get(btf_mod->btf);
9186 		btf = btf_mod->btf;
9187 		break;
9188 	}
9189 	mutex_unlock(&btf_module_mutex);
9190 #endif
9191 
9192 	return btf;
9193 }
9194 
9195 static int check_btf_kconfigs(const struct module *module, const char *feature)
9196 {
9197 	if (!module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
9198 		pr_err("missing vmlinux BTF, cannot register %s\n", feature);
9199 		return -ENOENT;
9200 	}
9201 	if (module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
9202 		pr_warn("missing module BTF, cannot register %s\n", feature);
9203 	return 0;
9204 }
9205 
9206 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
9207 {
9208 	struct btf *btf = NULL;
9209 	int btf_obj_fd = 0;
9210 	long ret;
9211 
9212 	if (flags)
9213 		return -EINVAL;
9214 
9215 	if (name_sz <= 1 || name[name_sz - 1])
9216 		return -EINVAL;
9217 
9218 	ret = bpf_find_btf_id(name, kind, &btf);
9219 	if (ret > 0 && btf_is_module(btf)) {
9220 		btf_obj_fd = __btf_new_fd(btf);
9221 		if (btf_obj_fd < 0) {
9222 			btf_put(btf);
9223 			return btf_obj_fd;
9224 		}
9225 		return ret | (((u64)btf_obj_fd) << 32);
9226 	}
9227 	if (ret > 0)
9228 		btf_put(btf);
9229 	return ret;
9230 }
9231 
9232 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
9233 	.func		= bpf_btf_find_by_name_kind,
9234 	.gpl_only	= false,
9235 	.might_sleep	= true,
9236 	.ret_type	= RET_INTEGER,
9237 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
9238 	.arg2_type	= ARG_MEM_SIZE,
9239 	.arg3_type	= ARG_ANYTHING,
9240 	.arg4_type	= ARG_ANYTHING,
9241 };
9242 
9243 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
9244 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
9245 BTF_TRACING_TYPE_xxx
9246 #undef BTF_TRACING_TYPE
9247 
9248 /* Validate well-formedness of iter argument type.
9249  * On success, return positive BTF ID of iter state's STRUCT type.
9250  * On error, negative error is returned.
9251  */
9252 int btf_check_iter_arg(struct btf *btf, const struct btf_type *func, int arg_idx)
9253 {
9254 	const struct btf_param *arg;
9255 	const struct btf_type *t;
9256 	const char *name;
9257 	int btf_id;
9258 
9259 	if (btf_type_vlen(func) <= arg_idx)
9260 		return -EINVAL;
9261 
9262 	arg = &btf_params(func)[arg_idx];
9263 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
9264 	if (!t || !btf_type_is_ptr(t))
9265 		return -EINVAL;
9266 	t = btf_type_skip_modifiers(btf, t->type, &btf_id);
9267 	if (!t || !__btf_type_is_struct(t))
9268 		return -EINVAL;
9269 
9270 	name = btf_name_by_offset(btf, t->name_off);
9271 	if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
9272 		return -EINVAL;
9273 
9274 	return btf_id;
9275 }
9276 
9277 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
9278 				 const struct btf_type *func, u32 func_flags)
9279 {
9280 	u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
9281 	const char *sfx, *iter_name;
9282 	const struct btf_type *t;
9283 	char exp_name[128];
9284 	u32 nr_args;
9285 	int btf_id;
9286 
9287 	/* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
9288 	if (!flags || (flags & (flags - 1)))
9289 		return -EINVAL;
9290 
9291 	/* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
9292 	nr_args = btf_type_vlen(func);
9293 	if (nr_args < 1)
9294 		return -EINVAL;
9295 
9296 	btf_id = btf_check_iter_arg(btf, func, 0);
9297 	if (btf_id < 0)
9298 		return btf_id;
9299 
9300 	/* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
9301 	 * fit nicely in stack slots
9302 	 */
9303 	t = btf_type_by_id(btf, btf_id);
9304 	if (t->size == 0 || (t->size % 8))
9305 		return -EINVAL;
9306 
9307 	/* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
9308 	 * naming pattern
9309 	 */
9310 	iter_name = btf_name_by_offset(btf, t->name_off) + sizeof(ITER_PREFIX) - 1;
9311 	if (flags & KF_ITER_NEW)
9312 		sfx = "new";
9313 	else if (flags & KF_ITER_NEXT)
9314 		sfx = "next";
9315 	else /* (flags & KF_ITER_DESTROY) */
9316 		sfx = "destroy";
9317 
9318 	snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
9319 	if (strcmp(func_name, exp_name))
9320 		return -EINVAL;
9321 
9322 	/* only iter constructor should have extra arguments */
9323 	if (!(flags & KF_ITER_NEW) && nr_args != 1)
9324 		return -EINVAL;
9325 
9326 	if (flags & KF_ITER_NEXT) {
9327 		/* bpf_iter_<type>_next() should return pointer */
9328 		t = btf_type_skip_modifiers(btf, func->type, NULL);
9329 		if (!t || !btf_type_is_ptr(t))
9330 			return -EINVAL;
9331 	}
9332 
9333 	if (flags & KF_ITER_DESTROY) {
9334 		/* bpf_iter_<type>_destroy() should return void */
9335 		t = btf_type_by_id(btf, func->type);
9336 		if (!t || !btf_type_is_void(t))
9337 			return -EINVAL;
9338 	}
9339 
9340 	return 0;
9341 }
9342 
9343 static int btf_check_kfunc_name(struct btf *btf, const char *func_name, u32 kind)
9344 {
9345 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9346 	struct btf_module *btf_mod, *tmp;
9347 #endif
9348 	s32 id;
9349 
9350 	if (!btf_is_module(btf))
9351 		return 0;
9352 
9353 	id = btf_find_by_name_kind(bpf_get_btf_vmlinux(), func_name, kind);
9354 	if (id >= 0) {
9355 		pr_err("kfunc %s (id: %d) is already present in vmlinux.\n",
9356 		       func_name, id);
9357 		return -EINVAL;
9358 	}
9359 
9360 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
9361 	guard(mutex)(&btf_module_mutex);
9362 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
9363 		if (btf_mod->btf == btf)
9364 			continue;
9365 		id = btf_find_by_name_kind(btf_mod->btf, func_name, kind);
9366 		if (id >= 0) {
9367 			pr_err("kfunc %s (id: %d) is already present in module %s.\n",
9368 			       func_name, id, btf_mod->module->name);
9369 			return -EINVAL;
9370 		}
9371 	}
9372 #endif
9373 	return 0;
9374 }
9375 
9376 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
9377 {
9378 	const struct btf_type *func;
9379 	const char *func_name;
9380 	int err;
9381 
9382 	/* any kfunc should be FUNC -> FUNC_PROTO */
9383 	func = btf_type_by_id(btf, func_id);
9384 	if (!func || !btf_type_is_func(func))
9385 		return -EINVAL;
9386 
9387 	/* sanity check kfunc name */
9388 	func_name = btf_name_by_offset(btf, func->name_off);
9389 	if (!func_name || !func_name[0] ||
9390 	    btf_check_kfunc_name(btf, func_name, BTF_INFO_KIND(func->info)))
9391 		return -EINVAL;
9392 
9393 	func = btf_type_by_id(btf, func->type);
9394 	if (!func || !btf_type_is_func_proto(func))
9395 		return -EINVAL;
9396 
9397 	if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
9398 		err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
9399 		if (err)
9400 			return err;
9401 	}
9402 
9403 	return 0;
9404 }
9405 
9406 /* Kernel Function (kfunc) BTF ID set registration API */
9407 
9408 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
9409 				  const struct btf_kfunc_id_set *kset)
9410 {
9411 	struct btf_kfunc_hook_filter *hook_filter;
9412 	struct btf_id_set8 *add_set = kset->set;
9413 	bool vmlinux_set = !btf_is_module(btf);
9414 	bool add_filter = !!kset->filter;
9415 	struct btf_kfunc_set_tab *tab;
9416 	struct btf_id_set8 *set;
9417 	u32 set_cnt, i;
9418 	int ret;
9419 
9420 	if (hook >= BTF_KFUNC_HOOK_MAX) {
9421 		ret = -EINVAL;
9422 		goto end;
9423 	}
9424 
9425 	if (!add_set->cnt)
9426 		return 0;
9427 
9428 	tab = btf->kfunc_set_tab;
9429 
9430 	if (tab && add_filter) {
9431 		u32 i;
9432 
9433 		hook_filter = &tab->hook_filters[hook];
9434 		for (i = 0; i < hook_filter->nr_filters; i++) {
9435 			if (hook_filter->filters[i] == kset->filter) {
9436 				add_filter = false;
9437 				break;
9438 			}
9439 		}
9440 
9441 		if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
9442 			ret = -E2BIG;
9443 			goto end;
9444 		}
9445 	}
9446 
9447 	if (!tab) {
9448 		tab = kzalloc_obj(*tab, GFP_KERNEL | __GFP_NOWARN);
9449 		if (!tab)
9450 			return -ENOMEM;
9451 		btf->kfunc_set_tab = tab;
9452 	}
9453 
9454 	set = tab->sets[hook];
9455 	/* Warn when register_btf_kfunc_id_set is called twice for the same hook
9456 	 * for module sets.
9457 	 */
9458 	if (WARN_ON_ONCE(set && !vmlinux_set)) {
9459 		ret = -EINVAL;
9460 		goto end;
9461 	}
9462 
9463 	/* In case of vmlinux sets, there may be more than one set being
9464 	 * registered per hook. To create a unified set, we allocate a new set
9465 	 * and concatenate all individual sets being registered. While each set
9466 	 * is individually sorted, they may become unsorted when concatenated,
9467 	 * hence re-sorting the final set again is required to make binary
9468 	 * searching the set using btf_id_set8_contains function work.
9469 	 *
9470 	 * For module sets, we need to allocate as we may need to relocate
9471 	 * BTF ids.
9472 	 */
9473 	set_cnt = set ? set->cnt : 0;
9474 
9475 	if (set_cnt > U32_MAX - add_set->cnt) {
9476 		ret = -EOVERFLOW;
9477 		goto end;
9478 	}
9479 
9480 	if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
9481 		ret = -E2BIG;
9482 		goto end;
9483 	}
9484 
9485 	/* Grow set */
9486 	set = krealloc(tab->sets[hook],
9487 		       struct_size(set, pairs, set_cnt + add_set->cnt),
9488 		       GFP_KERNEL | __GFP_NOWARN);
9489 	if (!set) {
9490 		ret = -ENOMEM;
9491 		goto end;
9492 	}
9493 
9494 	/* For newly allocated set, initialize set->cnt to 0 */
9495 	if (!tab->sets[hook])
9496 		set->cnt = 0;
9497 	tab->sets[hook] = set;
9498 
9499 	/* Concatenate the two sets */
9500 	memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
9501 	/* Now that the set is copied, update with relocated BTF ids */
9502 	for (i = set->cnt; i < set->cnt + add_set->cnt; i++)
9503 		set->pairs[i].id = btf_relocate_id(btf, set->pairs[i].id);
9504 
9505 	set->cnt += add_set->cnt;
9506 
9507 	sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
9508 
9509 	if (add_filter) {
9510 		hook_filter = &tab->hook_filters[hook];
9511 		hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
9512 	}
9513 	return 0;
9514 end:
9515 	btf_free_kfunc_set_tab(btf);
9516 	return ret;
9517 }
9518 
9519 static u32 *btf_kfunc_id_set_contains(const struct btf *btf,
9520 				      enum btf_kfunc_hook hook,
9521 				      u32 kfunc_btf_id)
9522 {
9523 	struct btf_id_set8 *set;
9524 	u32 *id;
9525 
9526 	if (hook >= BTF_KFUNC_HOOK_MAX)
9527 		return NULL;
9528 	if (!btf->kfunc_set_tab)
9529 		return NULL;
9530 	set = btf->kfunc_set_tab->sets[hook];
9531 	if (!set)
9532 		return NULL;
9533 	id = btf_id_set8_contains(set, kfunc_btf_id);
9534 	if (!id)
9535 		return NULL;
9536 	/* The flags for BTF ID are located next to it */
9537 	return id + 1;
9538 }
9539 
9540 static bool __btf_kfunc_is_allowed(const struct btf *btf,
9541 				   enum btf_kfunc_hook hook,
9542 				   u32 kfunc_btf_id,
9543 				   const struct bpf_prog *prog)
9544 {
9545 	struct btf_kfunc_hook_filter *hook_filter;
9546 	int i;
9547 
9548 	if (hook >= BTF_KFUNC_HOOK_MAX)
9549 		return false;
9550 	if (!btf->kfunc_set_tab)
9551 		return false;
9552 
9553 	hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
9554 	for (i = 0; i < hook_filter->nr_filters; i++) {
9555 		if (hook_filter->filters[i](prog, kfunc_btf_id))
9556 			return false;
9557 	}
9558 
9559 	return true;
9560 }
9561 
9562 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
9563 {
9564 	switch (prog_type) {
9565 	case BPF_PROG_TYPE_UNSPEC:
9566 		return BTF_KFUNC_HOOK_COMMON;
9567 	case BPF_PROG_TYPE_XDP:
9568 		return BTF_KFUNC_HOOK_XDP;
9569 	case BPF_PROG_TYPE_SCHED_CLS:
9570 		return BTF_KFUNC_HOOK_TC;
9571 	case BPF_PROG_TYPE_STRUCT_OPS:
9572 		return BTF_KFUNC_HOOK_STRUCT_OPS;
9573 	case BPF_PROG_TYPE_TRACING:
9574 	case BPF_PROG_TYPE_TRACEPOINT:
9575 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
9576 	case BPF_PROG_TYPE_PERF_EVENT:
9577 	case BPF_PROG_TYPE_LSM:
9578 		return BTF_KFUNC_HOOK_TRACING;
9579 	case BPF_PROG_TYPE_SYSCALL:
9580 		return BTF_KFUNC_HOOK_SYSCALL;
9581 	case BPF_PROG_TYPE_CGROUP_SKB:
9582 	case BPF_PROG_TYPE_CGROUP_SOCK:
9583 	case BPF_PROG_TYPE_CGROUP_DEVICE:
9584 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
9585 	case BPF_PROG_TYPE_CGROUP_SOCKOPT:
9586 	case BPF_PROG_TYPE_CGROUP_SYSCTL:
9587 	case BPF_PROG_TYPE_SOCK_OPS:
9588 		return BTF_KFUNC_HOOK_CGROUP;
9589 	case BPF_PROG_TYPE_SCHED_ACT:
9590 		return BTF_KFUNC_HOOK_SCHED_ACT;
9591 	case BPF_PROG_TYPE_SK_SKB:
9592 		return BTF_KFUNC_HOOK_SK_SKB;
9593 	case BPF_PROG_TYPE_SOCKET_FILTER:
9594 		return BTF_KFUNC_HOOK_SOCKET_FILTER;
9595 	case BPF_PROG_TYPE_LWT_OUT:
9596 	case BPF_PROG_TYPE_LWT_IN:
9597 	case BPF_PROG_TYPE_LWT_XMIT:
9598 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
9599 		return BTF_KFUNC_HOOK_LWT;
9600 	case BPF_PROG_TYPE_NETFILTER:
9601 		return BTF_KFUNC_HOOK_NETFILTER;
9602 	case BPF_PROG_TYPE_KPROBE:
9603 		return BTF_KFUNC_HOOK_KPROBE;
9604 	default:
9605 		return BTF_KFUNC_HOOK_MAX;
9606 	}
9607 }
9608 
9609 bool btf_kfunc_is_allowed(const struct btf *btf,
9610 			  u32 kfunc_btf_id,
9611 			  const struct bpf_prog *prog)
9612 {
9613 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
9614 	enum btf_kfunc_hook hook;
9615 	u32 *kfunc_flags;
9616 
9617 	kfunc_flags = btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
9618 	if (kfunc_flags && __btf_kfunc_is_allowed(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog))
9619 		return true;
9620 
9621 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
9622 	kfunc_flags = btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
9623 	if (kfunc_flags && __btf_kfunc_is_allowed(btf, hook, kfunc_btf_id, prog))
9624 		return true;
9625 
9626 	return false;
9627 }
9628 
9629 /* Caution:
9630  * Reference to the module (obtained using btf_try_get_module) corresponding to
9631  * the struct btf *MUST* be held when calling this function from verifier
9632  * context. This is usually true as we stash references in prog's kfunc_btf_tab;
9633  * keeping the reference for the duration of the call provides the necessary
9634  * protection for looking up a well-formed btf->kfunc_set_tab.
9635  */
9636 u32 *btf_kfunc_flags(const struct btf *btf, u32 kfunc_btf_id, const struct bpf_prog *prog)
9637 {
9638 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
9639 	enum btf_kfunc_hook hook;
9640 	u32 *kfunc_flags;
9641 
9642 	kfunc_flags = btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id);
9643 	if (kfunc_flags)
9644 		return kfunc_flags;
9645 
9646 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
9647 	return btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
9648 }
9649 
9650 /*
9651  * Check a single KF_* @flag on a kfunc across all of its hook sets.
9652  * Returns:
9653  *   * 1 if @flag is set
9654  *   * 0 if @flag is not set
9655  *   * -EINVAL if @flag is set inconsistently across the sets
9656  *   * -ENOENT if kfunc_btf_id is not a registered kfunc
9657  */
9658 int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag)
9659 {
9660 	enum btf_kfunc_hook hook;
9661 	int res = -ENOENT;
9662 	bool is_set;
9663 	u32 *flags;
9664 
9665 	for (hook = 0; hook < BTF_KFUNC_HOOK_MAX; hook++) {
9666 		flags = btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id);
9667 		if (!flags)
9668 			continue;
9669 		is_set = *flags & flag;
9670 		if (res < 0)
9671 			res = is_set;
9672 		else if (res != is_set)
9673 			return -EINVAL;
9674 	}
9675 
9676 	return res;
9677 }
9678 
9679 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
9680 				const struct bpf_prog *prog)
9681 {
9682 	if (!__btf_kfunc_is_allowed(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog))
9683 		return NULL;
9684 
9685 	return btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id);
9686 }
9687 
9688 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
9689 				       const struct btf_kfunc_id_set *kset)
9690 {
9691 	struct btf *btf;
9692 	int ret, i;
9693 
9694 	btf = btf_get_module_btf(kset->owner);
9695 	if (!btf)
9696 		return check_btf_kconfigs(kset->owner, "kfunc");
9697 	if (IS_ERR(btf))
9698 		return PTR_ERR(btf);
9699 
9700 	for (i = 0; i < kset->set->cnt; i++) {
9701 		ret = btf_check_kfunc_protos(btf, btf_relocate_id(btf, kset->set->pairs[i].id),
9702 					     kset->set->pairs[i].flags);
9703 		if (ret)
9704 			goto err_out;
9705 	}
9706 
9707 	ret = btf_populate_kfunc_set(btf, hook, kset);
9708 
9709 err_out:
9710 	btf_put(btf);
9711 	return ret;
9712 }
9713 
9714 /* This function must be invoked only from initcalls/module init functions */
9715 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
9716 			      const struct btf_kfunc_id_set *kset)
9717 {
9718 	enum btf_kfunc_hook hook;
9719 
9720 	/* All kfuncs need to be tagged as such in BTF.
9721 	 * WARN() for initcall registrations that do not check errors.
9722 	 */
9723 	if (!(kset->set->flags & BTF_SET8_KFUNCS)) {
9724 		WARN_ON(!kset->owner);
9725 		return -EINVAL;
9726 	}
9727 
9728 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
9729 	return __register_btf_kfunc_id_set(hook, kset);
9730 }
9731 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
9732 
9733 /* This function must be invoked only from initcalls/module init functions */
9734 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
9735 {
9736 	return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
9737 }
9738 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
9739 
9740 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
9741 {
9742 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
9743 	struct btf_id_dtor_kfunc *dtor;
9744 
9745 	if (!tab)
9746 		return -ENOENT;
9747 	/* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
9748 	 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
9749 	 */
9750 	BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
9751 	dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
9752 	if (!dtor)
9753 		return -ENOENT;
9754 	return dtor->kfunc_btf_id;
9755 }
9756 
9757 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
9758 {
9759 	const struct btf_type *dtor_func, *dtor_func_proto, *t;
9760 	const struct btf_param *args;
9761 	s32 dtor_btf_id;
9762 	u32 nr_args, i;
9763 
9764 	for (i = 0; i < cnt; i++) {
9765 		dtor_btf_id = btf_relocate_id(btf, dtors[i].kfunc_btf_id);
9766 
9767 		dtor_func = btf_type_by_id(btf, dtor_btf_id);
9768 		if (!dtor_func || !btf_type_is_func(dtor_func))
9769 			return -EINVAL;
9770 
9771 		dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
9772 		if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
9773 			return -EINVAL;
9774 
9775 		/* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
9776 		t = btf_type_by_id(btf, dtor_func_proto->type);
9777 		if (!t || !btf_type_is_void(t))
9778 			return -EINVAL;
9779 
9780 		nr_args = btf_type_vlen(dtor_func_proto);
9781 		if (nr_args != 1)
9782 			return -EINVAL;
9783 		args = btf_params(dtor_func_proto);
9784 		t = btf_type_by_id(btf, args[0].type);
9785 		/* Allow any pointer type, as width on targets Linux supports
9786 		 * will be same for all pointer types (i.e. sizeof(void *))
9787 		 */
9788 		if (!t || !btf_type_is_ptr(t))
9789 			return -EINVAL;
9790 
9791 		if (IS_ENABLED(CONFIG_CFI)) {
9792 			/* Ensure the destructor kfunc type matches btf_dtor_kfunc_t */
9793 			t = btf_type_by_id(btf, t->type);
9794 			if (!btf_type_is_void(t))
9795 				return -EINVAL;
9796 		}
9797 	}
9798 	return 0;
9799 }
9800 
9801 /* This function must be invoked only from initcalls/module init functions */
9802 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
9803 				struct module *owner)
9804 {
9805 	struct btf_id_dtor_kfunc_tab *tab;
9806 	struct btf *btf;
9807 	u32 tab_cnt, i;
9808 	int ret;
9809 
9810 	btf = btf_get_module_btf(owner);
9811 	if (!btf)
9812 		return check_btf_kconfigs(owner, "dtor kfuncs");
9813 	if (IS_ERR(btf))
9814 		return PTR_ERR(btf);
9815 
9816 	if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
9817 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
9818 		ret = -E2BIG;
9819 		goto end;
9820 	}
9821 
9822 	/* Ensure that the prototype of dtor kfuncs being registered is sane */
9823 	ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
9824 	if (ret < 0)
9825 		goto end;
9826 
9827 	tab = btf->dtor_kfunc_tab;
9828 	/* Only one call allowed for modules */
9829 	if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
9830 		ret = -EINVAL;
9831 		goto end;
9832 	}
9833 
9834 	tab_cnt = tab ? tab->cnt : 0;
9835 	if (tab_cnt > U32_MAX - add_cnt) {
9836 		ret = -EOVERFLOW;
9837 		goto end;
9838 	}
9839 	if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
9840 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
9841 		ret = -E2BIG;
9842 		goto end;
9843 	}
9844 
9845 	tab = krealloc(btf->dtor_kfunc_tab,
9846 		       struct_size(tab, dtors, tab_cnt + add_cnt),
9847 		       GFP_KERNEL | __GFP_NOWARN);
9848 	if (!tab) {
9849 		ret = -ENOMEM;
9850 		goto end;
9851 	}
9852 
9853 	if (!btf->dtor_kfunc_tab)
9854 		tab->cnt = 0;
9855 	btf->dtor_kfunc_tab = tab;
9856 
9857 	memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
9858 
9859 	/* remap BTF ids based on BTF relocation (if any) */
9860 	for (i = tab_cnt; i < tab_cnt + add_cnt; i++) {
9861 		tab->dtors[i].btf_id = btf_relocate_id(btf, tab->dtors[i].btf_id);
9862 		tab->dtors[i].kfunc_btf_id = btf_relocate_id(btf, tab->dtors[i].kfunc_btf_id);
9863 	}
9864 
9865 	tab->cnt += add_cnt;
9866 
9867 	sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
9868 
9869 end:
9870 	if (ret)
9871 		btf_free_dtor_kfunc_tab(btf);
9872 	btf_put(btf);
9873 	return ret;
9874 }
9875 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
9876 
9877 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
9878 
9879 /* Check local and target types for compatibility. This check is used for
9880  * type-based CO-RE relocations and follow slightly different rules than
9881  * field-based relocations. This function assumes that root types were already
9882  * checked for name match. Beyond that initial root-level name check, names
9883  * are completely ignored. Compatibility rules are as follows:
9884  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
9885  *     kind should match for local and target types (i.e., STRUCT is not
9886  *     compatible with UNION);
9887  *   - for ENUMs/ENUM64s, the size is ignored;
9888  *   - for INT, size and signedness are ignored;
9889  *   - for ARRAY, dimensionality is ignored, element types are checked for
9890  *     compatibility recursively;
9891  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
9892  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
9893  *   - FUNC_PROTOs are compatible if they have compatible signature: same
9894  *     number of input args and compatible return and argument types.
9895  * These rules are not set in stone and probably will be adjusted as we get
9896  * more experience with using BPF CO-RE relocations.
9897  */
9898 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
9899 			      const struct btf *targ_btf, __u32 targ_id)
9900 {
9901 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
9902 					   MAX_TYPES_ARE_COMPAT_DEPTH);
9903 }
9904 
9905 #define MAX_TYPES_MATCH_DEPTH 2
9906 
9907 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
9908 			 const struct btf *targ_btf, u32 targ_id)
9909 {
9910 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
9911 				      MAX_TYPES_MATCH_DEPTH);
9912 }
9913 
9914 static bool bpf_core_is_flavor_sep(const char *s)
9915 {
9916 	/* check X___Y name pattern, where X and Y are not underscores */
9917 	return s[0] != '_' &&				      /* X */
9918 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
9919 	       s[4] != '_';				      /* Y */
9920 }
9921 
9922 size_t bpf_core_essential_name_len(const char *name)
9923 {
9924 	size_t n = strlen(name);
9925 	int i;
9926 
9927 	for (i = n - 5; i >= 0; i--) {
9928 		if (bpf_core_is_flavor_sep(name + i))
9929 			return i + 1;
9930 	}
9931 	return n;
9932 }
9933 
9934 static void bpf_free_cands(struct bpf_cand_cache *cands)
9935 {
9936 	if (!cands->cnt)
9937 		/* empty candidate array was allocated on stack */
9938 		return;
9939 	kfree(cands);
9940 }
9941 
9942 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
9943 {
9944 	kfree(cands->name);
9945 	kfree(cands);
9946 }
9947 
9948 #define VMLINUX_CAND_CACHE_SIZE 31
9949 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
9950 
9951 #define MODULE_CAND_CACHE_SIZE 31
9952 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
9953 
9954 static void __print_cand_cache(struct bpf_verifier_log *log,
9955 			       struct bpf_cand_cache **cache,
9956 			       int cache_size)
9957 {
9958 	struct bpf_cand_cache *cc;
9959 	int i, j;
9960 
9961 	for (i = 0; i < cache_size; i++) {
9962 		cc = cache[i];
9963 		if (!cc)
9964 			continue;
9965 		bpf_log(log, "[%d]%s(", i, cc->name);
9966 		for (j = 0; j < cc->cnt; j++) {
9967 			bpf_log(log, "%d", cc->cands[j].id);
9968 			if (j < cc->cnt - 1)
9969 				bpf_log(log, " ");
9970 		}
9971 		bpf_log(log, "), ");
9972 	}
9973 }
9974 
9975 static void print_cand_cache(struct bpf_verifier_log *log)
9976 {
9977 	mutex_lock(&cand_cache_mutex);
9978 	bpf_log(log, "vmlinux_cand_cache:");
9979 	__print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
9980 	bpf_log(log, "\nmodule_cand_cache:");
9981 	__print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
9982 	bpf_log(log, "\n");
9983 	mutex_unlock(&cand_cache_mutex);
9984 }
9985 
9986 static u32 hash_cands(struct bpf_cand_cache *cands)
9987 {
9988 	return jhash(cands->name, cands->name_len, 0);
9989 }
9990 
9991 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
9992 					       struct bpf_cand_cache **cache,
9993 					       int cache_size)
9994 {
9995 	struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
9996 
9997 	if (cc && cc->name_len == cands->name_len &&
9998 	    !strncmp(cc->name, cands->name, cands->name_len))
9999 		return cc;
10000 	return NULL;
10001 }
10002 
10003 static size_t sizeof_cands(int cnt)
10004 {
10005 	return offsetof(struct bpf_cand_cache, cands[cnt]);
10006 }
10007 
10008 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
10009 						  struct bpf_cand_cache **cache,
10010 						  int cache_size)
10011 {
10012 	struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
10013 
10014 	if (*cc) {
10015 		bpf_free_cands_from_cache(*cc);
10016 		*cc = NULL;
10017 	}
10018 	new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL_ACCOUNT);
10019 	if (!new_cands) {
10020 		bpf_free_cands(cands);
10021 		return ERR_PTR(-ENOMEM);
10022 	}
10023 	/* strdup the name, since it will stay in cache.
10024 	 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
10025 	 */
10026 	new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL_ACCOUNT);
10027 	bpf_free_cands(cands);
10028 	if (!new_cands->name) {
10029 		kfree(new_cands);
10030 		return ERR_PTR(-ENOMEM);
10031 	}
10032 	*cc = new_cands;
10033 	return new_cands;
10034 }
10035 
10036 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
10037 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
10038 			       int cache_size)
10039 {
10040 	struct bpf_cand_cache *cc;
10041 	int i, j;
10042 
10043 	for (i = 0; i < cache_size; i++) {
10044 		cc = cache[i];
10045 		if (!cc)
10046 			continue;
10047 		if (!btf) {
10048 			/* when new module is loaded purge all of module_cand_cache,
10049 			 * since new module might have candidates with the name
10050 			 * that matches cached cands.
10051 			 */
10052 			bpf_free_cands_from_cache(cc);
10053 			cache[i] = NULL;
10054 			continue;
10055 		}
10056 		/* when module is unloaded purge cache entries
10057 		 * that match module's btf
10058 		 */
10059 		for (j = 0; j < cc->cnt; j++)
10060 			if (cc->cands[j].btf == btf) {
10061 				bpf_free_cands_from_cache(cc);
10062 				cache[i] = NULL;
10063 				break;
10064 			}
10065 	}
10066 
10067 }
10068 
10069 static void purge_cand_cache(struct btf *btf)
10070 {
10071 	mutex_lock(&cand_cache_mutex);
10072 	__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
10073 	mutex_unlock(&cand_cache_mutex);
10074 }
10075 #endif
10076 
10077 static struct bpf_cand_cache *
10078 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
10079 		   int targ_start_id)
10080 {
10081 	struct bpf_cand_cache *new_cands;
10082 	const struct btf_type *t;
10083 	const char *targ_name;
10084 	size_t targ_essent_len;
10085 	int n, i;
10086 
10087 	n = btf_nr_types(targ_btf);
10088 	for (i = targ_start_id; i < n; i++) {
10089 		t = btf_type_by_id(targ_btf, i);
10090 		if (btf_kind(t) != cands->kind)
10091 			continue;
10092 
10093 		targ_name = btf_name_by_offset(targ_btf, t->name_off);
10094 		if (!targ_name)
10095 			continue;
10096 
10097 		/* the resched point is before strncmp to make sure that search
10098 		 * for non-existing name will have a chance to schedule().
10099 		 */
10100 		cond_resched();
10101 
10102 		if (strncmp(cands->name, targ_name, cands->name_len) != 0)
10103 			continue;
10104 
10105 		targ_essent_len = bpf_core_essential_name_len(targ_name);
10106 		if (targ_essent_len != cands->name_len)
10107 			continue;
10108 
10109 		/* most of the time there is only one candidate for a given kind+name pair */
10110 		new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL_ACCOUNT);
10111 		if (!new_cands) {
10112 			bpf_free_cands(cands);
10113 			return ERR_PTR(-ENOMEM);
10114 		}
10115 
10116 		memcpy(new_cands, cands, sizeof_cands(cands->cnt));
10117 		bpf_free_cands(cands);
10118 		cands = new_cands;
10119 		cands->cands[cands->cnt].btf = targ_btf;
10120 		cands->cands[cands->cnt].id = i;
10121 		cands->cnt++;
10122 	}
10123 	return cands;
10124 }
10125 
10126 static struct bpf_cand_cache *
10127 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
10128 {
10129 	struct bpf_cand_cache *cands, *cc, local_cand = {};
10130 	const struct btf *local_btf = ctx->btf;
10131 	const struct btf_type *local_type;
10132 	const struct btf *main_btf;
10133 	size_t local_essent_len;
10134 	struct btf *mod_btf;
10135 	const char *name;
10136 	int id;
10137 
10138 	main_btf = bpf_get_btf_vmlinux();
10139 	if (IS_ERR(main_btf))
10140 		return ERR_CAST(main_btf);
10141 	if (!main_btf)
10142 		return ERR_PTR(-EINVAL);
10143 
10144 	local_type = btf_type_by_id(local_btf, local_type_id);
10145 	if (!local_type)
10146 		return ERR_PTR(-EINVAL);
10147 
10148 	name = btf_name_by_offset(local_btf, local_type->name_off);
10149 	if (str_is_empty(name))
10150 		return ERR_PTR(-EINVAL);
10151 	local_essent_len = bpf_core_essential_name_len(name);
10152 
10153 	cands = &local_cand;
10154 	cands->name = name;
10155 	cands->kind = btf_kind(local_type);
10156 	cands->name_len = local_essent_len;
10157 
10158 	cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
10159 	/* cands is a pointer to stack here */
10160 	if (cc) {
10161 		if (cc->cnt)
10162 			return cc;
10163 		goto check_modules;
10164 	}
10165 
10166 	/* Attempt to find target candidates in vmlinux BTF first */
10167 	cands = bpf_core_add_cands(cands, main_btf, btf_named_start_id(main_btf, true));
10168 	if (IS_ERR(cands))
10169 		return ERR_CAST(cands);
10170 
10171 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
10172 
10173 	/* populate cache even when cands->cnt == 0 */
10174 	cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
10175 	if (IS_ERR(cc))
10176 		return ERR_CAST(cc);
10177 
10178 	/* if vmlinux BTF has any candidate, don't go for module BTFs */
10179 	if (cc->cnt)
10180 		return cc;
10181 
10182 check_modules:
10183 	/* cands is a pointer to stack here and cands->cnt == 0 */
10184 	cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
10185 	if (cc)
10186 		/* if cache has it return it even if cc->cnt == 0 */
10187 		return cc;
10188 
10189 	/* If candidate is not found in vmlinux's BTF then search in module's BTFs */
10190 	spin_lock_bh(&btf_idr_lock);
10191 	idr_for_each_entry(&btf_idr, mod_btf, id) {
10192 		if (!btf_is_module(mod_btf))
10193 			continue;
10194 		/* linear search could be slow hence unlock/lock
10195 		 * the IDR to avoiding holding it for too long
10196 		 */
10197 		btf_get(mod_btf);
10198 		spin_unlock_bh(&btf_idr_lock);
10199 		cands = bpf_core_add_cands(cands, mod_btf, btf_named_start_id(mod_btf, true));
10200 		btf_put(mod_btf);
10201 		if (IS_ERR(cands))
10202 			return ERR_CAST(cands);
10203 		spin_lock_bh(&btf_idr_lock);
10204 	}
10205 	spin_unlock_bh(&btf_idr_lock);
10206 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0
10207 	 * or pointer to stack if cands->cnd == 0.
10208 	 * Copy it into the cache even when cands->cnt == 0 and
10209 	 * return the result.
10210 	 */
10211 	return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
10212 }
10213 
10214 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
10215 		   int relo_idx, void *insn)
10216 {
10217 	bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
10218 	struct bpf_core_cand_list cands = {};
10219 	struct bpf_core_relo_res targ_res;
10220 	struct bpf_core_spec *specs;
10221 	const struct btf_type *type;
10222 	int err;
10223 
10224 	/* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
10225 	 * into arrays of btf_ids of struct fields and array indices.
10226 	 */
10227 	specs = kzalloc_objs(*specs, 3, GFP_KERNEL_ACCOUNT);
10228 	if (!specs)
10229 		return -ENOMEM;
10230 
10231 	type = btf_type_by_id(ctx->btf, relo->type_id);
10232 	if (!type) {
10233 		bpf_log(ctx->log, "relo #%u: bad type id %u\n",
10234 			relo_idx, relo->type_id);
10235 		kfree(specs);
10236 		return -EINVAL;
10237 	}
10238 
10239 	if (need_cands) {
10240 		struct bpf_cand_cache *cc;
10241 		int i;
10242 
10243 		mutex_lock(&cand_cache_mutex);
10244 		cc = bpf_core_find_cands(ctx, relo->type_id);
10245 		if (IS_ERR(cc)) {
10246 			bpf_log(ctx->log, "target candidate search failed for %d\n",
10247 				relo->type_id);
10248 			err = PTR_ERR(cc);
10249 			goto out;
10250 		}
10251 		if (cc->cnt) {
10252 			cands.cands = kzalloc_objs(*cands.cands, cc->cnt,
10253 						   GFP_KERNEL_ACCOUNT);
10254 			if (!cands.cands) {
10255 				err = -ENOMEM;
10256 				goto out;
10257 			}
10258 		}
10259 		for (i = 0; i < cc->cnt; i++) {
10260 			bpf_log(ctx->log,
10261 				"CO-RE relocating %s %s: found target candidate [%d]\n",
10262 				btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
10263 			cands.cands[i].btf = cc->cands[i].btf;
10264 			cands.cands[i].id = cc->cands[i].id;
10265 		}
10266 		cands.len = cc->cnt;
10267 		/* cand_cache_mutex needs to span the cache lookup and
10268 		 * copy of btf pointer into bpf_core_cand_list,
10269 		 * since module can be unloaded while bpf_core_calc_relo_insn
10270 		 * is working with module's btf.
10271 		 */
10272 	}
10273 
10274 	err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
10275 				      &targ_res);
10276 	if (err)
10277 		goto out;
10278 
10279 	err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
10280 				  &targ_res);
10281 
10282 out:
10283 	kfree(specs);
10284 	if (need_cands) {
10285 		kfree(cands.cands);
10286 		mutex_unlock(&cand_cache_mutex);
10287 		if (ctx->log->level & BPF_LOG_LEVEL2)
10288 			print_cand_cache(ctx->log);
10289 	}
10290 	return err;
10291 }
10292 
10293 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
10294 				const struct bpf_reg_state *reg,
10295 				const char *field_name, u32 btf_id, const char *suffix)
10296 {
10297 	struct btf *btf = reg->btf;
10298 	const struct btf_type *walk_type, *safe_type;
10299 	const char *tname;
10300 	char safe_tname[64];
10301 	long ret, safe_id;
10302 	const struct btf_member *member;
10303 	u32 i;
10304 
10305 	walk_type = btf_type_by_id(btf, reg->btf_id);
10306 	if (!walk_type)
10307 		return false;
10308 
10309 	tname = btf_name_by_offset(btf, walk_type->name_off);
10310 
10311 	ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
10312 	if (ret >= sizeof(safe_tname))
10313 		return false;
10314 
10315 	safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
10316 	if (safe_id < 0)
10317 		return false;
10318 
10319 	safe_type = btf_type_by_id(btf, safe_id);
10320 	if (!safe_type)
10321 		return false;
10322 
10323 	for_each_member(i, safe_type, member) {
10324 		const char *m_name = __btf_name_by_offset(btf, member->name_off);
10325 		const struct btf_type *mtype = btf_type_by_id(btf, member->type);
10326 		u32 id;
10327 
10328 		if (!btf_type_is_ptr(mtype))
10329 			continue;
10330 
10331 		btf_type_skip_modifiers(btf, mtype->type, &id);
10332 		/* If we match on both type and name, the field is considered trusted. */
10333 		if (btf_id == id && !strcmp(field_name, m_name))
10334 			return true;
10335 	}
10336 
10337 	return false;
10338 }
10339 
10340 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
10341 			       const struct btf *reg_btf, u32 reg_id,
10342 			       const struct btf *arg_btf, u32 arg_id)
10343 {
10344 	const char *reg_name, *arg_name, *search_needle;
10345 	const struct btf_type *reg_type, *arg_type;
10346 	int reg_len, arg_len, cmp_len;
10347 	size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
10348 
10349 	reg_type = btf_type_by_id(reg_btf, reg_id);
10350 	if (!reg_type)
10351 		return false;
10352 
10353 	arg_type = btf_type_by_id(arg_btf, arg_id);
10354 	if (!arg_type)
10355 		return false;
10356 
10357 	reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
10358 	arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
10359 
10360 	reg_len = strlen(reg_name);
10361 	arg_len = strlen(arg_name);
10362 
10363 	/* Exactly one of the two type names may be suffixed with ___init, so
10364 	 * if the strings are the same size, they can't possibly be no-cast
10365 	 * aliases of one another. If you have two of the same type names, e.g.
10366 	 * they're both nf_conn___init, it would be improper to return true
10367 	 * because they are _not_ no-cast aliases, they are the same type.
10368 	 */
10369 	if (reg_len == arg_len)
10370 		return false;
10371 
10372 	/* Either of the two names must be the other name, suffixed with ___init. */
10373 	if ((reg_len != arg_len + pattern_len) &&
10374 	    (arg_len != reg_len + pattern_len))
10375 		return false;
10376 
10377 	if (reg_len < arg_len) {
10378 		search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
10379 		cmp_len = reg_len;
10380 	} else {
10381 		search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
10382 		cmp_len = arg_len;
10383 	}
10384 
10385 	if (!search_needle)
10386 		return false;
10387 
10388 	/* ___init suffix must come at the end of the name */
10389 	if (*(search_needle + pattern_len) != '\0')
10390 		return false;
10391 
10392 	return !strncmp(reg_name, arg_name, cmp_len);
10393 }
10394 
10395 #ifdef CONFIG_BPF_JIT
10396 static int
10397 btf_add_struct_ops(struct btf *btf, struct bpf_struct_ops *st_ops,
10398 		   struct bpf_verifier_log *log)
10399 {
10400 	struct btf_struct_ops_tab *tab, *new_tab;
10401 	int cgroup_atype;
10402 	int i, err;
10403 
10404 	tab = btf->struct_ops_tab;
10405 	if (!tab) {
10406 		tab = kzalloc_flex(*tab, ops, 4);
10407 		if (!tab)
10408 			return -ENOMEM;
10409 		tab->capacity = 4;
10410 		btf->struct_ops_tab = tab;
10411 	}
10412 
10413 	cgroup_atype = st_ops->cgroup_atype;
10414 	for (i = 0; i < tab->cnt; i++)
10415 		if (tab->ops[i].st_ops == st_ops ||
10416 		    (cgroup_atype && cgroup_atype == tab->ops[i].st_ops->cgroup_atype))
10417 			return -EEXIST;
10418 
10419 	if (tab->cnt == tab->capacity) {
10420 		new_tab = krealloc(tab,
10421 				   struct_size(tab, ops, tab->capacity * 2),
10422 				   GFP_KERNEL);
10423 		if (!new_tab)
10424 			return -ENOMEM;
10425 		tab = new_tab;
10426 		tab->capacity *= 2;
10427 		btf->struct_ops_tab = tab;
10428 	}
10429 
10430 	tab->ops[btf->struct_ops_tab->cnt].st_ops = st_ops;
10431 
10432 	err = bpf_struct_ops_desc_init(&tab->ops[btf->struct_ops_tab->cnt], btf, log);
10433 	if (err)
10434 		return err;
10435 
10436 	if (cgroup_atype) {
10437 		/*
10438 		 * Cgroup struct_ops callers hold the RCU read lock around the
10439 		 * entire trampoline call, including its trailing instructions.
10440 		 * A regular RCU grace period therefore protects both the kdata
10441 		 * and the trampoline image, so a tasks RCU grace period is not
10442 		 * needed.
10443 		 */
10444 		if (!cgroup_bpf_is_struct_ops_atype(cgroup_atype) ||
10445 		    st_ops->reg || st_ops->unreg || st_ops->free_after_tasks_rcu_gp) {
10446 			bpf_struct_ops_desc_release(&tab->ops[btf->struct_ops_tab->cnt]);
10447 			return -EINVAL;
10448 		}
10449 
10450 		/*
10451 		 * There is no need to unregister from the cgroup when btf_free()
10452 		 * runs. No struct_ops map or cgroup link can be created once its
10453 		 * BTF is gone.
10454 		 */
10455 		cgroup_bpf_struct_ops_register(cgroup_atype,
10456 					       tab->ops[btf->struct_ops_tab->cnt].type_id,
10457 					       st_ops->cfi_stubs,
10458 					       st_ops->free_after_mult_rcu_gp);
10459 	}
10460 
10461 	btf->struct_ops_tab->cnt++;
10462 
10463 	return 0;
10464 }
10465 
10466 const struct bpf_struct_ops_desc *
10467 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
10468 {
10469 	const struct bpf_struct_ops_desc *st_ops_list;
10470 	unsigned int i;
10471 	u32 cnt;
10472 
10473 	if (!value_id)
10474 		return NULL;
10475 	if (!btf->struct_ops_tab)
10476 		return NULL;
10477 
10478 	cnt = btf->struct_ops_tab->cnt;
10479 	st_ops_list = btf->struct_ops_tab->ops;
10480 	for (i = 0; i < cnt; i++) {
10481 		if (st_ops_list[i].value_id == value_id)
10482 			return &st_ops_list[i];
10483 	}
10484 
10485 	return NULL;
10486 }
10487 
10488 const struct bpf_struct_ops_desc *
10489 bpf_struct_ops_find(struct btf *btf, u32 type_id)
10490 {
10491 	const struct bpf_struct_ops_desc *st_ops_list;
10492 	unsigned int i;
10493 	u32 cnt;
10494 
10495 	if (!type_id)
10496 		return NULL;
10497 	if (!btf->struct_ops_tab)
10498 		return NULL;
10499 
10500 	cnt = btf->struct_ops_tab->cnt;
10501 	st_ops_list = btf->struct_ops_tab->ops;
10502 	for (i = 0; i < cnt; i++) {
10503 		if (st_ops_list[i].type_id == type_id)
10504 			return &st_ops_list[i];
10505 	}
10506 
10507 	return NULL;
10508 }
10509 
10510 int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
10511 {
10512 	struct bpf_verifier_log *log;
10513 	struct btf *btf;
10514 	int err = 0;
10515 
10516 	btf = btf_get_module_btf(st_ops->owner);
10517 	if (!btf)
10518 		return check_btf_kconfigs(st_ops->owner, "struct_ops");
10519 	if (IS_ERR(btf))
10520 		return PTR_ERR(btf);
10521 
10522 	log = kzalloc_obj(*log, GFP_KERNEL | __GFP_NOWARN);
10523 	if (!log) {
10524 		err = -ENOMEM;
10525 		goto errout;
10526 	}
10527 
10528 	log->level = BPF_LOG_KERNEL;
10529 
10530 	err = btf_add_struct_ops(btf, st_ops, log);
10531 
10532 errout:
10533 	kfree(log);
10534 	btf_put(btf);
10535 
10536 	return err;
10537 }
10538 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
10539 #endif
10540 
10541 bool btf_param_match_suffix(const struct btf *btf,
10542 			    const struct btf_param *arg,
10543 			    const char *suffix)
10544 {
10545 	int suffix_len = strlen(suffix), len;
10546 	const char *param_name;
10547 
10548 	/* In the future, this can be ported to use BTF tagging */
10549 	param_name = btf_name_by_offset(btf, arg->name_off);
10550 	if (str_is_empty(param_name))
10551 		return false;
10552 	len = strlen(param_name);
10553 	if (len <= suffix_len)
10554 		return false;
10555 	param_name += len - suffix_len;
10556 	return !strncmp(param_name, suffix, suffix_len);
10557 }
10558