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