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