xref: /linux/kernel/bpf/btf.c (revision a6a6a98094116b60e5523a571d9443c53325f5b1)
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_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5824 			  const struct btf_type *t, enum bpf_prog_type prog_type,
5825 			  int arg)
5826 {
5827 	const struct btf_type *ctx_type;
5828 	const char *tname, *ctx_tname;
5829 
5830 	t = btf_type_by_id(btf, t->type);
5831 
5832 	/* KPROBE programs allow bpf_user_pt_regs_t typedef, which we need to
5833 	 * check before we skip all the typedef below.
5834 	 */
5835 	if (prog_type == BPF_PROG_TYPE_KPROBE) {
5836 		while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
5837 			t = btf_type_by_id(btf, t->type);
5838 
5839 		if (btf_type_is_typedef(t)) {
5840 			tname = btf_name_by_offset(btf, t->name_off);
5841 			if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
5842 				return true;
5843 		}
5844 	}
5845 
5846 	while (btf_type_is_modifier(t))
5847 		t = btf_type_by_id(btf, t->type);
5848 	if (!btf_type_is_struct(t)) {
5849 		/* Only pointer to struct is supported for now.
5850 		 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
5851 		 * is not supported yet.
5852 		 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
5853 		 */
5854 		return false;
5855 	}
5856 	tname = btf_name_by_offset(btf, t->name_off);
5857 	if (!tname) {
5858 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
5859 		return false;
5860 	}
5861 
5862 	ctx_type = find_canonical_prog_ctx_type(prog_type);
5863 	if (!ctx_type) {
5864 		bpf_log(log, "btf_vmlinux is malformed\n");
5865 		/* should not happen */
5866 		return false;
5867 	}
5868 again:
5869 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
5870 	if (!ctx_tname) {
5871 		/* should not happen */
5872 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
5873 		return false;
5874 	}
5875 	/* program types without named context types work only with arg:ctx tag */
5876 	if (ctx_tname[0] == '\0')
5877 		return false;
5878 	/* only compare that prog's ctx type name is the same as
5879 	 * kernel expects. No need to compare field by field.
5880 	 * It's ok for bpf prog to do:
5881 	 * struct __sk_buff {};
5882 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
5883 	 * { // no fields of skb are ever used }
5884 	 */
5885 	if (strcmp(ctx_tname, "__sk_buff") == 0 && strcmp(tname, "sk_buff") == 0)
5886 		return true;
5887 	if (strcmp(ctx_tname, "xdp_md") == 0 && strcmp(tname, "xdp_buff") == 0)
5888 		return true;
5889 	if (strcmp(ctx_tname, tname)) {
5890 		/* bpf_user_pt_regs_t is a typedef, so resolve it to
5891 		 * underlying struct and check name again
5892 		 */
5893 		if (!btf_type_is_modifier(ctx_type))
5894 			return false;
5895 		while (btf_type_is_modifier(ctx_type))
5896 			ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
5897 		goto again;
5898 	}
5899 	return true;
5900 }
5901 
5902 /* forward declarations for arch-specific underlying types of
5903  * bpf_user_pt_regs_t; this avoids the need for arch-specific #ifdef
5904  * compilation guards below for BPF_PROG_TYPE_PERF_EVENT checks, but still
5905  * works correctly with __builtin_types_compatible_p() on respective
5906  * architectures
5907  */
5908 struct user_regs_struct;
5909 struct user_pt_regs;
5910 
5911 static int btf_validate_prog_ctx_type(struct bpf_verifier_log *log, const struct btf *btf,
5912 				      const struct btf_type *t, int arg,
5913 				      enum bpf_prog_type prog_type,
5914 				      enum bpf_attach_type attach_type)
5915 {
5916 	const struct btf_type *ctx_type;
5917 	const char *tname, *ctx_tname;
5918 
5919 	if (!btf_is_ptr(t)) {
5920 		bpf_log(log, "arg#%d type isn't a pointer\n", arg);
5921 		return -EINVAL;
5922 	}
5923 	t = btf_type_by_id(btf, t->type);
5924 
5925 	/* KPROBE and PERF_EVENT programs allow bpf_user_pt_regs_t typedef */
5926 	if (prog_type == BPF_PROG_TYPE_KPROBE || prog_type == BPF_PROG_TYPE_PERF_EVENT) {
5927 		while (btf_type_is_modifier(t) && !btf_type_is_typedef(t))
5928 			t = btf_type_by_id(btf, t->type);
5929 
5930 		if (btf_type_is_typedef(t)) {
5931 			tname = btf_name_by_offset(btf, t->name_off);
5932 			if (tname && strcmp(tname, "bpf_user_pt_regs_t") == 0)
5933 				return 0;
5934 		}
5935 	}
5936 
5937 	/* all other program types don't use typedefs for context type */
5938 	while (btf_type_is_modifier(t))
5939 		t = btf_type_by_id(btf, t->type);
5940 
5941 	/* `void *ctx __arg_ctx` is always valid */
5942 	if (btf_type_is_void(t))
5943 		return 0;
5944 
5945 	tname = btf_name_by_offset(btf, t->name_off);
5946 	if (str_is_empty(tname)) {
5947 		bpf_log(log, "arg#%d type doesn't have a name\n", arg);
5948 		return -EINVAL;
5949 	}
5950 
5951 	/* special cases */
5952 	switch (prog_type) {
5953 	case BPF_PROG_TYPE_KPROBE:
5954 		if (__btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
5955 			return 0;
5956 		break;
5957 	case BPF_PROG_TYPE_PERF_EVENT:
5958 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct pt_regs) &&
5959 		    __btf_type_is_struct(t) && strcmp(tname, "pt_regs") == 0)
5960 			return 0;
5961 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_pt_regs) &&
5962 		    __btf_type_is_struct(t) && strcmp(tname, "user_pt_regs") == 0)
5963 			return 0;
5964 		if (__builtin_types_compatible_p(bpf_user_pt_regs_t, struct user_regs_struct) &&
5965 		    __btf_type_is_struct(t) && strcmp(tname, "user_regs_struct") == 0)
5966 			return 0;
5967 		break;
5968 	case BPF_PROG_TYPE_RAW_TRACEPOINT:
5969 	case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE:
5970 		/* allow u64* as ctx */
5971 		if (btf_is_int(t) && t->size == 8)
5972 			return 0;
5973 		break;
5974 	case BPF_PROG_TYPE_TRACING:
5975 		switch (attach_type) {
5976 		case BPF_TRACE_RAW_TP:
5977 			/* tp_btf program is TRACING, so need special case here */
5978 			if (__btf_type_is_struct(t) &&
5979 			    strcmp(tname, "bpf_raw_tracepoint_args") == 0)
5980 				return 0;
5981 			/* allow u64* as ctx */
5982 			if (btf_is_int(t) && t->size == 8)
5983 				return 0;
5984 			break;
5985 		case BPF_TRACE_ITER:
5986 			/* allow struct bpf_iter__xxx types only */
5987 			if (__btf_type_is_struct(t) &&
5988 			    strncmp(tname, "bpf_iter__", sizeof("bpf_iter__") - 1) == 0)
5989 				return 0;
5990 			break;
5991 		case BPF_TRACE_FENTRY:
5992 		case BPF_TRACE_FEXIT:
5993 		case BPF_MODIFY_RETURN:
5994 			/* allow u64* as ctx */
5995 			if (btf_is_int(t) && t->size == 8)
5996 				return 0;
5997 			break;
5998 		default:
5999 			break;
6000 		}
6001 		break;
6002 	case BPF_PROG_TYPE_LSM:
6003 	case BPF_PROG_TYPE_STRUCT_OPS:
6004 		/* allow u64* as ctx */
6005 		if (btf_is_int(t) && t->size == 8)
6006 			return 0;
6007 		break;
6008 	case BPF_PROG_TYPE_TRACEPOINT:
6009 	case BPF_PROG_TYPE_SYSCALL:
6010 	case BPF_PROG_TYPE_EXT:
6011 		return 0; /* anything goes */
6012 	default:
6013 		break;
6014 	}
6015 
6016 	ctx_type = find_canonical_prog_ctx_type(prog_type);
6017 	if (!ctx_type) {
6018 		/* should not happen */
6019 		bpf_log(log, "btf_vmlinux is malformed\n");
6020 		return -EINVAL;
6021 	}
6022 
6023 	/* resolve typedefs and check that underlying structs are matching as well */
6024 	while (btf_type_is_modifier(ctx_type))
6025 		ctx_type = btf_type_by_id(btf_vmlinux, ctx_type->type);
6026 
6027 	/* if program type doesn't have distinctly named struct type for
6028 	 * context, then __arg_ctx argument can only be `void *`, which we
6029 	 * already checked above
6030 	 */
6031 	if (!__btf_type_is_struct(ctx_type)) {
6032 		bpf_log(log, "arg#%d should be void pointer\n", arg);
6033 		return -EINVAL;
6034 	}
6035 
6036 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_type->name_off);
6037 	if (!__btf_type_is_struct(t) || strcmp(ctx_tname, tname) != 0) {
6038 		bpf_log(log, "arg#%d should be `struct %s *`\n", arg, ctx_tname);
6039 		return -EINVAL;
6040 	}
6041 
6042 	return 0;
6043 }
6044 
6045 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
6046 				     struct btf *btf,
6047 				     const struct btf_type *t,
6048 				     enum bpf_prog_type prog_type,
6049 				     int arg)
6050 {
6051 	if (!btf_is_prog_ctx_type(log, btf, t, prog_type, arg))
6052 		return -ENOENT;
6053 	return find_kern_ctx_type_id(prog_type);
6054 }
6055 
6056 int get_kern_ctx_btf_id(struct bpf_verifier_log *log, enum bpf_prog_type prog_type)
6057 {
6058 	const struct btf_member *kctx_member;
6059 	const struct btf_type *conv_struct;
6060 	const struct btf_type *kctx_type;
6061 	u32 kctx_type_id;
6062 
6063 	conv_struct = bpf_ctx_convert.t;
6064 	/* get member for kernel ctx type */
6065 	kctx_member = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2 + 1;
6066 	kctx_type_id = kctx_member->type;
6067 	kctx_type = btf_type_by_id(btf_vmlinux, kctx_type_id);
6068 	if (!btf_type_is_struct(kctx_type)) {
6069 		bpf_log(log, "kern ctx type id %u is not a struct\n", kctx_type_id);
6070 		return -EINVAL;
6071 	}
6072 
6073 	return kctx_type_id;
6074 }
6075 
6076 BTF_ID_LIST(bpf_ctx_convert_btf_id)
6077 BTF_ID(struct, bpf_ctx_convert)
6078 
6079 struct btf *btf_parse_vmlinux(void)
6080 {
6081 	struct btf_verifier_env *env = NULL;
6082 	struct bpf_verifier_log *log;
6083 	struct btf *btf = NULL;
6084 	int err;
6085 
6086 	if (!IS_ENABLED(CONFIG_DEBUG_INFO_BTF))
6087 		return ERR_PTR(-ENOENT);
6088 
6089 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
6090 	if (!env)
6091 		return ERR_PTR(-ENOMEM);
6092 
6093 	log = &env->log;
6094 	log->level = BPF_LOG_KERNEL;
6095 
6096 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6097 	if (!btf) {
6098 		err = -ENOMEM;
6099 		goto errout;
6100 	}
6101 	env->btf = btf;
6102 
6103 	btf->data = __start_BTF;
6104 	btf->data_size = __stop_BTF - __start_BTF;
6105 	btf->kernel_btf = true;
6106 	snprintf(btf->name, sizeof(btf->name), "vmlinux");
6107 
6108 	err = btf_parse_hdr(env);
6109 	if (err)
6110 		goto errout;
6111 
6112 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6113 
6114 	err = btf_parse_str_sec(env);
6115 	if (err)
6116 		goto errout;
6117 
6118 	err = btf_check_all_metas(env);
6119 	if (err)
6120 		goto errout;
6121 
6122 	err = btf_check_type_tags(env, btf, 1);
6123 	if (err)
6124 		goto errout;
6125 
6126 	/* btf_parse_vmlinux() runs under bpf_verifier_lock */
6127 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
6128 
6129 	refcount_set(&btf->refcnt, 1);
6130 
6131 	err = btf_alloc_id(btf);
6132 	if (err)
6133 		goto errout;
6134 
6135 	btf_verifier_env_free(env);
6136 	return btf;
6137 
6138 errout:
6139 	btf_verifier_env_free(env);
6140 	if (btf) {
6141 		kvfree(btf->types);
6142 		kfree(btf);
6143 	}
6144 	return ERR_PTR(err);
6145 }
6146 
6147 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
6148 
6149 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
6150 {
6151 	struct btf_verifier_env *env = NULL;
6152 	struct bpf_verifier_log *log;
6153 	struct btf *btf = NULL, *base_btf;
6154 	int err;
6155 
6156 	base_btf = bpf_get_btf_vmlinux();
6157 	if (IS_ERR(base_btf))
6158 		return base_btf;
6159 	if (!base_btf)
6160 		return ERR_PTR(-EINVAL);
6161 
6162 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
6163 	if (!env)
6164 		return ERR_PTR(-ENOMEM);
6165 
6166 	log = &env->log;
6167 	log->level = BPF_LOG_KERNEL;
6168 
6169 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
6170 	if (!btf) {
6171 		err = -ENOMEM;
6172 		goto errout;
6173 	}
6174 	env->btf = btf;
6175 
6176 	btf->base_btf = base_btf;
6177 	btf->start_id = base_btf->nr_types;
6178 	btf->start_str_off = base_btf->hdr.str_len;
6179 	btf->kernel_btf = true;
6180 	snprintf(btf->name, sizeof(btf->name), "%s", module_name);
6181 
6182 	btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
6183 	if (!btf->data) {
6184 		err = -ENOMEM;
6185 		goto errout;
6186 	}
6187 	memcpy(btf->data, data, data_size);
6188 	btf->data_size = data_size;
6189 
6190 	err = btf_parse_hdr(env);
6191 	if (err)
6192 		goto errout;
6193 
6194 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
6195 
6196 	err = btf_parse_str_sec(env);
6197 	if (err)
6198 		goto errout;
6199 
6200 	err = btf_check_all_metas(env);
6201 	if (err)
6202 		goto errout;
6203 
6204 	err = btf_check_type_tags(env, btf, btf_nr_types(base_btf));
6205 	if (err)
6206 		goto errout;
6207 
6208 	btf_verifier_env_free(env);
6209 	refcount_set(&btf->refcnt, 1);
6210 	return btf;
6211 
6212 errout:
6213 	btf_verifier_env_free(env);
6214 	if (btf) {
6215 		kvfree(btf->data);
6216 		kvfree(btf->types);
6217 		kfree(btf);
6218 	}
6219 	return ERR_PTR(err);
6220 }
6221 
6222 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
6223 
6224 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
6225 {
6226 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6227 
6228 	if (tgt_prog)
6229 		return tgt_prog->aux->btf;
6230 	else
6231 		return prog->aux->attach_btf;
6232 }
6233 
6234 static bool is_int_ptr(struct btf *btf, const struct btf_type *t)
6235 {
6236 	/* skip modifiers */
6237 	t = btf_type_skip_modifiers(btf, t->type, NULL);
6238 
6239 	return btf_type_is_int(t);
6240 }
6241 
6242 static u32 get_ctx_arg_idx(struct btf *btf, const struct btf_type *func_proto,
6243 			   int off)
6244 {
6245 	const struct btf_param *args;
6246 	const struct btf_type *t;
6247 	u32 offset = 0, nr_args;
6248 	int i;
6249 
6250 	if (!func_proto)
6251 		return off / 8;
6252 
6253 	nr_args = btf_type_vlen(func_proto);
6254 	args = (const struct btf_param *)(func_proto + 1);
6255 	for (i = 0; i < nr_args; i++) {
6256 		t = btf_type_skip_modifiers(btf, args[i].type, NULL);
6257 		offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6258 		if (off < offset)
6259 			return i;
6260 	}
6261 
6262 	t = btf_type_skip_modifiers(btf, func_proto->type, NULL);
6263 	offset += btf_type_is_ptr(t) ? 8 : roundup(t->size, 8);
6264 	if (off < offset)
6265 		return nr_args;
6266 
6267 	return nr_args + 1;
6268 }
6269 
6270 static bool prog_args_trusted(const struct bpf_prog *prog)
6271 {
6272 	enum bpf_attach_type atype = prog->expected_attach_type;
6273 
6274 	switch (prog->type) {
6275 	case BPF_PROG_TYPE_TRACING:
6276 		return atype == BPF_TRACE_RAW_TP || atype == BPF_TRACE_ITER;
6277 	case BPF_PROG_TYPE_LSM:
6278 		return bpf_lsm_is_trusted(prog);
6279 	case BPF_PROG_TYPE_STRUCT_OPS:
6280 		return true;
6281 	default:
6282 		return false;
6283 	}
6284 }
6285 
6286 int btf_ctx_arg_offset(const struct btf *btf, const struct btf_type *func_proto,
6287 		       u32 arg_no)
6288 {
6289 	const struct btf_param *args;
6290 	const struct btf_type *t;
6291 	int off = 0, i;
6292 	u32 sz;
6293 
6294 	args = btf_params(func_proto);
6295 	for (i = 0; i < arg_no; i++) {
6296 		t = btf_type_by_id(btf, args[i].type);
6297 		t = btf_resolve_size(btf, t, &sz);
6298 		if (IS_ERR(t))
6299 			return PTR_ERR(t);
6300 		off += roundup(sz, 8);
6301 	}
6302 
6303 	return off;
6304 }
6305 
6306 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
6307 		    const struct bpf_prog *prog,
6308 		    struct bpf_insn_access_aux *info)
6309 {
6310 	const struct btf_type *t = prog->aux->attach_func_proto;
6311 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
6312 	struct btf *btf = bpf_prog_get_target_btf(prog);
6313 	const char *tname = prog->aux->attach_func_name;
6314 	struct bpf_verifier_log *log = info->log;
6315 	const struct btf_param *args;
6316 	const char *tag_value;
6317 	u32 nr_args, arg;
6318 	int i, ret;
6319 
6320 	if (off % 8) {
6321 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
6322 			tname, off);
6323 		return false;
6324 	}
6325 	arg = get_ctx_arg_idx(btf, t, off);
6326 	args = (const struct btf_param *)(t + 1);
6327 	/* if (t == NULL) Fall back to default BPF prog with
6328 	 * MAX_BPF_FUNC_REG_ARGS u64 arguments.
6329 	 */
6330 	nr_args = t ? btf_type_vlen(t) : MAX_BPF_FUNC_REG_ARGS;
6331 	if (prog->aux->attach_btf_trace) {
6332 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
6333 		args++;
6334 		nr_args--;
6335 	}
6336 
6337 	if (arg > nr_args) {
6338 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6339 			tname, arg + 1);
6340 		return false;
6341 	}
6342 
6343 	if (arg == nr_args) {
6344 		switch (prog->expected_attach_type) {
6345 		case BPF_LSM_CGROUP:
6346 		case BPF_LSM_MAC:
6347 		case BPF_TRACE_FEXIT:
6348 			/* When LSM programs are attached to void LSM hooks
6349 			 * they use FEXIT trampolines and when attached to
6350 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
6351 			 *
6352 			 * While the LSM programs are BPF_MODIFY_RETURN-like
6353 			 * the check:
6354 			 *
6355 			 *	if (ret_type != 'int')
6356 			 *		return -EINVAL;
6357 			 *
6358 			 * is _not_ done here. This is still safe as LSM hooks
6359 			 * have only void and int return types.
6360 			 */
6361 			if (!t)
6362 				return true;
6363 			t = btf_type_by_id(btf, t->type);
6364 			break;
6365 		case BPF_MODIFY_RETURN:
6366 			/* For now the BPF_MODIFY_RETURN can only be attached to
6367 			 * functions that return an int.
6368 			 */
6369 			if (!t)
6370 				return false;
6371 
6372 			t = btf_type_skip_modifiers(btf, t->type, NULL);
6373 			if (!btf_type_is_small_int(t)) {
6374 				bpf_log(log,
6375 					"ret type %s not allowed for fmod_ret\n",
6376 					btf_type_str(t));
6377 				return false;
6378 			}
6379 			break;
6380 		default:
6381 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
6382 				tname, arg + 1);
6383 			return false;
6384 		}
6385 	} else {
6386 		if (!t)
6387 			/* Default prog with MAX_BPF_FUNC_REG_ARGS args */
6388 			return true;
6389 		t = btf_type_by_id(btf, args[arg].type);
6390 	}
6391 
6392 	/* skip modifiers */
6393 	while (btf_type_is_modifier(t))
6394 		t = btf_type_by_id(btf, t->type);
6395 	if (btf_type_is_small_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6396 		/* accessing a scalar */
6397 		return true;
6398 	if (!btf_type_is_ptr(t)) {
6399 		bpf_log(log,
6400 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
6401 			tname, arg,
6402 			__btf_name_by_offset(btf, t->name_off),
6403 			btf_type_str(t));
6404 		return false;
6405 	}
6406 
6407 	/* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
6408 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6409 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6410 		u32 type, flag;
6411 
6412 		type = base_type(ctx_arg_info->reg_type);
6413 		flag = type_flag(ctx_arg_info->reg_type);
6414 		if (ctx_arg_info->offset == off && type == PTR_TO_BUF &&
6415 		    (flag & PTR_MAYBE_NULL)) {
6416 			info->reg_type = ctx_arg_info->reg_type;
6417 			return true;
6418 		}
6419 	}
6420 
6421 	if (t->type == 0)
6422 		/* This is a pointer to void.
6423 		 * It is the same as scalar from the verifier safety pov.
6424 		 * No further pointer walking is allowed.
6425 		 */
6426 		return true;
6427 
6428 	if (is_int_ptr(btf, t))
6429 		return true;
6430 
6431 	/* this is a pointer to another type */
6432 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
6433 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
6434 
6435 		if (ctx_arg_info->offset == off) {
6436 			if (!ctx_arg_info->btf_id) {
6437 				bpf_log(log,"invalid btf_id for context argument offset %u\n", off);
6438 				return false;
6439 			}
6440 
6441 			info->reg_type = ctx_arg_info->reg_type;
6442 			info->btf = ctx_arg_info->btf ? : btf_vmlinux;
6443 			info->btf_id = ctx_arg_info->btf_id;
6444 			return true;
6445 		}
6446 	}
6447 
6448 	info->reg_type = PTR_TO_BTF_ID;
6449 	if (prog_args_trusted(prog))
6450 		info->reg_type |= PTR_TRUSTED;
6451 
6452 	if (tgt_prog) {
6453 		enum bpf_prog_type tgt_type;
6454 
6455 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
6456 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
6457 		else
6458 			tgt_type = tgt_prog->type;
6459 
6460 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
6461 		if (ret > 0) {
6462 			info->btf = btf_vmlinux;
6463 			info->btf_id = ret;
6464 			return true;
6465 		} else {
6466 			return false;
6467 		}
6468 	}
6469 
6470 	info->btf = btf;
6471 	info->btf_id = t->type;
6472 	t = btf_type_by_id(btf, t->type);
6473 
6474 	if (btf_type_is_type_tag(t)) {
6475 		tag_value = __btf_name_by_offset(btf, t->name_off);
6476 		if (strcmp(tag_value, "user") == 0)
6477 			info->reg_type |= MEM_USER;
6478 		if (strcmp(tag_value, "percpu") == 0)
6479 			info->reg_type |= MEM_PERCPU;
6480 	}
6481 
6482 	/* skip modifiers */
6483 	while (btf_type_is_modifier(t)) {
6484 		info->btf_id = t->type;
6485 		t = btf_type_by_id(btf, t->type);
6486 	}
6487 	if (!btf_type_is_struct(t)) {
6488 		bpf_log(log,
6489 			"func '%s' arg%d type %s is not a struct\n",
6490 			tname, arg, btf_type_str(t));
6491 		return false;
6492 	}
6493 	bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
6494 		tname, arg, info->btf_id, btf_type_str(t),
6495 		__btf_name_by_offset(btf, t->name_off));
6496 	return true;
6497 }
6498 EXPORT_SYMBOL_GPL(btf_ctx_access);
6499 
6500 enum bpf_struct_walk_result {
6501 	/* < 0 error */
6502 	WALK_SCALAR = 0,
6503 	WALK_PTR,
6504 	WALK_STRUCT,
6505 };
6506 
6507 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
6508 			   const struct btf_type *t, int off, int size,
6509 			   u32 *next_btf_id, enum bpf_type_flag *flag,
6510 			   const char **field_name)
6511 {
6512 	u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
6513 	const struct btf_type *mtype, *elem_type = NULL;
6514 	const struct btf_member *member;
6515 	const char *tname, *mname, *tag_value;
6516 	u32 vlen, elem_id, mid;
6517 
6518 again:
6519 	if (btf_type_is_modifier(t))
6520 		t = btf_type_skip_modifiers(btf, t->type, NULL);
6521 	tname = __btf_name_by_offset(btf, t->name_off);
6522 	if (!btf_type_is_struct(t)) {
6523 		bpf_log(log, "Type '%s' is not a struct\n", tname);
6524 		return -EINVAL;
6525 	}
6526 
6527 	vlen = btf_type_vlen(t);
6528 	if (BTF_INFO_KIND(t->info) == BTF_KIND_UNION && vlen != 1 && !(*flag & PTR_UNTRUSTED))
6529 		/*
6530 		 * walking unions yields untrusted pointers
6531 		 * with exception of __bpf_md_ptr and other
6532 		 * unions with a single member
6533 		 */
6534 		*flag |= PTR_UNTRUSTED;
6535 
6536 	if (off + size > t->size) {
6537 		/* If the last element is a variable size array, we may
6538 		 * need to relax the rule.
6539 		 */
6540 		struct btf_array *array_elem;
6541 
6542 		if (vlen == 0)
6543 			goto error;
6544 
6545 		member = btf_type_member(t) + vlen - 1;
6546 		mtype = btf_type_skip_modifiers(btf, member->type,
6547 						NULL);
6548 		if (!btf_type_is_array(mtype))
6549 			goto error;
6550 
6551 		array_elem = (struct btf_array *)(mtype + 1);
6552 		if (array_elem->nelems != 0)
6553 			goto error;
6554 
6555 		moff = __btf_member_bit_offset(t, member) / 8;
6556 		if (off < moff)
6557 			goto error;
6558 
6559 		/* allow structure and integer */
6560 		t = btf_type_skip_modifiers(btf, array_elem->type,
6561 					    NULL);
6562 
6563 		if (btf_type_is_int(t))
6564 			return WALK_SCALAR;
6565 
6566 		if (!btf_type_is_struct(t))
6567 			goto error;
6568 
6569 		off = (off - moff) % t->size;
6570 		goto again;
6571 
6572 error:
6573 		bpf_log(log, "access beyond struct %s at off %u size %u\n",
6574 			tname, off, size);
6575 		return -EACCES;
6576 	}
6577 
6578 	for_each_member(i, t, member) {
6579 		/* offset of the field in bytes */
6580 		moff = __btf_member_bit_offset(t, member) / 8;
6581 		if (off + size <= moff)
6582 			/* won't find anything, field is already too far */
6583 			break;
6584 
6585 		if (__btf_member_bitfield_size(t, member)) {
6586 			u32 end_bit = __btf_member_bit_offset(t, member) +
6587 				__btf_member_bitfield_size(t, member);
6588 
6589 			/* off <= moff instead of off == moff because clang
6590 			 * does not generate a BTF member for anonymous
6591 			 * bitfield like the ":16" here:
6592 			 * struct {
6593 			 *	int :16;
6594 			 *	int x:8;
6595 			 * };
6596 			 */
6597 			if (off <= moff &&
6598 			    BITS_ROUNDUP_BYTES(end_bit) <= off + size)
6599 				return WALK_SCALAR;
6600 
6601 			/* off may be accessing a following member
6602 			 *
6603 			 * or
6604 			 *
6605 			 * Doing partial access at either end of this
6606 			 * bitfield.  Continue on this case also to
6607 			 * treat it as not accessing this bitfield
6608 			 * and eventually error out as field not
6609 			 * found to keep it simple.
6610 			 * It could be relaxed if there was a legit
6611 			 * partial access case later.
6612 			 */
6613 			continue;
6614 		}
6615 
6616 		/* In case of "off" is pointing to holes of a struct */
6617 		if (off < moff)
6618 			break;
6619 
6620 		/* type of the field */
6621 		mid = member->type;
6622 		mtype = btf_type_by_id(btf, member->type);
6623 		mname = __btf_name_by_offset(btf, member->name_off);
6624 
6625 		mtype = __btf_resolve_size(btf, mtype, &msize,
6626 					   &elem_type, &elem_id, &total_nelems,
6627 					   &mid);
6628 		if (IS_ERR(mtype)) {
6629 			bpf_log(log, "field %s doesn't have size\n", mname);
6630 			return -EFAULT;
6631 		}
6632 
6633 		mtrue_end = moff + msize;
6634 		if (off >= mtrue_end)
6635 			/* no overlap with member, keep iterating */
6636 			continue;
6637 
6638 		if (btf_type_is_array(mtype)) {
6639 			u32 elem_idx;
6640 
6641 			/* __btf_resolve_size() above helps to
6642 			 * linearize a multi-dimensional array.
6643 			 *
6644 			 * The logic here is treating an array
6645 			 * in a struct as the following way:
6646 			 *
6647 			 * struct outer {
6648 			 *	struct inner array[2][2];
6649 			 * };
6650 			 *
6651 			 * looks like:
6652 			 *
6653 			 * struct outer {
6654 			 *	struct inner array_elem0;
6655 			 *	struct inner array_elem1;
6656 			 *	struct inner array_elem2;
6657 			 *	struct inner array_elem3;
6658 			 * };
6659 			 *
6660 			 * When accessing outer->array[1][0], it moves
6661 			 * moff to "array_elem2", set mtype to
6662 			 * "struct inner", and msize also becomes
6663 			 * sizeof(struct inner).  Then most of the
6664 			 * remaining logic will fall through without
6665 			 * caring the current member is an array or
6666 			 * not.
6667 			 *
6668 			 * Unlike mtype/msize/moff, mtrue_end does not
6669 			 * change.  The naming difference ("_true") tells
6670 			 * that it is not always corresponding to
6671 			 * the current mtype/msize/moff.
6672 			 * It is the true end of the current
6673 			 * member (i.e. array in this case).  That
6674 			 * will allow an int array to be accessed like
6675 			 * a scratch space,
6676 			 * i.e. allow access beyond the size of
6677 			 *      the array's element as long as it is
6678 			 *      within the mtrue_end boundary.
6679 			 */
6680 
6681 			/* skip empty array */
6682 			if (moff == mtrue_end)
6683 				continue;
6684 
6685 			msize /= total_nelems;
6686 			elem_idx = (off - moff) / msize;
6687 			moff += elem_idx * msize;
6688 			mtype = elem_type;
6689 			mid = elem_id;
6690 		}
6691 
6692 		/* the 'off' we're looking for is either equal to start
6693 		 * of this field or inside of this struct
6694 		 */
6695 		if (btf_type_is_struct(mtype)) {
6696 			/* our field must be inside that union or struct */
6697 			t = mtype;
6698 
6699 			/* return if the offset matches the member offset */
6700 			if (off == moff) {
6701 				*next_btf_id = mid;
6702 				return WALK_STRUCT;
6703 			}
6704 
6705 			/* adjust offset we're looking for */
6706 			off -= moff;
6707 			goto again;
6708 		}
6709 
6710 		if (btf_type_is_ptr(mtype)) {
6711 			const struct btf_type *stype, *t;
6712 			enum bpf_type_flag tmp_flag = 0;
6713 			u32 id;
6714 
6715 			if (msize != size || off != moff) {
6716 				bpf_log(log,
6717 					"cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
6718 					mname, moff, tname, off, size);
6719 				return -EACCES;
6720 			}
6721 
6722 			/* check type tag */
6723 			t = btf_type_by_id(btf, mtype->type);
6724 			if (btf_type_is_type_tag(t)) {
6725 				tag_value = __btf_name_by_offset(btf, t->name_off);
6726 				/* check __user tag */
6727 				if (strcmp(tag_value, "user") == 0)
6728 					tmp_flag = MEM_USER;
6729 				/* check __percpu tag */
6730 				if (strcmp(tag_value, "percpu") == 0)
6731 					tmp_flag = MEM_PERCPU;
6732 				/* check __rcu tag */
6733 				if (strcmp(tag_value, "rcu") == 0)
6734 					tmp_flag = MEM_RCU;
6735 			}
6736 
6737 			stype = btf_type_skip_modifiers(btf, mtype->type, &id);
6738 			if (btf_type_is_struct(stype)) {
6739 				*next_btf_id = id;
6740 				*flag |= tmp_flag;
6741 				if (field_name)
6742 					*field_name = mname;
6743 				return WALK_PTR;
6744 			}
6745 		}
6746 
6747 		/* Allow more flexible access within an int as long as
6748 		 * it is within mtrue_end.
6749 		 * Since mtrue_end could be the end of an array,
6750 		 * that also allows using an array of int as a scratch
6751 		 * space. e.g. skb->cb[].
6752 		 */
6753 		if (off + size > mtrue_end && !(*flag & PTR_UNTRUSTED)) {
6754 			bpf_log(log,
6755 				"access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
6756 				mname, mtrue_end, tname, off, size);
6757 			return -EACCES;
6758 		}
6759 
6760 		return WALK_SCALAR;
6761 	}
6762 	bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
6763 	return -EINVAL;
6764 }
6765 
6766 int btf_struct_access(struct bpf_verifier_log *log,
6767 		      const struct bpf_reg_state *reg,
6768 		      int off, int size, enum bpf_access_type atype __maybe_unused,
6769 		      u32 *next_btf_id, enum bpf_type_flag *flag,
6770 		      const char **field_name)
6771 {
6772 	const struct btf *btf = reg->btf;
6773 	enum bpf_type_flag tmp_flag = 0;
6774 	const struct btf_type *t;
6775 	u32 id = reg->btf_id;
6776 	int err;
6777 
6778 	while (type_is_alloc(reg->type)) {
6779 		struct btf_struct_meta *meta;
6780 		struct btf_record *rec;
6781 		int i;
6782 
6783 		meta = btf_find_struct_meta(btf, id);
6784 		if (!meta)
6785 			break;
6786 		rec = meta->record;
6787 		for (i = 0; i < rec->cnt; i++) {
6788 			struct btf_field *field = &rec->fields[i];
6789 			u32 offset = field->offset;
6790 			if (off < offset + field->size && offset < off + size) {
6791 				bpf_log(log,
6792 					"direct access to %s is disallowed\n",
6793 					btf_field_type_name(field->type));
6794 				return -EACCES;
6795 			}
6796 		}
6797 		break;
6798 	}
6799 
6800 	t = btf_type_by_id(btf, id);
6801 	do {
6802 		err = btf_struct_walk(log, btf, t, off, size, &id, &tmp_flag, field_name);
6803 
6804 		switch (err) {
6805 		case WALK_PTR:
6806 			/* For local types, the destination register cannot
6807 			 * become a pointer again.
6808 			 */
6809 			if (type_is_alloc(reg->type))
6810 				return SCALAR_VALUE;
6811 			/* If we found the pointer or scalar on t+off,
6812 			 * we're done.
6813 			 */
6814 			*next_btf_id = id;
6815 			*flag = tmp_flag;
6816 			return PTR_TO_BTF_ID;
6817 		case WALK_SCALAR:
6818 			return SCALAR_VALUE;
6819 		case WALK_STRUCT:
6820 			/* We found nested struct, so continue the search
6821 			 * by diving in it. At this point the offset is
6822 			 * aligned with the new type, so set it to 0.
6823 			 */
6824 			t = btf_type_by_id(btf, id);
6825 			off = 0;
6826 			break;
6827 		default:
6828 			/* It's either error or unknown return value..
6829 			 * scream and leave.
6830 			 */
6831 			if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
6832 				return -EINVAL;
6833 			return err;
6834 		}
6835 	} while (t);
6836 
6837 	return -EINVAL;
6838 }
6839 
6840 /* Check that two BTF types, each specified as an BTF object + id, are exactly
6841  * the same. Trivial ID check is not enough due to module BTFs, because we can
6842  * end up with two different module BTFs, but IDs point to the common type in
6843  * vmlinux BTF.
6844  */
6845 bool btf_types_are_same(const struct btf *btf1, u32 id1,
6846 			const struct btf *btf2, u32 id2)
6847 {
6848 	if (id1 != id2)
6849 		return false;
6850 	if (btf1 == btf2)
6851 		return true;
6852 	return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
6853 }
6854 
6855 bool btf_struct_ids_match(struct bpf_verifier_log *log,
6856 			  const struct btf *btf, u32 id, int off,
6857 			  const struct btf *need_btf, u32 need_type_id,
6858 			  bool strict)
6859 {
6860 	const struct btf_type *type;
6861 	enum bpf_type_flag flag = 0;
6862 	int err;
6863 
6864 	/* Are we already done? */
6865 	if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
6866 		return true;
6867 	/* In case of strict type match, we do not walk struct, the top level
6868 	 * type match must succeed. When strict is true, off should have already
6869 	 * been 0.
6870 	 */
6871 	if (strict)
6872 		return false;
6873 again:
6874 	type = btf_type_by_id(btf, id);
6875 	if (!type)
6876 		return false;
6877 	err = btf_struct_walk(log, btf, type, off, 1, &id, &flag, NULL);
6878 	if (err != WALK_STRUCT)
6879 		return false;
6880 
6881 	/* We found nested struct object. If it matches
6882 	 * the requested ID, we're done. Otherwise let's
6883 	 * continue the search with offset 0 in the new
6884 	 * type.
6885 	 */
6886 	if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
6887 		off = 0;
6888 		goto again;
6889 	}
6890 
6891 	return true;
6892 }
6893 
6894 static int __get_type_size(struct btf *btf, u32 btf_id,
6895 			   const struct btf_type **ret_type)
6896 {
6897 	const struct btf_type *t;
6898 
6899 	*ret_type = btf_type_by_id(btf, 0);
6900 	if (!btf_id)
6901 		/* void */
6902 		return 0;
6903 	t = btf_type_by_id(btf, btf_id);
6904 	while (t && btf_type_is_modifier(t))
6905 		t = btf_type_by_id(btf, t->type);
6906 	if (!t)
6907 		return -EINVAL;
6908 	*ret_type = t;
6909 	if (btf_type_is_ptr(t))
6910 		/* kernel size of pointer. Not BPF's size of pointer*/
6911 		return sizeof(void *);
6912 	if (btf_type_is_int(t) || btf_is_any_enum(t) || __btf_type_is_struct(t))
6913 		return t->size;
6914 	return -EINVAL;
6915 }
6916 
6917 static u8 __get_type_fmodel_flags(const struct btf_type *t)
6918 {
6919 	u8 flags = 0;
6920 
6921 	if (__btf_type_is_struct(t))
6922 		flags |= BTF_FMODEL_STRUCT_ARG;
6923 	if (btf_type_is_signed_int(t))
6924 		flags |= BTF_FMODEL_SIGNED_ARG;
6925 
6926 	return flags;
6927 }
6928 
6929 int btf_distill_func_proto(struct bpf_verifier_log *log,
6930 			   struct btf *btf,
6931 			   const struct btf_type *func,
6932 			   const char *tname,
6933 			   struct btf_func_model *m)
6934 {
6935 	const struct btf_param *args;
6936 	const struct btf_type *t;
6937 	u32 i, nargs;
6938 	int ret;
6939 
6940 	if (!func) {
6941 		/* BTF function prototype doesn't match the verifier types.
6942 		 * Fall back to MAX_BPF_FUNC_REG_ARGS u64 args.
6943 		 */
6944 		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
6945 			m->arg_size[i] = 8;
6946 			m->arg_flags[i] = 0;
6947 		}
6948 		m->ret_size = 8;
6949 		m->ret_flags = 0;
6950 		m->nr_args = MAX_BPF_FUNC_REG_ARGS;
6951 		return 0;
6952 	}
6953 	args = (const struct btf_param *)(func + 1);
6954 	nargs = btf_type_vlen(func);
6955 	if (nargs > MAX_BPF_FUNC_ARGS) {
6956 		bpf_log(log,
6957 			"The function %s has %d arguments. Too many.\n",
6958 			tname, nargs);
6959 		return -EINVAL;
6960 	}
6961 	ret = __get_type_size(btf, func->type, &t);
6962 	if (ret < 0 || __btf_type_is_struct(t)) {
6963 		bpf_log(log,
6964 			"The function %s return type %s is unsupported.\n",
6965 			tname, btf_type_str(t));
6966 		return -EINVAL;
6967 	}
6968 	m->ret_size = ret;
6969 	m->ret_flags = __get_type_fmodel_flags(t);
6970 
6971 	for (i = 0; i < nargs; i++) {
6972 		if (i == nargs - 1 && args[i].type == 0) {
6973 			bpf_log(log,
6974 				"The function %s with variable args is unsupported.\n",
6975 				tname);
6976 			return -EINVAL;
6977 		}
6978 		ret = __get_type_size(btf, args[i].type, &t);
6979 
6980 		/* No support of struct argument size greater than 16 bytes */
6981 		if (ret < 0 || ret > 16) {
6982 			bpf_log(log,
6983 				"The function %s arg%d type %s is unsupported.\n",
6984 				tname, i, btf_type_str(t));
6985 			return -EINVAL;
6986 		}
6987 		if (ret == 0) {
6988 			bpf_log(log,
6989 				"The function %s has malformed void argument.\n",
6990 				tname);
6991 			return -EINVAL;
6992 		}
6993 		m->arg_size[i] = ret;
6994 		m->arg_flags[i] = __get_type_fmodel_flags(t);
6995 	}
6996 	m->nr_args = nargs;
6997 	return 0;
6998 }
6999 
7000 /* Compare BTFs of two functions assuming only scalars and pointers to context.
7001  * t1 points to BTF_KIND_FUNC in btf1
7002  * t2 points to BTF_KIND_FUNC in btf2
7003  * Returns:
7004  * EINVAL - function prototype mismatch
7005  * EFAULT - verifier bug
7006  * 0 - 99% match. The last 1% is validated by the verifier.
7007  */
7008 static int btf_check_func_type_match(struct bpf_verifier_log *log,
7009 				     struct btf *btf1, const struct btf_type *t1,
7010 				     struct btf *btf2, const struct btf_type *t2)
7011 {
7012 	const struct btf_param *args1, *args2;
7013 	const char *fn1, *fn2, *s1, *s2;
7014 	u32 nargs1, nargs2, i;
7015 
7016 	fn1 = btf_name_by_offset(btf1, t1->name_off);
7017 	fn2 = btf_name_by_offset(btf2, t2->name_off);
7018 
7019 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
7020 		bpf_log(log, "%s() is not a global function\n", fn1);
7021 		return -EINVAL;
7022 	}
7023 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
7024 		bpf_log(log, "%s() is not a global function\n", fn2);
7025 		return -EINVAL;
7026 	}
7027 
7028 	t1 = btf_type_by_id(btf1, t1->type);
7029 	if (!t1 || !btf_type_is_func_proto(t1))
7030 		return -EFAULT;
7031 	t2 = btf_type_by_id(btf2, t2->type);
7032 	if (!t2 || !btf_type_is_func_proto(t2))
7033 		return -EFAULT;
7034 
7035 	args1 = (const struct btf_param *)(t1 + 1);
7036 	nargs1 = btf_type_vlen(t1);
7037 	args2 = (const struct btf_param *)(t2 + 1);
7038 	nargs2 = btf_type_vlen(t2);
7039 
7040 	if (nargs1 != nargs2) {
7041 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
7042 			fn1, nargs1, fn2, nargs2);
7043 		return -EINVAL;
7044 	}
7045 
7046 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
7047 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
7048 	if (t1->info != t2->info) {
7049 		bpf_log(log,
7050 			"Return type %s of %s() doesn't match type %s of %s()\n",
7051 			btf_type_str(t1), fn1,
7052 			btf_type_str(t2), fn2);
7053 		return -EINVAL;
7054 	}
7055 
7056 	for (i = 0; i < nargs1; i++) {
7057 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
7058 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
7059 
7060 		if (t1->info != t2->info) {
7061 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
7062 				i, fn1, btf_type_str(t1),
7063 				fn2, btf_type_str(t2));
7064 			return -EINVAL;
7065 		}
7066 		if (btf_type_has_size(t1) && t1->size != t2->size) {
7067 			bpf_log(log,
7068 				"arg%d in %s() has size %d while %s() has %d\n",
7069 				i, fn1, t1->size,
7070 				fn2, t2->size);
7071 			return -EINVAL;
7072 		}
7073 
7074 		/* global functions are validated with scalars and pointers
7075 		 * to context only. And only global functions can be replaced.
7076 		 * Hence type check only those types.
7077 		 */
7078 		if (btf_type_is_int(t1) || btf_is_any_enum(t1))
7079 			continue;
7080 		if (!btf_type_is_ptr(t1)) {
7081 			bpf_log(log,
7082 				"arg%d in %s() has unrecognized type\n",
7083 				i, fn1);
7084 			return -EINVAL;
7085 		}
7086 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
7087 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
7088 		if (!btf_type_is_struct(t1)) {
7089 			bpf_log(log,
7090 				"arg%d in %s() is not a pointer to context\n",
7091 				i, fn1);
7092 			return -EINVAL;
7093 		}
7094 		if (!btf_type_is_struct(t2)) {
7095 			bpf_log(log,
7096 				"arg%d in %s() is not a pointer to context\n",
7097 				i, fn2);
7098 			return -EINVAL;
7099 		}
7100 		/* This is an optional check to make program writing easier.
7101 		 * Compare names of structs and report an error to the user.
7102 		 * btf_prepare_func_args() already checked that t2 struct
7103 		 * is a context type. btf_prepare_func_args() will check
7104 		 * later that t1 struct is a context type as well.
7105 		 */
7106 		s1 = btf_name_by_offset(btf1, t1->name_off);
7107 		s2 = btf_name_by_offset(btf2, t2->name_off);
7108 		if (strcmp(s1, s2)) {
7109 			bpf_log(log,
7110 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
7111 				i, fn1, s1, fn2, s2);
7112 			return -EINVAL;
7113 		}
7114 	}
7115 	return 0;
7116 }
7117 
7118 /* Compare BTFs of given program with BTF of target program */
7119 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
7120 			 struct btf *btf2, const struct btf_type *t2)
7121 {
7122 	struct btf *btf1 = prog->aux->btf;
7123 	const struct btf_type *t1;
7124 	u32 btf_id = 0;
7125 
7126 	if (!prog->aux->func_info) {
7127 		bpf_log(log, "Program extension requires BTF\n");
7128 		return -EINVAL;
7129 	}
7130 
7131 	btf_id = prog->aux->func_info[0].type_id;
7132 	if (!btf_id)
7133 		return -EFAULT;
7134 
7135 	t1 = btf_type_by_id(btf1, btf_id);
7136 	if (!t1 || !btf_type_is_func(t1))
7137 		return -EFAULT;
7138 
7139 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
7140 }
7141 
7142 static bool btf_is_dynptr_ptr(const struct btf *btf, const struct btf_type *t)
7143 {
7144 	const char *name;
7145 
7146 	t = btf_type_by_id(btf, t->type); /* skip PTR */
7147 
7148 	while (btf_type_is_modifier(t))
7149 		t = btf_type_by_id(btf, t->type);
7150 
7151 	/* allow either struct or struct forward declaration */
7152 	if (btf_type_is_struct(t) ||
7153 	    (btf_type_is_fwd(t) && btf_type_kflag(t) == 0)) {
7154 		name = btf_str_by_offset(btf, t->name_off);
7155 		return name && strcmp(name, "bpf_dynptr") == 0;
7156 	}
7157 
7158 	return false;
7159 }
7160 
7161 struct bpf_cand_cache {
7162 	const char *name;
7163 	u32 name_len;
7164 	u16 kind;
7165 	u16 cnt;
7166 	struct {
7167 		const struct btf *btf;
7168 		u32 id;
7169 	} cands[];
7170 };
7171 
7172 static DEFINE_MUTEX(cand_cache_mutex);
7173 
7174 static struct bpf_cand_cache *
7175 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id);
7176 
7177 static int btf_get_ptr_to_btf_id(struct bpf_verifier_log *log, int arg_idx,
7178 				 const struct btf *btf, const struct btf_type *t)
7179 {
7180 	struct bpf_cand_cache *cc;
7181 	struct bpf_core_ctx ctx = {
7182 		.btf = btf,
7183 		.log = log,
7184 	};
7185 	u32 kern_type_id, type_id;
7186 	int err = 0;
7187 
7188 	/* skip PTR and modifiers */
7189 	type_id = t->type;
7190 	t = btf_type_by_id(btf, t->type);
7191 	while (btf_type_is_modifier(t)) {
7192 		type_id = t->type;
7193 		t = btf_type_by_id(btf, t->type);
7194 	}
7195 
7196 	mutex_lock(&cand_cache_mutex);
7197 	cc = bpf_core_find_cands(&ctx, type_id);
7198 	if (IS_ERR(cc)) {
7199 		err = PTR_ERR(cc);
7200 		bpf_log(log, "arg#%d reference type('%s %s') candidate matching error: %d\n",
7201 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7202 			err);
7203 		goto cand_cache_unlock;
7204 	}
7205 	if (cc->cnt != 1) {
7206 		bpf_log(log, "arg#%d reference type('%s %s') %s\n",
7207 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off),
7208 			cc->cnt == 0 ? "has no matches" : "is ambiguous");
7209 		err = cc->cnt == 0 ? -ENOENT : -ESRCH;
7210 		goto cand_cache_unlock;
7211 	}
7212 	if (btf_is_module(cc->cands[0].btf)) {
7213 		bpf_log(log, "arg#%d reference type('%s %s') points to kernel module type (unsupported)\n",
7214 			arg_idx, btf_type_str(t), __btf_name_by_offset(btf, t->name_off));
7215 		err = -EOPNOTSUPP;
7216 		goto cand_cache_unlock;
7217 	}
7218 	kern_type_id = cc->cands[0].id;
7219 
7220 cand_cache_unlock:
7221 	mutex_unlock(&cand_cache_mutex);
7222 	if (err)
7223 		return err;
7224 
7225 	return kern_type_id;
7226 }
7227 
7228 enum btf_arg_tag {
7229 	ARG_TAG_CTX	 = BIT_ULL(0),
7230 	ARG_TAG_NONNULL  = BIT_ULL(1),
7231 	ARG_TAG_TRUSTED  = BIT_ULL(2),
7232 	ARG_TAG_NULLABLE = BIT_ULL(3),
7233 	ARG_TAG_ARENA	 = BIT_ULL(4),
7234 };
7235 
7236 /* Process BTF of a function to produce high-level expectation of function
7237  * arguments (like ARG_PTR_TO_CTX, or ARG_PTR_TO_MEM, etc). This information
7238  * is cached in subprog info for reuse.
7239  * Returns:
7240  * EFAULT - there is a verifier bug. Abort verification.
7241  * EINVAL - cannot convert BTF.
7242  * 0 - Successfully processed BTF and constructed argument expectations.
7243  */
7244 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog)
7245 {
7246 	bool is_global = subprog_aux(env, subprog)->linkage == BTF_FUNC_GLOBAL;
7247 	struct bpf_subprog_info *sub = subprog_info(env, subprog);
7248 	struct bpf_verifier_log *log = &env->log;
7249 	struct bpf_prog *prog = env->prog;
7250 	enum bpf_prog_type prog_type = prog->type;
7251 	struct btf *btf = prog->aux->btf;
7252 	const struct btf_param *args;
7253 	const struct btf_type *t, *ref_t, *fn_t;
7254 	u32 i, nargs, btf_id;
7255 	const char *tname;
7256 
7257 	if (sub->args_cached)
7258 		return 0;
7259 
7260 	if (!prog->aux->func_info) {
7261 		bpf_log(log, "Verifier bug\n");
7262 		return -EFAULT;
7263 	}
7264 
7265 	btf_id = prog->aux->func_info[subprog].type_id;
7266 	if (!btf_id) {
7267 		if (!is_global) /* not fatal for static funcs */
7268 			return -EINVAL;
7269 		bpf_log(log, "Global functions need valid BTF\n");
7270 		return -EFAULT;
7271 	}
7272 
7273 	fn_t = btf_type_by_id(btf, btf_id);
7274 	if (!fn_t || !btf_type_is_func(fn_t)) {
7275 		/* These checks were already done by the verifier while loading
7276 		 * struct bpf_func_info
7277 		 */
7278 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
7279 			subprog);
7280 		return -EFAULT;
7281 	}
7282 	tname = btf_name_by_offset(btf, fn_t->name_off);
7283 
7284 	if (prog->aux->func_info_aux[subprog].unreliable) {
7285 		bpf_log(log, "Verifier bug in function %s()\n", tname);
7286 		return -EFAULT;
7287 	}
7288 	if (prog_type == BPF_PROG_TYPE_EXT)
7289 		prog_type = prog->aux->dst_prog->type;
7290 
7291 	t = btf_type_by_id(btf, fn_t->type);
7292 	if (!t || !btf_type_is_func_proto(t)) {
7293 		bpf_log(log, "Invalid type of function %s()\n", tname);
7294 		return -EFAULT;
7295 	}
7296 	args = (const struct btf_param *)(t + 1);
7297 	nargs = btf_type_vlen(t);
7298 	if (nargs > MAX_BPF_FUNC_REG_ARGS) {
7299 		if (!is_global)
7300 			return -EINVAL;
7301 		bpf_log(log, "Global function %s() with %d > %d args. Buggy compiler.\n",
7302 			tname, nargs, MAX_BPF_FUNC_REG_ARGS);
7303 		return -EINVAL;
7304 	}
7305 	/* check that function returns int, exception cb also requires this */
7306 	t = btf_type_by_id(btf, t->type);
7307 	while (btf_type_is_modifier(t))
7308 		t = btf_type_by_id(btf, t->type);
7309 	if (!btf_type_is_int(t) && !btf_is_any_enum(t)) {
7310 		if (!is_global)
7311 			return -EINVAL;
7312 		bpf_log(log,
7313 			"Global function %s() doesn't return scalar. Only those are supported.\n",
7314 			tname);
7315 		return -EINVAL;
7316 	}
7317 	/* Convert BTF function arguments into verifier types.
7318 	 * Only PTR_TO_CTX and SCALAR are supported atm.
7319 	 */
7320 	for (i = 0; i < nargs; i++) {
7321 		u32 tags = 0;
7322 		int id = 0;
7323 
7324 		/* 'arg:<tag>' decl_tag takes precedence over derivation of
7325 		 * register type from BTF type itself
7326 		 */
7327 		while ((id = btf_find_next_decl_tag(btf, fn_t, i, "arg:", id)) > 0) {
7328 			const struct btf_type *tag_t = btf_type_by_id(btf, id);
7329 			const char *tag = __btf_name_by_offset(btf, tag_t->name_off) + 4;
7330 
7331 			/* disallow arg tags in static subprogs */
7332 			if (!is_global) {
7333 				bpf_log(log, "arg#%d type tag is not supported in static functions\n", i);
7334 				return -EOPNOTSUPP;
7335 			}
7336 
7337 			if (strcmp(tag, "ctx") == 0) {
7338 				tags |= ARG_TAG_CTX;
7339 			} else if (strcmp(tag, "trusted") == 0) {
7340 				tags |= ARG_TAG_TRUSTED;
7341 			} else if (strcmp(tag, "nonnull") == 0) {
7342 				tags |= ARG_TAG_NONNULL;
7343 			} else if (strcmp(tag, "nullable") == 0) {
7344 				tags |= ARG_TAG_NULLABLE;
7345 			} else if (strcmp(tag, "arena") == 0) {
7346 				tags |= ARG_TAG_ARENA;
7347 			} else {
7348 				bpf_log(log, "arg#%d has unsupported set of tags\n", i);
7349 				return -EOPNOTSUPP;
7350 			}
7351 		}
7352 		if (id != -ENOENT) {
7353 			bpf_log(log, "arg#%d type tag fetching failure: %d\n", i, id);
7354 			return id;
7355 		}
7356 
7357 		t = btf_type_by_id(btf, args[i].type);
7358 		while (btf_type_is_modifier(t))
7359 			t = btf_type_by_id(btf, t->type);
7360 		if (!btf_type_is_ptr(t))
7361 			goto skip_pointer;
7362 
7363 		if ((tags & ARG_TAG_CTX) || btf_is_prog_ctx_type(log, btf, t, prog_type, i)) {
7364 			if (tags & ~ARG_TAG_CTX) {
7365 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7366 				return -EINVAL;
7367 			}
7368 			if ((tags & ARG_TAG_CTX) &&
7369 			    btf_validate_prog_ctx_type(log, btf, t, i, prog_type,
7370 						       prog->expected_attach_type))
7371 				return -EINVAL;
7372 			sub->args[i].arg_type = ARG_PTR_TO_CTX;
7373 			continue;
7374 		}
7375 		if (btf_is_dynptr_ptr(btf, t)) {
7376 			if (tags) {
7377 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7378 				return -EINVAL;
7379 			}
7380 			sub->args[i].arg_type = ARG_PTR_TO_DYNPTR | MEM_RDONLY;
7381 			continue;
7382 		}
7383 		if (tags & ARG_TAG_TRUSTED) {
7384 			int kern_type_id;
7385 
7386 			if (tags & ARG_TAG_NONNULL) {
7387 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7388 				return -EINVAL;
7389 			}
7390 
7391 			kern_type_id = btf_get_ptr_to_btf_id(log, i, btf, t);
7392 			if (kern_type_id < 0)
7393 				return kern_type_id;
7394 
7395 			sub->args[i].arg_type = ARG_PTR_TO_BTF_ID | PTR_TRUSTED;
7396 			if (tags & ARG_TAG_NULLABLE)
7397 				sub->args[i].arg_type |= PTR_MAYBE_NULL;
7398 			sub->args[i].btf_id = kern_type_id;
7399 			continue;
7400 		}
7401 		if (tags & ARG_TAG_ARENA) {
7402 			if (tags & ~ARG_TAG_ARENA) {
7403 				bpf_log(log, "arg#%d arena cannot be combined with any other tags\n", i);
7404 				return -EINVAL;
7405 			}
7406 			sub->args[i].arg_type = ARG_PTR_TO_ARENA;
7407 			continue;
7408 		}
7409 		if (is_global) { /* generic user data pointer */
7410 			u32 mem_size;
7411 
7412 			if (tags & ARG_TAG_NULLABLE) {
7413 				bpf_log(log, "arg#%d has invalid combination of tags\n", i);
7414 				return -EINVAL;
7415 			}
7416 
7417 			t = btf_type_skip_modifiers(btf, t->type, NULL);
7418 			ref_t = btf_resolve_size(btf, t, &mem_size);
7419 			if (IS_ERR(ref_t)) {
7420 				bpf_log(log, "arg#%d reference type('%s %s') size cannot be determined: %ld\n",
7421 					i, btf_type_str(t), btf_name_by_offset(btf, t->name_off),
7422 					PTR_ERR(ref_t));
7423 				return -EINVAL;
7424 			}
7425 
7426 			sub->args[i].arg_type = ARG_PTR_TO_MEM | PTR_MAYBE_NULL;
7427 			if (tags & ARG_TAG_NONNULL)
7428 				sub->args[i].arg_type &= ~PTR_MAYBE_NULL;
7429 			sub->args[i].mem_size = mem_size;
7430 			continue;
7431 		}
7432 
7433 skip_pointer:
7434 		if (tags) {
7435 			bpf_log(log, "arg#%d has pointer tag, but is not a pointer type\n", i);
7436 			return -EINVAL;
7437 		}
7438 		if (btf_type_is_int(t) || btf_is_any_enum(t)) {
7439 			sub->args[i].arg_type = ARG_ANYTHING;
7440 			continue;
7441 		}
7442 		if (!is_global)
7443 			return -EINVAL;
7444 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
7445 			i, btf_type_str(t), tname);
7446 		return -EINVAL;
7447 	}
7448 
7449 	sub->arg_cnt = nargs;
7450 	sub->args_cached = true;
7451 
7452 	return 0;
7453 }
7454 
7455 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
7456 			  struct btf_show *show)
7457 {
7458 	const struct btf_type *t = btf_type_by_id(btf, type_id);
7459 
7460 	show->btf = btf;
7461 	memset(&show->state, 0, sizeof(show->state));
7462 	memset(&show->obj, 0, sizeof(show->obj));
7463 
7464 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
7465 }
7466 
7467 static void btf_seq_show(struct btf_show *show, const char *fmt,
7468 			 va_list args)
7469 {
7470 	seq_vprintf((struct seq_file *)show->target, fmt, args);
7471 }
7472 
7473 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
7474 			    void *obj, struct seq_file *m, u64 flags)
7475 {
7476 	struct btf_show sseq;
7477 
7478 	sseq.target = m;
7479 	sseq.showfn = btf_seq_show;
7480 	sseq.flags = flags;
7481 
7482 	btf_type_show(btf, type_id, obj, &sseq);
7483 
7484 	return sseq.state.status;
7485 }
7486 
7487 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
7488 		       struct seq_file *m)
7489 {
7490 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
7491 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
7492 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
7493 }
7494 
7495 struct btf_show_snprintf {
7496 	struct btf_show show;
7497 	int len_left;		/* space left in string */
7498 	int len;		/* length we would have written */
7499 };
7500 
7501 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
7502 			      va_list args)
7503 {
7504 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
7505 	int len;
7506 
7507 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
7508 
7509 	if (len < 0) {
7510 		ssnprintf->len_left = 0;
7511 		ssnprintf->len = len;
7512 	} else if (len >= ssnprintf->len_left) {
7513 		/* no space, drive on to get length we would have written */
7514 		ssnprintf->len_left = 0;
7515 		ssnprintf->len += len;
7516 	} else {
7517 		ssnprintf->len_left -= len;
7518 		ssnprintf->len += len;
7519 		show->target += len;
7520 	}
7521 }
7522 
7523 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
7524 			   char *buf, int len, u64 flags)
7525 {
7526 	struct btf_show_snprintf ssnprintf;
7527 
7528 	ssnprintf.show.target = buf;
7529 	ssnprintf.show.flags = flags;
7530 	ssnprintf.show.showfn = btf_snprintf_show;
7531 	ssnprintf.len_left = len;
7532 	ssnprintf.len = 0;
7533 
7534 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
7535 
7536 	/* If we encountered an error, return it. */
7537 	if (ssnprintf.show.state.status)
7538 		return ssnprintf.show.state.status;
7539 
7540 	/* Otherwise return length we would have written */
7541 	return ssnprintf.len;
7542 }
7543 
7544 #ifdef CONFIG_PROC_FS
7545 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
7546 {
7547 	const struct btf *btf = filp->private_data;
7548 
7549 	seq_printf(m, "btf_id:\t%u\n", btf->id);
7550 }
7551 #endif
7552 
7553 static int btf_release(struct inode *inode, struct file *filp)
7554 {
7555 	btf_put(filp->private_data);
7556 	return 0;
7557 }
7558 
7559 const struct file_operations btf_fops = {
7560 #ifdef CONFIG_PROC_FS
7561 	.show_fdinfo	= bpf_btf_show_fdinfo,
7562 #endif
7563 	.release	= btf_release,
7564 };
7565 
7566 static int __btf_new_fd(struct btf *btf)
7567 {
7568 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
7569 }
7570 
7571 int btf_new_fd(const union bpf_attr *attr, bpfptr_t uattr, u32 uattr_size)
7572 {
7573 	struct btf *btf;
7574 	int ret;
7575 
7576 	btf = btf_parse(attr, uattr, uattr_size);
7577 	if (IS_ERR(btf))
7578 		return PTR_ERR(btf);
7579 
7580 	ret = btf_alloc_id(btf);
7581 	if (ret) {
7582 		btf_free(btf);
7583 		return ret;
7584 	}
7585 
7586 	/*
7587 	 * The BTF ID is published to the userspace.
7588 	 * All BTF free must go through call_rcu() from
7589 	 * now on (i.e. free by calling btf_put()).
7590 	 */
7591 
7592 	ret = __btf_new_fd(btf);
7593 	if (ret < 0)
7594 		btf_put(btf);
7595 
7596 	return ret;
7597 }
7598 
7599 struct btf *btf_get_by_fd(int fd)
7600 {
7601 	struct btf *btf;
7602 	struct fd f;
7603 
7604 	f = fdget(fd);
7605 
7606 	if (!f.file)
7607 		return ERR_PTR(-EBADF);
7608 
7609 	if (f.file->f_op != &btf_fops) {
7610 		fdput(f);
7611 		return ERR_PTR(-EINVAL);
7612 	}
7613 
7614 	btf = f.file->private_data;
7615 	refcount_inc(&btf->refcnt);
7616 	fdput(f);
7617 
7618 	return btf;
7619 }
7620 
7621 int btf_get_info_by_fd(const struct btf *btf,
7622 		       const union bpf_attr *attr,
7623 		       union bpf_attr __user *uattr)
7624 {
7625 	struct bpf_btf_info __user *uinfo;
7626 	struct bpf_btf_info info;
7627 	u32 info_copy, btf_copy;
7628 	void __user *ubtf;
7629 	char __user *uname;
7630 	u32 uinfo_len, uname_len, name_len;
7631 	int ret = 0;
7632 
7633 	uinfo = u64_to_user_ptr(attr->info.info);
7634 	uinfo_len = attr->info.info_len;
7635 
7636 	info_copy = min_t(u32, uinfo_len, sizeof(info));
7637 	memset(&info, 0, sizeof(info));
7638 	if (copy_from_user(&info, uinfo, info_copy))
7639 		return -EFAULT;
7640 
7641 	info.id = btf->id;
7642 	ubtf = u64_to_user_ptr(info.btf);
7643 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
7644 	if (copy_to_user(ubtf, btf->data, btf_copy))
7645 		return -EFAULT;
7646 	info.btf_size = btf->data_size;
7647 
7648 	info.kernel_btf = btf->kernel_btf;
7649 
7650 	uname = u64_to_user_ptr(info.name);
7651 	uname_len = info.name_len;
7652 	if (!uname ^ !uname_len)
7653 		return -EINVAL;
7654 
7655 	name_len = strlen(btf->name);
7656 	info.name_len = name_len;
7657 
7658 	if (uname) {
7659 		if (uname_len >= name_len + 1) {
7660 			if (copy_to_user(uname, btf->name, name_len + 1))
7661 				return -EFAULT;
7662 		} else {
7663 			char zero = '\0';
7664 
7665 			if (copy_to_user(uname, btf->name, uname_len - 1))
7666 				return -EFAULT;
7667 			if (put_user(zero, uname + uname_len - 1))
7668 				return -EFAULT;
7669 			/* let user-space know about too short buffer */
7670 			ret = -ENOSPC;
7671 		}
7672 	}
7673 
7674 	if (copy_to_user(uinfo, &info, info_copy) ||
7675 	    put_user(info_copy, &uattr->info.info_len))
7676 		return -EFAULT;
7677 
7678 	return ret;
7679 }
7680 
7681 int btf_get_fd_by_id(u32 id)
7682 {
7683 	struct btf *btf;
7684 	int fd;
7685 
7686 	rcu_read_lock();
7687 	btf = idr_find(&btf_idr, id);
7688 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
7689 		btf = ERR_PTR(-ENOENT);
7690 	rcu_read_unlock();
7691 
7692 	if (IS_ERR(btf))
7693 		return PTR_ERR(btf);
7694 
7695 	fd = __btf_new_fd(btf);
7696 	if (fd < 0)
7697 		btf_put(btf);
7698 
7699 	return fd;
7700 }
7701 
7702 u32 btf_obj_id(const struct btf *btf)
7703 {
7704 	return btf->id;
7705 }
7706 
7707 bool btf_is_kernel(const struct btf *btf)
7708 {
7709 	return btf->kernel_btf;
7710 }
7711 
7712 bool btf_is_module(const struct btf *btf)
7713 {
7714 	return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
7715 }
7716 
7717 enum {
7718 	BTF_MODULE_F_LIVE = (1 << 0),
7719 };
7720 
7721 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7722 struct btf_module {
7723 	struct list_head list;
7724 	struct module *module;
7725 	struct btf *btf;
7726 	struct bin_attribute *sysfs_attr;
7727 	int flags;
7728 };
7729 
7730 static LIST_HEAD(btf_modules);
7731 static DEFINE_MUTEX(btf_module_mutex);
7732 
7733 static ssize_t
7734 btf_module_read(struct file *file, struct kobject *kobj,
7735 		struct bin_attribute *bin_attr,
7736 		char *buf, loff_t off, size_t len)
7737 {
7738 	const struct btf *btf = bin_attr->private;
7739 
7740 	memcpy(buf, btf->data + off, len);
7741 	return len;
7742 }
7743 
7744 static void purge_cand_cache(struct btf *btf);
7745 
7746 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
7747 			     void *module)
7748 {
7749 	struct btf_module *btf_mod, *tmp;
7750 	struct module *mod = module;
7751 	struct btf *btf;
7752 	int err = 0;
7753 
7754 	if (mod->btf_data_size == 0 ||
7755 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_LIVE &&
7756 	     op != MODULE_STATE_GOING))
7757 		goto out;
7758 
7759 	switch (op) {
7760 	case MODULE_STATE_COMING:
7761 		btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
7762 		if (!btf_mod) {
7763 			err = -ENOMEM;
7764 			goto out;
7765 		}
7766 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
7767 		if (IS_ERR(btf)) {
7768 			kfree(btf_mod);
7769 			if (!IS_ENABLED(CONFIG_MODULE_ALLOW_BTF_MISMATCH)) {
7770 				pr_warn("failed to validate module [%s] BTF: %ld\n",
7771 					mod->name, PTR_ERR(btf));
7772 				err = PTR_ERR(btf);
7773 			} else {
7774 				pr_warn_once("Kernel module BTF mismatch detected, BTF debug info may be unavailable for some modules\n");
7775 			}
7776 			goto out;
7777 		}
7778 		err = btf_alloc_id(btf);
7779 		if (err) {
7780 			btf_free(btf);
7781 			kfree(btf_mod);
7782 			goto out;
7783 		}
7784 
7785 		purge_cand_cache(NULL);
7786 		mutex_lock(&btf_module_mutex);
7787 		btf_mod->module = module;
7788 		btf_mod->btf = btf;
7789 		list_add(&btf_mod->list, &btf_modules);
7790 		mutex_unlock(&btf_module_mutex);
7791 
7792 		if (IS_ENABLED(CONFIG_SYSFS)) {
7793 			struct bin_attribute *attr;
7794 
7795 			attr = kzalloc(sizeof(*attr), GFP_KERNEL);
7796 			if (!attr)
7797 				goto out;
7798 
7799 			sysfs_bin_attr_init(attr);
7800 			attr->attr.name = btf->name;
7801 			attr->attr.mode = 0444;
7802 			attr->size = btf->data_size;
7803 			attr->private = btf;
7804 			attr->read = btf_module_read;
7805 
7806 			err = sysfs_create_bin_file(btf_kobj, attr);
7807 			if (err) {
7808 				pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
7809 					mod->name, err);
7810 				kfree(attr);
7811 				err = 0;
7812 				goto out;
7813 			}
7814 
7815 			btf_mod->sysfs_attr = attr;
7816 		}
7817 
7818 		break;
7819 	case MODULE_STATE_LIVE:
7820 		mutex_lock(&btf_module_mutex);
7821 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7822 			if (btf_mod->module != module)
7823 				continue;
7824 
7825 			btf_mod->flags |= BTF_MODULE_F_LIVE;
7826 			break;
7827 		}
7828 		mutex_unlock(&btf_module_mutex);
7829 		break;
7830 	case MODULE_STATE_GOING:
7831 		mutex_lock(&btf_module_mutex);
7832 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7833 			if (btf_mod->module != module)
7834 				continue;
7835 
7836 			list_del(&btf_mod->list);
7837 			if (btf_mod->sysfs_attr)
7838 				sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
7839 			purge_cand_cache(btf_mod->btf);
7840 			btf_put(btf_mod->btf);
7841 			kfree(btf_mod->sysfs_attr);
7842 			kfree(btf_mod);
7843 			break;
7844 		}
7845 		mutex_unlock(&btf_module_mutex);
7846 		break;
7847 	}
7848 out:
7849 	return notifier_from_errno(err);
7850 }
7851 
7852 static struct notifier_block btf_module_nb = {
7853 	.notifier_call = btf_module_notify,
7854 };
7855 
7856 static int __init btf_module_init(void)
7857 {
7858 	register_module_notifier(&btf_module_nb);
7859 	return 0;
7860 }
7861 
7862 fs_initcall(btf_module_init);
7863 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
7864 
7865 struct module *btf_try_get_module(const struct btf *btf)
7866 {
7867 	struct module *res = NULL;
7868 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7869 	struct btf_module *btf_mod, *tmp;
7870 
7871 	mutex_lock(&btf_module_mutex);
7872 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7873 		if (btf_mod->btf != btf)
7874 			continue;
7875 
7876 		/* We must only consider module whose __init routine has
7877 		 * finished, hence we must check for BTF_MODULE_F_LIVE flag,
7878 		 * which is set from the notifier callback for
7879 		 * MODULE_STATE_LIVE.
7880 		 */
7881 		if ((btf_mod->flags & BTF_MODULE_F_LIVE) && try_module_get(btf_mod->module))
7882 			res = btf_mod->module;
7883 
7884 		break;
7885 	}
7886 	mutex_unlock(&btf_module_mutex);
7887 #endif
7888 
7889 	return res;
7890 }
7891 
7892 /* Returns struct btf corresponding to the struct module.
7893  * This function can return NULL or ERR_PTR.
7894  */
7895 static struct btf *btf_get_module_btf(const struct module *module)
7896 {
7897 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7898 	struct btf_module *btf_mod, *tmp;
7899 #endif
7900 	struct btf *btf = NULL;
7901 
7902 	if (!module) {
7903 		btf = bpf_get_btf_vmlinux();
7904 		if (!IS_ERR_OR_NULL(btf))
7905 			btf_get(btf);
7906 		return btf;
7907 	}
7908 
7909 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
7910 	mutex_lock(&btf_module_mutex);
7911 	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
7912 		if (btf_mod->module != module)
7913 			continue;
7914 
7915 		btf_get(btf_mod->btf);
7916 		btf = btf_mod->btf;
7917 		break;
7918 	}
7919 	mutex_unlock(&btf_module_mutex);
7920 #endif
7921 
7922 	return btf;
7923 }
7924 
7925 static int check_btf_kconfigs(const struct module *module, const char *feature)
7926 {
7927 	if (!module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) {
7928 		pr_err("missing vmlinux BTF, cannot register %s\n", feature);
7929 		return -ENOENT;
7930 	}
7931 	if (module && IS_ENABLED(CONFIG_DEBUG_INFO_BTF_MODULES))
7932 		pr_warn("missing module BTF, cannot register %s\n", feature);
7933 	return 0;
7934 }
7935 
7936 BPF_CALL_4(bpf_btf_find_by_name_kind, char *, name, int, name_sz, u32, kind, int, flags)
7937 {
7938 	struct btf *btf = NULL;
7939 	int btf_obj_fd = 0;
7940 	long ret;
7941 
7942 	if (flags)
7943 		return -EINVAL;
7944 
7945 	if (name_sz <= 1 || name[name_sz - 1])
7946 		return -EINVAL;
7947 
7948 	ret = bpf_find_btf_id(name, kind, &btf);
7949 	if (ret > 0 && btf_is_module(btf)) {
7950 		btf_obj_fd = __btf_new_fd(btf);
7951 		if (btf_obj_fd < 0) {
7952 			btf_put(btf);
7953 			return btf_obj_fd;
7954 		}
7955 		return ret | (((u64)btf_obj_fd) << 32);
7956 	}
7957 	if (ret > 0)
7958 		btf_put(btf);
7959 	return ret;
7960 }
7961 
7962 const struct bpf_func_proto bpf_btf_find_by_name_kind_proto = {
7963 	.func		= bpf_btf_find_by_name_kind,
7964 	.gpl_only	= false,
7965 	.ret_type	= RET_INTEGER,
7966 	.arg1_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
7967 	.arg2_type	= ARG_CONST_SIZE,
7968 	.arg3_type	= ARG_ANYTHING,
7969 	.arg4_type	= ARG_ANYTHING,
7970 };
7971 
7972 BTF_ID_LIST_GLOBAL(btf_tracing_ids, MAX_BTF_TRACING_TYPE)
7973 #define BTF_TRACING_TYPE(name, type) BTF_ID(struct, type)
7974 BTF_TRACING_TYPE_xxx
7975 #undef BTF_TRACING_TYPE
7976 
7977 static int btf_check_iter_kfuncs(struct btf *btf, const char *func_name,
7978 				 const struct btf_type *func, u32 func_flags)
7979 {
7980 	u32 flags = func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY);
7981 	const char *name, *sfx, *iter_name;
7982 	const struct btf_param *arg;
7983 	const struct btf_type *t;
7984 	char exp_name[128];
7985 	u32 nr_args;
7986 
7987 	/* exactly one of KF_ITER_{NEW,NEXT,DESTROY} can be set */
7988 	if (!flags || (flags & (flags - 1)))
7989 		return -EINVAL;
7990 
7991 	/* any BPF iter kfunc should have `struct bpf_iter_<type> *` first arg */
7992 	nr_args = btf_type_vlen(func);
7993 	if (nr_args < 1)
7994 		return -EINVAL;
7995 
7996 	arg = &btf_params(func)[0];
7997 	t = btf_type_skip_modifiers(btf, arg->type, NULL);
7998 	if (!t || !btf_type_is_ptr(t))
7999 		return -EINVAL;
8000 	t = btf_type_skip_modifiers(btf, t->type, NULL);
8001 	if (!t || !__btf_type_is_struct(t))
8002 		return -EINVAL;
8003 
8004 	name = btf_name_by_offset(btf, t->name_off);
8005 	if (!name || strncmp(name, ITER_PREFIX, sizeof(ITER_PREFIX) - 1))
8006 		return -EINVAL;
8007 
8008 	/* sizeof(struct bpf_iter_<type>) should be a multiple of 8 to
8009 	 * fit nicely in stack slots
8010 	 */
8011 	if (t->size == 0 || (t->size % 8))
8012 		return -EINVAL;
8013 
8014 	/* validate bpf_iter_<type>_{new,next,destroy}(struct bpf_iter_<type> *)
8015 	 * naming pattern
8016 	 */
8017 	iter_name = name + sizeof(ITER_PREFIX) - 1;
8018 	if (flags & KF_ITER_NEW)
8019 		sfx = "new";
8020 	else if (flags & KF_ITER_NEXT)
8021 		sfx = "next";
8022 	else /* (flags & KF_ITER_DESTROY) */
8023 		sfx = "destroy";
8024 
8025 	snprintf(exp_name, sizeof(exp_name), "bpf_iter_%s_%s", iter_name, sfx);
8026 	if (strcmp(func_name, exp_name))
8027 		return -EINVAL;
8028 
8029 	/* only iter constructor should have extra arguments */
8030 	if (!(flags & KF_ITER_NEW) && nr_args != 1)
8031 		return -EINVAL;
8032 
8033 	if (flags & KF_ITER_NEXT) {
8034 		/* bpf_iter_<type>_next() should return pointer */
8035 		t = btf_type_skip_modifiers(btf, func->type, NULL);
8036 		if (!t || !btf_type_is_ptr(t))
8037 			return -EINVAL;
8038 	}
8039 
8040 	if (flags & KF_ITER_DESTROY) {
8041 		/* bpf_iter_<type>_destroy() should return void */
8042 		t = btf_type_by_id(btf, func->type);
8043 		if (!t || !btf_type_is_void(t))
8044 			return -EINVAL;
8045 	}
8046 
8047 	return 0;
8048 }
8049 
8050 static int btf_check_kfunc_protos(struct btf *btf, u32 func_id, u32 func_flags)
8051 {
8052 	const struct btf_type *func;
8053 	const char *func_name;
8054 	int err;
8055 
8056 	/* any kfunc should be FUNC -> FUNC_PROTO */
8057 	func = btf_type_by_id(btf, func_id);
8058 	if (!func || !btf_type_is_func(func))
8059 		return -EINVAL;
8060 
8061 	/* sanity check kfunc name */
8062 	func_name = btf_name_by_offset(btf, func->name_off);
8063 	if (!func_name || !func_name[0])
8064 		return -EINVAL;
8065 
8066 	func = btf_type_by_id(btf, func->type);
8067 	if (!func || !btf_type_is_func_proto(func))
8068 		return -EINVAL;
8069 
8070 	if (func_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY)) {
8071 		err = btf_check_iter_kfuncs(btf, func_name, func, func_flags);
8072 		if (err)
8073 			return err;
8074 	}
8075 
8076 	return 0;
8077 }
8078 
8079 /* Kernel Function (kfunc) BTF ID set registration API */
8080 
8081 static int btf_populate_kfunc_set(struct btf *btf, enum btf_kfunc_hook hook,
8082 				  const struct btf_kfunc_id_set *kset)
8083 {
8084 	struct btf_kfunc_hook_filter *hook_filter;
8085 	struct btf_id_set8 *add_set = kset->set;
8086 	bool vmlinux_set = !btf_is_module(btf);
8087 	bool add_filter = !!kset->filter;
8088 	struct btf_kfunc_set_tab *tab;
8089 	struct btf_id_set8 *set;
8090 	u32 set_cnt;
8091 	int ret;
8092 
8093 	if (hook >= BTF_KFUNC_HOOK_MAX) {
8094 		ret = -EINVAL;
8095 		goto end;
8096 	}
8097 
8098 	if (!add_set->cnt)
8099 		return 0;
8100 
8101 	tab = btf->kfunc_set_tab;
8102 
8103 	if (tab && add_filter) {
8104 		u32 i;
8105 
8106 		hook_filter = &tab->hook_filters[hook];
8107 		for (i = 0; i < hook_filter->nr_filters; i++) {
8108 			if (hook_filter->filters[i] == kset->filter) {
8109 				add_filter = false;
8110 				break;
8111 			}
8112 		}
8113 
8114 		if (add_filter && hook_filter->nr_filters == BTF_KFUNC_FILTER_MAX_CNT) {
8115 			ret = -E2BIG;
8116 			goto end;
8117 		}
8118 	}
8119 
8120 	if (!tab) {
8121 		tab = kzalloc(sizeof(*tab), GFP_KERNEL | __GFP_NOWARN);
8122 		if (!tab)
8123 			return -ENOMEM;
8124 		btf->kfunc_set_tab = tab;
8125 	}
8126 
8127 	set = tab->sets[hook];
8128 	/* Warn when register_btf_kfunc_id_set is called twice for the same hook
8129 	 * for module sets.
8130 	 */
8131 	if (WARN_ON_ONCE(set && !vmlinux_set)) {
8132 		ret = -EINVAL;
8133 		goto end;
8134 	}
8135 
8136 	/* We don't need to allocate, concatenate, and sort module sets, because
8137 	 * only one is allowed per hook. Hence, we can directly assign the
8138 	 * pointer and return.
8139 	 */
8140 	if (!vmlinux_set) {
8141 		tab->sets[hook] = add_set;
8142 		goto do_add_filter;
8143 	}
8144 
8145 	/* In case of vmlinux sets, there may be more than one set being
8146 	 * registered per hook. To create a unified set, we allocate a new set
8147 	 * and concatenate all individual sets being registered. While each set
8148 	 * is individually sorted, they may become unsorted when concatenated,
8149 	 * hence re-sorting the final set again is required to make binary
8150 	 * searching the set using btf_id_set8_contains function work.
8151 	 */
8152 	set_cnt = set ? set->cnt : 0;
8153 
8154 	if (set_cnt > U32_MAX - add_set->cnt) {
8155 		ret = -EOVERFLOW;
8156 		goto end;
8157 	}
8158 
8159 	if (set_cnt + add_set->cnt > BTF_KFUNC_SET_MAX_CNT) {
8160 		ret = -E2BIG;
8161 		goto end;
8162 	}
8163 
8164 	/* Grow set */
8165 	set = krealloc(tab->sets[hook],
8166 		       offsetof(struct btf_id_set8, pairs[set_cnt + add_set->cnt]),
8167 		       GFP_KERNEL | __GFP_NOWARN);
8168 	if (!set) {
8169 		ret = -ENOMEM;
8170 		goto end;
8171 	}
8172 
8173 	/* For newly allocated set, initialize set->cnt to 0 */
8174 	if (!tab->sets[hook])
8175 		set->cnt = 0;
8176 	tab->sets[hook] = set;
8177 
8178 	/* Concatenate the two sets */
8179 	memcpy(set->pairs + set->cnt, add_set->pairs, add_set->cnt * sizeof(set->pairs[0]));
8180 	set->cnt += add_set->cnt;
8181 
8182 	sort(set->pairs, set->cnt, sizeof(set->pairs[0]), btf_id_cmp_func, NULL);
8183 
8184 do_add_filter:
8185 	if (add_filter) {
8186 		hook_filter = &tab->hook_filters[hook];
8187 		hook_filter->filters[hook_filter->nr_filters++] = kset->filter;
8188 	}
8189 	return 0;
8190 end:
8191 	btf_free_kfunc_set_tab(btf);
8192 	return ret;
8193 }
8194 
8195 static u32 *__btf_kfunc_id_set_contains(const struct btf *btf,
8196 					enum btf_kfunc_hook hook,
8197 					u32 kfunc_btf_id,
8198 					const struct bpf_prog *prog)
8199 {
8200 	struct btf_kfunc_hook_filter *hook_filter;
8201 	struct btf_id_set8 *set;
8202 	u32 *id, i;
8203 
8204 	if (hook >= BTF_KFUNC_HOOK_MAX)
8205 		return NULL;
8206 	if (!btf->kfunc_set_tab)
8207 		return NULL;
8208 	hook_filter = &btf->kfunc_set_tab->hook_filters[hook];
8209 	for (i = 0; i < hook_filter->nr_filters; i++) {
8210 		if (hook_filter->filters[i](prog, kfunc_btf_id))
8211 			return NULL;
8212 	}
8213 	set = btf->kfunc_set_tab->sets[hook];
8214 	if (!set)
8215 		return NULL;
8216 	id = btf_id_set8_contains(set, kfunc_btf_id);
8217 	if (!id)
8218 		return NULL;
8219 	/* The flags for BTF ID are located next to it */
8220 	return id + 1;
8221 }
8222 
8223 static int bpf_prog_type_to_kfunc_hook(enum bpf_prog_type prog_type)
8224 {
8225 	switch (prog_type) {
8226 	case BPF_PROG_TYPE_UNSPEC:
8227 		return BTF_KFUNC_HOOK_COMMON;
8228 	case BPF_PROG_TYPE_XDP:
8229 		return BTF_KFUNC_HOOK_XDP;
8230 	case BPF_PROG_TYPE_SCHED_CLS:
8231 		return BTF_KFUNC_HOOK_TC;
8232 	case BPF_PROG_TYPE_STRUCT_OPS:
8233 		return BTF_KFUNC_HOOK_STRUCT_OPS;
8234 	case BPF_PROG_TYPE_TRACING:
8235 	case BPF_PROG_TYPE_LSM:
8236 		return BTF_KFUNC_HOOK_TRACING;
8237 	case BPF_PROG_TYPE_SYSCALL:
8238 		return BTF_KFUNC_HOOK_SYSCALL;
8239 	case BPF_PROG_TYPE_CGROUP_SKB:
8240 	case BPF_PROG_TYPE_CGROUP_SOCK_ADDR:
8241 		return BTF_KFUNC_HOOK_CGROUP_SKB;
8242 	case BPF_PROG_TYPE_SCHED_ACT:
8243 		return BTF_KFUNC_HOOK_SCHED_ACT;
8244 	case BPF_PROG_TYPE_SK_SKB:
8245 		return BTF_KFUNC_HOOK_SK_SKB;
8246 	case BPF_PROG_TYPE_SOCKET_FILTER:
8247 		return BTF_KFUNC_HOOK_SOCKET_FILTER;
8248 	case BPF_PROG_TYPE_LWT_OUT:
8249 	case BPF_PROG_TYPE_LWT_IN:
8250 	case BPF_PROG_TYPE_LWT_XMIT:
8251 	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
8252 		return BTF_KFUNC_HOOK_LWT;
8253 	case BPF_PROG_TYPE_NETFILTER:
8254 		return BTF_KFUNC_HOOK_NETFILTER;
8255 	case BPF_PROG_TYPE_KPROBE:
8256 		return BTF_KFUNC_HOOK_KPROBE;
8257 	default:
8258 		return BTF_KFUNC_HOOK_MAX;
8259 	}
8260 }
8261 
8262 /* Caution:
8263  * Reference to the module (obtained using btf_try_get_module) corresponding to
8264  * the struct btf *MUST* be held when calling this function from verifier
8265  * context. This is usually true as we stash references in prog's kfunc_btf_tab;
8266  * keeping the reference for the duration of the call provides the necessary
8267  * protection for looking up a well-formed btf->kfunc_set_tab.
8268  */
8269 u32 *btf_kfunc_id_set_contains(const struct btf *btf,
8270 			       u32 kfunc_btf_id,
8271 			       const struct bpf_prog *prog)
8272 {
8273 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
8274 	enum btf_kfunc_hook hook;
8275 	u32 *kfunc_flags;
8276 
8277 	kfunc_flags = __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_COMMON, kfunc_btf_id, prog);
8278 	if (kfunc_flags)
8279 		return kfunc_flags;
8280 
8281 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
8282 	return __btf_kfunc_id_set_contains(btf, hook, kfunc_btf_id, prog);
8283 }
8284 
8285 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
8286 				const struct bpf_prog *prog)
8287 {
8288 	return __btf_kfunc_id_set_contains(btf, BTF_KFUNC_HOOK_FMODRET, kfunc_btf_id, prog);
8289 }
8290 
8291 static int __register_btf_kfunc_id_set(enum btf_kfunc_hook hook,
8292 				       const struct btf_kfunc_id_set *kset)
8293 {
8294 	struct btf *btf;
8295 	int ret, i;
8296 
8297 	btf = btf_get_module_btf(kset->owner);
8298 	if (!btf)
8299 		return check_btf_kconfigs(kset->owner, "kfunc");
8300 	if (IS_ERR(btf))
8301 		return PTR_ERR(btf);
8302 
8303 	for (i = 0; i < kset->set->cnt; i++) {
8304 		ret = btf_check_kfunc_protos(btf, kset->set->pairs[i].id,
8305 					     kset->set->pairs[i].flags);
8306 		if (ret)
8307 			goto err_out;
8308 	}
8309 
8310 	ret = btf_populate_kfunc_set(btf, hook, kset);
8311 
8312 err_out:
8313 	btf_put(btf);
8314 	return ret;
8315 }
8316 
8317 /* This function must be invoked only from initcalls/module init functions */
8318 int register_btf_kfunc_id_set(enum bpf_prog_type prog_type,
8319 			      const struct btf_kfunc_id_set *kset)
8320 {
8321 	enum btf_kfunc_hook hook;
8322 
8323 	/* All kfuncs need to be tagged as such in BTF.
8324 	 * WARN() for initcall registrations that do not check errors.
8325 	 */
8326 	if (!(kset->set->flags & BTF_SET8_KFUNCS)) {
8327 		WARN_ON(!kset->owner);
8328 		return -EINVAL;
8329 	}
8330 
8331 	hook = bpf_prog_type_to_kfunc_hook(prog_type);
8332 	return __register_btf_kfunc_id_set(hook, kset);
8333 }
8334 EXPORT_SYMBOL_GPL(register_btf_kfunc_id_set);
8335 
8336 /* This function must be invoked only from initcalls/module init functions */
8337 int register_btf_fmodret_id_set(const struct btf_kfunc_id_set *kset)
8338 {
8339 	return __register_btf_kfunc_id_set(BTF_KFUNC_HOOK_FMODRET, kset);
8340 }
8341 EXPORT_SYMBOL_GPL(register_btf_fmodret_id_set);
8342 
8343 s32 btf_find_dtor_kfunc(struct btf *btf, u32 btf_id)
8344 {
8345 	struct btf_id_dtor_kfunc_tab *tab = btf->dtor_kfunc_tab;
8346 	struct btf_id_dtor_kfunc *dtor;
8347 
8348 	if (!tab)
8349 		return -ENOENT;
8350 	/* Even though the size of tab->dtors[0] is > sizeof(u32), we only need
8351 	 * to compare the first u32 with btf_id, so we can reuse btf_id_cmp_func.
8352 	 */
8353 	BUILD_BUG_ON(offsetof(struct btf_id_dtor_kfunc, btf_id) != 0);
8354 	dtor = bsearch(&btf_id, tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func);
8355 	if (!dtor)
8356 		return -ENOENT;
8357 	return dtor->kfunc_btf_id;
8358 }
8359 
8360 static int btf_check_dtor_kfuncs(struct btf *btf, const struct btf_id_dtor_kfunc *dtors, u32 cnt)
8361 {
8362 	const struct btf_type *dtor_func, *dtor_func_proto, *t;
8363 	const struct btf_param *args;
8364 	s32 dtor_btf_id;
8365 	u32 nr_args, i;
8366 
8367 	for (i = 0; i < cnt; i++) {
8368 		dtor_btf_id = dtors[i].kfunc_btf_id;
8369 
8370 		dtor_func = btf_type_by_id(btf, dtor_btf_id);
8371 		if (!dtor_func || !btf_type_is_func(dtor_func))
8372 			return -EINVAL;
8373 
8374 		dtor_func_proto = btf_type_by_id(btf, dtor_func->type);
8375 		if (!dtor_func_proto || !btf_type_is_func_proto(dtor_func_proto))
8376 			return -EINVAL;
8377 
8378 		/* Make sure the prototype of the destructor kfunc is 'void func(type *)' */
8379 		t = btf_type_by_id(btf, dtor_func_proto->type);
8380 		if (!t || !btf_type_is_void(t))
8381 			return -EINVAL;
8382 
8383 		nr_args = btf_type_vlen(dtor_func_proto);
8384 		if (nr_args != 1)
8385 			return -EINVAL;
8386 		args = btf_params(dtor_func_proto);
8387 		t = btf_type_by_id(btf, args[0].type);
8388 		/* Allow any pointer type, as width on targets Linux supports
8389 		 * will be same for all pointer types (i.e. sizeof(void *))
8390 		 */
8391 		if (!t || !btf_type_is_ptr(t))
8392 			return -EINVAL;
8393 	}
8394 	return 0;
8395 }
8396 
8397 /* This function must be invoked only from initcalls/module init functions */
8398 int register_btf_id_dtor_kfuncs(const struct btf_id_dtor_kfunc *dtors, u32 add_cnt,
8399 				struct module *owner)
8400 {
8401 	struct btf_id_dtor_kfunc_tab *tab;
8402 	struct btf *btf;
8403 	u32 tab_cnt;
8404 	int ret;
8405 
8406 	btf = btf_get_module_btf(owner);
8407 	if (!btf)
8408 		return check_btf_kconfigs(owner, "dtor kfuncs");
8409 	if (IS_ERR(btf))
8410 		return PTR_ERR(btf);
8411 
8412 	if (add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8413 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8414 		ret = -E2BIG;
8415 		goto end;
8416 	}
8417 
8418 	/* Ensure that the prototype of dtor kfuncs being registered is sane */
8419 	ret = btf_check_dtor_kfuncs(btf, dtors, add_cnt);
8420 	if (ret < 0)
8421 		goto end;
8422 
8423 	tab = btf->dtor_kfunc_tab;
8424 	/* Only one call allowed for modules */
8425 	if (WARN_ON_ONCE(tab && btf_is_module(btf))) {
8426 		ret = -EINVAL;
8427 		goto end;
8428 	}
8429 
8430 	tab_cnt = tab ? tab->cnt : 0;
8431 	if (tab_cnt > U32_MAX - add_cnt) {
8432 		ret = -EOVERFLOW;
8433 		goto end;
8434 	}
8435 	if (tab_cnt + add_cnt >= BTF_DTOR_KFUNC_MAX_CNT) {
8436 		pr_err("cannot register more than %d kfunc destructors\n", BTF_DTOR_KFUNC_MAX_CNT);
8437 		ret = -E2BIG;
8438 		goto end;
8439 	}
8440 
8441 	tab = krealloc(btf->dtor_kfunc_tab,
8442 		       offsetof(struct btf_id_dtor_kfunc_tab, dtors[tab_cnt + add_cnt]),
8443 		       GFP_KERNEL | __GFP_NOWARN);
8444 	if (!tab) {
8445 		ret = -ENOMEM;
8446 		goto end;
8447 	}
8448 
8449 	if (!btf->dtor_kfunc_tab)
8450 		tab->cnt = 0;
8451 	btf->dtor_kfunc_tab = tab;
8452 
8453 	memcpy(tab->dtors + tab->cnt, dtors, add_cnt * sizeof(tab->dtors[0]));
8454 	tab->cnt += add_cnt;
8455 
8456 	sort(tab->dtors, tab->cnt, sizeof(tab->dtors[0]), btf_id_cmp_func, NULL);
8457 
8458 end:
8459 	if (ret)
8460 		btf_free_dtor_kfunc_tab(btf);
8461 	btf_put(btf);
8462 	return ret;
8463 }
8464 EXPORT_SYMBOL_GPL(register_btf_id_dtor_kfuncs);
8465 
8466 #define MAX_TYPES_ARE_COMPAT_DEPTH 2
8467 
8468 /* Check local and target types for compatibility. This check is used for
8469  * type-based CO-RE relocations and follow slightly different rules than
8470  * field-based relocations. This function assumes that root types were already
8471  * checked for name match. Beyond that initial root-level name check, names
8472  * are completely ignored. Compatibility rules are as follows:
8473  *   - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs/ENUM64s are considered compatible, but
8474  *     kind should match for local and target types (i.e., STRUCT is not
8475  *     compatible with UNION);
8476  *   - for ENUMs/ENUM64s, the size is ignored;
8477  *   - for INT, size and signedness are ignored;
8478  *   - for ARRAY, dimensionality is ignored, element types are checked for
8479  *     compatibility recursively;
8480  *   - CONST/VOLATILE/RESTRICT modifiers are ignored;
8481  *   - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
8482  *   - FUNC_PROTOs are compatible if they have compatible signature: same
8483  *     number of input args and compatible return and argument types.
8484  * These rules are not set in stone and probably will be adjusted as we get
8485  * more experience with using BPF CO-RE relocations.
8486  */
8487 int bpf_core_types_are_compat(const struct btf *local_btf, __u32 local_id,
8488 			      const struct btf *targ_btf, __u32 targ_id)
8489 {
8490 	return __bpf_core_types_are_compat(local_btf, local_id, targ_btf, targ_id,
8491 					   MAX_TYPES_ARE_COMPAT_DEPTH);
8492 }
8493 
8494 #define MAX_TYPES_MATCH_DEPTH 2
8495 
8496 int bpf_core_types_match(const struct btf *local_btf, u32 local_id,
8497 			 const struct btf *targ_btf, u32 targ_id)
8498 {
8499 	return __bpf_core_types_match(local_btf, local_id, targ_btf, targ_id, false,
8500 				      MAX_TYPES_MATCH_DEPTH);
8501 }
8502 
8503 static bool bpf_core_is_flavor_sep(const char *s)
8504 {
8505 	/* check X___Y name pattern, where X and Y are not underscores */
8506 	return s[0] != '_' &&				      /* X */
8507 	       s[1] == '_' && s[2] == '_' && s[3] == '_' &&   /* ___ */
8508 	       s[4] != '_';				      /* Y */
8509 }
8510 
8511 size_t bpf_core_essential_name_len(const char *name)
8512 {
8513 	size_t n = strlen(name);
8514 	int i;
8515 
8516 	for (i = n - 5; i >= 0; i--) {
8517 		if (bpf_core_is_flavor_sep(name + i))
8518 			return i + 1;
8519 	}
8520 	return n;
8521 }
8522 
8523 static void bpf_free_cands(struct bpf_cand_cache *cands)
8524 {
8525 	if (!cands->cnt)
8526 		/* empty candidate array was allocated on stack */
8527 		return;
8528 	kfree(cands);
8529 }
8530 
8531 static void bpf_free_cands_from_cache(struct bpf_cand_cache *cands)
8532 {
8533 	kfree(cands->name);
8534 	kfree(cands);
8535 }
8536 
8537 #define VMLINUX_CAND_CACHE_SIZE 31
8538 static struct bpf_cand_cache *vmlinux_cand_cache[VMLINUX_CAND_CACHE_SIZE];
8539 
8540 #define MODULE_CAND_CACHE_SIZE 31
8541 static struct bpf_cand_cache *module_cand_cache[MODULE_CAND_CACHE_SIZE];
8542 
8543 static void __print_cand_cache(struct bpf_verifier_log *log,
8544 			       struct bpf_cand_cache **cache,
8545 			       int cache_size)
8546 {
8547 	struct bpf_cand_cache *cc;
8548 	int i, j;
8549 
8550 	for (i = 0; i < cache_size; i++) {
8551 		cc = cache[i];
8552 		if (!cc)
8553 			continue;
8554 		bpf_log(log, "[%d]%s(", i, cc->name);
8555 		for (j = 0; j < cc->cnt; j++) {
8556 			bpf_log(log, "%d", cc->cands[j].id);
8557 			if (j < cc->cnt - 1)
8558 				bpf_log(log, " ");
8559 		}
8560 		bpf_log(log, "), ");
8561 	}
8562 }
8563 
8564 static void print_cand_cache(struct bpf_verifier_log *log)
8565 {
8566 	mutex_lock(&cand_cache_mutex);
8567 	bpf_log(log, "vmlinux_cand_cache:");
8568 	__print_cand_cache(log, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8569 	bpf_log(log, "\nmodule_cand_cache:");
8570 	__print_cand_cache(log, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8571 	bpf_log(log, "\n");
8572 	mutex_unlock(&cand_cache_mutex);
8573 }
8574 
8575 static u32 hash_cands(struct bpf_cand_cache *cands)
8576 {
8577 	return jhash(cands->name, cands->name_len, 0);
8578 }
8579 
8580 static struct bpf_cand_cache *check_cand_cache(struct bpf_cand_cache *cands,
8581 					       struct bpf_cand_cache **cache,
8582 					       int cache_size)
8583 {
8584 	struct bpf_cand_cache *cc = cache[hash_cands(cands) % cache_size];
8585 
8586 	if (cc && cc->name_len == cands->name_len &&
8587 	    !strncmp(cc->name, cands->name, cands->name_len))
8588 		return cc;
8589 	return NULL;
8590 }
8591 
8592 static size_t sizeof_cands(int cnt)
8593 {
8594 	return offsetof(struct bpf_cand_cache, cands[cnt]);
8595 }
8596 
8597 static struct bpf_cand_cache *populate_cand_cache(struct bpf_cand_cache *cands,
8598 						  struct bpf_cand_cache **cache,
8599 						  int cache_size)
8600 {
8601 	struct bpf_cand_cache **cc = &cache[hash_cands(cands) % cache_size], *new_cands;
8602 
8603 	if (*cc) {
8604 		bpf_free_cands_from_cache(*cc);
8605 		*cc = NULL;
8606 	}
8607 	new_cands = kmemdup(cands, sizeof_cands(cands->cnt), GFP_KERNEL);
8608 	if (!new_cands) {
8609 		bpf_free_cands(cands);
8610 		return ERR_PTR(-ENOMEM);
8611 	}
8612 	/* strdup the name, since it will stay in cache.
8613 	 * the cands->name points to strings in prog's BTF and the prog can be unloaded.
8614 	 */
8615 	new_cands->name = kmemdup_nul(cands->name, cands->name_len, GFP_KERNEL);
8616 	bpf_free_cands(cands);
8617 	if (!new_cands->name) {
8618 		kfree(new_cands);
8619 		return ERR_PTR(-ENOMEM);
8620 	}
8621 	*cc = new_cands;
8622 	return new_cands;
8623 }
8624 
8625 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
8626 static void __purge_cand_cache(struct btf *btf, struct bpf_cand_cache **cache,
8627 			       int cache_size)
8628 {
8629 	struct bpf_cand_cache *cc;
8630 	int i, j;
8631 
8632 	for (i = 0; i < cache_size; i++) {
8633 		cc = cache[i];
8634 		if (!cc)
8635 			continue;
8636 		if (!btf) {
8637 			/* when new module is loaded purge all of module_cand_cache,
8638 			 * since new module might have candidates with the name
8639 			 * that matches cached cands.
8640 			 */
8641 			bpf_free_cands_from_cache(cc);
8642 			cache[i] = NULL;
8643 			continue;
8644 		}
8645 		/* when module is unloaded purge cache entries
8646 		 * that match module's btf
8647 		 */
8648 		for (j = 0; j < cc->cnt; j++)
8649 			if (cc->cands[j].btf == btf) {
8650 				bpf_free_cands_from_cache(cc);
8651 				cache[i] = NULL;
8652 				break;
8653 			}
8654 	}
8655 
8656 }
8657 
8658 static void purge_cand_cache(struct btf *btf)
8659 {
8660 	mutex_lock(&cand_cache_mutex);
8661 	__purge_cand_cache(btf, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8662 	mutex_unlock(&cand_cache_mutex);
8663 }
8664 #endif
8665 
8666 static struct bpf_cand_cache *
8667 bpf_core_add_cands(struct bpf_cand_cache *cands, const struct btf *targ_btf,
8668 		   int targ_start_id)
8669 {
8670 	struct bpf_cand_cache *new_cands;
8671 	const struct btf_type *t;
8672 	const char *targ_name;
8673 	size_t targ_essent_len;
8674 	int n, i;
8675 
8676 	n = btf_nr_types(targ_btf);
8677 	for (i = targ_start_id; i < n; i++) {
8678 		t = btf_type_by_id(targ_btf, i);
8679 		if (btf_kind(t) != cands->kind)
8680 			continue;
8681 
8682 		targ_name = btf_name_by_offset(targ_btf, t->name_off);
8683 		if (!targ_name)
8684 			continue;
8685 
8686 		/* the resched point is before strncmp to make sure that search
8687 		 * for non-existing name will have a chance to schedule().
8688 		 */
8689 		cond_resched();
8690 
8691 		if (strncmp(cands->name, targ_name, cands->name_len) != 0)
8692 			continue;
8693 
8694 		targ_essent_len = bpf_core_essential_name_len(targ_name);
8695 		if (targ_essent_len != cands->name_len)
8696 			continue;
8697 
8698 		/* most of the time there is only one candidate for a given kind+name pair */
8699 		new_cands = kmalloc(sizeof_cands(cands->cnt + 1), GFP_KERNEL);
8700 		if (!new_cands) {
8701 			bpf_free_cands(cands);
8702 			return ERR_PTR(-ENOMEM);
8703 		}
8704 
8705 		memcpy(new_cands, cands, sizeof_cands(cands->cnt));
8706 		bpf_free_cands(cands);
8707 		cands = new_cands;
8708 		cands->cands[cands->cnt].btf = targ_btf;
8709 		cands->cands[cands->cnt].id = i;
8710 		cands->cnt++;
8711 	}
8712 	return cands;
8713 }
8714 
8715 static struct bpf_cand_cache *
8716 bpf_core_find_cands(struct bpf_core_ctx *ctx, u32 local_type_id)
8717 {
8718 	struct bpf_cand_cache *cands, *cc, local_cand = {};
8719 	const struct btf *local_btf = ctx->btf;
8720 	const struct btf_type *local_type;
8721 	const struct btf *main_btf;
8722 	size_t local_essent_len;
8723 	struct btf *mod_btf;
8724 	const char *name;
8725 	int id;
8726 
8727 	main_btf = bpf_get_btf_vmlinux();
8728 	if (IS_ERR(main_btf))
8729 		return ERR_CAST(main_btf);
8730 	if (!main_btf)
8731 		return ERR_PTR(-EINVAL);
8732 
8733 	local_type = btf_type_by_id(local_btf, local_type_id);
8734 	if (!local_type)
8735 		return ERR_PTR(-EINVAL);
8736 
8737 	name = btf_name_by_offset(local_btf, local_type->name_off);
8738 	if (str_is_empty(name))
8739 		return ERR_PTR(-EINVAL);
8740 	local_essent_len = bpf_core_essential_name_len(name);
8741 
8742 	cands = &local_cand;
8743 	cands->name = name;
8744 	cands->kind = btf_kind(local_type);
8745 	cands->name_len = local_essent_len;
8746 
8747 	cc = check_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8748 	/* cands is a pointer to stack here */
8749 	if (cc) {
8750 		if (cc->cnt)
8751 			return cc;
8752 		goto check_modules;
8753 	}
8754 
8755 	/* Attempt to find target candidates in vmlinux BTF first */
8756 	cands = bpf_core_add_cands(cands, main_btf, 1);
8757 	if (IS_ERR(cands))
8758 		return ERR_CAST(cands);
8759 
8760 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0 */
8761 
8762 	/* populate cache even when cands->cnt == 0 */
8763 	cc = populate_cand_cache(cands, vmlinux_cand_cache, VMLINUX_CAND_CACHE_SIZE);
8764 	if (IS_ERR(cc))
8765 		return ERR_CAST(cc);
8766 
8767 	/* if vmlinux BTF has any candidate, don't go for module BTFs */
8768 	if (cc->cnt)
8769 		return cc;
8770 
8771 check_modules:
8772 	/* cands is a pointer to stack here and cands->cnt == 0 */
8773 	cc = check_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8774 	if (cc)
8775 		/* if cache has it return it even if cc->cnt == 0 */
8776 		return cc;
8777 
8778 	/* If candidate is not found in vmlinux's BTF then search in module's BTFs */
8779 	spin_lock_bh(&btf_idr_lock);
8780 	idr_for_each_entry(&btf_idr, mod_btf, id) {
8781 		if (!btf_is_module(mod_btf))
8782 			continue;
8783 		/* linear search could be slow hence unlock/lock
8784 		 * the IDR to avoiding holding it for too long
8785 		 */
8786 		btf_get(mod_btf);
8787 		spin_unlock_bh(&btf_idr_lock);
8788 		cands = bpf_core_add_cands(cands, mod_btf, btf_nr_types(main_btf));
8789 		btf_put(mod_btf);
8790 		if (IS_ERR(cands))
8791 			return ERR_CAST(cands);
8792 		spin_lock_bh(&btf_idr_lock);
8793 	}
8794 	spin_unlock_bh(&btf_idr_lock);
8795 	/* cands is a pointer to kmalloced memory here if cands->cnt > 0
8796 	 * or pointer to stack if cands->cnd == 0.
8797 	 * Copy it into the cache even when cands->cnt == 0 and
8798 	 * return the result.
8799 	 */
8800 	return populate_cand_cache(cands, module_cand_cache, MODULE_CAND_CACHE_SIZE);
8801 }
8802 
8803 int bpf_core_apply(struct bpf_core_ctx *ctx, const struct bpf_core_relo *relo,
8804 		   int relo_idx, void *insn)
8805 {
8806 	bool need_cands = relo->kind != BPF_CORE_TYPE_ID_LOCAL;
8807 	struct bpf_core_cand_list cands = {};
8808 	struct bpf_core_relo_res targ_res;
8809 	struct bpf_core_spec *specs;
8810 	int err;
8811 
8812 	/* ~4k of temp memory necessary to convert LLVM spec like "0:1:0:5"
8813 	 * into arrays of btf_ids of struct fields and array indices.
8814 	 */
8815 	specs = kcalloc(3, sizeof(*specs), GFP_KERNEL);
8816 	if (!specs)
8817 		return -ENOMEM;
8818 
8819 	if (need_cands) {
8820 		struct bpf_cand_cache *cc;
8821 		int i;
8822 
8823 		mutex_lock(&cand_cache_mutex);
8824 		cc = bpf_core_find_cands(ctx, relo->type_id);
8825 		if (IS_ERR(cc)) {
8826 			bpf_log(ctx->log, "target candidate search failed for %d\n",
8827 				relo->type_id);
8828 			err = PTR_ERR(cc);
8829 			goto out;
8830 		}
8831 		if (cc->cnt) {
8832 			cands.cands = kcalloc(cc->cnt, sizeof(*cands.cands), GFP_KERNEL);
8833 			if (!cands.cands) {
8834 				err = -ENOMEM;
8835 				goto out;
8836 			}
8837 		}
8838 		for (i = 0; i < cc->cnt; i++) {
8839 			bpf_log(ctx->log,
8840 				"CO-RE relocating %s %s: found target candidate [%d]\n",
8841 				btf_kind_str[cc->kind], cc->name, cc->cands[i].id);
8842 			cands.cands[i].btf = cc->cands[i].btf;
8843 			cands.cands[i].id = cc->cands[i].id;
8844 		}
8845 		cands.len = cc->cnt;
8846 		/* cand_cache_mutex needs to span the cache lookup and
8847 		 * copy of btf pointer into bpf_core_cand_list,
8848 		 * since module can be unloaded while bpf_core_calc_relo_insn
8849 		 * is working with module's btf.
8850 		 */
8851 	}
8852 
8853 	err = bpf_core_calc_relo_insn((void *)ctx->log, relo, relo_idx, ctx->btf, &cands, specs,
8854 				      &targ_res);
8855 	if (err)
8856 		goto out;
8857 
8858 	err = bpf_core_patch_insn((void *)ctx->log, insn, relo->insn_off / 8, relo, relo_idx,
8859 				  &targ_res);
8860 
8861 out:
8862 	kfree(specs);
8863 	if (need_cands) {
8864 		kfree(cands.cands);
8865 		mutex_unlock(&cand_cache_mutex);
8866 		if (ctx->log->level & BPF_LOG_LEVEL2)
8867 			print_cand_cache(ctx->log);
8868 	}
8869 	return err;
8870 }
8871 
8872 bool btf_nested_type_is_trusted(struct bpf_verifier_log *log,
8873 				const struct bpf_reg_state *reg,
8874 				const char *field_name, u32 btf_id, const char *suffix)
8875 {
8876 	struct btf *btf = reg->btf;
8877 	const struct btf_type *walk_type, *safe_type;
8878 	const char *tname;
8879 	char safe_tname[64];
8880 	long ret, safe_id;
8881 	const struct btf_member *member;
8882 	u32 i;
8883 
8884 	walk_type = btf_type_by_id(btf, reg->btf_id);
8885 	if (!walk_type)
8886 		return false;
8887 
8888 	tname = btf_name_by_offset(btf, walk_type->name_off);
8889 
8890 	ret = snprintf(safe_tname, sizeof(safe_tname), "%s%s", tname, suffix);
8891 	if (ret >= sizeof(safe_tname))
8892 		return false;
8893 
8894 	safe_id = btf_find_by_name_kind(btf, safe_tname, BTF_INFO_KIND(walk_type->info));
8895 	if (safe_id < 0)
8896 		return false;
8897 
8898 	safe_type = btf_type_by_id(btf, safe_id);
8899 	if (!safe_type)
8900 		return false;
8901 
8902 	for_each_member(i, safe_type, member) {
8903 		const char *m_name = __btf_name_by_offset(btf, member->name_off);
8904 		const struct btf_type *mtype = btf_type_by_id(btf, member->type);
8905 		u32 id;
8906 
8907 		if (!btf_type_is_ptr(mtype))
8908 			continue;
8909 
8910 		btf_type_skip_modifiers(btf, mtype->type, &id);
8911 		/* If we match on both type and name, the field is considered trusted. */
8912 		if (btf_id == id && !strcmp(field_name, m_name))
8913 			return true;
8914 	}
8915 
8916 	return false;
8917 }
8918 
8919 bool btf_type_ids_nocast_alias(struct bpf_verifier_log *log,
8920 			       const struct btf *reg_btf, u32 reg_id,
8921 			       const struct btf *arg_btf, u32 arg_id)
8922 {
8923 	const char *reg_name, *arg_name, *search_needle;
8924 	const struct btf_type *reg_type, *arg_type;
8925 	int reg_len, arg_len, cmp_len;
8926 	size_t pattern_len = sizeof(NOCAST_ALIAS_SUFFIX) - sizeof(char);
8927 
8928 	reg_type = btf_type_by_id(reg_btf, reg_id);
8929 	if (!reg_type)
8930 		return false;
8931 
8932 	arg_type = btf_type_by_id(arg_btf, arg_id);
8933 	if (!arg_type)
8934 		return false;
8935 
8936 	reg_name = btf_name_by_offset(reg_btf, reg_type->name_off);
8937 	arg_name = btf_name_by_offset(arg_btf, arg_type->name_off);
8938 
8939 	reg_len = strlen(reg_name);
8940 	arg_len = strlen(arg_name);
8941 
8942 	/* Exactly one of the two type names may be suffixed with ___init, so
8943 	 * if the strings are the same size, they can't possibly be no-cast
8944 	 * aliases of one another. If you have two of the same type names, e.g.
8945 	 * they're both nf_conn___init, it would be improper to return true
8946 	 * because they are _not_ no-cast aliases, they are the same type.
8947 	 */
8948 	if (reg_len == arg_len)
8949 		return false;
8950 
8951 	/* Either of the two names must be the other name, suffixed with ___init. */
8952 	if ((reg_len != arg_len + pattern_len) &&
8953 	    (arg_len != reg_len + pattern_len))
8954 		return false;
8955 
8956 	if (reg_len < arg_len) {
8957 		search_needle = strstr(arg_name, NOCAST_ALIAS_SUFFIX);
8958 		cmp_len = reg_len;
8959 	} else {
8960 		search_needle = strstr(reg_name, NOCAST_ALIAS_SUFFIX);
8961 		cmp_len = arg_len;
8962 	}
8963 
8964 	if (!search_needle)
8965 		return false;
8966 
8967 	/* ___init suffix must come at the end of the name */
8968 	if (*(search_needle + pattern_len) != '\0')
8969 		return false;
8970 
8971 	return !strncmp(reg_name, arg_name, cmp_len);
8972 }
8973 
8974 #ifdef CONFIG_BPF_JIT
8975 static int
8976 btf_add_struct_ops(struct btf *btf, struct bpf_struct_ops *st_ops,
8977 		   struct bpf_verifier_log *log)
8978 {
8979 	struct btf_struct_ops_tab *tab, *new_tab;
8980 	int i, err;
8981 
8982 	tab = btf->struct_ops_tab;
8983 	if (!tab) {
8984 		tab = kzalloc(offsetof(struct btf_struct_ops_tab, ops[4]),
8985 			      GFP_KERNEL);
8986 		if (!tab)
8987 			return -ENOMEM;
8988 		tab->capacity = 4;
8989 		btf->struct_ops_tab = tab;
8990 	}
8991 
8992 	for (i = 0; i < tab->cnt; i++)
8993 		if (tab->ops[i].st_ops == st_ops)
8994 			return -EEXIST;
8995 
8996 	if (tab->cnt == tab->capacity) {
8997 		new_tab = krealloc(tab,
8998 				   offsetof(struct btf_struct_ops_tab,
8999 					    ops[tab->capacity * 2]),
9000 				   GFP_KERNEL);
9001 		if (!new_tab)
9002 			return -ENOMEM;
9003 		tab = new_tab;
9004 		tab->capacity *= 2;
9005 		btf->struct_ops_tab = tab;
9006 	}
9007 
9008 	tab->ops[btf->struct_ops_tab->cnt].st_ops = st_ops;
9009 
9010 	err = bpf_struct_ops_desc_init(&tab->ops[btf->struct_ops_tab->cnt], btf, log);
9011 	if (err)
9012 		return err;
9013 
9014 	btf->struct_ops_tab->cnt++;
9015 
9016 	return 0;
9017 }
9018 
9019 const struct bpf_struct_ops_desc *
9020 bpf_struct_ops_find_value(struct btf *btf, u32 value_id)
9021 {
9022 	const struct bpf_struct_ops_desc *st_ops_list;
9023 	unsigned int i;
9024 	u32 cnt;
9025 
9026 	if (!value_id)
9027 		return NULL;
9028 	if (!btf->struct_ops_tab)
9029 		return NULL;
9030 
9031 	cnt = btf->struct_ops_tab->cnt;
9032 	st_ops_list = btf->struct_ops_tab->ops;
9033 	for (i = 0; i < cnt; i++) {
9034 		if (st_ops_list[i].value_id == value_id)
9035 			return &st_ops_list[i];
9036 	}
9037 
9038 	return NULL;
9039 }
9040 
9041 const struct bpf_struct_ops_desc *
9042 bpf_struct_ops_find(struct btf *btf, u32 type_id)
9043 {
9044 	const struct bpf_struct_ops_desc *st_ops_list;
9045 	unsigned int i;
9046 	u32 cnt;
9047 
9048 	if (!type_id)
9049 		return NULL;
9050 	if (!btf->struct_ops_tab)
9051 		return NULL;
9052 
9053 	cnt = btf->struct_ops_tab->cnt;
9054 	st_ops_list = btf->struct_ops_tab->ops;
9055 	for (i = 0; i < cnt; i++) {
9056 		if (st_ops_list[i].type_id == type_id)
9057 			return &st_ops_list[i];
9058 	}
9059 
9060 	return NULL;
9061 }
9062 
9063 int __register_bpf_struct_ops(struct bpf_struct_ops *st_ops)
9064 {
9065 	struct bpf_verifier_log *log;
9066 	struct btf *btf;
9067 	int err = 0;
9068 
9069 	btf = btf_get_module_btf(st_ops->owner);
9070 	if (!btf)
9071 		return check_btf_kconfigs(st_ops->owner, "struct_ops");
9072 	if (IS_ERR(btf))
9073 		return PTR_ERR(btf);
9074 
9075 	log = kzalloc(sizeof(*log), GFP_KERNEL | __GFP_NOWARN);
9076 	if (!log) {
9077 		err = -ENOMEM;
9078 		goto errout;
9079 	}
9080 
9081 	log->level = BPF_LOG_KERNEL;
9082 
9083 	err = btf_add_struct_ops(btf, st_ops, log);
9084 
9085 errout:
9086 	kfree(log);
9087 	btf_put(btf);
9088 
9089 	return err;
9090 }
9091 EXPORT_SYMBOL_GPL(__register_bpf_struct_ops);
9092 #endif
9093 
9094 bool btf_param_match_suffix(const struct btf *btf,
9095 			    const struct btf_param *arg,
9096 			    const char *suffix)
9097 {
9098 	int suffix_len = strlen(suffix), len;
9099 	const char *param_name;
9100 
9101 	/* In the future, this can be ported to use BTF tagging */
9102 	param_name = btf_name_by_offset(btf, arg->name_off);
9103 	if (str_is_empty(param_name))
9104 		return false;
9105 	len = strlen(param_name);
9106 	if (len <= suffix_len)
9107 		return false;
9108 	param_name += len - suffix_len;
9109 	return !strncmp(param_name, suffix, suffix_len);
9110 }
9111