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