xref: /openbmc/linux/kernel/bpf/btf.c (revision 4b7ead03)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /* Copyright (c) 2018 Facebook */
3 
4 #include <uapi/linux/btf.h>
5 #include <uapi/linux/bpf.h>
6 #include <uapi/linux/bpf_perf_event.h>
7 #include <uapi/linux/types.h>
8 #include <linux/seq_file.h>
9 #include <linux/compiler.h>
10 #include <linux/ctype.h>
11 #include <linux/errno.h>
12 #include <linux/slab.h>
13 #include <linux/anon_inodes.h>
14 #include <linux/file.h>
15 #include <linux/uaccess.h>
16 #include <linux/kernel.h>
17 #include <linux/idr.h>
18 #include <linux/sort.h>
19 #include <linux/bpf_verifier.h>
20 #include <linux/btf.h>
21 #include <linux/btf_ids.h>
22 #include <linux/skmsg.h>
23 #include <linux/perf_event.h>
24 #include <linux/bsearch.h>
25 #include <linux/kobject.h>
26 #include <linux/sysfs.h>
27 #include <net/sock.h>
28 
29 /* BTF (BPF Type Format) is the meta data format which describes
30  * the data types of BPF program/map.  Hence, it basically focus
31  * on the C programming language which the modern BPF is primary
32  * using.
33  *
34  * ELF Section:
35  * ~~~~~~~~~~~
36  * The BTF data is stored under the ".BTF" ELF section
37  *
38  * struct btf_type:
39  * ~~~~~~~~~~~~~~~
40  * Each 'struct btf_type' object describes a C data type.
41  * Depending on the type it is describing, a 'struct btf_type'
42  * object may be followed by more data.  F.e.
43  * To describe an array, 'struct btf_type' is followed by
44  * 'struct btf_array'.
45  *
46  * 'struct btf_type' and any extra data following it are
47  * 4 bytes aligned.
48  *
49  * Type section:
50  * ~~~~~~~~~~~~~
51  * The BTF type section contains a list of 'struct btf_type' objects.
52  * Each one describes a C type.  Recall from the above section
53  * that a 'struct btf_type' object could be immediately followed by extra
54  * data in order to desribe some particular C types.
55  *
56  * type_id:
57  * ~~~~~~~
58  * Each btf_type object is identified by a type_id.  The type_id
59  * is implicitly implied by the location of the btf_type object in
60  * the BTF type section.  The first one has type_id 1.  The second
61  * one has type_id 2...etc.  Hence, an earlier btf_type has
62  * a smaller type_id.
63  *
64  * A btf_type object may refer to another btf_type object by using
65  * type_id (i.e. the "type" in the "struct btf_type").
66  *
67  * NOTE that we cannot assume any reference-order.
68  * A btf_type object can refer to an earlier btf_type object
69  * but it can also refer to a later btf_type object.
70  *
71  * For example, to describe "const void *".  A btf_type
72  * object describing "const" may refer to another btf_type
73  * object describing "void *".  This type-reference is done
74  * by specifying type_id:
75  *
76  * [1] CONST (anon) type_id=2
77  * [2] PTR (anon) type_id=0
78  *
79  * The above is the btf_verifier debug log:
80  *   - Each line started with "[?]" is a btf_type object
81  *   - [?] is the type_id of the btf_type object.
82  *   - CONST/PTR is the BTF_KIND_XXX
83  *   - "(anon)" is the name of the type.  It just
84  *     happens that CONST and PTR has no name.
85  *   - type_id=XXX is the 'u32 type' in btf_type
86  *
87  * NOTE: "void" has type_id 0
88  *
89  * String section:
90  * ~~~~~~~~~~~~~~
91  * The BTF string section contains the names used by the type section.
92  * Each string is referred by an "offset" from the beginning of the
93  * string section.
94  *
95  * Each string is '\0' terminated.
96  *
97  * The first character in the string section must be '\0'
98  * which is used to mean 'anonymous'. Some btf_type may not
99  * have a name.
100  */
101 
102 /* BTF verification:
103  *
104  * To verify BTF data, two passes are needed.
105  *
106  * Pass #1
107  * ~~~~~~~
108  * The first pass is to collect all btf_type objects to
109  * an array: "btf->types".
110  *
111  * Depending on the C type that a btf_type is describing,
112  * a btf_type may be followed by extra data.  We don't know
113  * how many btf_type is there, and more importantly we don't
114  * know where each btf_type is located in the type section.
115  *
116  * Without knowing the location of each type_id, most verifications
117  * cannot be done.  e.g. an earlier btf_type may refer to a later
118  * btf_type (recall the "const void *" above), so we cannot
119  * check this type-reference in the first pass.
120  *
121  * In the first pass, it still does some verifications (e.g.
122  * checking the name is a valid offset to the string section).
123  *
124  * Pass #2
125  * ~~~~~~~
126  * The main focus is to resolve a btf_type that is referring
127  * to another type.
128  *
129  * We have to ensure the referring type:
130  * 1) does exist in the BTF (i.e. in btf->types[])
131  * 2) does not cause a loop:
132  *	struct A {
133  *		struct B b;
134  *	};
135  *
136  *	struct B {
137  *		struct A a;
138  *	};
139  *
140  * btf_type_needs_resolve() decides if a btf_type needs
141  * to be resolved.
142  *
143  * The needs_resolve type implements the "resolve()" ops which
144  * essentially does a DFS and detects backedge.
145  *
146  * During resolve (or DFS), different C types have different
147  * "RESOLVED" conditions.
148  *
149  * When resolving a BTF_KIND_STRUCT, we need to resolve all its
150  * members because a member is always referring to another
151  * type.  A struct's member can be treated as "RESOLVED" if
152  * it is referring to a BTF_KIND_PTR.  Otherwise, the
153  * following valid C struct would be rejected:
154  *
155  *	struct A {
156  *		int m;
157  *		struct A *a;
158  *	};
159  *
160  * When resolving a BTF_KIND_PTR, it needs to keep resolving if
161  * it is referring to another BTF_KIND_PTR.  Otherwise, we cannot
162  * detect a pointer loop, e.g.:
163  * BTF_KIND_CONST -> BTF_KIND_PTR -> BTF_KIND_CONST -> BTF_KIND_PTR +
164  *                        ^                                         |
165  *                        +-----------------------------------------+
166  *
167  */
168 
169 #define BITS_PER_U128 (sizeof(u64) * BITS_PER_BYTE * 2)
170 #define BITS_PER_BYTE_MASK (BITS_PER_BYTE - 1)
171 #define BITS_PER_BYTE_MASKED(bits) ((bits) & BITS_PER_BYTE_MASK)
172 #define BITS_ROUNDDOWN_BYTES(bits) ((bits) >> 3)
173 #define BITS_ROUNDUP_BYTES(bits) \
174 	(BITS_ROUNDDOWN_BYTES(bits) + !!BITS_PER_BYTE_MASKED(bits))
175 
176 #define BTF_INFO_MASK 0x8f00ffff
177 #define BTF_INT_MASK 0x0fffffff
178 #define BTF_TYPE_ID_VALID(type_id) ((type_id) <= BTF_MAX_TYPE)
179 #define BTF_STR_OFFSET_VALID(name_off) ((name_off) <= BTF_MAX_NAME_OFFSET)
180 
181 /* 16MB for 64k structs and each has 16 members and
182  * a few MB spaces for the string section.
183  * The hard limit is S32_MAX.
184  */
185 #define BTF_MAX_SIZE (16 * 1024 * 1024)
186 
187 #define for_each_member_from(i, from, struct_type, member)		\
188 	for (i = from, member = btf_type_member(struct_type) + from;	\
189 	     i < btf_type_vlen(struct_type);				\
190 	     i++, member++)
191 
192 #define for_each_vsi_from(i, from, struct_type, member)				\
193 	for (i = from, member = btf_type_var_secinfo(struct_type) + from;	\
194 	     i < btf_type_vlen(struct_type);					\
195 	     i++, member++)
196 
197 DEFINE_IDR(btf_idr);
198 DEFINE_SPINLOCK(btf_idr_lock);
199 
200 struct btf {
201 	void *data;
202 	struct btf_type **types;
203 	u32 *resolved_ids;
204 	u32 *resolved_sizes;
205 	const char *strings;
206 	void *nohdr_data;
207 	struct btf_header hdr;
208 	u32 nr_types; /* includes VOID for base BTF */
209 	u32 types_size;
210 	u32 data_size;
211 	refcount_t refcnt;
212 	u32 id;
213 	struct rcu_head rcu;
214 
215 	/* split BTF support */
216 	struct btf *base_btf;
217 	u32 start_id; /* first type ID in this BTF (0 for base BTF) */
218 	u32 start_str_off; /* first string offset (0 for base BTF) */
219 	char name[MODULE_NAME_LEN];
220 	bool kernel_btf;
221 };
222 
223 enum verifier_phase {
224 	CHECK_META,
225 	CHECK_TYPE,
226 };
227 
228 struct resolve_vertex {
229 	const struct btf_type *t;
230 	u32 type_id;
231 	u16 next_member;
232 };
233 
234 enum visit_state {
235 	NOT_VISITED,
236 	VISITED,
237 	RESOLVED,
238 };
239 
240 enum resolve_mode {
241 	RESOLVE_TBD,	/* To Be Determined */
242 	RESOLVE_PTR,	/* Resolving for Pointer */
243 	RESOLVE_STRUCT_OR_ARRAY,	/* Resolving for struct/union
244 					 * or array
245 					 */
246 };
247 
248 #define MAX_RESOLVE_DEPTH 32
249 
250 struct btf_sec_info {
251 	u32 off;
252 	u32 len;
253 };
254 
255 struct btf_verifier_env {
256 	struct btf *btf;
257 	u8 *visit_states;
258 	struct resolve_vertex stack[MAX_RESOLVE_DEPTH];
259 	struct bpf_verifier_log log;
260 	u32 log_type_id;
261 	u32 top_stack;
262 	enum verifier_phase phase;
263 	enum resolve_mode resolve_mode;
264 };
265 
266 static const char * const btf_kind_str[NR_BTF_KINDS] = {
267 	[BTF_KIND_UNKN]		= "UNKNOWN",
268 	[BTF_KIND_INT]		= "INT",
269 	[BTF_KIND_PTR]		= "PTR",
270 	[BTF_KIND_ARRAY]	= "ARRAY",
271 	[BTF_KIND_STRUCT]	= "STRUCT",
272 	[BTF_KIND_UNION]	= "UNION",
273 	[BTF_KIND_ENUM]		= "ENUM",
274 	[BTF_KIND_FWD]		= "FWD",
275 	[BTF_KIND_TYPEDEF]	= "TYPEDEF",
276 	[BTF_KIND_VOLATILE]	= "VOLATILE",
277 	[BTF_KIND_CONST]	= "CONST",
278 	[BTF_KIND_RESTRICT]	= "RESTRICT",
279 	[BTF_KIND_FUNC]		= "FUNC",
280 	[BTF_KIND_FUNC_PROTO]	= "FUNC_PROTO",
281 	[BTF_KIND_VAR]		= "VAR",
282 	[BTF_KIND_DATASEC]	= "DATASEC",
283 };
284 
285 static const char *btf_type_str(const struct btf_type *t)
286 {
287 	return btf_kind_str[BTF_INFO_KIND(t->info)];
288 }
289 
290 /* Chunk size we use in safe copy of data to be shown. */
291 #define BTF_SHOW_OBJ_SAFE_SIZE		32
292 
293 /*
294  * This is the maximum size of a base type value (equivalent to a
295  * 128-bit int); if we are at the end of our safe buffer and have
296  * less than 16 bytes space we can't be assured of being able
297  * to copy the next type safely, so in such cases we will initiate
298  * a new copy.
299  */
300 #define BTF_SHOW_OBJ_BASE_TYPE_SIZE	16
301 
302 /* Type name size */
303 #define BTF_SHOW_NAME_SIZE		80
304 
305 /*
306  * Common data to all BTF show operations. Private show functions can add
307  * their own data to a structure containing a struct btf_show and consult it
308  * in the show callback.  See btf_type_show() below.
309  *
310  * One challenge with showing nested data is we want to skip 0-valued
311  * data, but in order to figure out whether a nested object is all zeros
312  * we need to walk through it.  As a result, we need to make two passes
313  * when handling structs, unions and arrays; the first path simply looks
314  * for nonzero data, while the second actually does the display.  The first
315  * pass is signalled by show->state.depth_check being set, and if we
316  * encounter a non-zero value we set show->state.depth_to_show to
317  * the depth at which we encountered it.  When we have completed the
318  * first pass, we will know if anything needs to be displayed if
319  * depth_to_show > depth.  See btf_[struct,array]_show() for the
320  * implementation of this.
321  *
322  * Another problem is we want to ensure the data for display is safe to
323  * access.  To support this, the anonymous "struct {} obj" tracks the data
324  * object and our safe copy of it.  We copy portions of the data needed
325  * to the object "copy" buffer, but because its size is limited to
326  * BTF_SHOW_OBJ_COPY_LEN bytes, multiple copies may be required as we
327  * traverse larger objects for display.
328  *
329  * The various data type show functions all start with a call to
330  * btf_show_start_type() which returns a pointer to the safe copy
331  * of the data needed (or if BTF_SHOW_UNSAFE is specified, to the
332  * raw data itself).  btf_show_obj_safe() is responsible for
333  * using copy_from_kernel_nofault() to update the safe data if necessary
334  * as we traverse the object's data.  skbuff-like semantics are
335  * used:
336  *
337  * - obj.head points to the start of the toplevel object for display
338  * - obj.size is the size of the toplevel object
339  * - obj.data points to the current point in the original data at
340  *   which our safe data starts.  obj.data will advance as we copy
341  *   portions of the data.
342  *
343  * In most cases a single copy will suffice, but larger data structures
344  * such as "struct task_struct" will require many copies.  The logic in
345  * btf_show_obj_safe() handles the logic that determines if a new
346  * copy_from_kernel_nofault() is needed.
347  */
348 struct btf_show {
349 	u64 flags;
350 	void *target;	/* target of show operation (seq file, buffer) */
351 	void (*showfn)(struct btf_show *show, const char *fmt, va_list args);
352 	const struct btf *btf;
353 	/* below are used during iteration */
354 	struct {
355 		u8 depth;
356 		u8 depth_to_show;
357 		u8 depth_check;
358 		u8 array_member:1,
359 		   array_terminated:1;
360 		u16 array_encoding;
361 		u32 type_id;
362 		int status;			/* non-zero for error */
363 		const struct btf_type *type;
364 		const struct btf_member *member;
365 		char name[BTF_SHOW_NAME_SIZE];	/* space for member name/type */
366 	} state;
367 	struct {
368 		u32 size;
369 		void *head;
370 		void *data;
371 		u8 safe[BTF_SHOW_OBJ_SAFE_SIZE];
372 	} obj;
373 };
374 
375 struct btf_kind_operations {
376 	s32 (*check_meta)(struct btf_verifier_env *env,
377 			  const struct btf_type *t,
378 			  u32 meta_left);
379 	int (*resolve)(struct btf_verifier_env *env,
380 		       const struct resolve_vertex *v);
381 	int (*check_member)(struct btf_verifier_env *env,
382 			    const struct btf_type *struct_type,
383 			    const struct btf_member *member,
384 			    const struct btf_type *member_type);
385 	int (*check_kflag_member)(struct btf_verifier_env *env,
386 				  const struct btf_type *struct_type,
387 				  const struct btf_member *member,
388 				  const struct btf_type *member_type);
389 	void (*log_details)(struct btf_verifier_env *env,
390 			    const struct btf_type *t);
391 	void (*show)(const struct btf *btf, const struct btf_type *t,
392 			 u32 type_id, void *data, u8 bits_offsets,
393 			 struct btf_show *show);
394 };
395 
396 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS];
397 static struct btf_type btf_void;
398 
399 static int btf_resolve(struct btf_verifier_env *env,
400 		       const struct btf_type *t, u32 type_id);
401 
402 static bool btf_type_is_modifier(const struct btf_type *t)
403 {
404 	/* Some of them is not strictly a C modifier
405 	 * but they are grouped into the same bucket
406 	 * for BTF concern:
407 	 *   A type (t) that refers to another
408 	 *   type through t->type AND its size cannot
409 	 *   be determined without following the t->type.
410 	 *
411 	 * ptr does not fall into this bucket
412 	 * because its size is always sizeof(void *).
413 	 */
414 	switch (BTF_INFO_KIND(t->info)) {
415 	case BTF_KIND_TYPEDEF:
416 	case BTF_KIND_VOLATILE:
417 	case BTF_KIND_CONST:
418 	case BTF_KIND_RESTRICT:
419 		return true;
420 	}
421 
422 	return false;
423 }
424 
425 bool btf_type_is_void(const struct btf_type *t)
426 {
427 	return t == &btf_void;
428 }
429 
430 static bool btf_type_is_fwd(const struct btf_type *t)
431 {
432 	return BTF_INFO_KIND(t->info) == BTF_KIND_FWD;
433 }
434 
435 static bool btf_type_nosize(const struct btf_type *t)
436 {
437 	return btf_type_is_void(t) || btf_type_is_fwd(t) ||
438 	       btf_type_is_func(t) || btf_type_is_func_proto(t);
439 }
440 
441 static bool btf_type_nosize_or_null(const struct btf_type *t)
442 {
443 	return !t || btf_type_nosize(t);
444 }
445 
446 static bool __btf_type_is_struct(const struct btf_type *t)
447 {
448 	return BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT;
449 }
450 
451 static bool btf_type_is_array(const struct btf_type *t)
452 {
453 	return BTF_INFO_KIND(t->info) == BTF_KIND_ARRAY;
454 }
455 
456 static bool btf_type_is_datasec(const struct btf_type *t)
457 {
458 	return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
459 }
460 
461 static u32 btf_nr_types_total(const struct btf *btf)
462 {
463 	u32 total = 0;
464 
465 	while (btf) {
466 		total += btf->nr_types;
467 		btf = btf->base_btf;
468 	}
469 
470 	return total;
471 }
472 
473 s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
474 {
475 	const struct btf_type *t;
476 	const char *tname;
477 	u32 i, total;
478 
479 	total = btf_nr_types_total(btf);
480 	for (i = 1; i < total; i++) {
481 		t = btf_type_by_id(btf, i);
482 		if (BTF_INFO_KIND(t->info) != kind)
483 			continue;
484 
485 		tname = btf_name_by_offset(btf, t->name_off);
486 		if (!strcmp(tname, name))
487 			return i;
488 	}
489 
490 	return -ENOENT;
491 }
492 
493 const struct btf_type *btf_type_skip_modifiers(const struct btf *btf,
494 					       u32 id, u32 *res_id)
495 {
496 	const struct btf_type *t = btf_type_by_id(btf, id);
497 
498 	while (btf_type_is_modifier(t)) {
499 		id = t->type;
500 		t = btf_type_by_id(btf, t->type);
501 	}
502 
503 	if (res_id)
504 		*res_id = id;
505 
506 	return t;
507 }
508 
509 const struct btf_type *btf_type_resolve_ptr(const struct btf *btf,
510 					    u32 id, u32 *res_id)
511 {
512 	const struct btf_type *t;
513 
514 	t = btf_type_skip_modifiers(btf, id, NULL);
515 	if (!btf_type_is_ptr(t))
516 		return NULL;
517 
518 	return btf_type_skip_modifiers(btf, t->type, res_id);
519 }
520 
521 const struct btf_type *btf_type_resolve_func_ptr(const struct btf *btf,
522 						 u32 id, u32 *res_id)
523 {
524 	const struct btf_type *ptype;
525 
526 	ptype = btf_type_resolve_ptr(btf, id, res_id);
527 	if (ptype && btf_type_is_func_proto(ptype))
528 		return ptype;
529 
530 	return NULL;
531 }
532 
533 /* Types that act only as a source, not sink or intermediate
534  * type when resolving.
535  */
536 static bool btf_type_is_resolve_source_only(const struct btf_type *t)
537 {
538 	return btf_type_is_var(t) ||
539 	       btf_type_is_datasec(t);
540 }
541 
542 /* What types need to be resolved?
543  *
544  * btf_type_is_modifier() is an obvious one.
545  *
546  * btf_type_is_struct() because its member refers to
547  * another type (through member->type).
548  *
549  * btf_type_is_var() because the variable refers to
550  * another type. btf_type_is_datasec() holds multiple
551  * btf_type_is_var() types that need resolving.
552  *
553  * btf_type_is_array() because its element (array->type)
554  * refers to another type.  Array can be thought of a
555  * special case of struct while array just has the same
556  * member-type repeated by array->nelems of times.
557  */
558 static bool btf_type_needs_resolve(const struct btf_type *t)
559 {
560 	return btf_type_is_modifier(t) ||
561 	       btf_type_is_ptr(t) ||
562 	       btf_type_is_struct(t) ||
563 	       btf_type_is_array(t) ||
564 	       btf_type_is_var(t) ||
565 	       btf_type_is_datasec(t);
566 }
567 
568 /* t->size can be used */
569 static bool btf_type_has_size(const struct btf_type *t)
570 {
571 	switch (BTF_INFO_KIND(t->info)) {
572 	case BTF_KIND_INT:
573 	case BTF_KIND_STRUCT:
574 	case BTF_KIND_UNION:
575 	case BTF_KIND_ENUM:
576 	case BTF_KIND_DATASEC:
577 		return true;
578 	}
579 
580 	return false;
581 }
582 
583 static const char *btf_int_encoding_str(u8 encoding)
584 {
585 	if (encoding == 0)
586 		return "(none)";
587 	else if (encoding == BTF_INT_SIGNED)
588 		return "SIGNED";
589 	else if (encoding == BTF_INT_CHAR)
590 		return "CHAR";
591 	else if (encoding == BTF_INT_BOOL)
592 		return "BOOL";
593 	else
594 		return "UNKN";
595 }
596 
597 static u32 btf_type_int(const struct btf_type *t)
598 {
599 	return *(u32 *)(t + 1);
600 }
601 
602 static const struct btf_array *btf_type_array(const struct btf_type *t)
603 {
604 	return (const struct btf_array *)(t + 1);
605 }
606 
607 static const struct btf_enum *btf_type_enum(const struct btf_type *t)
608 {
609 	return (const struct btf_enum *)(t + 1);
610 }
611 
612 static const struct btf_var *btf_type_var(const struct btf_type *t)
613 {
614 	return (const struct btf_var *)(t + 1);
615 }
616 
617 static const struct btf_kind_operations *btf_type_ops(const struct btf_type *t)
618 {
619 	return kind_ops[BTF_INFO_KIND(t->info)];
620 }
621 
622 static bool btf_name_offset_valid(const struct btf *btf, u32 offset)
623 {
624 	if (!BTF_STR_OFFSET_VALID(offset))
625 		return false;
626 
627 	while (offset < btf->start_str_off)
628 		btf = btf->base_btf;
629 
630 	offset -= btf->start_str_off;
631 	return offset < btf->hdr.str_len;
632 }
633 
634 static bool __btf_name_char_ok(char c, bool first, bool dot_ok)
635 {
636 	if ((first ? !isalpha(c) :
637 		     !isalnum(c)) &&
638 	    c != '_' &&
639 	    ((c == '.' && !dot_ok) ||
640 	      c != '.'))
641 		return false;
642 	return true;
643 }
644 
645 static const char *btf_str_by_offset(const struct btf *btf, u32 offset)
646 {
647 	while (offset < btf->start_str_off)
648 		btf = btf->base_btf;
649 
650 	offset -= btf->start_str_off;
651 	if (offset < btf->hdr.str_len)
652 		return &btf->strings[offset];
653 
654 	return NULL;
655 }
656 
657 static bool __btf_name_valid(const struct btf *btf, u32 offset, bool dot_ok)
658 {
659 	/* offset must be valid */
660 	const char *src = btf_str_by_offset(btf, offset);
661 	const char *src_limit;
662 
663 	if (!__btf_name_char_ok(*src, true, dot_ok))
664 		return false;
665 
666 	/* set a limit on identifier length */
667 	src_limit = src + KSYM_NAME_LEN;
668 	src++;
669 	while (*src && src < src_limit) {
670 		if (!__btf_name_char_ok(*src, false, dot_ok))
671 			return false;
672 		src++;
673 	}
674 
675 	return !*src;
676 }
677 
678 /* Only C-style identifier is permitted. This can be relaxed if
679  * necessary.
680  */
681 static bool btf_name_valid_identifier(const struct btf *btf, u32 offset)
682 {
683 	return __btf_name_valid(btf, offset, false);
684 }
685 
686 static bool btf_name_valid_section(const struct btf *btf, u32 offset)
687 {
688 	return __btf_name_valid(btf, offset, true);
689 }
690 
691 static const char *__btf_name_by_offset(const struct btf *btf, u32 offset)
692 {
693 	const char *name;
694 
695 	if (!offset)
696 		return "(anon)";
697 
698 	name = btf_str_by_offset(btf, offset);
699 	return name ?: "(invalid-name-offset)";
700 }
701 
702 const char *btf_name_by_offset(const struct btf *btf, u32 offset)
703 {
704 	return btf_str_by_offset(btf, offset);
705 }
706 
707 const struct btf_type *btf_type_by_id(const struct btf *btf, u32 type_id)
708 {
709 	while (type_id < btf->start_id)
710 		btf = btf->base_btf;
711 
712 	type_id -= btf->start_id;
713 	if (type_id >= btf->nr_types)
714 		return NULL;
715 	return btf->types[type_id];
716 }
717 
718 /*
719  * Regular int is not a bit field and it must be either
720  * u8/u16/u32/u64 or __int128.
721  */
722 static bool btf_type_int_is_regular(const struct btf_type *t)
723 {
724 	u8 nr_bits, nr_bytes;
725 	u32 int_data;
726 
727 	int_data = btf_type_int(t);
728 	nr_bits = BTF_INT_BITS(int_data);
729 	nr_bytes = BITS_ROUNDUP_BYTES(nr_bits);
730 	if (BITS_PER_BYTE_MASKED(nr_bits) ||
731 	    BTF_INT_OFFSET(int_data) ||
732 	    (nr_bytes != sizeof(u8) && nr_bytes != sizeof(u16) &&
733 	     nr_bytes != sizeof(u32) && nr_bytes != sizeof(u64) &&
734 	     nr_bytes != (2 * sizeof(u64)))) {
735 		return false;
736 	}
737 
738 	return true;
739 }
740 
741 /*
742  * Check that given struct member is a regular int with expected
743  * offset and size.
744  */
745 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
746 			   const struct btf_member *m,
747 			   u32 expected_offset, u32 expected_size)
748 {
749 	const struct btf_type *t;
750 	u32 id, int_data;
751 	u8 nr_bits;
752 
753 	id = m->type;
754 	t = btf_type_id_size(btf, &id, NULL);
755 	if (!t || !btf_type_is_int(t))
756 		return false;
757 
758 	int_data = btf_type_int(t);
759 	nr_bits = BTF_INT_BITS(int_data);
760 	if (btf_type_kflag(s)) {
761 		u32 bitfield_size = BTF_MEMBER_BITFIELD_SIZE(m->offset);
762 		u32 bit_offset = BTF_MEMBER_BIT_OFFSET(m->offset);
763 
764 		/* if kflag set, int should be a regular int and
765 		 * bit offset should be at byte boundary.
766 		 */
767 		return !bitfield_size &&
768 		       BITS_ROUNDUP_BYTES(bit_offset) == expected_offset &&
769 		       BITS_ROUNDUP_BYTES(nr_bits) == expected_size;
770 	}
771 
772 	if (BTF_INT_OFFSET(int_data) ||
773 	    BITS_PER_BYTE_MASKED(m->offset) ||
774 	    BITS_ROUNDUP_BYTES(m->offset) != expected_offset ||
775 	    BITS_PER_BYTE_MASKED(nr_bits) ||
776 	    BITS_ROUNDUP_BYTES(nr_bits) != expected_size)
777 		return false;
778 
779 	return true;
780 }
781 
782 /* Similar to btf_type_skip_modifiers() but does not skip typedefs. */
783 static const struct btf_type *btf_type_skip_qualifiers(const struct btf *btf,
784 						       u32 id)
785 {
786 	const struct btf_type *t = btf_type_by_id(btf, id);
787 
788 	while (btf_type_is_modifier(t) &&
789 	       BTF_INFO_KIND(t->info) != BTF_KIND_TYPEDEF) {
790 		id = t->type;
791 		t = btf_type_by_id(btf, t->type);
792 	}
793 
794 	return t;
795 }
796 
797 #define BTF_SHOW_MAX_ITER	10
798 
799 #define BTF_KIND_BIT(kind)	(1ULL << kind)
800 
801 /*
802  * Populate show->state.name with type name information.
803  * Format of type name is
804  *
805  * [.member_name = ] (type_name)
806  */
807 static const char *btf_show_name(struct btf_show *show)
808 {
809 	/* BTF_MAX_ITER array suffixes "[]" */
810 	const char *array_suffixes = "[][][][][][][][][][]";
811 	const char *array_suffix = &array_suffixes[strlen(array_suffixes)];
812 	/* BTF_MAX_ITER pointer suffixes "*" */
813 	const char *ptr_suffixes = "**********";
814 	const char *ptr_suffix = &ptr_suffixes[strlen(ptr_suffixes)];
815 	const char *name = NULL, *prefix = "", *parens = "";
816 	const struct btf_member *m = show->state.member;
817 	const struct btf_type *t = show->state.type;
818 	const struct btf_array *array;
819 	u32 id = show->state.type_id;
820 	const char *member = NULL;
821 	bool show_member = false;
822 	u64 kinds = 0;
823 	int i;
824 
825 	show->state.name[0] = '\0';
826 
827 	/*
828 	 * Don't show type name if we're showing an array member;
829 	 * in that case we show the array type so don't need to repeat
830 	 * ourselves for each member.
831 	 */
832 	if (show->state.array_member)
833 		return "";
834 
835 	/* Retrieve member name, if any. */
836 	if (m) {
837 		member = btf_name_by_offset(show->btf, m->name_off);
838 		show_member = strlen(member) > 0;
839 		id = m->type;
840 	}
841 
842 	/*
843 	 * Start with type_id, as we have resolved the struct btf_type *
844 	 * via btf_modifier_show() past the parent typedef to the child
845 	 * struct, int etc it is defined as.  In such cases, the type_id
846 	 * still represents the starting type while the struct btf_type *
847 	 * in our show->state points at the resolved type of the typedef.
848 	 */
849 	t = btf_type_by_id(show->btf, id);
850 	if (!t)
851 		return "";
852 
853 	/*
854 	 * The goal here is to build up the right number of pointer and
855 	 * array suffixes while ensuring the type name for a typedef
856 	 * is represented.  Along the way we accumulate a list of
857 	 * BTF kinds we have encountered, since these will inform later
858 	 * display; for example, pointer types will not require an
859 	 * opening "{" for struct, we will just display the pointer value.
860 	 *
861 	 * We also want to accumulate the right number of pointer or array
862 	 * indices in the format string while iterating until we get to
863 	 * the typedef/pointee/array member target type.
864 	 *
865 	 * We start by pointing at the end of pointer and array suffix
866 	 * strings; as we accumulate pointers and arrays we move the pointer
867 	 * or array string backwards so it will show the expected number of
868 	 * '*' or '[]' for the type.  BTF_SHOW_MAX_ITER of nesting of pointers
869 	 * and/or arrays and typedefs are supported as a precaution.
870 	 *
871 	 * We also want to get typedef name while proceeding to resolve
872 	 * type it points to so that we can add parentheses if it is a
873 	 * "typedef struct" etc.
874 	 */
875 	for (i = 0; i < BTF_SHOW_MAX_ITER; i++) {
876 
877 		switch (BTF_INFO_KIND(t->info)) {
878 		case BTF_KIND_TYPEDEF:
879 			if (!name)
880 				name = btf_name_by_offset(show->btf,
881 							       t->name_off);
882 			kinds |= BTF_KIND_BIT(BTF_KIND_TYPEDEF);
883 			id = t->type;
884 			break;
885 		case BTF_KIND_ARRAY:
886 			kinds |= BTF_KIND_BIT(BTF_KIND_ARRAY);
887 			parens = "[";
888 			if (!t)
889 				return "";
890 			array = btf_type_array(t);
891 			if (array_suffix > array_suffixes)
892 				array_suffix -= 2;
893 			id = array->type;
894 			break;
895 		case BTF_KIND_PTR:
896 			kinds |= BTF_KIND_BIT(BTF_KIND_PTR);
897 			if (ptr_suffix > ptr_suffixes)
898 				ptr_suffix -= 1;
899 			id = t->type;
900 			break;
901 		default:
902 			id = 0;
903 			break;
904 		}
905 		if (!id)
906 			break;
907 		t = btf_type_skip_qualifiers(show->btf, id);
908 	}
909 	/* We may not be able to represent this type; bail to be safe */
910 	if (i == BTF_SHOW_MAX_ITER)
911 		return "";
912 
913 	if (!name)
914 		name = btf_name_by_offset(show->btf, t->name_off);
915 
916 	switch (BTF_INFO_KIND(t->info)) {
917 	case BTF_KIND_STRUCT:
918 	case BTF_KIND_UNION:
919 		prefix = BTF_INFO_KIND(t->info) == BTF_KIND_STRUCT ?
920 			 "struct" : "union";
921 		/* if it's an array of struct/union, parens is already set */
922 		if (!(kinds & (BTF_KIND_BIT(BTF_KIND_ARRAY))))
923 			parens = "{";
924 		break;
925 	case BTF_KIND_ENUM:
926 		prefix = "enum";
927 		break;
928 	default:
929 		break;
930 	}
931 
932 	/* pointer does not require parens */
933 	if (kinds & BTF_KIND_BIT(BTF_KIND_PTR))
934 		parens = "";
935 	/* typedef does not require struct/union/enum prefix */
936 	if (kinds & BTF_KIND_BIT(BTF_KIND_TYPEDEF))
937 		prefix = "";
938 
939 	if (!name)
940 		name = "";
941 
942 	/* Even if we don't want type name info, we want parentheses etc */
943 	if (show->flags & BTF_SHOW_NONAME)
944 		snprintf(show->state.name, sizeof(show->state.name), "%s",
945 			 parens);
946 	else
947 		snprintf(show->state.name, sizeof(show->state.name),
948 			 "%s%s%s(%s%s%s%s%s%s)%s",
949 			 /* first 3 strings comprise ".member = " */
950 			 show_member ? "." : "",
951 			 show_member ? member : "",
952 			 show_member ? " = " : "",
953 			 /* ...next is our prefix (struct, enum, etc) */
954 			 prefix,
955 			 strlen(prefix) > 0 && strlen(name) > 0 ? " " : "",
956 			 /* ...this is the type name itself */
957 			 name,
958 			 /* ...suffixed by the appropriate '*', '[]' suffixes */
959 			 strlen(ptr_suffix) > 0 ? " " : "", ptr_suffix,
960 			 array_suffix, parens);
961 
962 	return show->state.name;
963 }
964 
965 static const char *__btf_show_indent(struct btf_show *show)
966 {
967 	const char *indents = "                                ";
968 	const char *indent = &indents[strlen(indents)];
969 
970 	if ((indent - show->state.depth) >= indents)
971 		return indent - show->state.depth;
972 	return indents;
973 }
974 
975 static const char *btf_show_indent(struct btf_show *show)
976 {
977 	return show->flags & BTF_SHOW_COMPACT ? "" : __btf_show_indent(show);
978 }
979 
980 static const char *btf_show_newline(struct btf_show *show)
981 {
982 	return show->flags & BTF_SHOW_COMPACT ? "" : "\n";
983 }
984 
985 static const char *btf_show_delim(struct btf_show *show)
986 {
987 	if (show->state.depth == 0)
988 		return "";
989 
990 	if ((show->flags & BTF_SHOW_COMPACT) && show->state.type &&
991 		BTF_INFO_KIND(show->state.type->info) == BTF_KIND_UNION)
992 		return "|";
993 
994 	return ",";
995 }
996 
997 __printf(2, 3) static void btf_show(struct btf_show *show, const char *fmt, ...)
998 {
999 	va_list args;
1000 
1001 	if (!show->state.depth_check) {
1002 		va_start(args, fmt);
1003 		show->showfn(show, fmt, args);
1004 		va_end(args);
1005 	}
1006 }
1007 
1008 /* Macros are used here as btf_show_type_value[s]() prepends and appends
1009  * format specifiers to the format specifier passed in; these do the work of
1010  * adding indentation, delimiters etc while the caller simply has to specify
1011  * the type value(s) in the format specifier + value(s).
1012  */
1013 #define btf_show_type_value(show, fmt, value)				       \
1014 	do {								       \
1015 		if ((value) != 0 || (show->flags & BTF_SHOW_ZERO) ||	       \
1016 		    show->state.depth == 0) {				       \
1017 			btf_show(show, "%s%s" fmt "%s%s",		       \
1018 				 btf_show_indent(show),			       \
1019 				 btf_show_name(show),			       \
1020 				 value, btf_show_delim(show),		       \
1021 				 btf_show_newline(show));		       \
1022 			if (show->state.depth > show->state.depth_to_show)     \
1023 				show->state.depth_to_show = show->state.depth; \
1024 		}							       \
1025 	} while (0)
1026 
1027 #define btf_show_type_values(show, fmt, ...)				       \
1028 	do {								       \
1029 		btf_show(show, "%s%s" fmt "%s%s", btf_show_indent(show),       \
1030 			 btf_show_name(show),				       \
1031 			 __VA_ARGS__, btf_show_delim(show),		       \
1032 			 btf_show_newline(show));			       \
1033 		if (show->state.depth > show->state.depth_to_show)	       \
1034 			show->state.depth_to_show = show->state.depth;	       \
1035 	} while (0)
1036 
1037 /* How much is left to copy to safe buffer after @data? */
1038 static int btf_show_obj_size_left(struct btf_show *show, void *data)
1039 {
1040 	return show->obj.head + show->obj.size - data;
1041 }
1042 
1043 /* Is object pointed to by @data of @size already copied to our safe buffer? */
1044 static bool btf_show_obj_is_safe(struct btf_show *show, void *data, int size)
1045 {
1046 	return data >= show->obj.data &&
1047 	       (data + size) < (show->obj.data + BTF_SHOW_OBJ_SAFE_SIZE);
1048 }
1049 
1050 /*
1051  * If object pointed to by @data of @size falls within our safe buffer, return
1052  * the equivalent pointer to the same safe data.  Assumes
1053  * copy_from_kernel_nofault() has already happened and our safe buffer is
1054  * populated.
1055  */
1056 static void *__btf_show_obj_safe(struct btf_show *show, void *data, int size)
1057 {
1058 	if (btf_show_obj_is_safe(show, data, size))
1059 		return show->obj.safe + (data - show->obj.data);
1060 	return NULL;
1061 }
1062 
1063 /*
1064  * Return a safe-to-access version of data pointed to by @data.
1065  * We do this by copying the relevant amount of information
1066  * to the struct btf_show obj.safe buffer using copy_from_kernel_nofault().
1067  *
1068  * If BTF_SHOW_UNSAFE is specified, just return data as-is; no
1069  * safe copy is needed.
1070  *
1071  * Otherwise we need to determine if we have the required amount
1072  * of data (determined by the @data pointer and the size of the
1073  * largest base type we can encounter (represented by
1074  * BTF_SHOW_OBJ_BASE_TYPE_SIZE). Having that much data ensures
1075  * that we will be able to print some of the current object,
1076  * and if more is needed a copy will be triggered.
1077  * Some objects such as structs will not fit into the buffer;
1078  * in such cases additional copies when we iterate over their
1079  * members may be needed.
1080  *
1081  * btf_show_obj_safe() is used to return a safe buffer for
1082  * btf_show_start_type(); this ensures that as we recurse into
1083  * nested types we always have safe data for the given type.
1084  * This approach is somewhat wasteful; it's possible for example
1085  * that when iterating over a large union we'll end up copying the
1086  * same data repeatedly, but the goal is safety not performance.
1087  * We use stack data as opposed to per-CPU buffers because the
1088  * iteration over a type can take some time, and preemption handling
1089  * would greatly complicate use of the safe buffer.
1090  */
1091 static void *btf_show_obj_safe(struct btf_show *show,
1092 			       const struct btf_type *t,
1093 			       void *data)
1094 {
1095 	const struct btf_type *rt;
1096 	int size_left, size;
1097 	void *safe = NULL;
1098 
1099 	if (show->flags & BTF_SHOW_UNSAFE)
1100 		return data;
1101 
1102 	rt = btf_resolve_size(show->btf, t, &size);
1103 	if (IS_ERR(rt)) {
1104 		show->state.status = PTR_ERR(rt);
1105 		return NULL;
1106 	}
1107 
1108 	/*
1109 	 * Is this toplevel object? If so, set total object size and
1110 	 * initialize pointers.  Otherwise check if we still fall within
1111 	 * our safe object data.
1112 	 */
1113 	if (show->state.depth == 0) {
1114 		show->obj.size = size;
1115 		show->obj.head = data;
1116 	} else {
1117 		/*
1118 		 * If the size of the current object is > our remaining
1119 		 * safe buffer we _may_ need to do a new copy.  However
1120 		 * consider the case of a nested struct; it's size pushes
1121 		 * us over the safe buffer limit, but showing any individual
1122 		 * struct members does not.  In such cases, we don't need
1123 		 * to initiate a fresh copy yet; however we definitely need
1124 		 * at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes left
1125 		 * in our buffer, regardless of the current object size.
1126 		 * The logic here is that as we resolve types we will
1127 		 * hit a base type at some point, and we need to be sure
1128 		 * the next chunk of data is safely available to display
1129 		 * that type info safely.  We cannot rely on the size of
1130 		 * the current object here because it may be much larger
1131 		 * than our current buffer (e.g. task_struct is 8k).
1132 		 * All we want to do here is ensure that we can print the
1133 		 * next basic type, which we can if either
1134 		 * - the current type size is within the safe buffer; or
1135 		 * - at least BTF_SHOW_OBJ_BASE_TYPE_SIZE bytes are left in
1136 		 *   the safe buffer.
1137 		 */
1138 		safe = __btf_show_obj_safe(show, data,
1139 					   min(size,
1140 					       BTF_SHOW_OBJ_BASE_TYPE_SIZE));
1141 	}
1142 
1143 	/*
1144 	 * We need a new copy to our safe object, either because we haven't
1145 	 * yet copied and are intializing safe data, or because the data
1146 	 * we want falls outside the boundaries of the safe object.
1147 	 */
1148 	if (!safe) {
1149 		size_left = btf_show_obj_size_left(show, data);
1150 		if (size_left > BTF_SHOW_OBJ_SAFE_SIZE)
1151 			size_left = BTF_SHOW_OBJ_SAFE_SIZE;
1152 		show->state.status = copy_from_kernel_nofault(show->obj.safe,
1153 							      data, size_left);
1154 		if (!show->state.status) {
1155 			show->obj.data = data;
1156 			safe = show->obj.safe;
1157 		}
1158 	}
1159 
1160 	return safe;
1161 }
1162 
1163 /*
1164  * Set the type we are starting to show and return a safe data pointer
1165  * to be used for showing the associated data.
1166  */
1167 static void *btf_show_start_type(struct btf_show *show,
1168 				 const struct btf_type *t,
1169 				 u32 type_id, void *data)
1170 {
1171 	show->state.type = t;
1172 	show->state.type_id = type_id;
1173 	show->state.name[0] = '\0';
1174 
1175 	return btf_show_obj_safe(show, t, data);
1176 }
1177 
1178 static void btf_show_end_type(struct btf_show *show)
1179 {
1180 	show->state.type = NULL;
1181 	show->state.type_id = 0;
1182 	show->state.name[0] = '\0';
1183 }
1184 
1185 static void *btf_show_start_aggr_type(struct btf_show *show,
1186 				      const struct btf_type *t,
1187 				      u32 type_id, void *data)
1188 {
1189 	void *safe_data = btf_show_start_type(show, t, type_id, data);
1190 
1191 	if (!safe_data)
1192 		return safe_data;
1193 
1194 	btf_show(show, "%s%s%s", btf_show_indent(show),
1195 		 btf_show_name(show),
1196 		 btf_show_newline(show));
1197 	show->state.depth++;
1198 	return safe_data;
1199 }
1200 
1201 static void btf_show_end_aggr_type(struct btf_show *show,
1202 				   const char *suffix)
1203 {
1204 	show->state.depth--;
1205 	btf_show(show, "%s%s%s%s", btf_show_indent(show), suffix,
1206 		 btf_show_delim(show), btf_show_newline(show));
1207 	btf_show_end_type(show);
1208 }
1209 
1210 static void btf_show_start_member(struct btf_show *show,
1211 				  const struct btf_member *m)
1212 {
1213 	show->state.member = m;
1214 }
1215 
1216 static void btf_show_start_array_member(struct btf_show *show)
1217 {
1218 	show->state.array_member = 1;
1219 	btf_show_start_member(show, NULL);
1220 }
1221 
1222 static void btf_show_end_member(struct btf_show *show)
1223 {
1224 	show->state.member = NULL;
1225 }
1226 
1227 static void btf_show_end_array_member(struct btf_show *show)
1228 {
1229 	show->state.array_member = 0;
1230 	btf_show_end_member(show);
1231 }
1232 
1233 static void *btf_show_start_array_type(struct btf_show *show,
1234 				       const struct btf_type *t,
1235 				       u32 type_id,
1236 				       u16 array_encoding,
1237 				       void *data)
1238 {
1239 	show->state.array_encoding = array_encoding;
1240 	show->state.array_terminated = 0;
1241 	return btf_show_start_aggr_type(show, t, type_id, data);
1242 }
1243 
1244 static void btf_show_end_array_type(struct btf_show *show)
1245 {
1246 	show->state.array_encoding = 0;
1247 	show->state.array_terminated = 0;
1248 	btf_show_end_aggr_type(show, "]");
1249 }
1250 
1251 static void *btf_show_start_struct_type(struct btf_show *show,
1252 					const struct btf_type *t,
1253 					u32 type_id,
1254 					void *data)
1255 {
1256 	return btf_show_start_aggr_type(show, t, type_id, data);
1257 }
1258 
1259 static void btf_show_end_struct_type(struct btf_show *show)
1260 {
1261 	btf_show_end_aggr_type(show, "}");
1262 }
1263 
1264 __printf(2, 3) static void __btf_verifier_log(struct bpf_verifier_log *log,
1265 					      const char *fmt, ...)
1266 {
1267 	va_list args;
1268 
1269 	va_start(args, fmt);
1270 	bpf_verifier_vlog(log, fmt, args);
1271 	va_end(args);
1272 }
1273 
1274 __printf(2, 3) static void btf_verifier_log(struct btf_verifier_env *env,
1275 					    const char *fmt, ...)
1276 {
1277 	struct bpf_verifier_log *log = &env->log;
1278 	va_list args;
1279 
1280 	if (!bpf_verifier_log_needed(log))
1281 		return;
1282 
1283 	va_start(args, fmt);
1284 	bpf_verifier_vlog(log, fmt, args);
1285 	va_end(args);
1286 }
1287 
1288 __printf(4, 5) static void __btf_verifier_log_type(struct btf_verifier_env *env,
1289 						   const struct btf_type *t,
1290 						   bool log_details,
1291 						   const char *fmt, ...)
1292 {
1293 	struct bpf_verifier_log *log = &env->log;
1294 	u8 kind = BTF_INFO_KIND(t->info);
1295 	struct btf *btf = env->btf;
1296 	va_list args;
1297 
1298 	if (!bpf_verifier_log_needed(log))
1299 		return;
1300 
1301 	/* btf verifier prints all types it is processing via
1302 	 * btf_verifier_log_type(..., fmt = NULL).
1303 	 * Skip those prints for in-kernel BTF verification.
1304 	 */
1305 	if (log->level == BPF_LOG_KERNEL && !fmt)
1306 		return;
1307 
1308 	__btf_verifier_log(log, "[%u] %s %s%s",
1309 			   env->log_type_id,
1310 			   btf_kind_str[kind],
1311 			   __btf_name_by_offset(btf, t->name_off),
1312 			   log_details ? " " : "");
1313 
1314 	if (log_details)
1315 		btf_type_ops(t)->log_details(env, t);
1316 
1317 	if (fmt && *fmt) {
1318 		__btf_verifier_log(log, " ");
1319 		va_start(args, fmt);
1320 		bpf_verifier_vlog(log, fmt, args);
1321 		va_end(args);
1322 	}
1323 
1324 	__btf_verifier_log(log, "\n");
1325 }
1326 
1327 #define btf_verifier_log_type(env, t, ...) \
1328 	__btf_verifier_log_type((env), (t), true, __VA_ARGS__)
1329 #define btf_verifier_log_basic(env, t, ...) \
1330 	__btf_verifier_log_type((env), (t), false, __VA_ARGS__)
1331 
1332 __printf(4, 5)
1333 static void btf_verifier_log_member(struct btf_verifier_env *env,
1334 				    const struct btf_type *struct_type,
1335 				    const struct btf_member *member,
1336 				    const char *fmt, ...)
1337 {
1338 	struct bpf_verifier_log *log = &env->log;
1339 	struct btf *btf = env->btf;
1340 	va_list args;
1341 
1342 	if (!bpf_verifier_log_needed(log))
1343 		return;
1344 
1345 	if (log->level == BPF_LOG_KERNEL && !fmt)
1346 		return;
1347 	/* The CHECK_META phase already did a btf dump.
1348 	 *
1349 	 * If member is logged again, it must hit an error in
1350 	 * parsing this member.  It is useful to print out which
1351 	 * struct this member belongs to.
1352 	 */
1353 	if (env->phase != CHECK_META)
1354 		btf_verifier_log_type(env, struct_type, NULL);
1355 
1356 	if (btf_type_kflag(struct_type))
1357 		__btf_verifier_log(log,
1358 				   "\t%s type_id=%u bitfield_size=%u bits_offset=%u",
1359 				   __btf_name_by_offset(btf, member->name_off),
1360 				   member->type,
1361 				   BTF_MEMBER_BITFIELD_SIZE(member->offset),
1362 				   BTF_MEMBER_BIT_OFFSET(member->offset));
1363 	else
1364 		__btf_verifier_log(log, "\t%s type_id=%u bits_offset=%u",
1365 				   __btf_name_by_offset(btf, member->name_off),
1366 				   member->type, member->offset);
1367 
1368 	if (fmt && *fmt) {
1369 		__btf_verifier_log(log, " ");
1370 		va_start(args, fmt);
1371 		bpf_verifier_vlog(log, fmt, args);
1372 		va_end(args);
1373 	}
1374 
1375 	__btf_verifier_log(log, "\n");
1376 }
1377 
1378 __printf(4, 5)
1379 static void btf_verifier_log_vsi(struct btf_verifier_env *env,
1380 				 const struct btf_type *datasec_type,
1381 				 const struct btf_var_secinfo *vsi,
1382 				 const char *fmt, ...)
1383 {
1384 	struct bpf_verifier_log *log = &env->log;
1385 	va_list args;
1386 
1387 	if (!bpf_verifier_log_needed(log))
1388 		return;
1389 	if (log->level == BPF_LOG_KERNEL && !fmt)
1390 		return;
1391 	if (env->phase != CHECK_META)
1392 		btf_verifier_log_type(env, datasec_type, NULL);
1393 
1394 	__btf_verifier_log(log, "\t type_id=%u offset=%u size=%u",
1395 			   vsi->type, vsi->offset, vsi->size);
1396 	if (fmt && *fmt) {
1397 		__btf_verifier_log(log, " ");
1398 		va_start(args, fmt);
1399 		bpf_verifier_vlog(log, fmt, args);
1400 		va_end(args);
1401 	}
1402 
1403 	__btf_verifier_log(log, "\n");
1404 }
1405 
1406 static void btf_verifier_log_hdr(struct btf_verifier_env *env,
1407 				 u32 btf_data_size)
1408 {
1409 	struct bpf_verifier_log *log = &env->log;
1410 	const struct btf *btf = env->btf;
1411 	const struct btf_header *hdr;
1412 
1413 	if (!bpf_verifier_log_needed(log))
1414 		return;
1415 
1416 	if (log->level == BPF_LOG_KERNEL)
1417 		return;
1418 	hdr = &btf->hdr;
1419 	__btf_verifier_log(log, "magic: 0x%x\n", hdr->magic);
1420 	__btf_verifier_log(log, "version: %u\n", hdr->version);
1421 	__btf_verifier_log(log, "flags: 0x%x\n", hdr->flags);
1422 	__btf_verifier_log(log, "hdr_len: %u\n", hdr->hdr_len);
1423 	__btf_verifier_log(log, "type_off: %u\n", hdr->type_off);
1424 	__btf_verifier_log(log, "type_len: %u\n", hdr->type_len);
1425 	__btf_verifier_log(log, "str_off: %u\n", hdr->str_off);
1426 	__btf_verifier_log(log, "str_len: %u\n", hdr->str_len);
1427 	__btf_verifier_log(log, "btf_total_size: %u\n", btf_data_size);
1428 }
1429 
1430 static int btf_add_type(struct btf_verifier_env *env, struct btf_type *t)
1431 {
1432 	struct btf *btf = env->btf;
1433 
1434 	if (btf->types_size == btf->nr_types) {
1435 		/* Expand 'types' array */
1436 
1437 		struct btf_type **new_types;
1438 		u32 expand_by, new_size;
1439 
1440 		if (btf->start_id + btf->types_size == BTF_MAX_TYPE) {
1441 			btf_verifier_log(env, "Exceeded max num of types");
1442 			return -E2BIG;
1443 		}
1444 
1445 		expand_by = max_t(u32, btf->types_size >> 2, 16);
1446 		new_size = min_t(u32, BTF_MAX_TYPE,
1447 				 btf->types_size + expand_by);
1448 
1449 		new_types = kvcalloc(new_size, sizeof(*new_types),
1450 				     GFP_KERNEL | __GFP_NOWARN);
1451 		if (!new_types)
1452 			return -ENOMEM;
1453 
1454 		if (btf->nr_types == 0) {
1455 			if (!btf->base_btf) {
1456 				/* lazily init VOID type */
1457 				new_types[0] = &btf_void;
1458 				btf->nr_types++;
1459 			}
1460 		} else {
1461 			memcpy(new_types, btf->types,
1462 			       sizeof(*btf->types) * btf->nr_types);
1463 		}
1464 
1465 		kvfree(btf->types);
1466 		btf->types = new_types;
1467 		btf->types_size = new_size;
1468 	}
1469 
1470 	btf->types[btf->nr_types++] = t;
1471 
1472 	return 0;
1473 }
1474 
1475 static int btf_alloc_id(struct btf *btf)
1476 {
1477 	int id;
1478 
1479 	idr_preload(GFP_KERNEL);
1480 	spin_lock_bh(&btf_idr_lock);
1481 	id = idr_alloc_cyclic(&btf_idr, btf, 1, INT_MAX, GFP_ATOMIC);
1482 	if (id > 0)
1483 		btf->id = id;
1484 	spin_unlock_bh(&btf_idr_lock);
1485 	idr_preload_end();
1486 
1487 	if (WARN_ON_ONCE(!id))
1488 		return -ENOSPC;
1489 
1490 	return id > 0 ? 0 : id;
1491 }
1492 
1493 static void btf_free_id(struct btf *btf)
1494 {
1495 	unsigned long flags;
1496 
1497 	/*
1498 	 * In map-in-map, calling map_delete_elem() on outer
1499 	 * map will call bpf_map_put on the inner map.
1500 	 * It will then eventually call btf_free_id()
1501 	 * on the inner map.  Some of the map_delete_elem()
1502 	 * implementation may have irq disabled, so
1503 	 * we need to use the _irqsave() version instead
1504 	 * of the _bh() version.
1505 	 */
1506 	spin_lock_irqsave(&btf_idr_lock, flags);
1507 	idr_remove(&btf_idr, btf->id);
1508 	spin_unlock_irqrestore(&btf_idr_lock, flags);
1509 }
1510 
1511 static void btf_free(struct btf *btf)
1512 {
1513 	kvfree(btf->types);
1514 	kvfree(btf->resolved_sizes);
1515 	kvfree(btf->resolved_ids);
1516 	kvfree(btf->data);
1517 	kfree(btf);
1518 }
1519 
1520 static void btf_free_rcu(struct rcu_head *rcu)
1521 {
1522 	struct btf *btf = container_of(rcu, struct btf, rcu);
1523 
1524 	btf_free(btf);
1525 }
1526 
1527 void btf_get(struct btf *btf)
1528 {
1529 	refcount_inc(&btf->refcnt);
1530 }
1531 
1532 void btf_put(struct btf *btf)
1533 {
1534 	if (btf && refcount_dec_and_test(&btf->refcnt)) {
1535 		btf_free_id(btf);
1536 		call_rcu(&btf->rcu, btf_free_rcu);
1537 	}
1538 }
1539 
1540 static int env_resolve_init(struct btf_verifier_env *env)
1541 {
1542 	struct btf *btf = env->btf;
1543 	u32 nr_types = btf->nr_types;
1544 	u32 *resolved_sizes = NULL;
1545 	u32 *resolved_ids = NULL;
1546 	u8 *visit_states = NULL;
1547 
1548 	resolved_sizes = kvcalloc(nr_types, sizeof(*resolved_sizes),
1549 				  GFP_KERNEL | __GFP_NOWARN);
1550 	if (!resolved_sizes)
1551 		goto nomem;
1552 
1553 	resolved_ids = kvcalloc(nr_types, sizeof(*resolved_ids),
1554 				GFP_KERNEL | __GFP_NOWARN);
1555 	if (!resolved_ids)
1556 		goto nomem;
1557 
1558 	visit_states = kvcalloc(nr_types, sizeof(*visit_states),
1559 				GFP_KERNEL | __GFP_NOWARN);
1560 	if (!visit_states)
1561 		goto nomem;
1562 
1563 	btf->resolved_sizes = resolved_sizes;
1564 	btf->resolved_ids = resolved_ids;
1565 	env->visit_states = visit_states;
1566 
1567 	return 0;
1568 
1569 nomem:
1570 	kvfree(resolved_sizes);
1571 	kvfree(resolved_ids);
1572 	kvfree(visit_states);
1573 	return -ENOMEM;
1574 }
1575 
1576 static void btf_verifier_env_free(struct btf_verifier_env *env)
1577 {
1578 	kvfree(env->visit_states);
1579 	kfree(env);
1580 }
1581 
1582 static bool env_type_is_resolve_sink(const struct btf_verifier_env *env,
1583 				     const struct btf_type *next_type)
1584 {
1585 	switch (env->resolve_mode) {
1586 	case RESOLVE_TBD:
1587 		/* int, enum or void is a sink */
1588 		return !btf_type_needs_resolve(next_type);
1589 	case RESOLVE_PTR:
1590 		/* int, enum, void, struct, array, func or func_proto is a sink
1591 		 * for ptr
1592 		 */
1593 		return !btf_type_is_modifier(next_type) &&
1594 			!btf_type_is_ptr(next_type);
1595 	case RESOLVE_STRUCT_OR_ARRAY:
1596 		/* int, enum, void, ptr, func or func_proto is a sink
1597 		 * for struct and array
1598 		 */
1599 		return !btf_type_is_modifier(next_type) &&
1600 			!btf_type_is_array(next_type) &&
1601 			!btf_type_is_struct(next_type);
1602 	default:
1603 		BUG();
1604 	}
1605 }
1606 
1607 static bool env_type_is_resolved(const struct btf_verifier_env *env,
1608 				 u32 type_id)
1609 {
1610 	/* base BTF types should be resolved by now */
1611 	if (type_id < env->btf->start_id)
1612 		return true;
1613 
1614 	return env->visit_states[type_id - env->btf->start_id] == RESOLVED;
1615 }
1616 
1617 static int env_stack_push(struct btf_verifier_env *env,
1618 			  const struct btf_type *t, u32 type_id)
1619 {
1620 	const struct btf *btf = env->btf;
1621 	struct resolve_vertex *v;
1622 
1623 	if (env->top_stack == MAX_RESOLVE_DEPTH)
1624 		return -E2BIG;
1625 
1626 	if (type_id < btf->start_id
1627 	    || env->visit_states[type_id - btf->start_id] != NOT_VISITED)
1628 		return -EEXIST;
1629 
1630 	env->visit_states[type_id - btf->start_id] = VISITED;
1631 
1632 	v = &env->stack[env->top_stack++];
1633 	v->t = t;
1634 	v->type_id = type_id;
1635 	v->next_member = 0;
1636 
1637 	if (env->resolve_mode == RESOLVE_TBD) {
1638 		if (btf_type_is_ptr(t))
1639 			env->resolve_mode = RESOLVE_PTR;
1640 		else if (btf_type_is_struct(t) || btf_type_is_array(t))
1641 			env->resolve_mode = RESOLVE_STRUCT_OR_ARRAY;
1642 	}
1643 
1644 	return 0;
1645 }
1646 
1647 static void env_stack_set_next_member(struct btf_verifier_env *env,
1648 				      u16 next_member)
1649 {
1650 	env->stack[env->top_stack - 1].next_member = next_member;
1651 }
1652 
1653 static void env_stack_pop_resolved(struct btf_verifier_env *env,
1654 				   u32 resolved_type_id,
1655 				   u32 resolved_size)
1656 {
1657 	u32 type_id = env->stack[--(env->top_stack)].type_id;
1658 	struct btf *btf = env->btf;
1659 
1660 	type_id -= btf->start_id; /* adjust to local type id */
1661 	btf->resolved_sizes[type_id] = resolved_size;
1662 	btf->resolved_ids[type_id] = resolved_type_id;
1663 	env->visit_states[type_id] = RESOLVED;
1664 }
1665 
1666 static const struct resolve_vertex *env_stack_peak(struct btf_verifier_env *env)
1667 {
1668 	return env->top_stack ? &env->stack[env->top_stack - 1] : NULL;
1669 }
1670 
1671 /* Resolve the size of a passed-in "type"
1672  *
1673  * type: is an array (e.g. u32 array[x][y])
1674  * return type: type "u32[x][y]", i.e. BTF_KIND_ARRAY,
1675  * *type_size: (x * y * sizeof(u32)).  Hence, *type_size always
1676  *             corresponds to the return type.
1677  * *elem_type: u32
1678  * *elem_id: id of u32
1679  * *total_nelems: (x * y).  Hence, individual elem size is
1680  *                (*type_size / *total_nelems)
1681  * *type_id: id of type if it's changed within the function, 0 if not
1682  *
1683  * type: is not an array (e.g. const struct X)
1684  * return type: type "struct X"
1685  * *type_size: sizeof(struct X)
1686  * *elem_type: same as return type ("struct X")
1687  * *elem_id: 0
1688  * *total_nelems: 1
1689  * *type_id: id of type if it's changed within the function, 0 if not
1690  */
1691 static const struct btf_type *
1692 __btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1693 		   u32 *type_size, const struct btf_type **elem_type,
1694 		   u32 *elem_id, u32 *total_nelems, u32 *type_id)
1695 {
1696 	const struct btf_type *array_type = NULL;
1697 	const struct btf_array *array = NULL;
1698 	u32 i, size, nelems = 1, id = 0;
1699 
1700 	for (i = 0; i < MAX_RESOLVE_DEPTH; i++) {
1701 		switch (BTF_INFO_KIND(type->info)) {
1702 		/* type->size can be used */
1703 		case BTF_KIND_INT:
1704 		case BTF_KIND_STRUCT:
1705 		case BTF_KIND_UNION:
1706 		case BTF_KIND_ENUM:
1707 			size = type->size;
1708 			goto resolved;
1709 
1710 		case BTF_KIND_PTR:
1711 			size = sizeof(void *);
1712 			goto resolved;
1713 
1714 		/* Modifiers */
1715 		case BTF_KIND_TYPEDEF:
1716 		case BTF_KIND_VOLATILE:
1717 		case BTF_KIND_CONST:
1718 		case BTF_KIND_RESTRICT:
1719 			id = type->type;
1720 			type = btf_type_by_id(btf, type->type);
1721 			break;
1722 
1723 		case BTF_KIND_ARRAY:
1724 			if (!array_type)
1725 				array_type = type;
1726 			array = btf_type_array(type);
1727 			if (nelems && array->nelems > U32_MAX / nelems)
1728 				return ERR_PTR(-EINVAL);
1729 			nelems *= array->nelems;
1730 			type = btf_type_by_id(btf, array->type);
1731 			break;
1732 
1733 		/* type without size */
1734 		default:
1735 			return ERR_PTR(-EINVAL);
1736 		}
1737 	}
1738 
1739 	return ERR_PTR(-EINVAL);
1740 
1741 resolved:
1742 	if (nelems && size > U32_MAX / nelems)
1743 		return ERR_PTR(-EINVAL);
1744 
1745 	*type_size = nelems * size;
1746 	if (total_nelems)
1747 		*total_nelems = nelems;
1748 	if (elem_type)
1749 		*elem_type = type;
1750 	if (elem_id)
1751 		*elem_id = array ? array->type : 0;
1752 	if (type_id && id)
1753 		*type_id = id;
1754 
1755 	return array_type ? : type;
1756 }
1757 
1758 const struct btf_type *
1759 btf_resolve_size(const struct btf *btf, const struct btf_type *type,
1760 		 u32 *type_size)
1761 {
1762 	return __btf_resolve_size(btf, type, type_size, NULL, NULL, NULL, NULL);
1763 }
1764 
1765 static u32 btf_resolved_type_id(const struct btf *btf, u32 type_id)
1766 {
1767 	while (type_id < btf->start_id)
1768 		btf = btf->base_btf;
1769 
1770 	return btf->resolved_ids[type_id - btf->start_id];
1771 }
1772 
1773 /* The input param "type_id" must point to a needs_resolve type */
1774 static const struct btf_type *btf_type_id_resolve(const struct btf *btf,
1775 						  u32 *type_id)
1776 {
1777 	*type_id = btf_resolved_type_id(btf, *type_id);
1778 	return btf_type_by_id(btf, *type_id);
1779 }
1780 
1781 static u32 btf_resolved_type_size(const struct btf *btf, u32 type_id)
1782 {
1783 	while (type_id < btf->start_id)
1784 		btf = btf->base_btf;
1785 
1786 	return btf->resolved_sizes[type_id - btf->start_id];
1787 }
1788 
1789 const struct btf_type *btf_type_id_size(const struct btf *btf,
1790 					u32 *type_id, u32 *ret_size)
1791 {
1792 	const struct btf_type *size_type;
1793 	u32 size_type_id = *type_id;
1794 	u32 size = 0;
1795 
1796 	size_type = btf_type_by_id(btf, size_type_id);
1797 	if (btf_type_nosize_or_null(size_type))
1798 		return NULL;
1799 
1800 	if (btf_type_has_size(size_type)) {
1801 		size = size_type->size;
1802 	} else if (btf_type_is_array(size_type)) {
1803 		size = btf_resolved_type_size(btf, size_type_id);
1804 	} else if (btf_type_is_ptr(size_type)) {
1805 		size = sizeof(void *);
1806 	} else {
1807 		if (WARN_ON_ONCE(!btf_type_is_modifier(size_type) &&
1808 				 !btf_type_is_var(size_type)))
1809 			return NULL;
1810 
1811 		size_type_id = btf_resolved_type_id(btf, size_type_id);
1812 		size_type = btf_type_by_id(btf, size_type_id);
1813 		if (btf_type_nosize_or_null(size_type))
1814 			return NULL;
1815 		else if (btf_type_has_size(size_type))
1816 			size = size_type->size;
1817 		else if (btf_type_is_array(size_type))
1818 			size = btf_resolved_type_size(btf, size_type_id);
1819 		else if (btf_type_is_ptr(size_type))
1820 			size = sizeof(void *);
1821 		else
1822 			return NULL;
1823 	}
1824 
1825 	*type_id = size_type_id;
1826 	if (ret_size)
1827 		*ret_size = size;
1828 
1829 	return size_type;
1830 }
1831 
1832 static int btf_df_check_member(struct btf_verifier_env *env,
1833 			       const struct btf_type *struct_type,
1834 			       const struct btf_member *member,
1835 			       const struct btf_type *member_type)
1836 {
1837 	btf_verifier_log_basic(env, struct_type,
1838 			       "Unsupported check_member");
1839 	return -EINVAL;
1840 }
1841 
1842 static int btf_df_check_kflag_member(struct btf_verifier_env *env,
1843 				     const struct btf_type *struct_type,
1844 				     const struct btf_member *member,
1845 				     const struct btf_type *member_type)
1846 {
1847 	btf_verifier_log_basic(env, struct_type,
1848 			       "Unsupported check_kflag_member");
1849 	return -EINVAL;
1850 }
1851 
1852 /* Used for ptr, array and struct/union type members.
1853  * int, enum and modifier types have their specific callback functions.
1854  */
1855 static int btf_generic_check_kflag_member(struct btf_verifier_env *env,
1856 					  const struct btf_type *struct_type,
1857 					  const struct btf_member *member,
1858 					  const struct btf_type *member_type)
1859 {
1860 	if (BTF_MEMBER_BITFIELD_SIZE(member->offset)) {
1861 		btf_verifier_log_member(env, struct_type, member,
1862 					"Invalid member bitfield_size");
1863 		return -EINVAL;
1864 	}
1865 
1866 	/* bitfield size is 0, so member->offset represents bit offset only.
1867 	 * It is safe to call non kflag check_member variants.
1868 	 */
1869 	return btf_type_ops(member_type)->check_member(env, struct_type,
1870 						       member,
1871 						       member_type);
1872 }
1873 
1874 static int btf_df_resolve(struct btf_verifier_env *env,
1875 			  const struct resolve_vertex *v)
1876 {
1877 	btf_verifier_log_basic(env, v->t, "Unsupported resolve");
1878 	return -EINVAL;
1879 }
1880 
1881 static void btf_df_show(const struct btf *btf, const struct btf_type *t,
1882 			u32 type_id, void *data, u8 bits_offsets,
1883 			struct btf_show *show)
1884 {
1885 	btf_show(show, "<unsupported kind:%u>", BTF_INFO_KIND(t->info));
1886 }
1887 
1888 static int btf_int_check_member(struct btf_verifier_env *env,
1889 				const struct btf_type *struct_type,
1890 				const struct btf_member *member,
1891 				const struct btf_type *member_type)
1892 {
1893 	u32 int_data = btf_type_int(member_type);
1894 	u32 struct_bits_off = member->offset;
1895 	u32 struct_size = struct_type->size;
1896 	u32 nr_copy_bits;
1897 	u32 bytes_offset;
1898 
1899 	if (U32_MAX - struct_bits_off < BTF_INT_OFFSET(int_data)) {
1900 		btf_verifier_log_member(env, struct_type, member,
1901 					"bits_offset exceeds U32_MAX");
1902 		return -EINVAL;
1903 	}
1904 
1905 	struct_bits_off += BTF_INT_OFFSET(int_data);
1906 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1907 	nr_copy_bits = BTF_INT_BITS(int_data) +
1908 		BITS_PER_BYTE_MASKED(struct_bits_off);
1909 
1910 	if (nr_copy_bits > BITS_PER_U128) {
1911 		btf_verifier_log_member(env, struct_type, member,
1912 					"nr_copy_bits exceeds 128");
1913 		return -EINVAL;
1914 	}
1915 
1916 	if (struct_size < bytes_offset ||
1917 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1918 		btf_verifier_log_member(env, struct_type, member,
1919 					"Member exceeds struct_size");
1920 		return -EINVAL;
1921 	}
1922 
1923 	return 0;
1924 }
1925 
1926 static int btf_int_check_kflag_member(struct btf_verifier_env *env,
1927 				      const struct btf_type *struct_type,
1928 				      const struct btf_member *member,
1929 				      const struct btf_type *member_type)
1930 {
1931 	u32 struct_bits_off, nr_bits, nr_int_data_bits, bytes_offset;
1932 	u32 int_data = btf_type_int(member_type);
1933 	u32 struct_size = struct_type->size;
1934 	u32 nr_copy_bits;
1935 
1936 	/* a regular int type is required for the kflag int member */
1937 	if (!btf_type_int_is_regular(member_type)) {
1938 		btf_verifier_log_member(env, struct_type, member,
1939 					"Invalid member base type");
1940 		return -EINVAL;
1941 	}
1942 
1943 	/* check sanity of bitfield size */
1944 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
1945 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
1946 	nr_int_data_bits = BTF_INT_BITS(int_data);
1947 	if (!nr_bits) {
1948 		/* Not a bitfield member, member offset must be at byte
1949 		 * boundary.
1950 		 */
1951 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
1952 			btf_verifier_log_member(env, struct_type, member,
1953 						"Invalid member offset");
1954 			return -EINVAL;
1955 		}
1956 
1957 		nr_bits = nr_int_data_bits;
1958 	} else if (nr_bits > nr_int_data_bits) {
1959 		btf_verifier_log_member(env, struct_type, member,
1960 					"Invalid member bitfield_size");
1961 		return -EINVAL;
1962 	}
1963 
1964 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
1965 	nr_copy_bits = nr_bits + BITS_PER_BYTE_MASKED(struct_bits_off);
1966 	if (nr_copy_bits > BITS_PER_U128) {
1967 		btf_verifier_log_member(env, struct_type, member,
1968 					"nr_copy_bits exceeds 128");
1969 		return -EINVAL;
1970 	}
1971 
1972 	if (struct_size < bytes_offset ||
1973 	    struct_size - bytes_offset < BITS_ROUNDUP_BYTES(nr_copy_bits)) {
1974 		btf_verifier_log_member(env, struct_type, member,
1975 					"Member exceeds struct_size");
1976 		return -EINVAL;
1977 	}
1978 
1979 	return 0;
1980 }
1981 
1982 static s32 btf_int_check_meta(struct btf_verifier_env *env,
1983 			      const struct btf_type *t,
1984 			      u32 meta_left)
1985 {
1986 	u32 int_data, nr_bits, meta_needed = sizeof(int_data);
1987 	u16 encoding;
1988 
1989 	if (meta_left < meta_needed) {
1990 		btf_verifier_log_basic(env, t,
1991 				       "meta_left:%u meta_needed:%u",
1992 				       meta_left, meta_needed);
1993 		return -EINVAL;
1994 	}
1995 
1996 	if (btf_type_vlen(t)) {
1997 		btf_verifier_log_type(env, t, "vlen != 0");
1998 		return -EINVAL;
1999 	}
2000 
2001 	if (btf_type_kflag(t)) {
2002 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2003 		return -EINVAL;
2004 	}
2005 
2006 	int_data = btf_type_int(t);
2007 	if (int_data & ~BTF_INT_MASK) {
2008 		btf_verifier_log_basic(env, t, "Invalid int_data:%x",
2009 				       int_data);
2010 		return -EINVAL;
2011 	}
2012 
2013 	nr_bits = BTF_INT_BITS(int_data) + BTF_INT_OFFSET(int_data);
2014 
2015 	if (nr_bits > BITS_PER_U128) {
2016 		btf_verifier_log_type(env, t, "nr_bits exceeds %zu",
2017 				      BITS_PER_U128);
2018 		return -EINVAL;
2019 	}
2020 
2021 	if (BITS_ROUNDUP_BYTES(nr_bits) > t->size) {
2022 		btf_verifier_log_type(env, t, "nr_bits exceeds type_size");
2023 		return -EINVAL;
2024 	}
2025 
2026 	/*
2027 	 * Only one of the encoding bits is allowed and it
2028 	 * should be sufficient for the pretty print purpose (i.e. decoding).
2029 	 * Multiple bits can be allowed later if it is found
2030 	 * to be insufficient.
2031 	 */
2032 	encoding = BTF_INT_ENCODING(int_data);
2033 	if (encoding &&
2034 	    encoding != BTF_INT_SIGNED &&
2035 	    encoding != BTF_INT_CHAR &&
2036 	    encoding != BTF_INT_BOOL) {
2037 		btf_verifier_log_type(env, t, "Unsupported encoding");
2038 		return -ENOTSUPP;
2039 	}
2040 
2041 	btf_verifier_log_type(env, t, NULL);
2042 
2043 	return meta_needed;
2044 }
2045 
2046 static void btf_int_log(struct btf_verifier_env *env,
2047 			const struct btf_type *t)
2048 {
2049 	int int_data = btf_type_int(t);
2050 
2051 	btf_verifier_log(env,
2052 			 "size=%u bits_offset=%u nr_bits=%u encoding=%s",
2053 			 t->size, BTF_INT_OFFSET(int_data),
2054 			 BTF_INT_BITS(int_data),
2055 			 btf_int_encoding_str(BTF_INT_ENCODING(int_data)));
2056 }
2057 
2058 static void btf_int128_print(struct btf_show *show, void *data)
2059 {
2060 	/* data points to a __int128 number.
2061 	 * Suppose
2062 	 *     int128_num = *(__int128 *)data;
2063 	 * The below formulas shows what upper_num and lower_num represents:
2064 	 *     upper_num = int128_num >> 64;
2065 	 *     lower_num = int128_num & 0xffffffffFFFFFFFFULL;
2066 	 */
2067 	u64 upper_num, lower_num;
2068 
2069 #ifdef __BIG_ENDIAN_BITFIELD
2070 	upper_num = *(u64 *)data;
2071 	lower_num = *(u64 *)(data + 8);
2072 #else
2073 	upper_num = *(u64 *)(data + 8);
2074 	lower_num = *(u64 *)data;
2075 #endif
2076 	if (upper_num == 0)
2077 		btf_show_type_value(show, "0x%llx", lower_num);
2078 	else
2079 		btf_show_type_values(show, "0x%llx%016llx", upper_num,
2080 				     lower_num);
2081 }
2082 
2083 static void btf_int128_shift(u64 *print_num, u16 left_shift_bits,
2084 			     u16 right_shift_bits)
2085 {
2086 	u64 upper_num, lower_num;
2087 
2088 #ifdef __BIG_ENDIAN_BITFIELD
2089 	upper_num = print_num[0];
2090 	lower_num = print_num[1];
2091 #else
2092 	upper_num = print_num[1];
2093 	lower_num = print_num[0];
2094 #endif
2095 
2096 	/* shake out un-needed bits by shift/or operations */
2097 	if (left_shift_bits >= 64) {
2098 		upper_num = lower_num << (left_shift_bits - 64);
2099 		lower_num = 0;
2100 	} else {
2101 		upper_num = (upper_num << left_shift_bits) |
2102 			    (lower_num >> (64 - left_shift_bits));
2103 		lower_num = lower_num << left_shift_bits;
2104 	}
2105 
2106 	if (right_shift_bits >= 64) {
2107 		lower_num = upper_num >> (right_shift_bits - 64);
2108 		upper_num = 0;
2109 	} else {
2110 		lower_num = (lower_num >> right_shift_bits) |
2111 			    (upper_num << (64 - right_shift_bits));
2112 		upper_num = upper_num >> right_shift_bits;
2113 	}
2114 
2115 #ifdef __BIG_ENDIAN_BITFIELD
2116 	print_num[0] = upper_num;
2117 	print_num[1] = lower_num;
2118 #else
2119 	print_num[0] = lower_num;
2120 	print_num[1] = upper_num;
2121 #endif
2122 }
2123 
2124 static void btf_bitfield_show(void *data, u8 bits_offset,
2125 			      u8 nr_bits, struct btf_show *show)
2126 {
2127 	u16 left_shift_bits, right_shift_bits;
2128 	u8 nr_copy_bytes;
2129 	u8 nr_copy_bits;
2130 	u64 print_num[2] = {};
2131 
2132 	nr_copy_bits = nr_bits + bits_offset;
2133 	nr_copy_bytes = BITS_ROUNDUP_BYTES(nr_copy_bits);
2134 
2135 	memcpy(print_num, data, nr_copy_bytes);
2136 
2137 #ifdef __BIG_ENDIAN_BITFIELD
2138 	left_shift_bits = bits_offset;
2139 #else
2140 	left_shift_bits = BITS_PER_U128 - nr_copy_bits;
2141 #endif
2142 	right_shift_bits = BITS_PER_U128 - nr_bits;
2143 
2144 	btf_int128_shift(print_num, left_shift_bits, right_shift_bits);
2145 	btf_int128_print(show, print_num);
2146 }
2147 
2148 
2149 static void btf_int_bits_show(const struct btf *btf,
2150 			      const struct btf_type *t,
2151 			      void *data, u8 bits_offset,
2152 			      struct btf_show *show)
2153 {
2154 	u32 int_data = btf_type_int(t);
2155 	u8 nr_bits = BTF_INT_BITS(int_data);
2156 	u8 total_bits_offset;
2157 
2158 	/*
2159 	 * bits_offset is at most 7.
2160 	 * BTF_INT_OFFSET() cannot exceed 128 bits.
2161 	 */
2162 	total_bits_offset = bits_offset + BTF_INT_OFFSET(int_data);
2163 	data += BITS_ROUNDDOWN_BYTES(total_bits_offset);
2164 	bits_offset = BITS_PER_BYTE_MASKED(total_bits_offset);
2165 	btf_bitfield_show(data, bits_offset, nr_bits, show);
2166 }
2167 
2168 static void btf_int_show(const struct btf *btf, const struct btf_type *t,
2169 			 u32 type_id, void *data, u8 bits_offset,
2170 			 struct btf_show *show)
2171 {
2172 	u32 int_data = btf_type_int(t);
2173 	u8 encoding = BTF_INT_ENCODING(int_data);
2174 	bool sign = encoding & BTF_INT_SIGNED;
2175 	u8 nr_bits = BTF_INT_BITS(int_data);
2176 	void *safe_data;
2177 
2178 	safe_data = btf_show_start_type(show, t, type_id, data);
2179 	if (!safe_data)
2180 		return;
2181 
2182 	if (bits_offset || BTF_INT_OFFSET(int_data) ||
2183 	    BITS_PER_BYTE_MASKED(nr_bits)) {
2184 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2185 		goto out;
2186 	}
2187 
2188 	switch (nr_bits) {
2189 	case 128:
2190 		btf_int128_print(show, safe_data);
2191 		break;
2192 	case 64:
2193 		if (sign)
2194 			btf_show_type_value(show, "%lld", *(s64 *)safe_data);
2195 		else
2196 			btf_show_type_value(show, "%llu", *(u64 *)safe_data);
2197 		break;
2198 	case 32:
2199 		if (sign)
2200 			btf_show_type_value(show, "%d", *(s32 *)safe_data);
2201 		else
2202 			btf_show_type_value(show, "%u", *(u32 *)safe_data);
2203 		break;
2204 	case 16:
2205 		if (sign)
2206 			btf_show_type_value(show, "%d", *(s16 *)safe_data);
2207 		else
2208 			btf_show_type_value(show, "%u", *(u16 *)safe_data);
2209 		break;
2210 	case 8:
2211 		if (show->state.array_encoding == BTF_INT_CHAR) {
2212 			/* check for null terminator */
2213 			if (show->state.array_terminated)
2214 				break;
2215 			if (*(char *)data == '\0') {
2216 				show->state.array_terminated = 1;
2217 				break;
2218 			}
2219 			if (isprint(*(char *)data)) {
2220 				btf_show_type_value(show, "'%c'",
2221 						    *(char *)safe_data);
2222 				break;
2223 			}
2224 		}
2225 		if (sign)
2226 			btf_show_type_value(show, "%d", *(s8 *)safe_data);
2227 		else
2228 			btf_show_type_value(show, "%u", *(u8 *)safe_data);
2229 		break;
2230 	default:
2231 		btf_int_bits_show(btf, t, safe_data, bits_offset, show);
2232 		break;
2233 	}
2234 out:
2235 	btf_show_end_type(show);
2236 }
2237 
2238 static const struct btf_kind_operations int_ops = {
2239 	.check_meta = btf_int_check_meta,
2240 	.resolve = btf_df_resolve,
2241 	.check_member = btf_int_check_member,
2242 	.check_kflag_member = btf_int_check_kflag_member,
2243 	.log_details = btf_int_log,
2244 	.show = btf_int_show,
2245 };
2246 
2247 static int btf_modifier_check_member(struct btf_verifier_env *env,
2248 				     const struct btf_type *struct_type,
2249 				     const struct btf_member *member,
2250 				     const struct btf_type *member_type)
2251 {
2252 	const struct btf_type *resolved_type;
2253 	u32 resolved_type_id = member->type;
2254 	struct btf_member resolved_member;
2255 	struct btf *btf = env->btf;
2256 
2257 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2258 	if (!resolved_type) {
2259 		btf_verifier_log_member(env, struct_type, member,
2260 					"Invalid member");
2261 		return -EINVAL;
2262 	}
2263 
2264 	resolved_member = *member;
2265 	resolved_member.type = resolved_type_id;
2266 
2267 	return btf_type_ops(resolved_type)->check_member(env, struct_type,
2268 							 &resolved_member,
2269 							 resolved_type);
2270 }
2271 
2272 static int btf_modifier_check_kflag_member(struct btf_verifier_env *env,
2273 					   const struct btf_type *struct_type,
2274 					   const struct btf_member *member,
2275 					   const struct btf_type *member_type)
2276 {
2277 	const struct btf_type *resolved_type;
2278 	u32 resolved_type_id = member->type;
2279 	struct btf_member resolved_member;
2280 	struct btf *btf = env->btf;
2281 
2282 	resolved_type = btf_type_id_size(btf, &resolved_type_id, NULL);
2283 	if (!resolved_type) {
2284 		btf_verifier_log_member(env, struct_type, member,
2285 					"Invalid member");
2286 		return -EINVAL;
2287 	}
2288 
2289 	resolved_member = *member;
2290 	resolved_member.type = resolved_type_id;
2291 
2292 	return btf_type_ops(resolved_type)->check_kflag_member(env, struct_type,
2293 							       &resolved_member,
2294 							       resolved_type);
2295 }
2296 
2297 static int btf_ptr_check_member(struct btf_verifier_env *env,
2298 				const struct btf_type *struct_type,
2299 				const struct btf_member *member,
2300 				const struct btf_type *member_type)
2301 {
2302 	u32 struct_size, struct_bits_off, bytes_offset;
2303 
2304 	struct_size = struct_type->size;
2305 	struct_bits_off = member->offset;
2306 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2307 
2308 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2309 		btf_verifier_log_member(env, struct_type, member,
2310 					"Member is not byte aligned");
2311 		return -EINVAL;
2312 	}
2313 
2314 	if (struct_size - bytes_offset < sizeof(void *)) {
2315 		btf_verifier_log_member(env, struct_type, member,
2316 					"Member exceeds struct_size");
2317 		return -EINVAL;
2318 	}
2319 
2320 	return 0;
2321 }
2322 
2323 static int btf_ref_type_check_meta(struct btf_verifier_env *env,
2324 				   const struct btf_type *t,
2325 				   u32 meta_left)
2326 {
2327 	if (btf_type_vlen(t)) {
2328 		btf_verifier_log_type(env, t, "vlen != 0");
2329 		return -EINVAL;
2330 	}
2331 
2332 	if (btf_type_kflag(t)) {
2333 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2334 		return -EINVAL;
2335 	}
2336 
2337 	if (!BTF_TYPE_ID_VALID(t->type)) {
2338 		btf_verifier_log_type(env, t, "Invalid type_id");
2339 		return -EINVAL;
2340 	}
2341 
2342 	/* typedef type must have a valid name, and other ref types,
2343 	 * volatile, const, restrict, should have a null name.
2344 	 */
2345 	if (BTF_INFO_KIND(t->info) == BTF_KIND_TYPEDEF) {
2346 		if (!t->name_off ||
2347 		    !btf_name_valid_identifier(env->btf, t->name_off)) {
2348 			btf_verifier_log_type(env, t, "Invalid name");
2349 			return -EINVAL;
2350 		}
2351 	} else {
2352 		if (t->name_off) {
2353 			btf_verifier_log_type(env, t, "Invalid name");
2354 			return -EINVAL;
2355 		}
2356 	}
2357 
2358 	btf_verifier_log_type(env, t, NULL);
2359 
2360 	return 0;
2361 }
2362 
2363 static int btf_modifier_resolve(struct btf_verifier_env *env,
2364 				const struct resolve_vertex *v)
2365 {
2366 	const struct btf_type *t = v->t;
2367 	const struct btf_type *next_type;
2368 	u32 next_type_id = t->type;
2369 	struct btf *btf = env->btf;
2370 
2371 	next_type = btf_type_by_id(btf, next_type_id);
2372 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2373 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2374 		return -EINVAL;
2375 	}
2376 
2377 	if (!env_type_is_resolve_sink(env, next_type) &&
2378 	    !env_type_is_resolved(env, next_type_id))
2379 		return env_stack_push(env, next_type, next_type_id);
2380 
2381 	/* Figure out the resolved next_type_id with size.
2382 	 * They will be stored in the current modifier's
2383 	 * resolved_ids and resolved_sizes such that it can
2384 	 * save us a few type-following when we use it later (e.g. in
2385 	 * pretty print).
2386 	 */
2387 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2388 		if (env_type_is_resolved(env, next_type_id))
2389 			next_type = btf_type_id_resolve(btf, &next_type_id);
2390 
2391 		/* "typedef void new_void", "const void"...etc */
2392 		if (!btf_type_is_void(next_type) &&
2393 		    !btf_type_is_fwd(next_type) &&
2394 		    !btf_type_is_func_proto(next_type)) {
2395 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2396 			return -EINVAL;
2397 		}
2398 	}
2399 
2400 	env_stack_pop_resolved(env, next_type_id, 0);
2401 
2402 	return 0;
2403 }
2404 
2405 static int btf_var_resolve(struct btf_verifier_env *env,
2406 			   const struct resolve_vertex *v)
2407 {
2408 	const struct btf_type *next_type;
2409 	const struct btf_type *t = v->t;
2410 	u32 next_type_id = t->type;
2411 	struct btf *btf = env->btf;
2412 
2413 	next_type = btf_type_by_id(btf, next_type_id);
2414 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2415 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2416 		return -EINVAL;
2417 	}
2418 
2419 	if (!env_type_is_resolve_sink(env, next_type) &&
2420 	    !env_type_is_resolved(env, next_type_id))
2421 		return env_stack_push(env, next_type, next_type_id);
2422 
2423 	if (btf_type_is_modifier(next_type)) {
2424 		const struct btf_type *resolved_type;
2425 		u32 resolved_type_id;
2426 
2427 		resolved_type_id = next_type_id;
2428 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2429 
2430 		if (btf_type_is_ptr(resolved_type) &&
2431 		    !env_type_is_resolve_sink(env, resolved_type) &&
2432 		    !env_type_is_resolved(env, resolved_type_id))
2433 			return env_stack_push(env, resolved_type,
2434 					      resolved_type_id);
2435 	}
2436 
2437 	/* We must resolve to something concrete at this point, no
2438 	 * forward types or similar that would resolve to size of
2439 	 * zero is allowed.
2440 	 */
2441 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2442 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2443 		return -EINVAL;
2444 	}
2445 
2446 	env_stack_pop_resolved(env, next_type_id, 0);
2447 
2448 	return 0;
2449 }
2450 
2451 static int btf_ptr_resolve(struct btf_verifier_env *env,
2452 			   const struct resolve_vertex *v)
2453 {
2454 	const struct btf_type *next_type;
2455 	const struct btf_type *t = v->t;
2456 	u32 next_type_id = t->type;
2457 	struct btf *btf = env->btf;
2458 
2459 	next_type = btf_type_by_id(btf, next_type_id);
2460 	if (!next_type || btf_type_is_resolve_source_only(next_type)) {
2461 		btf_verifier_log_type(env, v->t, "Invalid type_id");
2462 		return -EINVAL;
2463 	}
2464 
2465 	if (!env_type_is_resolve_sink(env, next_type) &&
2466 	    !env_type_is_resolved(env, next_type_id))
2467 		return env_stack_push(env, next_type, next_type_id);
2468 
2469 	/* If the modifier was RESOLVED during RESOLVE_STRUCT_OR_ARRAY,
2470 	 * the modifier may have stopped resolving when it was resolved
2471 	 * to a ptr (last-resolved-ptr).
2472 	 *
2473 	 * We now need to continue from the last-resolved-ptr to
2474 	 * ensure the last-resolved-ptr will not referring back to
2475 	 * the currenct ptr (t).
2476 	 */
2477 	if (btf_type_is_modifier(next_type)) {
2478 		const struct btf_type *resolved_type;
2479 		u32 resolved_type_id;
2480 
2481 		resolved_type_id = next_type_id;
2482 		resolved_type = btf_type_id_resolve(btf, &resolved_type_id);
2483 
2484 		if (btf_type_is_ptr(resolved_type) &&
2485 		    !env_type_is_resolve_sink(env, resolved_type) &&
2486 		    !env_type_is_resolved(env, resolved_type_id))
2487 			return env_stack_push(env, resolved_type,
2488 					      resolved_type_id);
2489 	}
2490 
2491 	if (!btf_type_id_size(btf, &next_type_id, NULL)) {
2492 		if (env_type_is_resolved(env, next_type_id))
2493 			next_type = btf_type_id_resolve(btf, &next_type_id);
2494 
2495 		if (!btf_type_is_void(next_type) &&
2496 		    !btf_type_is_fwd(next_type) &&
2497 		    !btf_type_is_func_proto(next_type)) {
2498 			btf_verifier_log_type(env, v->t, "Invalid type_id");
2499 			return -EINVAL;
2500 		}
2501 	}
2502 
2503 	env_stack_pop_resolved(env, next_type_id, 0);
2504 
2505 	return 0;
2506 }
2507 
2508 static void btf_modifier_show(const struct btf *btf,
2509 			      const struct btf_type *t,
2510 			      u32 type_id, void *data,
2511 			      u8 bits_offset, struct btf_show *show)
2512 {
2513 	if (btf->resolved_ids)
2514 		t = btf_type_id_resolve(btf, &type_id);
2515 	else
2516 		t = btf_type_skip_modifiers(btf, type_id, NULL);
2517 
2518 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2519 }
2520 
2521 static void btf_var_show(const struct btf *btf, const struct btf_type *t,
2522 			 u32 type_id, void *data, u8 bits_offset,
2523 			 struct btf_show *show)
2524 {
2525 	t = btf_type_id_resolve(btf, &type_id);
2526 
2527 	btf_type_ops(t)->show(btf, t, type_id, data, bits_offset, show);
2528 }
2529 
2530 static void btf_ptr_show(const struct btf *btf, const struct btf_type *t,
2531 			 u32 type_id, void *data, u8 bits_offset,
2532 			 struct btf_show *show)
2533 {
2534 	void *safe_data;
2535 
2536 	safe_data = btf_show_start_type(show, t, type_id, data);
2537 	if (!safe_data)
2538 		return;
2539 
2540 	/* It is a hashed value unless BTF_SHOW_PTR_RAW is specified */
2541 	if (show->flags & BTF_SHOW_PTR_RAW)
2542 		btf_show_type_value(show, "0x%px", *(void **)safe_data);
2543 	else
2544 		btf_show_type_value(show, "0x%p", *(void **)safe_data);
2545 	btf_show_end_type(show);
2546 }
2547 
2548 static void btf_ref_type_log(struct btf_verifier_env *env,
2549 			     const struct btf_type *t)
2550 {
2551 	btf_verifier_log(env, "type_id=%u", t->type);
2552 }
2553 
2554 static struct btf_kind_operations modifier_ops = {
2555 	.check_meta = btf_ref_type_check_meta,
2556 	.resolve = btf_modifier_resolve,
2557 	.check_member = btf_modifier_check_member,
2558 	.check_kflag_member = btf_modifier_check_kflag_member,
2559 	.log_details = btf_ref_type_log,
2560 	.show = btf_modifier_show,
2561 };
2562 
2563 static struct btf_kind_operations ptr_ops = {
2564 	.check_meta = btf_ref_type_check_meta,
2565 	.resolve = btf_ptr_resolve,
2566 	.check_member = btf_ptr_check_member,
2567 	.check_kflag_member = btf_generic_check_kflag_member,
2568 	.log_details = btf_ref_type_log,
2569 	.show = btf_ptr_show,
2570 };
2571 
2572 static s32 btf_fwd_check_meta(struct btf_verifier_env *env,
2573 			      const struct btf_type *t,
2574 			      u32 meta_left)
2575 {
2576 	if (btf_type_vlen(t)) {
2577 		btf_verifier_log_type(env, t, "vlen != 0");
2578 		return -EINVAL;
2579 	}
2580 
2581 	if (t->type) {
2582 		btf_verifier_log_type(env, t, "type != 0");
2583 		return -EINVAL;
2584 	}
2585 
2586 	/* fwd type must have a valid name */
2587 	if (!t->name_off ||
2588 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
2589 		btf_verifier_log_type(env, t, "Invalid name");
2590 		return -EINVAL;
2591 	}
2592 
2593 	btf_verifier_log_type(env, t, NULL);
2594 
2595 	return 0;
2596 }
2597 
2598 static void btf_fwd_type_log(struct btf_verifier_env *env,
2599 			     const struct btf_type *t)
2600 {
2601 	btf_verifier_log(env, "%s", btf_type_kflag(t) ? "union" : "struct");
2602 }
2603 
2604 static struct btf_kind_operations fwd_ops = {
2605 	.check_meta = btf_fwd_check_meta,
2606 	.resolve = btf_df_resolve,
2607 	.check_member = btf_df_check_member,
2608 	.check_kflag_member = btf_df_check_kflag_member,
2609 	.log_details = btf_fwd_type_log,
2610 	.show = btf_df_show,
2611 };
2612 
2613 static int btf_array_check_member(struct btf_verifier_env *env,
2614 				  const struct btf_type *struct_type,
2615 				  const struct btf_member *member,
2616 				  const struct btf_type *member_type)
2617 {
2618 	u32 struct_bits_off = member->offset;
2619 	u32 struct_size, bytes_offset;
2620 	u32 array_type_id, array_size;
2621 	struct btf *btf = env->btf;
2622 
2623 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2624 		btf_verifier_log_member(env, struct_type, member,
2625 					"Member is not byte aligned");
2626 		return -EINVAL;
2627 	}
2628 
2629 	array_type_id = member->type;
2630 	btf_type_id_size(btf, &array_type_id, &array_size);
2631 	struct_size = struct_type->size;
2632 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2633 	if (struct_size - bytes_offset < array_size) {
2634 		btf_verifier_log_member(env, struct_type, member,
2635 					"Member exceeds struct_size");
2636 		return -EINVAL;
2637 	}
2638 
2639 	return 0;
2640 }
2641 
2642 static s32 btf_array_check_meta(struct btf_verifier_env *env,
2643 				const struct btf_type *t,
2644 				u32 meta_left)
2645 {
2646 	const struct btf_array *array = btf_type_array(t);
2647 	u32 meta_needed = sizeof(*array);
2648 
2649 	if (meta_left < meta_needed) {
2650 		btf_verifier_log_basic(env, t,
2651 				       "meta_left:%u meta_needed:%u",
2652 				       meta_left, meta_needed);
2653 		return -EINVAL;
2654 	}
2655 
2656 	/* array type should not have a name */
2657 	if (t->name_off) {
2658 		btf_verifier_log_type(env, t, "Invalid name");
2659 		return -EINVAL;
2660 	}
2661 
2662 	if (btf_type_vlen(t)) {
2663 		btf_verifier_log_type(env, t, "vlen != 0");
2664 		return -EINVAL;
2665 	}
2666 
2667 	if (btf_type_kflag(t)) {
2668 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
2669 		return -EINVAL;
2670 	}
2671 
2672 	if (t->size) {
2673 		btf_verifier_log_type(env, t, "size != 0");
2674 		return -EINVAL;
2675 	}
2676 
2677 	/* Array elem type and index type cannot be in type void,
2678 	 * so !array->type and !array->index_type are not allowed.
2679 	 */
2680 	if (!array->type || !BTF_TYPE_ID_VALID(array->type)) {
2681 		btf_verifier_log_type(env, t, "Invalid elem");
2682 		return -EINVAL;
2683 	}
2684 
2685 	if (!array->index_type || !BTF_TYPE_ID_VALID(array->index_type)) {
2686 		btf_verifier_log_type(env, t, "Invalid index");
2687 		return -EINVAL;
2688 	}
2689 
2690 	btf_verifier_log_type(env, t, NULL);
2691 
2692 	return meta_needed;
2693 }
2694 
2695 static int btf_array_resolve(struct btf_verifier_env *env,
2696 			     const struct resolve_vertex *v)
2697 {
2698 	const struct btf_array *array = btf_type_array(v->t);
2699 	const struct btf_type *elem_type, *index_type;
2700 	u32 elem_type_id, index_type_id;
2701 	struct btf *btf = env->btf;
2702 	u32 elem_size;
2703 
2704 	/* Check array->index_type */
2705 	index_type_id = array->index_type;
2706 	index_type = btf_type_by_id(btf, index_type_id);
2707 	if (btf_type_nosize_or_null(index_type) ||
2708 	    btf_type_is_resolve_source_only(index_type)) {
2709 		btf_verifier_log_type(env, v->t, "Invalid index");
2710 		return -EINVAL;
2711 	}
2712 
2713 	if (!env_type_is_resolve_sink(env, index_type) &&
2714 	    !env_type_is_resolved(env, index_type_id))
2715 		return env_stack_push(env, index_type, index_type_id);
2716 
2717 	index_type = btf_type_id_size(btf, &index_type_id, NULL);
2718 	if (!index_type || !btf_type_is_int(index_type) ||
2719 	    !btf_type_int_is_regular(index_type)) {
2720 		btf_verifier_log_type(env, v->t, "Invalid index");
2721 		return -EINVAL;
2722 	}
2723 
2724 	/* Check array->type */
2725 	elem_type_id = array->type;
2726 	elem_type = btf_type_by_id(btf, elem_type_id);
2727 	if (btf_type_nosize_or_null(elem_type) ||
2728 	    btf_type_is_resolve_source_only(elem_type)) {
2729 		btf_verifier_log_type(env, v->t,
2730 				      "Invalid elem");
2731 		return -EINVAL;
2732 	}
2733 
2734 	if (!env_type_is_resolve_sink(env, elem_type) &&
2735 	    !env_type_is_resolved(env, elem_type_id))
2736 		return env_stack_push(env, elem_type, elem_type_id);
2737 
2738 	elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
2739 	if (!elem_type) {
2740 		btf_verifier_log_type(env, v->t, "Invalid elem");
2741 		return -EINVAL;
2742 	}
2743 
2744 	if (btf_type_is_int(elem_type) && !btf_type_int_is_regular(elem_type)) {
2745 		btf_verifier_log_type(env, v->t, "Invalid array of int");
2746 		return -EINVAL;
2747 	}
2748 
2749 	if (array->nelems && elem_size > U32_MAX / array->nelems) {
2750 		btf_verifier_log_type(env, v->t,
2751 				      "Array size overflows U32_MAX");
2752 		return -EINVAL;
2753 	}
2754 
2755 	env_stack_pop_resolved(env, elem_type_id, elem_size * array->nelems);
2756 
2757 	return 0;
2758 }
2759 
2760 static void btf_array_log(struct btf_verifier_env *env,
2761 			  const struct btf_type *t)
2762 {
2763 	const struct btf_array *array = btf_type_array(t);
2764 
2765 	btf_verifier_log(env, "type_id=%u index_type_id=%u nr_elems=%u",
2766 			 array->type, array->index_type, array->nelems);
2767 }
2768 
2769 static void __btf_array_show(const struct btf *btf, const struct btf_type *t,
2770 			     u32 type_id, void *data, u8 bits_offset,
2771 			     struct btf_show *show)
2772 {
2773 	const struct btf_array *array = btf_type_array(t);
2774 	const struct btf_kind_operations *elem_ops;
2775 	const struct btf_type *elem_type;
2776 	u32 i, elem_size = 0, elem_type_id;
2777 	u16 encoding = 0;
2778 
2779 	elem_type_id = array->type;
2780 	elem_type = btf_type_skip_modifiers(btf, elem_type_id, NULL);
2781 	if (elem_type && btf_type_has_size(elem_type))
2782 		elem_size = elem_type->size;
2783 
2784 	if (elem_type && btf_type_is_int(elem_type)) {
2785 		u32 int_type = btf_type_int(elem_type);
2786 
2787 		encoding = BTF_INT_ENCODING(int_type);
2788 
2789 		/*
2790 		 * BTF_INT_CHAR encoding never seems to be set for
2791 		 * char arrays, so if size is 1 and element is
2792 		 * printable as a char, we'll do that.
2793 		 */
2794 		if (elem_size == 1)
2795 			encoding = BTF_INT_CHAR;
2796 	}
2797 
2798 	if (!btf_show_start_array_type(show, t, type_id, encoding, data))
2799 		return;
2800 
2801 	if (!elem_type)
2802 		goto out;
2803 	elem_ops = btf_type_ops(elem_type);
2804 
2805 	for (i = 0; i < array->nelems; i++) {
2806 
2807 		btf_show_start_array_member(show);
2808 
2809 		elem_ops->show(btf, elem_type, elem_type_id, data,
2810 			       bits_offset, show);
2811 		data += elem_size;
2812 
2813 		btf_show_end_array_member(show);
2814 
2815 		if (show->state.array_terminated)
2816 			break;
2817 	}
2818 out:
2819 	btf_show_end_array_type(show);
2820 }
2821 
2822 static void btf_array_show(const struct btf *btf, const struct btf_type *t,
2823 			   u32 type_id, void *data, u8 bits_offset,
2824 			   struct btf_show *show)
2825 {
2826 	const struct btf_member *m = show->state.member;
2827 
2828 	/*
2829 	 * First check if any members would be shown (are non-zero).
2830 	 * See comments above "struct btf_show" definition for more
2831 	 * details on how this works at a high-level.
2832 	 */
2833 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
2834 		if (!show->state.depth_check) {
2835 			show->state.depth_check = show->state.depth + 1;
2836 			show->state.depth_to_show = 0;
2837 		}
2838 		__btf_array_show(btf, t, type_id, data, bits_offset, show);
2839 		show->state.member = m;
2840 
2841 		if (show->state.depth_check != show->state.depth + 1)
2842 			return;
2843 		show->state.depth_check = 0;
2844 
2845 		if (show->state.depth_to_show <= show->state.depth)
2846 			return;
2847 		/*
2848 		 * Reaching here indicates we have recursed and found
2849 		 * non-zero array member(s).
2850 		 */
2851 	}
2852 	__btf_array_show(btf, t, type_id, data, bits_offset, show);
2853 }
2854 
2855 static struct btf_kind_operations array_ops = {
2856 	.check_meta = btf_array_check_meta,
2857 	.resolve = btf_array_resolve,
2858 	.check_member = btf_array_check_member,
2859 	.check_kflag_member = btf_generic_check_kflag_member,
2860 	.log_details = btf_array_log,
2861 	.show = btf_array_show,
2862 };
2863 
2864 static int btf_struct_check_member(struct btf_verifier_env *env,
2865 				   const struct btf_type *struct_type,
2866 				   const struct btf_member *member,
2867 				   const struct btf_type *member_type)
2868 {
2869 	u32 struct_bits_off = member->offset;
2870 	u32 struct_size, bytes_offset;
2871 
2872 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
2873 		btf_verifier_log_member(env, struct_type, member,
2874 					"Member is not byte aligned");
2875 		return -EINVAL;
2876 	}
2877 
2878 	struct_size = struct_type->size;
2879 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
2880 	if (struct_size - bytes_offset < member_type->size) {
2881 		btf_verifier_log_member(env, struct_type, member,
2882 					"Member exceeds struct_size");
2883 		return -EINVAL;
2884 	}
2885 
2886 	return 0;
2887 }
2888 
2889 static s32 btf_struct_check_meta(struct btf_verifier_env *env,
2890 				 const struct btf_type *t,
2891 				 u32 meta_left)
2892 {
2893 	bool is_union = BTF_INFO_KIND(t->info) == BTF_KIND_UNION;
2894 	const struct btf_member *member;
2895 	u32 meta_needed, last_offset;
2896 	struct btf *btf = env->btf;
2897 	u32 struct_size = t->size;
2898 	u32 offset;
2899 	u16 i;
2900 
2901 	meta_needed = btf_type_vlen(t) * sizeof(*member);
2902 	if (meta_left < meta_needed) {
2903 		btf_verifier_log_basic(env, t,
2904 				       "meta_left:%u meta_needed:%u",
2905 				       meta_left, meta_needed);
2906 		return -EINVAL;
2907 	}
2908 
2909 	/* struct type either no name or a valid one */
2910 	if (t->name_off &&
2911 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
2912 		btf_verifier_log_type(env, t, "Invalid name");
2913 		return -EINVAL;
2914 	}
2915 
2916 	btf_verifier_log_type(env, t, NULL);
2917 
2918 	last_offset = 0;
2919 	for_each_member(i, t, member) {
2920 		if (!btf_name_offset_valid(btf, member->name_off)) {
2921 			btf_verifier_log_member(env, t, member,
2922 						"Invalid member name_offset:%u",
2923 						member->name_off);
2924 			return -EINVAL;
2925 		}
2926 
2927 		/* struct member either no name or a valid one */
2928 		if (member->name_off &&
2929 		    !btf_name_valid_identifier(btf, member->name_off)) {
2930 			btf_verifier_log_member(env, t, member, "Invalid name");
2931 			return -EINVAL;
2932 		}
2933 		/* A member cannot be in type void */
2934 		if (!member->type || !BTF_TYPE_ID_VALID(member->type)) {
2935 			btf_verifier_log_member(env, t, member,
2936 						"Invalid type_id");
2937 			return -EINVAL;
2938 		}
2939 
2940 		offset = btf_member_bit_offset(t, member);
2941 		if (is_union && offset) {
2942 			btf_verifier_log_member(env, t, member,
2943 						"Invalid member bits_offset");
2944 			return -EINVAL;
2945 		}
2946 
2947 		/*
2948 		 * ">" instead of ">=" because the last member could be
2949 		 * "char a[0];"
2950 		 */
2951 		if (last_offset > offset) {
2952 			btf_verifier_log_member(env, t, member,
2953 						"Invalid member bits_offset");
2954 			return -EINVAL;
2955 		}
2956 
2957 		if (BITS_ROUNDUP_BYTES(offset) > struct_size) {
2958 			btf_verifier_log_member(env, t, member,
2959 						"Member bits_offset exceeds its struct size");
2960 			return -EINVAL;
2961 		}
2962 
2963 		btf_verifier_log_member(env, t, member, NULL);
2964 		last_offset = offset;
2965 	}
2966 
2967 	return meta_needed;
2968 }
2969 
2970 static int btf_struct_resolve(struct btf_verifier_env *env,
2971 			      const struct resolve_vertex *v)
2972 {
2973 	const struct btf_member *member;
2974 	int err;
2975 	u16 i;
2976 
2977 	/* Before continue resolving the next_member,
2978 	 * ensure the last member is indeed resolved to a
2979 	 * type with size info.
2980 	 */
2981 	if (v->next_member) {
2982 		const struct btf_type *last_member_type;
2983 		const struct btf_member *last_member;
2984 		u16 last_member_type_id;
2985 
2986 		last_member = btf_type_member(v->t) + v->next_member - 1;
2987 		last_member_type_id = last_member->type;
2988 		if (WARN_ON_ONCE(!env_type_is_resolved(env,
2989 						       last_member_type_id)))
2990 			return -EINVAL;
2991 
2992 		last_member_type = btf_type_by_id(env->btf,
2993 						  last_member_type_id);
2994 		if (btf_type_kflag(v->t))
2995 			err = btf_type_ops(last_member_type)->check_kflag_member(env, v->t,
2996 								last_member,
2997 								last_member_type);
2998 		else
2999 			err = btf_type_ops(last_member_type)->check_member(env, v->t,
3000 								last_member,
3001 								last_member_type);
3002 		if (err)
3003 			return err;
3004 	}
3005 
3006 	for_each_member_from(i, v->next_member, v->t, member) {
3007 		u32 member_type_id = member->type;
3008 		const struct btf_type *member_type = btf_type_by_id(env->btf,
3009 								member_type_id);
3010 
3011 		if (btf_type_nosize_or_null(member_type) ||
3012 		    btf_type_is_resolve_source_only(member_type)) {
3013 			btf_verifier_log_member(env, v->t, member,
3014 						"Invalid member");
3015 			return -EINVAL;
3016 		}
3017 
3018 		if (!env_type_is_resolve_sink(env, member_type) &&
3019 		    !env_type_is_resolved(env, member_type_id)) {
3020 			env_stack_set_next_member(env, i + 1);
3021 			return env_stack_push(env, member_type, member_type_id);
3022 		}
3023 
3024 		if (btf_type_kflag(v->t))
3025 			err = btf_type_ops(member_type)->check_kflag_member(env, v->t,
3026 									    member,
3027 									    member_type);
3028 		else
3029 			err = btf_type_ops(member_type)->check_member(env, v->t,
3030 								      member,
3031 								      member_type);
3032 		if (err)
3033 			return err;
3034 	}
3035 
3036 	env_stack_pop_resolved(env, 0, 0);
3037 
3038 	return 0;
3039 }
3040 
3041 static void btf_struct_log(struct btf_verifier_env *env,
3042 			   const struct btf_type *t)
3043 {
3044 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3045 }
3046 
3047 /* find 'struct bpf_spin_lock' in map value.
3048  * return >= 0 offset if found
3049  * and < 0 in case of error
3050  */
3051 int btf_find_spin_lock(const struct btf *btf, const struct btf_type *t)
3052 {
3053 	const struct btf_member *member;
3054 	u32 i, off = -ENOENT;
3055 
3056 	if (!__btf_type_is_struct(t))
3057 		return -EINVAL;
3058 
3059 	for_each_member(i, t, member) {
3060 		const struct btf_type *member_type = btf_type_by_id(btf,
3061 								    member->type);
3062 		if (!__btf_type_is_struct(member_type))
3063 			continue;
3064 		if (member_type->size != sizeof(struct bpf_spin_lock))
3065 			continue;
3066 		if (strcmp(__btf_name_by_offset(btf, member_type->name_off),
3067 			   "bpf_spin_lock"))
3068 			continue;
3069 		if (off != -ENOENT)
3070 			/* only one 'struct bpf_spin_lock' is allowed */
3071 			return -E2BIG;
3072 		off = btf_member_bit_offset(t, member);
3073 		if (off % 8)
3074 			/* valid C code cannot generate such BTF */
3075 			return -EINVAL;
3076 		off /= 8;
3077 		if (off % __alignof__(struct bpf_spin_lock))
3078 			/* valid struct bpf_spin_lock will be 4 byte aligned */
3079 			return -EINVAL;
3080 	}
3081 	return off;
3082 }
3083 
3084 static void __btf_struct_show(const struct btf *btf, const struct btf_type *t,
3085 			      u32 type_id, void *data, u8 bits_offset,
3086 			      struct btf_show *show)
3087 {
3088 	const struct btf_member *member;
3089 	void *safe_data;
3090 	u32 i;
3091 
3092 	safe_data = btf_show_start_struct_type(show, t, type_id, data);
3093 	if (!safe_data)
3094 		return;
3095 
3096 	for_each_member(i, t, member) {
3097 		const struct btf_type *member_type = btf_type_by_id(btf,
3098 								member->type);
3099 		const struct btf_kind_operations *ops;
3100 		u32 member_offset, bitfield_size;
3101 		u32 bytes_offset;
3102 		u8 bits8_offset;
3103 
3104 		btf_show_start_member(show, member);
3105 
3106 		member_offset = btf_member_bit_offset(t, member);
3107 		bitfield_size = btf_member_bitfield_size(t, member);
3108 		bytes_offset = BITS_ROUNDDOWN_BYTES(member_offset);
3109 		bits8_offset = BITS_PER_BYTE_MASKED(member_offset);
3110 		if (bitfield_size) {
3111 			safe_data = btf_show_start_type(show, member_type,
3112 							member->type,
3113 							data + bytes_offset);
3114 			if (safe_data)
3115 				btf_bitfield_show(safe_data,
3116 						  bits8_offset,
3117 						  bitfield_size, show);
3118 			btf_show_end_type(show);
3119 		} else {
3120 			ops = btf_type_ops(member_type);
3121 			ops->show(btf, member_type, member->type,
3122 				  data + bytes_offset, bits8_offset, show);
3123 		}
3124 
3125 		btf_show_end_member(show);
3126 	}
3127 
3128 	btf_show_end_struct_type(show);
3129 }
3130 
3131 static void btf_struct_show(const struct btf *btf, const struct btf_type *t,
3132 			    u32 type_id, void *data, u8 bits_offset,
3133 			    struct btf_show *show)
3134 {
3135 	const struct btf_member *m = show->state.member;
3136 
3137 	/*
3138 	 * First check if any members would be shown (are non-zero).
3139 	 * See comments above "struct btf_show" definition for more
3140 	 * details on how this works at a high-level.
3141 	 */
3142 	if (show->state.depth > 0 && !(show->flags & BTF_SHOW_ZERO)) {
3143 		if (!show->state.depth_check) {
3144 			show->state.depth_check = show->state.depth + 1;
3145 			show->state.depth_to_show = 0;
3146 		}
3147 		__btf_struct_show(btf, t, type_id, data, bits_offset, show);
3148 		/* Restore saved member data here */
3149 		show->state.member = m;
3150 		if (show->state.depth_check != show->state.depth + 1)
3151 			return;
3152 		show->state.depth_check = 0;
3153 
3154 		if (show->state.depth_to_show <= show->state.depth)
3155 			return;
3156 		/*
3157 		 * Reaching here indicates we have recursed and found
3158 		 * non-zero child values.
3159 		 */
3160 	}
3161 
3162 	__btf_struct_show(btf, t, type_id, data, bits_offset, show);
3163 }
3164 
3165 static struct btf_kind_operations struct_ops = {
3166 	.check_meta = btf_struct_check_meta,
3167 	.resolve = btf_struct_resolve,
3168 	.check_member = btf_struct_check_member,
3169 	.check_kflag_member = btf_generic_check_kflag_member,
3170 	.log_details = btf_struct_log,
3171 	.show = btf_struct_show,
3172 };
3173 
3174 static int btf_enum_check_member(struct btf_verifier_env *env,
3175 				 const struct btf_type *struct_type,
3176 				 const struct btf_member *member,
3177 				 const struct btf_type *member_type)
3178 {
3179 	u32 struct_bits_off = member->offset;
3180 	u32 struct_size, bytes_offset;
3181 
3182 	if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3183 		btf_verifier_log_member(env, struct_type, member,
3184 					"Member is not byte aligned");
3185 		return -EINVAL;
3186 	}
3187 
3188 	struct_size = struct_type->size;
3189 	bytes_offset = BITS_ROUNDDOWN_BYTES(struct_bits_off);
3190 	if (struct_size - bytes_offset < member_type->size) {
3191 		btf_verifier_log_member(env, struct_type, member,
3192 					"Member exceeds struct_size");
3193 		return -EINVAL;
3194 	}
3195 
3196 	return 0;
3197 }
3198 
3199 static int btf_enum_check_kflag_member(struct btf_verifier_env *env,
3200 				       const struct btf_type *struct_type,
3201 				       const struct btf_member *member,
3202 				       const struct btf_type *member_type)
3203 {
3204 	u32 struct_bits_off, nr_bits, bytes_end, struct_size;
3205 	u32 int_bitsize = sizeof(int) * BITS_PER_BYTE;
3206 
3207 	struct_bits_off = BTF_MEMBER_BIT_OFFSET(member->offset);
3208 	nr_bits = BTF_MEMBER_BITFIELD_SIZE(member->offset);
3209 	if (!nr_bits) {
3210 		if (BITS_PER_BYTE_MASKED(struct_bits_off)) {
3211 			btf_verifier_log_member(env, struct_type, member,
3212 						"Member is not byte aligned");
3213 			return -EINVAL;
3214 		}
3215 
3216 		nr_bits = int_bitsize;
3217 	} else if (nr_bits > int_bitsize) {
3218 		btf_verifier_log_member(env, struct_type, member,
3219 					"Invalid member bitfield_size");
3220 		return -EINVAL;
3221 	}
3222 
3223 	struct_size = struct_type->size;
3224 	bytes_end = BITS_ROUNDUP_BYTES(struct_bits_off + nr_bits);
3225 	if (struct_size < bytes_end) {
3226 		btf_verifier_log_member(env, struct_type, member,
3227 					"Member exceeds struct_size");
3228 		return -EINVAL;
3229 	}
3230 
3231 	return 0;
3232 }
3233 
3234 static s32 btf_enum_check_meta(struct btf_verifier_env *env,
3235 			       const struct btf_type *t,
3236 			       u32 meta_left)
3237 {
3238 	const struct btf_enum *enums = btf_type_enum(t);
3239 	struct btf *btf = env->btf;
3240 	u16 i, nr_enums;
3241 	u32 meta_needed;
3242 
3243 	nr_enums = btf_type_vlen(t);
3244 	meta_needed = nr_enums * sizeof(*enums);
3245 
3246 	if (meta_left < meta_needed) {
3247 		btf_verifier_log_basic(env, t,
3248 				       "meta_left:%u meta_needed:%u",
3249 				       meta_left, meta_needed);
3250 		return -EINVAL;
3251 	}
3252 
3253 	if (btf_type_kflag(t)) {
3254 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3255 		return -EINVAL;
3256 	}
3257 
3258 	if (t->size > 8 || !is_power_of_2(t->size)) {
3259 		btf_verifier_log_type(env, t, "Unexpected size");
3260 		return -EINVAL;
3261 	}
3262 
3263 	/* enum type either no name or a valid one */
3264 	if (t->name_off &&
3265 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3266 		btf_verifier_log_type(env, t, "Invalid name");
3267 		return -EINVAL;
3268 	}
3269 
3270 	btf_verifier_log_type(env, t, NULL);
3271 
3272 	for (i = 0; i < nr_enums; i++) {
3273 		if (!btf_name_offset_valid(btf, enums[i].name_off)) {
3274 			btf_verifier_log(env, "\tInvalid name_offset:%u",
3275 					 enums[i].name_off);
3276 			return -EINVAL;
3277 		}
3278 
3279 		/* enum member must have a valid name */
3280 		if (!enums[i].name_off ||
3281 		    !btf_name_valid_identifier(btf, enums[i].name_off)) {
3282 			btf_verifier_log_type(env, t, "Invalid name");
3283 			return -EINVAL;
3284 		}
3285 
3286 		if (env->log.level == BPF_LOG_KERNEL)
3287 			continue;
3288 		btf_verifier_log(env, "\t%s val=%d\n",
3289 				 __btf_name_by_offset(btf, enums[i].name_off),
3290 				 enums[i].val);
3291 	}
3292 
3293 	return meta_needed;
3294 }
3295 
3296 static void btf_enum_log(struct btf_verifier_env *env,
3297 			 const struct btf_type *t)
3298 {
3299 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3300 }
3301 
3302 static void btf_enum_show(const struct btf *btf, const struct btf_type *t,
3303 			  u32 type_id, void *data, u8 bits_offset,
3304 			  struct btf_show *show)
3305 {
3306 	const struct btf_enum *enums = btf_type_enum(t);
3307 	u32 i, nr_enums = btf_type_vlen(t);
3308 	void *safe_data;
3309 	int v;
3310 
3311 	safe_data = btf_show_start_type(show, t, type_id, data);
3312 	if (!safe_data)
3313 		return;
3314 
3315 	v = *(int *)safe_data;
3316 
3317 	for (i = 0; i < nr_enums; i++) {
3318 		if (v != enums[i].val)
3319 			continue;
3320 
3321 		btf_show_type_value(show, "%s",
3322 				    __btf_name_by_offset(btf,
3323 							 enums[i].name_off));
3324 
3325 		btf_show_end_type(show);
3326 		return;
3327 	}
3328 
3329 	btf_show_type_value(show, "%d", v);
3330 	btf_show_end_type(show);
3331 }
3332 
3333 static struct btf_kind_operations enum_ops = {
3334 	.check_meta = btf_enum_check_meta,
3335 	.resolve = btf_df_resolve,
3336 	.check_member = btf_enum_check_member,
3337 	.check_kflag_member = btf_enum_check_kflag_member,
3338 	.log_details = btf_enum_log,
3339 	.show = btf_enum_show,
3340 };
3341 
3342 static s32 btf_func_proto_check_meta(struct btf_verifier_env *env,
3343 				     const struct btf_type *t,
3344 				     u32 meta_left)
3345 {
3346 	u32 meta_needed = btf_type_vlen(t) * sizeof(struct btf_param);
3347 
3348 	if (meta_left < meta_needed) {
3349 		btf_verifier_log_basic(env, t,
3350 				       "meta_left:%u meta_needed:%u",
3351 				       meta_left, meta_needed);
3352 		return -EINVAL;
3353 	}
3354 
3355 	if (t->name_off) {
3356 		btf_verifier_log_type(env, t, "Invalid name");
3357 		return -EINVAL;
3358 	}
3359 
3360 	if (btf_type_kflag(t)) {
3361 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3362 		return -EINVAL;
3363 	}
3364 
3365 	btf_verifier_log_type(env, t, NULL);
3366 
3367 	return meta_needed;
3368 }
3369 
3370 static void btf_func_proto_log(struct btf_verifier_env *env,
3371 			       const struct btf_type *t)
3372 {
3373 	const struct btf_param *args = (const struct btf_param *)(t + 1);
3374 	u16 nr_args = btf_type_vlen(t), i;
3375 
3376 	btf_verifier_log(env, "return=%u args=(", t->type);
3377 	if (!nr_args) {
3378 		btf_verifier_log(env, "void");
3379 		goto done;
3380 	}
3381 
3382 	if (nr_args == 1 && !args[0].type) {
3383 		/* Only one vararg */
3384 		btf_verifier_log(env, "vararg");
3385 		goto done;
3386 	}
3387 
3388 	btf_verifier_log(env, "%u %s", args[0].type,
3389 			 __btf_name_by_offset(env->btf,
3390 					      args[0].name_off));
3391 	for (i = 1; i < nr_args - 1; i++)
3392 		btf_verifier_log(env, ", %u %s", args[i].type,
3393 				 __btf_name_by_offset(env->btf,
3394 						      args[i].name_off));
3395 
3396 	if (nr_args > 1) {
3397 		const struct btf_param *last_arg = &args[nr_args - 1];
3398 
3399 		if (last_arg->type)
3400 			btf_verifier_log(env, ", %u %s", last_arg->type,
3401 					 __btf_name_by_offset(env->btf,
3402 							      last_arg->name_off));
3403 		else
3404 			btf_verifier_log(env, ", vararg");
3405 	}
3406 
3407 done:
3408 	btf_verifier_log(env, ")");
3409 }
3410 
3411 static struct btf_kind_operations func_proto_ops = {
3412 	.check_meta = btf_func_proto_check_meta,
3413 	.resolve = btf_df_resolve,
3414 	/*
3415 	 * BTF_KIND_FUNC_PROTO cannot be directly referred by
3416 	 * a struct's member.
3417 	 *
3418 	 * It should be a funciton pointer instead.
3419 	 * (i.e. struct's member -> BTF_KIND_PTR -> BTF_KIND_FUNC_PROTO)
3420 	 *
3421 	 * Hence, there is no btf_func_check_member().
3422 	 */
3423 	.check_member = btf_df_check_member,
3424 	.check_kflag_member = btf_df_check_kflag_member,
3425 	.log_details = btf_func_proto_log,
3426 	.show = btf_df_show,
3427 };
3428 
3429 static s32 btf_func_check_meta(struct btf_verifier_env *env,
3430 			       const struct btf_type *t,
3431 			       u32 meta_left)
3432 {
3433 	if (!t->name_off ||
3434 	    !btf_name_valid_identifier(env->btf, t->name_off)) {
3435 		btf_verifier_log_type(env, t, "Invalid name");
3436 		return -EINVAL;
3437 	}
3438 
3439 	if (btf_type_vlen(t) > BTF_FUNC_GLOBAL) {
3440 		btf_verifier_log_type(env, t, "Invalid func linkage");
3441 		return -EINVAL;
3442 	}
3443 
3444 	if (btf_type_kflag(t)) {
3445 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3446 		return -EINVAL;
3447 	}
3448 
3449 	btf_verifier_log_type(env, t, NULL);
3450 
3451 	return 0;
3452 }
3453 
3454 static struct btf_kind_operations func_ops = {
3455 	.check_meta = btf_func_check_meta,
3456 	.resolve = btf_df_resolve,
3457 	.check_member = btf_df_check_member,
3458 	.check_kflag_member = btf_df_check_kflag_member,
3459 	.log_details = btf_ref_type_log,
3460 	.show = btf_df_show,
3461 };
3462 
3463 static s32 btf_var_check_meta(struct btf_verifier_env *env,
3464 			      const struct btf_type *t,
3465 			      u32 meta_left)
3466 {
3467 	const struct btf_var *var;
3468 	u32 meta_needed = sizeof(*var);
3469 
3470 	if (meta_left < meta_needed) {
3471 		btf_verifier_log_basic(env, t,
3472 				       "meta_left:%u meta_needed:%u",
3473 				       meta_left, meta_needed);
3474 		return -EINVAL;
3475 	}
3476 
3477 	if (btf_type_vlen(t)) {
3478 		btf_verifier_log_type(env, t, "vlen != 0");
3479 		return -EINVAL;
3480 	}
3481 
3482 	if (btf_type_kflag(t)) {
3483 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3484 		return -EINVAL;
3485 	}
3486 
3487 	if (!t->name_off ||
3488 	    !__btf_name_valid(env->btf, t->name_off, true)) {
3489 		btf_verifier_log_type(env, t, "Invalid name");
3490 		return -EINVAL;
3491 	}
3492 
3493 	/* A var cannot be in type void */
3494 	if (!t->type || !BTF_TYPE_ID_VALID(t->type)) {
3495 		btf_verifier_log_type(env, t, "Invalid type_id");
3496 		return -EINVAL;
3497 	}
3498 
3499 	var = btf_type_var(t);
3500 	if (var->linkage != BTF_VAR_STATIC &&
3501 	    var->linkage != BTF_VAR_GLOBAL_ALLOCATED) {
3502 		btf_verifier_log_type(env, t, "Linkage not supported");
3503 		return -EINVAL;
3504 	}
3505 
3506 	btf_verifier_log_type(env, t, NULL);
3507 
3508 	return meta_needed;
3509 }
3510 
3511 static void btf_var_log(struct btf_verifier_env *env, const struct btf_type *t)
3512 {
3513 	const struct btf_var *var = btf_type_var(t);
3514 
3515 	btf_verifier_log(env, "type_id=%u linkage=%u", t->type, var->linkage);
3516 }
3517 
3518 static const struct btf_kind_operations var_ops = {
3519 	.check_meta		= btf_var_check_meta,
3520 	.resolve		= btf_var_resolve,
3521 	.check_member		= btf_df_check_member,
3522 	.check_kflag_member	= btf_df_check_kflag_member,
3523 	.log_details		= btf_var_log,
3524 	.show			= btf_var_show,
3525 };
3526 
3527 static s32 btf_datasec_check_meta(struct btf_verifier_env *env,
3528 				  const struct btf_type *t,
3529 				  u32 meta_left)
3530 {
3531 	const struct btf_var_secinfo *vsi;
3532 	u64 last_vsi_end_off = 0, sum = 0;
3533 	u32 i, meta_needed;
3534 
3535 	meta_needed = btf_type_vlen(t) * sizeof(*vsi);
3536 	if (meta_left < meta_needed) {
3537 		btf_verifier_log_basic(env, t,
3538 				       "meta_left:%u meta_needed:%u",
3539 				       meta_left, meta_needed);
3540 		return -EINVAL;
3541 	}
3542 
3543 	if (!btf_type_vlen(t)) {
3544 		btf_verifier_log_type(env, t, "vlen == 0");
3545 		return -EINVAL;
3546 	}
3547 
3548 	if (!t->size) {
3549 		btf_verifier_log_type(env, t, "size == 0");
3550 		return -EINVAL;
3551 	}
3552 
3553 	if (btf_type_kflag(t)) {
3554 		btf_verifier_log_type(env, t, "Invalid btf_info kind_flag");
3555 		return -EINVAL;
3556 	}
3557 
3558 	if (!t->name_off ||
3559 	    !btf_name_valid_section(env->btf, t->name_off)) {
3560 		btf_verifier_log_type(env, t, "Invalid name");
3561 		return -EINVAL;
3562 	}
3563 
3564 	btf_verifier_log_type(env, t, NULL);
3565 
3566 	for_each_vsi(i, t, vsi) {
3567 		/* A var cannot be in type void */
3568 		if (!vsi->type || !BTF_TYPE_ID_VALID(vsi->type)) {
3569 			btf_verifier_log_vsi(env, t, vsi,
3570 					     "Invalid type_id");
3571 			return -EINVAL;
3572 		}
3573 
3574 		if (vsi->offset < last_vsi_end_off || vsi->offset >= t->size) {
3575 			btf_verifier_log_vsi(env, t, vsi,
3576 					     "Invalid offset");
3577 			return -EINVAL;
3578 		}
3579 
3580 		if (!vsi->size || vsi->size > t->size) {
3581 			btf_verifier_log_vsi(env, t, vsi,
3582 					     "Invalid size");
3583 			return -EINVAL;
3584 		}
3585 
3586 		last_vsi_end_off = vsi->offset + vsi->size;
3587 		if (last_vsi_end_off > t->size) {
3588 			btf_verifier_log_vsi(env, t, vsi,
3589 					     "Invalid offset+size");
3590 			return -EINVAL;
3591 		}
3592 
3593 		btf_verifier_log_vsi(env, t, vsi, NULL);
3594 		sum += vsi->size;
3595 	}
3596 
3597 	if (t->size < sum) {
3598 		btf_verifier_log_type(env, t, "Invalid btf_info size");
3599 		return -EINVAL;
3600 	}
3601 
3602 	return meta_needed;
3603 }
3604 
3605 static int btf_datasec_resolve(struct btf_verifier_env *env,
3606 			       const struct resolve_vertex *v)
3607 {
3608 	const struct btf_var_secinfo *vsi;
3609 	struct btf *btf = env->btf;
3610 	u16 i;
3611 
3612 	for_each_vsi_from(i, v->next_member, v->t, vsi) {
3613 		u32 var_type_id = vsi->type, type_id, type_size = 0;
3614 		const struct btf_type *var_type = btf_type_by_id(env->btf,
3615 								 var_type_id);
3616 		if (!var_type || !btf_type_is_var(var_type)) {
3617 			btf_verifier_log_vsi(env, v->t, vsi,
3618 					     "Not a VAR kind member");
3619 			return -EINVAL;
3620 		}
3621 
3622 		if (!env_type_is_resolve_sink(env, var_type) &&
3623 		    !env_type_is_resolved(env, var_type_id)) {
3624 			env_stack_set_next_member(env, i + 1);
3625 			return env_stack_push(env, var_type, var_type_id);
3626 		}
3627 
3628 		type_id = var_type->type;
3629 		if (!btf_type_id_size(btf, &type_id, &type_size)) {
3630 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid type");
3631 			return -EINVAL;
3632 		}
3633 
3634 		if (vsi->size < type_size) {
3635 			btf_verifier_log_vsi(env, v->t, vsi, "Invalid size");
3636 			return -EINVAL;
3637 		}
3638 	}
3639 
3640 	env_stack_pop_resolved(env, 0, 0);
3641 	return 0;
3642 }
3643 
3644 static void btf_datasec_log(struct btf_verifier_env *env,
3645 			    const struct btf_type *t)
3646 {
3647 	btf_verifier_log(env, "size=%u vlen=%u", t->size, btf_type_vlen(t));
3648 }
3649 
3650 static void btf_datasec_show(const struct btf *btf,
3651 			     const struct btf_type *t, u32 type_id,
3652 			     void *data, u8 bits_offset,
3653 			     struct btf_show *show)
3654 {
3655 	const struct btf_var_secinfo *vsi;
3656 	const struct btf_type *var;
3657 	u32 i;
3658 
3659 	if (!btf_show_start_type(show, t, type_id, data))
3660 		return;
3661 
3662 	btf_show_type_value(show, "section (\"%s\") = {",
3663 			    __btf_name_by_offset(btf, t->name_off));
3664 	for_each_vsi(i, t, vsi) {
3665 		var = btf_type_by_id(btf, vsi->type);
3666 		if (i)
3667 			btf_show(show, ",");
3668 		btf_type_ops(var)->show(btf, var, vsi->type,
3669 					data + vsi->offset, bits_offset, show);
3670 	}
3671 	btf_show_end_type(show);
3672 }
3673 
3674 static const struct btf_kind_operations datasec_ops = {
3675 	.check_meta		= btf_datasec_check_meta,
3676 	.resolve		= btf_datasec_resolve,
3677 	.check_member		= btf_df_check_member,
3678 	.check_kflag_member	= btf_df_check_kflag_member,
3679 	.log_details		= btf_datasec_log,
3680 	.show			= btf_datasec_show,
3681 };
3682 
3683 static int btf_func_proto_check(struct btf_verifier_env *env,
3684 				const struct btf_type *t)
3685 {
3686 	const struct btf_type *ret_type;
3687 	const struct btf_param *args;
3688 	const struct btf *btf;
3689 	u16 nr_args, i;
3690 	int err;
3691 
3692 	btf = env->btf;
3693 	args = (const struct btf_param *)(t + 1);
3694 	nr_args = btf_type_vlen(t);
3695 
3696 	/* Check func return type which could be "void" (t->type == 0) */
3697 	if (t->type) {
3698 		u32 ret_type_id = t->type;
3699 
3700 		ret_type = btf_type_by_id(btf, ret_type_id);
3701 		if (!ret_type) {
3702 			btf_verifier_log_type(env, t, "Invalid return type");
3703 			return -EINVAL;
3704 		}
3705 
3706 		if (btf_type_needs_resolve(ret_type) &&
3707 		    !env_type_is_resolved(env, ret_type_id)) {
3708 			err = btf_resolve(env, ret_type, ret_type_id);
3709 			if (err)
3710 				return err;
3711 		}
3712 
3713 		/* Ensure the return type is a type that has a size */
3714 		if (!btf_type_id_size(btf, &ret_type_id, NULL)) {
3715 			btf_verifier_log_type(env, t, "Invalid return type");
3716 			return -EINVAL;
3717 		}
3718 	}
3719 
3720 	if (!nr_args)
3721 		return 0;
3722 
3723 	/* Last func arg type_id could be 0 if it is a vararg */
3724 	if (!args[nr_args - 1].type) {
3725 		if (args[nr_args - 1].name_off) {
3726 			btf_verifier_log_type(env, t, "Invalid arg#%u",
3727 					      nr_args);
3728 			return -EINVAL;
3729 		}
3730 		nr_args--;
3731 	}
3732 
3733 	err = 0;
3734 	for (i = 0; i < nr_args; i++) {
3735 		const struct btf_type *arg_type;
3736 		u32 arg_type_id;
3737 
3738 		arg_type_id = args[i].type;
3739 		arg_type = btf_type_by_id(btf, arg_type_id);
3740 		if (!arg_type) {
3741 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3742 			err = -EINVAL;
3743 			break;
3744 		}
3745 
3746 		if (args[i].name_off &&
3747 		    (!btf_name_offset_valid(btf, args[i].name_off) ||
3748 		     !btf_name_valid_identifier(btf, args[i].name_off))) {
3749 			btf_verifier_log_type(env, t,
3750 					      "Invalid arg#%u", i + 1);
3751 			err = -EINVAL;
3752 			break;
3753 		}
3754 
3755 		if (btf_type_needs_resolve(arg_type) &&
3756 		    !env_type_is_resolved(env, arg_type_id)) {
3757 			err = btf_resolve(env, arg_type, arg_type_id);
3758 			if (err)
3759 				break;
3760 		}
3761 
3762 		if (!btf_type_id_size(btf, &arg_type_id, NULL)) {
3763 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3764 			err = -EINVAL;
3765 			break;
3766 		}
3767 	}
3768 
3769 	return err;
3770 }
3771 
3772 static int btf_func_check(struct btf_verifier_env *env,
3773 			  const struct btf_type *t)
3774 {
3775 	const struct btf_type *proto_type;
3776 	const struct btf_param *args;
3777 	const struct btf *btf;
3778 	u16 nr_args, i;
3779 
3780 	btf = env->btf;
3781 	proto_type = btf_type_by_id(btf, t->type);
3782 
3783 	if (!proto_type || !btf_type_is_func_proto(proto_type)) {
3784 		btf_verifier_log_type(env, t, "Invalid type_id");
3785 		return -EINVAL;
3786 	}
3787 
3788 	args = (const struct btf_param *)(proto_type + 1);
3789 	nr_args = btf_type_vlen(proto_type);
3790 	for (i = 0; i < nr_args; i++) {
3791 		if (!args[i].name_off && args[i].type) {
3792 			btf_verifier_log_type(env, t, "Invalid arg#%u", i + 1);
3793 			return -EINVAL;
3794 		}
3795 	}
3796 
3797 	return 0;
3798 }
3799 
3800 static const struct btf_kind_operations * const kind_ops[NR_BTF_KINDS] = {
3801 	[BTF_KIND_INT] = &int_ops,
3802 	[BTF_KIND_PTR] = &ptr_ops,
3803 	[BTF_KIND_ARRAY] = &array_ops,
3804 	[BTF_KIND_STRUCT] = &struct_ops,
3805 	[BTF_KIND_UNION] = &struct_ops,
3806 	[BTF_KIND_ENUM] = &enum_ops,
3807 	[BTF_KIND_FWD] = &fwd_ops,
3808 	[BTF_KIND_TYPEDEF] = &modifier_ops,
3809 	[BTF_KIND_VOLATILE] = &modifier_ops,
3810 	[BTF_KIND_CONST] = &modifier_ops,
3811 	[BTF_KIND_RESTRICT] = &modifier_ops,
3812 	[BTF_KIND_FUNC] = &func_ops,
3813 	[BTF_KIND_FUNC_PROTO] = &func_proto_ops,
3814 	[BTF_KIND_VAR] = &var_ops,
3815 	[BTF_KIND_DATASEC] = &datasec_ops,
3816 };
3817 
3818 static s32 btf_check_meta(struct btf_verifier_env *env,
3819 			  const struct btf_type *t,
3820 			  u32 meta_left)
3821 {
3822 	u32 saved_meta_left = meta_left;
3823 	s32 var_meta_size;
3824 
3825 	if (meta_left < sizeof(*t)) {
3826 		btf_verifier_log(env, "[%u] meta_left:%u meta_needed:%zu",
3827 				 env->log_type_id, meta_left, sizeof(*t));
3828 		return -EINVAL;
3829 	}
3830 	meta_left -= sizeof(*t);
3831 
3832 	if (t->info & ~BTF_INFO_MASK) {
3833 		btf_verifier_log(env, "[%u] Invalid btf_info:%x",
3834 				 env->log_type_id, t->info);
3835 		return -EINVAL;
3836 	}
3837 
3838 	if (BTF_INFO_KIND(t->info) > BTF_KIND_MAX ||
3839 	    BTF_INFO_KIND(t->info) == BTF_KIND_UNKN) {
3840 		btf_verifier_log(env, "[%u] Invalid kind:%u",
3841 				 env->log_type_id, BTF_INFO_KIND(t->info));
3842 		return -EINVAL;
3843 	}
3844 
3845 	if (!btf_name_offset_valid(env->btf, t->name_off)) {
3846 		btf_verifier_log(env, "[%u] Invalid name_offset:%u",
3847 				 env->log_type_id, t->name_off);
3848 		return -EINVAL;
3849 	}
3850 
3851 	var_meta_size = btf_type_ops(t)->check_meta(env, t, meta_left);
3852 	if (var_meta_size < 0)
3853 		return var_meta_size;
3854 
3855 	meta_left -= var_meta_size;
3856 
3857 	return saved_meta_left - meta_left;
3858 }
3859 
3860 static int btf_check_all_metas(struct btf_verifier_env *env)
3861 {
3862 	struct btf *btf = env->btf;
3863 	struct btf_header *hdr;
3864 	void *cur, *end;
3865 
3866 	hdr = &btf->hdr;
3867 	cur = btf->nohdr_data + hdr->type_off;
3868 	end = cur + hdr->type_len;
3869 
3870 	env->log_type_id = btf->base_btf ? btf->start_id : 1;
3871 	while (cur < end) {
3872 		struct btf_type *t = cur;
3873 		s32 meta_size;
3874 
3875 		meta_size = btf_check_meta(env, t, end - cur);
3876 		if (meta_size < 0)
3877 			return meta_size;
3878 
3879 		btf_add_type(env, t);
3880 		cur += meta_size;
3881 		env->log_type_id++;
3882 	}
3883 
3884 	return 0;
3885 }
3886 
3887 static bool btf_resolve_valid(struct btf_verifier_env *env,
3888 			      const struct btf_type *t,
3889 			      u32 type_id)
3890 {
3891 	struct btf *btf = env->btf;
3892 
3893 	if (!env_type_is_resolved(env, type_id))
3894 		return false;
3895 
3896 	if (btf_type_is_struct(t) || btf_type_is_datasec(t))
3897 		return !btf_resolved_type_id(btf, type_id) &&
3898 		       !btf_resolved_type_size(btf, type_id);
3899 
3900 	if (btf_type_is_modifier(t) || btf_type_is_ptr(t) ||
3901 	    btf_type_is_var(t)) {
3902 		t = btf_type_id_resolve(btf, &type_id);
3903 		return t &&
3904 		       !btf_type_is_modifier(t) &&
3905 		       !btf_type_is_var(t) &&
3906 		       !btf_type_is_datasec(t);
3907 	}
3908 
3909 	if (btf_type_is_array(t)) {
3910 		const struct btf_array *array = btf_type_array(t);
3911 		const struct btf_type *elem_type;
3912 		u32 elem_type_id = array->type;
3913 		u32 elem_size;
3914 
3915 		elem_type = btf_type_id_size(btf, &elem_type_id, &elem_size);
3916 		return elem_type && !btf_type_is_modifier(elem_type) &&
3917 			(array->nelems * elem_size ==
3918 			 btf_resolved_type_size(btf, type_id));
3919 	}
3920 
3921 	return false;
3922 }
3923 
3924 static int btf_resolve(struct btf_verifier_env *env,
3925 		       const struct btf_type *t, u32 type_id)
3926 {
3927 	u32 save_log_type_id = env->log_type_id;
3928 	const struct resolve_vertex *v;
3929 	int err = 0;
3930 
3931 	env->resolve_mode = RESOLVE_TBD;
3932 	env_stack_push(env, t, type_id);
3933 	while (!err && (v = env_stack_peak(env))) {
3934 		env->log_type_id = v->type_id;
3935 		err = btf_type_ops(v->t)->resolve(env, v);
3936 	}
3937 
3938 	env->log_type_id = type_id;
3939 	if (err == -E2BIG) {
3940 		btf_verifier_log_type(env, t,
3941 				      "Exceeded max resolving depth:%u",
3942 				      MAX_RESOLVE_DEPTH);
3943 	} else if (err == -EEXIST) {
3944 		btf_verifier_log_type(env, t, "Loop detected");
3945 	}
3946 
3947 	/* Final sanity check */
3948 	if (!err && !btf_resolve_valid(env, t, type_id)) {
3949 		btf_verifier_log_type(env, t, "Invalid resolve state");
3950 		err = -EINVAL;
3951 	}
3952 
3953 	env->log_type_id = save_log_type_id;
3954 	return err;
3955 }
3956 
3957 static int btf_check_all_types(struct btf_verifier_env *env)
3958 {
3959 	struct btf *btf = env->btf;
3960 	const struct btf_type *t;
3961 	u32 type_id, i;
3962 	int err;
3963 
3964 	err = env_resolve_init(env);
3965 	if (err)
3966 		return err;
3967 
3968 	env->phase++;
3969 	for (i = btf->base_btf ? 0 : 1; i < btf->nr_types; i++) {
3970 		type_id = btf->start_id + i;
3971 		t = btf_type_by_id(btf, type_id);
3972 
3973 		env->log_type_id = type_id;
3974 		if (btf_type_needs_resolve(t) &&
3975 		    !env_type_is_resolved(env, type_id)) {
3976 			err = btf_resolve(env, t, type_id);
3977 			if (err)
3978 				return err;
3979 		}
3980 
3981 		if (btf_type_is_func_proto(t)) {
3982 			err = btf_func_proto_check(env, t);
3983 			if (err)
3984 				return err;
3985 		}
3986 
3987 		if (btf_type_is_func(t)) {
3988 			err = btf_func_check(env, t);
3989 			if (err)
3990 				return err;
3991 		}
3992 	}
3993 
3994 	return 0;
3995 }
3996 
3997 static int btf_parse_type_sec(struct btf_verifier_env *env)
3998 {
3999 	const struct btf_header *hdr = &env->btf->hdr;
4000 	int err;
4001 
4002 	/* Type section must align to 4 bytes */
4003 	if (hdr->type_off & (sizeof(u32) - 1)) {
4004 		btf_verifier_log(env, "Unaligned type_off");
4005 		return -EINVAL;
4006 	}
4007 
4008 	if (!env->btf->base_btf && !hdr->type_len) {
4009 		btf_verifier_log(env, "No type found");
4010 		return -EINVAL;
4011 	}
4012 
4013 	err = btf_check_all_metas(env);
4014 	if (err)
4015 		return err;
4016 
4017 	return btf_check_all_types(env);
4018 }
4019 
4020 static int btf_parse_str_sec(struct btf_verifier_env *env)
4021 {
4022 	const struct btf_header *hdr;
4023 	struct btf *btf = env->btf;
4024 	const char *start, *end;
4025 
4026 	hdr = &btf->hdr;
4027 	start = btf->nohdr_data + hdr->str_off;
4028 	end = start + hdr->str_len;
4029 
4030 	if (end != btf->data + btf->data_size) {
4031 		btf_verifier_log(env, "String section is not at the end");
4032 		return -EINVAL;
4033 	}
4034 
4035 	btf->strings = start;
4036 
4037 	if (btf->base_btf && !hdr->str_len)
4038 		return 0;
4039 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_NAME_OFFSET || end[-1]) {
4040 		btf_verifier_log(env, "Invalid string section");
4041 		return -EINVAL;
4042 	}
4043 	if (!btf->base_btf && start[0]) {
4044 		btf_verifier_log(env, "Invalid string section");
4045 		return -EINVAL;
4046 	}
4047 
4048 	return 0;
4049 }
4050 
4051 static const size_t btf_sec_info_offset[] = {
4052 	offsetof(struct btf_header, type_off),
4053 	offsetof(struct btf_header, str_off),
4054 };
4055 
4056 static int btf_sec_info_cmp(const void *a, const void *b)
4057 {
4058 	const struct btf_sec_info *x = a;
4059 	const struct btf_sec_info *y = b;
4060 
4061 	return (int)(x->off - y->off) ? : (int)(x->len - y->len);
4062 }
4063 
4064 static int btf_check_sec_info(struct btf_verifier_env *env,
4065 			      u32 btf_data_size)
4066 {
4067 	struct btf_sec_info secs[ARRAY_SIZE(btf_sec_info_offset)];
4068 	u32 total, expected_total, i;
4069 	const struct btf_header *hdr;
4070 	const struct btf *btf;
4071 
4072 	btf = env->btf;
4073 	hdr = &btf->hdr;
4074 
4075 	/* Populate the secs from hdr */
4076 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++)
4077 		secs[i] = *(struct btf_sec_info *)((void *)hdr +
4078 						   btf_sec_info_offset[i]);
4079 
4080 	sort(secs, ARRAY_SIZE(btf_sec_info_offset),
4081 	     sizeof(struct btf_sec_info), btf_sec_info_cmp, NULL);
4082 
4083 	/* Check for gaps and overlap among sections */
4084 	total = 0;
4085 	expected_total = btf_data_size - hdr->hdr_len;
4086 	for (i = 0; i < ARRAY_SIZE(btf_sec_info_offset); i++) {
4087 		if (expected_total < secs[i].off) {
4088 			btf_verifier_log(env, "Invalid section offset");
4089 			return -EINVAL;
4090 		}
4091 		if (total < secs[i].off) {
4092 			/* gap */
4093 			btf_verifier_log(env, "Unsupported section found");
4094 			return -EINVAL;
4095 		}
4096 		if (total > secs[i].off) {
4097 			btf_verifier_log(env, "Section overlap found");
4098 			return -EINVAL;
4099 		}
4100 		if (expected_total - total < secs[i].len) {
4101 			btf_verifier_log(env,
4102 					 "Total section length too long");
4103 			return -EINVAL;
4104 		}
4105 		total += secs[i].len;
4106 	}
4107 
4108 	/* There is data other than hdr and known sections */
4109 	if (expected_total != total) {
4110 		btf_verifier_log(env, "Unsupported section found");
4111 		return -EINVAL;
4112 	}
4113 
4114 	return 0;
4115 }
4116 
4117 static int btf_parse_hdr(struct btf_verifier_env *env)
4118 {
4119 	u32 hdr_len, hdr_copy, btf_data_size;
4120 	const struct btf_header *hdr;
4121 	struct btf *btf;
4122 	int err;
4123 
4124 	btf = env->btf;
4125 	btf_data_size = btf->data_size;
4126 
4127 	if (btf_data_size <
4128 	    offsetof(struct btf_header, hdr_len) + sizeof(hdr->hdr_len)) {
4129 		btf_verifier_log(env, "hdr_len not found");
4130 		return -EINVAL;
4131 	}
4132 
4133 	hdr = btf->data;
4134 	hdr_len = hdr->hdr_len;
4135 	if (btf_data_size < hdr_len) {
4136 		btf_verifier_log(env, "btf_header not found");
4137 		return -EINVAL;
4138 	}
4139 
4140 	/* Ensure the unsupported header fields are zero */
4141 	if (hdr_len > sizeof(btf->hdr)) {
4142 		u8 *expected_zero = btf->data + sizeof(btf->hdr);
4143 		u8 *end = btf->data + hdr_len;
4144 
4145 		for (; expected_zero < end; expected_zero++) {
4146 			if (*expected_zero) {
4147 				btf_verifier_log(env, "Unsupported btf_header");
4148 				return -E2BIG;
4149 			}
4150 		}
4151 	}
4152 
4153 	hdr_copy = min_t(u32, hdr_len, sizeof(btf->hdr));
4154 	memcpy(&btf->hdr, btf->data, hdr_copy);
4155 
4156 	hdr = &btf->hdr;
4157 
4158 	btf_verifier_log_hdr(env, btf_data_size);
4159 
4160 	if (hdr->magic != BTF_MAGIC) {
4161 		btf_verifier_log(env, "Invalid magic");
4162 		return -EINVAL;
4163 	}
4164 
4165 	if (hdr->version != BTF_VERSION) {
4166 		btf_verifier_log(env, "Unsupported version");
4167 		return -ENOTSUPP;
4168 	}
4169 
4170 	if (hdr->flags) {
4171 		btf_verifier_log(env, "Unsupported flags");
4172 		return -ENOTSUPP;
4173 	}
4174 
4175 	if (btf_data_size == hdr->hdr_len) {
4176 		btf_verifier_log(env, "No data");
4177 		return -EINVAL;
4178 	}
4179 
4180 	err = btf_check_sec_info(env, btf_data_size);
4181 	if (err)
4182 		return err;
4183 
4184 	return 0;
4185 }
4186 
4187 static struct btf *btf_parse(void __user *btf_data, u32 btf_data_size,
4188 			     u32 log_level, char __user *log_ubuf, u32 log_size)
4189 {
4190 	struct btf_verifier_env *env = NULL;
4191 	struct bpf_verifier_log *log;
4192 	struct btf *btf = NULL;
4193 	u8 *data;
4194 	int err;
4195 
4196 	if (btf_data_size > BTF_MAX_SIZE)
4197 		return ERR_PTR(-E2BIG);
4198 
4199 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4200 	if (!env)
4201 		return ERR_PTR(-ENOMEM);
4202 
4203 	log = &env->log;
4204 	if (log_level || log_ubuf || log_size) {
4205 		/* user requested verbose verifier output
4206 		 * and supplied buffer to store the verification trace
4207 		 */
4208 		log->level = log_level;
4209 		log->ubuf = log_ubuf;
4210 		log->len_total = log_size;
4211 
4212 		/* log attributes have to be sane */
4213 		if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 ||
4214 		    !log->level || !log->ubuf) {
4215 			err = -EINVAL;
4216 			goto errout;
4217 		}
4218 	}
4219 
4220 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4221 	if (!btf) {
4222 		err = -ENOMEM;
4223 		goto errout;
4224 	}
4225 	env->btf = btf;
4226 
4227 	data = kvmalloc(btf_data_size, GFP_KERNEL | __GFP_NOWARN);
4228 	if (!data) {
4229 		err = -ENOMEM;
4230 		goto errout;
4231 	}
4232 
4233 	btf->data = data;
4234 	btf->data_size = btf_data_size;
4235 
4236 	if (copy_from_user(data, btf_data, btf_data_size)) {
4237 		err = -EFAULT;
4238 		goto errout;
4239 	}
4240 
4241 	err = btf_parse_hdr(env);
4242 	if (err)
4243 		goto errout;
4244 
4245 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4246 
4247 	err = btf_parse_str_sec(env);
4248 	if (err)
4249 		goto errout;
4250 
4251 	err = btf_parse_type_sec(env);
4252 	if (err)
4253 		goto errout;
4254 
4255 	if (log->level && bpf_verifier_log_full(log)) {
4256 		err = -ENOSPC;
4257 		goto errout;
4258 	}
4259 
4260 	btf_verifier_env_free(env);
4261 	refcount_set(&btf->refcnt, 1);
4262 	return btf;
4263 
4264 errout:
4265 	btf_verifier_env_free(env);
4266 	if (btf)
4267 		btf_free(btf);
4268 	return ERR_PTR(err);
4269 }
4270 
4271 extern char __weak __start_BTF[];
4272 extern char __weak __stop_BTF[];
4273 extern struct btf *btf_vmlinux;
4274 
4275 #define BPF_MAP_TYPE(_id, _ops)
4276 #define BPF_LINK_TYPE(_id, _name)
4277 static union {
4278 	struct bpf_ctx_convert {
4279 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4280 	prog_ctx_type _id##_prog; \
4281 	kern_ctx_type _id##_kern;
4282 #include <linux/bpf_types.h>
4283 #undef BPF_PROG_TYPE
4284 	} *__t;
4285 	/* 't' is written once under lock. Read many times. */
4286 	const struct btf_type *t;
4287 } bpf_ctx_convert;
4288 enum {
4289 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4290 	__ctx_convert##_id,
4291 #include <linux/bpf_types.h>
4292 #undef BPF_PROG_TYPE
4293 	__ctx_convert_unused, /* to avoid empty enum in extreme .config */
4294 };
4295 static u8 bpf_ctx_convert_map[] = {
4296 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \
4297 	[_id] = __ctx_convert##_id,
4298 #include <linux/bpf_types.h>
4299 #undef BPF_PROG_TYPE
4300 	0, /* avoid empty array */
4301 };
4302 #undef BPF_MAP_TYPE
4303 #undef BPF_LINK_TYPE
4304 
4305 static const struct btf_member *
4306 btf_get_prog_ctx_type(struct bpf_verifier_log *log, struct btf *btf,
4307 		      const struct btf_type *t, enum bpf_prog_type prog_type,
4308 		      int arg)
4309 {
4310 	const struct btf_type *conv_struct;
4311 	const struct btf_type *ctx_struct;
4312 	const struct btf_member *ctx_type;
4313 	const char *tname, *ctx_tname;
4314 
4315 	conv_struct = bpf_ctx_convert.t;
4316 	if (!conv_struct) {
4317 		bpf_log(log, "btf_vmlinux is malformed\n");
4318 		return NULL;
4319 	}
4320 	t = btf_type_by_id(btf, t->type);
4321 	while (btf_type_is_modifier(t))
4322 		t = btf_type_by_id(btf, t->type);
4323 	if (!btf_type_is_struct(t)) {
4324 		/* Only pointer to struct is supported for now.
4325 		 * That means that BPF_PROG_TYPE_TRACEPOINT with BTF
4326 		 * is not supported yet.
4327 		 * BPF_PROG_TYPE_RAW_TRACEPOINT is fine.
4328 		 */
4329 		if (log->level & BPF_LOG_LEVEL)
4330 			bpf_log(log, "arg#%d type is not a struct\n", arg);
4331 		return NULL;
4332 	}
4333 	tname = btf_name_by_offset(btf, t->name_off);
4334 	if (!tname) {
4335 		bpf_log(log, "arg#%d struct doesn't have a name\n", arg);
4336 		return NULL;
4337 	}
4338 	/* prog_type is valid bpf program type. No need for bounds check. */
4339 	ctx_type = btf_type_member(conv_struct) + bpf_ctx_convert_map[prog_type] * 2;
4340 	/* ctx_struct is a pointer to prog_ctx_type in vmlinux.
4341 	 * Like 'struct __sk_buff'
4342 	 */
4343 	ctx_struct = btf_type_by_id(btf_vmlinux, ctx_type->type);
4344 	if (!ctx_struct)
4345 		/* should not happen */
4346 		return NULL;
4347 	ctx_tname = btf_name_by_offset(btf_vmlinux, ctx_struct->name_off);
4348 	if (!ctx_tname) {
4349 		/* should not happen */
4350 		bpf_log(log, "Please fix kernel include/linux/bpf_types.h\n");
4351 		return NULL;
4352 	}
4353 	/* only compare that prog's ctx type name is the same as
4354 	 * kernel expects. No need to compare field by field.
4355 	 * It's ok for bpf prog to do:
4356 	 * struct __sk_buff {};
4357 	 * int socket_filter_bpf_prog(struct __sk_buff *skb)
4358 	 * { // no fields of skb are ever used }
4359 	 */
4360 	if (strcmp(ctx_tname, tname))
4361 		return NULL;
4362 	return ctx_type;
4363 }
4364 
4365 static const struct bpf_map_ops * const btf_vmlinux_map_ops[] = {
4366 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type)
4367 #define BPF_LINK_TYPE(_id, _name)
4368 #define BPF_MAP_TYPE(_id, _ops) \
4369 	[_id] = &_ops,
4370 #include <linux/bpf_types.h>
4371 #undef BPF_PROG_TYPE
4372 #undef BPF_LINK_TYPE
4373 #undef BPF_MAP_TYPE
4374 };
4375 
4376 static int btf_vmlinux_map_ids_init(const struct btf *btf,
4377 				    struct bpf_verifier_log *log)
4378 {
4379 	const struct bpf_map_ops *ops;
4380 	int i, btf_id;
4381 
4382 	for (i = 0; i < ARRAY_SIZE(btf_vmlinux_map_ops); ++i) {
4383 		ops = btf_vmlinux_map_ops[i];
4384 		if (!ops || (!ops->map_btf_name && !ops->map_btf_id))
4385 			continue;
4386 		if (!ops->map_btf_name || !ops->map_btf_id) {
4387 			bpf_log(log, "map type %d is misconfigured\n", i);
4388 			return -EINVAL;
4389 		}
4390 		btf_id = btf_find_by_name_kind(btf, ops->map_btf_name,
4391 					       BTF_KIND_STRUCT);
4392 		if (btf_id < 0)
4393 			return btf_id;
4394 		*ops->map_btf_id = btf_id;
4395 	}
4396 
4397 	return 0;
4398 }
4399 
4400 static int btf_translate_to_vmlinux(struct bpf_verifier_log *log,
4401 				     struct btf *btf,
4402 				     const struct btf_type *t,
4403 				     enum bpf_prog_type prog_type,
4404 				     int arg)
4405 {
4406 	const struct btf_member *prog_ctx_type, *kern_ctx_type;
4407 
4408 	prog_ctx_type = btf_get_prog_ctx_type(log, btf, t, prog_type, arg);
4409 	if (!prog_ctx_type)
4410 		return -ENOENT;
4411 	kern_ctx_type = prog_ctx_type + 1;
4412 	return kern_ctx_type->type;
4413 }
4414 
4415 BTF_ID_LIST(bpf_ctx_convert_btf_id)
4416 BTF_ID(struct, bpf_ctx_convert)
4417 
4418 struct btf *btf_parse_vmlinux(void)
4419 {
4420 	struct btf_verifier_env *env = NULL;
4421 	struct bpf_verifier_log *log;
4422 	struct btf *btf = NULL;
4423 	int err;
4424 
4425 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4426 	if (!env)
4427 		return ERR_PTR(-ENOMEM);
4428 
4429 	log = &env->log;
4430 	log->level = BPF_LOG_KERNEL;
4431 
4432 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4433 	if (!btf) {
4434 		err = -ENOMEM;
4435 		goto errout;
4436 	}
4437 	env->btf = btf;
4438 
4439 	btf->data = __start_BTF;
4440 	btf->data_size = __stop_BTF - __start_BTF;
4441 	btf->kernel_btf = true;
4442 	snprintf(btf->name, sizeof(btf->name), "vmlinux");
4443 
4444 	err = btf_parse_hdr(env);
4445 	if (err)
4446 		goto errout;
4447 
4448 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4449 
4450 	err = btf_parse_str_sec(env);
4451 	if (err)
4452 		goto errout;
4453 
4454 	err = btf_check_all_metas(env);
4455 	if (err)
4456 		goto errout;
4457 
4458 	/* btf_parse_vmlinux() runs under bpf_verifier_lock */
4459 	bpf_ctx_convert.t = btf_type_by_id(btf, bpf_ctx_convert_btf_id[0]);
4460 
4461 	/* find bpf map structs for map_ptr access checking */
4462 	err = btf_vmlinux_map_ids_init(btf, log);
4463 	if (err < 0)
4464 		goto errout;
4465 
4466 	bpf_struct_ops_init(btf, log);
4467 
4468 	refcount_set(&btf->refcnt, 1);
4469 
4470 	err = btf_alloc_id(btf);
4471 	if (err)
4472 		goto errout;
4473 
4474 	btf_verifier_env_free(env);
4475 	return btf;
4476 
4477 errout:
4478 	btf_verifier_env_free(env);
4479 	if (btf) {
4480 		kvfree(btf->types);
4481 		kfree(btf);
4482 	}
4483 	return ERR_PTR(err);
4484 }
4485 
4486 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
4487 
4488 static struct btf *btf_parse_module(const char *module_name, const void *data, unsigned int data_size)
4489 {
4490 	struct btf_verifier_env *env = NULL;
4491 	struct bpf_verifier_log *log;
4492 	struct btf *btf = NULL, *base_btf;
4493 	int err;
4494 
4495 	base_btf = bpf_get_btf_vmlinux();
4496 	if (IS_ERR(base_btf))
4497 		return base_btf;
4498 	if (!base_btf)
4499 		return ERR_PTR(-EINVAL);
4500 
4501 	env = kzalloc(sizeof(*env), GFP_KERNEL | __GFP_NOWARN);
4502 	if (!env)
4503 		return ERR_PTR(-ENOMEM);
4504 
4505 	log = &env->log;
4506 	log->level = BPF_LOG_KERNEL;
4507 
4508 	btf = kzalloc(sizeof(*btf), GFP_KERNEL | __GFP_NOWARN);
4509 	if (!btf) {
4510 		err = -ENOMEM;
4511 		goto errout;
4512 	}
4513 	env->btf = btf;
4514 
4515 	btf->base_btf = base_btf;
4516 	btf->start_id = base_btf->nr_types;
4517 	btf->start_str_off = base_btf->hdr.str_len;
4518 	btf->kernel_btf = true;
4519 	snprintf(btf->name, sizeof(btf->name), "%s", module_name);
4520 
4521 	btf->data = kvmalloc(data_size, GFP_KERNEL | __GFP_NOWARN);
4522 	if (!btf->data) {
4523 		err = -ENOMEM;
4524 		goto errout;
4525 	}
4526 	memcpy(btf->data, data, data_size);
4527 	btf->data_size = data_size;
4528 
4529 	err = btf_parse_hdr(env);
4530 	if (err)
4531 		goto errout;
4532 
4533 	btf->nohdr_data = btf->data + btf->hdr.hdr_len;
4534 
4535 	err = btf_parse_str_sec(env);
4536 	if (err)
4537 		goto errout;
4538 
4539 	err = btf_check_all_metas(env);
4540 	if (err)
4541 		goto errout;
4542 
4543 	btf_verifier_env_free(env);
4544 	refcount_set(&btf->refcnt, 1);
4545 	return btf;
4546 
4547 errout:
4548 	btf_verifier_env_free(env);
4549 	if (btf) {
4550 		kvfree(btf->data);
4551 		kvfree(btf->types);
4552 		kfree(btf);
4553 	}
4554 	return ERR_PTR(err);
4555 }
4556 
4557 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
4558 
4559 struct btf *bpf_prog_get_target_btf(const struct bpf_prog *prog)
4560 {
4561 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4562 
4563 	if (tgt_prog)
4564 		return tgt_prog->aux->btf;
4565 	else
4566 		return prog->aux->attach_btf;
4567 }
4568 
4569 static bool is_string_ptr(struct btf *btf, const struct btf_type *t)
4570 {
4571 	/* t comes in already as a pointer */
4572 	t = btf_type_by_id(btf, t->type);
4573 
4574 	/* allow const */
4575 	if (BTF_INFO_KIND(t->info) == BTF_KIND_CONST)
4576 		t = btf_type_by_id(btf, t->type);
4577 
4578 	/* char, signed char, unsigned char */
4579 	return btf_type_is_int(t) && t->size == 1;
4580 }
4581 
4582 bool btf_ctx_access(int off, int size, enum bpf_access_type type,
4583 		    const struct bpf_prog *prog,
4584 		    struct bpf_insn_access_aux *info)
4585 {
4586 	const struct btf_type *t = prog->aux->attach_func_proto;
4587 	struct bpf_prog *tgt_prog = prog->aux->dst_prog;
4588 	struct btf *btf = bpf_prog_get_target_btf(prog);
4589 	const char *tname = prog->aux->attach_func_name;
4590 	struct bpf_verifier_log *log = info->log;
4591 	const struct btf_param *args;
4592 	u32 nr_args, arg;
4593 	int i, ret;
4594 
4595 	if (off % 8) {
4596 		bpf_log(log, "func '%s' offset %d is not multiple of 8\n",
4597 			tname, off);
4598 		return false;
4599 	}
4600 	arg = off / 8;
4601 	args = (const struct btf_param *)(t + 1);
4602 	/* if (t == NULL) Fall back to default BPF prog with 5 u64 arguments */
4603 	nr_args = t ? btf_type_vlen(t) : 5;
4604 	if (prog->aux->attach_btf_trace) {
4605 		/* skip first 'void *__data' argument in btf_trace_##name typedef */
4606 		args++;
4607 		nr_args--;
4608 	}
4609 
4610 	if (arg > nr_args) {
4611 		bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4612 			tname, arg + 1);
4613 		return false;
4614 	}
4615 
4616 	if (arg == nr_args) {
4617 		switch (prog->expected_attach_type) {
4618 		case BPF_LSM_MAC:
4619 		case BPF_TRACE_FEXIT:
4620 			/* When LSM programs are attached to void LSM hooks
4621 			 * they use FEXIT trampolines and when attached to
4622 			 * int LSM hooks, they use MODIFY_RETURN trampolines.
4623 			 *
4624 			 * While the LSM programs are BPF_MODIFY_RETURN-like
4625 			 * the check:
4626 			 *
4627 			 *	if (ret_type != 'int')
4628 			 *		return -EINVAL;
4629 			 *
4630 			 * is _not_ done here. This is still safe as LSM hooks
4631 			 * have only void and int return types.
4632 			 */
4633 			if (!t)
4634 				return true;
4635 			t = btf_type_by_id(btf, t->type);
4636 			break;
4637 		case BPF_MODIFY_RETURN:
4638 			/* For now the BPF_MODIFY_RETURN can only be attached to
4639 			 * functions that return an int.
4640 			 */
4641 			if (!t)
4642 				return false;
4643 
4644 			t = btf_type_skip_modifiers(btf, t->type, NULL);
4645 			if (!btf_type_is_small_int(t)) {
4646 				bpf_log(log,
4647 					"ret type %s not allowed for fmod_ret\n",
4648 					btf_kind_str[BTF_INFO_KIND(t->info)]);
4649 				return false;
4650 			}
4651 			break;
4652 		default:
4653 			bpf_log(log, "func '%s' doesn't have %d-th argument\n",
4654 				tname, arg + 1);
4655 			return false;
4656 		}
4657 	} else {
4658 		if (!t)
4659 			/* Default prog with 5 args */
4660 			return true;
4661 		t = btf_type_by_id(btf, args[arg].type);
4662 	}
4663 
4664 	/* skip modifiers */
4665 	while (btf_type_is_modifier(t))
4666 		t = btf_type_by_id(btf, t->type);
4667 	if (btf_type_is_small_int(t) || btf_type_is_enum(t))
4668 		/* accessing a scalar */
4669 		return true;
4670 	if (!btf_type_is_ptr(t)) {
4671 		bpf_log(log,
4672 			"func '%s' arg%d '%s' has type %s. Only pointer access is allowed\n",
4673 			tname, arg,
4674 			__btf_name_by_offset(btf, t->name_off),
4675 			btf_kind_str[BTF_INFO_KIND(t->info)]);
4676 		return false;
4677 	}
4678 
4679 	/* check for PTR_TO_RDONLY_BUF_OR_NULL or PTR_TO_RDWR_BUF_OR_NULL */
4680 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4681 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4682 
4683 		if (ctx_arg_info->offset == off &&
4684 		    (ctx_arg_info->reg_type == PTR_TO_RDONLY_BUF_OR_NULL ||
4685 		     ctx_arg_info->reg_type == PTR_TO_RDWR_BUF_OR_NULL)) {
4686 			info->reg_type = ctx_arg_info->reg_type;
4687 			return true;
4688 		}
4689 	}
4690 
4691 	if (t->type == 0)
4692 		/* This is a pointer to void.
4693 		 * It is the same as scalar from the verifier safety pov.
4694 		 * No further pointer walking is allowed.
4695 		 */
4696 		return true;
4697 
4698 	if (is_string_ptr(btf, t))
4699 		return true;
4700 
4701 	/* this is a pointer to another type */
4702 	for (i = 0; i < prog->aux->ctx_arg_info_size; i++) {
4703 		const struct bpf_ctx_arg_aux *ctx_arg_info = &prog->aux->ctx_arg_info[i];
4704 
4705 		if (ctx_arg_info->offset == off) {
4706 			info->reg_type = ctx_arg_info->reg_type;
4707 			info->btf = btf_vmlinux;
4708 			info->btf_id = ctx_arg_info->btf_id;
4709 			return true;
4710 		}
4711 	}
4712 
4713 	info->reg_type = PTR_TO_BTF_ID;
4714 	if (tgt_prog) {
4715 		enum bpf_prog_type tgt_type;
4716 
4717 		if (tgt_prog->type == BPF_PROG_TYPE_EXT)
4718 			tgt_type = tgt_prog->aux->saved_dst_prog_type;
4719 		else
4720 			tgt_type = tgt_prog->type;
4721 
4722 		ret = btf_translate_to_vmlinux(log, btf, t, tgt_type, arg);
4723 		if (ret > 0) {
4724 			info->btf = btf_vmlinux;
4725 			info->btf_id = ret;
4726 			return true;
4727 		} else {
4728 			return false;
4729 		}
4730 	}
4731 
4732 	info->btf = btf;
4733 	info->btf_id = t->type;
4734 	t = btf_type_by_id(btf, t->type);
4735 	/* skip modifiers */
4736 	while (btf_type_is_modifier(t)) {
4737 		info->btf_id = t->type;
4738 		t = btf_type_by_id(btf, t->type);
4739 	}
4740 	if (!btf_type_is_struct(t)) {
4741 		bpf_log(log,
4742 			"func '%s' arg%d type %s is not a struct\n",
4743 			tname, arg, btf_kind_str[BTF_INFO_KIND(t->info)]);
4744 		return false;
4745 	}
4746 	bpf_log(log, "func '%s' arg%d has btf_id %d type %s '%s'\n",
4747 		tname, arg, info->btf_id, btf_kind_str[BTF_INFO_KIND(t->info)],
4748 		__btf_name_by_offset(btf, t->name_off));
4749 	return true;
4750 }
4751 
4752 enum bpf_struct_walk_result {
4753 	/* < 0 error */
4754 	WALK_SCALAR = 0,
4755 	WALK_PTR,
4756 	WALK_STRUCT,
4757 };
4758 
4759 static int btf_struct_walk(struct bpf_verifier_log *log, const struct btf *btf,
4760 			   const struct btf_type *t, int off, int size,
4761 			   u32 *next_btf_id)
4762 {
4763 	u32 i, moff, mtrue_end, msize = 0, total_nelems = 0;
4764 	const struct btf_type *mtype, *elem_type = NULL;
4765 	const struct btf_member *member;
4766 	const char *tname, *mname;
4767 	u32 vlen, elem_id, mid;
4768 
4769 again:
4770 	tname = __btf_name_by_offset(btf, t->name_off);
4771 	if (!btf_type_is_struct(t)) {
4772 		bpf_log(log, "Type '%s' is not a struct\n", tname);
4773 		return -EINVAL;
4774 	}
4775 
4776 	vlen = btf_type_vlen(t);
4777 	if (off + size > t->size) {
4778 		/* If the last element is a variable size array, we may
4779 		 * need to relax the rule.
4780 		 */
4781 		struct btf_array *array_elem;
4782 
4783 		if (vlen == 0)
4784 			goto error;
4785 
4786 		member = btf_type_member(t) + vlen - 1;
4787 		mtype = btf_type_skip_modifiers(btf, member->type,
4788 						NULL);
4789 		if (!btf_type_is_array(mtype))
4790 			goto error;
4791 
4792 		array_elem = (struct btf_array *)(mtype + 1);
4793 		if (array_elem->nelems != 0)
4794 			goto error;
4795 
4796 		moff = btf_member_bit_offset(t, member) / 8;
4797 		if (off < moff)
4798 			goto error;
4799 
4800 		/* Only allow structure for now, can be relaxed for
4801 		 * other types later.
4802 		 */
4803 		t = btf_type_skip_modifiers(btf, array_elem->type,
4804 					    NULL);
4805 		if (!btf_type_is_struct(t))
4806 			goto error;
4807 
4808 		off = (off - moff) % t->size;
4809 		goto again;
4810 
4811 error:
4812 		bpf_log(log, "access beyond struct %s at off %u size %u\n",
4813 			tname, off, size);
4814 		return -EACCES;
4815 	}
4816 
4817 	for_each_member(i, t, member) {
4818 		/* offset of the field in bytes */
4819 		moff = btf_member_bit_offset(t, member) / 8;
4820 		if (off + size <= moff)
4821 			/* won't find anything, field is already too far */
4822 			break;
4823 
4824 		if (btf_member_bitfield_size(t, member)) {
4825 			u32 end_bit = btf_member_bit_offset(t, member) +
4826 				btf_member_bitfield_size(t, member);
4827 
4828 			/* off <= moff instead of off == moff because clang
4829 			 * does not generate a BTF member for anonymous
4830 			 * bitfield like the ":16" here:
4831 			 * struct {
4832 			 *	int :16;
4833 			 *	int x:8;
4834 			 * };
4835 			 */
4836 			if (off <= moff &&
4837 			    BITS_ROUNDUP_BYTES(end_bit) <= off + size)
4838 				return WALK_SCALAR;
4839 
4840 			/* off may be accessing a following member
4841 			 *
4842 			 * or
4843 			 *
4844 			 * Doing partial access at either end of this
4845 			 * bitfield.  Continue on this case also to
4846 			 * treat it as not accessing this bitfield
4847 			 * and eventually error out as field not
4848 			 * found to keep it simple.
4849 			 * It could be relaxed if there was a legit
4850 			 * partial access case later.
4851 			 */
4852 			continue;
4853 		}
4854 
4855 		/* In case of "off" is pointing to holes of a struct */
4856 		if (off < moff)
4857 			break;
4858 
4859 		/* type of the field */
4860 		mid = member->type;
4861 		mtype = btf_type_by_id(btf, member->type);
4862 		mname = __btf_name_by_offset(btf, member->name_off);
4863 
4864 		mtype = __btf_resolve_size(btf, mtype, &msize,
4865 					   &elem_type, &elem_id, &total_nelems,
4866 					   &mid);
4867 		if (IS_ERR(mtype)) {
4868 			bpf_log(log, "field %s doesn't have size\n", mname);
4869 			return -EFAULT;
4870 		}
4871 
4872 		mtrue_end = moff + msize;
4873 		if (off >= mtrue_end)
4874 			/* no overlap with member, keep iterating */
4875 			continue;
4876 
4877 		if (btf_type_is_array(mtype)) {
4878 			u32 elem_idx;
4879 
4880 			/* __btf_resolve_size() above helps to
4881 			 * linearize a multi-dimensional array.
4882 			 *
4883 			 * The logic here is treating an array
4884 			 * in a struct as the following way:
4885 			 *
4886 			 * struct outer {
4887 			 *	struct inner array[2][2];
4888 			 * };
4889 			 *
4890 			 * looks like:
4891 			 *
4892 			 * struct outer {
4893 			 *	struct inner array_elem0;
4894 			 *	struct inner array_elem1;
4895 			 *	struct inner array_elem2;
4896 			 *	struct inner array_elem3;
4897 			 * };
4898 			 *
4899 			 * When accessing outer->array[1][0], it moves
4900 			 * moff to "array_elem2", set mtype to
4901 			 * "struct inner", and msize also becomes
4902 			 * sizeof(struct inner).  Then most of the
4903 			 * remaining logic will fall through without
4904 			 * caring the current member is an array or
4905 			 * not.
4906 			 *
4907 			 * Unlike mtype/msize/moff, mtrue_end does not
4908 			 * change.  The naming difference ("_true") tells
4909 			 * that it is not always corresponding to
4910 			 * the current mtype/msize/moff.
4911 			 * It is the true end of the current
4912 			 * member (i.e. array in this case).  That
4913 			 * will allow an int array to be accessed like
4914 			 * a scratch space,
4915 			 * i.e. allow access beyond the size of
4916 			 *      the array's element as long as it is
4917 			 *      within the mtrue_end boundary.
4918 			 */
4919 
4920 			/* skip empty array */
4921 			if (moff == mtrue_end)
4922 				continue;
4923 
4924 			msize /= total_nelems;
4925 			elem_idx = (off - moff) / msize;
4926 			moff += elem_idx * msize;
4927 			mtype = elem_type;
4928 			mid = elem_id;
4929 		}
4930 
4931 		/* the 'off' we're looking for is either equal to start
4932 		 * of this field or inside of this struct
4933 		 */
4934 		if (btf_type_is_struct(mtype)) {
4935 			/* our field must be inside that union or struct */
4936 			t = mtype;
4937 
4938 			/* return if the offset matches the member offset */
4939 			if (off == moff) {
4940 				*next_btf_id = mid;
4941 				return WALK_STRUCT;
4942 			}
4943 
4944 			/* adjust offset we're looking for */
4945 			off -= moff;
4946 			goto again;
4947 		}
4948 
4949 		if (btf_type_is_ptr(mtype)) {
4950 			const struct btf_type *stype;
4951 			u32 id;
4952 
4953 			if (msize != size || off != moff) {
4954 				bpf_log(log,
4955 					"cannot access ptr member %s with moff %u in struct %s with off %u size %u\n",
4956 					mname, moff, tname, off, size);
4957 				return -EACCES;
4958 			}
4959 			stype = btf_type_skip_modifiers(btf, mtype->type, &id);
4960 			if (btf_type_is_struct(stype)) {
4961 				*next_btf_id = id;
4962 				return WALK_PTR;
4963 			}
4964 		}
4965 
4966 		/* Allow more flexible access within an int as long as
4967 		 * it is within mtrue_end.
4968 		 * Since mtrue_end could be the end of an array,
4969 		 * that also allows using an array of int as a scratch
4970 		 * space. e.g. skb->cb[].
4971 		 */
4972 		if (off + size > mtrue_end) {
4973 			bpf_log(log,
4974 				"access beyond the end of member %s (mend:%u) in struct %s with off %u size %u\n",
4975 				mname, mtrue_end, tname, off, size);
4976 			return -EACCES;
4977 		}
4978 
4979 		return WALK_SCALAR;
4980 	}
4981 	bpf_log(log, "struct %s doesn't have field at offset %d\n", tname, off);
4982 	return -EINVAL;
4983 }
4984 
4985 int btf_struct_access(struct bpf_verifier_log *log, const struct btf *btf,
4986 		      const struct btf_type *t, int off, int size,
4987 		      enum bpf_access_type atype __maybe_unused,
4988 		      u32 *next_btf_id)
4989 {
4990 	int err;
4991 	u32 id;
4992 
4993 	do {
4994 		err = btf_struct_walk(log, btf, t, off, size, &id);
4995 
4996 		switch (err) {
4997 		case WALK_PTR:
4998 			/* If we found the pointer or scalar on t+off,
4999 			 * we're done.
5000 			 */
5001 			*next_btf_id = id;
5002 			return PTR_TO_BTF_ID;
5003 		case WALK_SCALAR:
5004 			return SCALAR_VALUE;
5005 		case WALK_STRUCT:
5006 			/* We found nested struct, so continue the search
5007 			 * by diving in it. At this point the offset is
5008 			 * aligned with the new type, so set it to 0.
5009 			 */
5010 			t = btf_type_by_id(btf, id);
5011 			off = 0;
5012 			break;
5013 		default:
5014 			/* It's either error or unknown return value..
5015 			 * scream and leave.
5016 			 */
5017 			if (WARN_ONCE(err > 0, "unknown btf_struct_walk return value"))
5018 				return -EINVAL;
5019 			return err;
5020 		}
5021 	} while (t);
5022 
5023 	return -EINVAL;
5024 }
5025 
5026 /* Check that two BTF types, each specified as an BTF object + id, are exactly
5027  * the same. Trivial ID check is not enough due to module BTFs, because we can
5028  * end up with two different module BTFs, but IDs point to the common type in
5029  * vmlinux BTF.
5030  */
5031 static bool btf_types_are_same(const struct btf *btf1, u32 id1,
5032 			       const struct btf *btf2, u32 id2)
5033 {
5034 	if (id1 != id2)
5035 		return false;
5036 	if (btf1 == btf2)
5037 		return true;
5038 	return btf_type_by_id(btf1, id1) == btf_type_by_id(btf2, id2);
5039 }
5040 
5041 bool btf_struct_ids_match(struct bpf_verifier_log *log,
5042 			  const struct btf *btf, u32 id, int off,
5043 			  const struct btf *need_btf, u32 need_type_id)
5044 {
5045 	const struct btf_type *type;
5046 	int err;
5047 
5048 	/* Are we already done? */
5049 	if (off == 0 && btf_types_are_same(btf, id, need_btf, need_type_id))
5050 		return true;
5051 
5052 again:
5053 	type = btf_type_by_id(btf, id);
5054 	if (!type)
5055 		return false;
5056 	err = btf_struct_walk(log, btf, type, off, 1, &id);
5057 	if (err != WALK_STRUCT)
5058 		return false;
5059 
5060 	/* We found nested struct object. If it matches
5061 	 * the requested ID, we're done. Otherwise let's
5062 	 * continue the search with offset 0 in the new
5063 	 * type.
5064 	 */
5065 	if (!btf_types_are_same(btf, id, need_btf, need_type_id)) {
5066 		off = 0;
5067 		goto again;
5068 	}
5069 
5070 	return true;
5071 }
5072 
5073 static int __get_type_size(struct btf *btf, u32 btf_id,
5074 			   const struct btf_type **bad_type)
5075 {
5076 	const struct btf_type *t;
5077 
5078 	if (!btf_id)
5079 		/* void */
5080 		return 0;
5081 	t = btf_type_by_id(btf, btf_id);
5082 	while (t && btf_type_is_modifier(t))
5083 		t = btf_type_by_id(btf, t->type);
5084 	if (!t) {
5085 		*bad_type = btf_type_by_id(btf, 0);
5086 		return -EINVAL;
5087 	}
5088 	if (btf_type_is_ptr(t))
5089 		/* kernel size of pointer. Not BPF's size of pointer*/
5090 		return sizeof(void *);
5091 	if (btf_type_is_int(t) || btf_type_is_enum(t))
5092 		return t->size;
5093 	*bad_type = t;
5094 	return -EINVAL;
5095 }
5096 
5097 int btf_distill_func_proto(struct bpf_verifier_log *log,
5098 			   struct btf *btf,
5099 			   const struct btf_type *func,
5100 			   const char *tname,
5101 			   struct btf_func_model *m)
5102 {
5103 	const struct btf_param *args;
5104 	const struct btf_type *t;
5105 	u32 i, nargs;
5106 	int ret;
5107 
5108 	if (!func) {
5109 		/* BTF function prototype doesn't match the verifier types.
5110 		 * Fall back to 5 u64 args.
5111 		 */
5112 		for (i = 0; i < 5; i++)
5113 			m->arg_size[i] = 8;
5114 		m->ret_size = 8;
5115 		m->nr_args = 5;
5116 		return 0;
5117 	}
5118 	args = (const struct btf_param *)(func + 1);
5119 	nargs = btf_type_vlen(func);
5120 	if (nargs >= MAX_BPF_FUNC_ARGS) {
5121 		bpf_log(log,
5122 			"The function %s has %d arguments. Too many.\n",
5123 			tname, nargs);
5124 		return -EINVAL;
5125 	}
5126 	ret = __get_type_size(btf, func->type, &t);
5127 	if (ret < 0) {
5128 		bpf_log(log,
5129 			"The function %s return type %s is unsupported.\n",
5130 			tname, btf_kind_str[BTF_INFO_KIND(t->info)]);
5131 		return -EINVAL;
5132 	}
5133 	m->ret_size = ret;
5134 
5135 	for (i = 0; i < nargs; i++) {
5136 		ret = __get_type_size(btf, args[i].type, &t);
5137 		if (ret < 0) {
5138 			bpf_log(log,
5139 				"The function %s arg%d type %s is unsupported.\n",
5140 				tname, i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5141 			return -EINVAL;
5142 		}
5143 		m->arg_size[i] = ret;
5144 	}
5145 	m->nr_args = nargs;
5146 	return 0;
5147 }
5148 
5149 /* Compare BTFs of two functions assuming only scalars and pointers to context.
5150  * t1 points to BTF_KIND_FUNC in btf1
5151  * t2 points to BTF_KIND_FUNC in btf2
5152  * Returns:
5153  * EINVAL - function prototype mismatch
5154  * EFAULT - verifier bug
5155  * 0 - 99% match. The last 1% is validated by the verifier.
5156  */
5157 static int btf_check_func_type_match(struct bpf_verifier_log *log,
5158 				     struct btf *btf1, const struct btf_type *t1,
5159 				     struct btf *btf2, const struct btf_type *t2)
5160 {
5161 	const struct btf_param *args1, *args2;
5162 	const char *fn1, *fn2, *s1, *s2;
5163 	u32 nargs1, nargs2, i;
5164 
5165 	fn1 = btf_name_by_offset(btf1, t1->name_off);
5166 	fn2 = btf_name_by_offset(btf2, t2->name_off);
5167 
5168 	if (btf_func_linkage(t1) != BTF_FUNC_GLOBAL) {
5169 		bpf_log(log, "%s() is not a global function\n", fn1);
5170 		return -EINVAL;
5171 	}
5172 	if (btf_func_linkage(t2) != BTF_FUNC_GLOBAL) {
5173 		bpf_log(log, "%s() is not a global function\n", fn2);
5174 		return -EINVAL;
5175 	}
5176 
5177 	t1 = btf_type_by_id(btf1, t1->type);
5178 	if (!t1 || !btf_type_is_func_proto(t1))
5179 		return -EFAULT;
5180 	t2 = btf_type_by_id(btf2, t2->type);
5181 	if (!t2 || !btf_type_is_func_proto(t2))
5182 		return -EFAULT;
5183 
5184 	args1 = (const struct btf_param *)(t1 + 1);
5185 	nargs1 = btf_type_vlen(t1);
5186 	args2 = (const struct btf_param *)(t2 + 1);
5187 	nargs2 = btf_type_vlen(t2);
5188 
5189 	if (nargs1 != nargs2) {
5190 		bpf_log(log, "%s() has %d args while %s() has %d args\n",
5191 			fn1, nargs1, fn2, nargs2);
5192 		return -EINVAL;
5193 	}
5194 
5195 	t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5196 	t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5197 	if (t1->info != t2->info) {
5198 		bpf_log(log,
5199 			"Return type %s of %s() doesn't match type %s of %s()\n",
5200 			btf_type_str(t1), fn1,
5201 			btf_type_str(t2), fn2);
5202 		return -EINVAL;
5203 	}
5204 
5205 	for (i = 0; i < nargs1; i++) {
5206 		t1 = btf_type_skip_modifiers(btf1, args1[i].type, NULL);
5207 		t2 = btf_type_skip_modifiers(btf2, args2[i].type, NULL);
5208 
5209 		if (t1->info != t2->info) {
5210 			bpf_log(log, "arg%d in %s() is %s while %s() has %s\n",
5211 				i, fn1, btf_type_str(t1),
5212 				fn2, btf_type_str(t2));
5213 			return -EINVAL;
5214 		}
5215 		if (btf_type_has_size(t1) && t1->size != t2->size) {
5216 			bpf_log(log,
5217 				"arg%d in %s() has size %d while %s() has %d\n",
5218 				i, fn1, t1->size,
5219 				fn2, t2->size);
5220 			return -EINVAL;
5221 		}
5222 
5223 		/* global functions are validated with scalars and pointers
5224 		 * to context only. And only global functions can be replaced.
5225 		 * Hence type check only those types.
5226 		 */
5227 		if (btf_type_is_int(t1) || btf_type_is_enum(t1))
5228 			continue;
5229 		if (!btf_type_is_ptr(t1)) {
5230 			bpf_log(log,
5231 				"arg%d in %s() has unrecognized type\n",
5232 				i, fn1);
5233 			return -EINVAL;
5234 		}
5235 		t1 = btf_type_skip_modifiers(btf1, t1->type, NULL);
5236 		t2 = btf_type_skip_modifiers(btf2, t2->type, NULL);
5237 		if (!btf_type_is_struct(t1)) {
5238 			bpf_log(log,
5239 				"arg%d in %s() is not a pointer to context\n",
5240 				i, fn1);
5241 			return -EINVAL;
5242 		}
5243 		if (!btf_type_is_struct(t2)) {
5244 			bpf_log(log,
5245 				"arg%d in %s() is not a pointer to context\n",
5246 				i, fn2);
5247 			return -EINVAL;
5248 		}
5249 		/* This is an optional check to make program writing easier.
5250 		 * Compare names of structs and report an error to the user.
5251 		 * btf_prepare_func_args() already checked that t2 struct
5252 		 * is a context type. btf_prepare_func_args() will check
5253 		 * later that t1 struct is a context type as well.
5254 		 */
5255 		s1 = btf_name_by_offset(btf1, t1->name_off);
5256 		s2 = btf_name_by_offset(btf2, t2->name_off);
5257 		if (strcmp(s1, s2)) {
5258 			bpf_log(log,
5259 				"arg%d %s(struct %s *) doesn't match %s(struct %s *)\n",
5260 				i, fn1, s1, fn2, s2);
5261 			return -EINVAL;
5262 		}
5263 	}
5264 	return 0;
5265 }
5266 
5267 /* Compare BTFs of given program with BTF of target program */
5268 int btf_check_type_match(struct bpf_verifier_log *log, const struct bpf_prog *prog,
5269 			 struct btf *btf2, const struct btf_type *t2)
5270 {
5271 	struct btf *btf1 = prog->aux->btf;
5272 	const struct btf_type *t1;
5273 	u32 btf_id = 0;
5274 
5275 	if (!prog->aux->func_info) {
5276 		bpf_log(log, "Program extension requires BTF\n");
5277 		return -EINVAL;
5278 	}
5279 
5280 	btf_id = prog->aux->func_info[0].type_id;
5281 	if (!btf_id)
5282 		return -EFAULT;
5283 
5284 	t1 = btf_type_by_id(btf1, btf_id);
5285 	if (!t1 || !btf_type_is_func(t1))
5286 		return -EFAULT;
5287 
5288 	return btf_check_func_type_match(log, btf1, t1, btf2, t2);
5289 }
5290 
5291 /* Compare BTF of a function with given bpf_reg_state.
5292  * Returns:
5293  * EFAULT - there is a verifier bug. Abort verification.
5294  * EINVAL - there is a type mismatch or BTF is not available.
5295  * 0 - BTF matches with what bpf_reg_state expects.
5296  * Only PTR_TO_CTX and SCALAR_VALUE states are recognized.
5297  */
5298 int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog,
5299 			     struct bpf_reg_state *reg)
5300 {
5301 	struct bpf_verifier_log *log = &env->log;
5302 	struct bpf_prog *prog = env->prog;
5303 	struct btf *btf = prog->aux->btf;
5304 	const struct btf_param *args;
5305 	const struct btf_type *t;
5306 	u32 i, nargs, btf_id;
5307 	const char *tname;
5308 
5309 	if (!prog->aux->func_info)
5310 		return -EINVAL;
5311 
5312 	btf_id = prog->aux->func_info[subprog].type_id;
5313 	if (!btf_id)
5314 		return -EFAULT;
5315 
5316 	if (prog->aux->func_info_aux[subprog].unreliable)
5317 		return -EINVAL;
5318 
5319 	t = btf_type_by_id(btf, btf_id);
5320 	if (!t || !btf_type_is_func(t)) {
5321 		/* These checks were already done by the verifier while loading
5322 		 * struct bpf_func_info
5323 		 */
5324 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
5325 			subprog);
5326 		return -EFAULT;
5327 	}
5328 	tname = btf_name_by_offset(btf, t->name_off);
5329 
5330 	t = btf_type_by_id(btf, t->type);
5331 	if (!t || !btf_type_is_func_proto(t)) {
5332 		bpf_log(log, "Invalid BTF of func %s\n", tname);
5333 		return -EFAULT;
5334 	}
5335 	args = (const struct btf_param *)(t + 1);
5336 	nargs = btf_type_vlen(t);
5337 	if (nargs > 5) {
5338 		bpf_log(log, "Function %s has %d > 5 args\n", tname, nargs);
5339 		goto out;
5340 	}
5341 	/* check that BTF function arguments match actual types that the
5342 	 * verifier sees.
5343 	 */
5344 	for (i = 0; i < nargs; i++) {
5345 		t = btf_type_by_id(btf, args[i].type);
5346 		while (btf_type_is_modifier(t))
5347 			t = btf_type_by_id(btf, t->type);
5348 		if (btf_type_is_int(t) || btf_type_is_enum(t)) {
5349 			if (reg[i + 1].type == SCALAR_VALUE)
5350 				continue;
5351 			bpf_log(log, "R%d is not a scalar\n", i + 1);
5352 			goto out;
5353 		}
5354 		if (btf_type_is_ptr(t)) {
5355 			if (reg[i + 1].type == SCALAR_VALUE) {
5356 				bpf_log(log, "R%d is not a pointer\n", i + 1);
5357 				goto out;
5358 			}
5359 			/* If function expects ctx type in BTF check that caller
5360 			 * is passing PTR_TO_CTX.
5361 			 */
5362 			if (btf_get_prog_ctx_type(log, btf, t, prog->type, i)) {
5363 				if (reg[i + 1].type != PTR_TO_CTX) {
5364 					bpf_log(log,
5365 						"arg#%d expected pointer to ctx, but got %s\n",
5366 						i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5367 					goto out;
5368 				}
5369 				if (check_ctx_reg(env, &reg[i + 1], i + 1))
5370 					goto out;
5371 				continue;
5372 			}
5373 		}
5374 		bpf_log(log, "Unrecognized arg#%d type %s\n",
5375 			i, btf_kind_str[BTF_INFO_KIND(t->info)]);
5376 		goto out;
5377 	}
5378 	return 0;
5379 out:
5380 	/* Compiler optimizations can remove arguments from static functions
5381 	 * or mismatched type can be passed into a global function.
5382 	 * In such cases mark the function as unreliable from BTF point of view.
5383 	 */
5384 	prog->aux->func_info_aux[subprog].unreliable = true;
5385 	return -EINVAL;
5386 }
5387 
5388 /* Convert BTF of a function into bpf_reg_state if possible
5389  * Returns:
5390  * EFAULT - there is a verifier bug. Abort verification.
5391  * EINVAL - cannot convert BTF.
5392  * 0 - Successfully converted BTF into bpf_reg_state
5393  * (either PTR_TO_CTX or SCALAR_VALUE).
5394  */
5395 int btf_prepare_func_args(struct bpf_verifier_env *env, int subprog,
5396 			  struct bpf_reg_state *reg)
5397 {
5398 	struct bpf_verifier_log *log = &env->log;
5399 	struct bpf_prog *prog = env->prog;
5400 	enum bpf_prog_type prog_type = prog->type;
5401 	struct btf *btf = prog->aux->btf;
5402 	const struct btf_param *args;
5403 	const struct btf_type *t;
5404 	u32 i, nargs, btf_id;
5405 	const char *tname;
5406 
5407 	if (!prog->aux->func_info ||
5408 	    prog->aux->func_info_aux[subprog].linkage != BTF_FUNC_GLOBAL) {
5409 		bpf_log(log, "Verifier bug\n");
5410 		return -EFAULT;
5411 	}
5412 
5413 	btf_id = prog->aux->func_info[subprog].type_id;
5414 	if (!btf_id) {
5415 		bpf_log(log, "Global functions need valid BTF\n");
5416 		return -EFAULT;
5417 	}
5418 
5419 	t = btf_type_by_id(btf, btf_id);
5420 	if (!t || !btf_type_is_func(t)) {
5421 		/* These checks were already done by the verifier while loading
5422 		 * struct bpf_func_info
5423 		 */
5424 		bpf_log(log, "BTF of func#%d doesn't point to KIND_FUNC\n",
5425 			subprog);
5426 		return -EFAULT;
5427 	}
5428 	tname = btf_name_by_offset(btf, t->name_off);
5429 
5430 	if (log->level & BPF_LOG_LEVEL)
5431 		bpf_log(log, "Validating %s() func#%d...\n",
5432 			tname, subprog);
5433 
5434 	if (prog->aux->func_info_aux[subprog].unreliable) {
5435 		bpf_log(log, "Verifier bug in function %s()\n", tname);
5436 		return -EFAULT;
5437 	}
5438 	if (prog_type == BPF_PROG_TYPE_EXT)
5439 		prog_type = prog->aux->dst_prog->type;
5440 
5441 	t = btf_type_by_id(btf, t->type);
5442 	if (!t || !btf_type_is_func_proto(t)) {
5443 		bpf_log(log, "Invalid type of function %s()\n", tname);
5444 		return -EFAULT;
5445 	}
5446 	args = (const struct btf_param *)(t + 1);
5447 	nargs = btf_type_vlen(t);
5448 	if (nargs > 5) {
5449 		bpf_log(log, "Global function %s() with %d > 5 args. Buggy compiler.\n",
5450 			tname, nargs);
5451 		return -EINVAL;
5452 	}
5453 	/* check that function returns int */
5454 	t = btf_type_by_id(btf, t->type);
5455 	while (btf_type_is_modifier(t))
5456 		t = btf_type_by_id(btf, t->type);
5457 	if (!btf_type_is_int(t) && !btf_type_is_enum(t)) {
5458 		bpf_log(log,
5459 			"Global function %s() doesn't return scalar. Only those are supported.\n",
5460 			tname);
5461 		return -EINVAL;
5462 	}
5463 	/* Convert BTF function arguments into verifier types.
5464 	 * Only PTR_TO_CTX and SCALAR are supported atm.
5465 	 */
5466 	for (i = 0; i < nargs; i++) {
5467 		t = btf_type_by_id(btf, args[i].type);
5468 		while (btf_type_is_modifier(t))
5469 			t = btf_type_by_id(btf, t->type);
5470 		if (btf_type_is_int(t) || btf_type_is_enum(t)) {
5471 			reg[i + 1].type = SCALAR_VALUE;
5472 			continue;
5473 		}
5474 		if (btf_type_is_ptr(t) &&
5475 		    btf_get_prog_ctx_type(log, btf, t, prog_type, i)) {
5476 			reg[i + 1].type = PTR_TO_CTX;
5477 			continue;
5478 		}
5479 		bpf_log(log, "Arg#%d type %s in %s() is not supported yet.\n",
5480 			i, btf_kind_str[BTF_INFO_KIND(t->info)], tname);
5481 		return -EINVAL;
5482 	}
5483 	return 0;
5484 }
5485 
5486 static void btf_type_show(const struct btf *btf, u32 type_id, void *obj,
5487 			  struct btf_show *show)
5488 {
5489 	const struct btf_type *t = btf_type_by_id(btf, type_id);
5490 
5491 	show->btf = btf;
5492 	memset(&show->state, 0, sizeof(show->state));
5493 	memset(&show->obj, 0, sizeof(show->obj));
5494 
5495 	btf_type_ops(t)->show(btf, t, type_id, obj, 0, show);
5496 }
5497 
5498 static void btf_seq_show(struct btf_show *show, const char *fmt,
5499 			 va_list args)
5500 {
5501 	seq_vprintf((struct seq_file *)show->target, fmt, args);
5502 }
5503 
5504 int btf_type_seq_show_flags(const struct btf *btf, u32 type_id,
5505 			    void *obj, struct seq_file *m, u64 flags)
5506 {
5507 	struct btf_show sseq;
5508 
5509 	sseq.target = m;
5510 	sseq.showfn = btf_seq_show;
5511 	sseq.flags = flags;
5512 
5513 	btf_type_show(btf, type_id, obj, &sseq);
5514 
5515 	return sseq.state.status;
5516 }
5517 
5518 void btf_type_seq_show(const struct btf *btf, u32 type_id, void *obj,
5519 		       struct seq_file *m)
5520 {
5521 	(void) btf_type_seq_show_flags(btf, type_id, obj, m,
5522 				       BTF_SHOW_NONAME | BTF_SHOW_COMPACT |
5523 				       BTF_SHOW_ZERO | BTF_SHOW_UNSAFE);
5524 }
5525 
5526 struct btf_show_snprintf {
5527 	struct btf_show show;
5528 	int len_left;		/* space left in string */
5529 	int len;		/* length we would have written */
5530 };
5531 
5532 static void btf_snprintf_show(struct btf_show *show, const char *fmt,
5533 			      va_list args)
5534 {
5535 	struct btf_show_snprintf *ssnprintf = (struct btf_show_snprintf *)show;
5536 	int len;
5537 
5538 	len = vsnprintf(show->target, ssnprintf->len_left, fmt, args);
5539 
5540 	if (len < 0) {
5541 		ssnprintf->len_left = 0;
5542 		ssnprintf->len = len;
5543 	} else if (len > ssnprintf->len_left) {
5544 		/* no space, drive on to get length we would have written */
5545 		ssnprintf->len_left = 0;
5546 		ssnprintf->len += len;
5547 	} else {
5548 		ssnprintf->len_left -= len;
5549 		ssnprintf->len += len;
5550 		show->target += len;
5551 	}
5552 }
5553 
5554 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
5555 			   char *buf, int len, u64 flags)
5556 {
5557 	struct btf_show_snprintf ssnprintf;
5558 
5559 	ssnprintf.show.target = buf;
5560 	ssnprintf.show.flags = flags;
5561 	ssnprintf.show.showfn = btf_snprintf_show;
5562 	ssnprintf.len_left = len;
5563 	ssnprintf.len = 0;
5564 
5565 	btf_type_show(btf, type_id, obj, (struct btf_show *)&ssnprintf);
5566 
5567 	/* If we encontered an error, return it. */
5568 	if (ssnprintf.show.state.status)
5569 		return ssnprintf.show.state.status;
5570 
5571 	/* Otherwise return length we would have written */
5572 	return ssnprintf.len;
5573 }
5574 
5575 #ifdef CONFIG_PROC_FS
5576 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
5577 {
5578 	const struct btf *btf = filp->private_data;
5579 
5580 	seq_printf(m, "btf_id:\t%u\n", btf->id);
5581 }
5582 #endif
5583 
5584 static int btf_release(struct inode *inode, struct file *filp)
5585 {
5586 	btf_put(filp->private_data);
5587 	return 0;
5588 }
5589 
5590 const struct file_operations btf_fops = {
5591 #ifdef CONFIG_PROC_FS
5592 	.show_fdinfo	= bpf_btf_show_fdinfo,
5593 #endif
5594 	.release	= btf_release,
5595 };
5596 
5597 static int __btf_new_fd(struct btf *btf)
5598 {
5599 	return anon_inode_getfd("btf", &btf_fops, btf, O_RDONLY | O_CLOEXEC);
5600 }
5601 
5602 int btf_new_fd(const union bpf_attr *attr)
5603 {
5604 	struct btf *btf;
5605 	int ret;
5606 
5607 	btf = btf_parse(u64_to_user_ptr(attr->btf),
5608 			attr->btf_size, attr->btf_log_level,
5609 			u64_to_user_ptr(attr->btf_log_buf),
5610 			attr->btf_log_size);
5611 	if (IS_ERR(btf))
5612 		return PTR_ERR(btf);
5613 
5614 	ret = btf_alloc_id(btf);
5615 	if (ret) {
5616 		btf_free(btf);
5617 		return ret;
5618 	}
5619 
5620 	/*
5621 	 * The BTF ID is published to the userspace.
5622 	 * All BTF free must go through call_rcu() from
5623 	 * now on (i.e. free by calling btf_put()).
5624 	 */
5625 
5626 	ret = __btf_new_fd(btf);
5627 	if (ret < 0)
5628 		btf_put(btf);
5629 
5630 	return ret;
5631 }
5632 
5633 struct btf *btf_get_by_fd(int fd)
5634 {
5635 	struct btf *btf;
5636 	struct fd f;
5637 
5638 	f = fdget(fd);
5639 
5640 	if (!f.file)
5641 		return ERR_PTR(-EBADF);
5642 
5643 	if (f.file->f_op != &btf_fops) {
5644 		fdput(f);
5645 		return ERR_PTR(-EINVAL);
5646 	}
5647 
5648 	btf = f.file->private_data;
5649 	refcount_inc(&btf->refcnt);
5650 	fdput(f);
5651 
5652 	return btf;
5653 }
5654 
5655 int btf_get_info_by_fd(const struct btf *btf,
5656 		       const union bpf_attr *attr,
5657 		       union bpf_attr __user *uattr)
5658 {
5659 	struct bpf_btf_info __user *uinfo;
5660 	struct bpf_btf_info info;
5661 	u32 info_copy, btf_copy;
5662 	void __user *ubtf;
5663 	char __user *uname;
5664 	u32 uinfo_len, uname_len, name_len;
5665 	int ret = 0;
5666 
5667 	uinfo = u64_to_user_ptr(attr->info.info);
5668 	uinfo_len = attr->info.info_len;
5669 
5670 	info_copy = min_t(u32, uinfo_len, sizeof(info));
5671 	memset(&info, 0, sizeof(info));
5672 	if (copy_from_user(&info, uinfo, info_copy))
5673 		return -EFAULT;
5674 
5675 	info.id = btf->id;
5676 	ubtf = u64_to_user_ptr(info.btf);
5677 	btf_copy = min_t(u32, btf->data_size, info.btf_size);
5678 	if (copy_to_user(ubtf, btf->data, btf_copy))
5679 		return -EFAULT;
5680 	info.btf_size = btf->data_size;
5681 
5682 	info.kernel_btf = btf->kernel_btf;
5683 
5684 	uname = u64_to_user_ptr(info.name);
5685 	uname_len = info.name_len;
5686 	if (!uname ^ !uname_len)
5687 		return -EINVAL;
5688 
5689 	name_len = strlen(btf->name);
5690 	info.name_len = name_len;
5691 
5692 	if (uname) {
5693 		if (uname_len >= name_len + 1) {
5694 			if (copy_to_user(uname, btf->name, name_len + 1))
5695 				return -EFAULT;
5696 		} else {
5697 			char zero = '\0';
5698 
5699 			if (copy_to_user(uname, btf->name, uname_len - 1))
5700 				return -EFAULT;
5701 			if (put_user(zero, uname + uname_len - 1))
5702 				return -EFAULT;
5703 			/* let user-space know about too short buffer */
5704 			ret = -ENOSPC;
5705 		}
5706 	}
5707 
5708 	if (copy_to_user(uinfo, &info, info_copy) ||
5709 	    put_user(info_copy, &uattr->info.info_len))
5710 		return -EFAULT;
5711 
5712 	return ret;
5713 }
5714 
5715 int btf_get_fd_by_id(u32 id)
5716 {
5717 	struct btf *btf;
5718 	int fd;
5719 
5720 	rcu_read_lock();
5721 	btf = idr_find(&btf_idr, id);
5722 	if (!btf || !refcount_inc_not_zero(&btf->refcnt))
5723 		btf = ERR_PTR(-ENOENT);
5724 	rcu_read_unlock();
5725 
5726 	if (IS_ERR(btf))
5727 		return PTR_ERR(btf);
5728 
5729 	fd = __btf_new_fd(btf);
5730 	if (fd < 0)
5731 		btf_put(btf);
5732 
5733 	return fd;
5734 }
5735 
5736 u32 btf_obj_id(const struct btf *btf)
5737 {
5738 	return btf->id;
5739 }
5740 
5741 bool btf_is_kernel(const struct btf *btf)
5742 {
5743 	return btf->kernel_btf;
5744 }
5745 
5746 static int btf_id_cmp_func(const void *a, const void *b)
5747 {
5748 	const int *pa = a, *pb = b;
5749 
5750 	return *pa - *pb;
5751 }
5752 
5753 bool btf_id_set_contains(const struct btf_id_set *set, u32 id)
5754 {
5755 	return bsearch(&id, set->ids, set->cnt, sizeof(u32), btf_id_cmp_func) != NULL;
5756 }
5757 
5758 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
5759 struct btf_module {
5760 	struct list_head list;
5761 	struct module *module;
5762 	struct btf *btf;
5763 	struct bin_attribute *sysfs_attr;
5764 };
5765 
5766 static LIST_HEAD(btf_modules);
5767 static DEFINE_MUTEX(btf_module_mutex);
5768 
5769 static ssize_t
5770 btf_module_read(struct file *file, struct kobject *kobj,
5771 		struct bin_attribute *bin_attr,
5772 		char *buf, loff_t off, size_t len)
5773 {
5774 	const struct btf *btf = bin_attr->private;
5775 
5776 	memcpy(buf, btf->data + off, len);
5777 	return len;
5778 }
5779 
5780 static int btf_module_notify(struct notifier_block *nb, unsigned long op,
5781 			     void *module)
5782 {
5783 	struct btf_module *btf_mod, *tmp;
5784 	struct module *mod = module;
5785 	struct btf *btf;
5786 	int err = 0;
5787 
5788 	if (mod->btf_data_size == 0 ||
5789 	    (op != MODULE_STATE_COMING && op != MODULE_STATE_GOING))
5790 		goto out;
5791 
5792 	switch (op) {
5793 	case MODULE_STATE_COMING:
5794 		btf_mod = kzalloc(sizeof(*btf_mod), GFP_KERNEL);
5795 		if (!btf_mod) {
5796 			err = -ENOMEM;
5797 			goto out;
5798 		}
5799 		btf = btf_parse_module(mod->name, mod->btf_data, mod->btf_data_size);
5800 		if (IS_ERR(btf)) {
5801 			pr_warn("failed to validate module [%s] BTF: %ld\n",
5802 				mod->name, PTR_ERR(btf));
5803 			kfree(btf_mod);
5804 			err = PTR_ERR(btf);
5805 			goto out;
5806 		}
5807 		err = btf_alloc_id(btf);
5808 		if (err) {
5809 			btf_free(btf);
5810 			kfree(btf_mod);
5811 			goto out;
5812 		}
5813 
5814 		mutex_lock(&btf_module_mutex);
5815 		btf_mod->module = module;
5816 		btf_mod->btf = btf;
5817 		list_add(&btf_mod->list, &btf_modules);
5818 		mutex_unlock(&btf_module_mutex);
5819 
5820 		if (IS_ENABLED(CONFIG_SYSFS)) {
5821 			struct bin_attribute *attr;
5822 
5823 			attr = kzalloc(sizeof(*attr), GFP_KERNEL);
5824 			if (!attr)
5825 				goto out;
5826 
5827 			sysfs_bin_attr_init(attr);
5828 			attr->attr.name = btf->name;
5829 			attr->attr.mode = 0444;
5830 			attr->size = btf->data_size;
5831 			attr->private = btf;
5832 			attr->read = btf_module_read;
5833 
5834 			err = sysfs_create_bin_file(btf_kobj, attr);
5835 			if (err) {
5836 				pr_warn("failed to register module [%s] BTF in sysfs: %d\n",
5837 					mod->name, err);
5838 				kfree(attr);
5839 				err = 0;
5840 				goto out;
5841 			}
5842 
5843 			btf_mod->sysfs_attr = attr;
5844 		}
5845 
5846 		break;
5847 	case MODULE_STATE_GOING:
5848 		mutex_lock(&btf_module_mutex);
5849 		list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
5850 			if (btf_mod->module != module)
5851 				continue;
5852 
5853 			list_del(&btf_mod->list);
5854 			if (btf_mod->sysfs_attr)
5855 				sysfs_remove_bin_file(btf_kobj, btf_mod->sysfs_attr);
5856 			btf_put(btf_mod->btf);
5857 			kfree(btf_mod->sysfs_attr);
5858 			kfree(btf_mod);
5859 			break;
5860 		}
5861 		mutex_unlock(&btf_module_mutex);
5862 		break;
5863 	}
5864 out:
5865 	return notifier_from_errno(err);
5866 }
5867 
5868 static struct notifier_block btf_module_nb = {
5869 	.notifier_call = btf_module_notify,
5870 };
5871 
5872 static int __init btf_module_init(void)
5873 {
5874 	register_module_notifier(&btf_module_nb);
5875 	return 0;
5876 }
5877 
5878 fs_initcall(btf_module_init);
5879 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
5880