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