3

I'm working on a device that has very tight memory size and virtual address space constraint.

I'm trying to solve this problem by reclaiming memory more frequently while reclaiming virtual address less frequently, e.g. reserving virtual address early but committing memory late, while reclaiming memory early and releasing virtual address late.

Particularly there is a very large allocation that suffers a lot from address space fragmentation and I'm trying to solve it by reserving address space for it up front.

This question solves the first problem: use mmap with PROT_NONE to acquire virtual address range, and use mprotect with PROT_READ|PROT_WRITE before use, and then pages would be faulted in when used.

However, I couldn't find a way to do the reverse: mprotect with PROT_NONE doesn't seem to release the pages, while calling munmap loses the virtual address range.

Is there to unmap/detach pages while preserving virtual address?

user3528438
  • 2,737
  • 2
  • 23
  • 42
  • 2
    Not sure if it will work but have you tried [`madvise(ptr, size, MADV_DONTNEED)`](http://man7.org/linux/man-pages/man2/madvise.2.html)? There are a few other advice flags in the manual that also look potentially useful. This is a comment instead of an answer because I've never done this and have no idea if it'll work. ;) – TypeIA Apr 11 '18 at 21:35
  • I second TypeIA. But you need to use `MAP_PRIVATE`. Consider also `MAP_NORESERVE`. – Hadi Brais Apr 12 '18 at 00:18

1 Answers1

4

mmap with MAP_FIXED will replace any existing mapping in the specified address range, and free the memory if it is no longer referenced.

Timothy Baldwin
  • 3,551
  • 1
  • 14
  • 23