2026-06-10
Stack Overflow: View Question
Tags: c, linux, linux-kernel, shared-memory, demand-paging
Score: 0 | Views: 85
The asker has a working Netlink-based log pipeline from a kernel module to a userspace consumer, but wants to experiment with something faster — specifically, demand-paged shared memory where the kernel writes log records into pages that userspace maps directly. The goal is zero-copy delivery: no copy_to_user, no socket buffer round-trip, just a ring buffer in memory both sides can see.
Why is this interesting? "Shared memory between kernel and userspace" sounds simple but has several sharp edges that AI assistants tend to gloss over:
struct vm_operations_struct with proper open/close refcounting, or pin the module via try_module_get..fault handler in vm_operations_struct. The handler allocates a page on first access (via alloc_page or vmalloc_to_page if backed by vmalloc) and returns it. This is what remap_pfn_range avoids by mapping everything up front.io_uring-style: keep producer/consumer indices in the shared region with smp_store_release/smp_load_acquire, and fall back to an eventfd or poll() on the chardev only when the consumer needs to sleep.A sketch:
.mmap on its file_operations..mmap, set vma->vm_ops to your ops struct with a .fault handler. Set VM_DONTEXPAND | VM_DONTDUMP. Do not call remap_pfn_range — let faults drive allocation..fault handler computes which slot in the ring is being touched, allocates a page (cached, kernel-owned), stuffs it into vmf->page, and returns 0. Track allocated pages in a per-mapping array so .close can free them.poll_wait on the chardev, kernel calls wake_up_interruptible when crossing the empty->non-empty edge.Gotchas: cache coherency is usually fine on x86 (write-back, snooped) but on ARM you may need flush_dcache_page. Don't use vmalloc pages with remap_pfn_range — it'll silently work in subtle ways. And remember: faster than Netlink is not free — you're trading syscall cost for memory-barrier discipline, which is much harder to debug.
