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