Hello,

as far as AVR - small 8 bit target - is concerned, it would IMO be preferred to avoid calling memalign. I remember a recent change that pulled mm_memalign into the build, consuming more than 1% of total program memory. (The change was later tweaked so memalign was again not called.)

That said, if variant 1 only affects build when mmap is used, that's probably OK - on device this small, there is not much use for mmap anyway (at least as far as I can imagine.)

On 2026-10-09 13:18, Marco C. wrote:
Hello,

mmap() with MAP_ANONYMOUS returns memory from the heap:
fs/mmap/fs_anonmap.c allocates it with kumm_zalloc() (or
fs_heap_zalloc()). The address therefore has the alignment of malloc(),
not of a page.

POSIX does not say in so many words that mmap() without MAP_FIXED
returns a page-aligned address. But it says that "the system performs
mapping operations over whole pages", munmap() and mprotect() act on the whole pages that contain the range, and both "may require that addr be a multiple of the page size" (EINVAL otherwise). So a portable program can
only release or protect what mmap() returned if it is page-aligned, and
with a heap address the pages it shares with other data cannot be
unmapped or protected safely. Linux, the BSDs and macOS return
page-aligned addresses, and programs (page allocators, garbage
collectors) rely on it. For example:

    void *p = mmap(NULL, len, PROT_READ | PROT_WRITE,
                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    long pg = sysconf(_SC_PAGESIZE);
    assert(((uintptr_t)p & (pg - 1)) == 0);   /* fails on NuttX */

A comment in fs_anonmap.c already notes that a kernel build could use
pgalloc() for this.

Possible directions:

1. Small fix, all builds: allocate with kumm_memalign() at the page size
   and round the length up to a whole page. It costs up to one page of
   heap per mapping.
2. Kernel builds with CONFIG_ARCH_ADDRENV: map real pages into the
   address environment with pgalloc(), so that munmap() and mprotect()
   can work on parts of a mapping. This is more work.
3. Both: 1 now, 2 later for kernel builds.

Is 1 acceptable as a bug fix without a Kconfig option, given the memory
cost on small targets? Or should the alignment depend on an option?

Thanks,
Marco Casaroli

Reply via email to