bpf: Import external pages into an arena
Andrea Righi
reviewerv3 cover bpf: Import external pages into an arena
As discussed in the BPF track and the sched_ext microconference at Linux Plumbers 2026 [1][2], shared BPF arenas can provide a generic channel for bidirectional zero-copy communication between BPF programs running on a host and its guests, for example to exchange scheduling hints between host and guest sched_ext schedulers.
This series teaches the arena to map pages that it didn't allocate, based on Alexei's prototype [3].
Background
==========
An arena can only map pages it allocated itself, so its memory can be shared only with the BPF programs and the user space that map the arena. A host and a guest have no such mapping in common: they need an arena that maps memory supplied by something else, such as the VMM or a paravirt device.
Design
======
The arena gains a single primitive, which maps pages supplied from outside at a free arena address. Each call creates one import, kept in an interval tree with its pages, which belong to their supplier, not to the arena:
- bpf_arena_free_pages() over any of them releases the whole import: the pages are unmapped and given back to their supplier, and the range goes back to the arena, so the arena doesn't grow as guests come and go,
- they are released when the arena is destroyed,
- they are not counted in the arena memory usage,
- the arena mapping raises SIGBUS on them (SIGSEGV with BPF_F_SEGV_ON_FAULT): user space accesses them through their supplier.
There are three ways to supply the pages. Two are sleepable kfuncs for syscall programs, one for each side of a host/guest shared arena, which work with existing VMMs:
int bpf_arena_import_memfd(void *map, void __arena *addr,
u32 page_cnt, int fd, u64 off);
Host side: pins the pages of a memfd, or of any file on tmpfs or hugetlbfs, with memfd_pin_folios() like udmabuf does. The host hands the same file to the VMM as a memory backend, with no change to the VMM.
int bpf_arena_import_dax(void *map, void __arena *addr,
u32 page_cnt, u64 src);
Guest side: the VMM exposes the file as a virtio-pmem or NVDIMM device, which the guest turns into a device-dax device (/dev/daxX.Y). The kfunc pins the device-dax pages mapped at an address of the calling task, and holds a reference on their dev_pagemap until it releases them. It needs CONFIG_DAX=y.
Both kfuncs act on the current task, its file descriptors or its address space, so they fail with -EPERM in async callbacks, which may run in another task.
The third one is a kernel API, for suppliers that own the pages, such as a paravirt transport:
int bpf_arena_map_ext_pages(struct bpf_map *map, u64 addr,
struct page **pages, u32 page_cnt, void (*release)(struct page **pages,
u32 page_cnt, void *priv),
void *priv);
int bpf_arena_unmap_ext_pages(struct bpf_map *map, u64 addr, void *priv);
The arena calls release() once it no longer maps the pages, whatever the reason. bpf_arena_unmap_ext_pages() revokes them synchronously: when it returns, BPF programs can no longer access the pages and release() has run. release() is called under a mutex of the arena, so it must not take a lock that is held across bpf_arena_unmap_ext_pages(). The only user in this series is bpf_testmod: the API is meant for transports like pvsched, see the discussion on v2 [4][5]. Once one is available, bpf_arena_import_dax() may be deprecated in favor of it.
Both sides then see the same pages as arena memory, at an offset known to both of them, so they can agree on a layout in-band, with plain BPF loads and stores, and keep pointers to it in the rest of their arena state.
Use case: paravirt scheduling
=============================
The git tree below has an additional [DEMO] commit, not meant for upstream, that provides a real, tested use case of this functionality: a pair of sched_ext schedulers, scx_pvhost on the host and scx_pvguest in every guest, which share a few pages per VM through their arenas. The host publishes which vCPUs it has preempted, its idle CPUs and every VM's fair share of the host CPUs; the guests publish their demand and the state of their vCPUs. With that, the guests stop queueing work behind preempted vCPUs and fold onto their share of the host CPUs only while that pays off.
On an NVIDIA Vera host (arm64), with 8-vCPU VMs on QEMU or Firecracker, at 2x and 6x overcommit, compared to stock VMs, the paravirt pair is 2.2-3x as fast on hackbench, 1.3-1.9x on a kernel build and serves 1.6-2x the requests of schbench and nginx; tools/sched_ext/scx-pvsched.md in the [DEMO] commit describes the design, the results and how to run it.
Known limitations
=================
- Imports are released whole: freeing part of an import releases all of it.
- Imported device-dax pages keep the device in use: unbinding it blocks until the arena releases them. Revoking them would need a notification from the dax core.
- BPF programs have no machine check recovery: on a real NVDIMM, the supplier has to keep bad pages out of the arena.
- There is no doorbell: the sched_ext use case polls the shared pages at scheduling events.
- Confidential VMs would need the guest to keep the shared pages shared with the host, which the device-dax import doesn't handle. A paravirt transport can do that before it maps the pages with bpf_arena_map_ext_pages().
References
==========
[1] https://lpc.events/event/20/contributions/2429/
[2] https://lpc.events/event/20/contributions/2482/
[3] https://lore.kernel.org/r/[email protected]/
[4] https://lore.kernel.org/r/CA+HDTgQ0mx0PgXDps2h2kd8TbJsFWOmJGJmDRGEHZgBZ_qSVwQ@mail.gmail.com/
[5] https://github.com/pvsched/linux
Git tree: git://git.kernel.org/pub/scm/linux/kernel/git/arighi/linux.git scx-pvsched
Changes in v3:
- Make the import kfuncs fail in async callbacks, with bpf_in_async_cb(): from a bpf_task_work callback, a program could import a memfd of another task (BPF CI bot)
- Add bpf_arena_map_ext_pages() and bpf_arena_unmap_ext_pages(), to let kernel code import its own pages and revoke them synchronously, and release all the imports through a callback of their supplier (Vineeth Pillai)
- Protect the device-dax import from a concurrent unbind with the dax SRCU and dax_alive(), instead of get_online_mems(), which could deadlock with mmap_lock; this requires CONFIG_DAX=y, the kfunc returns -EOPNOTSUPP otherwise (BPF CI bot)
- Add a preliminary patch that declares inode_dax() in linux/dax.h, needed to call dax_alive() on the device of a device-dax mapping
- Accept tagged addresses in bpf_arena_import_dax() (BPF CI bot)
- Document that importing a range of a memfd with holes allocates their pages, and which memory cgroup is charged for them (BPF CI bot)
- Link to v2: https://lore.kernel.org/r/[email protected]/
Changes in v2:
- Drop BPF_F_ARENA_NO_FREE, BPF_F_ARENA_EXPORT and the sized bpffs file, and map pages that the arena didn't allocate instead (Alexei Starovoitov)
- Import the host's pages from a memfd with memfd_pin_folios(), the VMM uses the same file as a memory backend (Alexei Starovoitov)
- Replace the guest NUMA node with a device-dax import, so the guest's pages never go back to its buddy allocator (Alexei Starovoitov, Josh Don)
- Release an import with bpf_arena_free_pages(), instead of keeping the arena at its high watermark (Alexei Starovoitov, Josh Don)
- Map the shared pages at an offset known to both sides, instead of discovering it out of band (Josh Don)
- Track imports in an interval tree instead of a second range tree and a list, so that a release finds its import without allocating
- Link to v1: https://lore.kernel.org/r/[email protected]/
Andrea Righi (5):
dax: Declare inode_dax() in linux/dax.h
bpf: Allow importing memfd pages into an arena
bpf: Let kernel code import pages into an arena
bpf: Allow importing device-dax pages into an arena selftests/bpf: Test importing pages into an arena
drivers/dax/dax-private.h | 1 - include/linux/bpf.h | 21 + include/linux/dax.h | 1 + kernel/bpf/arena.c | 607 +++++++++++++++++++++- tools/testing/selftests/bpf/prog_tests/arena_import.c | 553 ++++++++++++++++++++ tools/testing/selftests/bpf/progs/arena_import.c | 170 ++++++ tools/testing/selftests/bpf/test_kmods/bpf_testmod.c | 90 ++++ .../selftests/bpf/test_kmods/bpf_testmod_kfunc.h | 3 + 8 files changed, 1432 insertions(+), 14 deletions(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/arena_import.c create mode 100644 tools/testing/selftests/bpf/progs/arena_import.c
Andrea Righi
reviewerPATCH v3 1/5 dax: Declare inode_dax() in linux/dax.h
inode_dax() is exported, but it's declared only in the private header of the dax drivers, so code outside of drivers/dax can't use it to find the dax_device of a device-dax file.
Move its declaration to linux/dax.h, next to dax_alive(). This will be used to import device-dax pages into a BPF arena, which has to check that the dax device is alive before it pins the pages.
No functional change.
--- drivers/dax/dax-private.h | 1 - include/linux/dax.h | 1 + 2 files changed, 1 insertion(+), 1 deletion(-)
drivers/dax/dax-private.h +0 -1
@@ -11,7 +11,6 @@/* private routines between core files */ struct dax_device ; -struct dax_device *inode_dax (struct inode *inode);struct inode *dax_inode (struct dax_device *dax_dev);int dax_bus_init (void );void dax_bus_exit (void );
include/linux/dax.h +1 -0
@@ -235,6 +235,7 @@ static inline void dax_break_layout_final(struct inode *inode) }#endif +struct dax_device *inode_dax (struct inode *inode);bool dax_alive (struct dax_device *dax_dev);void *dax_get_private (struct dax_device *dax_dev);int dax_set_ops (struct dax_device *dax_dev,const struct dax_operations *ops);
Signature · 1 line
2.56.1
Andrea Righi
reviewerPATCH v3 2/5 bpf: Allow importing memfd pages into an arena
In reply to Andrea RighiAn arena can only map pages it allocated itself, so its memory can be shared only with the BPF programs and the user space that map the arena.
Teach the arena to map pages that it didn't allocate and add a sleepable kfunc for syscall programs that imports the pages of a memfd, or of any file on tmpfs or hugetlbfs:
int bpf_arena_import_memfd(void *map, void __arena *addr,
u32 page_cnt, int fd, u64 off);
The folios are pinned with memfd_pin_folios(), like udmabuf does, and mapped at addr. Whatever maps the file then sees the same pages as the BPF programs, for example a VMM that maps it into a guest.
Each import is kept in an interval tree with its pages, which belong to the file, not to the arena:
- bpf_arena_free_pages() over any of them releases the whole import:
the pages are unmapped and unpinned, the data stays in the file,
- they are released when the arena is destroyed,
- they are not counted in the arena memory usage,
- the arena mapping raises SIGBUS on them (SIGSEGV with BPF_F_SEGV_ON_FAULT): user space accesses them by mapping the file.
The arena gives the pages back through a release callback of the import, which unpins them and drops the file here, so that other suppliers can import pages the same way.
The file must be open for reading and writing and the LSMs must allow a shared mapping of it. It must not be append-only or sealed against writes.
F_SEAL_SHRINK is not required, unlike udmabuf: a file on tmpfs, such as a VMM memory backend, can't be sealed. If the supplier shrinks the file or punches a hole in the imported range, the arena keeps the pages it pinned, which are no longer the file's.
While its pages are imported, the file can't be executed, as when it's open for writing.
The pins aren't charged to locked_vm: like the rest of BPF memory, the pages are accounted to a memory cgroup, the one of the supplier that allocated them (hugetlbfs pages come from the hugetlb pool). Pinning keeps them from being swapped out until the arena releases them. The pages of any holes in the range are allocated by the import, as a write to the file would, charged to the memory cgroup of the current task, and stay in the file after the release.
Like the other arena kfuncs, it's marked KF_PERFMON: only a program with CAP_BPF and CAP_PERFMON, or a BPF token that grants them, can import pages.
The kfunc looks up the fd in the current task, so it fails in async
callbacks: a bpf_task_work one would look it up in another task.
--- kernel/bpf/arena.c | 372 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 361 insertions(+), 11 deletions(-)
kernel/bpf/arena.c +361 -11
@@ -4,7 +4,10 @@#include <linux/btf.h> #include <linux/cacheflush.h> #include <linux/err.h> +#include <linux/file.h> +#include <linux/interval_tree_generic.h> #include <linux/irq_work.h> +#include <linux/memfd.h> #include "linux/filter.h" #include <linux/llist.h> #include <linux/mman.h>
@@ -14,6 +17,7 @@#include <linux/printk.h> #include <linux/ratelimit.h> #include <linux/rbtree_latch.h> +#include <linux/security.h> #include <asm/tlbflush.h> #include "range_tree.h"
@@ -64,7 +68,9 @@ struct bpf_arena {struct vm_struct *kern_vm;struct page *scratch_page;struct range_tree rt; -/* protects rt and nr_pages */ +/* pages the arena didn't allocate, see struct arena_import */ +struct rb_root_cached imports; +/* protects rt, imports and nr_pages */ rqspinlock_t spinlock;/* number of pages currently populated in the arena */ u64 nr_pages;
@@ -114,6 +120,29 @@ struct arena_free_span {u32 page_cnt; }; +/* +* Pages mapped by one import, which belong to its supplier. They are released +* together, when the arena frees any of them or is destroyed. +*/ +struct arena_import { +struct rb_node rb; +long subtree_last; +/* on a list while being released */ +struct list_head head; +struct page **pages; +/* gives the pages back to the supplier once they are unmapped */ +void (*release)(struct page **pages,u32 page_cnt,void *priv); +void *priv; +long pgoff; +long page_cnt; +u32 uaddr;/* lower 32 bits of the user address */ +}; + +#define IMPORT_START (imp) ((imp)->pgoff) +#define IMPORT_LAST (imp) ((imp)->pgoff + (imp)->page_cnt - 1) +INTERVAL_TREE_DEFINE(struct arena_import, rb, long, subtree_last, IMPORT_START, IMPORT_LAST, + static inline __maybe_unused, arena_import_it) +u64 bpf_arena_get_kern_vm_start (struct bpf_arena *arena) {return arena ? (u64 ) (long ) arena->kern_vm->addr +GUARD_SZ /2 :0 ;
@@ -210,6 +239,8 @@ static long compute_pgoff(struct bpf_arena *arena, long uaddr)struct apply_range_data {struct bpf_arena *arena;struct llist_head *pages; +/* imported pages, they can't be linked through pcp_llist */ +struct page **ext_pages;int i;bool can_flush;/* the caller can flush TLB of all cpus after it drops the lock */ bool flush;
@@ -223,17 +254,21 @@ struct clear_range_data {static int apply_range_set_cb (pte_t *pte,unsigned long addr,void *data) {struct apply_range_data *d = data; -struct llist_node *node; +struct llist_node *node =NULL ;struct page *page;pte_t pteval;if (!data)return 0 ; - node =READ_ONCE (d->pages->first); -if (WARN_ON_ONCE (!node)) -return -EINVAL ; - page = llist_entry(node, struct page, pcp_llist); +if (d->ext_pages) { + page = d->ext_pages[d->i]; + }else { + node =READ_ONCE (d->pages->first); +if (WARN_ON_ONCE (!node)) +return -EINVAL ; + page = llist_entry(node, struct page, pcp_llist); + }/* paranoia, similar to vmap_pages_pte_range() */ if (WARN_ON_ONCE (!pfn_valid (page_to_pfn (page))))return -EINVAL ;
@@ -272,8 +307,11 @@ static int apply_range_set_cb(pte_t *pte, unsigned long addr, void *data)return -EBUSY ;set_pte_at (&init_mm, addr, pte, pteval);#endif -WARN_ON_ONCE (llist_del_first (d->pages) != node); d->i++; +/* Imported pages are accounted to their supplier */ +if (!node) +return 0 ; +WARN_ON_ONCE (llist_del_first (d->pages) != node);WRITE_ONCE (d->arena->nr_pages, d->arena->nr_pages +1 );return 0 ; }
@@ -332,6 +370,43 @@ static int apply_range_set_scratch_cb(pte_t *pte, unsigned long addr, void *datareturn 0 ; } +static int apply_range_clear_ext_cb (pte_t *pte,unsigned long addr,void *data) +{ +ptep_get_and_clear (&init_mm, addr, pte); +return 0 ; +} + +/* Under arena->spinlock, or when nothing else can use the arena anymore */ +static struct arena_import *arena_find_import (struct bpf_arena *arena,long pgoff) +{ +return arena_import_it_iter_first (&arena->imports, pgoff, pgoff); +} + +static u64 arena_import_kaddr (struct bpf_arena *arena,struct arena_import *imp) +{ +return bpf_arena_get_kern_vm_start (arena) + imp->uaddr; +} + +/* Like arena_find_import(), the caller flushes the TLB after */ +static void arena_unmap_import (struct bpf_arena *arena,struct arena_import *imp) +{ +apply_to_existing_page_range (&init_mm,arena_import_kaddr (arena, imp), + imp->page_cnt <<PAGE_SHIFT , apply_range_clear_ext_cb,NULL ); +} + +static void arena_flush_import (struct bpf_arena *arena,struct arena_import *imp) +{ +u64 kaddr =arena_import_kaddr (arena, imp); + +flush_tlb_kernel_range (kaddr, kaddr + (imp->page_cnt <<PAGE_SHIFT )); +} + +static void arena_release_import (struct arena_import *imp) +{ + imp->release (imp->pages, imp->page_cnt, imp->priv); +kfree (imp); +} +static int populate_pgtable_except_pte (struct bpf_arena *arena) {/* Populate intermediates for the recovery range (4 GiB + upper half-guard). */
@@ -383,6 +458,7 @@ static struct bpf_map *arena_map_alloc(union bpf_attr *attr) arena->user_vm_end = arena->user_vm_start + vm_range;INIT_LIST_HEAD (&arena->vma_list); + arena->imports =RB_ROOT_CACHED ;init_llist_head (&arena->free_spans);init_irq_work (&arena->free_irq, arena_free_irq);INIT_WORK (&arena->free_work, arena_free_worker);
@@ -451,6 +527,15 @@ static void arena_map_destroy(struct work_struct *work) { struct bpf_arena *arena = container_of(to_rcu_work(work), struct bpf_arena, destroy_work); +struct arena_import *imp; + +/* Imported pages go back to their supplier */ +while ((imp =arena_import_it_iter_first (&arena->imports,0 ,LONG_MAX ))) { +arena_import_it_remove (imp, &arena->imports); +arena_unmap_import (arena, imp); +arena_flush_import (arena, imp); +arena_release_import (imp); + }/* * free_vm_area() calls remove_vm_area() that calls free_unmap_vmap_area().
@@ -577,7 +662,7 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf)struct mem_cgroup *new_memcg, *old_memcg;LLIST_HEAD (pages);struct page *page, *new_page =NULL ; -struct apply_range_data data; +struct apply_range_data data = {};vm_fault_t fault_ret;long kbase, kaddr;unsigned long flags;
@@ -613,6 +698,15 @@ static vm_fault_t arena_vm_fault(struct vm_fault *vmf) page =vmalloc_to_page ((void *)kaddr);if (page) { +/* +* Not the arena's: user space maps the file or the device the +* pages come from +*/ +if (arena_find_import (arena, vmf->pgoff)) { + fault_ret = (arena->map.map_flags &BPF_F_SEGV_ON_FAULT ) + ?VM_FAULT_SIGSEGV :VM_FAULT_SIGBUS ; + goto out_err_locked; + }if (page == arena->scratch_page) {/* BPF triggered scratch here; don't lazy-alloc over it */ fault_ret = (arena->map.map_flags &BPF_F_SEGV_ON_FAULT )
@@ -861,7 +955,7 @@ static long arena_alloc_pages(struct bpf_arena *arena, long uaddr, long page_cntlong page_cnt_max = (arena->user_vm_end - arena->user_vm_start) >>PAGE_SHIFT ;u64 kern_vm_start =bpf_arena_get_kern_vm_start (arena);struct mem_cgroup *new_memcg, *old_memcg; -struct apply_range_data data; +struct apply_range_data data = {};LLIST_HEAD (pages);long mapped =0 ;unsigned long flags;
@@ -1019,9 +1113,12 @@ static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt)u64 full_uaddr =clear_lo32 (arena->user_vm_start) + uaddr;long kaddr =bpf_arena_get_kern_vm_start (arena) + uaddr;long pgoff =compute_pgoff (arena, uaddr); +long first = pgoff, last = pgoff + page_cnt -1 ; +struct arena_import *imp, *tmp;struct clear_range_data cdata;struct llist_node *pos, *t;LLIST_HEAD (free_pages); +LIST_HEAD (imports);unsigned long flags;struct page *page;int ret;
@@ -1042,6 +1139,15 @@ static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt)return 0 ; } +/* Imports are released whole, also the ones that are only partly in the range */ +while ((imp =arena_import_it_iter_first (&arena->imports, pgoff, pgoff + page_cnt -1 ))) { + first =min (first,IMPORT_START (imp)); + last =max (last,IMPORT_LAST (imp)); +arena_import_it_remove (imp, &arena->imports); +arena_unmap_import (arena, imp); +list_add (&imp->head, &imports); + } + cdata.arena = arena; cdata.free_pages = &free_pages;/* clear ptes and collect struct pages */
@@ -1059,6 +1165,8 @@ static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt)/* ensure no stale TLB entries */ flush_tlb_kernel_range (kaddr, kaddr + (page_cnt *PAGE_SIZE )); +list_for_each_entry (imp, &imports, head) +arena_flush_import (arena, imp);if (page_cnt >1 )/* bulk zap if multiple pages being freed */
@@ -1079,8 +1187,15 @@ static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt)/* The callers hold no other rqspinlock, so this one can only time out */ while (raw_res_spin_lock_irqsave (&arena->spinlock, flags))cond_resched (); -range_tree_set (&arena->rt, pgoff, page_cnt); +/* +* The range and the imports it overlaps are contiguous: set them at once, +* so that the imports need no more range tree nodes than the range alone +*/ +range_tree_set (&arena->rt, first, last - first +1 );raw_res_spin_unlock_irqrestore (&arena->spinlock, flags); + +list_for_each_entry_safe (imp, tmp, &imports, head) +arena_release_import (imp);return 0 ; }
@@ -1281,6 +1396,187 @@ static int arena_reserve_pages(struct bpf_arena *arena, long uaddr, u32 page_cntreturn ret; } +/* +* Map @page_cnt pages that the arena didn't allocate at @uaddr, which must be +* free. On success the arena keeps @pages until it calls @release, from +* process context, see struct arena_import. +*/ +static int arena_map_ext_pages (struct bpf_arena *arena,long uaddr,struct page **pages, +long page_cnt, +void (*release)(struct page **pages,u32 page_cnt,void *priv), +void *priv) +{ +/* The first mmap() may be setting the user range: a non-zero start is final */ +u64 user_vm_start =READ_ONCE (arena->user_vm_start); +struct apply_range_data data = { + .arena = arena, + .ext_pages = pages, + .can_flush = true, + }; +struct mem_cgroup *new_memcg, *old_memcg; +long page_cnt_max, pgoff, kaddr; +struct arena_import *imp; +unsigned long flags; +int ret; + +if (!user_vm_start) +return -EINVAL ; + page_cnt_max = ((long )READ_ONCE (arena->user_vm_end) - (long )user_vm_start) >>PAGE_SHIFT ; +if (!uaddr || (uaddr & ~PAGE_MASK ) || page_cnt > page_cnt_max) +return -EINVAL ; + pgoff = (u32)(uaddr - (u32 )user_vm_start) >>PAGE_SHIFT ; +if (pgoff > page_cnt_max - page_cnt) +return -EINVAL ; + kaddr =bpf_arena_get_kern_vm_start (arena) + (u32 )uaddr; + + imp =kmalloc_obj (*imp,GFP_KERNEL_ACCOUNT ); +if (!imp) +return -ENOMEM ; + imp->pages = pages; + imp->release = release; + imp->priv = priv; + imp->pgoff = pgoff; + imp->page_cnt = page_cnt; + imp->uaddr = (u32 )uaddr; + +bpf_map_memcg_enter (&arena->map, &old_memcg, &new_memcg); +if (raw_res_spin_lock_irqsave (&arena->spinlock, flags)) { + ret = -EBUSY ; + goto out; + } + ret =is_range_tree_set (&arena->rt, pgoff, page_cnt) ? -EBUSY : +range_tree_clear (&arena->rt, pgoff, page_cnt); +if (!ret) { +/* The page tables are there, and a free range has at most the scratch page */ +WARN_ON_ONCE (apply_to_page_range (&init_mm, kaddr, page_cnt <<PAGE_SHIFT , + apply_range_set_cb, &data)); +flush_vmap_cache (kaddr, page_cnt <<PAGE_SHIFT ); +arena_import_it_insert (imp, &arena->imports); + } +raw_res_spin_unlock_irqrestore (&arena->spinlock, flags); +if (data.flush) +flush_tlb_kernel_range (kaddr, kaddr + (page_cnt <<PAGE_SHIFT )); +out: +bpf_map_memcg_exit (old_memcg, new_memcg); +if (ret) +kfree (imp); +return ret; +} + +static void arena_release_file_pages (struct page **pages,u32 page_cnt,void *priv) +{ +struct file *file = priv; + +/* BPF programs write through the kernel mapping, which doesn't track dirty */ +unpin_user_pages_dirty_lock (pages, page_cnt, true); +kvfree (pages); +put_write_access (file_inode (file)); +fput (file); +} + +/* +* Import the pages of a memfd or of a file on tmpfs or hugetlbfs. Every file +* there has seals: one that isn't a memfd reports F_SEAL_SEAL alone. Other +* files have none and can't be imported. +*/ +static int arena_import_file (struct bpf_arena *arena,long uaddr,u32 page_cnt, +struct file *file,u64 off) +{ +long i, nr_folios, first, cnt =0 ; +struct folio **folios; +struct page **pages; +pgoff_t folio_off; +int seals, ret; + +/* +* Like a writable open: exec of the file fails with -ETXTBSY until the +* pages are released, and a file being executed can't be imported. +* Keeping the file open isn't enough, a memfd holds no write access. +*/ + ret =get_write_access (file_inode (file)); +if (ret) +return ret; + + folios =kvmalloc_array (page_cnt,sizeof (*folios),GFP_KERNEL_ACCOUNT ); + pages =kvmalloc_array (page_cnt,sizeof (*pages),GFP_KERNEL_ACCOUNT ); +if (!folios || !pages) { + ret = -ENOMEM ; + goto out; + } + +/* +* Adding F_SEAL_WRITE takes the inode lock and fails while pages are +* pinned: hold it until they are, like udmabuf +*/ +inode_lock_shared (file_inode (file)); + seals =memfd_get_seals (file); +if (seals <0 ) + nr_folios = -EINVAL ; +else if ((seals & (F_SEAL_WRITE |F_SEAL_FUTURE_WRITE )) ||IS_APPEND (file_inode (file))) + nr_folios = -EPERM ; +else + nr_folios =memfd_pin_folios (file, off, + off + ((u64 )page_cnt <<PAGE_SHIFT ) -1 , + folios, page_cnt, &folio_off); +inode_unlock_shared (file_inode (file)); +if (nr_folios <=0 ) { + ret = nr_folios ?: -EINVAL ; + goto out; + } + +/* One pin per page, like pin_user_pages() */ +for (i =0 ; i < nr_folios; i++, folio_off =0 ) { + first = cnt; +for (; folio_off <folio_size (folios[i]) && cnt < page_cnt; + folio_off +=PAGE_SIZE ) + pages[cnt++] =folio_page (folios[i], folio_off >>PAGE_SHIFT ); +if (cnt - first >1 &&folio_add_pins (folios[i], cnt - first -1 )) { +unpin_folios (folios + i, nr_folios - i); + cnt = first; + ret = -ENOMEM ; + goto out; + } + } + +if (cnt != page_cnt) { + ret = -EINVAL ; + goto out; + } +/* The arena can release the pages as soon as they are mapped */ +get_file (file); + ret =arena_map_ext_pages (arena, uaddr, pages, page_cnt, arena_release_file_pages, file); +if (ret) +fput (file); +out: +if (ret) { +unpin_user_pages (pages, cnt); +kvfree (pages); +put_write_access (file_inode (file)); + } +kvfree (folios); +return ret; +} + +static int arena_import_memfd (struct bpf_arena *arena,long uaddr,u32 page_cnt,int fd, +u64 off) +{ +int ret; + +if (off & ~PAGE_MASK ) +return -EINVAL ; + +CLASS (fd, f)(fd); +if (fd_empty (f)) +return -EBADF ; +/* BPF programs read and write it like a shared mapping, which needs the same */ +if ((fd_file (f)->f_mode & (FMODE_READ |FMODE_WRITE )) != (FMODE_READ |FMODE_WRITE )) +return -EPERM ; + ret =security_mmap_file (fd_file (f),PROT_READ |PROT_WRITE ,MAP_SHARED ); +if (ret) +return ret; +return arena_import_file (arena, uaddr, page_cnt,fd_file (f), off); +} +static void arena_free_worker (struct work_struct *work) { struct bpf_arena *arena = container_of(work, struct bpf_arena, free_work);
@@ -1378,6 +1674,50 @@ __bpf_kfunc int bpf_arena_reserve_pages(void *p__map, void *ptr__ign, u32 page_creturn arena_reserve_pages (arena, (long )ptr__ign, page_cnt); } + +/** +* bpf_arena_import_memfd - map the pages of a memfd into an arena +* @p__map: the arena +* @addr__ign: page-aligned arena address where the pages are mapped +* @page_cnt: number of pages to import +* @fd: memfd, or file on tmpfs or hugetlbfs, open for reading and writing +* @off: page-aligned offset in the file +* +* Pin the pages of @fd at @off and map them at @addr__ign, which must be free. +* They stay until bpf_arena_free_pages() frees any of them, which releases the +* whole import, or until the arena is destroyed. Their content stays in the +* file. User space accesses them by mapping @fd: the arena mapping raises +* SIGBUS (SIGSEGV with BPF_F_SEGV_ON_FAULT) at their addresses. The first page +* of an arena that starts on a 4GB boundary can't be imported: its address +* reaches the kfunc as NULL. +* +* @fd is looked up in the current task, so the kfunc fails in async callbacks, +* which may run in another one. The pages of any holes in the range are +* allocated, as a write to the file would, and stay in the file. +* +* F_SEAL_SHRINK is not required, a file on tmpfs can't be sealed. The supplier +* must not shrink the file below the imported range or punch holes in it: the +* arena would keep the pages it pinned, which are no longer the file's. +* +* While its pages are imported, the file can't be executed, as when it's open +* for writing, and a file being executed can't be imported. +* +* Return: 0 on success, -EPERM in an async callback, negative error code +* otherwise. +*/ +__bpf_kfunc int bpf_arena_import_memfd(void *p__map, void *addr__ign, u32 page_cnt, +int fd,u64 off) +{ +struct bpf_map *map = p__map; + struct bpf_arena *arena = container_of(map, struct bpf_arena, map); + +/* Only the task that runs the program can import pages */ +if (bpf_in_async_cb ()) +return -EPERM ; +if (map->map_type !=BPF_MAP_TYPE_ARENA || !page_cnt || page_cnt > map->max_entries) +return -EINVAL ; +return arena_import_memfd (arena, (long )addr__ign, page_cnt, fd, off); +}__bpf_kfunc_end_defs ();BTF_KFUNCS_START (arena_kfuncs)
@@ -1392,9 +1732,19 @@ static const struct btf_kfunc_id_set common_kfunc_set = { .set = &arena_kfuncs, }; +BTF_KFUNCS_START (arena_syscall_kfuncs) +BTF_ID_FLAGS(func, bpf_arena_import_memfd, KF_ARENA_ARG2 | KF_SLEEPABLE | KF_PERFMON) +BTF_KFUNCS_END (arena_syscall_kfuncs) + +static const struct btf_kfunc_id_set syscall_kfunc_set = { + .owner =THIS_MODULE , + .set = &arena_syscall_kfuncs, +}; + static int __init kfunc_init(void) { -return register_btf_kfunc_id_set (BPF_PROG_TYPE_UNSPEC , &common_kfunc_set); +return register_btf_kfunc_id_set (BPF_PROG_TYPE_UNSPEC , &common_kfunc_set) ?: +register_btf_kfunc_id_set (BPF_PROG_TYPE_SYSCALL , &syscall_kfunc_set); }late_initcall (kfunc_init);
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 2/5] bpf: Allow importing memfd pages into an arena
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf: redundant TLB flushes, PTE walks, and VMA zaps in arena_free_range() --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: redundant TLB flushes, PTE walks, and VMA zaps in arena_free_range()
--
commit d96cf4c4916f7758809e32ec47ce01b90e4ddf99
Author: Andrea Righi <[email protected]>
bpf: Allow importing memfd pages into an arena
This commit allows BPF arenas to map externally supplied pages and adds the bpf_arena_import_memfd() kfunc to pin and import pages from memfd, tmpfs, or hugetlbfs files into an arena.
Quoted 4 lines
kernel/bpf/arena.c +0
-0
[ ... ]
Quoted 30 lines
kernel/bpf/arena.c +12
-0@@ -1019,9 +1113,12 @@ static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt)u64 full_uaddr =clear_lo32 (arena->user_vm_start) + uaddr;long kaddr =bpf_arena_get_kern_vm_start (arena) + uaddr;long pgoff =compute_pgoff (arena, uaddr); +long first = pgoff, last = pgoff + page_cnt -1 ; +struct arena_import *imp, *tmp;struct clear_range_data cdata;struct llist_node *pos, *t;LLIST_HEAD (free_pages); +LIST_HEAD (imports);unsigned long flags;struct page *page;int ret;@@ -1042,6 +1139,15 @@ static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt)return 0 ; } +/* Imports are released whole, also the ones that are only partly in the range */ +while ((imp =arena_import_it_iter_first (&arena->imports, pgoff, pgoff + page_cnt -1 ))) { + first =min (first,IMPORT_START (imp)); + last =max (last,IMPORT_LAST (imp)); +arena_import_it_remove (imp, &arena->imports); +arena_unmap_import (arena, imp); +list_add (&imp->head, &imports); + } + cdata.arena = arena; cdata.free_pages = &free_pages;/* clear ptes and collect struct pages */
kernel/bpf/arena.c static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt) · line 1172
Quoted 8 lines
kernel/bpf/arena.c +2
-0@@ -1059,6 +1165,8 @@ static int arena_free_range(struct bpf_arena *arena, long uaddr, long page_cnt)/* ensure no stale TLB entries */ flush_tlb_kernel_range (kaddr, kaddr + (page_cnt *PAGE_SIZE )); +list_for_each_entry (imp, &imports, head) +arena_flush_import (arena, imp);if (page_cnt >1 )/* bulk zap if multiple pages being freed */
[Severity: Medium]
Does freeing a range that overlaps imported pages issue redundant TLB shootdowns, duplicate PTE walks, and unnecessary VMA zaps?
Because the freed range and any overlapping imports form a single contiguous range [first, last], flushing [kaddr, kaddr + page_cnt * PAGE_SIZE) and then calling arena_flush_import() for each import issues overlapping cross-CPU TLB shootdowns instead of one flush across [first, last]. Similarly, arena_map_destroy() calls arena_flush_import() inside its per-import loop rather than unmapping all imports and flushing once.
In addition, calling arena_unmap_import() before apply_to_existing_page_range() walks and clears the overlapping import PTEs twice under arena->spinlock, and when page_cnt > 1, zap_pages() still takes arena->lock and mmap_read_lock() across all user VMAs even when free_pages is empty because only imported pages (which are never faulted into arena user VMAs) were unmapped.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
Andrea Righi
reviewerPATCH v3 3/5 bpf: Let kernel code import pages into an arena
In reply to Andrea RighiA paravirt transport, such as pvsched, can share guest memory with the host without a file: the guest registers ordinary pages with a device, and the host driver pins them. Such a driver needs to map the pages into an arena, and to revoke them synchronously when the guest detaches or the VM goes away, without waiting for BPF programs to free them.
Add a kernel API around the imports of the arena:
int bpf_arena_map_ext_pages(struct bpf_map *map, u64 addr,
struct page **pages, u32 page_cnt, void (*release)(struct page **pages,
u32 page_cnt, void *priv),
void *priv);
int bpf_arena_unmap_ext_pages(struct bpf_map *map, u64 addr,
void *priv);
The pages are mapped like the ones of a memfd and stay the caller's:
the arena calls release once it no longer maps them, whether bpf_arena_unmap_ext_pages() revoked them, a BPF program freed them or the arena was destroyed. bpf_arena_unmap_ext_pages() returns after the release, so the caller can free the pages then. BPF accesses to revoked pages fault like the ones to free arena pages.
--- include/linux/bpf.h | 21 ++++++++++ kernel/bpf/arena.c | 96 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 115 insertions(+), 2 deletions(-)
include/linux/bpf.h +21 -0
@@ -787,6 +787,27 @@ static inline void *bpf_arena_alloc_pages_sleepable(void *p__map, void *addr__ig }#endif +#if defined(CONFIG_BPF_SYSCALL ) && defined(CONFIG_MMU ) && defined(CONFIG_64BIT ) +int bpf_arena_map_ext_pages (struct bpf_map *map,u64 addr,struct page **pages,u32 page_cnt, +void (*release)(struct page **pages,u32 page_cnt,void *priv), +void *priv); +int bpf_arena_unmap_ext_pages (struct bpf_map *map,u64 addr,void *priv); +#else +static inline int bpf_arena_map_ext_pages (struct bpf_map *map,u64 addr,struct page **pages, +u32 page_cnt, +void (*release)(struct page **pages,u32 page_cnt, +void *priv), +void *priv) +{ +return -EOPNOTSUPP ; +} + +static inline int bpf_arena_unmap_ext_pages (struct bpf_map *map,u64 addr,void *priv) +{ +return -EOPNOTSUPP ; +} +#endif +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/arena.c +94 -2
120 lines not on this page · raw message
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 3/5] bpf: Let kernel code import pages into an arena
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] bpf: pending bpf_arena_free_pages() frees reallocated pages after unmap - [Medium] bpf: redundant…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] bpf: pending bpf_arena_free_pages() frees reallocated pages after unmap
- [Medium] bpf: redundant TLB flushes and VMA zapping in bpf_arena_unmap_ext_pages()
--
commit c1c5f31a6539d777582fe2bfea7ec8bf0b090c7d
Author: Andrea Righi <[email protected]>
bpf: Let kernel code import pages into an arena
This commit adds bpf_arena_map_ext_pages() and bpf_arena_unmap_ext_pages() so kernel code can map external pages into a BPF arena and synchronously revoke them.
Quoted 4 lines
kernel/bpf/arena.c +0
-0
[ ... ]
Quoted 1 line
kernel/bpf/arena.c +0
-0@@ -1603,6 +1609,92 @@ static void arena_free_irq(struct irq_work *iw)
[ ... ]
Quoted 17 lines
kernel/bpf/arena.c +17
-0+int bpf_arena_unmap_ext_pages (struct bpf_map *map,u64 addr,void *priv) +{ + struct bpf_arena *arena = container_of(map, struct bpf_arena, map); +struct mem_cgroup *new_memcg, *old_memcg; +struct arena_import *imp; +long pgoff, page_cnt =0 ; +unsigned long flags; + +if (map->map_type !=BPF_MAP_TYPE_ARENA || (addr & ~PAGE_MASK )) +return -EINVAL ; +/* Pages were mapped: the user range is set */ +if (!READ_ONCE (arena->user_vm_start)) +return -ENOENT ; + pgoff =compute_pgoff (arena, addr); + +/* A concurrent free releases the pages before this finds them gone */ +guard (mutex)(&arena->zap_mutex);
kernel/bpf/arena.c static void arena_free_irq(struct irq_work *iw) · line 1688
Quoted 10 lines
kernel/bpf/arena.c +10
-0+ +/* No other rqspinlock is held, so this one can only time out */ +while (raw_res_spin_lock_irqsave (&arena->spinlock, flags)) +cond_resched (); + imp =arena_find_import (arena, pgoff); +if (imp &&IMPORT_START (imp) == pgoff && imp->priv == priv) + page_cnt = imp->page_cnt; +raw_res_spin_unlock_irqrestore (&arena->spinlock, flags); +if (!page_cnt) +return -ENOENT ;
[Severity: Medium]
Can a pending bpf_arena_free_pages() on the same import end up freeing unrelated pages that were reallocated at addr after bpf_arena_unmap_ext_pages() returns?
When a non-sleepable BPF program calls bpf_arena_free_pages() (or when arena_free_range() hits spinlock contention), arena_free_pages() queues an arena_free_span by raw uaddr onto arena->free_spans and schedules arena->free_irq and arena->free_work. A sleepable bpf_arena_free_pages() can also block on arena->zap_mutex behind bpf_arena_unmap_ext_pages().
Because bpf_arena_unmap_ext_pages() does not flush pending free work and returns the pgoff range to arena->rt, a subsequent allocation can reuse that virtual address range before the pending free runs:
CPU0 CPU1 (kworker)bpf_arena_free_pages(addr)
arena_free_pages(..., false)
llist_add(..., &arena->free_spans)
irq_work_queue(&arena->free_irq)bpf_arena_unmap_ext_pages(addr)
mutex_lock(&arena->zap_mutex)
__arena_free_range(addr)
arena_import_it_remove(imp)
...
range_tree_set(&arena->rt, ...)
arena_release_import(imp) mutex_unlock(&arena->zap_mutex)
bpf_arena_alloc_pages()
range_tree_find(&arena->rt, ...)
/* reallocates addr */
arena_free_worker()
arena_free_range(addr)
/* unmaps and frees new pages */kernel/bpf/arena.c static void arena_free_irq(struct irq_work *iw) · line 1692
Quoted 4 lines
kernel/bpf/arena.c +4
-0+ +bpf_map_memcg_enter (&arena->map, &old_memcg, &new_memcg); +while (__arena_free_range (arena, (u32 )addr, page_cnt)) +cond_resched ();
[Severity: Medium]
Does calling __arena_free_range() here do redundant page-table walks, duplicate TLB shootdowns, and unnecessary user VMA zapping after imp has already been found?
Under arena->spinlock with IRQs disabled, __arena_free_range() searches arena->imports again, calls arena_unmap_import() to clear the kernel PTEs, and then walks the same [kaddr, kaddr + (page_cnt << PAGE_SHIFT)) range a second time in apply_to_existing_page_range(). After dropping the lock, it calls flush_tlb_kernel_range() on that range and immediately flushes the same range a second time via arena_flush_import():
kernel/bpf/arena.c:__arena_free_range() {
...
flush_tlb_kernel_range(kaddr, kaddr + (page_cnt * PAGE_SIZE));
list_for_each_entry(imp, &imports, head)
arena_flush_import(arena, imp);
if (page_cnt > 1)
/* bulk zap if multiple pages being freed */
zap_pages(arena, full_uaddr, page_cnt);
...
}When page_cnt > 1, it also calls zap_pages() across all user VMAs in arena->vma_list even though imported pages are never mapped into user VMAs (arena_vm_fault() rejects them). Unmapping imp directly under arena->spinlock and then flushing, returning the range to arena->rt, and calling arena_release_import() would avoid the extra walks and TLB shootdown.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
Re: [PATCH 3/5] bpf: Let kernel code import pages into an arena
In reply to Andrea RighiQuoted 23 lines · Andrea Righi
A paravirt transport, such as pvsched, can share guest memory with the host without a file: the guest registers ordinary pages with a device, and the host driver pins them. Such a driver needs to map the pages into an arena, and to revoke them synchronously when the guest detaches or the VM goes away, without waiting for BPF programs to free them.
Add a kernel API around the imports of the arena:
int bpf_arena_map_ext_pages(struct
bpf_map*map, u64 addr,
struct page **pages, u32page_cnt, void (*release)(struct page **pages,
u32page_cnt, void *priv),
void *priv);
int bpf_arena_unmap_ext_pages(structbpf_map*map, u64 addr,void *priv);The pages are mapped like the ones of a memfd and stay the caller's:
the arena calls release once it no longer maps them, whetherbpf_arena_unmap_ext_pages()revoked them, a BPF program freed them or the arena was destroyed.bpf_arena_unmap_ext_pages()returns after the release, so the caller can free the pages then. BPF accesses to revoked pages fault like the ones to free arena pages.
Quoted 2 lines
Suggested-by Vineeth Pillai <[email protected]>Signed-off-by Andrea Righi <[email protected]>
Only half of the patches reached bpf list.
In this shape is unreviewable.
pw-bot: cr
Andrea Righi
reviewerRe: [PATCH 3/5] bpf: Let kernel code import pages into an arena
Hi Alexei,
On Thu, Dec 03, 2026 at 04:25:33AM +0000, Alexei Starovoitov wrote:
...
Quoted 2 lines
Only half of the patches reached bpf list.
In this shape is unreviewable.
I'm hitting this issue quite often recently with kernel.org addresses that forward to Gmail. I checked the bounces and Gmail rejected your copies of the cover letter, 2/5 and 5/5 after forwarding through [email protected], reporting an SPF failure for kernel.org.
But it looks like all five patches and the cover letter reached the BPF list:
https://lore.kernel.org/bpf/[email protected]
Konstantin, is there anything we can do on our side to avoid these delivery failures?
Thanks,
-Andrea
Re: [PATCH 3/5] bpf: Let kernel code import pages into an arena
Quoted 10 lines · Andrea Righi
On Thu, Dec 03, 2026 at 04:25:33AM +0000, Alexei Starovoitov wrote:
...Quoted 2 lines
Only half of the patches reached bpf list.
In this shape is unreviewable.I'm hitting this issue quite often recently with kernel.org addresses that forward to Gmail. I checked the bounces and Gmail rejected your copies of the cover letter, 2/5 and 5/5 after forwarding through [email protected], reporting an SPF failure for kernel.org.
Quoted 6 lines
But it looks like all five patches and the cover letter reached the BPF list:
https://lore.kernel.org/bpf/[email protected]Konstantin, is there anything we can do on our side to avoid these delivery failures?
Unfortunately, no. Gmail is pretty awful these days.
Take this particular case:
Dec 2 18:27:25 ... postfix/smtp[207088]: A6DEA4540D: to=<[email protected]>, relay=gmail-smtp-in.l.google.com[2607:f8b0:400e:c09::1a]:25, delay=0.44, delays=0.03/0/0.27/0.14, dsn=4.7.28, status=deferred (host gmail-smtp-in.l.google.com[2607:f8b0:400e:c09::1a] said: 421-4.7.28 Gmail has detected this message exceeded its quota for sending 421-4.7.28 messages with the same Message-ID. To best protect our users, the 421-4.7.28 message has been temporarily rejected. For more information, go to 421 4.7.28 https://support.google.com/mail/answer/188131 41be03b00d2f7-cde6ceca70csi69339089a12.1 - gsmtp (in reply to end of DATA command))
"This message exceeded its quota for sending messages" is just chef's kiss. Even when worded properly, it's just a completely arbitrary metric invented by Gmail to stop legitimate mail from getting delivered.
Dec 2 18:42:03 ... postfix/smtp[235252]: C0BE3455DF: to=<[email protected]>, relay=gmail-smtp-in.l.google.com[74.125.195.26]:25, delay=0.32, delays=0.01/0.01/0.06/0.24, dsn=2.0.0, status=sent (250 2.0.0 OK 1796236923 d9443c01a7336-2f0472a7856si957428775ad.47 - gsmtp) Dec 2 18:43:15 ... postfix/smtp[235251]: A6DEA4540D: to=<[email protected]>, relay=gmail-smtp-in.l.google.com[74.125.195.26]:25, conn_use=7, delay=951, delays=950/0.42/0.15/0.16, dsn=5.7.27, status=bounced (host gmail-smtp-in.l.google.com[74.125.195.26] said: 550-5.7.27 Your email has been blocked because SPF authentication didn't pass 550-5.7.27 for this message. Gmail requires all bulk email senders to 550-5.7.27 authenticate Authentication results: 550-5.7.27 SPF [kernel.org] with ip: [172.234.252.31] = did not pass 550-5.7.27 550-5.7.27 To set up SPF for your sending domains, visit 550-5.7.27 https://support.google.com/a?p=setup-spf 550-5.7.27 To learn more about Gmail requirements for bulk senders, visit 550 5.7.27 https://support.google.com/a?p=sender-guidelines. d2e1a72fcca58-8c872c5153csi91938962b3a.70 - gsmtp (in reply to end of DATA command))
This one is my favourite -- two back-to-back messages with one passing the SPF check and the other, from the exact same IP a minute later, failing the SPF check. I'm guessing because some lookup failed and Gmail doesn't believe in caching? And then immediately at that exact second:
Dec 2 18:43:15 ... postfix/smtp[230805]: 450BA441EF: to=<[email protected]>, relay=gmail-smtp-in.l.google.com[74.125.195.26]:25, conn_use=2, delay=923, delays=922/0.69/0.16/0.1, dsn=4.7.28, status=deferred (host gmail-smtp-in.l.google.com[74.125.195.26] said: 421-4.7.28 Gmail has detected this message exceeded its quota for sending 421-4.7.28 messages with the same Message-ID. To best protect our users, the 421-4.7.28 message has been temporarily rejected. For more information, go to 421 4.7.28 https://support.google.com/mail/answer/188131 d9443c01a7336-2f12cd525e6si301869005ad.31 - gsmtp (in reply to end of DATA command))
SPF passes again! But only to trip on the same "too many messages with this message-id".
I wish everyone could stop using Gmail as it's rapidly approaching unusable for any serious work. Unfortunately, I can't make this happen, and there is also nothing I can do to stop Gmail from arbitrarily rejecting legitimate mail.
My best recommendation is to switch to using korgalore for mail delivery if you must use Gmail.
https://korgalore.docs.kernel.org/
-K
Andrea Righi
reviewerPATCH v3 4/5 bpf: Allow importing device-dax pages into an arena
In reply to Andrea Righibpf_arena_import_memfd() covers the host side of a host/guest shared
arena: the host imports a memfd and hands the same file to the VMM. The guest has no such file. The host memory can be exposed to the guest as a virtio-pmem or NVDIMM device, which the guest turns into a device-dax device, /dev/daxX.Y.
Add a sleepable kfunc for syscall programs that imports the device-dax pages mapped at an address of the calling task:
int bpf_arena_import_dax(void *map, void __arena *addr,
u32 page_cnt, u64 src);
The pages are pinned with pin_user_pages(FOLL_LONGTERM) and mapped like memfd imports. Only a device-dax mapping is accepted, checked under mmap_lock together with the pin.
A pin doesn't keep the dev_pagemap alive, so the import holds a reference on it until the pages are released. Unbinding the device blocks until
then: the dax core doesn't notify its users, so the pages can't be revoked.
To not race with an unbind before it takes that reference, the import pins the pages under the dax SRCU and checks that the device is alive, like the device-dax fault path. This needs the dax core built in, otherwise the kfunc returns -EOPNOTSUPP.
Like bpf_arena_import_memfd(), the kfunc fails in async callbacks and is marked KF_PERFMON.
This works with QEMU and Firecracker today, without changes to the VMM. It may be deprecated once a paravirt transport, such as pvsched, can supply guest pages through bpf_arena_map_ext_pages().
--- kernel/bpf/arena.c | 139 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 139 insertions(+)
kernel/bpf/arena.c +139 -0
@@ -7,7 +7,10 @@#include <linux/file.h> #include <linux/interval_tree_generic.h> #include <linux/irq_work.h> +#include <linux/magic.h> #include <linux/memfd.h> +#include <linux/dax.h> +#include <linux/memremap.h> #include "linux/filter.h" #include <linux/llist.h> #include <linux/mman.h>
@@ -1583,6 +1586,102 @@ static int arena_import_memfd(struct bpf_arena *arena, long uaddr, u32 page_cnt,return arena_import_file (arena, uaddr, page_cnt,fd_file (f), off); } +/* +* A device-dax file maps the inode of its dax_device, which lives on the dax +* pseudo filesystem, whatever CONFIG_FS_DAX says (S_DAX is 0 without it). +*/ +static bool vma_is_devdax (struct vm_area_struct *vma) +{ +struct file *file = vma->vm_file; + +return file && file->f_mapping->host->i_sb->s_magic ==DAXFS_MAGIC ; +} + +static void arena_release_dax_pages (struct page **pages,u32 page_cnt,void *priv) +{ +unpin_user_pages_dirty_lock (pages, page_cnt, true); +/* After the pins: the memmap of the pages goes away with it */ +put_dev_pagemap (priv); +kvfree (pages); +} + +/* +* Import the device-dax pages mapped at [src, src + page_cnt * PAGE_SIZE) in +* the calling task. Only device-dax is accepted: other drivers hand out +* MEMORY_DEVICE_GENERIC pages too (e.g. Xen grants). +*/ +static int arena_import_dax (struct bpf_arena *arena,long uaddr,u32 page_cnt,u64 src) +{ +struct mm_struct *mm = current->mm; +struct dev_pagemap *pgmap =NULL ; +struct vm_area_struct *vma; +long i, pinned =0 ; +struct page **pages; +int ret = -EINVAL ; +int id; + +/* The dax SRCU, below, can't be reached from here if the dax core is a module */ +if (!IS_BUILTIN (CONFIG_DAX )) +return -EOPNOTSUPP ; +/* Kernel code may run the program without an address space */ + src =untagged_addr (src); +if (!mm || (src & ~PAGE_MASK )) +return -EINVAL ; + + pages =kvmalloc_array (page_cnt,sizeof (*pages),GFP_KERNEL_ACCOUNT ); +if (!pages) +return -ENOMEM ; + +mmap_read_lock (mm); +/* +* A pin doesn't keep the memmap of device pages: an unbind can free it +* until a dev_pagemap reference is held. It kills the dax device first, +* then waits for the readers of the dax SRCU: the memmap stays if the +* device is alive here, as in the fault path. Pages that are mapped +* already are pinned without a fault, so check it here too. +*/ + id =dax_read_lock (); + vma =vma_lookup (mm, src); +if (!vma || !vma_is_devdax (vma) || + ((unsigned long )page_cnt <<PAGE_SHIFT ) > vma->vm_end - src) + goto out_unlock; +if (!dax_alive (inode_dax (vma->vm_file->f_mapping->host))) { + ret = -ENXIO ; + goto out_unlock; + } + pinned =pin_user_pages (src, page_cnt,FOLL_WRITE |FOLL_LONGTERM , pages); +if (pinned <0 ) + ret = pinned; +else if (pinned == page_cnt &&is_zone_device_page (pages[0 ])) + pgmap =get_dev_pagemap (page_to_pfn (pages[0 ])); +if (pgmap && pgmap->type ==MEMORY_DEVICE_GENERIC ) { + ret =0 ; +/* All of the pages are on the device of the mapping */ +for (i =1 ; i < pinned; i++) +if (!is_zone_device_page (pages[i]) ||page_pgmap (pages[i]) != pgmap) + ret = -EINVAL ; + } +/* Still under the lock: there may be no dev_pagemap reference */ +if (ret && pinned >0 ) { +unpin_user_pages (pages, pinned); + pinned =0 ; + } +out_unlock: +dax_read_unlock (id); +mmap_read_unlock (mm); + +if (!ret) + ret =arena_map_ext_pages (arena, uaddr, pages, page_cnt, arena_release_dax_pages, + pgmap); +if (ret) { +if (pinned >0 ) +unpin_user_pages (pages, pinned); +put_dev_pagemap (pgmap); +kvfree (pages); + } +return ret; +} +static void arena_free_worker (struct work_struct *work) { struct bpf_arena *arena = container_of(work, struct bpf_arena, free_work);
@@ -1810,6 +1909,45 @@ __bpf_kfunc int bpf_arena_import_memfd(void *p__map, void *addr__ign, u32 page_creturn -EINVAL ;return arena_import_memfd (arena, (long )addr__ign, page_cnt, fd, off); } + +/** +* bpf_arena_import_dax - map device-dax pages of the calling task into an arena +* @p__map: the arena +* @addr__ign: page-aligned arena address where the pages are mapped +* @page_cnt: number of pages to import +* @src: page-aligned address of a writable device-dax mapping in the calling task +* +* Pin the pages backing @src and map them at @addr__ign, like +* bpf_arena_import_memfd() does with the pages of a file. The whole range must +* be in one mapping of a device-dax device, e.g. the /dev/daxX.Y that a guest +* gets from a virtio-pmem or NVDIMM device backed by host memory, which the +* host imports by file. User space keeps accessing the pages through @src. +* +* Imported pages keep the device in use: unbinding or removing it blocks until +* the arena releases them, for as long as a map fd or a bpffs pin keeps the +* arena alive. +* +* BPF programs have no machine check recovery: on a real NVDIMM, the supplier +* has to keep bad pages out of the arena. +* +* The kfunc uses the address space of the current task, so it fails in async +* callbacks, which may run in another one. +* +* Return: 0 on success, -EPERM in an async callback, -EOPNOTSUPP if the dax core +* is a module, negative error code otherwise. +*/ +__bpf_kfunc int bpf_arena_import_dax(void *p__map, void *addr__ign, u32 page_cnt, u64 src) +{ +struct bpf_map *map = p__map; + struct bpf_arena *arena = container_of(map, struct bpf_arena, map); + +/* Only the task that runs the program can import pages */ +if (bpf_in_async_cb ()) +return -EPERM ; +if (map->map_type !=BPF_MAP_TYPE_ARENA || !page_cnt || page_cnt > map->max_entries) +return -EINVAL ; +return arena_import_dax (arena, (long )addr__ign, page_cnt, src); +}__bpf_kfunc_end_defs ();BTF_KFUNCS_START (arena_kfuncs)
@@ -1826,6 +1964,7 @@ static const struct btf_kfunc_id_set common_kfunc_set = { BTF_KFUNCS_START(arena_syscall_kfuncs) BTF_ID_FLAGS(func, bpf_arena_import_memfd, KF_ARENA_ARG2 | KF_SLEEPABLE | KF_PERFMON) +BTF_ID_FLAGS(func, bpf_arena_import_dax, KF_ARENA_ARG2 | KF_SLEEPABLE | KF_PERFMON) BTF_KFUNCS_END(arena_syscall_kfuncs) static const struct btf_kfunc_id_set syscall_kfunc_set = {
Signature · 1 line
2.56.1
Andrea Righi
reviewerPATCH v3 5/5 selftests/bpf: Test importing pages into an arena
In reply to Andrea RighiCheck that pages imported with bpf_arena_import_memfd() are shared between BPF programs and user space mapping the memfd, that they outlive the arena, that freeing any of them releases the whole import while their data stays in the memfd, that invalid or overlapping imports are rejected, and that user space faults on them through the arena mapping.
Also check that bpf_arena_import_dax() rejects anything but a device-dax mapping. Importing device-dax pages needs a device-dax device.
Add kfuncs to bpf_testmod that import pages of the module with bpf_arena_map_ext_pages(), like a paravirt transport would, and revoke them with bpf_arena_unmap_ext_pages(). Check that BPF programs see the pages, that only the start of the import revokes it, that the pages are released by the time the revoke returns and BPF reads zero there, and that a BPF free releases them first.
Check that the import kfuncs fail when a bpf_task_work callback calls them.
--- .../selftests/bpf/prog_tests/arena_import.c | 553 ++++++++++++++++++ .../selftests/bpf/progs/arena_import.c | 170 ++++++ .../selftests/bpf/test_kmods/bpf_testmod.c | 90 +++ .../bpf/test_kmods/bpf_testmod_kfunc.h | 3 + 4 files changed, 816 insertions(+) create mode 100644 tools/testing/selftests/bpf/prog_tests/arena_import.c create mode 100644 tools/testing/selftests/bpf/progs/arena_import.c
tools/testing/selftests/bpf/prog_tests/arena_import.c new file +553 -0
@@ -0,0 +1,553 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2026 NVIDIA Corporation */ + +#include <test_progs.h> +#include <fcntl.h> +#include <signal.h> +#include <stdatomic.h> +#include <sys/mman.h> +#include <sys/wait.h> +#include <unistd.h> + +#include "arena_import.skel.h" + +#define MEMFD_PAGES 4 + +#ifndef F_SEAL_FUTURE_WRITE +#define F_SEAL_FUTURE_WRITE 0x0010 +#endif + +static long ps; + +static int run (struct bpf_program *prog) +{ +LIBBPF_OPTS (bpf_test_run_opts, opts); +int err; + + err =bpf_prog_test_run_opts (bpf_program__fd (prog), &opts); +if (!ASSERT_OK (err,bpf_program__name (prog))) +return -1 ; +return opts.retval; +} + +static int do_import (struct arena_import *skel,int fd,long fd_off,__u32 pg,__u32 cnt) +{ + skel->bss->fd = fd; + skel->bss->fd_off = fd_off; + skel->bss->pg = pg; + skel->bss->page_cnt = cnt; + skel->bss->ret =1 ; +if (run (skel->progs.op_import)) +return 1 ; +return skel->bss->ret; +} + +static int do_import_dax (struct arena_import *skel,void *src,__u32 pg,__u32 cnt) +{ + skel->bss->src = (unsigned long )src; + skel->bss->pg = pg; + skel->bss->page_cnt = cnt; + skel->bss->ret =1 ; +if (run (skel->progs.op_import_dax)) +return 1 ; +return skel->bss->ret; +} + +static int do_ext (struct arena_import *skel,struct bpf_program *prog,__u32 pg,__u32 cnt) +{ + skel->bss->pg = pg; + skel->bss->page_cnt = cnt; + skel->bss->ret =1 ; +if (run (prog)) +return 1 ; +return skel->bss->ret; +} + +static int do_alloc (struct arena_import *skel,__u32 pg,__u32 cnt) +{ + skel->bss->pg = pg; + skel->bss->page_cnt = cnt; + skel->bss->ret =1 ; +if (run (skel->progs.op_alloc)) +return 1 ; +return skel->bss->ret; +} + +static void do_free (struct arena_import *skel,__u32 pg,__u32 cnt) +{ + skel->bss->pg = pg; + skel->bss->page_cnt = cnt; +run (skel->progs.op_free); +} + +static void do_write (struct arena_import *skel,__u32 pg,__u64 val) +{ + skel->bss->pg = pg; + skel->bss->val = val; +run (skel->progs.op_write); +} + +static __u64 do_read (struct arena_import *skel,__u32 pg) +{ + skel->bss->pg = pg; + skel->bss->val =0 ; +run (skel->progs.op_read); +return skel->bss->val; +} + +static int make_memfd (unsigned int seals) +{ +int fd; + + fd =memfd_create ("arena_import" ,MFD_ALLOW_SEALING ); +if (fd <0 && errno ==ENOSYS ) { +printf ("%s:SKIP:no memfd_create()\n" , __func__); +test__skip (); +return -1 ; + } +if (!ASSERT_OK_FD (fd,"memfd_create" )) +return -1 ; +if (!ASSERT_OK (ftruncate (fd,MEMFD_PAGES * ps),"ftruncate" )) + goto err; +if (seals && !ASSERT_OK (fcntl (fd,F_ADD_SEALS , seals),"add_seals" )) + goto err; +return fd; +err: +close (fd); +return -1 ; +} + +static struct arena_import *open_skel (void ) +{ +struct arena_import *skel; +size_t sz; + + skel =arena_import__open_and_load (); +if (!skel && errno ==EOPNOTSUPP ) { +printf ("%s:SKIP:no arena support\n" , __func__); +test__skip (); +return NULL ; + } +if (!ASSERT_OK_PTR (skel,"open_and_load" )) +return NULL ; +if (skel->rodata->skip) { +printf ("%s:SKIP:the compiler lacks arena address space casts\n" , __func__); +test__skip (); +arena_import__destroy (skel); +return NULL ; + } + skel->bss->base =bpf_map__initial_value (skel->maps.arena, &sz); +if (!ASSERT_OK_PTR (skel->bss->base,"arena_base" )) { +arena_import__destroy (skel); +return NULL ; + } + skel->bss->page_size = ps; +return skel; +} + +/* Imported pages are not allocated by the arena and must not be counted */ +static long map_memlock (int map_fd) +{ +char path[64 ], line[128 ]; +long memlock =-1 ; +FILE *f; + +snprintf (path,sizeof (path),"/proc/self/fdinfo/%d" , map_fd); + f =fopen (path,"r" ); +if (!ASSERT_OK_PTR (f,"open_fdinfo" )) +return -1 ; +while (fgets (line,sizeof (line), f)) { +if (sscanf (line,"memlock:\t%ld" , &memlock) ==1 ) +break ; + } +fclose (f); +return memlock; +} + +/* Data written on either side is visible on the other one */ +static void test_share (void ) +{ +struct arena_import *skel; +__u64 *shm =MAP_FAILED ; +__u64 val; +int fd, i; + + fd =make_memfd (F_SEAL_SHRINK ); +if (fd <0 ) +return ; + skel =open_skel (); +if (!skel) + goto out; + +/* Import memfd pages 1-2 at test pages 2-3, see page_addr() */ +if (!ASSERT_OK (do_import (skel, fd, ps,2 ,2 ),"import" )) + goto out; +ASSERT_EQ (map_memlock (bpf_map__fd (skel->maps.arena)),0 ,"memlock" ); + + shm =mmap (NULL ,MEMFD_PAGES * ps,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 ); +if (!ASSERT_NEQ (shm,MAP_FAILED ,"mmap_memfd" )) + goto out; + +do_write (skel,2 ,0xcafe ); +do_write (skel,3 ,0xbeef ); +ASSERT_EQ (shm[ps /sizeof (*shm)],0xcafe ,"bpf_to_user_pg2" ); +ASSERT_EQ (shm[2 * ps /sizeof (*shm)],0xbeef ,"bpf_to_user_pg3" ); + + shm[ps /sizeof (*shm)] =0xf00d ; +ASSERT_EQ (do_read (skel,2 ),0xf00d ,"user_to_bpf" ); + +/* Pages outside of the imported range are not shared */ +if (!ASSERT_OK (do_alloc (skel,0 ,1 ),"alloc" )) + goto out; +do_write (skel,0 ,0xdead ); +ASSERT_EQ (do_read (skel,0 ),0xdead ,"allocated" ); +ASSERT_EQ (shm[0 ],0 ,"not_shared" ); + +/* +* The data outlives the arena. The arena releases the pages after an +* RCU grace period: sealing the memfd against writes fails while they +* are pinned, so wait until it works (no writable mapping either). +*/ +arena_import__destroy (skel); + skel =NULL ; +munmap (shm,MEMFD_PAGES * ps); + shm =MAP_FAILED ; +for (i =0 ; i <500 &&fcntl (fd,F_ADD_SEALS ,F_SEAL_WRITE ); i++) +usleep (10000 ); +if (ASSERT_LT (i,500 ,"released" ) && +ASSERT_EQ (pread (fd, &val,sizeof (val),2 * ps),sizeof (val),"pread" )) +ASSERT_EQ (val,0xbeef ,"after_destroy" ); +out: +if (shm !=MAP_FAILED ) +munmap (shm,MEMFD_PAGES * ps); +arena_import__destroy (skel); +close (fd); +} + +/* Freeing any imported page releases the whole import, the data stays in the memfd */ +static void test_free (void ) +{ +struct arena_import *skel; +__u64 *shm =MAP_FAILED ; +int fd; + + fd =make_memfd (F_SEAL_SHRINK ); +if (fd <0 ) +return ; + skel =open_skel (); +if (!skel) + goto out; + + shm =mmap (NULL ,MEMFD_PAGES * ps,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 ); +if (!ASSERT_NEQ (shm,MAP_FAILED ,"mmap_memfd" )) + goto out; + +/* Allocated page 0, memfd pages 0-1 imported at 1-2, allocated page 3 */ +if (!ASSERT_OK (do_alloc (skel,0 ,1 ),"alloc_pg0" ) || + !ASSERT_OK (do_import (skel, fd,0 ,1 ,2 ),"import" ) || + !ASSERT_OK (do_alloc (skel,3 ,1 ),"alloc_pg3" )) + goto out; +do_write (skel,0 ,0x1 ); +do_write (skel,1 ,0x1234 ); +do_write (skel,2 ,0x5678 ); +do_write (skel,3 ,0x3 ); + +/* Page 2 only: pages 1-2 go away, 0 and 3 stay */ +do_free (skel,2 ,1 ); +ASSERT_EQ (do_read (skel,1 ),0 ,"pg1_unmapped" ); +ASSERT_EQ (do_read (skel,2 ),0 ,"pg2_unmapped" ); +ASSERT_EQ (do_read (skel,0 ),0x1 ,"pg0_kept" ); +ASSERT_EQ (do_read (skel,3 ),0x3 ,"pg3_kept" ); +ASSERT_EQ (shm[0 ],0x1234 ,"memfd_kept" ); + +/* The range can be imported again */ +if (!ASSERT_OK (do_import (skel, fd,0 ,1 ,2 ),"reimport" )) + goto out; +ASSERT_EQ (do_read (skel,2 ),0x5678 ,"reimported" ); + +/* Across allocated and imported pages, then the whole arena is free */ +do_free (skel,0 ,4 ); +ASSERT_EQ (map_memlock (bpf_map__fd (skel->maps.arena)),0 ,"memlock" ); +ASSERT_OK (do_alloc (skel,0 ,8 ),"alloc_all" ); +out: +if (shm !=MAP_FAILED ) +munmap (shm,MEMFD_PAGES * ps); +arena_import__destroy (skel); +close (fd); +} + +static void test_invalid (void ) +{ +int fd, ro_fd =-1 , wo_fd =-1 , null_fd =-1 ; +struct arena_import *skel; +char path[64 ]; + + skel =open_skel (); +if (!skel) +return ; + +/* Write seals are not allowed */ + fd =make_memfd (F_SEAL_SHRINK |F_SEAL_FUTURE_WRITE ); +if (fd >=0 ) { +ASSERT_EQ (do_import (skel, fd,0 ,0 ,1 ), -EPERM ,"write_seal" ); +close (fd); + } + + fd =make_memfd (F_SEAL_SHRINK ); +if (fd <0 ) + goto out; + +/* The memfd must be open for reading and writing, like for a shared mapping */ +snprintf (path,sizeof (path),"/proc/self/fd/%d" , fd); + ro_fd =open (path,O_RDONLY ); +if (ASSERT_OK_FD (ro_fd,"open_ro" )) +ASSERT_EQ (do_import (skel, ro_fd,0 ,0 ,1 ), -EPERM ,"read_only" ); + wo_fd =open (path,O_WRONLY ); +if (ASSERT_OK_FD (wo_fd,"open_wo" )) +ASSERT_EQ (do_import (skel, wo_fd,0 ,0 ,1 ), -EPERM ,"write_only" ); + +/* Not a memfd */ + null_fd =open ("/dev/null" ,O_RDWR ); +if (ASSERT_OK_FD (null_fd,"open_null" )) +ASSERT_EQ (do_import (skel, null_fd,0 ,0 ,1 ), -EINVAL ,"not_memfd" ); + +ASSERT_EQ (do_import (skel,-1 ,0 ,0 ,1 ), -EBADF ,"bad_fd" ); +ASSERT_EQ (do_import (skel, fd,1 ,0 ,1 ), -EINVAL ,"unaligned_off" ); +ASSERT_EQ (do_import (skel, fd,0 ,0 ,MEMFD_PAGES +1 ), -EINVAL ,"beyond_memfd" ); +ASSERT_EQ (do_import (skel, fd,0 ,7 ,2 ), -EINVAL ,"beyond_arena" ); +ASSERT_EQ (do_import (skel, fd,0 ,0 ,0 ), -EINVAL ,"zero_pages" ); + +/* The range must be free */ +if (ASSERT_OK (do_alloc (skel,0 ,1 ),"alloc" )) +ASSERT_EQ (do_import (skel, fd,0 ,0 ,2 ), -EBUSY ,"over_allocated" ); +if (ASSERT_OK (do_import (skel, fd,0 ,2 ,2 ),"import" )) +ASSERT_EQ (do_import (skel, fd,0 ,3 ,1 ), -EBUSY ,"over_imported" ); +do_free (skel,0 ,4 ); + +/* Nothing above may leave a range behind */ +ASSERT_OK (do_alloc (skel,0 ,8 ),"alloc_all" ); +out: +if (null_fd >=0 ) +close (null_fd); +if (ro_fd >=0 ) +close (ro_fd); +if (wo_fd >=0 ) +close (wo_fd); +if (fd >=0 ) +close (fd); +arena_import__destroy (skel); +} + +static char *fault_expected; + +static void fault_handler (int sig,siginfo_t *si,void *uc) +{ +_exit (si->si_addr == fault_expected ?3 :4 ); +} + +/* User space accesses imported pages through the memfd, not through the arena */ +static void test_user_fault (void ) +{ +struct arena_import *skel; +int fd, status, ret; +pid_t pid; + + fd =make_memfd (F_SEAL_SHRINK ); +if (fd <0 ) +return ; + skel =open_skel (); +if (!skel) + goto out; + +if (!ASSERT_OK (do_import (skel, fd,0 ,1 ,1 ),"import" )) + goto out; + + pid =fork (); +if (!ASSERT_GE (pid,0 ,"fork" )) + goto out; +if (!pid) { +/* The arena mapping is not inherited, map it again */ +struct sigaction sa = { .sa_sigaction = fault_handler, .sa_flags =SA_SIGINFO }; +size_t sz =bpf_map__max_entries (skel->maps.arena) * ps; +char *p; + + p =mmap (skel->bss->base, sz,PROT_READ |PROT_WRITE , +MAP_SHARED |MAP_FIXED ,bpf_map__fd (skel->maps.arena),0 ); +if (p ==MAP_FAILED ||sigaction (SIGBUS , &sa,NULL )) +_exit (1 ); +/* Test pages 0 and 1, see page_addr() */ + p[ps] =1 ;/* allocated on demand */ + fault_expected = p +2 * ps; +/* Set before the store that faults */ +atomic_signal_fence (memory_order_seq_cst); + p[2 * ps] =1 ;/* imported */ +_exit (2 ); + } +/* The watchdog of the runner interrupts system calls */ +do { + ret =waitpid (pid, &status,0 ); + }while (ret <0 && errno ==EINTR ); +if (ASSERT_EQ (ret, pid,"waitpid" )) { +ASSERT_TRUE (WIFEXITED (status),"exited" ); +/* 3: SIGBUS on the imported page, 4: elsewhere, 2: no fault */ +ASSERT_EQ (WEXITSTATUS (status),3 ,"sigbus_on_imported" ); + } +out: +arena_import__destroy (skel); +close (fd); +} + +/* +* Only a device-dax mapping can be imported by address. This needs no +* device-dax device: it only checks that everything else is refused. +*/ +static void test_dax_invalid (void ) +{ +char *anon =MAP_FAILED , *shm =MAP_FAILED ; +struct arena_import *skel; +int fd =-1 ; + + skel =open_skel (); +if (!skel) +return ; + + anon =mmap (NULL ,2 * ps,PROT_READ |PROT_WRITE ,MAP_PRIVATE |MAP_ANONYMOUS ,-1 ,0 ); +if (!ASSERT_NEQ (anon,MAP_FAILED ,"mmap_anon" )) + goto out; + anon[0 ] =1 ; +ASSERT_EQ (do_import_dax (skel, anon,0 ,1 ), -EINVAL ,"anon" ); +ASSERT_EQ (do_import_dax (skel, anon +1 ,0 ,1 ), -EINVAL ,"unaligned_src" ); +ASSERT_EQ (do_import_dax (skel, anon,0 ,0 ), -EINVAL ,"zero_pages" ); +ASSERT_EQ (do_import_dax (skel, anon,0 ,bpf_map__max_entries (skel->maps.arena) +1 ), + -EINVAL ,"too_many_pages" ); +if (ASSERT_OK (munmap (anon + ps, ps),"munmap" )) +ASSERT_EQ (do_import_dax (skel, anon + ps,0 ,1 ), -EINVAL ,"unmapped" ); + +/* Memory with a file behind it is imported by file */ + fd =make_memfd (F_SEAL_SHRINK ); +if (fd <0 ) + goto out; + shm =mmap (NULL , ps,PROT_READ |PROT_WRITE ,MAP_SHARED , fd,0 ); +if (ASSERT_NEQ (shm,MAP_FAILED ,"mmap_memfd" )) +ASSERT_EQ (do_import_dax (skel, shm,0 ,1 ), -EINVAL ,"memfd" ); + +/* Nothing above may leave a range behind */ +ASSERT_OK (do_alloc (skel,0 ,8 ),"alloc_all" ); +out: +if (shm !=MAP_FAILED ) +munmap (shm, ps); +/* Both pages, the second one may still be mapped */ +if (anon !=MAP_FAILED ) +munmap (anon,2 * ps); +if (fd >=0 ) +close (fd); +arena_import__destroy (skel); +} + +/* +* An async callback may run in another task, where the import kfuncs must not +* use its files or its memory. This one runs in the same task, with a memfd +* that can be imported: only the check for async callbacks refuses it. +*/ +static void test_async (void ) +{ +struct arena_import *skel; +int fd, i; + + fd =make_memfd (F_SEAL_SHRINK ); +if (fd <0 ) +return ; + skel =open_skel (); +if (!skel) + goto out; + + skel->bss->fd = fd; + skel->bss->fd_off =0 ; + skel->bss->src =0 ; + skel->bss->pg =0 ; + skel->bss->page_cnt =1 ; + skel->bss->ret =1 ; +if (run (skel->progs.op_import_async) || !ASSERT_OK (skel->bss->ret,"schedule" )) + goto out; +for (i =0 ; i <1000 && !READ_ONCE (skel->bss->async_done); i++) +usleep (1000 ); +if (!ASSERT_EQ (READ_ONCE (skel->bss->async_done),1 ,"async_done" )) + goto out; +ASSERT_EQ (skel->bss->async_memfd_ret, -EPERM ,"memfd" ); +ASSERT_EQ (skel->bss->async_dax_ret, -EPERM ,"dax" ); + +/* The same import works from the program itself */ +ASSERT_OK (do_import (skel, fd,0 ,0 ,1 ),"import" ); +out: +arena_import__destroy (skel); +close (fd); +} + +#define ARENA_EXT_MAGIC 0xa5e0a5e0ULL + +/* A kernel supplier, bpf_testmod, imports pages of its own and revokes them */ +static void test_kernel (void ) +{ +struct arena_import *skel; +int released, ret; + + skel =open_skel (); +if (!skel) +return ; + + released =do_ext (skel, skel->progs.op_ext_released,0 ,0 ); + ret =do_ext (skel, skel->progs.op_ext_map,0 ,2 ); +if (ret == -EOPNOTSUPP ) { +printf ("%s:SKIP:no bpf_testmod\n" , __func__); +test__skip (); + goto out; + } +if (!ASSERT_OK (ret,"map" )) + goto out; +ASSERT_EQ (do_read (skel,0 ),ARENA_EXT_MAGIC ,"pg0_shared" ); +ASSERT_EQ (do_read (skel,1 ),ARENA_EXT_MAGIC +1 ,"pg1_shared" ); +do_write (skel,1 ,0x1234 ); +ASSERT_EQ (do_read (skel,1 ),0x1234 ,"pg1_written" ); +ASSERT_ERR (do_alloc (skel,1 ,1 ),"alloc_over_import" ); + +/* Only the start of the import revokes it */ +ASSERT_EQ (do_ext (skel, skel->progs.op_ext_unmap,1 ,0 ), -ENOENT ,"unmap_middle" ); +ASSERT_EQ (do_ext (skel, skel->progs.op_ext_released,0 ,0 ), released,"not_released" ); + +/* Released by the time the revoke returns, the range is free */ +ASSERT_OK (do_ext (skel, skel->progs.op_ext_unmap,0 ,0 ),"unmap" ); +ASSERT_EQ (do_ext (skel, skel->progs.op_ext_released,0 ,0 ), released +1 ,"released" ); +ASSERT_EQ (do_read (skel,0 ),0 ,"pg0_revoked" ); +ASSERT_EQ (do_ext (skel, skel->progs.op_ext_unmap,0 ,0 ), -ENOENT ,"unmap_again" ); +if (ASSERT_OK (do_alloc (skel,0 ,2 ),"alloc_after_revoke" )) +do_free (skel,0 ,2 ); + +/* A BPF free releases the pages first, the revoke finds them gone */ +if (!ASSERT_OK (do_ext (skel, skel->progs.op_ext_map,2 ,1 ),"map_again" )) + goto out; +do_free (skel,2 ,1 ); +ASSERT_EQ (do_ext (skel, skel->progs.op_ext_released,0 ,0 ), released +2 ,"freed" ); +ASSERT_EQ (do_ext (skel, skel->progs.op_ext_unmap,2 ,0 ), -ENOENT ,"unmap_freed" ); +out: +arena_import__destroy (skel); +} + +void serial_test_arena_import (void ) +{ + ps =sysconf (_SC_PAGESIZE); + +if (test__start_subtest ("share" )) +test_share (); +if (test__start_subtest ("free" )) +test_free (); +if (test__start_subtest ("invalid" )) +test_invalid (); +if (test__start_subtest ("user_fault" )) +test_user_fault (); +if (test__start_subtest ("dax_invalid" )) +test_dax_invalid (); +if (test__start_subtest ("async" )) +test_async (); +if (test__start_subtest ("kernel" )) +test_kernel (); +}
tools/testing/selftests/bpf/progs/arena_import.c new file +170 -0
170 lines not on this page · raw message
tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +90 -0
108 lines not on this page · raw message
tools/testing/selftests/bpf/test_kmods/bpf_testmod_kfunc.h +3 -0
@@ -323,6 +323,9 @@ void bpf_kfunc_call_test_mem_len_fail2(__u64 *mem, int len) __ksym; void bpf_kfunc_call_test_destructive(void) __ksym; void bpf_kfunc_call_test_sleepable(void) __ksym; +int bpf_kfunc_arena_ext_map(void *p__map, void *addr__ign, u32 page_cnt) __ksym; +int bpf_kfunc_arena_ext_unmap(void *p__map, void *addr__ign) __ksym; +int bpf_kfunc_arena_ext_released(void) __ksym; int bpf_kfunc_call_test_call_rcu_tasks_trace(int *done) __ksym;void bpf_kfunc_call_test_offset (struct prog_test_ref_kfunc *p);
Signature · 1 line
2.56.1
[email protected]
AI reviewRe: [PATCH 5/5] selftests/bpf: Test importing pages into an arena
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] selftests/bpf: test_dax_invalid() fails when CONFIG_DAX is not built-in - [Medium] selftests/bpf…
Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] selftests/bpf: test_dax_invalid() fails when CONFIG_DAX is not built-in
- [Medium] selftests/bpf: unsynchronized arena_ext state in bpf_testmod kfuncs
--
commit 8cbf53ce81f32ae5f961370e9a60385a4198f27f
Author: Andrea Righi <[email protected]>
selftests/bpf: Test importing pages into an arena
This commit adds BPF selftests and bpf_testmod kfuncs to test importing memfd, device-dax, and external kernel pages into a BPF arena.
Quoted 5 lines
tools/testing/selftests/bpf/prog_tests/arena_import.c new file +0
-0
[ ... ]
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/arena_import.c new file +10
-0+/* +* Only a device-dax mapping can be imported by address. This needs no +* device-dax device: it only checks that everything else is refused. +*/ +static void test_dax_invalid (void ) +{ +char *anon =MAP_FAILED , *shm =MAP_FAILED ; +struct arena_import *skel; +int fd =-1 ; +
tools/testing/selftests/bpf/prog_tests/arena_import.c line 419
Quoted 10 lines
tools/testing/selftests/bpf/prog_tests/arena_import.c new file +10
-0+ skel =open_skel (); +if (!skel) +return ; + + anon =mmap (NULL ,2 * ps,PROT_READ |PROT_WRITE ,MAP_PRIVATE |MAP_ANONYMOUS ,-1 ,0 ); +if (!ASSERT_NEQ (anon,MAP_FAILED ,"mmap_anon" )) + goto out; + anon[0 ] =1 ; +ASSERT_EQ (do_import_dax (skel, anon,0 ,1 ), -EINVAL ,"anon" ); +ASSERT_EQ (do_import_dax (skel, anon +1 ,0 ,1 ), -EINVAL ,"unaligned_src" );
[Severity: Medium]
Does test_dax_invalid() fail instead of skipping when CONFIG_DAX is disabled or built as a module (including kernels built with tools/testing/selftests/bpf/config)?
In kernel/bpf/arena.c, arena_import_dax() returns -EOPNOTSUPP before checking src alignment or VMA type:
kernel/bpf/arena.c:arena_import_dax() {
/* The dax SRCU, below, can't be reached from here if the dax core is a module */
if (!IS_BUILTIN(CONFIG_DAX))
return -EOPNOTSUPP;
/* Kernel code may run the program without an address space */
src = untagged_addr(src);
if (!mm || (src & ~PAGE_MASK))
return -EINVAL;
...
}When CONFIG_DAX is not built-in, the do_import_dax() calls with page_cnt == 1 return -EOPNOTSUPP rather than -EINVAL, failing these assertions.
Quoted 16 lines
tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +8
-0@@ -1607,6 +1607,91 @@ __bpf_kfunc void bpf_kfunc_call_test_sleepable(void) { } +#define ARENA_EXT_MAGIC 0xa5e0a5e0ULL + +/* Pages that the module imports into an arena, one import at a time */ +static struct { +struct bpf_map *map; +u64 addr; +atomic_t released; +} arena_ext;
[ ... ]
Quoted 42 lines
tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +42
-0+/* Like a paravirt transport: map pages that the module keeps into an arena */ +__bpf_kfunc int bpf_kfunc_arena_ext_map(void *p__map, void *addr__ign, u32 page_cnt) +{ +struct bpf_map *map = p__map; +struct page **pages; +u32 i; +int ret; + +if (!page_cnt || page_cnt >16 ) +return -EINVAL ; +if (arena_ext.map) +return -EBUSY ; + + pages =kvcalloc (page_cnt,sizeof (*pages),GFP_KERNEL ); +if (!pages) +return -ENOMEM ; +for (i =0 ; i < page_cnt; i++) { + pages[i] =alloc_page (GFP_KERNEL | __GFP_ZERO); +if (!pages[i]) { + ret = -ENOMEM ; + goto err; + } + *(u64 *)page_address (pages[i]) =ARENA_EXT_MAGIC + i; + } + + ret =bpf_arena_map_ext_pages (map, (u64 )addr__ign, pages, page_cnt, + bpf_testmod_arena_ext_release, &arena_ext); +if (ret) + goto err; +/* Until the pages are revoked, also when BPF frees them first */ +bpf_map_inc (map); + arena_ext.map = map; + arena_ext.addr = (u64 )addr__ign; +return 0 ; +err: +while (i--) +__free_page (pages[i]); +kvfree (pages); +return ret; +} + +__bpf_kfunc int bpf_kfunc_arena_ext_unmap(void *p__map, void *addr__ign)
tools/testing/selftests/bpf/test_kmods/bpf_testmod.c __bpf_kfunc void bpf_kfunc_call_test_sleepable(void) · line 1680
Quoted 10 lines
tools/testing/selftests/bpf/test_kmods/bpf_testmod.c +10
-0+{ +int ret; + + ret =bpf_arena_unmap_ext_pages (p__map, (u64 )addr__ign, &arena_ext); +if (p__map == arena_ext.map && (u64 )addr__ign == arena_ext.addr) { +bpf_map_put (arena_ext.map); + arena_ext.map =NULL ; + } +return ret; +}
[Severity: Medium]
Can concurrent calls to bpf_kfunc_arena_ext_map() and bpf_kfunc_arena_ext_unmap() race on arena_ext.map and arena_ext.addr?
Both sleepable kfuncs access arena_ext without a lock. In bpf_kfunc_arena_ext_unmap(), two concurrent callers passing the active map and addr can both pass the check and call bpf_map_put(arena_ext.map), causing a double bpf_map_put() and use-after-free on struct bpf_map, or a NULL pointer dereference in bpf_map_put(NULL) if arena_ext.map is reloaded after being cleared.
In bpf_kfunc_arena_ext_map(), two concurrent callers can both observe arena_ext.map == NULL across the sleeping allocations and bpf_arena_map_ext_pages(), overwriting arena_ext.map and leaking the first map reference (leaving the first import active if bpf_testmod is unloaded).
Also, bpf_arena_map_ext_pages() and bpf_arena_unmap_ext_pages() truncate the address to u32 when indexing the arena, whereas arena_ext.addr compares the full 64-bit value, so unmapping with different upper 32 bits revokes the import without dropping arena_ext.map. Serializing these kfuncs with a mutex and comparing (u32)(u64)addr__ign would avoid both issues.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5