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