diff mbox series

[RFC,bpf-next,2/4] bpf: support BPF ksym variables in kernel modules

Message ID 20201211042734.730147-3-andrii@kernel.org
State Superseded
Headers show
Series Support kernel module ksym variables | expand

Commit Message

Andrii Nakryiko Dec. 11, 2020, 4:27 a.m. UTC
Add support for directly accessing kernel module variables from BPF programs
using special ldimm64 instructions. This functionality builds upon vmlinux
ksym support, but extends ldimm64 with src_reg=BPF_PSEUDO_BTF_ID to allow
specifying kernel module BTF's FD in insn[1].imm field.

During BPF program load time, verifier will resolve FD to BTF object and will
take reference on BTF object itself and, for module BTFs, corresponding module
as well, to make sure it won't be unloaded from under running BPF program. The
mechanism used is similar to how bpf_prog keeps track of used bpf_maps.

Better naming suggestions for struct btf_mod_pair is greatly appreciated.

One interesting change is also in how per-CPU variable is determined. The
logic is to find .data..percpu data section in provided BTF, but both vmlinux
and module each have their own .data..percpu entries in BTF. So for module's
case, the search for DATASEC record needs to look at only module's added BTF
types. This is implemented with custom search function.

Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
---
 include/linux/bpf.h          |   9 +++
 include/linux/bpf_verifier.h |   3 +
 include/linux/btf.h          |   3 +
 kernel/bpf/btf.c             |  31 +++++++-
 kernel/bpf/core.c            |  23 ++++++
 kernel/bpf/verifier.c        | 149 ++++++++++++++++++++++++++++-------
 6 files changed, 188 insertions(+), 30 deletions(-)

Comments

Andrii Nakryiko Dec. 11, 2020, 10:15 p.m. UTC | #1
On Fri, Dec 11, 2020 at 1:27 PM Alexei Starovoitov
<alexei.starovoitov@gmail.com> wrote:
>
> On Thu, Dec 10, 2020 at 08:27:32PM -0800, Andrii Nakryiko wrote:
> > During BPF program load time, verifier will resolve FD to BTF object and will
> > take reference on BTF object itself and, for module BTFs, corresponding module
> > as well, to make sure it won't be unloaded from under running BPF program. The
> > mechanism used is similar to how bpf_prog keeps track of used bpf_maps.
> ...
> > +
> > +     /* if we reference variables from kernel module, bump its refcount */
> > +     if (btf_is_module(btf)) {
> > +             btf_mod->module = btf_try_get_module(btf);
>
> Is it necessary to refcnt the module? Correct me if I'm wrong, but
> for module's BTF we register a notifier. Then the module can be rmmod-ed
> at any time and we will do btf_put() for corresponding BTF, but that BTF may
> stay around because bpftool or something is looking at it.

Correct, BTF object itself doesn't take a refcnt on module.

> Similarly when prog is attached to raw_tp in a module we currently do try_module_get(),
> but is it really necessary ? When bpf is attached to a netdev the netdev can
> be removed and the link will be dangling. May be it makes sense to do the same
> with modules?  The raw_tp can become dangling after rmmod and the prog won't be

So for raw_tp it's not the case today. I tested, I attached raw_tp,
kept triggering it in a loop, and tried to rmmod bpf_testmod. It
failed, because raw tracepoint takes refcnt on module. rmmod -f
bpf_testmod also didn't work, but it's because my kernel wasn't built
with force-unload enabled for modules. But force-unload is an entirely
different matter and it's inherently dangerous to do, it can crash and
corrupt anything in the kernel.

> executed anymore. So hard coded address of a per-cpu var in a ksym will
> be pointing to freed mod memory after rmmod, but that's ok, since that prog will
> never execute.

Not so fast :) Indeed, if somehow module gets unloaded while we keep
BPF program loaded, we'll point to unallocated memory **OR** to a
memory re-used for something else. That's bad. Nothing will crash even
if it's unmapped memory (due to bpf_probe_read semantics), but we will
potentially be reading some garbage (not zeroes), if some other module
re-uses that per-CPU memory.

As for the BPF program won't be triggered. That's not true in general,
as you mention yourself below.

> On the other side if we envision a bpf prog attaching to a vmlinux function
> and accessing per-cpu or normal ksym in some module it would need to inc refcnt
> of that module, since we won't be able to guarantee that this prog will
> not execute any more. So we cannot allow dangling memory addresses.

That's what my new selftest is doing actually. It's a generic
sys_enter raw_tp, which doesn't attach to the module, but it does read
module's per-CPU variable. So I actually ran a test before posting. I
successfully unloaded bpf_testmod, but kept running the prog. And it
kept returning *correct* per-CPU value. Most probably due to per-CPU
memory not unmapped and not yet reused for something else. But it's a
really nasty and surprising situation.

Keep in mind, also, that whenever BPF program declares per-cpu
variable extern, it doesn't know or care whether it will get resolved
to built-in vmlinux per-CPU variable or module per-CPU variable.
Restricting attachment to only module-provided hooks is both tedious
and might be quite surprising sometimes, seems not worth the pain.

> If latter is what we want to allow then we probably need a test case for it and
> document the reasons for keeping modules pinned while progs access their data.
> Since such pinning behavior is different from other bpf attaching cases where
> underlying objects (like netdev and cgroup) can go away.

See above, that's already the case for module tracepoints.

So in summary, I think we should take a refcnt on module, as that's
already the case for stuff like raw_tp. I can add more comments to
make this clear, of course.
Alexei Starovoitov Dec. 12, 2020, 1:52 a.m. UTC | #2
On Fri, Dec 11, 2020 at 02:15:28PM -0800, Andrii Nakryiko wrote:
> On Fri, Dec 11, 2020 at 1:27 PM Alexei Starovoitov

> <alexei.starovoitov@gmail.com> wrote:

> >

> > On Thu, Dec 10, 2020 at 08:27:32PM -0800, Andrii Nakryiko wrote:

> > > During BPF program load time, verifier will resolve FD to BTF object and will

> > > take reference on BTF object itself and, for module BTFs, corresponding module

> > > as well, to make sure it won't be unloaded from under running BPF program. The

> > > mechanism used is similar to how bpf_prog keeps track of used bpf_maps.

> > ...

> > > +

> > > +     /* if we reference variables from kernel module, bump its refcount */

> > > +     if (btf_is_module(btf)) {

> > > +             btf_mod->module = btf_try_get_module(btf);

> >

> > Is it necessary to refcnt the module? Correct me if I'm wrong, but

> > for module's BTF we register a notifier. Then the module can be rmmod-ed

> > at any time and we will do btf_put() for corresponding BTF, but that BTF may

> > stay around because bpftool or something is looking at it.

> 

> Correct, BTF object itself doesn't take a refcnt on module.

> 

> > Similarly when prog is attached to raw_tp in a module we currently do try_module_get(),

> > but is it really necessary ? When bpf is attached to a netdev the netdev can

> > be removed and the link will be dangling. May be it makes sense to do the same

> > with modules?  The raw_tp can become dangling after rmmod and the prog won't be

> 

> So for raw_tp it's not the case today. I tested, I attached raw_tp,

> kept triggering it in a loop, and tried to rmmod bpf_testmod. It

> failed, because raw tracepoint takes refcnt on module. rmmod -f


Right. I meant that we can change that behavior if it would make sense to do so.

> bpf_testmod also didn't work, but it's because my kernel wasn't built

> with force-unload enabled for modules. But force-unload is an entirely

> different matter and it's inherently dangerous to do, it can crash and

> corrupt anything in the kernel.

> 

> > executed anymore. So hard coded address of a per-cpu var in a ksym will

> > be pointing to freed mod memory after rmmod, but that's ok, since that prog will

> > never execute.

> 

> Not so fast :) Indeed, if somehow module gets unloaded while we keep

> BPF program loaded, we'll point to unallocated memory **OR** to a

> memory re-used for something else. That's bad. Nothing will crash even

> if it's unmapped memory (due to bpf_probe_read semantics), but we will

> potentially be reading some garbage (not zeroes), if some other module

> re-uses that per-CPU memory.

> 

> As for the BPF program won't be triggered. That's not true in general,

> as you mention yourself below.

> 

> > On the other side if we envision a bpf prog attaching to a vmlinux function

> > and accessing per-cpu or normal ksym in some module it would need to inc refcnt

> > of that module, since we won't be able to guarantee that this prog will

> > not execute any more. So we cannot allow dangling memory addresses.

> 

> That's what my new selftest is doing actually. It's a generic

> sys_enter raw_tp, which doesn't attach to the module, but it does read

> module's per-CPU variable. 


Got it. I see that now.

> So I actually ran a test before posting. I

> successfully unloaded bpf_testmod, but kept running the prog. And it

> kept returning *correct* per-CPU value. Most probably due to per-CPU

> memory not unmapped and not yet reused for something else. But it's a

> really nasty and surprising situation.


you mean you managed to unload early during development before
you've introduced refcnting of modules?

> Keep in mind, also, that whenever BPF program declares per-cpu

> variable extern, it doesn't know or care whether it will get resolved

> to built-in vmlinux per-CPU variable or module per-CPU variable.

> Restricting attachment to only module-provided hooks is both tedious

> and might be quite surprising sometimes, seems not worth the pain.

> 

> > If latter is what we want to allow then we probably need a test case for it and

> > document the reasons for keeping modules pinned while progs access their data.

> > Since such pinning behavior is different from other bpf attaching cases where

> > underlying objects (like netdev and cgroup) can go away.

> 

> See above, that's already the case for module tracepoints.

> 

> So in summary, I think we should take a refcnt on module, as that's

> already the case for stuff like raw_tp. I can add more comments to

> make this clear, of course.


ok. agreed.

Regarding fd+id in upper/lower 32-bit of ld_imm64...
That works for ksyms because at that end the pair is converted to single
address that fits into ld_imm64. That won't work for Alan's case
where btf_obj pointer and btf_id are two values (64-bit and 32-bit).
So api-wise it's fine here, but cannot adopt the same idea everywhere.

re: patch 4
Please add non-percpu var to the test. Just for completeness.
The pair fd+id should be enough to disambiguate, right?

re: patch 1.
Instead of copy paste that hack please convert it to sys_membarrier(MEMBARRIER_CMD_GLOBAL).

The rest looks good to me.
Andrii Nakryiko Dec. 12, 2020, 5:23 a.m. UTC | #3
On Fri, Dec 11, 2020 at 5:52 PM Alexei Starovoitov
<alexei.starovoitov@gmail.com> wrote:
>

> On Fri, Dec 11, 2020 at 02:15:28PM -0800, Andrii Nakryiko wrote:

> > On Fri, Dec 11, 2020 at 1:27 PM Alexei Starovoitov

> > <alexei.starovoitov@gmail.com> wrote:

> > >

> > > On Thu, Dec 10, 2020 at 08:27:32PM -0800, Andrii Nakryiko wrote:

> > > > During BPF program load time, verifier will resolve FD to BTF object and will

> > > > take reference on BTF object itself and, for module BTFs, corresponding module

> > > > as well, to make sure it won't be unloaded from under running BPF program. The

> > > > mechanism used is similar to how bpf_prog keeps track of used bpf_maps.

> > > ...

> > > > +

> > > > +     /* if we reference variables from kernel module, bump its refcount */

> > > > +     if (btf_is_module(btf)) {

> > > > +             btf_mod->module = btf_try_get_module(btf);

> > >

> > > Is it necessary to refcnt the module? Correct me if I'm wrong, but

> > > for module's BTF we register a notifier. Then the module can be rmmod-ed

> > > at any time and we will do btf_put() for corresponding BTF, but that BTF may

> > > stay around because bpftool or something is looking at it.

> >

> > Correct, BTF object itself doesn't take a refcnt on module.

> >

> > > Similarly when prog is attached to raw_tp in a module we currently do try_module_get(),

> > > but is it really necessary ? When bpf is attached to a netdev the netdev can

> > > be removed and the link will be dangling. May be it makes sense to do the same

> > > with modules?  The raw_tp can become dangling after rmmod and the prog won't be

> >

> > So for raw_tp it's not the case today. I tested, I attached raw_tp,

> > kept triggering it in a loop, and tried to rmmod bpf_testmod. It

> > failed, because raw tracepoint takes refcnt on module. rmmod -f

>

> Right. I meant that we can change that behavior if it would make sense to do so.


Oh, ok, yeah, I guess we can. But given it's been like that for a
while and no one complained, might as well leave it as is for now.

>

> > bpf_testmod also didn't work, but it's because my kernel wasn't built

> > with force-unload enabled for modules. But force-unload is an entirely

> > different matter and it's inherently dangerous to do, it can crash and

> > corrupt anything in the kernel.

> >

> > > executed anymore. So hard coded address of a per-cpu var in a ksym will

> > > be pointing to freed mod memory after rmmod, but that's ok, since that prog will

> > > never execute.

> >

> > Not so fast :) Indeed, if somehow module gets unloaded while we keep

> > BPF program loaded, we'll point to unallocated memory **OR** to a

> > memory re-used for something else. That's bad. Nothing will crash even

> > if it's unmapped memory (due to bpf_probe_read semantics), but we will

> > potentially be reading some garbage (not zeroes), if some other module

> > re-uses that per-CPU memory.

> >

> > As for the BPF program won't be triggered. That's not true in general,

> > as you mention yourself below.

> >

> > > On the other side if we envision a bpf prog attaching to a vmlinux function

> > > and accessing per-cpu or normal ksym in some module it would need to inc refcnt

> > > of that module, since we won't be able to guarantee that this prog will

> > > not execute any more. So we cannot allow dangling memory addresses.

> >

> > That's what my new selftest is doing actually. It's a generic

> > sys_enter raw_tp, which doesn't attach to the module, but it does read

> > module's per-CPU variable.

>

> Got it. I see that now.

>

> > So I actually ran a test before posting. I

> > successfully unloaded bpf_testmod, but kept running the prog. And it

> > kept returning *correct* per-CPU value. Most probably due to per-CPU

> > memory not unmapped and not yet reused for something else. But it's a

> > really nasty and surprising situation.

>

> you mean you managed to unload early during development before

> you've introduced refcnting of modules?


Yep, exactly.

>

> > Keep in mind, also, that whenever BPF program declares per-cpu

> > variable extern, it doesn't know or care whether it will get resolved

> > to built-in vmlinux per-CPU variable or module per-CPU variable.

> > Restricting attachment to only module-provided hooks is both tedious

> > and might be quite surprising sometimes, seems not worth the pain.

> >

> > > If latter is what we want to allow then we probably need a test case for it and

> > > document the reasons for keeping modules pinned while progs access their data.

> > > Since such pinning behavior is different from other bpf attaching cases where

> > > underlying objects (like netdev and cgroup) can go away.

> >

> > See above, that's already the case for module tracepoints.

> >

> > So in summary, I think we should take a refcnt on module, as that's

> > already the case for stuff like raw_tp. I can add more comments to

> > make this clear, of course.

>

> ok. agreed.

>

> Regarding fd+id in upper/lower 32-bit of ld_imm64...

> That works for ksyms because at that end the pair is converted to single

> address that fits into ld_imm64. That won't work for Alan's case

> where btf_obj pointer and btf_id are two values (64-bit and 32-bit).

> So api-wise it's fine here, but cannot adopt the same idea everywhere.


Right, won't work for Alan, but not because of ldimm64 not having
space for pointer and u32. There is bpf_insn_aux, which can store
whatever extra needs to be stored, if necessary.

But for Alan's case, because we want runtime lookup of btf obj + btf
id, the approach has to be different. We might do something like
sockmap, but for BPF types. I.e., user-space writes btf fd + btf id,
but internally we take BTF obj refcnt and store struct btf * and btf
type ID. On read we get BTF object ID + BTF type ID, for example.
WDYT?


>

> re: patch 4

> Please add non-percpu var to the test. Just for completeness.

> The pair fd+id should be enough to disambiguate, right?


Right, kernel detects per-CPU vs non-per-CPU on its own from the BTF
info. The problem is that pahole doesn't generate BTF for non-per-CPU
variables, so it's really impossible to test non-per-CPU variables
right now. :(

>

> re: patch 1.

> Instead of copy paste that hack please convert it to sys_membarrier(MEMBARRIER_CMD_GLOBAL).


Oh, cool, didn't know about it, nice.

>

> The rest looks good to me.
diff mbox series

Patch

diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 07cb5d15e743..408db1122e9a 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -761,9 +761,15 @@  struct bpf_ctx_arg_aux {
 	u32 btf_id;
 };
 
+struct btf_mod_pair {
+	struct btf *btf;
+	struct module *module;
+};
+
 struct bpf_prog_aux {
 	atomic64_t refcnt;
 	u32 used_map_cnt;
+	u32 used_btf_cnt;
 	u32 max_ctx_offset;
 	u32 max_pkt_offset;
 	u32 max_tp_access;
@@ -802,6 +808,7 @@  struct bpf_prog_aux {
 	const struct bpf_prog_ops *ops;
 	struct bpf_map **used_maps;
 	struct mutex used_maps_mutex; /* mutex for used_maps and used_map_cnt */
+	struct btf_mod_pair *used_btfs;
 	struct bpf_prog *prog;
 	struct user_struct *user;
 	u64 load_time; /* ns since boottime */
@@ -1208,6 +1215,8 @@  struct bpf_prog * __must_check bpf_prog_inc_not_zero(struct bpf_prog *prog);
 void bpf_prog_put(struct bpf_prog *prog);
 void __bpf_free_used_maps(struct bpf_prog_aux *aux,
 			  struct bpf_map **used_maps, u32 len);
+void __bpf_free_used_btfs(struct bpf_prog_aux *aux,
+			  struct btf_mod_pair *used_btfs, u32 len);
 
 void bpf_prog_free_id(struct bpf_prog *prog, bool do_idr_lock);
 void bpf_map_free_id(struct bpf_map *map, bool do_idr_lock);
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index e941fe1484e5..dfe6f85d97dd 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -340,6 +340,7 @@  struct bpf_insn_aux_data {
 };
 
 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
+#define MAX_USED_BTFS 64 /* max number of BTFs accessed by one BPF program */
 
 #define BPF_VERIFIER_TMP_LOG_SIZE	1024
 
@@ -398,7 +399,9 @@  struct bpf_verifier_env {
 	struct bpf_verifier_state_list **explored_states; /* search pruning optimization */
 	struct bpf_verifier_state_list *free_list;
 	struct bpf_map *used_maps[MAX_USED_MAPS]; /* array of map's used by eBPF program */
+	struct btf_mod_pair used_btfs[MAX_USED_BTFS]; /* array of BTF's used by BPF program */
 	u32 used_map_cnt;		/* number of used maps */
+	u32 used_btf_cnt;		/* number of used BTF objects */
 	u32 id_gen;			/* used to generate unique reg IDs */
 	bool allow_ptr_leaks;
 	bool allow_ptr_to_map_access;
diff --git a/include/linux/btf.h b/include/linux/btf.h
index 4c200f5d242b..7fabf1428093 100644
--- a/include/linux/btf.h
+++ b/include/linux/btf.h
@@ -91,6 +91,9 @@  int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
 int btf_get_fd_by_id(u32 id);
 u32 btf_obj_id(const struct btf *btf);
 bool btf_is_kernel(const struct btf *btf);
+bool btf_is_module(const struct btf *btf);
+struct module *btf_try_get_module(const struct btf *btf);
+u32 btf_nr_types(const struct btf *btf);
 bool btf_member_is_reg_int(const struct btf *btf, const struct btf_type *s,
 			   const struct btf_member *m,
 			   u32 expected_offset, u32 expected_size);
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index 8d6bdb4f4d61..7ccc0133723a 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -458,7 +458,7 @@  static bool btf_type_is_datasec(const struct btf_type *t)
 	return BTF_INFO_KIND(t->info) == BTF_KIND_DATASEC;
 }
 
-static u32 btf_nr_types_total(const struct btf *btf)
+u32 btf_nr_types(const struct btf *btf)
 {
 	u32 total = 0;
 
@@ -476,7 +476,7 @@  s32 btf_find_by_name_kind(const struct btf *btf, const char *name, u8 kind)
 	const char *tname;
 	u32 i, total;
 
-	total = btf_nr_types_total(btf);
+	total = btf_nr_types(btf);
 	for (i = 1; i < total; i++) {
 		t = btf_type_by_id(btf, i);
 		if (BTF_INFO_KIND(t->info) != kind)
@@ -5743,6 +5743,11 @@  bool btf_is_kernel(const struct btf *btf)
 	return btf->kernel_btf;
 }
 
+bool btf_is_module(const struct btf *btf)
+{
+	return btf->kernel_btf && strcmp(btf->name, "vmlinux") != 0;
+}
+
 static int btf_id_cmp_func(const void *a, const void *b)
 {
 	const int *pa = a, *pb = b;
@@ -5877,3 +5882,25 @@  static int __init btf_module_init(void)
 
 fs_initcall(btf_module_init);
 #endif /* CONFIG_DEBUG_INFO_BTF_MODULES */
+
+struct module *btf_try_get_module(const struct btf *btf)
+{
+	struct module *res = NULL;
+#ifdef CONFIG_DEBUG_INFO_BTF_MODULES
+	struct btf_module *btf_mod, *tmp;
+
+	mutex_lock(&btf_module_mutex);
+	list_for_each_entry_safe(btf_mod, tmp, &btf_modules, list) {
+		if (btf_mod->btf != btf)
+			continue;
+
+		if (try_module_get(btf_mod->module))
+			res = btf_mod->module;
+
+		break;
+	}
+	mutex_unlock(&btf_module_mutex);
+#endif
+
+	return res;
+}
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 261f8692d0d2..69c3c308de5e 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -2119,6 +2119,28 @@  static void bpf_free_used_maps(struct bpf_prog_aux *aux)
 	kfree(aux->used_maps);
 }
 
+void __bpf_free_used_btfs(struct bpf_prog_aux *aux,
+			  struct btf_mod_pair *used_btfs, u32 len)
+{
+#ifdef CONFIG_BPF_SYSCALL
+	struct btf_mod_pair *btf_mod;
+	u32 i;
+
+	for (i = 0; i < len; i++) {
+		btf_mod = &used_btfs[i];
+		if (btf_mod->module)
+			module_put(btf_mod->module);
+		btf_put(btf_mod->btf);
+	}
+#endif
+}
+
+static void bpf_free_used_btfs(struct bpf_prog_aux *aux)
+{
+	__bpf_free_used_btfs(aux, aux->used_btfs, aux->used_btf_cnt);
+	kfree(aux->used_btfs);
+}
+
 static void bpf_prog_free_deferred(struct work_struct *work)
 {
 	struct bpf_prog_aux *aux;
@@ -2126,6 +2148,7 @@  static void bpf_prog_free_deferred(struct work_struct *work)
 
 	aux = container_of(work, struct bpf_prog_aux, work);
 	bpf_free_used_maps(aux);
+	bpf_free_used_btfs(aux);
 	if (bpf_prog_is_dev_bound(aux))
 		bpf_prog_offload_destroy(aux->prog);
 #ifdef CONFIG_PERF_EVENTS
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 93def76cf32b..ac0cf84a2d67 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -9702,6 +9702,31 @@  static int do_check(struct bpf_verifier_env *env)
 	return 0;
 }
 
+static int find_btf_percpu_datasec(struct btf *btf)
+{
+	const struct btf_type *t;
+	const char *tname;
+	int i, n;
+
+	n = btf_nr_types(btf);
+	if (btf_is_module(btf))
+		i = btf_nr_types(btf_vmlinux);
+	else
+		i = 1;
+
+	for(; i < n; i++) {
+		t = btf_type_by_id(btf, i);
+		if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC)
+			continue;
+
+		tname = btf_name_by_offset(btf, t->name_off);
+		if (!strcmp(tname, ".data..percpu"))
+			return i;
+	}
+
+	return -ENOENT;
+}
+
 /* replace pseudo btf_id with kernel symbol address */
 static int check_pseudo_btf_id(struct bpf_verifier_env *env,
 			       struct bpf_insn *insn,
@@ -9709,48 +9734,57 @@  static int check_pseudo_btf_id(struct bpf_verifier_env *env,
 {
 	const struct btf_var_secinfo *vsi;
 	const struct btf_type *datasec;
+	struct btf_mod_pair *btf_mod;
 	const struct btf_type *t;
 	const char *sym_name;
 	bool percpu = false;
 	u32 type, id = insn->imm;
+	struct btf *btf;
 	s32 datasec_id;
 	u64 addr;
-	int i;
+	int i, btf_fd, err;
 
-	if (!btf_vmlinux) {
-		verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
-		return -EINVAL;
-	}
-
-	if (insn[1].imm != 0) {
-		verbose(env, "reserved field (insn[1].imm) is used in pseudo_btf_id ldimm64 insn.\n");
-		return -EINVAL;
+	btf_fd = insn[1].imm;
+	if (btf_fd) {
+		btf = btf_get_by_fd(btf_fd);
+		if (IS_ERR(btf)) {
+			verbose(env, "invalid module BTF object FD specified.\n");
+			return -EINVAL;
+		}
+	} else {
+		if (!btf_vmlinux) {
+			verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n");
+			return -EINVAL;
+		}
+		btf = btf_vmlinux;
+		btf_get(btf);
 	}
 
-	t = btf_type_by_id(btf_vmlinux, id);
+	t = btf_type_by_id(btf, id);
 	if (!t) {
 		verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id);
-		return -ENOENT;
+		err = -ENOENT;
+		goto err_put;
 	}
 
 	if (!btf_type_is_var(t)) {
-		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n",
-			id);
-		return -EINVAL;
+		verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id);
+		err = -EINVAL;
+		goto err_put;
 	}
 
-	sym_name = btf_name_by_offset(btf_vmlinux, t->name_off);
+	sym_name = btf_name_by_offset(btf, t->name_off);
 	addr = kallsyms_lookup_name(sym_name);
 	if (!addr) {
 		verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n",
 			sym_name);
-		return -ENOENT;
+		err = -ENOENT;
+		goto err_put;
 	}
 
-	datasec_id = btf_find_by_name_kind(btf_vmlinux, ".data..percpu",
-					   BTF_KIND_DATASEC);
+	datasec_id = find_btf_percpu_datasec(btf);
 	if (datasec_id > 0) {
-		datasec = btf_type_by_id(btf_vmlinux, datasec_id);
+		datasec = btf_type_by_id(btf, datasec_id);
 		for_each_vsi(i, datasec, vsi) {
 			if (vsi->type == id) {
 				percpu = true;
@@ -9763,10 +9797,10 @@  static int check_pseudo_btf_id(struct bpf_verifier_env *env,
 	insn[1].imm = addr >> 32;
 
 	type = t->type;
-	t = btf_type_skip_modifiers(btf_vmlinux, type, NULL);
+	t = btf_type_skip_modifiers(btf, type, NULL);
 	if (percpu) {
 		aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID;
-		aux->btf_var.btf = btf_vmlinux;
+		aux->btf_var.btf = btf;
 		aux->btf_var.btf_id = type;
 	} else if (!btf_type_is_struct(t)) {
 		const struct btf_type *ret;
@@ -9774,21 +9808,54 @@  static int check_pseudo_btf_id(struct bpf_verifier_env *env,
 		u32 tsize;
 
 		/* resolve the type size of ksym. */
-		ret = btf_resolve_size(btf_vmlinux, t, &tsize);
+		ret = btf_resolve_size(btf, t, &tsize);
 		if (IS_ERR(ret)) {
-			tname = btf_name_by_offset(btf_vmlinux, t->name_off);
+			tname = btf_name_by_offset(btf, t->name_off);
 			verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n",
 				tname, PTR_ERR(ret));
-			return -EINVAL;
+			err = -EINVAL;
+			goto err_put;
 		}
 		aux->btf_var.reg_type = PTR_TO_MEM;
 		aux->btf_var.mem_size = tsize;
 	} else {
 		aux->btf_var.reg_type = PTR_TO_BTF_ID;
-		aux->btf_var.btf = btf_vmlinux;
+		aux->btf_var.btf = btf;
 		aux->btf_var.btf_id = type;
 	}
+
+	/* check whether we recorded this BTF (and maybe module) already */
+	for (i = 0; i < env->used_btf_cnt; i++) {
+		if (env->used_btfs[i].btf == btf) {
+			btf_put(btf);
+			return 0;
+		}
+	}
+
+	if (env->used_btf_cnt >= MAX_USED_BTFS) {
+		err = -E2BIG;
+		goto err_put;
+	}
+
+	btf_mod = &env->used_btfs[env->used_btf_cnt];
+	btf_mod->btf = btf;
+	btf_mod->module = NULL;
+
+	/* if we reference variables from kernel module, bump its refcount */
+	if (btf_is_module(btf)) {
+		btf_mod->module = btf_try_get_module(btf);
+		if (!btf_mod->module) {
+			err = -ENXIO;
+			goto err_put;
+		}
+	}
+
+	env->used_btf_cnt++;
+
 	return 0;
+err_put:
+	btf_put(btf);
+	return err;
 }
 
 static int check_map_prealloc(struct bpf_map *map)
@@ -10085,6 +10152,13 @@  static void release_maps(struct bpf_verifier_env *env)
 			     env->used_map_cnt);
 }
 
+/* drop refcnt of maps used by the rejected program */
+static void release_btfs(struct bpf_verifier_env *env)
+{
+	__bpf_free_used_btfs(env->prog->aux, env->used_btfs,
+			     env->used_btf_cnt);
+}
+
 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */
 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env)
 {
@@ -12097,7 +12171,10 @@  int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
 		goto err_release_maps;
 	}
 
-	if (ret == 0 && env->used_map_cnt) {
+	if (ret)
+		goto err_release_maps;
+
+	if (env->used_map_cnt) {
 		/* if program passed verifier, update used_maps in bpf_prog_info */
 		env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt,
 							  sizeof(env->used_maps[0]),
@@ -12111,15 +12188,29 @@  int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
 		memcpy(env->prog->aux->used_maps, env->used_maps,
 		       sizeof(env->used_maps[0]) * env->used_map_cnt);
 		env->prog->aux->used_map_cnt = env->used_map_cnt;
+	}
+	if (env->used_btf_cnt) {
+		/* if program passed verifier, update used_btfs in bpf_prog_aux */
+		env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt,
+							  sizeof(env->used_btfs[0]),
+							  GFP_KERNEL);
+		if (!env->prog->aux->used_btfs) {
+			ret = -ENOMEM;
+			goto err_release_maps;
+		}
 
+		memcpy(env->prog->aux->used_btfs, env->used_btfs,
+		       sizeof(env->used_btfs[0]) * env->used_btf_cnt);
+		env->prog->aux->used_btf_cnt = env->used_btf_cnt;
+	}
+	if (env->used_map_cnt || env->used_btf_cnt) {
 		/* program is valid. Convert pseudo bpf_ld_imm64 into generic
 		 * bpf_ld_imm64 instructions
 		 */
 		convert_pseudo_ld_imm64(env);
 	}
 
-	if (ret == 0)
-		adjust_btf_func(env);
+	adjust_btf_func(env);
 
 err_release_maps:
 	if (!env->prog->aux->used_maps)
@@ -12127,6 +12218,8 @@  int bpf_check(struct bpf_prog **prog, union bpf_attr *attr,
 		 * them now. Otherwise free_used_maps() will release them.
 		 */
 		release_maps(env);
+	if (!env->prog->aux->used_btfs)
+		release_btfs(env);
 
 	/* extension progs temporarily inherit the attach_type of their targets
 	   for verification purposes, so set it back to zero before returning