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