1 //:build linux && !baremetal
2 3 package runtime
4 5 import "unsafe"
6 7 // flag_MADV_DONTNEED is Linux's "the pages can be dropped" advice.
8 const flag_MADV_DONTNEED = 4
9 10 // arenaTrimTail releases up to pages of the arena's unused tail. The bump
11 // offset is NOT moved: the next allocation writes into the released range and
12 // faults the pages back in, zero-filled, so no bookkeeping changes and no
13 // live object is touched. Trimming starts at the first page boundary at or
14 // after off, never before it.
15 func arenaTrimTail(a *Arena, pages int32) (n int32) {
16 if a == nil || a.nregions <= 0 || pages <= 0 || a.compacting != 0 {
17 return 0
18 }
19 r := &a.regions[a.active]
20 if r.off >= r.cap {
21 return 0
22 }
23 start := (r.off + 4095) &^ 4095
24 for n < pages && start < r.cap {
25 end := start + 4096
26 if end > r.cap {
27 end = r.cap
28 }
29 if madvise(unsafe.Pointer(start), end-start, flag_MADV_DONTNEED) == 0 {
30 n++
31 }
32 start = end
33 }
34 return n
35 }
36 37 // idleTrimPages is the domain's idle maintenance: release up to budget pages
38 // of unused arena tail, the root arena first and then the active frame arena.
39 // Its job is to stop the arena's committed set from ratcheting upward across
40 // idle turns - the tail a previous burst left mapped is handed back, and the
41 // next allocation reuses those pages instead of the arena claiming new ones.
42 // It is not a reclaimer: pages holding live data are never touched, so RSS of
43 // live data does not fall. The caller must re-check its inbox between pages;
44 // one page is the worst-case delay if a message arrives while it runs.
45 func idleTrimPages(budget int32) (n int32) {
46 if budget <= 0 || domainRoot == nil {
47 return 0
48 }
49 n += arenaTrimTail(trueRootArena(), budget)
50 if n >= budget {
51 return n
52 }
53 if domainRoot.fnTop > 0 {
54 n += arenaTrimTail(domainRoot.fnStack[domainRoot.fnTop], budget-n)
55 }
56 return n
57 }
58