package runtime // Per-arena scope attribution. // // The question this answers, concretely and without guessing: WHICH function's // arena is holding the bytes that N requests left behind? // // An arena is tagged with the scope that was current when it was pushed, and // every allocation into it and every reclaim of it is charged to that tag. A // scope normally opens and closes with a function: the shell sets one around a // phase of request handling so a retained byte is charged to the phase that // allocated it. The report then shows, per scope, allocated vs reclaimed - and // the difference is exactly the retention, with a name attached. // // Cost: one int32 store on push, one 64-bit add per allocation, one add plus a // reset on reclaim. Nothing here allocates, so the instrument cannot perturb // what it measures. const arenaScopeMax = int32(64) // Scopes the runtime itself names. Everything else is the shell's: leaving 0 // unnamed is deliberate, so that an allocation nobody accounted for is visible // as scope 0 instead of hiding inside the root arena's row (which is exactly how // the group leak was misread as "root retention" for several rounds). const ArenaScopeRoot = int32(5) type arenaScopeRec struct { alloc uint64 freed uint64 resets int32 arenas int32 } var arenaScopes [arenaScopeMax]arenaScopeRec var arenaScopeCurrent int32 // --- allocation-size histogram (phase 0b) --- // // The phase 4 header size (D8), the slab decision (D9) and the frame budget // question are all read from this, so it is always on. The cost is one bin // computation and two adds per allocation; the bin is floor(log2(size)), so a // question about "objects at or below 32 bytes" is bins 0..5 and "just above // 64 KiB" is bin 16. // // The two slices are carved from the DOMAIN segment by initDomain and are // therefore per-domain TLS, like every other runtime table: a worker's // histogram is its own. const allocHistBins = int32(64) var allocHistCount []uint64 var allocHistBytes []uint64 // sizeBin is floor(log2(size)) without a library call or a loop. TargetBits // gates the 64-bit step because a shift of a 32-bit uintptr by 32 is not that // comparison on wasm. func sizeBin(size uintptr) (b int32) { if TargetBits == 64 && size > 0xFFFFFFFF { b = b + 32 size = size >> 32 } if size >= 1<<16 { b = b + 16 size = size >> 16 } if size >= 1<<8 { b = b + 8 size = size >> 8 } if size >= 1<<4 { b = b + 4 size = size >> 4 } if size >= 1<<2 { b = b + 2 size = size >> 2 } if size >= 1<<1 { b = b + 1 } return b } // recordAllocSize charges one allocation to its size bin. A zero-length table // is the pre-initDomain state: initDomain itself allocates nothing through the // allocator, so nothing is ever dropped. func recordAllocSize(size uintptr) { if len(allocHistCount) == 0 { return } b := sizeBin(size) if b >= allocHistBins { b = allocHistBins - 1 } allocHistCount[b]++ allocHistBytes[b] += uint64(size) } // AllocHistogram returns the size histogram (floor(log2) bins, count and // bytes). It is the measurement D8 and D9 are decided from. func AllocHistogram() (counts []uint64, bytes []uint64) { return allocHistCount, allocHistBytes } // SegmentStats is the per-kind ledger: live segments, bytes reserved and // bytes allocated. A segment is a mapping; the arena's region table is its // descriptor, so these counters and that table must agree at every quiescent // point. type SegmentStats struct { FnCount uint64 FnBytes uint64 RootCount uint64 RootBytes uint64 LargeCount uint64 LargeBytes uint64 DomainCount uint64 DomainBytes uint64 ChanCount uint64 ChanBytes uint64 } var segFnCount uint64 var segFnBytes uint64 var segRootCount uint64 var segRootBytes uint64 var segLargeCount uint64 var segLargeBytes uint64 var segDomainCount uint64 var segDomainBytes uint64 var segChanCount uint64 var segChanBytes uint64 // RecordSegmentAdd charges one mapping to its kind. func RecordSegmentAdd(kind int32, bytes uintptr) { switch kind { case segKindFn: segFnCount++ segFnBytes += uint64(bytes) case segKindRoot: segRootCount++ segRootBytes += uint64(bytes) case segKindLarge: segLargeCount++ segLargeBytes += uint64(bytes) case segKindDomain: segDomainCount++ segDomainBytes += uint64(bytes) case segKindChannel: segChanCount++ segChanBytes += uint64(bytes) } } // RecordSegmentFree retires one mapping from its kind's ledger. func RecordSegmentFree(kind int32, bytes uintptr) { switch kind { case segKindFn: segFnCount-- segFnBytes -= uint64(bytes) case segKindRoot: segRootCount-- segRootBytes -= uint64(bytes) case segKindLarge: segLargeCount-- segLargeBytes -= uint64(bytes) case segKindDomain: segDomainCount-- segDomainBytes -= uint64(bytes) case segKindChannel: segChanCount-- segChanBytes -= uint64(bytes) } } // ReadSegmentStats copies the ledger into s. func ReadSegmentStats(s *SegmentStats) { s.FnCount = segFnCount s.FnBytes = segFnBytes s.RootCount = segRootCount s.RootBytes = segRootBytes s.LargeCount = segLargeCount s.LargeBytes = segLargeBytes s.DomainCount = segDomainCount s.DomainBytes = segDomainBytes s.ChanCount = segChanCount s.ChanBytes = segChanBytes } // ArenaLedger reports the function-tier book balance: pushes, releases, the // live frame depth and the pooled arenas. At quiescence pushed == released and // depth == 0; anything else is a release path that did not run, and the two // numbers name it. func ArenaLedger() (pushed, released, depth, pooled uint64) { pushed = fnPushCount released = fnReleaseCount if domainRoot != nil { depth = uint64(uint32(domainRoot.fnTop)) } pooled = uint64(uint32(arenaPoolN)) return } // SysMapStats reports the process-level mapping ledger. Phase 2's exit // criterion is that a warm allocating loop stops mapping: two reads around the // loop with equal counts is that evidence, and it is the one measurement the // segment pool exists to make true. func SysMapStats() (maps, unmaps, mapBytes, unmapBytes uint64) { maps = sysMapCount unmaps = sysUnmapCount mapBytes = sysMapBytes unmapBytes = sysUnmapBytes return } // ArenaDomainExitCheck runs at the end of a spawned domain, where the thread is // about to end and every frame it owns should already be gone. It reports only // when the ledger does not balance and only under the trace gate, because a // correct program's exit must stay silent. func ArenaDomainExitCheck() { if domainRoot == nil || !arenaTraceWanted() { return } pushed, released, depth, pooled := ArenaLedger() if pushed == released && depth == 0 { return } printstring("arena domain-exit pushed=") printuint64(pushed) printstring(" released=") printuint64(released) printstring(" depth=") printuint64(depth) printstring(" pooled=") printuint64(pooled) printstring("\n") } // SetArenaScope names the scope that arenas pushed from now on belong to, and // returns the previous one so a caller can restore it. func SetArenaScope(id int32) (prev int32) { prev = arenaScopeCurrent if id >= 0 && id < arenaScopeMax { arenaScopeCurrent = id } return prev } // ArenaScope reports the current scope. func ArenaScope() (id int32) { return arenaScopeCurrent } // --- region accounting --- // // A region is the unit an arena grows by. One that is added and never unmapped // costs its whole mapping whether or not its bytes are reported as "used", which // is why the byte counters can look clean while RSS climbs. var regionAddCount [arenaScopeMax]uint64 var regionAddBytes [arenaScopeMax]uint64 var regionFreeCount [arenaScopeMax]uint64 var regionFreeBytes [arenaScopeMax]uint64 var sysMapCount uint64 var sysMapBytes uint64 var sysUnmapCount uint64 var sysUnmapBytes uint64 // RecordRegionAdd charges one region acquisition to a scope. func RecordRegionAdd(id int32, bytes uintptr) { if id >= 0 && id < arenaScopeMax { regionAddCount[id]++ regionAddBytes[id] += uint64(bytes) } } // RecordRegionFree charges region releases to a scope. func RecordRegionFree(id int32, count uintptr, bytes uintptr) { if id >= 0 && id < arenaScopeMax { regionFreeCount[id] += uint64(count) regionFreeBytes[id] += uint64(bytes) } } // RecordSysMap / RecordSysUnmap count the process-level mappings. func RecordSysMap(bytes uintptr) { sysMapCount++ sysMapBytes += uint64(bytes) } func RecordSysUnmap(bytes uintptr) { sysUnmapCount++ sysUnmapBytes += uint64(bytes) } // --- sovereign group accounting --- // // A sovereign group is the arena set that a self-mutating type's receiver owns. // Its arenas are the only ones that double (growDouble), so their region adds // are counted apart from the ordinary 64MB ones, and created vs released is // the direct test of the binding rule: a group lives exactly as long as the // arena that holds its receiver. If created climbs and released does not, the // groups outlive their receivers, and `regionadd` says how fast the arenas they // keep alive are growing. var sovCreated uint64 var sovReleased uint64 var sovRegionAdd uint64 var sovRegionAddBytes uint64 var sovRegionFree uint64 var sovRegionFreeBytes uint64 func RecordSovCreate() { sovCreated++ } func RecordSovRelease() { sovReleased++ } // The three ways a group can escape release, counted separately so a residual // leak names its own path instead of being inferred: // // untracked - created for a receiver that was in no live arena, so no arena // list ever names it (the documented ctxArena == nil case); // miss - its receiver was not in the receiver map at release time; // refused - its receiver was nil or attributed to another arena. var sovUntracked uint64 var sovReleaseMiss uint64 var sovReleaseRefused uint64 func RecordSovUntracked() { sovUntracked++ } func RecordSovReleaseMiss() { sovReleaseMiss++ } func RecordSovReleaseRefused() { sovReleaseRefused++ } // sovMetaBytes is the group bookkeeping (group struct, record slice, batch // stack, slot table) charged to the arena that owns the receiver. It is not a // retention number: it is the proof that the bookkeeping follows the receiver // instead of the process. var sovMetaBytes uint64 func RecordSovMeta(size uintptr) { sovMetaBytes += uint64(size) } // RecordSovRegionAdd charges a doubling arena's new region to the group // accounting. func RecordSovRegionAdd(bytes uintptr) { sovRegionAdd++ sovRegionAddBytes += uint64(bytes) } // RecordSovRegionFree charges a doubling arena's released regions. func RecordSovRegionFree(count uintptr, bytes uintptr) { sovRegionFree += uint64(count) sovRegionFreeBytes += uint64(bytes) } func arenaScopeAlloc(id int32, size uintptr) { if id >= 0 && id < arenaScopeMax { arenaScopes[id].alloc += uint64(size) } } func arenaScopeFreed(id int32, size uintptr) { if id >= 0 && id < arenaScopeMax { arenaScopes[id].freed += uint64(size) arenaScopes[id].resets++ } } // --- trace gate --- // // SetArenaTrace turns the DIRECT-allocation size recorder on. Kept because a // size histogram is the one thing the scope counters cannot show: a single // large allocation (a codec buffer, a bucket array) is one event, not a pattern. var arenaTraceOn bool var rootTraceBusy bool // SetArenaTrace turns allocation-size capture on or off. func SetArenaTrace(on bool) { arenaTraceOn = on } // RecordRootSize charges one DIRECT allocation into the root arena, keyed by // size. Powers of two are the hashmap bucket signature; variable sizes are codec // buffers. It answers "is the root taking bytes", not "from where": the scope // rows answer that, and the group counters answer "for whom". const rootSizeMax = int32(24) type rootSizeRec struct { size uintptr count uint64 bytes uint64 } var rootSizes [rootSizeMax]rootSizeRec var rootSizeN int32 // RecordRootSize records one direct allocation into the root arena. func RecordRootSize(size uintptr) { if rootTraceBusy { return } rootTraceBusy = true var i int32 = 0 for i = 0; i < rootSizeN; i++ { if rootSizes[i].size == size { rootSizes[i].count++ rootSizes[i].bytes += uint64(size) rootTraceBusy = false return } } if rootSizeN < rootSizeMax { rootSizes[rootSizeN].size = size rootSizes[rootSizeN].count = 1 rootSizes[rootSizeN].bytes = uint64(size) rootSizeN++ } rootTraceBusy = false } // arenaTraceWanted reports whether site capture is on. func arenaTraceWanted() (on bool) { return arenaTraceOn } func arenaScopeArena(id int32) { if id >= 0 && id < arenaScopeMax { arenaScopes[id].arenas++ } } // resetArenaScopeStats clears the counters so a measurement can start from zero. func ResetArenaScopeStats() { for i := int32(0); i < arenaScopeMax; i++ { arenaScopes[i].alloc = 0 arenaScopes[i].freed = 0 arenaScopes[i].resets = 0 arenaScopes[i].arenas = 0 } } // ArenaScopeReport writes one line per scope that has seen any traffic: // // scope= allocated= reclaimed= retained= resets= arenas= // // retained is the number the whole instrument exists for: bytes this scope's // arenas have allocated and no reset or free has reclaimed. A scope that // retains across many requests is the leak, and its id says which phase of the // port it belongs to (net/http's chanpath.mx assigns the ids). func ArenaScopeReport() (out []byte) { for i := int32(0); i < arenaScopeMax; i++ { r := arenaScopes[i] if r.alloc == 0 && r.freed == 0 && r.arenas == 0 { continue } out = appendScopeStr(out, "scope=") out = appendScopeUint(out, uint64(i)) out = appendScopeStr(out, " allocated=") out = appendScopeUint(out, r.alloc) out = appendScopeStr(out, " reclaimed=") out = appendScopeUint(out, r.freed) out = appendScopeStr(out, " retained=") if r.alloc > r.freed { out = appendScopeUint(out, r.alloc-r.freed) } else { out = appendScopeUint(out, 0) } out = appendScopeStr(out, " resets=") out = appendScopeUint(out, uint64(uint32(r.resets))) out = appendScopeStr(out, " arenas=") out = appendScopeUint(out, uint64(uint32(r.arenas))) out = appendScopeStr(out, "\n") } if domainRoot != nil { for i := int32(0); i <= domainRoot.fnTop; i++ { out = emitLiveArena(out, domainRoot.fnStack[i], "live") } out = emitLiveArena(out, trueRootArena(), "root") } for i := int32(0); i < arenaPoolN; i++ { out = emitLiveArena(out, arenaPool[i], "pooled") } out = appendScopeStr(out, "fnarena pushed=") out = appendScopeUint(out, fnPushCount) out = appendScopeStr(out, " released=") out = appendScopeUint(out, fnReleaseCount) out = appendScopeStr(out, " leaked=") out = appendScopeUint(out, fnPushCount-fnReleaseCount) out = appendScopeStr(out, "\n") out = appendScopeStr(out, "sovhome root=") out = appendScopeUint(out, sovHomeRoot) out = appendScopeStr(out, " sov=") out = appendScopeUint(out, sovHomeSov) out = appendScopeStr(out, " frame=") out = appendScopeUint(out, sovHomeFrame) out = appendScopeStr(out, "\n") out = appendScopeStr(out, "sysmap count=") out = appendScopeUint(out, sysMapCount) out = appendScopeStr(out, " bytes=") out = appendScopeUint(out, sysMapBytes) out = appendScopeStr(out, "\n") out = appendScopeStr(out, "sysunmap count=") out = appendScopeUint(out, sysUnmapCount) out = appendScopeStr(out, " bytes=") out = appendScopeUint(out, sysUnmapBytes) out = appendScopeStr(out, "\n") out = appendScopeStr(out, "mapped sysmap_bytes=") out = appendScopeUint(out, sysMapBytes) out = appendScopeStr(out, " sysunmap_bytes=") out = appendScopeUint(out, sysUnmapBytes) out = appendScopeStr(out, " net=") if sysMapBytes > sysUnmapBytes { out = appendScopeUint(out, sysMapBytes-sysUnmapBytes) } else { out = appendScopeUint(out, 0) } out = appendScopeStr(out, " livecap=") out = appendScopeUint(out, uint64(liveArenaCapBytes())) out = appendScopeStr(out, "\n") out = appendScopeStr(out, "sov created=") out = appendScopeUint(out, sovCreated) out = appendScopeStr(out, " released=") out = appendScopeUint(out, sovReleased) out = appendScopeStr(out, " live=") if sovCreated > sovReleased { out = appendScopeUint(out, sovCreated-sovReleased) } else { out = appendScopeUint(out, 0) } out = appendScopeStr(out, " regionadd=") out = appendScopeUint(out, sovRegionAdd) out = appendScopeStr(out, "/") out = appendScopeUint(out, sovRegionAddBytes) out = appendScopeStr(out, " untracked=") out = appendScopeUint(out, sovUntracked) out = appendScopeStr(out, " miss=") out = appendScopeUint(out, sovReleaseMiss) out = appendScopeStr(out, " refused=") out = appendScopeUint(out, sovReleaseRefused) out = appendScopeStr(out, " meta=") out = appendScopeUint(out, sovMetaBytes) out = appendScopeStr(out, " recycled=") out = appendScopeUint(out, sovGroupRecycleCount()) out = appendScopeStr(out, " regionfree=") out = appendScopeUint(out, sovRegionFree) out = appendScopeStr(out, "/") out = appendScopeUint(out, sovRegionFreeBytes) out = appendScopeStr(out, "\n") for i := int32(0); i < arenaScopeMax; i++ { if regionAddCount[i] == 0 && regionFreeCount[i] == 0 { continue } out = appendScopeStr(out, "region scope=") out = appendScopeUint(out, uint64(i)) out = appendScopeStr(out, " added=") out = appendScopeUint(out, regionAddCount[i]) out = appendScopeStr(out, "/") out = appendScopeUint(out, regionAddBytes[i]) out = appendScopeStr(out, " freed=") out = appendScopeUint(out, regionFreeCount[i]) out = appendScopeStr(out, "/") out = appendScopeUint(out, regionFreeBytes[i]) out = appendScopeStr(out, "\n") } for i := int32(0); i < rootSizeN; i++ { out = appendScopeStr(out, "rootsize=") out = appendScopeUint(out, uint64(rootSizes[i].size)) out = appendScopeStr(out, " count=") out = appendScopeUint(out, rootSizes[i].count) out = appendScopeStr(out, " bytes=") out = appendScopeUint(out, rootSizes[i].bytes) out = appendScopeStr(out, "\n") } return out } // emitLiveArena writes one arena that is currently holding memory: its scope, // what kind of arena it is, how many regions it holds and how many bytes it has // used, and how much it has reserved. func emitLiveArena(out []byte, a *Arena, tag []byte) (res []byte) { res = out if a == nil { return res } used := uintptr(0) for i := int32(0); i < a.nregions; i++ { used += a.regions[i].off } if used == 0 { return res } res = appendScopeStr(res, tag) res = appendScopeStr(res, " scope=") res = appendScopeUint(res, uint64(uint32(a.scope))) res = appendScopeStr(res, " sovereign=") res = appendScopeUint(res, uint64(uint32(a.sovereign))) res = appendScopeStr(res, " n=") res = appendScopeUint(res, uint64(uint32(a.nregions))) res = appendScopeStr(res, " groups=") res = appendScopeUint(res, uint64(uint32(a.sovGroups))) res = appendScopeStr(res, " used=") res = appendScopeUint(res, uint64(used)) reserved := uintptr(0) for i := int32(0); i < a.nregions; i++ { reserved += a.regions[i].cap } res = appendScopeStr(res, " cap=") res = appendScopeUint(res, uint64(reserved)) res = appendScopeStr(res, "\n") return res } // liveArenaCapBytes is every byte of arena memory currently reserved: the root, // the function stack, and the pool. It is the number that must stay flat when a // scope boundary is doing its job - a scope that frees regions but leaves them // mapped shows nothing here, and neither does one that leaves a child group // alive. func liveArenaCapBytes() (n uintptr) { if domainRoot == nil { return 0 } for i := int32(0); i <= domainRoot.fnTop; i++ { a := domainRoot.fnStack[i] if a == nil { continue } for j := int32(0); j < a.nregions; j++ { n += a.regions[j].cap } } for i := int32(0); i < arenaPoolN; i++ { a := arenaPool[i] if a == nil { continue } for j := int32(0); j < a.nregions; j++ { n += a.regions[j].cap } } return n } func appendScopeStr(b []byte, s []byte) (out []byte) { out = b for i := 0; i < len(s); i++ { out = push(out, s[i]) } return out } func appendScopeUint(b []byte, v uint64) (out []byte) { out = b if v == 0 { return push(out, '0') } d := []byte{:24} n := int32(0) for v > 0 { d[n] = byte('0' + v%10) n = n + 1 v = v / 10 } for n > 0 { n = n - 1 out = push(out, d[n]) } return out }