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