| 1 | // Copyright 2026 The Memory Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | //go:build unix |
| 6 | |
| 7 | package memory // import "modernc.org/memory" |
| 8 | |
| 9 | import ( |
| 10 | "unsafe" |
| 11 | |
| 12 | "golang.org/x/sys/unix" |
| 13 | ) |
| 14 | |
| 15 | // canDecommit gates the decommit policy: pooled regions past the hot window |
| 16 | // hand their pages back to the OS. |
| 17 | const canDecommit = true |
| 18 | |
| 19 | // madviseAdvice is the advice passed for a region falling out of the hot |
| 20 | // window. |
| 21 | // |
| 22 | // MADV_DONTNEED rather than MADV_FREE: MADV_FREE reclaims lazily, so the |
| 23 | // resident set does not actually drop until the machine is under pressure |
| 24 | // - measured, a 2 GiB pool still read as 2 GiB of RSS. That is the same |
| 25 | // reason the Go runtime defaults to MADV_DONTNEED. |
| 26 | const madviseAdvice = unix.MADV_DONTNEED |
| 27 | |
| 28 | // decommit asks the kernel to reclaim the physical pages backing the empty |
| 29 | // region at p without unmapping it. The mapping stays, and with it the address, |
| 30 | // the VMA and the absence of a future mmap - that is the whole point: retention |
| 31 | // keeps its syscall and map-count savings while handing the resident set back. |
| 32 | // |
| 33 | // MADV_DONTNEED does not change vm_flags, so this does not split the VMA. |
| 34 | // |
| 35 | // The first OS page is left alone because it carries the page header, so |
| 36 | // nothing has to be reconstructed when the region comes back out of the pool. |
| 37 | // That holds only while osPageSize < pageSize; on a kernel configured with |
| 38 | // 64 KiB base pages the two are equal and decommit turns itself off rather than |
| 39 | // zeroing a live header. Such hosts would instead need page.size restored from |
| 40 | // the pool's map key in the reuse path. |
| 41 | func decommit(p uintptr, size int) { |
| 42 | if size <= osPageSize { |
| 43 | return |
| 44 | } |
| 45 | |
| 46 | n := size - osPageSize |
| 47 | unix.Madvise((*rawmem)(unsafe.Pointer(p + uintptr(osPageSize)))[:n:n], madviseAdvice) |
| 48 | } |
| 49 | |
| 50 | // recommit is what makes a region from the pool's decommitted prefix usable |
| 51 | // again before it is handed out. On unix there is nothing to do: pages |
| 52 | // discarded by MADV_DONTNEED soft-fault back zero-filled on first touch. |
| 53 | func recommit(uintptr, int) error { return nil } |