Skip to contentSkip to conversation

bpf: Introduce file dynptr

RFC PATCH Superseded Mykyta Yatsenko 5 participants 36 messages Oct 15, 2025 – Oct 17, 2025

Subsystems (8)
Kselftest Library code BPF Tracing +4 more subsystems

v2 of 5 Superseded Latest is v5 →

lore
Share & tools
lore
#0 lore raw

v2 cover bpf: Introduce file dynptr

From: Mykyta Yatsenko <[email protected]>

This series adds a new dynptr kind, file dynptr, which enables BPF programs to perform safe reads from files in a structured way. Initial motivations include:
* Parsing the executable’s ELF to locate thread-local variable symbols
* Capturing stack traces when frame pointers are disabled

By leveraging the existing dynptr abstraction, we reuse the verifier’s lifetime/size checks and keep the API consistent with existing dynptr read helpers.

Technical details:
1. Reuses the existing freader library to read files a folio at a time.
2. bpf_dynptr_slice() and bpf_dynptr_read() always copy data from folios into a program-provided buffer; zero-copy access is intentionally not supported to keep it simple.
3. Reads may sleep if the requested folios are not in the page cache.
4. Few verifier changes required:
* Support dynptr destruction in kfuncs
* Add kfunc address substitution based on whether the program runs in a sleepable or non-sleepable context.

Testing:
The final patch adds a selftest that parses the executable’s ELF to locate thread-local symbol information, demonstrating the file dynptr workflow end-to-end.

Mykyta Yatsenko (11):
selftests/bpf: remove unnecessary kfunc prototypes
bpf: widen dynptr size/offset to 64 bit
lib: move freader into buildid.h lib/freader: support reading more than 2 folios
bpf: verifier: centralize const dynptr check in
unmark_stack_slots_dynptr()
bpf: mark vm_area_struct as trusted
bpf: add plumbing for file-backed dynptr
bpf: add kfuncs and helpers support for file dynptrs
bpf: verifier: refactor kfunc specialization
bpf: dispatch to sleepable file dynptr selftests/bpf: add file dynptr tests

 MAINTAINERS                                   |   1 +
 include/linux/bpf.h                           |  30 +--
 include/linux/buildid.h                       |  25 +++
 include/uapi/linux/bpf.h                      |   8 +-
 kernel/bpf/helpers.c                          | 172 ++++++++++++++----
 kernel/bpf/log.c                              |   2 +
 kernel/bpf/verifier.c                         | 158 ++++++++++------
 kernel/trace/bpf_trace.c                      |  46 ++---
 lib/buildid.c                                 |  55 ++----
 tools/include/uapi/linux/bpf.h                |   8 +-
 tools/testing/selftests/bpf/bpf_kfuncs.h      |  12 +-
 .../selftests/bpf/prog_tests/file_reader.c    | 114 ++++++++++++
 .../selftests/bpf/progs/dynptr_success.c      |  12 +-
 .../testing/selftests/bpf/progs/file_reader.c | 157 ++++++++++++++++
 tools/testing/selftests/bpf/progs/find_vma.c  |   6 +-
 .../selftests/bpf/progs/ip_check_defrag.c     |   5 -
 .../bpf/progs/verifier_netfilter_ctx.c        |   5 -
 17 files changed, 624 insertions(+), 192 deletions(-)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/file_reader.c
 create mode 100644 tools/testing/selftests/bpf/progs/file_reader.c
Signature · 1 line
2.51.0
#1 lore raw

RFC PATCH v2 1/11 selftests/bpf: remove unnecessary kfunc prototypes

From: Mykyta Yatsenko <[email protected]>

Remove unnecessary kfunc prototypes from test programs, these are provided by vmlinux.h

---
 tools/testing/selftests/bpf/progs/ip_check_defrag.c        | 5 -----
 tools/testing/selftests/bpf/progs/verifier_netfilter_ctx.c | 5 -----
 2 files changed, 10 deletions(-)
tools/testing/selftests/bpf/progs/ip_check_defrag.c +0 -5
index 645b2c9f7867..0e87ad1ebcfa 100644
@@ -12,11 +12,6 @@
 #define IP_OFFSET		0x1FFF
 #define NEXTHDR_FRAGMENT	44
 
-extern int bpf_dynptr_from_skb(struct __sk_buff *skb, __u64 flags,
-			      struct bpf_dynptr *ptr__uninit) __ksym;
-extern void *bpf_dynptr_slice(const struct bpf_dynptr *ptr, uint32_t offset,
-			      void *buffer, uint32_t buffer__sz) __ksym;
-
 volatile int shootdowns = 0;
 
 static bool is_frag_v4(struct iphdr *iph)
tools/testing/selftests/bpf/progs/verifier_netfilter_ctx.c +0 -5
index ab9f9f2620ed..e2cbc5bda65e 100644
@@ -79,11 +79,6 @@ int with_invalid_ctx_access_test5(struct bpf_nf_ctx *ctx)
 	return NF_ACCEPT;
 }
 
-extern int bpf_dynptr_from_skb(struct __sk_buff *skb, __u64 flags,
-                               struct bpf_dynptr *ptr__uninit) __ksym;
-extern void *bpf_dynptr_slice(const struct bpf_dynptr *ptr, uint32_t offset,
-                                   void *buffer, uint32_t buffer__sz) __ksym;
-
 SEC("netfilter")
 __description("netfilter test prog with skb and state read access")
 __success __failure_unpriv
Signature · 1 line
2.51.0
#2 lore raw

RFC PATCH v2 2/11 bpf: widen dynptr size/offset to 64 bit

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Dynptr currently caps size and offset at 24 bits, which isn’t sufficient for file-backed use cases; even 32 bits can be limiting. Refactor dynptr helpers/kfuncs to use 64-bit size and offset, ensuring consistency across the APIs.

This change does not affect internals of xdp, skb or other dynptrs, which continue to behave as before.

The widening enables large-file access support via dynptr, implemented in the next patches.

---
 include/linux/bpf.h                           | 20 +++---
 include/uapi/linux/bpf.h                      |  8 +--
 kernel/bpf/helpers.c                          | 66 +++++++++----------
 kernel/trace/bpf_trace.c                      | 46 ++++++-------
 tools/include/uapi/linux/bpf.h                |  8 +--
 tools/testing/selftests/bpf/bpf_kfuncs.h      | 12 ++--
 .../selftests/bpf/progs/dynptr_success.c      | 12 ++--
 7 files changed, 86 insertions(+), 86 deletions(-)
include/linux/bpf.h +10 -10
index f87fb203aaae..7daddb44c348 100644
@@ -1387,19 +1387,19 @@ enum bpf_dynptr_type {
 	BPF_DYNPTR_TYPE_SKB_META,
 };
 
-int bpf_dynptr_check_size(u32 size);
-u32 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr);
-const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u32 len);
-void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u32 len);
+int bpf_dynptr_check_size(u64 size);
+u64 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr);
+const void *__bpf_dynptr_data(const struct bpf_dynptr_kern *ptr, u64 len);
+void *__bpf_dynptr_data_rw(const struct bpf_dynptr_kern *ptr, u64 len);
 bool __bpf_dynptr_is_rdonly(const struct bpf_dynptr_kern *ptr);
-int __bpf_dynptr_write(const struct bpf_dynptr_kern *dst, u32 offset,
-		       void *src, u32 len, u64 flags);
-void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *p, u32 offset,
-			    void *buffer__opt, u32 buffer__szk);
+int __bpf_dynptr_write(const struct bpf_dynptr_kern *dst, u64 offset,
+		       void *src, u64 len, u64 flags);
+void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *p, u64 offset,
+			    void *buffer__opt, u64 buffer__szk);
 
-static inline int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u32 offset, u32 len)
+static inline int bpf_dynptr_check_off_len(const struct bpf_dynptr_kern *ptr, u64 offset, u64 len)
 {
-	u32 size = __bpf_dynptr_size(ptr);
+	u64 size = __bpf_dynptr_size(ptr);
 
 	if (len > size || offset > size - len)
 		return -E2BIG;
include/uapi/linux/bpf.h +4 -4
index 6829936d33f5..77edd0253989 100644
@@ -5618,7 +5618,7 @@ union bpf_attr {
  *	Return
  *		*sk* if casting is valid, or **NULL** otherwise.
  *
- * long bpf_dynptr_from_mem(void *data, u32 size, u64 flags, struct bpf_dynptr *ptr)
+ * long bpf_dynptr_from_mem(void *data, u64 size, u64 flags, struct bpf_dynptr *ptr)
  *	Description
  *		Get a dynptr to local memory *data*.
  *
@@ -5661,7 +5661,7 @@ union bpf_attr {
  *	Return
  *		Nothing. Always succeeds.
  *
- * long bpf_dynptr_read(void *dst, u32 len, const struct bpf_dynptr *src, u32 offset, u64 flags)
+ * long bpf_dynptr_read(void *dst, u64 len, const struct bpf_dynptr *src, u64 offset, u64 flags)
  *	Description
  *		Read *len* bytes from *src* into *dst*, starting from *offset*
  *		into *src*.
@@ -5671,7 +5671,7 @@ union bpf_attr {
  *		of *src*'s data, -EINVAL if *src* is an invalid dynptr or if
  *		*flags* is not 0.
  *
- * long bpf_dynptr_write(const struct bpf_dynptr *dst, u32 offset, void *src, u32 len, u64 flags)
+ * long bpf_dynptr_write(const struct bpf_dynptr *dst, u64 offset, void *src, u64 len, u64 flags)
  *	Description
  *		Write *len* bytes from *src* into *dst*, starting from *offset*
  *		into *dst*.
@@ -5692,7 +5692,7 @@ union bpf_attr {
  *		is a read-only dynptr or if *flags* is not correct. For skb-type dynptrs,
  *		other errors correspond to errors returned by **bpf_skb_store_bytes**\ ().
  *
- * void *bpf_dynptr_data(const struct bpf_dynptr *ptr, u32 offset, u32 len)
+ * void *bpf_dynptr_data(const struct bpf_dynptr *ptr, u64 offset, u64 len)
  *	Description
  *		Get a pointer to the underlying dynptr data.
  *
kernel/bpf/helpers.c +33 -33

191 lines not on this page · raw message

kernel/trace/bpf_trace.c +23 -23

122 lines not on this page · raw message

tools/include/uapi/linux/bpf.h +4 -4
index 6829936d33f5..77edd0253989 100644
@@ -5618,7 +5618,7 @@ union bpf_attr {
  *	Return
  *		*sk* if casting is valid, or **NULL** otherwise.
  *
- * long bpf_dynptr_from_mem(void *data, u32 size, u64 flags, struct bpf_dynptr *ptr)
+ * long bpf_dynptr_from_mem(void *data, u64 size, u64 flags, struct bpf_dynptr *ptr)
  *	Description
  *		Get a dynptr to local memory *data*.
  *
@@ -5661,7 +5661,7 @@ union bpf_attr {
  *	Return
  *		Nothing. Always succeeds.
  *
- * long bpf_dynptr_read(void *dst, u32 len, const struct bpf_dynptr *src, u32 offset, u64 flags)
+ * long bpf_dynptr_read(void *dst, u64 len, const struct bpf_dynptr *src, u64 offset, u64 flags)
  *	Description
  *		Read *len* bytes from *src* into *dst*, starting from *offset*
  *		into *src*.
@@ -5671,7 +5671,7 @@ union bpf_attr {
  *		of *src*'s data, -EINVAL if *src* is an invalid dynptr or if
  *		*flags* is not 0.
  *
- * long bpf_dynptr_write(const struct bpf_dynptr *dst, u32 offset, void *src, u32 len, u64 flags)
+ * long bpf_dynptr_write(const struct bpf_dynptr *dst, u64 offset, void *src, u64 len, u64 flags)
  *	Description
  *		Write *len* bytes from *src* into *dst*, starting from *offset*
  *		into *dst*.
@@ -5692,7 +5692,7 @@ union bpf_attr {
  *		is a read-only dynptr or if *flags* is not correct. For skb-type dynptrs,
  *		other errors correspond to errors returned by **bpf_skb_store_bytes**\ ().
  *
- * void *bpf_dynptr_data(const struct bpf_dynptr *ptr, u32 offset, u32 len)
+ * void *bpf_dynptr_data(const struct bpf_dynptr *ptr, u64 offset, u64 len)
  *	Description
  *		Get a pointer to the underlying dynptr data.
  *
tools/testing/selftests/bpf/bpf_kfuncs.h +6 -6
index 794d44d19c88..e0189254bb6e 100644
@@ -28,8 +28,8 @@ extern int bpf_dynptr_from_skb_meta(struct __sk_buff *skb, __u64 flags,
  *  Either a direct pointer to the dynptr data or a pointer to the user-provided
  *  buffer if unable to obtain a direct pointer
  */
-extern void *bpf_dynptr_slice(const struct bpf_dynptr *ptr, __u32 offset,
-			      void *buffer, __u32 buffer__szk) __ksym __weak;
+extern void *bpf_dynptr_slice(const struct bpf_dynptr *ptr, __u64 offset,
+			      void *buffer, __u64 buffer__szk) __ksym __weak;
 
 /* Description
  *  Obtain a read-write pointer to the dynptr's data
@@ -37,13 +37,13 @@ extern void *bpf_dynptr_slice(const struct bpf_dynptr *ptr, __u32 offset,
  *  Either a direct pointer to the dynptr data or a pointer to the user-provided
  *  buffer if unable to obtain a direct pointer
  */
-extern void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *ptr, __u32 offset,
-			      void *buffer, __u32 buffer__szk) __ksym __weak;
+extern void *bpf_dynptr_slice_rdwr(const struct bpf_dynptr *ptr, __u64 offset, void *buffer,
+				   __u64 buffer__szk) __ksym __weak;
 
-extern int bpf_dynptr_adjust(const struct bpf_dynptr *ptr, __u32 start, __u32 end) __ksym __weak;
+extern int bpf_dynptr_adjust(const struct bpf_dynptr *ptr, __u64 start, __u64 end) __ksym __weak;
 extern bool bpf_dynptr_is_null(const struct bpf_dynptr *ptr) __ksym __weak;
 extern bool bpf_dynptr_is_rdonly(const struct bpf_dynptr *ptr) __ksym __weak;
-extern __u32 bpf_dynptr_size(const struct bpf_dynptr *ptr) __ksym __weak;
+extern __u64 bpf_dynptr_size(const struct bpf_dynptr *ptr) __ksym __weak;
 extern int bpf_dynptr_clone(const struct bpf_dynptr *ptr, struct bpf_dynptr *clone__init) __ksym __weak;
 
 /* Description
tools/testing/selftests/bpf/progs/dynptr_success.c +6 -6
index 127dea342e5a..e0d672d93adf 100644
@@ -914,8 +914,8 @@ void *user_ptr;
 char expected_str[384];
 __u32 test_len[7] = {0/* placeholder */, 0, 1, 2, 255, 256, 257};
 
-typedef int (*bpf_read_dynptr_fn_t)(struct bpf_dynptr *dptr, u32 off,
-				    u32 size, const void *unsafe_ptr);
+typedef int (*bpf_read_dynptr_fn_t)(struct bpf_dynptr *dptr, u64 off,
+				    u64 size, const void *unsafe_ptr);
 
 /* Returns the offset just before the end of the maximum sized xdp fragment.
  * Any write larger than 32 bytes will be split between 2 fragments.
@@ -1106,16 +1106,16 @@ int test_copy_from_user_str_dynptr(void *ctx)
 	return 0;
 }
 
-static int bpf_copy_data_from_user_task(struct bpf_dynptr *dptr, u32 off,
-					u32 size, const void *unsafe_ptr)
+static int bpf_copy_data_from_user_task(struct bpf_dynptr *dptr, u64 off,
+					u64 size, const void *unsafe_ptr)
 {
 	struct task_struct *task = bpf_get_current_task_btf();
 
 	return bpf_copy_from_user_task_dynptr(dptr, off, size, unsafe_ptr, task);
 }
 
-static int bpf_copy_data_from_user_task_str(struct bpf_dynptr *dptr, u32 off,
-					    u32 size, const void *unsafe_ptr)
+static int bpf_copy_data_from_user_task_str(struct bpf_dynptr *dptr, u64 off,
+					    u64 size, const void *unsafe_ptr)
 {
 	struct task_struct *task = bpf_get_current_task_btf();
 
Signature · 1 line
2.51.0
maintainer Acked-by on v2 2/11
#3 lore raw

Re: [RFC PATCH v2 02/11] bpf: widen dynptr size/offset to 64 bit

Quoted 7 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Dynptr currently caps size and offset at 24 bits, which isn’t sufficient for file-backed use cases; even 32 bits can be limiting. Refactor dynptr helpers/kfuncs to use 64-bit size and offset, ensuring consistency across the APIs.

Quoted 5 lines

This change does not affect internals of xdp, skb or other dynptrs, which continue to behave as before.

The widening enables large-file access support via dynptr, implemented in the next patches.

Nit: still think that mentioning that this change does not break
binary compatibility is important.

Quoted 2 lines

---

I grepped references to functions changed in this patch, all changes seem to be consistent. The only places with leftover u32 is:

  ./fs/verity/measure.c:  u32 dynptr_sz = __bpf_dynptr_size(digest_ptr);

But it is probably fine to keep it as-is.

[...]

#4 lore raw

RFC PATCH v2 3/11 lib: move freader into buildid.h

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Move struct freader and prototypes of the functions operating on it into the buildid.h.

This allows reusing freader outside buildid, e.g. for file dynptr support added later.

---
 MAINTAINERS             |  1 +
 include/linux/buildid.h | 25 +++++++++++++++++++++++++
 lib/buildid.c           | 29 +++++------------------------
 3 files changed, 31 insertions(+), 24 deletions(-)
MAINTAINERS +1 -0
index 46126ce2f968..c0dd43d517c5 100644
@@ -4648,6 +4648,7 @@ F:	Documentation/userspace-api/ebpf/
 F:	arch/*/net/*
 F:	include/linux/bpf*
 F:	include/linux/btf*
+F:	include/linux/buildid.h
 F:	include/linux/filter.h
 F:	include/trace/events/xdp.h
 F:	include/uapi/linux/bpf*
include/linux/buildid.h +25 -0
index 014a88c41073..831c1b4b626c 100644
@@ -18,4 +18,29 @@ void init_vmlinux_build_id(void);
 static inline void init_vmlinux_build_id(void) { }
 #endif
 
+struct freader {
+	void *buf;
+	u32 buf_sz;
+	int err;
+	union {
+		struct {
+			struct file *file;
+			struct folio *folio;
+			void *addr;
+			loff_t folio_off;
+			bool may_fault;
+		};
+		struct {
+			const char *data;
+			u64 data_sz;
+		};
+	};
+};
+
+void freader_init_from_file(struct freader *r, void *buf, u32 buf_sz,
+			    struct file *file, bool may_fault);
+void freader_init_from_mem(struct freader *r, const char *data, u64 data_sz);
+const void *freader_fetch(struct freader *r, loff_t file_off, size_t sz);
+void freader_cleanup(struct freader *r);
+
 #endif
lib/buildid.c +5 -24
index c4b0f376fb34..df06e492810d 100644
@@ -11,27 +11,8 @@
 
 #define MAX_PHDR_CNT 256
 
-struct freader {
-	void *buf;
-	u32 buf_sz;
-	int err;
-	union {
-		struct {
-			struct file *file;
-			struct folio *folio;
-			void *addr;
-			loff_t folio_off;
-			bool may_fault;
-		};
-		struct {
-			const char *data;
-			u64 data_sz;
-		};
-	};
-};
-
-static void freader_init_from_file(struct freader *r, void *buf, u32 buf_sz,
-				   struct file *file, bool may_fault)
+void freader_init_from_file(struct freader *r, void *buf, u32 buf_sz,
+			    struct file *file, bool may_fault)
 {
 	memset(r, 0, sizeof(*r));
 	r->buf = buf;
@@ -40,7 +21,7 @@ static void freader_init_from_file(struct freader *r, void *buf, u32 buf_sz,
 	r->may_fault = may_fault;
 }
 
-static void freader_init_from_mem(struct freader *r, const char *data, u64 data_sz)
+void freader_init_from_mem(struct freader *r, const char *data, u64 data_sz)
 {
 	memset(r, 0, sizeof(*r));
 	r->data = data;
@@ -92,7 +73,7 @@ static int freader_get_folio(struct freader *r, loff_t file_off)
 	return 0;
 }
 
-static const void *freader_fetch(struct freader *r, loff_t file_off, size_t sz)
+const void *freader_fetch(struct freader *r, loff_t file_off, size_t sz)
 {
 	size_t folio_sz;
 
@@ -147,7 +128,7 @@ static const void *freader_fetch(struct freader *r, loff_t file_off, size_t sz)
 	return r->addr + (file_off - r->folio_off);
 }
 
-static void freader_cleanup(struct freader *r)
+void freader_cleanup(struct freader *r)
 {
 	if (!r->buf)
 		return; /* non-file-backed mode */
Signature · 1 line
2.51.0
#5 lore raw

RFC PATCH v2 4/11 lib/freader: support reading more than 2 folios

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

freader_fetch currently reads from at most two folios. When a read spans into a third folio, the overflow bytes are copied adjacent to the second folio’s data instead of being handled as a separate folio. This patch modifies fetch algorithm to support reading from many folios.

---
 lib/buildid.c | 26 ++++++++++++++------------
 1 file changed, 14 insertions(+), 12 deletions(-)
lib/buildid.c +14 -12
index df06e492810d..ade01d7ff682 100644
@@ -108,18 +108,20 @@ const void *freader_fetch(struct freader *r, loff_t file_off, size_t sz)
 	 */
 	folio_sz = folio_size(r->folio);
 	if (file_off + sz > r->folio_off + folio_sz) {
-		int part_sz = r->folio_off + folio_sz - file_off;
-
-		/* copy the part that resides in the current folio */
-		memcpy(r->buf, r->addr + (file_off - r->folio_off), part_sz);
-
-		/* fetch next folio */
-		r->err = freader_get_folio(r, r->folio_off + folio_sz);
-		if (r->err)
-			return NULL;
-
-		/* copy the rest of requested data */
-		memcpy(r->buf + part_sz, r->addr, sz - part_sz);
+		u64 part_sz = r->folio_off + folio_sz - file_off, off;
+
+		memcpy(r->buf, r->addr + file_off - r->folio_off, part_sz);
+		off = part_sz;
+
+		while (off < sz) {
+			/* fetch next folio */
+			r->err = freader_get_folio(r, r->folio_off + folio_sz);
+			if (r->err)
+				return NULL;
+			part_sz = min_t(u64, sz - off, folio_size(r->folio));
+			memcpy(r->buf + off, r->addr, part_sz);
+			off += part_sz;
+		}
 
 		return r->buf;
 	}
Signature · 1 line
2.51.0
Reviewed-by on v2 4/11
#6 lore raw

Re: [RFC PATCH v2 04/11] lib/freader: support reading more than 2 folios

Quoted 8 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

freader_fetch currently reads from at most two folios. When a read spans into a third folio, the overflow bytes are copied adjacent to the second folio’s data instead of being handled as a separate folio. This patch modifies fetch algorithm to support reading from many folios.

Quoted 5 lines
---
 lib/buildid.c | 26 ++++++++++++++------------
 1 file changed, 14 insertions(+), 12 deletions(-)

LGTM

Quoted 40 lines
lib/buildid.c +14 -13
index df06e492810d..ade01d7ff682 100644
@@ -108,18 +108,20 @@ const void *freader_fetch(struct freader *r, loff_t file_off, size_t sz)
         */
        folio_sz = folio_size(r->folio);
        if (file_off + sz > r->folio_off + folio_sz) {
-               int part_sz = r->folio_off + folio_sz - file_off;
-
-               /* copy the part that resides in the current folio */
-               memcpy(r->buf, r->addr + (file_off - r->folio_off), part_sz);
-
-               /* fetch next folio */
-               r->err = freader_get_folio(r, r->folio_off + folio_sz);
-               if (r->err)
-                       return NULL;
-
-               /* copy the rest of requested data */
-               memcpy(r->buf + part_sz, r->addr, sz - part_sz);
+               u64 part_sz = r->folio_off + folio_sz - file_off, off;
+
+               memcpy(r->buf, r->addr + file_off - r->folio_off, part_sz);
+               off = part_sz;
+
+               while (off < sz) {
+                       /* fetch next folio */
+                       r->err = freader_get_folio(r, r->folio_off + folio_sz);
+                       if (r->err)
+                               return NULL;
+                       part_sz = min_t(u64, sz - off, folio_size(r->folio));
+                       memcpy(r->buf + off, r->addr, part_sz);
+                       off += part_sz;
+               }
 
                return r->buf;
        }
--

2.51.0

#7 lore raw

RFC PATCH v2 5/11 bpf: verifier: centralize const dynptr check in unmark_stack_slots_dynptr()

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Move the const dynptr check into unmark_stack_slots_dynptr() so callers don’t have to duplicate it. This puts the validation next to the code that manipulates dynptr stack slots and allows upcoming changes to reuse it directly.

---
 kernel/bpf/verifier.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
kernel/bpf/verifier.c +9 -8
index c908015b2d34..528782835c84 100644
@@ -828,6 +828,15 @@ static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_re
 	struct bpf_func_state *state = func(env, reg);
 	int spi, ref_obj_id, i;
 
+	/*
+	 * This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
+	 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
+	 * is safe to do directly.
+	 */
+	if (reg->type == CONST_PTR_TO_DYNPTR) {
+		verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
+		return -EFAULT;
+	}
 	spi = dynptr_get_spi(env, reg);
 	if (spi < 0)
 		return spi;
@@ -11505,15 +11514,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 
 	if (meta.release_regno) {
 		err = -EINVAL;
-		/* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot
-		 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr
-		 * is safe to do directly.
-		 */
 		if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) {
-			if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) {
-				verifier_bug(env, "CONST_PTR_TO_DYNPTR cannot be released");
-				return -EFAULT;
-			}
 			err = unmark_stack_slots_dynptr(env, &regs[meta.release_regno]);
 		} else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) {
 			u32 ref_obj_id = meta.ref_obj_id;
Signature · 1 line
2.51.0
#8 lore raw

RFC PATCH v2 6/11 bpf: mark vm_area_struct as trusted

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Mark vm_area_struct in bpf_find_vma callback as trusted, also mark its field struct file *vm_file as trusted or NULL.

---
 kernel/bpf/verifier.c                        | 8 +++++++-
 tools/testing/selftests/bpf/progs/find_vma.c | 6 ++++--
 2 files changed, 11 insertions(+), 3 deletions(-)
kernel/bpf/verifier.c +7 -1
index 528782835c84..a33ab6175651 100644
@@ -7102,6 +7102,10 @@ BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket) {
 	struct sock *sk;
 };
 
+BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct) {
+	struct file *vm_file;
+};
+
 static bool type_is_rcu(struct bpf_verifier_env *env,
 			struct bpf_reg_state *reg,
 			const char *field_name, u32 btf_id)
@@ -7133,6 +7137,7 @@ static bool type_is_trusted(struct bpf_verifier_env *env,
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));
 
 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
 }
@@ -7143,6 +7148,7 @@ static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
 {
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
 
 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
 					  "__safe_trusted_or_null");
@@ -10859,7 +10865,7 @@ static int set_find_vma_callback_state(struct bpf_verifier_env *env,
 	 */
 	callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1];
 
-	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID;
+	callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID | PTR_TRUSTED;
 	__mark_reg_known_zero(&callee->regs[BPF_REG_2]);
 	callee->regs[BPF_REG_2].btf =  btf_vmlinux;
 	callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA];
tools/testing/selftests/bpf/progs/find_vma.c +4 -2
index 02b82774469c..75b85ba3ab6a 100644
@@ -23,9 +23,11 @@ int find_addr_ret = -1;
 static long check_vma(struct task_struct *task, struct vm_area_struct *vma,
 		      struct callback_ctx *data)
 {
-	if (vma->vm_file)
+	struct file *file = vma->vm_file;
+
+	if (file)
 		bpf_probe_read_kernel_str(d_iname, DNAME_INLINE_LEN - 1,
-					  vma->vm_file->f_path.dentry->d_shortname.string);
+					  file->f_path.dentry->d_shortname.string);
 
 	/* check for VM_EXEC */
 	if (vma->vm_flags & VM_EXEC)
Signature · 1 line
2.51.0
maintainer
#9 lore raw

Re: [RFC PATCH v2 06/11] bpf: mark vm_area_struct as trusted

Quoted 4 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Mark vm_area_struct in bpf_find_vma callback as trusted, also mark its field struct file *vm_file as trusted or NULL.

This is because this struct is only returned by:

BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL)

and task iterator is RCU protected:

BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU)

or passed to a callback inside bpf_find_vma with a lock being held,

right?

[...]

Quoted 9 lines
kernel/bpf/verifier.c +1 -0
@@ -7133,6 +7137,7 @@ static bool type_is_trusted(struct bpf_verifier_env *env,
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));
 
 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
 }

kernel/bpf/verifier.c static bool type_is_trusted_or_null(struct bpf_verifier_env *env, · line 7154

Quoted 7 lines
kernel/bpf/verifier.c +1 -0
@@ -7143,6 +7148,7 @@ static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
 {
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
 	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
 
 	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
 					  "__safe_trusted_or_null");

Why changing both type_is_trusted() and type_is_trusted_or_null()? The only place where type_is_trusted_or_null() is called is here:

static int check_ptr_to_btf_access(...)

  {
		...
                if (type_is_trusted(env, reg, field_name, btf_id)) {
                        flag |= PTR_TRUSTED;
                } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
                        flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
		...

}

So, it seems that type_is_trusted() will always return true before type_is_trusted_or_null() is called.

[...]

#10 lore raw

Re: [RFC PATCH v2 06/11] bpf: mark vm_area_struct as trusted

Quoted 33 lines · Eduard Zingerman
Quoted 4 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Mark vm_area_struct in bpf_find_vma callback as trusted, also mark its field struct file *vm_file as trusted or NULL.

This is because this struct is only returned by:

BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL)

and task iterator is RCU protected:

BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU)

or passed to a callback inside bpf_find_vma with a lock being held,

right?

[...]

Quoted 14 lines
kernel/bpf/verifier.c +2 -0
@@ -7133,6 +7137,7 @@ static bool type_is_trusted(struct bpf_verifier_env *env,
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));
 
  	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
  }
@@ -7143,6 +7148,7 @@ static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
  {
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
 
Quoted 4 lines

kernel/bpf/verifier.c static bool type_is_trusted_or_null(struct bpf_verifier_env *env, · line 7154

Quoted 2 lines
kernel/bpf/verifier.c +0 -0
  	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
  					  "__safe_trusted_or_null");

Why changing both type_is_trusted() and type_is_trusted_or_null()? The only place where type_is_trusted_or_null() is called is here:

this is because type_is_trusted_or_null() check is only executed when:

```
else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
```
condition is hit. I understand this code as vm_area_struct has to be a trusted,
so that its field can be trusted or null (It did not work without adding vm_area_struct to trusted).
From verifier log I can see that the type for vm_file is correctly set by the verifier:
```
; struct file *file = vma->vm_file; @ file_reader.c:117
48: (79) r1 = *(u64 *)(r2 +88)        ; frame1: R1=trusted_ptr_or_null_file(id=1) R2=trusted_ptr_vm_area_struct() cb
```
Quoted 15 lines
   static int check_ptr_to_btf_access(...)
   {
		...
                 if (type_is_trusted(env, reg, field_name, btf_id)) {
                         flag |= PTR_TRUSTED;
                 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
                         flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
		...
   }

So, it seems that type_is_trusted() will always return true before type_is_trusted_or_null() is called.

[...]

maintainer
#11 lore raw

Re: [RFC PATCH v2 06/11] bpf: mark vm_area_struct as trusted

Quoted 48 lines · Mykyta Yatsenko
Quoted 33 lines · Eduard Zingerman
Quoted 4 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Mark vm_area_struct in bpf_find_vma callback as trusted, also mark its field struct file *vm_file as trusted or NULL.

This is because this struct is only returned by:

BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL)

and task iterator is RCU protected:

BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU)

or passed to a callback inside bpf_find_vma with a lock being held,

right?

[...]

Quoted 14 lines
kernel/bpf/verifier.c +2 -0
@@ -7133,6 +7137,7 @@ static bool type_is_trusted(struct bpf_verifier_env *env,
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));
 
  	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
  }
@@ -7143,6 +7148,7 @@ static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
  {
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
  	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
 
Quoted 4 lines

kernel/bpf/verifier.c static bool type_is_trusted_or_null(struct bpf_verifier_env *env, · line 7154

Quoted 2 lines
kernel/bpf/verifier.c +0 -0
  	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
  					  "__safe_trusted_or_null");

Why changing both type_is_trusted() and type_is_trusted_or_null()? The only place where type_is_trusted_or_null() is called is here:

this is because type_is_trusted_or_null() check is only executed when:

```
else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
```

condition is hit. I understand this code as vm_area_struct has to be a trusted,
so that its field can be trusted or null (It did not work without adding vm_area_struct to trusted).
From verifier log I can see that the type for vm_file is correctly set
by the verifier:

Quoted 5 lines
```
; struct file *file = vma->vm_file; @ file_reader.c:117
48: (79) r1 = *(u64 *)(r2 +88)        ; frame1:
R1=trusted_ptr_or_null_file(id=1) R2=trusted_ptr_vm_area_struct() cb
```

The test cases still verify, if I remove vm_area_struct from type_is_trusted():

--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -7143,7 +7143,7 @@ static bool type_is_trusted(struct bpf_verifier_env *env,

          BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
          BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
          BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));

- BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));
+ //BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));

          return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");

}

Quoted 14 lines
Quoted 14 lines
   static int check_ptr_to_btf_access(...)
   {
		...
                 if (type_is_trusted(env, reg, field_name, btf_id)) {
                         flag |= PTR_TRUSTED;
                 } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
                         flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
		...
   }

So, it seems that type_is_trusted() will always return true before type_is_trusted_or_null() is called.

[...]

#12 lore raw

Re: [RFC PATCH v2 06/11] bpf: mark vm_area_struct as trusted

Quoted 54 lines · Eduard Zingerman
Quoted 48 lines · Mykyta Yatsenko
Quoted 33 lines · Eduard Zingerman
Quoted 4 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Mark vm_area_struct in bpf_find_vma callback as trusted, also mark its field struct file *vm_file as trusted or NULL.

This is because this struct is only returned by:

BTF_ID_FLAGS(func, bpf_iter_task_vma_next, KF_ITER_NEXT | KF_RET_NULL)

and task iterator is RCU protected:

BTF_ID_FLAGS(func, bpf_iter_task_vma_new, KF_ITER_NEW | KF_RCU)

or passed to a callback inside bpf_find_vma with a lock being held,

right?

[...]

Quoted 14 lines
kernel/bpf/verifier.c +2 -0
@@ -7133,6 +7137,7 @@ static bool type_is_trusted(struct bpf_verifier_env *env,
   	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
   	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
   	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));
 
   	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
   }
@@ -7143,6 +7148,7 @@ static bool type_is_trusted_or_null(struct bpf_verifier_env *env,
   {
   	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct socket));
   	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct dentry));
+	BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED_OR_NULL(struct vm_area_struct));
 
Quoted 4 lines

kernel/bpf/verifier.c static bool type_is_trusted_or_null(struct bpf_verifier_env *env, · line 7154

Quoted 2 lines
kernel/bpf/verifier.c +0 -0
   	return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id,
   					  "__safe_trusted_or_null");

Why changing both type_is_trusted() and type_is_trusted_or_null()? The only place where type_is_trusted_or_null() is called is here:

this is because type_is_trusted_or_null() check is only executed when:

```
else if (is_trusted_reg(reg) || is_rcu_reg(reg)) {
```

condition is hit. I understand this code as vm_area_struct has to be a trusted,
so that its field can be trusted or null (It did not work without adding vm_area_struct to trusted).
From verifier log I can see that the type for vm_file is correctly set
by the verifier:

Quoted 5 lines
```
; struct file *file = vma->vm_file; @ file_reader.c:117
48: (79) r1 = *(u64 *)(r2 +88)        ; frame1:
R1=trusted_ptr_or_null_file(id=1) R2=trusted_ptr_vm_area_struct() cb
```
Quoted 2 lines

The test cases still verify, if I remove vm_area_struct from type_is_trusted():

Ack, you are right, this line should be removed.

Quoted 28 lines
   --- a/kernel/bpf/verifier.c
   +++ b/kernel/bpf/verifier.c
   @@ -7143,7 +7143,7 @@ static bool type_is_trusted(struct bpf_verifier_env *env,
           BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task));
           BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm));
           BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file));
   -       BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));
   +       //BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct vm_area_struct));

           return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted");
    }
Quoted 14 lines
Quoted 14 lines
    static int check_ptr_to_btf_access(...)
    {
		...
                  if (type_is_trusted(env, reg, field_name, btf_id)) {
                          flag |= PTR_TRUSTED;
                  } else if (type_is_trusted_or_null(env, reg, field_name, btf_id)) {
                          flag |= PTR_TRUSTED | PTR_MAYBE_NULL;
		...
    }

So, it seems that type_is_trusted() will always return true before type_is_trusted_or_null() is called.

[...]

#13 lore raw

RFC PATCH v2 7/11 bpf: add plumbing for file-backed dynptr

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Add the necessary verifier plumbing for the new file-backed dynptr type. Introduce two kfuncs for its lifecycle management:
* bpf_dynptr_from_file() for initialization
* bpf_dynptr_file_discard() for destruction

Currently there is no mechanism for kfunc to release dynptr, this patch add one:
* Dynptr release function sets meta->release_regno
* Call unmark_stack_slots_dynptr() if meta->release_regno is set and dynptr ref_obj_id is set as well.

---
 include/linux/bpf.h   |  7 ++++++-
 kernel/bpf/helpers.c  | 12 ++++++++++++
 kernel/bpf/log.c      |  2 ++
 kernel/bpf/verifier.c | 25 +++++++++++++++++++++++--
 4 files changed, 43 insertions(+), 3 deletions(-)
include/linux/bpf.h +6 -1
index 7daddb44c348..1d7d50d0c587 100644
@@ -792,12 +792,15 @@ enum bpf_type_flag {
 	/* DYNPTR points to skb_metadata_end()-skb_metadata_len() */
 	DYNPTR_TYPE_SKB_META	= BIT(19 + BPF_BASE_TYPE_BITS),
 
+	/* DYNPTR points to file */
+	DYNPTR_TYPE_FILE	= BIT(20 + BPF_BASE_TYPE_BITS),
+
 	__BPF_TYPE_FLAG_MAX,
 	__BPF_TYPE_LAST_FLAG	= __BPF_TYPE_FLAG_MAX - 1,
 };
 
 #define DYNPTR_TYPE_FLAG_MASK	(DYNPTR_TYPE_LOCAL | DYNPTR_TYPE_RINGBUF | DYNPTR_TYPE_SKB \
-				 | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META)
+				 | DYNPTR_TYPE_XDP | DYNPTR_TYPE_SKB_META | DYNPTR_TYPE_FILE)
 
 /* Max number of base types. */
 #define BPF_BASE_TYPE_LIMIT	(1UL << BPF_BASE_TYPE_BITS)
@@ -1385,6 +1388,8 @@ enum bpf_dynptr_type {
 	BPF_DYNPTR_TYPE_XDP,
 	/* Points to skb_metadata_end()-skb_metadata_len() */
 	BPF_DYNPTR_TYPE_SKB_META,
+	/* Underlying data is a file */
+	BPF_DYNPTR_TYPE_FILE,
 };
 
 int bpf_dynptr_check_size(u64 size);
kernel/bpf/helpers.c +12 -0
index 01541b24d3ee..3841c1c51b06 100644
@@ -4253,6 +4253,16 @@ __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b
 	return bpf_task_work_schedule(task, tw, map__map, callback, aux__prog, TWA_RESUME);
 }
 
+__bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+{
+	return 0;
+}
+
+__bpf_kfunc int bpf_dynptr_file_discard(struct bpf_dynptr *dynptr)
+{
+	return 0;
+}
+
 __bpf_kfunc_end_defs();
 
 static void bpf_task_work_cancel_scheduled(struct irq_work *irq_work)
@@ -4430,6 +4440,8 @@ BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU)
 BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_TRUSTED_ARGS)
 BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_TRUSTED_ARGS)
 BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_TRUSTED_ARGS)
+BTF_ID_FLAGS(func, bpf_dynptr_from_file, KF_TRUSTED_ARGS)
+BTF_ID_FLAGS(func, bpf_dynptr_file_discard, KF_TRUSTED_ARGS)
 BTF_KFUNCS_END(common_btf_ids)
 
 static const struct btf_kfunc_id_set common_kfunc_set = {
kernel/bpf/log.c +2 -0
index f50533169cc3..70221aafc35c 100644
@@ -500,6 +500,8 @@ const char *dynptr_type_str(enum bpf_dynptr_type type)
 		return "xdp";
 	case BPF_DYNPTR_TYPE_SKB_META:
 		return "skb_meta";
+	case BPF_DYNPTR_TYPE_FILE:
+		return "file";
 	case BPF_DYNPTR_TYPE_INVALID:
 		return "<invalid>";
 	default:
kernel/bpf/verifier.c +23 -2
index a33ab6175651..7bae81c631cf 100644
@@ -692,6 +692,8 @@ static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type)
 		return BPF_DYNPTR_TYPE_XDP;
 	case DYNPTR_TYPE_SKB_META:
 		return BPF_DYNPTR_TYPE_SKB_META;
+	case DYNPTR_TYPE_FILE:
+		return BPF_DYNPTR_TYPE_FILE;
 	default:
 		return BPF_DYNPTR_TYPE_INVALID;
 	}
@@ -710,6 +712,8 @@ static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
 		return DYNPTR_TYPE_XDP;
 	case BPF_DYNPTR_TYPE_SKB_META:
 		return DYNPTR_TYPE_SKB_META;
+	case BPF_DYNPTR_TYPE_FILE:
+		return DYNPTR_TYPE_FILE;
 	default:
 		return 0;
 	}
@@ -717,7 +721,7 @@ static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type)
 
 static bool dynptr_type_refcounted(enum bpf_dynptr_type type)
 {
-	return type == BPF_DYNPTR_TYPE_RINGBUF;
+	return type == BPF_DYNPTR_TYPE_RINGBUF || type == BPF_DYNPTR_TYPE_FILE;
 }
 
 static void __mark_dynptr_reg(struct bpf_reg_state *reg,
@@ -12288,6 +12292,8 @@ enum special_kfunc_type {
 	KF_bpf_res_spin_unlock,
 	KF_bpf_res_spin_lock_irqsave,
 	KF_bpf_res_spin_unlock_irqrestore,
+	KF_bpf_dynptr_from_file,
+	KF_bpf_dynptr_file_discard,
 	KF___bpf_trap,
 	KF_bpf_task_work_schedule_signal,
 	KF_bpf_task_work_schedule_resume,
@@ -12360,6 +12366,8 @@ BTF_ID(func, bpf_res_spin_lock)
 BTF_ID(func, bpf_res_spin_unlock)
 BTF_ID(func, bpf_res_spin_lock_irqsave)
 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
+BTF_ID(func, bpf_dynptr_from_file)
+BTF_ID(func, bpf_dynptr_file_discard)
 BTF_ID(func, __bpf_trap)
 BTF_ID(func, bpf_task_work_schedule_signal)
 BTF_ID(func, bpf_task_work_schedule_resume)
@@ -13323,6 +13331,11 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_
 				dynptr_arg_type |= DYNPTR_TYPE_XDP;
 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
 				dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
+			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
+				dynptr_arg_type |= DYNPTR_TYPE_FILE;
+			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
+				dynptr_arg_type |= DYNPTR_TYPE_FILE;
+				meta->release_regno = regno;
 			} else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
 				   (dynptr_arg_type & MEM_UNINIT)) {
 				enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
@@ -14003,7 +14016,15 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
 	 */
 	if (meta.release_regno) {
-		err = release_reference(env, regs[meta.release_regno].ref_obj_id);
+		struct bpf_reg_state *reg = &regs[meta.release_regno];
+
+		if (meta.initialized_dynptr.ref_obj_id) {
+			err = unmark_stack_slots_dynptr(env, reg);
+			if (err)
+				return err;
+		} else {
+			err = release_reference(env, reg->ref_obj_id);
+		}
 		if (err) {
 			verbose(env, "kfunc %s#%d reference has not been acquired before\n",
 				func_name, meta.func_id);
Signature · 1 line
2.51.0
maintainer Acked-by on v2 7/11
#14 lore raw

Re: [RFC PATCH v2 07/11] bpf: add plumbing for file-backed dynptr

Quoted 7 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Add the necessary verifier plumbing for the new file-backed dynptr type. Introduce two kfuncs for its lifecycle management:
* bpf_dynptr_from_file() for initialization
* bpf_dynptr_file_discard() for destruction

Quoted 8 lines

Currently there is no mechanism for kfunc to release dynptr, this patch add one:
* Dynptr release function sets meta->release_regno
* Call unmark_stack_slots_dynptr() if meta->release_regno is set and dynptr ref_obj_id is set as well.

---

[...]

#15 lore raw

Re: [RFC PATCH v2 07/11] bpf: add plumbing for file-backed dynptr

In reply to Mykyta Yatsenko
Quoted 21 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Add the necessary verifier plumbing for the new file-backed dynptr type. Introduce two kfuncs for its lifecycle management:
* bpf_dynptr_from_file() for initialization
* bpf_dynptr_file_discard() for destruction

Currently there is no mechanism for kfunc to release dynptr, this patch add one:
* Dynptr release function sets meta->release_regno
* Call unmark_stack_slots_dynptr() if meta->release_regno is set and dynptr ref_obj_id is set as well.

---
 include/linux/bpf.h   |  7 ++++++-
 kernel/bpf/helpers.c  | 12 ++++++++++++
 kernel/bpf/log.c      |  2 ++
 kernel/bpf/verifier.c | 25 +++++++++++++++++++++++--
 4 files changed, 43 insertions(+), 3 deletions(-)

[...]

kernel/bpf/helpers.c BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU) · line 4444

Quoted 7 lines

static void bpf_task_work_cancel_scheduled(struct irq_work *irq_work)

kernel/bpf/helpers.c +2 -0
@@ -4430,6 +4440,8 @@ BTF_ID_FLAGS(func, bpf_cgroup_read_xattr, KF_RCU)
 BTF_ID_FLAGS(func, bpf_stream_vprintk, KF_TRUSTED_ARGS)
 BTF_ID_FLAGS(func, bpf_task_work_schedule_signal, KF_TRUSTED_ARGS)
 BTF_ID_FLAGS(func, bpf_task_work_schedule_resume, KF_TRUSTED_ARGS)
+BTF_ID_FLAGS(func, bpf_dynptr_from_file, KF_TRUSTED_ARGS)
+BTF_ID_FLAGS(func, bpf_dynptr_file_discard, KF_TRUSTED_ARGS)

do we need KF_TRUSTED_ARGS for this one? dynptr passed into kfunc always has to be correct, so KF_TRUSTED_ARGS serves no purpose?

Quoted 3 lines
kernel/bpf/helpers.c +0 -0
 BTF_KFUNCS_END(common_btf_ids)
 
 static const struct btf_kfunc_id_set common_kfunc_set = {

[...]

Quoted 16 lines
kernel/bpf/verifier.c +5 -0
@@ -13323,6 +13331,11 @@ static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_
                                dynptr_arg_type |= DYNPTR_TYPE_XDP;
                        } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb_meta]) {
                                dynptr_arg_type |= DYNPTR_TYPE_SKB_META;
+                       } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
+                               dynptr_arg_type |= DYNPTR_TYPE_FILE;
+                       } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_file_discard]) {
+                               dynptr_arg_type |= DYNPTR_TYPE_FILE;
+                               meta->release_regno = regno;
                        } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] &&
                                   (dynptr_arg_type & MEM_UNINIT)) {
                                enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type;
@@ -14003,7 +14016,15 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
         * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now.
         */
        if (meta.release_regno) {

kernel/bpf/verifier.c static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, · line 14027

Quoted 10 lines
kernel/bpf/verifier.c +9 -1
-               err = release_reference(env, regs[meta.release_regno].ref_obj_id);
+               struct bpf_reg_state *reg = &regs[meta.release_regno];
+
+               if (meta.initialized_dynptr.ref_obj_id) {
+                       err = unmark_stack_slots_dynptr(env, reg);
+                       if (err)
+                               return err;
+               } else {
+                       err = release_reference(env, reg->ref_obj_id);
+               }

um... error handling is asymmetrical for no good reason. Move below if (err) verbose inside the else branch above, as it's release_reference-specific?

Quoted 6 lines
kernel/bpf/verifier.c +0 -1
                if (err) {
                        verbose(env, "kfunc %s#%d reference has not been acquired before\n",
                                func_name, meta.func_id);
--

2.51.0

#16 lore raw

RFC PATCH v2 8/11 bpf: add kfuncs and helpers support for file dynptrs

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Add support for file dynptr.

Introduce struct bpf_dynptr_file_impl to hold internal state for file dynptrs, with 64-bit size and offset support.

Introduce lifecycle management kfuncs:
- bpf_dynptr_from_file() for initialization
- bpf_dynptr_file_discard() for destruction

Extend existing helpers to support file dynptrs in:
- bpf_dynptr_read()
- bpf_dynptr_slice()

---
 kernel/bpf/helpers.c | 91 +++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 89 insertions(+), 2 deletions(-)
kernel/bpf/helpers.c +89 -2
index 3841c1c51b06..da83298bf916 100644
@@ -28,6 +28,7 @@
 #include <linux/verification.h>
 #include <linux/task_work.h>
 #include <linux/irq_work.h>
+#include <linux/buildid.h>
 
 #include "../../lib/kstrtox.h"
 
@@ -1657,6 +1658,13 @@ static const struct bpf_func_proto bpf_kptr_xchg_proto = {
 	.arg2_btf_id  = BPF_PTR_POISON,
 };
 
+struct bpf_dynptr_file_impl {
+	struct freader freader;
+	/* 64 bit offset and size overriding 32 bit ones in bpf_dynptr_kern */
+	u64 offset;
+	u64 size;
+};
+
 /* Since the upper 8 bits of dynptr->size is reserved, the
  * maximum supported size is 2^24 - 1.
  */
@@ -1687,13 +1695,36 @@ static enum bpf_dynptr_type bpf_dynptr_get_type(const struct bpf_dynptr_kern *pt
 
 u64 __bpf_dynptr_size(const struct bpf_dynptr_kern *ptr)
 {
+	if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) {
+		struct bpf_dynptr_file_impl *df = ptr->data;
+
+		return df->size;
+	}
+
 	return ptr->size & DYNPTR_SIZE_MASK;
 }
 
+static void bpf_dynptr_advance_offset(struct bpf_dynptr_kern *ptr, u64 off)
+{
+	if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) {
+		struct bpf_dynptr_file_impl *df = ptr->data;
+
+		df->offset += off;
+		return;
+	}
+	ptr->offset += off;
+}
+
 static void bpf_dynptr_set_size(struct bpf_dynptr_kern *ptr, u64 new_size)
 {
 	u32 metadata = ptr->size & ~DYNPTR_SIZE_MASK;
 
+	if (bpf_dynptr_get_type(ptr) == BPF_DYNPTR_TYPE_FILE) {
+		struct bpf_dynptr_file_impl *df = ptr->data;
+
+		df->size = new_size;
+		return;
+	}
 	ptr->size = (u32)new_size | metadata;
 }
 
@@ -1702,6 +1733,25 @@ int bpf_dynptr_check_size(u64 size)
 	return size > DYNPTR_MAX_SIZE ? -E2BIG : 0;
 }
 
+static int bpf_file_fetch_bytes(struct bpf_dynptr_file_impl *df, u64 offset, void *buf, u64 len)
+{
+	const void *ptr;
+
+	if (!buf)
+		return -EINVAL;
+
+	df->freader.buf = buf;
+	df->freader.buf_sz = len;
+	ptr = freader_fetch(&df->freader, offset + df->offset, len);
+	if (!ptr)
+		return df->freader.err;
+
+	if (ptr != buf) /* Force copying into the buffer */
+		memcpy(buf, ptr, len);
+
+	return 0;
+}
+
 void bpf_dynptr_init(struct bpf_dynptr_kern *ptr, void *data,
 		     enum bpf_dynptr_type type, u32 offset, u32 size)
 {
@@ -1782,6 +1832,8 @@ static int __bpf_dynptr_read(void *dst, u64 len, const struct bpf_dynptr_kern *s
 	case BPF_DYNPTR_TYPE_SKB_META:
 		memmove(dst, bpf_skb_meta_pointer(src->data, src->offset + offset), len);
 		return 0;
+	case BPF_DYNPTR_TYPE_FILE:
+		return bpf_file_fetch_bytes(src->data, offset, dst, len);
 	default:
 		WARN_ONCE(true, "bpf_dynptr_read: unknown dynptr type %d\n", type);
 		return -EFAULT;
@@ -2720,6 +2772,9 @@ __bpf_kfunc void *bpf_dynptr_slice(const struct bpf_dynptr *p, u64 offset,
 	}
 	case BPF_DYNPTR_TYPE_SKB_META:
 		return bpf_skb_meta_pointer(ptr->data, ptr->offset + offset);
+	case BPF_DYNPTR_TYPE_FILE:
+		err = bpf_file_fetch_bytes(ptr->data, offset, buffer__opt, buffer__szk);
+		return err ? NULL : buffer__opt;
 	default:
 		WARN_ONCE(true, "unknown dynptr type %d\n", type);
 		return NULL;
@@ -2814,7 +2869,7 @@ __bpf_kfunc int bpf_dynptr_adjust(const struct bpf_dynptr *p, u64 start, u64 end
 	if (start > size || end > size)
 		return -ERANGE;
 
-	ptr->offset += start;
+	bpf_dynptr_advance_offset(ptr, start);
 	bpf_dynptr_set_size(ptr, end - start);
 
 	return 0;
@@ -4253,13 +4308,45 @@ __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b
 	return bpf_task_work_schedule(task, tw, map__map, callback, aux__prog, TWA_RESUME);
 }
 
-__bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+static int make_file_dynptr(struct file *file, u32 flags, bool may_sleep,
+			    struct bpf_dynptr_kern *ptr)
 {
+	struct bpf_dynptr_file_impl *state;
+
+	/* flags is currently unsupported */
+	if (flags) {
+		bpf_dynptr_set_null(ptr);
+		return -EINVAL;
+	}
+
+	state = bpf_mem_alloc(&bpf_global_ma, sizeof(struct bpf_dynptr_file_impl));
+	if (!state) {
+		bpf_dynptr_set_null(ptr);
+		return -ENOMEM;
+	}
+	state->offset = 0;
+	state->size = U64_MAX; /* Don't restrict size, as file may change anyways */
+	freader_init_from_file(&state->freader, NULL, 0, file, may_sleep);
+	bpf_dynptr_init(ptr, state, BPF_DYNPTR_TYPE_FILE, 0, 0);
+	bpf_dynptr_set_rdonly(ptr);
 	return 0;
 }
 
+__bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+{
+	return make_file_dynptr(file, flags, false, (struct bpf_dynptr_kern *)ptr__uninit);
+}
+
 __bpf_kfunc int bpf_dynptr_file_discard(struct bpf_dynptr *dynptr)
 {
+	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)dynptr;
+	struct bpf_dynptr_file_impl *df = ptr->data;
+
+	if (!df)
+		return 0;
+
+	freader_cleanup(&df->freader);
+	bpf_mem_free(&bpf_global_ma, df);
 	return 0;
 }
 
Signature · 1 line
2.51.0
maintainer
#17 lore raw

Re: [RFC PATCH v2 08/11] bpf: add kfuncs and helpers support for file dynptrs

On Wed, 2025-10-15 at 17:11 +0100, Mykyta Yatsenko wrote:

Overall, lgtm.

[...]

Quoted 13 lines
kernel/bpf/helpers.c +7 -1
@@ -4253,13 +4308,45 @@ __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b
 	return bpf_task_work_schedule(task, tw, map__map, callback, aux__prog, TWA_RESUME);
 }
 
-__bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+static int make_file_dynptr(struct file *file, u32 flags, bool may_sleep,
+			    struct bpf_dynptr_kern *ptr)
 {
+	struct bpf_dynptr_file_impl *state;
+
+	/* flags is currently unsupported */
+	if (flags) {
+		bpf_dynptr_set_null(ptr);

kernel/bpf/helpers.c __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b · line 4328

Quoted 10 lines
kernel/bpf/helpers.c +10 -0
+		return -EINVAL;
+	}
+
+	state = bpf_mem_alloc(&bpf_global_ma, sizeof(struct bpf_dynptr_file_impl));
+	if (!state) {
+		bpf_dynptr_set_null(ptr);
+		return -ENOMEM;
+	}
+	state->offset = 0;
+	state->size = U64_MAX; /* Don't restrict size, as file may change anyways */

If ->size field can't be relied upon, why tracking it at all? Why not just return U64_MAX from __bpf_dynptr_size()?

Quoted 5 lines
kernel/bpf/helpers.c +3 -0
+	freader_init_from_file(&state->freader, NULL, 0, file, may_sleep);
+	bpf_dynptr_init(ptr, state, BPF_DYNPTR_TYPE_FILE, 0, 0);
+	bpf_dynptr_set_rdonly(ptr);
 	return 0;
 }

[...]

#18 lore raw

Re: [RFC PATCH v2 08/11] bpf: add kfuncs and helpers support for file dynptrs

Quoted 23 lines · Eduard Zingerman

On Wed, 2025-10-15 at 17:11 +0100, Mykyta Yatsenko wrote:

Overall, lgtm.

[...]

Quoted 17 lines
kernel/bpf/helpers.c +11 -1
@@ -4253,13 +4308,45 @@ __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b
  	return bpf_task_work_schedule(task, tw, map__map, callback, aux__prog, TWA_RESUME);
  }
 
-__bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+static int make_file_dynptr(struct file *file, u32 flags, bool may_sleep,
+			    struct bpf_dynptr_kern *ptr)
  {
+	struct bpf_dynptr_file_impl *state;
+
+	/* flags is currently unsupported */
+	if (flags) {
+		bpf_dynptr_set_null(ptr);
+		return -EINVAL;
+	}
+
+	state = bpf_mem_alloc(&bpf_global_ma, sizeof(struct bpf_dynptr_file_impl));
Quoted 8 lines

kernel/bpf/helpers.c __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b · line 4328

Quoted 6 lines
kernel/bpf/helpers.c +6 -0
+	if (!state) {
+		bpf_dynptr_set_null(ptr);
+		return -ENOMEM;
+	}
+	state->offset = 0;
+	state->size = U64_MAX; /* Don't restrict size, as file may change anyways */

If ->size field can't be relied upon, why tracking it at all? Why not just return U64_MAX from __bpf_dynptr_size()?

Good point. This is a little bit ugly part of the implementation bpf_dynptr_adjust() is still implemented for the file dynptr (for the sake of supporting generic dynptr API), and it sets the size, because it makes sense that bpf_dynptr_adjust(start, end) leaves dynptr with size = end - start.

Quoted 7 lines
Quoted 6 lines
kernel/bpf/helpers.c +3 -0
+	freader_init_from_file(&state->freader, NULL, 0, file, may_sleep);
+	bpf_dynptr_init(ptr, state, BPF_DYNPTR_TYPE_FILE, 0, 0);
+	bpf_dynptr_set_rdonly(ptr);
  	return 0;
  }

[...]

maintainer
#19 lore raw

Re: [RFC PATCH v2 08/11] bpf: add kfuncs and helpers support for file dynptrs

Quoted 34 lines · Mykyta Yatsenko
Quoted 24 lines · Eduard Zingerman

On Wed, 2025-10-15 at 17:11 +0100, Mykyta Yatsenko wrote:

Overall, lgtm.

[...]

Quoted 18 lines
kernel/bpf/helpers.c +12 -1
@@ -4253,13 +4308,45 @@ __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b
  	return bpf_task_work_schedule(task, tw, map__map, callback, aux__prog, TWA_RESUME);
  }
 
-__bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+static int make_file_dynptr(struct file *file, u32 flags, bool may_sleep,
+			    struct bpf_dynptr_kern *ptr)
  {
+	struct bpf_dynptr_file_impl *state;
+
+	/* flags is currently unsupported */
+	if (flags) {
+		bpf_dynptr_set_null(ptr);
+		return -EINVAL;
+	}
+
+	state = bpf_mem_alloc(&bpf_global_ma, sizeof(struct bpf_dynptr_file_impl));
+	if (!state) {
Quoted 8 lines

kernel/bpf/helpers.c __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b · line 4328

Quoted 5 lines
kernel/bpf/helpers.c +5 -0
+		bpf_dynptr_set_null(ptr);
+		return -ENOMEM;
+	}
+	state->offset = 0;
+	state->size = U64_MAX; /* Don't restrict size, as file may change anyways */

If ->size field can't be relied upon, why tracking it at all? Why not just return U64_MAX from __bpf_dynptr_size()?

Quoted 7 lines

Good point. This is a little bit ugly part of the implementation bpf_dynptr_adjust()
is still implemented for the file dynptr (for the sake of supporting generic dynptr API),
 and it sets the size, because it makes sense that
bpf_dynptr_adjust(start, end) leaves dynptr
with size = end - start.

I see, makes sense.
Thank you for explaining.

#20 lore raw

Re: [RFC PATCH v2 08/11] bpf: add kfuncs and helpers support for file dynptrs

Quoted 44 lines · Eduard Zingerman
Quoted 34 lines · Mykyta Yatsenko
Quoted 24 lines · Eduard Zingerman

On Wed, 2025-10-15 at 17:11 +0100, Mykyta Yatsenko wrote:

Overall, lgtm.

[...]

Quoted 18 lines
kernel/bpf/helpers.c +12 -1
@@ -4253,13 +4308,45 @@ __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b
          return bpf_task_work_schedule(task, tw, map__map, callback, aux__prog, TWA_RESUME);
  }
 
-__bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+static int make_file_dynptr(struct file *file, u32 flags, bool may_sleep,
+                     struct bpf_dynptr_kern *ptr)
  {
+ struct bpf_dynptr_file_impl *state;
+
+ /* flags is currently unsupported */
+ if (flags) {
+         bpf_dynptr_set_null(ptr);
+         return -EINVAL;
+ }
+
+ state = bpf_mem_alloc(&bpf_global_ma, sizeof(struct bpf_dynptr_file_impl));
+ if (!state) {
Quoted 8 lines

kernel/bpf/helpers.c __bpf_kfunc int bpf_task_work_schedule_resume(struct task_struct *task, struct b · line 4328

Quoted 5 lines
kernel/bpf/helpers.c +5 -0
+         bpf_dynptr_set_null(ptr);
+         return -ENOMEM;
+ }
+ state->offset = 0;
+ state->size = U64_MAX; /* Don't restrict size, as file may change anyways */

If ->size field can't be relied upon, why tracking it at all? Why not just return U64_MAX from __bpf_dynptr_size()?

Quoted 7 lines

Good point. This is a little bit ugly part of the implementation bpf_dynptr_adjust()
is still implemented for the file dynptr (for the sake of supporting generic dynptr API),
and it sets the size, because it makes sense that
bpf_dynptr_adjust(start, end) leaves dynptr
with size = end - start.

Quoted 2 lines

I see, makes sense.
Thank you for explaining.

Um... Not sure why it's ugly :) but I want to elaborate a bit (and let's include those details in the commit itself, please).

For all dynptrs before file dynptr size serves double purpose. On construction, it denotes actual size limitation beyond which it would be unsafe to access contents. But it's also possible with bpf_dynptr_adjust(), especially in combination with bpf_dynptr_clone(), to create a more restricted view on the original dynptr, which will artificially limit access to portions of dynptr contents. Just like, e.g., in Go or Rust you can have an underlying bigger array, but then create a smaller slice on top. Accessing contents beyond imposed slice boundaries is invalid.

Same idea here as well. But for file dynptr, determining size initially is a) not necessary (freader never knows the size, actually, just attempts to get folio for given file offset) and b) if we ever support creating file dynptr for non-locked binary (unlike vma's vm_file, for example), then this size can increase or shrink anyways. So initial size doesn't matter for file dynptr.

But the artificially limited size with bpf_dynptr_adjust() does make sense to keep (you can imagine generic dynptr-based content hashing functions, and you'll pass a small section of file for hashing into it using bpf_dynptr_clone() + bpf_dynptr_adjust()). Which is why we track it. And setting it to zero would be inconvenient for all the above reasons, so U64_MAX is a better initial value (still prevents all the potential size+offset overflows, without any extra logic).

#21 lore raw

RFC PATCH v2 9/11 bpf: verifier: refactor kfunc specialization

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Move kfunc specialization (function address substitution) to later stage of verification to support a new use case, where we need to take into consideration whether kfunc is called in sleepable context.

Minor refactoring in add_kfunc_call(), making sure that if function fails, kfunc desc is not added to tab->descs (previously it could be added or not, depending on what failed).

---
 kernel/bpf/verifier.c | 99 ++++++++++++++++++++++++-------------------
 1 file changed, 56 insertions(+), 43 deletions(-)
kernel/bpf/verifier.c +56 -43
index 7bae81c631cf..f9f7151eaf1f 100644
@@ -209,8 +209,6 @@ static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
 static int ref_set_non_owning(struct bpf_verifier_env *env,
 			      struct bpf_reg_state *reg);
-static void specialize_kfunc(struct bpf_verifier_env *env,
-			     u32 func_id, u16 offset, unsigned long *addr);
 static bool is_trusted_reg(const struct bpf_reg_state *reg);
 
 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux)
@@ -3126,6 +3124,10 @@ struct bpf_kfunc_btf_tab {
 	u32 nr_descs;
 };
 
+static unsigned long kfunc_call_imm(unsigned long func_addr, u32 func_id);
+
+static void specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc);
+
 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
 {
 	const struct bpf_kfunc_desc *d0 = a;
@@ -3143,7 +3145,7 @@ static int kfunc_btf_cmp_by_off(const void *a, const void *b)
 	return d0->offset - d1->offset;
 }
 
-static const struct bpf_kfunc_desc *
+static struct bpf_kfunc_desc *
 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset)
 {
 	struct bpf_kfunc_desc desc = {
@@ -3266,6 +3268,7 @@ static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
 {
 	const struct btf_type *func, *func_proto;
 	struct bpf_kfunc_btf_tab *btf_tab;
+	struct btf_func_model func_model;
 	struct bpf_kfunc_desc_tab *tab;
 	struct bpf_prog_aux *prog_aux;
 	struct bpf_kfunc_desc *desc;
@@ -3355,19 +3358,6 @@ static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
 			func_name);
 		return -EINVAL;
 	}
-	specialize_kfunc(env, func_id, offset, &addr);
-
-	if (bpf_jit_supports_far_kfunc_call()) {
-		call_imm = func_id;
-	} else {
-		call_imm = BPF_CALL_IMM(addr);
-		/* Check whether the relative offset overflows desc->imm */
-		if ((unsigned long)(s32)call_imm != call_imm) {
-			verbose(env, "address of kernel function %s is out of range\n",
-				func_name);
-			return -EINVAL;
-		}
-	}
 
 	if (bpf_dev_bound_kfunc_id(func_id)) {
 		err = bpf_dev_bound_kfunc_check(&env->log, prog_aux);
@@ -3375,18 +3365,29 @@ static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset)
 			return err;
 	}
 
+	err = btf_distill_func_proto(&env->log, desc_btf,
+				     func_proto, func_name,
+				     &func_model);
+	if (err)
+		return err;
+
+	call_imm = kfunc_call_imm(addr, func_id);
+	/* Check whether the relative offset overflows desc->imm */
+	if ((unsigned long)(s32)call_imm != call_imm) {
+		verbose(env, "address of kernel function %s is out of range\n",
+			func_name);
+		return -EINVAL;
+	}
+
 	desc = &tab->descs[tab->nr_descs++];
 	desc->func_id = func_id;
 	desc->imm = call_imm;
 	desc->offset = offset;
 	desc->addr = addr;
-	err = btf_distill_func_proto(&env->log, desc_btf,
-				     func_proto, func_name,
-				     &desc->func_model);
-	if (!err)
-		sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
-		     kfunc_desc_cmp_by_id_off, NULL);
-	return err;
+	desc->func_model = func_model;
+	sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]),
+	     kfunc_desc_cmp_by_id_off, NULL);
+	return 0;
 }
 
 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b)
@@ -21860,47 +21861,57 @@ static int fixup_call_args(struct bpf_verifier_env *env)
 	return err;
 }
 
+static unsigned long kfunc_call_imm(unsigned long func_addr, u32 func_id)
+{
+	if (bpf_jit_supports_far_kfunc_call())
+		return func_id;
+
+	return BPF_CALL_IMM(func_addr);
+}
+
 /* replace a generic kfunc with a specialized version if necessary */
-static void specialize_kfunc(struct bpf_verifier_env *env,
-			     u32 func_id, u16 offset, unsigned long *addr)
+static void specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc)
 {
 	struct bpf_prog *prog = env->prog;
 	bool seen_direct_write;
 	void *xdp_kfunc;
 	bool is_rdonly;
+	u32 func_id = desc->func_id;
+	u16 offset = desc->offset;
+	unsigned long addr = 0;
+
+	if (offset) /* return if module BTF is used */
+		return;
 
 	if (bpf_dev_bound_kfunc_id(func_id)) {
 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
-		if (xdp_kfunc) {
-			*addr = (unsigned long)xdp_kfunc;
-			return;
-		}
+		if (xdp_kfunc)
+			addr = (unsigned long)xdp_kfunc;
 		/* fallback to default kfunc when not supported by netdev */
-	}
-
-	if (offset)
-		return;
-
-	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
+	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
 		seen_direct_write = env->seen_direct_write;
 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
 
 		if (is_rdonly)
-			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
+			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
 
 		/* restore env->seen_direct_write to its original value, since
 		 * may_access_direct_pkt_data mutates it
 		 */
 		env->seen_direct_write = seen_direct_write;
+	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
+		if (bpf_lsm_has_d_inode_locked(prog))
+			addr = (unsigned long)bpf_set_dentry_xattr_locked;
+	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
+		if (bpf_lsm_has_d_inode_locked(prog))
+			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
 	}
 
-	if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] &&
-	    bpf_lsm_has_d_inode_locked(prog))
-		*addr = (unsigned long)bpf_set_dentry_xattr_locked;
+	if (!addr) /* Nothing to patch with */
+		return;
 
-	if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] &&
-	    bpf_lsm_has_d_inode_locked(prog))
-		*addr = (unsigned long)bpf_remove_dentry_xattr_locked;
+	desc->imm = kfunc_call_imm(addr, func_id);
+	desc->addr = addr;
 }
 
 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
@@ -21923,7 +21934,7 @@ static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,
 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			    struct bpf_insn *insn_buf, int insn_idx, int *cnt)
 {
-	const struct bpf_kfunc_desc *desc;
+	struct bpf_kfunc_desc *desc;
 
 	if (!insn->imm) {
 		verbose(env, "invalid kernel function call not eliminated in verifier pass\n");
@@ -21943,6 +21954,8 @@ static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		return -EFAULT;
 	}
 
+	specialize_kfunc(env, desc);
+
 	if (!bpf_jit_supports_far_kfunc_call())
 		insn->imm = BPF_CALL_IMM(desc->addr);
 	if (insn->off)
Signature · 1 line
2.51.0
maintainer
#22 lore raw

Re: [RFC PATCH v2 09/11] bpf: verifier: refactor kfunc specialization

Quoted 6 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Move kfunc specialization (function address substitution) to later stage of verification to support a new use case, where we need to take into consideration whether kfunc is called in sleepable context.

Quoted 6 lines

Minor refactoring in add_kfunc_call(), making sure that if function fails, kfunc desc is not added to tab->descs (previously it could be added or not, depending on what failed).

---

Lgtm, but I think ai caught a real bug.

[...]

Quoted 43 lines
kernel/bpf/verifier.c +14 -11
+static void specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc)
 {
 	struct bpf_prog *prog = env->prog;
 	bool seen_direct_write;
 	void *xdp_kfunc;
 	bool is_rdonly;
+	u32 func_id = desc->func_id;
+	u16 offset = desc->offset;
+	unsigned long addr = 0;
+
+	if (offset) /* return if module BTF is used */
+		return;
 
 	if (bpf_dev_bound_kfunc_id(func_id)) {
 		xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id);
-		if (xdp_kfunc) {
-			*addr = (unsigned long)xdp_kfunc;
-			return;
-		}
+		if (xdp_kfunc)
+			addr = (unsigned long)xdp_kfunc;
 		/* fallback to default kfunc when not supported by netdev */
-	}
-
-	if (offset)
-		return;
-
-	if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
+	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) {
 		seen_direct_write = env->seen_direct_write;
 		is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE);
 
 		if (is_rdonly)
-			*addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
+			addr = (unsigned long)bpf_dynptr_from_skb_rdonly;
 
 		/* restore env->seen_direct_write to its original value, since
 		 * may_access_direct_pkt_data mutates it
 		 */
 		env->seen_direct_write = seen_direct_write;
+	} else if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr]) {
+		if (bpf_lsm_has_d_inode_locked(prog))
+			addr = (unsigned long)bpf_set_dentry_xattr_locked;

kernel/bpf/verifier.c static int fixup_call_args(struct bpf_verifier_env *env) · line 21911

Quoted 10 lines
kernel/bpf/verifier.c +5 -3
+	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
+		if (bpf_lsm_has_d_inode_locked(prog))
+			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
 	}
 
-	if (func_id == special_kfunc_list[KF_bpf_set_dentry_xattr] &&
-	    bpf_lsm_has_d_inode_locked(prog))
-		*addr = (unsigned long)bpf_set_dentry_xattr_locked;
+	if (!addr) /* Nothing to patch with */
+		return;

Nit: move this to a final else branch?

        } else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] {
                ...
        } else {
                return
        }

kernel/bpf/verifier.c static int fixup_call_args(struct bpf_verifier_env *env) · line 21914

Quoted 6 lines
kernel/bpf/verifier.c +2 -3
-	if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr] &&
-	    bpf_lsm_has_d_inode_locked(prog))
-		*addr = (unsigned long)bpf_remove_dentry_xattr_locked;
+	desc->imm = kfunc_call_imm(addr, func_id);
+	desc->addr = addr;

I think ai review is right here, overflow check after specialization is missing.

Quoted 3 lines

}

static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux,

[...]

#23 lore raw

RFC PATCH v2 10/11 bpf: dispatch to sleepable file dynptr

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

File dynptr reads may sleep when the requested folios are not in the page cache. To avoid sleeping in non-sleepable contexts while still supporting valid sleepable use, given that dynptrs are non-sleepable by default, enable sleeping only when bpf_dynptr_from_file() is invoked from a sleepable context.

This change:
* Introduces a sleepable constructor: bpf_dynptr_from_file_sleepable()
* Override non-sleepable constructor with sleepable if it's always called in sleepable context

---
 include/linux/bpf.h   |  3 +++
 kernel/bpf/helpers.c  |  5 +++++
 kernel/bpf/verifier.c | 11 ++++++++---
 3 files changed, 16 insertions(+), 3 deletions(-)
include/linux/bpf.h +3 -0
index 1d7d50d0c587..73fca44a3dfa 100644
@@ -670,6 +670,9 @@ static inline bool bpf_map_has_internal_structs(struct bpf_map *map)
 
 void bpf_map_free_internal_structs(struct bpf_map *map, void *obj);
 
+int bpf_dynptr_from_file_sleepable(struct file *file, u32 flags,
+				   struct bpf_dynptr *ptr__uninit);
+
 extern const struct bpf_map_ops bpf_map_offload_ops;
 
 /* bpf_type_flag contains a set of flags that are applicable to the values of
kernel/bpf/helpers.c +5 -0
index da83298bf916..42e2add35589 100644
@@ -4337,6 +4337,11 @@ __bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dy
 	return make_file_dynptr(file, flags, false, (struct bpf_dynptr_kern *)ptr__uninit);
 }
 
+int bpf_dynptr_from_file_sleepable(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+{
+	return make_file_dynptr(file, flags, true, (struct bpf_dynptr_kern *)ptr__uninit);
+}
+
 __bpf_kfunc int bpf_dynptr_file_discard(struct bpf_dynptr *dynptr)
 {
 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)dynptr;
kernel/bpf/verifier.c +8 -3
index f9f7151eaf1f..673923ecd465 100644
@@ -3126,7 +3126,8 @@ struct bpf_kfunc_btf_tab {
 
 static unsigned long kfunc_call_imm(unsigned long func_addr, u32 func_id);
 
-static void specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc);
+static void specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc,
+			     int insn_idx);
 
 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b)
 {
@@ -21870,7 +21871,8 @@ static unsigned long kfunc_call_imm(unsigned long func_addr, u32 func_id)
 }
 
 /* replace a generic kfunc with a specialized version if necessary */
-static void specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc)
+static void specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc *desc,
+			     int insn_idx)
 {
 	struct bpf_prog *prog = env->prog;
 	bool seen_direct_write;
@@ -21905,6 +21907,9 @@ static void specialize_kfunc(struct bpf_verifier_env *env, struct bpf_kfunc_desc
 	} else if (func_id == special_kfunc_list[KF_bpf_remove_dentry_xattr]) {
 		if (bpf_lsm_has_d_inode_locked(prog))
 			addr = (unsigned long)bpf_remove_dentry_xattr_locked;
+	} else if (func_id == special_kfunc_list[KF_bpf_dynptr_from_file]) {
+		if (!env->insn_aux_data[insn_idx].non_sleepable)
+			addr = (unsigned long)bpf_dynptr_from_file_sleepable;
 	}
 
 	if (!addr) /* Nothing to patch with */
@@ -21954,7 +21959,7 @@ static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		return -EFAULT;
 	}
 
-	specialize_kfunc(env, desc);
+	specialize_kfunc(env, desc, insn_idx);
 
 	if (!bpf_jit_supports_far_kfunc_call())
 		insn->imm = BPF_CALL_IMM(desc->addr);
Signature · 1 line
2.51.0
maintainer Acked-by on v2 10/11
#24 lore raw

Re: [RFC PATCH v2 10/11] bpf: dispatch to sleepable file dynptr

Quoted 8 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

File dynptr reads may sleep when the requested folios are not in the page cache. To avoid sleeping in non-sleepable contexts while still supporting valid sleepable use, given that dynptrs are non-sleepable by default, enable sleeping only when bpf_dynptr_from_file() is invoked from a sleepable context.

Quoted 7 lines

This change:
* Introduces a sleepable constructor: bpf_dynptr_from_file_sleepable()
* Override non-sleepable constructor with sleepable if it's always called in sleepable context

---

[...]

kernel/bpf/helpers.c __bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dy · line 4342

Quoted 7 lines
kernel/bpf/helpers.c +3 -0
@@ -4337,6 +4337,11 @@ __bpf_kfunc int bpf_dynptr_from_file(struct file *file, u32 flags, struct bpf_dy
 	return make_file_dynptr(file, flags, false, (struct bpf_dynptr_kern *)ptr__uninit);
 }
 
+int bpf_dynptr_from_file_sleepable(struct file *file, u32 flags, struct bpf_dynptr *ptr__uninit)
+{
+	return make_file_dynptr(file, flags, true, (struct bpf_dynptr_kern *)ptr__uninit);

^^^^
Having may_sleep as a flag seems more logical,
but unfortunately, this will make the verifier's job much harder. Hence, I think this patch is fine as it is.

Quoted 5 lines
kernel/bpf/helpers.c +2 -0
+}
+
 __bpf_kfunc int bpf_dynptr_file_discard(struct bpf_dynptr *dynptr)
 {
 	struct bpf_dynptr_kern *ptr = (struct bpf_dynptr_kern *)dynptr;

[...]

#25 lore raw

RFC PATCH v2 11/11 selftests/bpf: add file dynptr tests

In reply to Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Introducing selftests for validating file-backed dynptr works as expected.
* validate implementation supports dynptr slice and read operations
* validate destructors should be paired with initializers
* validate sleepable progs can page in.

---
 .../selftests/bpf/prog_tests/file_reader.c    | 114 +++++++++++++
 .../testing/selftests/bpf/progs/file_reader.c | 157 ++++++++++++++++++
 2 files changed, 271 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/file_reader.c
 create mode 100644 tools/testing/selftests/bpf/progs/file_reader.c
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +114 -0
new file mode 100644
index 000000000000..f4f52dfcb2a5
@@ -0,0 +1,114 @@
+// SPDX-License-Identifier: GPL-2.0
+/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
+
+#include <test_progs.h>
+#include <network_helpers.h>
+#include "file_reader.skel.h"
+#include <dlfcn.h>
+#include <sys/mman.h>
+
+const char *user_ptr = "hello world";
+char file_contents[256000];
+
+void *get_executable_base_addr(void)
+{
+	Dl_info info;
+
+	if (!dladdr((void *)&get_executable_base_addr, &info)) {
+		fprintf(stderr, "dladdr failed\n");
+		return NULL;
+	}
+
+	return info.dli_fbase;
+}
+
+static int initialize_file_contents(void)
+{
+	int fd, page_sz = sysconf(_SC_PAGESIZE);
+	ssize_t n = 0, cur, off;
+	void *addr;
+
+	fd = open("/proc/self/exe", O_RDONLY);
+	if (!ASSERT_GT(fd, 0, "Open /proc/self/exe\n"))
+		return 1;
+
+	do {
+		cur = read(fd, file_contents + n, sizeof(file_contents) - n);
+		if (!ASSERT_GT(cur, 0, "read success"))
+			break;
+		n += cur;
+	} while (n < sizeof(file_contents));
+
+	close(fd);
+
+	if (!ASSERT_EQ(n, sizeof(file_contents), "Read /proc/self/exe\n"))
+		return 1;
+
+	addr = get_executable_base_addr();
+	if (!ASSERT_NEQ(addr, NULL, "get executable address"))
+		return 1;
+
+	/* page-align base file address */
+	addr = (void *)((unsigned long)addr & ~(page_sz - 1));
+
+	for (off = 0; off < sizeof(file_contents); off += page_sz) {
+		if (!ASSERT_OK(madvise(addr + off, page_sz, MADV_PAGEOUT),
+			       "madvise pageout"))
+			return errno;
+	}
+
+	return 0;
+}
+
+static void run_test(const char *prog_name)
+{
+	struct file_reader *skel;
+	struct bpf_program *prog;
+	int err;
+	char data[256];
+	LIBBPF_OPTS(bpf_test_run_opts, opts, .data_in = &data, .repeat = 1,
+		    .data_size_in = sizeof(data));
+
+	err = initialize_file_contents();
+	if (!ASSERT_OK(err, "initialize file contents"))
+		return;
+
+	skel = file_reader__open();
+	if (!ASSERT_OK_PTR(skel, "file_reader__open"))
+		return;
+
+	bpf_object__for_each_program(prog, skel->obj) {
+		if (strcmp(bpf_program__name(prog), prog_name) == 0)
+			bpf_program__set_autoload(prog, true);
+		else
+			bpf_program__set_autoload(prog, false);
+	}
+
+	skel->bss->user_buf = file_contents;
+	skel->rodata->user_buf_sz = sizeof(file_contents);
+	skel->bss->pid = getpid();
+	skel->bss->user_ptr = (char *)user_ptr;
+
+	err = file_reader__load(skel);
+	if (!ASSERT_OK(err, "file_reader__load"))
+		goto cleanup;
+
+	err = file_reader__attach(skel);
+	if (!ASSERT_OK(err, "file_reader__attach"))
+		goto cleanup;
+
+	getpid();
+
+	ASSERT_EQ(skel->bss->err, 0, "err");
+cleanup:
+	file_reader__destroy(skel);
+}
+
+void test_file_reader(void)
+{
+	if (test__start_subtest("on_getpid_expect_fault"))
+		run_test("on_getpid_expect_fault");
+
+	if (test__start_subtest("on_getpid_validate_file_read"))
+		run_test("on_getpid_validate_file_read");
+}
tools/testing/selftests/bpf/progs/file_reader.c new file +157 -0

157 lines not on this page · raw message

Signature · 1 line
2.51.0
maintainer
#26 lore raw

Re: [RFC PATCH v2 11/11] selftests/bpf: add file dynptr tests

Quoted 10 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Introducing selftests for validating file-backed dynptr works as expected.
* validate implementation supports dynptr slice and read operations
* validate destructors should be paired with initializers
* validate sleepable progs can page in.

---

I get the following error report when running this test on top of [1].

[1] 48a97ffc6c82 ("bpf: Consistently use bpf_rcu_lock_held() everywhere")

---

[   11.790725] ============================================
[   11.790999] WARNING: possible recursive locking detected
[   11.791195] 6.17.0-gbfd75250bee0 #1 Tainted: G           OE      
[   11.791418] --------------------------------------------
[   11.791446] test_progs/153 is trying to acquire lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446] 
[   11.791446] but task is already holding lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446] 
[   11.791446] other info that might help us debug this:
[   11.791446]  Possible unsafe locking scenario:
[   11.791446] 
[   11.791446]        CPU0
[   11.791446]        ----
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446] 
[   11.791446]  *** DEADLOCK ***
[   11.791446] 
[   11.791446]  May be due to missing lock nesting notation
[   11.791446] 
[   11.791446] 2 locks held by test_progs/153:
[   11.791446]  #0: ffffffff85a73be0 (rcu_read_lock_trace){....}-{0:0}, at: bpf_task_work_callback (./include/linux/rcupdate.h:331 (discriminator 1) ./include/linux/rcupdate_trace.h:58 (discriminator 1) ./include/linux/rcupdate_trace.h:102 (discriminator 1) kernel/bpf/helpers.c:4101 (discriminator 1))
[   11.791446]  #1: ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446] 
[   11.791446] stack backtrace:
[   11.791446] Tainted: [O]=OOT_MODULE, [E]=UNSIGNED_MODULE
[   11.791446] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-4.el9 04/01/2014
[   11.791446] Call Trace:
[   11.791446]  <TASK>
[   11.791446]  dump_stack_lvl (lib/dump_stack.c:122)
[   11.791446]  print_deadlock_bug.cold (kernel/locking/lockdep.c:3044)
[   11.791446]  __lock_acquire (kernel/locking/lockdep.c:3897 kernel/locking/lockdep.c:5237)
[   11.791446]  ? __pfx___up_read (kernel/locking/rwsem.c:1350)
[   11.791446]  lock_acquire (kernel/locking/lockdep.c:470 kernel/locking/lockdep.c:5870 kernel/locking/lockdep.c:5825)
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  ? __pfx___might_resched (kernel/sched/core.c:8880)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  __might_fault (mm/memory.c:7081 (discriminator 7))
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  _copy_from_user (./include/linux/instrumented.h:129 ./include/linux/uaccess.h:177 lib/usercopy.c:18)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  bpf_copy_from_user (kernel/bpf/helpers.c:664 (discriminator 1) kernel/bpf/helpers.c:659 (discriminator 1))
[   11.791446]  bpf_prog_1791842c6dbe7a9d_validate_file_read+0xeb/0x1c3
[   11.791446]  ? 0xffffffffc000098c
[   11.791446]  bpf_find_vma (kernel/bpf/task_iter.c:780 kernel/bpf/task_iter.c:751)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  bpf_prog_b8b63503b43f929b_task_work_callback+0x3b/0x43
[   11.791446]  bpf_task_work_callback (./include/linux/sched.h:2353 ./include/linux/sched.h:2417 kernel/bpf/helpers.c:4118)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? __pfx_bpf_task_work_callback (kernel/bpf/helpers.c:4094)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? lock_release (kernel/locking/lockdep.c:470 (discriminator 6) kernel/locking/lockdep.c:5891 (discriminator 6) kernel/locking/lockdep.c:5875 (discriminator 6))
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  task_work_run (kernel/task_work.c:229)
[   11.791446]  ? __pfx_task_work_run (kernel/task_work.c:195)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? __irq_work_queue_local (kernel/irq_work.c:89)
[   11.791446]  ? __pfx___irq_work_queue_local (kernel/irq_work.c:89)
[   11.791446]  get_signal (kernel/signal.c:2807)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? irq_work_queue (kernel/irq_work.c:125 (discriminator 3) kernel/irq_work.c:116 (discriminator 3))
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? bpf_task_work_schedule.isra.0 (kernel/bpf/helpers.c:4264)
[   11.791446]  ? 0xffffffffc000071c
[   11.791446]  ? __pfx_bpf_task_work_schedule.isra.0 (kernel/bpf/helpers.c:4229)
[   11.791446]  ? __pfx_get_signal (kernel/signal.c:2800)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? __lock_acquire (kernel/locking/lockdep.c:4674 (discriminator 1) kernel/locking/lockdep.c:5191 (discriminator 1))
[   11.791446]  arch_do_signal_or_restart (./arch/x86/include/asm/current.h:23 arch/x86/kernel/signal.c:258 arch/x86/kernel/signal.c:339)
[   11.791446]  ? __pfx_arch_do_signal_or_restart (arch/x86/kernel/signal.c:334)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? find_held_lock (kernel/locking/lockdep.c:5350 (discriminator 1))
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? lock_release (kernel/locking/lockdep.c:470 (discriminator 6) kernel/locking/lockdep.c:5891 (discriminator 6) kernel/locking/lockdep.c:5875 (discriminator 6))
[   11.791446]  exit_to_user_mode_loop (kernel/entry/common.c:42)
[   11.791446]  do_syscall_64 (./include/linux/irq-entry-common.h:225 ./include/linux/entry-common.h:175 ./include/linux/entry-common.h:210 arch/x86/entry/syscall_64.c:100)
[   11.791446]  entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:130)
[   11.791446] RIP: 0033:0x7fc6d58da89b
[   11.791446] Code: 0f 1e fa b9 01 00 00 00 e9 b2 fc ff ff 66 90 f3 0f 1e fa 31 c9 e9 a5 fc ff ff 0f 1f 44 00 00 f3 0f 1e fa b8 27 00 00 00 0f 05 <c3> 0f 1f 40 00 f3 0f 1e fa b8 6e 00 00 00 0f 05 c3 0f 1f 40 00 f3
All code
========
   0:	0f 1e fa             	nop    %edx
   3:	b9 01 00 00 00       	mov    $0x1,%ecx
   8:	e9 b2 fc ff ff       	jmp    0xfffffffffffffcbf
   d:	66 90                	xchg   %ax,%ax
   f:	f3 0f 1e fa          	endbr64
  13:	31 c9                	xor    %ecx,%ecx
  15:	e9 a5 fc ff ff       	jmp    0xfffffffffffffcbf
  1a:	0f 1f 44 00 00       	nopl   0x0(%rax,%rax,1)
  1f:	f3 0f 1e fa          	endbr64
  23:	b8 27 00 00 00       	mov    $0x27,%eax
  28:	0f 05                	syscall
  2a:*	c3                   	ret		<-- trapping instruction
  2b:	0f 1f 40 00          	nopl   0x0(%rax)
  2f:	f3 0f 1e fa          	endbr64
  33:	b8 6e 00 00 00       	mov    $0x6e,%eax
  38:	0f 05                	syscall
  3a:	c3                   	ret
  3b:	0f 1f 40 00          	nopl   0x0(%rax)
  3f:	f3                   	repz

Code starting with the faulting instruction
===========================================

   0:	c3                   	ret
   1:	0f 1f 40 00          	nopl   0x0(%rax)
   5:	f3 0f 1e fa          	endbr64
   9:	b8 6e 00 00 00       	mov    $0x6e,%eax
   e:	0f 05                	syscall
  10:	c3                   	ret
  11:	0f 1f 40 00          	nopl   0x0(%rax)
  15:	f3                   	repz
[   11.791446] RSP: 002b:00007fffab903ff8 EFLAGS: 00000246 ORIG_RAX: 0000000000000027
[   11.791446] RAX: 0000000000000099 RBX: 00007fc6d60b7000 RCX: 00007fc6d58da89b
[   11.791446] RDX: 000000000000005f RSI: 00000000013d1c62 RDI: 00007fffab903aa0
[   11.791446] RBP: 00007fffab9042a0 R08: 0000000000000000 R09: 00007fffab903ed7
[   11.791446] R10: 0000000000000000 R11: 0000000000000246 R12: 00007fffab9044f8
[   11.791446] R13: 00000000007c2531 R14: 000000000334fd10 R15: 00007fc6d60f6000
[   11.791446]  </TASK>
#115/1   file_reader/on_getpid_expect_fault:OK
#115/2   file_reader/on_getpid_validate_file_read:OK
#115     file_reader:OK
Summary: 1/2 PASSED, 0 SKIPPED, 0 FAILED
Powering off.
[   11.946617] sd 0:0:0:0: [sda] Synchronizing SCSI cache
[   11.948196] sd 0:0:0:0: [sda] Stopping disk
#27 lore raw

Re: [RFC PATCH v2 11/11] selftests/bpf: add file dynptr tests

Quoted 51 lines · Eduard Zingerman
Quoted 10 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Introducing selftests for validating file-backed dynptr works as expected.
* validate implementation supports dynptr slice and read operations
* validate destructors should be paired with initializers
* validate sleepable progs can page in.

---

I get the following error report when running this test on top of [1].

[1] 48a97ffc6c82 ("bpf: Consistently use bpf_rcu_lock_held() everywhere")

---

[   11.790725] ============================================
[   11.790999] WARNING: possible recursive locking detected
[   11.791195] 6.17.0-gbfd75250bee0 #1 Tainted: G           OE
[   11.791418] --------------------------------------------
[   11.791446] test_progs/153 is trying to acquire lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]
[   11.791446] but task is already holding lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446]
[   11.791446] other info that might help us debug this:
[   11.791446]  Possible unsafe locking scenario:
[   11.791446]
[   11.791446]        CPU0
[   11.791446]        ----
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]
[   11.791446]  *** DEADLOCK ***
[   11.791446]
[   11.791446]  May be due to missing lock nesting notation
[   11.791446]
[   11.791446] 2 locks held by test_progs/153:
[   11.791446]  #0: ffffffff85a73be0 (rcu_read_lock_trace){....}-{0:0}, at: bpf_task_work_callback (./include/linux/rcupdate.h:331 (discriminator 1) ./include/linux/rcupdate_trace.h:58 (discriminator 1) ./include/linux/rcupdate_trace.h:102 (discriminator 1) kernel/bpf/helpers.c:4101 (discriminator 1))
[   11.791446]  #1: ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446]
[   11.791446] stack backtrace:
[   11.791446] Tainted: [O]=OOT_MODULE, [E]=UNSIGNED_MODULE
[   11.791446] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-4.el9 04/01/2014
[   11.791446] Call Trace:
[   11.791446]  <TASK>
[   11.791446]  dump_stack_lvl (lib/dump_stack.c:122)
Quoted 8 lines
[   11.791446]  print_deadlock_bug.cold (kernel/locking/lockdep.c:3044)
[   11.791446]  __lock_acquire (kernel/locking/lockdep.c:3897 kernel/locking/lockdep.c:5237)
[   11.791446]  ? __pfx___up_read (kernel/locking/rwsem.c:1350)
[   11.791446]  lock_acquire (kernel/locking/lockdep.c:470 kernel/locking/lockdep.c:5870 kernel/locking/lockdep.c:5825)
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  ? __pfx___might_resched (kernel/sched/core.c:8880)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  __might_fault (mm/memory.c:7081 (discriminator 7))

cc'ing some mm folks for help

Is it a lockdep implementation detail that __might_fault is taking mmap_lock, or __might_fault is asserting that when fault is allowed, something (presumably kernel's page fault handler) might take mmap_lock? It's not clear to me.

bpf_find_vma() clearly is holding mmap_lock, so if that's unsafe, we'd have to make sure that bpf_find_vma() cannot be called in a sleepable BPF program.

Quoted 89 lines
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  _copy_from_user (./include/linux/instrumented.h:129 ./include/linux/uaccess.h:177 lib/usercopy.c:18)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  bpf_copy_from_user (kernel/bpf/helpers.c:664 (discriminator 1) kernel/bpf/helpers.c:659 (discriminator 1))
[   11.791446]  bpf_prog_1791842c6dbe7a9d_validate_file_read+0xeb/0x1c3
[   11.791446]  ? 0xffffffffc000098c
[   11.791446]  bpf_find_vma (kernel/bpf/task_iter.c:780 kernel/bpf/task_iter.c:751)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  bpf_prog_b8b63503b43f929b_task_work_callback+0x3b/0x43
[   11.791446]  bpf_task_work_callback (./include/linux/sched.h:2353 ./include/linux/sched.h:2417 kernel/bpf/helpers.c:4118)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? __pfx_bpf_task_work_callback (kernel/bpf/helpers.c:4094)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? lock_release (kernel/locking/lockdep.c:470 (discriminator 6) kernel/locking/lockdep.c:5891 (discriminator 6) kernel/locking/lockdep.c:5875 (discriminator 6))
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  task_work_run (kernel/task_work.c:229)
[   11.791446]  ? __pfx_task_work_run (kernel/task_work.c:195)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? __irq_work_queue_local (kernel/irq_work.c:89)
[   11.791446]  ? __pfx___irq_work_queue_local (kernel/irq_work.c:89)
[   11.791446]  get_signal (kernel/signal.c:2807)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? irq_work_queue (kernel/irq_work.c:125 (discriminator 3) kernel/irq_work.c:116 (discriminator 3))
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? bpf_task_work_schedule.isra.0 (kernel/bpf/helpers.c:4264)
[   11.791446]  ? 0xffffffffc000071c
[   11.791446]  ? __pfx_bpf_task_work_schedule.isra.0 (kernel/bpf/helpers.c:4229)
[   11.791446]  ? __pfx_get_signal (kernel/signal.c:2800)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? __lock_acquire (kernel/locking/lockdep.c:4674 (discriminator 1) kernel/locking/lockdep.c:5191 (discriminator 1))
[   11.791446]  arch_do_signal_or_restart (./arch/x86/include/asm/current.h:23 arch/x86/kernel/signal.c:258 arch/x86/kernel/signal.c:339)
[   11.791446]  ? __pfx_arch_do_signal_or_restart (arch/x86/kernel/signal.c:334)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? find_held_lock (kernel/locking/lockdep.c:5350 (discriminator 1))
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  ? lock_release (kernel/locking/lockdep.c:470 (discriminator 6) kernel/locking/lockdep.c:5891 (discriminator 6) kernel/locking/lockdep.c:5875 (discriminator 6))
[   11.791446]  exit_to_user_mode_loop (kernel/entry/common.c:42)
[   11.791446]  do_syscall_64 (./include/linux/irq-entry-common.h:225 ./include/linux/entry-common.h:175 ./include/linux/entry-common.h:210 arch/x86/entry/syscall_64.c:100)
[   11.791446]  entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:130)
[   11.791446] RIP: 0033:0x7fc6d58da89b
[   11.791446] Code: 0f 1e fa b9 01 00 00 00 e9 b2 fc ff ff 66 90 f3 0f 1e fa 31 c9 e9 a5 fc ff ff 0f 1f 44 00 00 f3 0f 1e fa b8 27 00 00 00 0f 05 <c3> 0f 1f 40 00 f3 0f 1e fa b8 6e 00 00 00 0f 05 c3 0f 1f 40 00 f3
All code
========
   0:   0f 1e fa                nop    %edx
   3:   b9 01 00 00 00          mov    $0x1,%ecx
   8:   e9 b2 fc ff ff          jmp    0xfffffffffffffcbf
   d:   66 90                   xchg   %ax,%ax
   f:   f3 0f 1e fa             endbr64
  13:   31 c9                   xor    %ecx,%ecx
  15:   e9 a5 fc ff ff          jmp    0xfffffffffffffcbf
  1a:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)
  1f:   f3 0f 1e fa             endbr64
  23:   b8 27 00 00 00          mov    $0x27,%eax
  28:   0f 05                   syscall
  2a:*  c3                      ret             <-- trapping instruction
  2b:   0f 1f 40 00             nopl   0x0(%rax)
  2f:   f3 0f 1e fa             endbr64
  33:   b8 6e 00 00 00          mov    $0x6e,%eax
  38:   0f 05                   syscall
  3a:   c3                      ret
  3b:   0f 1f 40 00             nopl   0x0(%rax)
  3f:   f3                      repz

Code starting with the faulting instruction
===========================================

   0:   c3                      ret
   1:   0f 1f 40 00             nopl   0x0(%rax)
   5:   f3 0f 1e fa             endbr64
   9:   b8 6e 00 00 00          mov    $0x6e,%eax
   e:   0f 05                   syscall
  10:   c3                      ret
  11:   0f 1f 40 00             nopl   0x0(%rax)
  15:   f3                      repz
[   11.791446] RSP: 002b:00007fffab903ff8 EFLAGS: 00000246 ORIG_RAX: 0000000000000027
[   11.791446] RAX: 0000000000000099 RBX: 00007fc6d60b7000 RCX: 00007fc6d58da89b
[   11.791446] RDX: 000000000000005f RSI: 00000000013d1c62 RDI: 00007fffab903aa0
[   11.791446] RBP: 00007fffab9042a0 R08: 0000000000000000 R09: 00007fffab903ed7
[   11.791446] R10: 0000000000000000 R11: 0000000000000246 R12: 00007fffab9044f8
[   11.791446] R13: 00000000007c2531 R14: 000000000334fd10 R15: 00007fc6d60f6000
[   11.791446]  </TASK>
#115/1   file_reader/on_getpid_expect_fault:OK
#115/2   file_reader/on_getpid_validate_file_read:OK
#115     file_reader:OK
Summary: 1/2 PASSED, 0 SKIPPED, 0 FAILED
Powering off.
[   11.946617] sd 0:0:0:0: [sda] Synchronizing SCSI cache
[   11.948196] sd 0:0:0:0: [sda] Stopping disk
#28 lore raw

Re: [RFC PATCH v2 11/11] selftests/bpf: add file dynptr tests

Quoted 61 lines · Andrii Nakryiko
Quoted 51 lines · Eduard Zingerman
Quoted 10 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Introducing selftests for validating file-backed dynptr works as expected.
* validate implementation supports dynptr slice and read operations
* validate destructors should be paired with initializers
* validate sleepable progs can page in.

---

I get the following error report when running this test on top of [1].

[1] 48a97ffc6c82 ("bpf: Consistently use bpf_rcu_lock_held() everywhere")

---

[   11.790725] ============================================
[   11.790999] WARNING: possible recursive locking detected
[   11.791195] 6.17.0-gbfd75250bee0 #1 Tainted: G           OE
[   11.791418] --------------------------------------------
[   11.791446] test_progs/153 is trying to acquire lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]
[   11.791446] but task is already holding lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446]
[   11.791446] other info that might help us debug this:
[   11.791446]  Possible unsafe locking scenario:
[   11.791446]
[   11.791446]        CPU0
[   11.791446]        ----
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]
[   11.791446]  *** DEADLOCK ***
[   11.791446]
[   11.791446]  May be due to missing lock nesting notation
[   11.791446]
[   11.791446] 2 locks held by test_progs/153:
[   11.791446]  #0: ffffffff85a73be0 (rcu_read_lock_trace){....}-{0:0}, at: bpf_task_work_callback (./include/linux/rcupdate.h:331 (discriminator 1) ./include/linux/rcupdate_trace.h:58 (discriminator 1) ./include/linux/rcupdate_trace.h:102 (discriminator 1) kernel/bpf/helpers.c:4101 (discriminator 1))
[   11.791446]  #1: ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446]
[   11.791446] stack backtrace:
[   11.791446] Tainted: [O]=OOT_MODULE, [E]=UNSIGNED_MODULE
[   11.791446] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-4.el9 04/01/2014
[   11.791446] Call Trace:
[   11.791446]  <TASK>
[   11.791446]  dump_stack_lvl (lib/dump_stack.c:122)
Quoted 8 lines
[   11.791446]  print_deadlock_bug.cold (kernel/locking/lockdep.c:3044)
[   11.791446]  __lock_acquire (kernel/locking/lockdep.c:3897 kernel/locking/lockdep.c:5237)
[   11.791446]  ? __pfx___up_read (kernel/locking/rwsem.c:1350)
[   11.791446]  lock_acquire (kernel/locking/lockdep.c:470 kernel/locking/lockdep.c:5870 kernel/locking/lockdep.c:5825)
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  ? __pfx___might_resched (kernel/sched/core.c:8880)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  __might_fault (mm/memory.c:7081 (discriminator 7))
Quoted 6 lines

cc'ing some mm folks for help

Is it a lockdep implementation detail that __might_fault is taking mmap_lock, or __might_fault is asserting that when fault is allowed, something (presumably kernel's page fault handler) might take mmap_lock? It's not clear to me.

It's the later i.e. current might take its mmap_lock.

Quoted 5 lines

bpf_find_vma() clearly is holding mmap_lock, so if that's unsafe, we'd have to make sure that bpf_find_vma() cannot be called in a sleepable BPF program.

Sorry I am not sure about sleepable part but the issue is that this path is leading to copy_from_user while holding mmap_lock which is not allowed as it may cause a fault (acquire and release mmap_lock). We don't support nested mmap read lock. (Suren can correct me if I missed something).

You can use copy_from_user_nofault() instead but expect occasional -EFAULT.

Quoted 10 lines
Quoted 10 lines

[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  _copy_from_user (./include/linux/instrumented.h:129 ./include/linux/uaccess.h:177 lib/usercopy.c:18)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  bpf_copy_from_user (kernel/bpf/helpers.c:664 (discriminator 1) kernel/bpf/helpers.c:659 (discriminator 1))
[   11.791446]  bpf_prog_1791842c6dbe7a9d_validate_file_read+0xeb/0x1c3
[   11.791446]  ? 0xffffffffc000098c
[   11.791446]  bpf_find_vma (kernel/bpf/task_iter.c:780 kernel/bpf/task_iter.c:751)
#29 lore raw

Re: [RFC PATCH v2 11/11] selftests/bpf: add file dynptr tests

In reply to Andrii Nakryiko
Quoted 60 lines · Andrii Nakryiko
Quoted 49 lines · Eduard Zingerman
Quoted 10 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Introducing selftests for validating file-backed dynptr works as expected.
* validate implementation supports dynptr slice and read operations
* validate destructors should be paired with initializers
* validate sleepable progs can page in.

---

I get the following error report when running this test on top of [1].

[1] 48a97ffc6c82 ("bpf: Consistently use bpf_rcu_lock_held() everywhere")

---

[   11.790725] ============================================
[   11.790999] WARNING: possible recursive locking detected
[   11.791195] 6.17.0-gbfd75250bee0 #1 Tainted: G           OE
[   11.791418] --------------------------------------------
[   11.791446] test_progs/153 is trying to acquire lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]
[   11.791446] but task is already holding lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446]
[   11.791446] other info that might help us debug this:
[   11.791446]  Possible unsafe locking scenario:
[   11.791446]
[   11.791446]        CPU0
[   11.791446]        ----
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]
[   11.791446]  *** DEADLOCK ***
[   11.791446]
[   11.791446]  May be due to missing lock nesting notation
[   11.791446]
[   11.791446] 2 locks held by test_progs/153:
[   11.791446]  #0: ffffffff85a73be0 (rcu_read_lock_trace){....}-{0:0}, at: bpf_task_work_callback (./include/linux/rcupdate.h:331 (discriminator 1) ./include/linux/rcupdate_trace.h:58 (discriminator 1) ./include/linux/rcupdate_trace.h:102 (discriminator 1) kernel/bpf/helpers.c:4101 (discriminator 1))
[   11.791446]  #1: ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446]
[   11.791446] stack backtrace:
[   11.791446] Tainted: [O]=OOT_MODULE, [E]=UNSIGNED_MODULE
[   11.791446] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-4.el9 04/01/2014
[   11.791446] Call Trace:
[   11.791446]  <TASK>
[   11.791446]  dump_stack_lvl (lib/dump_stack.c:122)
Quoted 8 lines
[   11.791446]  print_deadlock_bug.cold (kernel/locking/lockdep.c:3044)
[   11.791446]  __lock_acquire (kernel/locking/lockdep.c:3897 kernel/locking/lockdep.c:5237)
[   11.791446]  ? __pfx___up_read (kernel/locking/rwsem.c:1350)
[   11.791446]  lock_acquire (kernel/locking/lockdep.c:470 kernel/locking/lockdep.c:5870 kernel/locking/lockdep.c:5825)
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  ? __pfx___might_resched (kernel/sched/core.c:8880)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  __might_fault (mm/memory.c:7081 (discriminator 7))

cc'ing some mm folks for help

Quoted 9 lines

Is it a lockdep implementation detail that __might_fault is taking mmap_lock, or __might_fault is asserting that when fault is allowed, something (presumably kernel's page fault handler) might take mmap_lock? It's not clear to me.

bpf_find_vma() clearly is holding mmap_lock, so if that's unsafe, we'd have to make sure that bpf_find_vma() cannot be called in a sleepable BPF program.

Do we want to have a finer granularity, for example just disallow calls to copy_from_user type of functions in the bpf_find_vma callback?

#30 lore raw

Re: [RFC PATCH v2 11/11] selftests/bpf: add file dynptr tests

Quoted 67 lines · Mykyta Yatsenko
Quoted 65 lines · Andrii Nakryiko
Quoted 49 lines · Eduard Zingerman
Quoted 10 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Introducing selftests for validating file-backed dynptr works as expected.
* validate implementation supports dynptr slice and read operations
* validate destructors should be paired with initializers
* validate sleepable progs can page in.

---

I get the following error report when running this test on top of [1].

[1] 48a97ffc6c82 ("bpf: Consistently use bpf_rcu_lock_held() everywhere")

---

[   11.790725] ============================================
[   11.790999] WARNING: possible recursive locking detected
[   11.791195] 6.17.0-gbfd75250bee0 #1 Tainted: G           OE
[   11.791418] --------------------------------------------
[   11.791446] test_progs/153 is trying to acquire lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]
[   11.791446] but task is already holding lock:
[   11.791446] ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446]
[   11.791446] other info that might help us debug this:
[   11.791446]  Possible unsafe locking scenario:
[   11.791446]
[   11.791446]        CPU0
[   11.791446]        ----
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]   lock(&mm->mmap_lock);
[   11.791446]
[   11.791446]  *** DEADLOCK ***
[   11.791446]
[   11.791446]  May be due to missing lock nesting notation
[   11.791446]
[   11.791446] 2 locks held by test_progs/153:
[   11.791446]  #0: ffffffff85a73be0 (rcu_read_lock_trace){....}-{0:0}, at: bpf_task_work_callback (./include/linux/rcupdate.h:331 (discriminator 1) ./include/linux/rcupdate_trace.h:58 (discriminator 1) ./include/linux/rcupdate_trace.h:102 (discriminator 1) kernel/bpf/helpers.c:4101 (discriminator 1))
[   11.791446]  #1: ff110001066916d0 (&mm->mmap_lock){++++}-{4:4}, at: bpf_find_vma (./arch/x86/include/asm/jump_label.h:36 ./include/linux/mmap_lock.h:41 ./include/linux/mmap_lock.h:388 kernel/bpf/task_iter.c:772 kernel/bpf/task_iter.c:751)
[   11.791446]
[   11.791446] stack backtrace:
[   11.791446] Tainted: [O]=OOT_MODULE, [E]=UNSIGNED_MODULE
[   11.791446] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-4.el9 04/01/2014
[   11.791446] Call Trace:
[   11.791446]  <TASK>
[   11.791446]  dump_stack_lvl (lib/dump_stack.c:122)
Quoted 8 lines
[   11.791446]  print_deadlock_bug.cold (kernel/locking/lockdep.c:3044)
[   11.791446]  __lock_acquire (kernel/locking/lockdep.c:3897 kernel/locking/lockdep.c:5237)
[   11.791446]  ? __pfx___up_read (kernel/locking/rwsem.c:1350)
[   11.791446]  lock_acquire (kernel/locking/lockdep.c:470 kernel/locking/lockdep.c:5870 kernel/locking/lockdep.c:5825)
[   11.791446]  ? __might_fault (mm/memory.c:7081 (discriminator 4))
[   11.791446]  ? __pfx___might_resched (kernel/sched/core.c:8880)
[   11.791446]  ? srso_alias_return_thunk (arch/x86/lib/retpoline.S:221)
[   11.791446]  __might_fault (mm/memory.c:7081 (discriminator 7))

cc'ing some mm folks for help

Is it a lockdep implementation detail that __might_fault is taking mmap_lock, or __might_fault is asserting that when fault is allowed, something (presumably kernel's page fault handler) might take mmap_lock? It's not clear to me.

Quoted 6 lines
Quoted 4 lines

bpf_find_vma() clearly is holding mmap_lock, so if that's unsafe, we'd have to make sure that bpf_find_vma() cannot be called in a sleepable BPF program.

Do we want to have a finer granularity, for example just disallow calls to copy_from_user type of functions in the bpf_find_vma callback?

I think this means that bpf_find_vma() is not compatible with BPF sleepable programs, not just with with bpf_copy_from_user(). Same stands for task_vma iterator, as it does mmap locking just as well.

We should look into avoiding mmap locking altogether and using RCU protection and per-VMA locks instead. Suren recently made use of that in /proc/PID/maps/PROCMAP_QUERY. This will have to be dependent on CONFIG_PER_VMA_LOCK, unfortunately.

Suren, Shakeel, do you see any other way to avoid taking mmap_lock, but let BPF safely work in VMA while allowing page faults (that's what we mean by "BPF sleepable mode")?

maintainer
#31 lore raw

Re: [RFC PATCH v2 11/11] selftests/bpf: add file dynptr tests

In reply to Mykyta Yatsenko
Quoted 10 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Introducing selftests for validating file-backed dynptr works as expected.
* validate implementation supports dynptr slice and read operations
* validate destructors should be paired with initializers
* validate sleepable progs can page in.

---

I think a few additional test cases are needed:
- negative verification test cases, e.g. when file dynptr is created but not discarded and vice versa;
- a test case for bpf_dynptr_adjust();
- a test case for bpf_dynptr_read() starting at non-zero offset.

[...]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +0 -0

[...]

tools/testing/selftests/bpf/prog_tests/file_reader.c line 32

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +8 -0
+static int initialize_file_contents(void)
+{
+	int fd, page_sz = sysconf(_SC_PAGESIZE);
+	ssize_t n = 0, cur, off;
+	void *addr;
+
+	fd = open("/proc/self/exe", O_RDONLY);
+	if (!ASSERT_GT(fd, 0, "Open /proc/self/exe\n"))

Nit: ASSERT_OK_FD, 0 is a valid fd number.

Quoted 42 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +42 -0
+		return 1;
+
+	do {
+		cur = read(fd, file_contents + n, sizeof(file_contents) - n);
+		if (!ASSERT_GT(cur, 0, "read success"))
+			break;
+		n += cur;
+	} while (n < sizeof(file_contents));
+
+	close(fd);
+
+	if (!ASSERT_EQ(n, sizeof(file_contents), "Read /proc/self/exe\n"))
+		return 1;
+
+	addr = get_executable_base_addr();
+	if (!ASSERT_NEQ(addr, NULL, "get executable address"))
+		return 1;
+
+	/* page-align base file address */
+	addr = (void *)((unsigned long)addr & ~(page_sz - 1));
+
+	for (off = 0; off < sizeof(file_contents); off += page_sz) {
+		if (!ASSERT_OK(madvise(addr + off, page_sz, MADV_PAGEOUT),
+			       "madvise pageout"))
+			return errno;
+	}
+
+	return 0;
+}
+
+static void run_test(const char *prog_name)
+{
+	struct file_reader *skel;
+	struct bpf_program *prog;
+	int err;
+	char data[256];
+	LIBBPF_OPTS(bpf_test_run_opts, opts, .data_in = &data, .repeat = 1,
+		    .data_size_in = sizeof(data));
+
+	err = initialize_file_contents();
+	if (!ASSERT_OK(err, "initialize file contents"))
+		return;

tools/testing/selftests/bpf/prog_tests/file_reader.c line 84

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +10 -0
+
+	skel = file_reader__open();
+	if (!ASSERT_OK_PTR(skel, "file_reader__open"))
+		return;
+
+	bpf_object__for_each_program(prog, skel->obj) {
+		if (strcmp(bpf_program__name(prog), prog_name) == 0)
+			bpf_program__set_autoload(prog, true);
+		else
+			bpf_program__set_autoload(prog, false);

Nit: bpf_program__set_autoload(prog, strcmp(bpf_program__name(prog), prog_name) == 0);

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +8 -0
+	}
+
+	skel->bss->user_buf = file_contents;
+	skel->rodata->user_buf_sz = sizeof(file_contents);
+	skel->bss->pid = getpid();
+	skel->bss->user_ptr = (char *)user_ptr;
+
+	err = file_reader__load(skel);

tools/testing/selftests/bpf/prog_tests/file_reader.c line 102

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +10 -0
+	if (!ASSERT_OK(err, "file_reader__load"))
+		goto cleanup;
+
+	err = file_reader__attach(skel);
+	if (!ASSERT_OK(err, "file_reader__attach"))
+		goto cleanup;
+
+	getpid();
+
+	ASSERT_EQ(skel->bss->err, 0, "err");

Nit: I'd check for some more unique value, e.g. 42, something not null.

Quoted 12 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +12 -0
+cleanup:
+	file_reader__destroy(skel);
+}
+
+void test_file_reader(void)
+{
+	if (test__start_subtest("on_getpid_expect_fault"))
+		run_test("on_getpid_expect_fault");
+
+	if (test__start_subtest("on_getpid_validate_file_read"))
+		run_test("on_getpid_validate_file_read");
+}

[...]

#32 lore raw

Re: [RFC PATCH v2 11/11] selftests/bpf: add file dynptr tests

Quoted 98 lines · Eduard Zingerman
Quoted 10 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

Introducing selftests for validating file-backed dynptr works as expected.
* validate implementation supports dynptr slice and read operations
* validate destructors should be paired with initializers
* validate sleepable progs can page in.

---

I think a few additional test cases are needed:
- negative verification test cases, e.g. when file dynptr is created but not discarded and vice versa;
- a test case for bpf_dynptr_adjust();
- a test case for bpf_dynptr_read() starting at non-zero offset.

[...]

Quoted 2 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +0 -0

[...]

tools/testing/selftests/bpf/prog_tests/file_reader.c line 32

Quoted 8 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +8 -0
+static int initialize_file_contents(void)
+{
+	int fd, page_sz = sysconf(_SC_PAGESIZE);
+	ssize_t n = 0, cur, off;
+	void *addr;
+
+	fd = open("/proc/self/exe", O_RDONLY);
+	if (!ASSERT_GT(fd, 0, "Open /proc/self/exe\n"))

Nit: ASSERT_OK_FD, 0 is a valid fd number.

Quoted 42 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +42 -0
+		return 1;
+
+	do {
+		cur = read(fd, file_contents + n, sizeof(file_contents) - n);
+		if (!ASSERT_GT(cur, 0, "read success"))
+			break;
+		n += cur;
+	} while (n < sizeof(file_contents));
+
+	close(fd);
+
+	if (!ASSERT_EQ(n, sizeof(file_contents), "Read /proc/self/exe\n"))
+		return 1;
+
+	addr = get_executable_base_addr();
+	if (!ASSERT_NEQ(addr, NULL, "get executable address"))
+		return 1;
+
+	/* page-align base file address */
+	addr = (void *)((unsigned long)addr & ~(page_sz - 1));
+
+	for (off = 0; off < sizeof(file_contents); off += page_sz) {
+		if (!ASSERT_OK(madvise(addr + off, page_sz, MADV_PAGEOUT),
+			       "madvise pageout"))
+			return errno;
+	}
+
+	return 0;
+}
+
+static void run_test(const char *prog_name)
+{
+	struct file_reader *skel;
+	struct bpf_program *prog;
+	int err;
+	char data[256];
+	LIBBPF_OPTS(bpf_test_run_opts, opts, .data_in = &data, .repeat = 1,
+		    .data_size_in = sizeof(data));
+
+	err = initialize_file_contents();
+	if (!ASSERT_OK(err, "initialize file contents"))
+		return;

tools/testing/selftests/bpf/prog_tests/file_reader.c line 84

Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +10 -0
+
+	skel = file_reader__open();
+	if (!ASSERT_OK_PTR(skel, "file_reader__open"))
+		return;
+
+	bpf_object__for_each_program(prog, skel->obj) {
+		if (strcmp(bpf_program__name(prog), prog_name) == 0)
+			bpf_program__set_autoload(prog, true);
+		else
+			bpf_program__set_autoload(prog, false);

Nit: bpf_program__set_autoload(prog, strcmp(bpf_program__name(prog), prog_name) == 0);

Quoted 11 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +11 -0
+	}
+
+	skel->bss->user_buf = file_contents;
+	skel->rodata->user_buf_sz = sizeof(file_contents);
+	skel->bss->pid = getpid();
+	skel->bss->user_ptr = (char *)user_ptr;
+
+	err = file_reader__load(skel);
+	if (!ASSERT_OK(err, "file_reader__load"))
+		goto cleanup;
+
Quoted 8 lines

tools/testing/selftests/bpf/prog_tests/file_reader.c line 102

Quoted 7 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +7 -0
+	err = file_reader__attach(skel);
+	if (!ASSERT_OK(err, "file_reader__attach"))
+		goto cleanup;
+
+	getpid();
+
+	ASSERT_EQ(skel->bss->err, 0, "err");

Nit: I'd check for some more unique value, e.g. 42, something not null.

I'd like not to use non-zero err value to indicate success, it's probably better to introduce a separate success variable, to verify that programs did what we expect.

Quoted 14 lines
Quoted 13 lines
tools/testing/selftests/bpf/prog_tests/file_reader.c new file +12 -0
+cleanup:
+	file_reader__destroy(skel);
+}
+
+void test_file_reader(void)
+{
+	if (test__start_subtest("on_getpid_expect_fault"))
+		run_test("on_getpid_expect_fault");
+
+	if (test__start_subtest("on_getpid_validate_file_read"))
+		run_test("on_getpid_validate_file_read");
+}

[...]

maintainer
#33 lore raw
In reply to Mykyta Yatsenko
Quoted 23 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

This series adds a new dynptr kind, file dynptr, which enables BPF programs to perform safe reads from files in a structured way. Initial motivations include:
* Parsing the executable’s ELF to locate thread-local variable symbols
* Capturing stack traces when frame pointers are disabled

By leveraging the existing dynptr abstraction, we reuse the verifier’s lifetime/size checks and keep the API consistent with existing dynptr read helpers.

Technical details:
1. Reuses the existing freader library to read files a folio at a time.
2. bpf_dynptr_slice() and bpf_dynptr_read() always copy data from folios into a program-provided buffer; zero-copy access is intentionally not supported to keep it simple.
3. Reads may sleep if the requested folios are not in the page cache.
4. Few verifier changes required:
* Support dynptr destruction in kfuncs
* Add kfunc address substitution based on whether the program runs in a sleepable or non-sleepable context.

Quoted 4 lines

Testing:
The final patch adds a selftest that parses the executable’s ELF to locate thread-local symbol information, demonstrating the file dynptr workflow end-to-end.

Nit: could you please include summary of changes between patch-set
versions in the cover letter?

#34 lore raw
Quoted 25 lines · Eduard Zingerman
Quoted 23 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

This series adds a new dynptr kind, file dynptr, which enables BPF programs to perform safe reads from files in a structured way. Initial motivations include:
* Parsing the executable’s ELF to locate thread-local variable symbols
* Capturing stack traces when frame pointers are disabled

By leveraging the existing dynptr abstraction, we reuse the verifier’s lifetime/size checks and keep the API consistent with existing dynptr read helpers.

Technical details:
1. Reuses the existing freader library to read files a folio at a time.
2. bpf_dynptr_slice() and bpf_dynptr_read() always copy data from folios into a program-provided buffer; zero-copy access is intentionally not supported to keep it simple.
3. Reads may sleep if the requested folios are not in the page cache.
4. Few verifier changes required:
* Support dynptr destruction in kfuncs
* Add kfunc address substitution based on whether the program runs in a sleepable or non-sleepable context.

Quoted 7 lines
Quoted 4 lines

Testing:
The final patch adds a selftest that parses the executable’s ELF to locate thread-local symbol information, demonstrating the file dynptr workflow end-to-end.

Nit: could you please include summary of changes between patch-set
versions in the cover letter?

... and lore links to all previous revisions, so that cover letter has full history.

#35 lore raw
In reply to Eduard Zingerman
Quoted 24 lines · Eduard Zingerman
Quoted 23 lines · Mykyta Yatsenko

From: Mykyta Yatsenko <[email protected]>

This series adds a new dynptr kind, file dynptr, which enables BPF programs to perform safe reads from files in a structured way. Initial motivations include:
* Parsing the executable’s ELF to locate thread-local variable symbols
* Capturing stack traces when frame pointers are disabled

By leveraging the existing dynptr abstraction, we reuse the verifier’s lifetime/size checks and keep the API consistent with existing dynptr read helpers.

Technical details:
1. Reuses the existing freader library to read files a folio at a time.
2. bpf_dynptr_slice() and bpf_dynptr_read() always copy data from folios into a program-provided buffer; zero-copy access is intentionally not supported to keep it simple.
3. Reads may sleep if the requested folios are not in the page cache.
4. Few verifier changes required:
* Support dynptr destruction in kfuncs
* Add kfunc address substitution based on whether the program runs in a sleepable or non-sleepable context.

Quoted 6 lines
Quoted 4 lines

Testing:
The final patch adds a selftest that parses the executable’s ELF to locate thread-local symbol information, demonstrating the file dynptr workflow end-to-end.

Nit: could you please include summary of changes between patch-set
versions in the cover letter?

Thanks for the reminder, I messed it up.