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