Debian Codegraph @

src/runtime/export_test.go

raw
1 // Copyright 2010 The Go 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 // Export guts for testing.
6
7 package runtime
8
9 import (
10 "internal/abi"
11 "internal/goarch"
12 "internal/goos"
13 "internal/runtime/atomic"
14 "internal/runtime/gc"
15 "internal/runtime/sys"
16 "unsafe"
17 )
18
19 var Fadd64 = fadd64
20 var Fsub64 = fsub64
21 var Fmul64 = fmul64
22 var Fdiv64 = fdiv64
23 var F64to32 = f64to32
24 var F32to64 = f32to64
25 var Fcmp64 = fcmp64
26 var Fintto64 = fintto64
27 var F64toint = f64toint
28
29 var Entersyscall = entersyscall
30 var Exitsyscall = exitsyscall
31 var LockedOSThread = lockedOSThread
32 var Xadduintptr = atomic.Xadduintptr
33
34 var ReadRandomFailed = &readRandomFailed
35
36 var Fastlog2 = fastlog2
37
38 var ParseByteCount = parseByteCount
39
40 var Nanotime = nanotime
41 var Cputicks = cputicks
42 var CyclesPerSecond = pprof_cyclesPerSecond
43 var NetpollBreak = netpollBreak
44 var Usleep = usleep
45
46 var PhysPageSize = physPageSize
47 var PhysHugePageSize = physHugePageSize
48
49 var NetpollGenericInit = netpollGenericInit
50
51 var Memmove = memmove
52 var MemclrNoHeapPointers = memclrNoHeapPointers
53
54 var CgoCheckPointer = cgoCheckPointer
55
56 const CrashStackImplemented = crashStackImplemented
57
58 const TracebackInnerFrames = tracebackInnerFrames
59 const TracebackOuterFrames = tracebackOuterFrames
60
61 var MapKeys = keys
62 var MapValues = values
63
64 var LockPartialOrder = lockPartialOrder
65
66 type TimeTimer = timeTimer
67
68 type LockRank lockRank
69
70 func (l LockRank) String() string {
71 return lockRank(l).String()
72 }
73
74 const PreemptMSupported = preemptMSupported
75
76 type LFNode struct {
77 Next uint64
78 Pushcnt uintptr
79 }
80
81 func LFStackPush(head *uint64, node *LFNode) {
82 (*lfstack)(head).push((*lfnode)(unsafe.Pointer(node)))
83 }
84
85 func LFStackPop(head *uint64) *LFNode {
86 return (*LFNode)((*lfstack)(head).pop())
87 }
88 func LFNodeValidate(node *LFNode) {
89 lfnodeValidate((*lfnode)(unsafe.Pointer(node)))
90 }
91
92 func Netpoll(delta int64) {
93 systemstack(func() {
94 netpoll(delta)
95 })
96 }
97
98 func PointerMask(x any) (ret []byte) {
99 systemstack(func() {
100 ret = pointerMask(x)
101 })
102 return
103 }
104
105 func RunSchedLocalQueueTest() {
106 pp := new(p)
107 gs := make([]g, len(pp.runq))
108 Escape(gs) // Ensure gs doesn't move, since we use guintptrs
109 for i := 0; i < len(pp.runq); i++ {
110 if g, _ := runqget(pp); g != nil {
111 throw("runq is not empty initially")
112 }
113 for j := 0; j < i; j++ {
114 runqput(pp, &gs[i], false)
115 }
116 for j := 0; j < i; j++ {
117 if g, _ := runqget(pp); g != &gs[i] {
118 print("bad element at iter ", i, "/", j, "\n")
119 throw("bad element")
120 }
121 }
122 if g, _ := runqget(pp); g != nil {
123 throw("runq is not empty afterwards")
124 }
125 }
126 }
127
128 func RunSchedLocalQueueStealTest() {
129 p1 := new(p)
130 p2 := new(p)
131 gs := make([]g, len(p1.runq))
132 Escape(gs) // Ensure gs doesn't move, since we use guintptrs
133 for i := 0; i < len(p1.runq); i++ {
134 for j := 0; j < i; j++ {
135 gs[j].sig = 0
136 runqput(p1, &gs[j], false)
137 }
138 gp := runqsteal(p2, p1, true)
139 s := 0
140 if gp != nil {
141 s++
142 gp.sig++
143 }
144 for {
145 gp, _ = runqget(p2)
146 if gp == nil {
147 break
148 }
149 s++
150 gp.sig++
151 }
152 for {
153 gp, _ = runqget(p1)
154 if gp == nil {
155 break
156 }
157 gp.sig++
158 }
159 for j := 0; j < i; j++ {
160 if gs[j].sig != 1 {
161 print("bad element ", j, "(", gs[j].sig, ") at iter ", i, "\n")
162 throw("bad element")
163 }
164 }
165 if s != i/2 && s != i/2+1 {
166 print("bad steal ", s, ", want ", i/2, " or ", i/2+1, ", iter ", i, "\n")
167 throw("bad steal")
168 }
169 }
170 }
171
172 func RunSchedLocalQueueEmptyTest(iters int) {
173 // Test that runq is not spuriously reported as empty.
174 // Runq emptiness affects scheduling decisions and spurious emptiness
175 // can lead to underutilization (both runnable Gs and idle Ps coexist
176 // for arbitrary long time).
177 done := make(chan bool, 1)
178 p := new(p)
179 gs := make([]g, 2)
180 Escape(gs) // Ensure gs doesn't move, since we use guintptrs
181 ready := new(uint32)
182 for i := 0; i < iters; i++ {
183 *ready = 0
184 next0 := (i & 1) == 0
185 next1 := (i & 2) == 0
186 runqput(p, &gs[0], next0)
187 go func() {
188 for atomic.Xadd(ready, 1); atomic.Load(ready) != 2; {
189 }
190 if runqempty(p) {
191 println("next:", next0, next1)
192 throw("queue is empty")
193 }
194 done <- true
195 }()
196 for atomic.Xadd(ready, 1); atomic.Load(ready) != 2; {
197 }
198 runqput(p, &gs[1], next1)
199 runqget(p)
200 <-done
201 runqget(p)
202 }
203 }
204
205 var (
206 StringHash = stringHash
207 BytesHash = bytesHash
208 Int32Hash = int32Hash
209 Int64Hash = int64Hash
210 MemHash = memhash
211 MemHash32 = memhash32
212 MemHash64 = memhash64
213 EfaceHash = efaceHash
214 IfaceHash = ifaceHash
215 )
216
217 var UseAeshash = &useAeshash
218
219 func MemclrBytes(b []byte) {
220 s := (*slice)(unsafe.Pointer(&b))
221 memclrNoHeapPointers(s.array, uintptr(s.len))
222 }
223
224 const HashLoad = hashLoad
225
226 // entry point for testing
227 func GostringW(w []uint16) (s string) {
228 systemstack(func() {
229 s = gostringw(&w[0])
230 })
231 return
232 }
233
234 var Open = open
235 var Close = closefd
236 var Read = read
237 var Write = write
238
239 func Envs() []string { return envs }
240 func SetEnvs(e []string) { envs = e }
241
242 const PtrSize = goarch.PtrSize
243
244 var ForceGCPeriod = &forcegcperiod
245
246 // SetTracebackEnv is like runtime/debug.SetTraceback, but it raises
247 // the "environment" traceback level, so later calls to
248 // debug.SetTraceback (e.g., from testing timeouts) can't lower it.
249 func SetTracebackEnv(level string) {
250 setTraceback(level)
251 traceback_env = traceback_cache
252 }
253
254 var ReadUnaligned32 = readUnaligned32
255 var ReadUnaligned64 = readUnaligned64
256
257 func CountPagesInUse() (pagesInUse, counted uintptr) {
258 stw := stopTheWorld(stwForTestCountPagesInUse)
259
260 pagesInUse = mheap_.pagesInUse.Load()
261
262 for _, s := range mheap_.allspans {
263 if s.state.get() == mSpanInUse {
264 counted += s.npages
265 }
266 }
267
268 startTheWorld(stw)
269
270 return
271 }
272
273 func Fastrand() uint32 { return uint32(rand()) }
274 func Fastrand64() uint64 { return rand() }
275 func Fastrandn(n uint32) uint32 { return randn(n) }
276
277 type ProfBuf profBuf
278
279 func NewProfBuf(hdrsize, bufwords, tags int) *ProfBuf {
280 return (*ProfBuf)(newProfBuf(hdrsize, bufwords, tags))
281 }
282
283 func (p *ProfBuf) Write(tag *unsafe.Pointer, now int64, hdr []uint64, stk []uintptr) {
284 (*profBuf)(p).write(tag, now, hdr, stk)
285 }
286
287 const (
288 ProfBufBlocking = profBufBlocking
289 ProfBufNonBlocking = profBufNonBlocking
290 )
291
292 func (p *ProfBuf) Read(mode profBufReadMode) ([]uint64, []unsafe.Pointer, bool) {
293 return (*profBuf)(p).read(mode)
294 }
295
296 func (p *ProfBuf) Close() {
297 (*profBuf)(p).close()
298 }
299
300 type CPUStats = cpuStats
301
302 func ReadCPUStats() CPUStats {
303 return work.cpuStats
304 }
305
306 func ReadMetricsSlow(memStats *MemStats, samplesp unsafe.Pointer, len, cap int) {
307 stw := stopTheWorld(stwForTestReadMetricsSlow)
308
309 // Initialize the metrics beforehand because this could
310 // allocate and skew the stats.
311 metricsLock()
312 initMetrics()
313
314 systemstack(func() {
315 // Donate the racectx to g0. readMetricsLocked calls into the race detector
316 // via map access.
317 getg().racectx = getg().m.curg.racectx
318
319 // Read the metrics once before in case it allocates and skews the metrics.
320 // readMetricsLocked is designed to only allocate the first time it is called
321 // with a given slice of samples. In effect, this extra read tests that this
322 // remains true, since otherwise the second readMetricsLocked below could
323 // allocate before it returns.
324 readMetricsLocked(samplesp, len, cap)
325
326 // Read memstats first. It's going to flush
327 // the mcaches which readMetrics does not do, so
328 // going the other way around may result in
329 // inconsistent statistics.
330 readmemstats_m(memStats)
331
332 // Read metrics again. We need to be sure we're on the
333 // system stack with readmemstats_m so that we don't call into
334 // the stack allocator and adjust metrics between there and here.
335 readMetricsLocked(samplesp, len, cap)
336
337 // Undo the donation.
338 getg().racectx = 0
339 })
340 metricsUnlock()
341
342 startTheWorld(stw)
343 }
344
345 var DoubleCheckReadMemStats = &doubleCheckReadMemStats
346
347 // ReadMemStatsSlow returns both the runtime-computed MemStats and
348 // MemStats accumulated by scanning the heap.
349 func ReadMemStatsSlow() (base, slow MemStats) {
350 stw := stopTheWorld(stwForTestReadMemStatsSlow)
351
352 // Run on the system stack to avoid stack growth allocation.
353 systemstack(func() {
354 // Make sure stats don't change.
355 getg().m.mallocing++
356
357 readmemstats_m(&base)
358
359 // Initialize slow from base and zero the fields we're
360 // recomputing.
361 slow = base
362 slow.Alloc = 0
363 slow.TotalAlloc = 0
364 slow.Mallocs = 0
365 slow.Frees = 0
366 slow.HeapReleased = 0
367 var bySize [gc.NumSizeClasses]struct {
368 Mallocs, Frees uint64
369 }
370
371 // Add up current allocations in spans.
372 for _, s := range mheap_.allspans {
373 if s.state.get() != mSpanInUse {
374 continue
375 }
376 if s.isUnusedUserArenaChunk() {
377 continue
378 }
379 if sizeclass := s.spanclass.sizeclass(); sizeclass == 0 {
380 slow.Mallocs++
381 slow.Alloc += uint64(s.elemsize)
382 } else {
383 slow.Mallocs += uint64(s.allocCount)
384 slow.Alloc += uint64(s.allocCount) * uint64(s.elemsize)
385 bySize[sizeclass].Mallocs += uint64(s.allocCount)
386 }
387 }
388
389 // Add in frees by just reading the stats for those directly.
390 var m heapStatsDelta
391 memstats.heapStats.unsafeRead(&m)
392
393 // Collect per-sizeclass free stats.
394 var smallFree uint64
395 for i := 0; i < gc.NumSizeClasses; i++ {
396 slow.Frees += m.smallFreeCount[i]
397 bySize[i].Frees += m.smallFreeCount[i]
398 bySize[i].Mallocs += m.smallFreeCount[i]
399 smallFree += m.smallFreeCount[i] * uint64(gc.SizeClassToSize[i])
400 }
401 slow.Frees += m.tinyAllocCount + m.largeFreeCount
402 slow.Mallocs += slow.Frees
403
404 slow.TotalAlloc = slow.Alloc + m.largeFree + smallFree
405
406 for i := range slow.BySize {
407 slow.BySize[i].Mallocs = bySize[i].Mallocs
408 slow.BySize[i].Frees = bySize[i].Frees
409 }
410
411 for i := mheap_.pages.start; i < mheap_.pages.end; i++ {
412 chunk := mheap_.pages.tryChunkOf(i)
413 if chunk == nil {
414 continue
415 }
416 pg := chunk.scavenged.popcntRange(0, pallocChunkPages)
417 slow.HeapReleased += uint64(pg) * pageSize
418 }
419 for _, p := range allp {
420 pg := sys.OnesCount64(p.pcache.scav)
421 slow.HeapReleased += uint64(pg) * pageSize
422 }
423
424 getg().m.mallocing--
425 })
426
427 startTheWorld(stw)
428 return
429 }
430
431 // ShrinkStackAndVerifyFramePointers attempts to shrink the stack of the current goroutine
432 // and verifies that unwinding the new stack doesn't crash, even if the old
433 // stack has been freed or reused (simulated via poisoning).
434 func ShrinkStackAndVerifyFramePointers() {
435 before := stackPoisonCopy
436 defer func() { stackPoisonCopy = before }()
437 stackPoisonCopy = 1
438
439 gp := getg()
440 systemstack(func() {
441 shrinkstack(gp)
442 })
443 // If our new stack contains frame pointers into the old stack, this will
444 // crash because the old stack has been poisoned.
445 FPCallers(make([]uintptr, 1024))
446 }
447
448 type StackPoisonCopyRestore int
449
450 func (s StackPoisonCopyRestore) Restore() { stackPoisonCopy = int(s) }
451
452 func StackPoisonCopy() StackPoisonCopyRestore {
453 before := stackPoisonCopy
454 stackPoisonCopy = 1
455 return StackPoisonCopyRestore(before)
456 }
457
458 // BlockOnSystemStack switches to the system stack, prints "x\n" to
459 // stderr, and blocks in a stack containing
460 // "runtime.blockOnSystemStackInternal".
461 func BlockOnSystemStack() {
462 systemstack(blockOnSystemStackInternal)
463 }
464
465 func blockOnSystemStackInternal() {
466 print("x\n")
467 lock(&deadlock)
468 lock(&deadlock)
469 }
470
471 type RWMutex struct {
472 rw rwmutex
473 }
474
475 func (rw *RWMutex) Init() {
476 rw.rw.init(lockRankTestR, lockRankTestRInternal, lockRankTestW)
477 }
478
479 func (rw *RWMutex) RLock() {
480 rw.rw.rlock()
481 }
482
483 func (rw *RWMutex) RUnlock() {
484 rw.rw.runlock()
485 }
486
487 func (rw *RWMutex) Lock() {
488 rw.rw.lock()
489 }
490
491 func (rw *RWMutex) Unlock() {
492 rw.rw.unlock()
493 }
494
495 func LockOSCounts() (external, internal uint32) {
496 gp := getg()
497 if gp.m.lockedExt+gp.m.lockedInt == 0 {
498 if gp.lockedm != 0 {
499 panic("lockedm on non-locked goroutine")
500 }
501 } else {
502 if gp.lockedm == 0 {
503 panic("nil lockedm on locked goroutine")
504 }
505 }
506 return gp.m.lockedExt, gp.m.lockedInt
507 }
508
509 //go:noinline
510 func TracebackSystemstack(stk []uintptr, i int) int {
511 if i == 0 {
512 pc, sp := sys.GetCallerPC(), sys.GetCallerSP()
513 var u unwinder
514 u.initAt(pc, sp, 0, getg(), unwindJumpStack) // Don't ignore errors, for testing
515 return tracebackPCs(&u, 0, stk)
516 }
517 n := 0
518 systemstack(func() {
519 n = TracebackSystemstack(stk, i-1)
520 })
521 return n
522 }
523
524 func KeepNArenaHints(n int) {
525 hint := mheap_.arenaHints
526 for i := 1; i < n; i++ {
527 hint = hint.next
528 if hint == nil {
529 return
530 }
531 }
532 hint.next = nil
533 }
534
535 // MapNextArenaHint reserves a page at the next arena growth hint,
536 // preventing the arena from growing there, and returns the range of
537 // addresses that are no longer viable.
538 //
539 // This may fail to reserve memory. If it fails, it still returns the
540 // address range it attempted to reserve.
541 func MapNextArenaHint() (start, end uintptr, ok bool) {
542 hint := mheap_.arenaHints
543 addr := hint.addr
544 if hint.down {
545 start, end = addr-heapArenaBytes, addr
546 addr -= physPageSize
547 } else {
548 start, end = addr, addr+heapArenaBytes
549 }
550 got := sysReserve(unsafe.Pointer(addr), physPageSize, "")
551 ok = (addr == uintptr(got))
552 if !ok {
553 // We were unable to get the requested reservation.
554 // Release what we did get and fail.
555 sysUnreserve(got, physPageSize)
556 }
557 return
558 }
559
560 func GetNextArenaHint() uintptr {
561 return mheap_.arenaHints.addr
562 }
563
564 type G = g
565
566 type Sudog = sudog
567
568 func Getg() *G {
569 return getg()
570 }
571
572 func Goid() uint64 {
573 return getg().goid
574 }
575
576 func GIsWaitingOnMutex(gp *G) bool {
577 return readgstatus(gp) == _Gwaiting && gp.waitreason.isMutexWait()
578 }
579
580 var CasGStatusAlwaysTrack = &casgstatusAlwaysTrack
581
582 //go:noinline
583 func PanicForTesting(b []byte, i int) byte {
584 return unexportedPanicForTesting(b, i)
585 }
586
587 //go:noinline
588 func unexportedPanicForTesting(b []byte, i int) byte {
589 return b[i]
590 }
591
592 func G0StackOverflow() {
593 systemstack(func() {
594 g0 := getg()
595 sp := sys.GetCallerSP()
596 // The stack bounds for g0 stack is not always precise.
597 // Use an artificially small stack, to trigger a stack overflow
598 // without actually run out of the system stack (which may seg fault).
599 g0.stack.lo = sp - 4096 - stackSystem
600 g0.stackguard0 = g0.stack.lo + stackGuard
601 g0.stackguard1 = g0.stackguard0
602
603 stackOverflow(nil)
604 })
605 }
606
607 func stackOverflow(x *byte) {
608 var buf [256]byte
609 stackOverflow(&buf[0])
610 }
611
612 func RunGetgThreadSwitchTest() {
613 // Test that getg works correctly with thread switch.
614 // With gccgo, if we generate getg inlined, the backend
615 // may cache the address of the TLS variable, which
616 // will become invalid after a thread switch. This test
617 // checks that the bad caching doesn't happen.
618
619 ch := make(chan int)
620 go func(ch chan int) {
621 ch <- 5
622 LockOSThread()
623 }(ch)
624
625 g1 := getg()
626
627 // Block on a receive. This is likely to get us a thread
628 // switch. If we yield to the sender goroutine, it will
629 // lock the thread, forcing us to resume on a different
630 // thread.
631 <-ch
632
633 g2 := getg()
634 if g1 != g2 {
635 panic("g1 != g2")
636 }
637
638 // Also test getg after some control flow, as the
639 // backend is sensitive to control flow.
640 g3 := getg()
641 if g1 != g3 {
642 panic("g1 != g3")
643 }
644 }
645
646 const (
647 PageSize = pageSize
648 PallocChunkPages = pallocChunkPages
649 PageAlloc64Bit = pageAlloc64Bit
650 PallocSumBytes = pallocSumBytes
651 )
652
653 // Expose pallocSum for testing.
654 type PallocSum pallocSum
655
656 func PackPallocSum(start, max, end uint) PallocSum { return PallocSum(packPallocSum(start, max, end)) }
657 func (m PallocSum) Start() uint { return pallocSum(m).start() }
658 func (m PallocSum) Max() uint { return pallocSum(m).max() }
659 func (m PallocSum) End() uint { return pallocSum(m).end() }
660
661 // Expose pallocBits for testing.
662 type PallocBits pallocBits
663
664 func (b *PallocBits) Find(npages uintptr, searchIdx uint) (uint, uint) {
665 return (*pallocBits)(b).find(npages, searchIdx)
666 }
667 func (b *PallocBits) AllocRange(i, n uint) { (*pallocBits)(b).allocRange(i, n) }
668 func (b *PallocBits) Free(i, n uint) { (*pallocBits)(b).free(i, n) }
669 func (b *PallocBits) Summarize() PallocSum { return PallocSum((*pallocBits)(b).summarize()) }
670 func (b *PallocBits) PopcntRange(i, n uint) uint { return (*pageBits)(b).popcntRange(i, n) }
671
672 // SummarizeSlow is a slow but more obviously correct implementation
673 // of (*pallocBits).summarize. Used for testing.
674 func SummarizeSlow(b *PallocBits) PallocSum {
675 var start, most, end uint
676
677 const N = uint(len(b)) * 64
678 for start < N && (*pageBits)(b).get(start) == 0 {
679 start++
680 }
681 for end < N && (*pageBits)(b).get(N-end-1) == 0 {
682 end++
683 }
684 run := uint(0)
685 for i := uint(0); i < N; i++ {
686 if (*pageBits)(b).get(i) == 0 {
687 run++
688 } else {
689 run = 0
690 }
691 most = max(most, run)
692 }
693 return PackPallocSum(start, most, end)
694 }
695
696 // Expose non-trivial helpers for testing.
697 func FindBitRange64(c uint64, n uint) uint { return findBitRange64(c, n) }
698
699 // Given two PallocBits, returns a set of bit ranges where
700 // they differ.
701 func DiffPallocBits(a, b *PallocBits) []BitRange {
702 ba := (*pageBits)(a)
703 bb := (*pageBits)(b)
704
705 var d []BitRange
706 base, size := uint(0), uint(0)
707 for i := uint(0); i < uint(len(ba))*64; i++ {
708 if ba.get(i) != bb.get(i) {
709 if size == 0 {
710 base = i
711 }
712 size++
713 } else {
714 if size != 0 {
715 d = append(d, BitRange{base, size})
716 }
717 size = 0
718 }
719 }
720 if size != 0 {
721 d = append(d, BitRange{base, size})
722 }
723 return d
724 }
725
726 // StringifyPallocBits gets the bits in the bit range r from b,
727 // and returns a string containing the bits as ASCII 0 and 1
728 // characters.
729 func StringifyPallocBits(b *PallocBits, r BitRange) string {
730 str := ""
731 for j := r.I; j < r.I+r.N; j++ {
732 if (*pageBits)(b).get(j) != 0 {
733 str += "1"
734 } else {
735 str += "0"
736 }
737 }
738 return str
739 }
740
741 // Expose pallocData for testing.
742 type PallocData pallocData
743
744 func (d *PallocData) FindScavengeCandidate(searchIdx uint, min, max uintptr) (uint, uint) {
745 return (*pallocData)(d).findScavengeCandidate(searchIdx, min, max)
746 }
747 func (d *PallocData) AllocRange(i, n uint) { (*pallocData)(d).allocRange(i, n) }
748 func (d *PallocData) ScavengedSetRange(i, n uint) {
749 (*pallocData)(d).scavenged.setRange(i, n)
750 }
751 func (d *PallocData) PallocBits() *PallocBits {
752 return (*PallocBits)(&(*pallocData)(d).pallocBits)
753 }
754 func (d *PallocData) Scavenged() *PallocBits {
755 return (*PallocBits)(&(*pallocData)(d).scavenged)
756 }
757
758 // Expose fillAligned for testing.
759 func FillAligned(x uint64, m uint) uint64 { return fillAligned(x, m) }
760
761 // Expose pageCache for testing.
762 type PageCache pageCache
763
764 const PageCachePages = pageCachePages
765
766 func NewPageCache(base uintptr, cache, scav uint64) PageCache {
767 return PageCache(pageCache{base: base, cache: cache, scav: scav})
768 }
769 func (c *PageCache) Empty() bool { return (*pageCache)(c).empty() }
770 func (c *PageCache) Base() uintptr { return (*pageCache)(c).base }
771 func (c *PageCache) Cache() uint64 { return (*pageCache)(c).cache }
772 func (c *PageCache) Scav() uint64 { return (*pageCache)(c).scav }
773 func (c *PageCache) Alloc(npages uintptr) (uintptr, uintptr) {
774 return (*pageCache)(c).alloc(npages)
775 }
776 func (c *PageCache) Flush(s *PageAlloc) {
777 cp := (*pageCache)(c)
778 sp := (*pageAlloc)(s)
779
780 systemstack(func() {
781 // None of the tests need any higher-level locking, so we just
782 // take the lock internally.
783 lock(sp.mheapLock)
784 cp.flush(sp)
785 unlock(sp.mheapLock)
786 })
787 }
788
789 // Expose chunk index type.
790 type ChunkIdx chunkIdx
791
792 // Expose pageAlloc for testing. Note that because pageAlloc is
793 // not in the heap, so is PageAlloc.
794 type PageAlloc pageAlloc
795
796 func (p *PageAlloc) Alloc(npages uintptr) (uintptr, uintptr) {
797 pp := (*pageAlloc)(p)
798
799 var addr, scav uintptr
800 systemstack(func() {
801 // None of the tests need any higher-level locking, so we just
802 // take the lock internally.
803 lock(pp.mheapLock)
804 addr, scav = pp.alloc(npages)
805 unlock(pp.mheapLock)
806 })
807 return addr, scav
808 }
809 func (p *PageAlloc) AllocToCache() PageCache {
810 pp := (*pageAlloc)(p)
811
812 var c PageCache
813 systemstack(func() {
814 // None of the tests need any higher-level locking, so we just
815 // take the lock internally.
816 lock(pp.mheapLock)
817 c = PageCache(pp.allocToCache())
818 unlock(pp.mheapLock)
819 })
820 return c
821 }
822 func (p *PageAlloc) Free(base, npages uintptr) {
823 pp := (*pageAlloc)(p)
824
825 systemstack(func() {
826 // None of the tests need any higher-level locking, so we just
827 // take the lock internally.
828 lock(pp.mheapLock)
829 pp.free(base, npages)
830 unlock(pp.mheapLock)
831 })
832 }
833 func (p *PageAlloc) Bounds() (ChunkIdx, ChunkIdx) {
834 return ChunkIdx((*pageAlloc)(p).start), ChunkIdx((*pageAlloc)(p).end)
835 }
836 func (p *PageAlloc) Scavenge(nbytes uintptr) (r uintptr) {
837 pp := (*pageAlloc)(p)
838 systemstack(func() {
839 r = pp.scavenge(nbytes, nil, true)
840 })
841 return
842 }
843 func (p *PageAlloc) InUse() []AddrRange {
844 ranges := make([]AddrRange, 0, len(p.inUse.ranges))
845 for _, r := range p.inUse.ranges {
846 ranges = append(ranges, AddrRange{r})
847 }
848 return ranges
849 }
850
851 // Returns nil if the PallocData's L2 is missing.
852 func (p *PageAlloc) PallocData(i ChunkIdx) *PallocData {
853 ci := chunkIdx(i)
854 return (*PallocData)((*pageAlloc)(p).tryChunkOf(ci))
855 }
856
857 // AddrRange is a wrapper around addrRange for testing.
858 type AddrRange struct {
859 addrRange
860 }
861
862 // MakeAddrRange creates a new address range.
863 func MakeAddrRange(base, limit uintptr) AddrRange {
864 return AddrRange{makeAddrRange(base, limit)}
865 }
866
867 // Base returns the virtual base address of the address range.
868 func (a AddrRange) Base() uintptr {
869 return a.addrRange.base.addr()
870 }
871
872 // Base returns the virtual address of the limit of the address range.
873 func (a AddrRange) Limit() uintptr {
874 return a.addrRange.limit.addr()
875 }
876
877 // Equals returns true if the two address ranges are exactly equal.
878 func (a AddrRange) Equals(b AddrRange) bool {
879 return a == b
880 }
881
882 // Size returns the size in bytes of the address range.
883 func (a AddrRange) Size() uintptr {
884 return a.addrRange.size()
885 }
886
887 // testSysStat is the sysStat passed to test versions of various
888 // runtime structures. We do actually have to keep track of this
889 // because otherwise memstats.mappedReady won't actually line up
890 // with other stats in the runtime during tests.
891 var testSysStat = &memstats.other_sys
892
893 // AddrRanges is a wrapper around addrRanges for testing.
894 type AddrRanges struct {
895 addrRanges
896 mutable bool
897 }
898
899 // NewAddrRanges creates a new empty addrRanges.
900 //
901 // Note that this initializes addrRanges just like in the
902 // runtime, so its memory is persistentalloc'd. Call this
903 // function sparingly since the memory it allocates is
904 // leaked.
905 //
906 // This AddrRanges is mutable, so we can test methods like
907 // Add.
908 func NewAddrRanges() AddrRanges {
909 r := addrRanges{}
910 r.init(testSysStat)
911 return AddrRanges{r, true}
912 }
913
914 // MakeAddrRanges creates a new addrRanges populated with
915 // the ranges in a.
916 //
917 // The returned AddrRanges is immutable, so methods like
918 // Add will fail.
919 func MakeAddrRanges(a ...AddrRange) AddrRanges {
920 // Methods that manipulate the backing store of addrRanges.ranges should
921 // not be used on the result from this function (e.g. add) since they may
922 // trigger reallocation. That would normally be fine, except the new
923 // backing store won't come from the heap, but from persistentalloc, so
924 // we'll leak some memory implicitly.
925 ranges := make([]addrRange, 0, len(a))
926 total := uintptr(0)
927 for _, r := range a {
928 ranges = append(ranges, r.addrRange)
929 total += r.Size()
930 }
931 return AddrRanges{addrRanges{
932 ranges: ranges,
933 totalBytes: total,
934 sysStat: testSysStat,
935 }, false}
936 }
937
938 // Ranges returns a copy of the ranges described by the
939 // addrRanges.
940 func (a *AddrRanges) Ranges() []AddrRange {
941 result := make([]AddrRange, 0, len(a.addrRanges.ranges))
942 for _, r := range a.addrRanges.ranges {
943 result = append(result, AddrRange{r})
944 }
945 return result
946 }
947
948 // FindSucc returns the successor to base. See addrRanges.findSucc
949 // for more details.
950 func (a *AddrRanges) FindSucc(base uintptr) int {
951 return a.findSucc(base)
952 }
953
954 // Add adds a new AddrRange to the AddrRanges.
955 //
956 // The AddrRange must be mutable (i.e. created by NewAddrRanges),
957 // otherwise this method will throw.
958 func (a *AddrRanges) Add(r AddrRange) {
959 if !a.mutable {
960 throw("attempt to mutate immutable AddrRanges")
961 }
962 a.add(r.addrRange)
963 }
964
965 // TotalBytes returns the totalBytes field of the addrRanges.
966 func (a *AddrRanges) TotalBytes() uintptr {
967 return a.addrRanges.totalBytes
968 }
969
970 // BitRange represents a range over a bitmap.
971 type BitRange struct {
972 I, N uint // bit index and length in bits
973 }
974
975 // NewPageAlloc creates a new page allocator for testing and
976 // initializes it with the scav and chunks maps. Each key in these maps
977 // represents a chunk index and each value is a series of bit ranges to
978 // set within each bitmap's chunk.
979 //
980 // The initialization of the pageAlloc preserves the invariant that if a
981 // scavenged bit is set the alloc bit is necessarily unset, so some
982 // of the bits described by scav may be cleared in the final bitmap if
983 // ranges in chunks overlap with them.
984 //
985 // scav is optional, and if nil, the scavenged bitmap will be cleared
986 // (as opposed to all 1s, which it usually is). Furthermore, every
987 // chunk index in scav must appear in chunks; ones that do not are
988 // ignored.
989 func NewPageAlloc(chunks, scav map[ChunkIdx][]BitRange) *PageAlloc {
990 p := new(pageAlloc)
991
992 // We've got an entry, so initialize the pageAlloc.
993 p.init(new(mutex), testSysStat, true)
994 lockInit(p.mheapLock, lockRankMheap)
995 for i, init := range chunks {
996 addr := chunkBase(chunkIdx(i))
997
998 // Mark the chunk's existence in the pageAlloc.
999 systemstack(func() {
1000 lock(p.mheapLock)
1001 p.grow(addr, pallocChunkBytes)
1002 unlock(p.mheapLock)
1003 })
1004
1005 // Initialize the bitmap and update pageAlloc metadata.
1006 ci := chunkIndex(addr)
1007 chunk := p.chunkOf(ci)
1008
1009 // Clear all the scavenged bits which grow set.
1010 chunk.scavenged.clearRange(0, pallocChunkPages)
1011
1012 // Simulate the allocation and subsequent free of all pages in
1013 // the chunk for the scavenge index. This sets the state equivalent
1014 // with all pages within the index being free.
1015 p.scav.index.alloc(ci, pallocChunkPages)
1016 p.scav.index.free(ci, 0, pallocChunkPages)
1017
1018 // Apply scavenge state if applicable.
1019 if scav != nil {
1020 if scvg, ok := scav[i]; ok {
1021 for _, s := range scvg {
1022 // Ignore the case of s.N == 0. setRange doesn't handle
1023 // it and it's a no-op anyway.
1024 if s.N != 0 {
1025 chunk.scavenged.setRange(s.I, s.N)
1026 }
1027 }
1028 }
1029 }
1030
1031 // Apply alloc state.
1032 for _, s := range init {
1033 // Ignore the case of s.N == 0. allocRange doesn't handle
1034 // it and it's a no-op anyway.
1035 if s.N != 0 {
1036 chunk.allocRange(s.I, s.N)
1037
1038 // Make sure the scavenge index is updated.
1039 p.scav.index.alloc(ci, s.N)
1040 }
1041 }
1042
1043 // Update heap metadata for the allocRange calls above.
1044 systemstack(func() {
1045 lock(p.mheapLock)
1046 p.update(addr, pallocChunkPages, false, false)
1047 unlock(p.mheapLock)
1048 })
1049 }
1050
1051 return (*PageAlloc)(p)
1052 }
1053
1054 // FreePageAlloc releases hard OS resources owned by the pageAlloc. Once this
1055 // is called the pageAlloc may no longer be used. The object itself will be
1056 // collected by the garbage collector once it is no longer live.
1057 func FreePageAlloc(pp *PageAlloc) {
1058 p := (*pageAlloc)(pp)
1059
1060 // Free all the mapped space for the summary levels.
1061 if pageAlloc64Bit != 0 {
1062 for l := 0; l < summaryLevels; l++ {
1063 // This isn't quite right, as some of this memory may
1064 // be Ready instead of Reserved. The mappedReady and
1065 // testSysStat adjustments below correct for the
1066 // difference.
1067 sysUnreserve(unsafe.Pointer(&p.summary[l][0]), uintptr(cap(p.summary[l]))*pallocSumBytes)
1068 }
1069 } else {
1070 resSize := uintptr(0)
1071 for _, s := range p.summary {
1072 resSize += uintptr(cap(s)) * pallocSumBytes
1073 }
1074 // See sysUnreserve comment above.
1075 sysUnreserve(unsafe.Pointer(&p.summary[0][0]), alignUp(resSize, physPageSize))
1076 }
1077
1078 // Subtract back out whatever we mapped for the summaries.
1079 // sysUsed adds to p.sysStat and memstats.mappedReady no matter what
1080 // (and in anger should actually be accounted for), and there's no other
1081 // way to figure out how much we actually mapped.
1082 gcController.mappedReady.Add(-int64(p.summaryMappedReady))
1083 testSysStat.add(-int64(p.summaryMappedReady))
1084
1085 // Free extra data structures.
1086 //
1087 // TODO(prattmic): As above, some of this may be Ready, so we should
1088 // manually adjust mappedReady and testSysStat?
1089 sysUnreserve(unsafe.Pointer(&p.scav.index.chunks[0]), uintptr(cap(p.scav.index.chunks))*unsafe.Sizeof(atomicScavChunkData{}))
1090
1091 // Free the mapped space for chunks.
1092 for i := range p.chunks {
1093 if x := p.chunks[i]; x != nil {
1094 p.chunks[i] = nil
1095 // This memory comes from sysAlloc and will always be page-aligned.
1096 sysFree(unsafe.Pointer(x), unsafe.Sizeof(*p.chunks[0]), testSysStat)
1097 }
1098 }
1099 }
1100
1101 // BaseChunkIdx is a convenient chunkIdx value which works on both
1102 // 64 bit and 32 bit platforms, allowing the tests to share code
1103 // between the two.
1104 //
1105 // This should not be higher than 0x100*pallocChunkBytes to support
1106 // mips and mipsle, which only have 31-bit address spaces.
1107 var BaseChunkIdx = func() ChunkIdx {
1108 var prefix uintptr
1109 if pageAlloc64Bit != 0 {
1110 prefix = 0xc000
1111 } else {
1112 prefix = 0x100
1113 }
1114 baseAddr := prefix * pallocChunkBytes
1115 if goos.IsAix != 0 {
1116 baseAddr += arenaBaseOffset
1117 }
1118 return ChunkIdx(chunkIndex(baseAddr))
1119 }()
1120
1121 // PageBase returns an address given a chunk index and a page index
1122 // relative to that chunk.
1123 func PageBase(c ChunkIdx, pageIdx uint) uintptr {
1124 return chunkBase(chunkIdx(c)) + uintptr(pageIdx)*pageSize
1125 }
1126
1127 type BitsMismatch struct {
1128 Base uintptr
1129 Got, Want uint64
1130 }
1131
1132 func CheckScavengedBitsCleared(mismatches []BitsMismatch) (n int, ok bool) {
1133 ok = true
1134
1135 // Run on the system stack to avoid stack growth allocation.
1136 systemstack(func() {
1137 getg().m.mallocing++
1138
1139 // Lock so that we can safely access the bitmap.
1140 lock(&mheap_.lock)
1141 chunkLoop:
1142 for i := mheap_.pages.start; i < mheap_.pages.end; i++ {
1143 chunk := mheap_.pages.tryChunkOf(i)
1144 if chunk == nil {
1145 continue
1146 }
1147 for j := 0; j < pallocChunkPages/64; j++ {
1148 // Run over each 64-bit bitmap section and ensure
1149 // scavenged is being cleared properly on allocation.
1150 // If a used bit and scavenged bit are both set, that's
1151 // an error, and could indicate a larger problem, or
1152 // an accounting problem.
1153 want := chunk.scavenged[j] &^ chunk.pallocBits[j]
1154 got := chunk.scavenged[j]
1155 if want != got {
1156 ok = false
1157 if n >= len(mismatches) {
1158 break chunkLoop
1159 }
1160 mismatches[n] = BitsMismatch{
1161 Base: chunkBase(i) + uintptr(j)*64*pageSize,
1162 Got: got,
1163 Want: want,
1164 }
1165 n++
1166 }
1167 }
1168 }
1169 unlock(&mheap_.lock)
1170
1171 getg().m.mallocing--
1172 })
1173 return
1174 }
1175
1176 func PageCachePagesLeaked() (leaked uintptr) {
1177 stw := stopTheWorld(stwForTestPageCachePagesLeaked)
1178
1179 // Walk over destroyed Ps and look for unflushed caches.
1180 deadp := allp[len(allp):cap(allp)]
1181 for _, p := range deadp {
1182 // Since we're going past len(allp) we may see nil Ps.
1183 // Just ignore them.
1184 if p != nil {
1185 leaked += uintptr(sys.OnesCount64(p.pcache.cache))
1186 }
1187 }
1188
1189 startTheWorld(stw)
1190 return
1191 }
1192
1193 var ProcYield = procyield
1194 var OSYield = osyield
1195
1196 type Mutex = mutex
1197
1198 var Lock = lock
1199 var Unlock = unlock
1200
1201 var MutexContended = mutexContended
1202
1203 func SemRootLock(addr *uint32) *mutex {
1204 root := semtable.rootFor(addr)
1205 return &root.lock
1206 }
1207
1208 var Semacquire = semacquire
1209 var Semrelease1 = semrelease1
1210
1211 func SemNwait(addr *uint32) uint32 {
1212 root := semtable.rootFor(addr)
1213 return root.nwait.Load()
1214 }
1215
1216 const SemTableSize = semTabSize
1217
1218 // SemTable is a wrapper around semTable exported for testing.
1219 type SemTable struct {
1220 semTable
1221 }
1222
1223 // Enqueue simulates enqueuing a waiter for a semaphore (or lock) at addr.
1224 func (t *SemTable) Enqueue(addr *uint32) {
1225 s := acquireSudog()
1226 s.releasetime = 0
1227 s.acquiretime = 0
1228 s.ticket = 0
1229 t.semTable.rootFor(addr).queue(addr, s, false)
1230 }
1231
1232 // Dequeue simulates dequeuing a waiter for a semaphore (or lock) at addr.
1233 //
1234 // Returns true if there actually was a waiter to be dequeued.
1235 func (t *SemTable) Dequeue(addr *uint32) bool {
1236 s, _, _ := t.semTable.rootFor(addr).dequeue(addr)
1237 if s != nil {
1238 releaseSudog(s)
1239 return true
1240 }
1241 return false
1242 }
1243
1244 // mspan wrapper for testing.
1245 type MSpan mspan
1246
1247 // Allocate an mspan for testing.
1248 func AllocMSpan() *MSpan {
1249 var s *mspan
1250 systemstack(func() {
1251 lock(&mheap_.lock)
1252 s = (*mspan)(mheap_.spanalloc.alloc())
1253 s.init(0, 0)
1254 unlock(&mheap_.lock)
1255 })
1256 return (*MSpan)(s)
1257 }
1258
1259 // Free an allocated mspan.
1260 func FreeMSpan(s *MSpan) {
1261 systemstack(func() {
1262 lock(&mheap_.lock)
1263 mheap_.spanalloc.free(unsafe.Pointer(s))
1264 unlock(&mheap_.lock)
1265 })
1266 }
1267
1268 func MSpanCountAlloc(ms *MSpan, bits []byte) int {
1269 s := (*mspan)(ms)
1270 s.nelems = uint16(len(bits) * 8)
1271 s.gcmarkBits = (*gcBits)(unsafe.Pointer(&bits[0]))
1272 result := s.countAlloc()
1273 s.gcmarkBits = nil
1274 return result
1275 }
1276
1277 type MSpanQueue mSpanQueue
1278
1279 func (q *MSpanQueue) Size() int {
1280 return (*mSpanQueue)(q).n
1281 }
1282
1283 func (q *MSpanQueue) Push(s *MSpan) {
1284 (*mSpanQueue)(q).push((*mspan)(s))
1285 }
1286
1287 func (q *MSpanQueue) Pop() *MSpan {
1288 s := (*mSpanQueue)(q).pop()
1289 return (*MSpan)(s)
1290 }
1291
1292 func (q *MSpanQueue) TakeAll(p *MSpanQueue) {
1293 (*mSpanQueue)(q).takeAll((*mSpanQueue)(p))
1294 }
1295
1296 func (q *MSpanQueue) PopN(n int) MSpanQueue {
1297 p := (*mSpanQueue)(q).popN(n)
1298 return (MSpanQueue)(p)
1299 }
1300
1301 const (
1302 TimeHistSubBucketBits = timeHistSubBucketBits
1303 TimeHistNumSubBuckets = timeHistNumSubBuckets
1304 TimeHistNumBuckets = timeHistNumBuckets
1305 TimeHistMinBucketBits = timeHistMinBucketBits
1306 TimeHistMaxBucketBits = timeHistMaxBucketBits
1307 )
1308
1309 type TimeHistogram timeHistogram
1310
1311 // Count returns the counts for the given bucket, subBucket indices.
1312 // Returns true if the bucket was valid, otherwise returns the counts
1313 // for the overflow bucket if bucket > 0 or the underflow bucket if
1314 // bucket < 0, and false.
1315 func (th *TimeHistogram) Count(bucket, subBucket int) (uint64, bool) {
1316 t := (*timeHistogram)(th)
1317 if bucket < 0 {
1318 return t.underflow.Load(), false
1319 }
1320 i := bucket*TimeHistNumSubBuckets + subBucket
1321 if i >= len(t.counts) {
1322 return t.overflow.Load(), false
1323 }
1324 return t.counts[i].Load(), true
1325 }
1326
1327 func (th *TimeHistogram) Record(duration int64) {
1328 (*timeHistogram)(th).record(duration)
1329 }
1330
1331 var TimeHistogramMetricsBuckets = timeHistogramMetricsBuckets
1332
1333 func SetIntArgRegs(a int) int {
1334 lock(&finlock)
1335 old := intArgRegs
1336 if a >= 0 {
1337 intArgRegs = a
1338 }
1339 unlock(&finlock)
1340 return old
1341 }
1342
1343 func FinalizerGAsleep() bool {
1344 return fingStatus.Load()&fingWait != 0
1345 }
1346
1347 // For GCTestMoveStackOnNextCall, it's important not to introduce an
1348 // extra layer of call, since then there's a return before the "real"
1349 // next call.
1350 var GCTestMoveStackOnNextCall = gcTestMoveStackOnNextCall
1351
1352 // For GCTestIsReachable, it's important that we do this as a call so
1353 // escape analysis can see through it.
1354 func GCTestIsReachable(ptrs ...unsafe.Pointer) (mask uint64) {
1355 return gcTestIsReachable(ptrs...)
1356 }
1357
1358 // For GCTestPointerClass, it's important that we do this as a call so
1359 // escape analysis can see through it.
1360 //
1361 // This is nosplit because gcTestPointerClass is.
1362 //
1363 //go:nosplit
1364 func GCTestPointerClass(p unsafe.Pointer) string {
1365 return gcTestPointerClass(p)
1366 }
1367
1368 const Raceenabled = raceenabled
1369
1370 const (
1371 GCBackgroundUtilization = gcBackgroundUtilization
1372 GCGoalUtilization = gcGoalUtilization
1373 DefaultHeapMinimum = defaultHeapMinimum
1374 MemoryLimitHeapGoalHeadroomPercent = memoryLimitHeapGoalHeadroomPercent
1375 MemoryLimitMinHeapGoalHeadroom = memoryLimitMinHeapGoalHeadroom
1376 )
1377
1378 type GCController struct {
1379 gcControllerState
1380 }
1381
1382 func NewGCController(gcPercent int, memoryLimit int64) *GCController {
1383 // Force the controller to escape. We're going to
1384 // do 64-bit atomics on it, and if it gets stack-allocated
1385 // on a 32-bit architecture, it may get allocated unaligned
1386 // space.
1387 g := Escape(new(GCController))
1388 g.gcControllerState.test = true // Mark it as a test copy.
1389 g.init(int32(gcPercent), memoryLimit)
1390 return g
1391 }
1392
1393 func (c *GCController) StartCycle(stackSize, globalsSize uint64, scannableFrac float64, gomaxprocs int) {
1394 trigger, _ := c.trigger()
1395 if c.heapMarked > trigger {
1396 trigger = c.heapMarked
1397 }
1398 c.maxStackScan.Store(stackSize)
1399 c.globalsScan.Store(globalsSize)
1400 c.heapLive.Store(trigger)
1401 c.heapScan.Add(int64(float64(trigger-c.heapMarked) * scannableFrac))
1402 c.startCycle(0, gomaxprocs, gcTrigger{kind: gcTriggerHeap})
1403 }
1404
1405 func (c *GCController) AssistWorkPerByte() float64 {
1406 return c.assistWorkPerByte.Load()
1407 }
1408
1409 func (c *GCController) HeapGoal() uint64 {
1410 return c.heapGoal()
1411 }
1412
1413 func (c *GCController) HeapLive() uint64 {
1414 return c.heapLive.Load()
1415 }
1416
1417 func (c *GCController) HeapMarked() uint64 {
1418 return c.heapMarked
1419 }
1420
1421 func (c *GCController) Triggered() uint64 {
1422 return c.triggered
1423 }
1424
1425 type GCControllerReviseDelta struct {
1426 HeapLive int64
1427 HeapScan int64
1428 HeapScanWork int64
1429 StackScanWork int64
1430 GlobalsScanWork int64
1431 }
1432
1433 func (c *GCController) Revise(d GCControllerReviseDelta) {
1434 c.heapLive.Add(d.HeapLive)
1435 c.heapScan.Add(d.HeapScan)
1436 c.heapScanWork.Add(d.HeapScanWork)
1437 c.stackScanWork.Add(d.StackScanWork)
1438 c.globalsScanWork.Add(d.GlobalsScanWork)
1439 c.revise()
1440 }
1441
1442 func (c *GCController) EndCycle(bytesMarked uint64, assistTime, elapsed int64, gomaxprocs int) {
1443 c.assistTime.Store(assistTime)
1444 c.endCycle(elapsed, gomaxprocs, false)
1445 c.resetLive(bytesMarked)
1446 c.commit(false)
1447 }
1448
1449 func (c *GCController) AddIdleMarkWorker() bool {
1450 return c.addIdleMarkWorker()
1451 }
1452
1453 func (c *GCController) NeedIdleMarkWorker() bool {
1454 return c.needIdleMarkWorker()
1455 }
1456
1457 func (c *GCController) RemoveIdleMarkWorker() {
1458 c.removeIdleMarkWorker()
1459 }
1460
1461 func (c *GCController) SetMaxIdleMarkWorkers(max int32) {
1462 c.setMaxIdleMarkWorkers(max)
1463 }
1464
1465 var alwaysFalse bool
1466 var escapeSink any
1467
1468 func Escape[T any](x T) T {
1469 if alwaysFalse {
1470 escapeSink = x
1471 }
1472 return x
1473 }
1474
1475 // Acquirem blocks preemption.
1476 func Acquirem() {
1477 acquirem()
1478 }
1479
1480 func Releasem() {
1481 releasem(getg().m)
1482 }
1483
1484 var Timediv = timediv
1485
1486 type PIController struct {
1487 piController
1488 }
1489
1490 func NewPIController(kp, ti, tt, min, max float64) *PIController {
1491 return &PIController{piController{
1492 kp: kp,
1493 ti: ti,
1494 tt: tt,
1495 min: min,
1496 max: max,
1497 }}
1498 }
1499
1500 func (c *PIController) Next(input, setpoint, period float64) (float64, bool) {
1501 return c.piController.next(input, setpoint, period)
1502 }
1503
1504 const (
1505 CapacityPerProc = capacityPerProc
1506 GCCPULimiterUpdatePeriod = gcCPULimiterUpdatePeriod
1507 )
1508
1509 type GCCPULimiter struct {
1510 limiter gcCPULimiterState
1511 }
1512
1513 func NewGCCPULimiter(now int64, gomaxprocs int32) *GCCPULimiter {
1514 // Force the controller to escape. We're going to
1515 // do 64-bit atomics on it, and if it gets stack-allocated
1516 // on a 32-bit architecture, it may get allocated unaligned
1517 // space.
1518 l := Escape(new(GCCPULimiter))
1519 l.limiter.test = true
1520 l.limiter.resetCapacity(now, gomaxprocs)
1521 return l
1522 }
1523
1524 func (l *GCCPULimiter) Fill() uint64 {
1525 return l.limiter.bucket.fill
1526 }
1527
1528 func (l *GCCPULimiter) Capacity() uint64 {
1529 return l.limiter.bucket.capacity
1530 }
1531
1532 func (l *GCCPULimiter) Overflow() uint64 {
1533 return l.limiter.overflow
1534 }
1535
1536 func (l *GCCPULimiter) Limiting() bool {
1537 return l.limiter.limiting()
1538 }
1539
1540 func (l *GCCPULimiter) NeedUpdate(now int64) bool {
1541 return l.limiter.needUpdate(now)
1542 }
1543
1544 func (l *GCCPULimiter) StartGCTransition(enableGC bool, now int64) {
1545 l.limiter.startGCTransition(enableGC, now)
1546 }
1547
1548 func (l *GCCPULimiter) FinishGCTransition(now int64) {
1549 l.limiter.finishGCTransition(now)
1550 }
1551
1552 func (l *GCCPULimiter) Update(now int64) {
1553 l.limiter.update(now)
1554 }
1555
1556 func (l *GCCPULimiter) AddAssistTime(t int64) {
1557 l.limiter.addAssistTime(t)
1558 }
1559
1560 func (l *GCCPULimiter) ResetCapacity(now int64, nprocs int32) {
1561 l.limiter.resetCapacity(now, nprocs)
1562 }
1563
1564 const ScavengePercent = scavengePercent
1565
1566 type Scavenger struct {
1567 Sleep func(int64) int64
1568 Scavenge func(uintptr) (uintptr, int64)
1569 ShouldStop func() bool
1570 GoMaxProcs func() int32
1571
1572 released atomic.Uintptr
1573 scavenger scavengerState
1574 stop chan<- struct{}
1575 done <-chan struct{}
1576 }
1577
1578 func (s *Scavenger) Start() {
1579 if s.Sleep == nil || s.Scavenge == nil || s.ShouldStop == nil || s.GoMaxProcs == nil {
1580 panic("must populate all stubs")
1581 }
1582
1583 // Install hooks.
1584 s.scavenger.sleepStub = s.Sleep
1585 s.scavenger.scavenge = s.Scavenge
1586 s.scavenger.shouldStop = s.ShouldStop
1587 s.scavenger.gomaxprocs = s.GoMaxProcs
1588
1589 // Start up scavenger goroutine, and wait for it to be ready.
1590 stop := make(chan struct{})
1591 s.stop = stop
1592 done := make(chan struct{})
1593 s.done = done
1594 go func() {
1595 // This should match bgscavenge, loosely.
1596 s.scavenger.init()
1597 s.scavenger.park()
1598 for {
1599 select {
1600 case <-stop:
1601 close(done)
1602 return
1603 default:
1604 }
1605 released, workTime := s.scavenger.run()
1606 if released == 0 {
1607 s.scavenger.park()
1608 continue
1609 }
1610 s.released.Add(released)
1611 s.scavenger.sleep(workTime)
1612 }
1613 }()
1614 if !s.BlockUntilParked(1e9 /* 1 second */) {
1615 panic("timed out waiting for scavenger to get ready")
1616 }
1617 }
1618
1619 // BlockUntilParked blocks until the scavenger parks, or until
1620 // timeout is exceeded. Returns true if the scavenger parked.
1621 //
1622 // Note that in testing, parked means something slightly different.
1623 // In anger, the scavenger parks to sleep, too, but in testing,
1624 // it only parks when it actually has no work to do.
1625 func (s *Scavenger) BlockUntilParked(timeout int64) bool {
1626 // Just spin, waiting for it to park.
1627 //
1628 // The actual parking process is racy with respect to
1629 // wakeups, which is fine, but for testing we need something
1630 // a bit more robust.
1631 start := nanotime()
1632 for nanotime()-start < timeout {
1633 lock(&s.scavenger.lock)
1634 parked := s.scavenger.parked
1635 unlock(&s.scavenger.lock)
1636 if parked {
1637 return true
1638 }
1639 Gosched()
1640 }
1641 return false
1642 }
1643
1644 // Released returns how many bytes the scavenger released.
1645 func (s *Scavenger) Released() uintptr {
1646 return s.released.Load()
1647 }
1648
1649 // Wake wakes up a parked scavenger to keep running.
1650 func (s *Scavenger) Wake() {
1651 s.scavenger.wake()
1652 }
1653
1654 // Stop cleans up the scavenger's resources. The scavenger
1655 // must be parked for this to work.
1656 func (s *Scavenger) Stop() {
1657 lock(&s.scavenger.lock)
1658 parked := s.scavenger.parked
1659 unlock(&s.scavenger.lock)
1660 if !parked {
1661 panic("tried to clean up scavenger that is not parked")
1662 }
1663 close(s.stop)
1664 s.Wake()
1665 <-s.done
1666 }
1667
1668 type ScavengeIndex struct {
1669 i scavengeIndex
1670 }
1671
1672 func NewScavengeIndex(min, max ChunkIdx) *ScavengeIndex {
1673 s := new(ScavengeIndex)
1674 // This is a bit lazy but we easily guarantee we'll be able
1675 // to reference all the relevant chunks. The worst-case
1676 // memory usage here is 512 MiB, but tests generally use
1677 // small offsets from BaseChunkIdx, which results in ~100s
1678 // of KiB in memory use.
1679 //
1680 // This may still be worth making better, at least by sharing
1681 // this fairly large array across calls with a sync.Pool or
1682 // something. Currently, when the tests are run serially,
1683 // it takes around 0.5s. Not all that much, but if we have
1684 // a lot of tests like this it could add up.
1685 s.i.chunks = make([]atomicScavChunkData, max)
1686 s.i.min.Store(uintptr(min))
1687 s.i.max.Store(uintptr(max))
1688 s.i.minHeapIdx.Store(uintptr(min))
1689 s.i.test = true
1690 return s
1691 }
1692
1693 func (s *ScavengeIndex) Find(force bool) (ChunkIdx, uint) {
1694 ci, off := s.i.find(force)
1695 return ChunkIdx(ci), off
1696 }
1697
1698 func (s *ScavengeIndex) AllocRange(base, limit uintptr) {
1699 sc, ec := chunkIndex(base), chunkIndex(limit-1)
1700 si, ei := chunkPageIndex(base), chunkPageIndex(limit-1)
1701
1702 if sc == ec {
1703 // The range doesn't cross any chunk boundaries.
1704 s.i.alloc(sc, ei+1-si)
1705 } else {
1706 // The range crosses at least one chunk boundary.
1707 s.i.alloc(sc, pallocChunkPages-si)
1708 for c := sc + 1; c < ec; c++ {
1709 s.i.alloc(c, pallocChunkPages)
1710 }
1711 s.i.alloc(ec, ei+1)
1712 }
1713 }
1714
1715 func (s *ScavengeIndex) FreeRange(base, limit uintptr) {
1716 sc, ec := chunkIndex(base), chunkIndex(limit-1)
1717 si, ei := chunkPageIndex(base), chunkPageIndex(limit-1)
1718
1719 if sc == ec {
1720 // The range doesn't cross any chunk boundaries.
1721 s.i.free(sc, si, ei+1-si)
1722 } else {
1723 // The range crosses at least one chunk boundary.
1724 s.i.free(sc, si, pallocChunkPages-si)
1725 for c := sc + 1; c < ec; c++ {
1726 s.i.free(c, 0, pallocChunkPages)
1727 }
1728 s.i.free(ec, 0, ei+1)
1729 }
1730 }
1731
1732 func (s *ScavengeIndex) ResetSearchAddrs() {
1733 for _, a := range []*atomicOffAddr{&s.i.searchAddrBg, &s.i.searchAddrForce} {
1734 addr, marked := a.Load()
1735 if marked {
1736 a.StoreUnmark(addr, addr)
1737 }
1738 a.Clear()
1739 }
1740 s.i.freeHWM = minOffAddr
1741 }
1742
1743 func (s *ScavengeIndex) NextGen() {
1744 s.i.nextGen()
1745 }
1746
1747 func (s *ScavengeIndex) SetEmpty(ci ChunkIdx) {
1748 s.i.setEmpty(chunkIdx(ci))
1749 }
1750
1751 func CheckPackScavChunkData(gen uint32, inUse, lastInUse uint16, flags uint8) bool {
1752 sc0 := scavChunkData{
1753 gen: gen,
1754 inUse: inUse,
1755 lastInUse: lastInUse,
1756 scavChunkFlags: scavChunkFlags(flags),
1757 }
1758 scp := sc0.pack()
1759 sc1 := unpackScavChunkData(scp)
1760 return sc0 == sc1
1761 }
1762
1763 const GTrackingPeriod = gTrackingPeriod
1764
1765 var ZeroBase = unsafe.Pointer(&zerobase)
1766
1767 const UserArenaChunkBytes = userArenaChunkBytes
1768
1769 type UserArena struct {
1770 arena *userArena
1771 }
1772
1773 func NewUserArena() *UserArena {
1774 return &UserArena{newUserArena()}
1775 }
1776
1777 func (a *UserArena) New(out *any) {
1778 i := efaceOf(out)
1779 typ := i._type
1780 if typ.Kind_&abi.KindMask != abi.Pointer {
1781 panic("new result of non-ptr type")
1782 }
1783 typ = (*ptrtype)(unsafe.Pointer(typ)).Elem
1784 i.data = a.arena.new(typ)
1785 }
1786
1787 func (a *UserArena) Slice(sl any, cap int) {
1788 a.arena.slice(sl, cap)
1789 }
1790
1791 func (a *UserArena) Free() {
1792 a.arena.free()
1793 }
1794
1795 func GlobalWaitingArenaChunks() int {
1796 n := 0
1797 systemstack(func() {
1798 lock(&mheap_.lock)
1799 for s := mheap_.userArena.quarantineList.first; s != nil; s = s.next {
1800 n++
1801 }
1802 unlock(&mheap_.lock)
1803 })
1804 return n
1805 }
1806
1807 func UserArenaClone[T any](s T) T {
1808 return arena_heapify(s).(T)
1809 }
1810
1811 var AlignUp = alignUp
1812
1813 func BlockUntilEmptyFinalizerQueue(timeout int64) bool {
1814 return blockUntilEmptyFinalizerQueue(timeout)
1815 }
1816
1817 func BlockUntilEmptyCleanupQueue(timeout int64) bool {
1818 return gcCleanups.blockUntilEmpty(timeout)
1819 }
1820
1821 func FrameStartLine(f *Frame) int {
1822 return f.startLine
1823 }
1824
1825 // PersistentAlloc allocates some memory that lives outside the Go heap.
1826 // This memory will never be freed; use sparingly.
1827 func PersistentAlloc(n, align uintptr) unsafe.Pointer {
1828 return persistentalloc(n, align, &memstats.other_sys)
1829 }
1830
1831 const TagAlign = tagAlign
1832
1833 // FPCallers works like Callers and uses frame pointer unwinding to populate
1834 // pcBuf with the return addresses of the physical frames on the stack.
1835 func FPCallers(pcBuf []uintptr) int {
1836 return fpTracebackPCs(unsafe.Pointer(getfp()), pcBuf)
1837 }
1838
1839 const FramePointerEnabled = framepointer_enabled
1840
1841 var (
1842 IsPinned = isPinned
1843 GetPinCounter = pinnerGetPinCounter
1844 )
1845
1846 func SetPinnerLeakPanic(f func()) {
1847 pinnerLeakPanic = f
1848 }
1849 func GetPinnerLeakPanic() func() {
1850 return pinnerLeakPanic
1851 }
1852
1853 var testUintptr uintptr
1854
1855 func MyGenericFunc[T any]() {
1856 systemstack(func() {
1857 testUintptr = 4
1858 })
1859 }
1860
1861 func UnsafePoint(pc uintptr) bool {
1862 fi := findfunc(pc)
1863 v := pcdatavalue(fi, abi.PCDATA_UnsafePoint, pc)
1864 switch v {
1865 case abi.UnsafePointUnsafe:
1866 return true
1867 case abi.UnsafePointSafe:
1868 return false
1869 case abi.UnsafePointRestart1, abi.UnsafePointRestart2, abi.UnsafePointRestartAtEntry:
1870 // These are all interruptible, they just encode a nonstandard
1871 // way of recovering when interrupted.
1872 return false
1873 default:
1874 var buf [20]byte
1875 panic("invalid unsafe point code " + string(itoa(buf[:], uint64(v))))
1876 }
1877 }
1878
1879 type TraceMap struct {
1880 traceMap
1881 }
1882
1883 func (m *TraceMap) PutString(s string) (uint64, bool) {
1884 return m.traceMap.put(unsafe.Pointer(unsafe.StringData(s)), uintptr(len(s)))
1885 }
1886
1887 func (m *TraceMap) Reset() {
1888 m.traceMap.reset()
1889 }
1890
1891 func SetSpinInGCMarkDone(spin bool) {
1892 gcDebugMarkDone.spinAfterRaggedBarrier.Store(spin)
1893 }
1894
1895 func GCMarkDoneRestarted() bool {
1896 // Only read this outside of the GC. If we're running during a GC, just report false.
1897 mp := acquirem()
1898 if gcphase != _GCoff {
1899 releasem(mp)
1900 return false
1901 }
1902 restarted := gcDebugMarkDone.restartedDueTo27993
1903 releasem(mp)
1904 return restarted
1905 }
1906
1907 func GCMarkDoneResetRestartFlag() {
1908 mp := acquirem()
1909 for gcphase != _GCoff {
1910 releasem(mp)
1911 Gosched()
1912 mp = acquirem()
1913 }
1914 gcDebugMarkDone.restartedDueTo27993 = false
1915 releasem(mp)
1916 }
1917
1918 type BitCursor struct {
1919 b bitCursor
1920 }
1921
1922 func NewBitCursor(buf *byte) BitCursor {
1923 return BitCursor{b: bitCursor{ptr: buf, n: 0}}
1924 }
1925
1926 func (b BitCursor) Write(data *byte, cnt uintptr) {
1927 b.b.write(data, cnt)
1928 }
1929 func (b BitCursor) Offset(cnt uintptr) BitCursor {
1930 return BitCursor{b: b.b.offset(cnt)}
1931 }
1932
1933 const (
1934 BubbleAssocUnbubbled = bubbleAssocUnbubbled
1935 BubbleAssocCurrentBubble = bubbleAssocCurrentBubble
1936 BubbleAssocOtherBubble = bubbleAssocOtherBubble
1937 )
1938
1939 type TraceStackTable traceStackTable
1940
1941 func (t *TraceStackTable) Reset() {
1942 t.tab.reset()
1943 }
1944
1945 func TraceStack(gp *G, tab *TraceStackTable) {
1946 traceStack(0, gp, (*traceStackTable)(tab))
1947 }
1948
1949 var DebugDecorateMappings = &debug.decoratemappings
1950
1951 func SetVMANameSupported() bool { return setVMANameSupported() }