Source file src/runtime/export_test.go

     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  // BlockOnSystemStack switches to the system stack, prints "x\n" to
   449  // stderr, and blocks in a stack containing
   450  // "runtime.blockOnSystemStackInternal".
   451  func BlockOnSystemStack() {
   452  	systemstack(blockOnSystemStackInternal)
   453  }
   454  
   455  func blockOnSystemStackInternal() {
   456  	print("x\n")
   457  	lock(&deadlock)
   458  	lock(&deadlock)
   459  }
   460  
   461  type RWMutex struct {
   462  	rw rwmutex
   463  }
   464  
   465  func (rw *RWMutex) Init() {
   466  	rw.rw.init(lockRankTestR, lockRankTestRInternal, lockRankTestW)
   467  }
   468  
   469  func (rw *RWMutex) RLock() {
   470  	rw.rw.rlock()
   471  }
   472  
   473  func (rw *RWMutex) RUnlock() {
   474  	rw.rw.runlock()
   475  }
   476  
   477  func (rw *RWMutex) Lock() {
   478  	rw.rw.lock()
   479  }
   480  
   481  func (rw *RWMutex) Unlock() {
   482  	rw.rw.unlock()
   483  }
   484  
   485  func LockOSCounts() (external, internal uint32) {
   486  	gp := getg()
   487  	if gp.m.lockedExt+gp.m.lockedInt == 0 {
   488  		if gp.lockedm != 0 {
   489  			panic("lockedm on non-locked goroutine")
   490  		}
   491  	} else {
   492  		if gp.lockedm == 0 {
   493  			panic("nil lockedm on locked goroutine")
   494  		}
   495  	}
   496  	return gp.m.lockedExt, gp.m.lockedInt
   497  }
   498  
   499  //go:noinline
   500  func TracebackSystemstack(stk []uintptr, i int) int {
   501  	if i == 0 {
   502  		pc, sp := sys.GetCallerPC(), sys.GetCallerSP()
   503  		var u unwinder
   504  		u.initAt(pc, sp, 0, getg(), unwindJumpStack) // Don't ignore errors, for testing
   505  		return tracebackPCs(&u, 0, stk)
   506  	}
   507  	n := 0
   508  	systemstack(func() {
   509  		n = TracebackSystemstack(stk, i-1)
   510  	})
   511  	return n
   512  }
   513  
   514  func KeepNArenaHints(n int) {
   515  	hint := mheap_.arenaHints
   516  	for i := 1; i < n; i++ {
   517  		hint = hint.next
   518  		if hint == nil {
   519  			return
   520  		}
   521  	}
   522  	hint.next = nil
   523  }
   524  
   525  // MapNextArenaHint reserves a page at the next arena growth hint,
   526  // preventing the arena from growing there, and returns the range of
   527  // addresses that are no longer viable.
   528  //
   529  // This may fail to reserve memory. If it fails, it still returns the
   530  // address range it attempted to reserve.
   531  func MapNextArenaHint() (start, end uintptr, ok bool) {
   532  	hint := mheap_.arenaHints
   533  	addr := hint.addr
   534  	if hint.down {
   535  		start, end = addr-heapArenaBytes, addr
   536  		addr -= physPageSize
   537  	} else {
   538  		start, end = addr, addr+heapArenaBytes
   539  	}
   540  	got := sysReserve(unsafe.Pointer(addr), physPageSize, "")
   541  	ok = (addr == uintptr(got))
   542  	if !ok {
   543  		// We were unable to get the requested reservation.
   544  		// Release what we did get and fail.
   545  		sysUnreserve(got, physPageSize)
   546  	}
   547  	return
   548  }
   549  
   550  func GetNextArenaHint() uintptr {
   551  	return mheap_.arenaHints.addr
   552  }
   553  
   554  type G = g
   555  
   556  type Sudog = sudog
   557  
   558  func Getg() *G {
   559  	return getg()
   560  }
   561  
   562  func Goid() uint64 {
   563  	return getg().goid
   564  }
   565  
   566  func GIsWaitingOnMutex(gp *G) bool {
   567  	return readgstatus(gp) == _Gwaiting && gp.waitreason.isMutexWait()
   568  }
   569  
   570  var CasGStatusAlwaysTrack = &casgstatusAlwaysTrack
   571  
   572  //go:noinline
   573  func PanicForTesting(b []byte, i int) byte {
   574  	return unexportedPanicForTesting(b, i)
   575  }
   576  
   577  //go:noinline
   578  func unexportedPanicForTesting(b []byte, i int) byte {
   579  	return b[i]
   580  }
   581  
   582  func G0StackOverflow() {
   583  	systemstack(func() {
   584  		g0 := getg()
   585  		sp := sys.GetCallerSP()
   586  		// The stack bounds for g0 stack is not always precise.
   587  		// Use an artificially small stack, to trigger a stack overflow
   588  		// without actually run out of the system stack (which may seg fault).
   589  		g0.stack.lo = sp - 4096 - stackSystem
   590  		g0.stackguard0 = g0.stack.lo + stackGuard
   591  		g0.stackguard1 = g0.stackguard0
   592  
   593  		stackOverflow(nil)
   594  	})
   595  }
   596  
   597  func stackOverflow(x *byte) {
   598  	var buf [256]byte
   599  	stackOverflow(&buf[0])
   600  }
   601  
   602  func RunGetgThreadSwitchTest() {
   603  	// Test that getg works correctly with thread switch.
   604  	// With gccgo, if we generate getg inlined, the backend
   605  	// may cache the address of the TLS variable, which
   606  	// will become invalid after a thread switch. This test
   607  	// checks that the bad caching doesn't happen.
   608  
   609  	ch := make(chan int)
   610  	go func(ch chan int) {
   611  		ch <- 5
   612  		LockOSThread()
   613  	}(ch)
   614  
   615  	g1 := getg()
   616  
   617  	// Block on a receive. This is likely to get us a thread
   618  	// switch. If we yield to the sender goroutine, it will
   619  	// lock the thread, forcing us to resume on a different
   620  	// thread.
   621  	<-ch
   622  
   623  	g2 := getg()
   624  	if g1 != g2 {
   625  		panic("g1 != g2")
   626  	}
   627  
   628  	// Also test getg after some control flow, as the
   629  	// backend is sensitive to control flow.
   630  	g3 := getg()
   631  	if g1 != g3 {
   632  		panic("g1 != g3")
   633  	}
   634  }
   635  
   636  const (
   637  	PageSize         = pageSize
   638  	PallocChunkPages = pallocChunkPages
   639  	PageAlloc64Bit   = pageAlloc64Bit
   640  	PallocSumBytes   = pallocSumBytes
   641  )
   642  
   643  // Expose pallocSum for testing.
   644  type PallocSum pallocSum
   645  
   646  func PackPallocSum(start, max, end uint) PallocSum { return PallocSum(packPallocSum(start, max, end)) }
   647  func (m PallocSum) Start() uint                    { return pallocSum(m).start() }
   648  func (m PallocSum) Max() uint                      { return pallocSum(m).max() }
   649  func (m PallocSum) End() uint                      { return pallocSum(m).end() }
   650  
   651  // Expose pallocBits for testing.
   652  type PallocBits pallocBits
   653  
   654  func (b *PallocBits) Find(npages uintptr, searchIdx uint) (uint, uint) {
   655  	return (*pallocBits)(b).find(npages, searchIdx)
   656  }
   657  func (b *PallocBits) AllocRange(i, n uint)       { (*pallocBits)(b).allocRange(i, n) }
   658  func (b *PallocBits) Free(i, n uint)             { (*pallocBits)(b).free(i, n) }
   659  func (b *PallocBits) Summarize() PallocSum       { return PallocSum((*pallocBits)(b).summarize()) }
   660  func (b *PallocBits) PopcntRange(i, n uint) uint { return (*pageBits)(b).popcntRange(i, n) }
   661  
   662  // SummarizeSlow is a slow but more obviously correct implementation
   663  // of (*pallocBits).summarize. Used for testing.
   664  func SummarizeSlow(b *PallocBits) PallocSum {
   665  	var start, most, end uint
   666  
   667  	const N = uint(len(b)) * 64
   668  	for start < N && (*pageBits)(b).get(start) == 0 {
   669  		start++
   670  	}
   671  	for end < N && (*pageBits)(b).get(N-end-1) == 0 {
   672  		end++
   673  	}
   674  	run := uint(0)
   675  	for i := uint(0); i < N; i++ {
   676  		if (*pageBits)(b).get(i) == 0 {
   677  			run++
   678  		} else {
   679  			run = 0
   680  		}
   681  		most = max(most, run)
   682  	}
   683  	return PackPallocSum(start, most, end)
   684  }
   685  
   686  // Expose non-trivial helpers for testing.
   687  func FindBitRange64(c uint64, n uint) uint { return findBitRange64(c, n) }
   688  
   689  // Given two PallocBits, returns a set of bit ranges where
   690  // they differ.
   691  func DiffPallocBits(a, b *PallocBits) []BitRange {
   692  	ba := (*pageBits)(a)
   693  	bb := (*pageBits)(b)
   694  
   695  	var d []BitRange
   696  	base, size := uint(0), uint(0)
   697  	for i := uint(0); i < uint(len(ba))*64; i++ {
   698  		if ba.get(i) != bb.get(i) {
   699  			if size == 0 {
   700  				base = i
   701  			}
   702  			size++
   703  		} else {
   704  			if size != 0 {
   705  				d = append(d, BitRange{base, size})
   706  			}
   707  			size = 0
   708  		}
   709  	}
   710  	if size != 0 {
   711  		d = append(d, BitRange{base, size})
   712  	}
   713  	return d
   714  }
   715  
   716  // StringifyPallocBits gets the bits in the bit range r from b,
   717  // and returns a string containing the bits as ASCII 0 and 1
   718  // characters.
   719  func StringifyPallocBits(b *PallocBits, r BitRange) string {
   720  	str := ""
   721  	for j := r.I; j < r.I+r.N; j++ {
   722  		if (*pageBits)(b).get(j) != 0 {
   723  			str += "1"
   724  		} else {
   725  			str += "0"
   726  		}
   727  	}
   728  	return str
   729  }
   730  
   731  // Expose pallocData for testing.
   732  type PallocData pallocData
   733  
   734  func (d *PallocData) FindScavengeCandidate(searchIdx uint, min, max uintptr) (uint, uint) {
   735  	return (*pallocData)(d).findScavengeCandidate(searchIdx, min, max)
   736  }
   737  func (d *PallocData) AllocRange(i, n uint) { (*pallocData)(d).allocRange(i, n) }
   738  func (d *PallocData) ScavengedSetRange(i, n uint) {
   739  	(*pallocData)(d).scavenged.setRange(i, n)
   740  }
   741  func (d *PallocData) PallocBits() *PallocBits {
   742  	return (*PallocBits)(&(*pallocData)(d).pallocBits)
   743  }
   744  func (d *PallocData) Scavenged() *PallocBits {
   745  	return (*PallocBits)(&(*pallocData)(d).scavenged)
   746  }
   747  
   748  // Expose fillAligned for testing.
   749  func FillAligned(x uint64, m uint) uint64 { return fillAligned(x, m) }
   750  
   751  // Expose pageCache for testing.
   752  type PageCache pageCache
   753  
   754  const PageCachePages = pageCachePages
   755  
   756  func NewPageCache(base uintptr, cache, scav uint64) PageCache {
   757  	return PageCache(pageCache{base: base, cache: cache, scav: scav})
   758  }
   759  func (c *PageCache) Empty() bool   { return (*pageCache)(c).empty() }
   760  func (c *PageCache) Base() uintptr { return (*pageCache)(c).base }
   761  func (c *PageCache) Cache() uint64 { return (*pageCache)(c).cache }
   762  func (c *PageCache) Scav() uint64  { return (*pageCache)(c).scav }
   763  func (c *PageCache) Alloc(npages uintptr) (uintptr, uintptr) {
   764  	return (*pageCache)(c).alloc(npages)
   765  }
   766  func (c *PageCache) Flush(s *PageAlloc) {
   767  	cp := (*pageCache)(c)
   768  	sp := (*pageAlloc)(s)
   769  
   770  	systemstack(func() {
   771  		// None of the tests need any higher-level locking, so we just
   772  		// take the lock internally.
   773  		lock(sp.mheapLock)
   774  		cp.flush(sp)
   775  		unlock(sp.mheapLock)
   776  	})
   777  }
   778  
   779  // Expose chunk index type.
   780  type ChunkIdx chunkIdx
   781  
   782  // Expose pageAlloc for testing. Note that because pageAlloc is
   783  // not in the heap, so is PageAlloc.
   784  type PageAlloc pageAlloc
   785  
   786  func (p *PageAlloc) Alloc(npages uintptr) (uintptr, uintptr) {
   787  	pp := (*pageAlloc)(p)
   788  
   789  	var addr, scav uintptr
   790  	systemstack(func() {
   791  		// None of the tests need any higher-level locking, so we just
   792  		// take the lock internally.
   793  		lock(pp.mheapLock)
   794  		addr, scav = pp.alloc(npages)
   795  		unlock(pp.mheapLock)
   796  	})
   797  	return addr, scav
   798  }
   799  func (p *PageAlloc) AllocToCache() PageCache {
   800  	pp := (*pageAlloc)(p)
   801  
   802  	var c PageCache
   803  	systemstack(func() {
   804  		// None of the tests need any higher-level locking, so we just
   805  		// take the lock internally.
   806  		lock(pp.mheapLock)
   807  		c = PageCache(pp.allocToCache())
   808  		unlock(pp.mheapLock)
   809  	})
   810  	return c
   811  }
   812  func (p *PageAlloc) Free(base, npages uintptr) {
   813  	pp := (*pageAlloc)(p)
   814  
   815  	systemstack(func() {
   816  		// None of the tests need any higher-level locking, so we just
   817  		// take the lock internally.
   818  		lock(pp.mheapLock)
   819  		pp.free(base, npages)
   820  		unlock(pp.mheapLock)
   821  	})
   822  }
   823  func (p *PageAlloc) Bounds() (ChunkIdx, ChunkIdx) {
   824  	return ChunkIdx((*pageAlloc)(p).start), ChunkIdx((*pageAlloc)(p).end)
   825  }
   826  func (p *PageAlloc) Scavenge(nbytes uintptr) (r uintptr) {
   827  	pp := (*pageAlloc)(p)
   828  	systemstack(func() {
   829  		r = pp.scavenge(nbytes, nil, true)
   830  	})
   831  	return
   832  }
   833  func (p *PageAlloc) InUse() []AddrRange {
   834  	ranges := make([]AddrRange, 0, len(p.inUse.ranges))
   835  	for _, r := range p.inUse.ranges {
   836  		ranges = append(ranges, AddrRange{r})
   837  	}
   838  	return ranges
   839  }
   840  
   841  // Returns nil if the PallocData's L2 is missing.
   842  func (p *PageAlloc) PallocData(i ChunkIdx) *PallocData {
   843  	ci := chunkIdx(i)
   844  	return (*PallocData)((*pageAlloc)(p).tryChunkOf(ci))
   845  }
   846  
   847  // AddrRange is a wrapper around addrRange for testing.
   848  type AddrRange struct {
   849  	addrRange
   850  }
   851  
   852  // MakeAddrRange creates a new address range.
   853  func MakeAddrRange(base, limit uintptr) AddrRange {
   854  	return AddrRange{makeAddrRange(base, limit)}
   855  }
   856  
   857  // Base returns the virtual base address of the address range.
   858  func (a AddrRange) Base() uintptr {
   859  	return a.addrRange.base.addr()
   860  }
   861  
   862  // Base returns the virtual address of the limit of the address range.
   863  func (a AddrRange) Limit() uintptr {
   864  	return a.addrRange.limit.addr()
   865  }
   866  
   867  // Equals returns true if the two address ranges are exactly equal.
   868  func (a AddrRange) Equals(b AddrRange) bool {
   869  	return a == b
   870  }
   871  
   872  // Size returns the size in bytes of the address range.
   873  func (a AddrRange) Size() uintptr {
   874  	return a.addrRange.size()
   875  }
   876  
   877  // testSysStat is the sysStat passed to test versions of various
   878  // runtime structures. We do actually have to keep track of this
   879  // because otherwise memstats.mappedReady won't actually line up
   880  // with other stats in the runtime during tests.
   881  var testSysStat = &memstats.other_sys
   882  
   883  // AddrRanges is a wrapper around addrRanges for testing.
   884  type AddrRanges struct {
   885  	addrRanges
   886  	mutable bool
   887  }
   888  
   889  // NewAddrRanges creates a new empty addrRanges.
   890  //
   891  // Note that this initializes addrRanges just like in the
   892  // runtime, so its memory is persistentalloc'd. Call this
   893  // function sparingly since the memory it allocates is
   894  // leaked.
   895  //
   896  // This AddrRanges is mutable, so we can test methods like
   897  // Add.
   898  func NewAddrRanges() AddrRanges {
   899  	r := addrRanges{}
   900  	r.init(testSysStat)
   901  	return AddrRanges{r, true}
   902  }
   903  
   904  // MakeAddrRanges creates a new addrRanges populated with
   905  // the ranges in a.
   906  //
   907  // The returned AddrRanges is immutable, so methods like
   908  // Add will fail.
   909  func MakeAddrRanges(a ...AddrRange) AddrRanges {
   910  	// Methods that manipulate the backing store of addrRanges.ranges should
   911  	// not be used on the result from this function (e.g. add) since they may
   912  	// trigger reallocation. That would normally be fine, except the new
   913  	// backing store won't come from the heap, but from persistentalloc, so
   914  	// we'll leak some memory implicitly.
   915  	ranges := make([]addrRange, 0, len(a))
   916  	total := uintptr(0)
   917  	for _, r := range a {
   918  		ranges = append(ranges, r.addrRange)
   919  		total += r.Size()
   920  	}
   921  	return AddrRanges{addrRanges{
   922  		ranges:     ranges,
   923  		totalBytes: total,
   924  		sysStat:    testSysStat,
   925  	}, false}
   926  }
   927  
   928  // Ranges returns a copy of the ranges described by the
   929  // addrRanges.
   930  func (a *AddrRanges) Ranges() []AddrRange {
   931  	result := make([]AddrRange, 0, len(a.addrRanges.ranges))
   932  	for _, r := range a.addrRanges.ranges {
   933  		result = append(result, AddrRange{r})
   934  	}
   935  	return result
   936  }
   937  
   938  // FindSucc returns the successor to base. See addrRanges.findSucc
   939  // for more details.
   940  func (a *AddrRanges) FindSucc(base uintptr) int {
   941  	return a.findSucc(base)
   942  }
   943  
   944  // Add adds a new AddrRange to the AddrRanges.
   945  //
   946  // The AddrRange must be mutable (i.e. created by NewAddrRanges),
   947  // otherwise this method will throw.
   948  func (a *AddrRanges) Add(r AddrRange) {
   949  	if !a.mutable {
   950  		throw("attempt to mutate immutable AddrRanges")
   951  	}
   952  	a.add(r.addrRange)
   953  }
   954  
   955  // TotalBytes returns the totalBytes field of the addrRanges.
   956  func (a *AddrRanges) TotalBytes() uintptr {
   957  	return a.addrRanges.totalBytes
   958  }
   959  
   960  // BitRange represents a range over a bitmap.
   961  type BitRange struct {
   962  	I, N uint // bit index and length in bits
   963  }
   964  
   965  // NewPageAlloc creates a new page allocator for testing and
   966  // initializes it with the scav and chunks maps. Each key in these maps
   967  // represents a chunk index and each value is a series of bit ranges to
   968  // set within each bitmap's chunk.
   969  //
   970  // The initialization of the pageAlloc preserves the invariant that if a
   971  // scavenged bit is set the alloc bit is necessarily unset, so some
   972  // of the bits described by scav may be cleared in the final bitmap if
   973  // ranges in chunks overlap with them.
   974  //
   975  // scav is optional, and if nil, the scavenged bitmap will be cleared
   976  // (as opposed to all 1s, which it usually is). Furthermore, every
   977  // chunk index in scav must appear in chunks; ones that do not are
   978  // ignored.
   979  func NewPageAlloc(chunks, scav map[ChunkIdx][]BitRange) *PageAlloc {
   980  	p := new(pageAlloc)
   981  
   982  	// We've got an entry, so initialize the pageAlloc.
   983  	p.init(new(mutex), testSysStat, true)
   984  	lockInit(p.mheapLock, lockRankMheap)
   985  	for i, init := range chunks {
   986  		addr := chunkBase(chunkIdx(i))
   987  
   988  		// Mark the chunk's existence in the pageAlloc.
   989  		systemstack(func() {
   990  			lock(p.mheapLock)
   991  			p.grow(addr, pallocChunkBytes)
   992  			unlock(p.mheapLock)
   993  		})
   994  
   995  		// Initialize the bitmap and update pageAlloc metadata.
   996  		ci := chunkIndex(addr)
   997  		chunk := p.chunkOf(ci)
   998  
   999  		// Clear all the scavenged bits which grow set.
  1000  		chunk.scavenged.clearRange(0, pallocChunkPages)
  1001  
  1002  		// Simulate the allocation and subsequent free of all pages in
  1003  		// the chunk for the scavenge index. This sets the state equivalent
  1004  		// with all pages within the index being free.
  1005  		p.scav.index.alloc(ci, pallocChunkPages)
  1006  		p.scav.index.free(ci, 0, pallocChunkPages)
  1007  
  1008  		// Apply scavenge state if applicable.
  1009  		if scav != nil {
  1010  			if scvg, ok := scav[i]; ok {
  1011  				for _, s := range scvg {
  1012  					// Ignore the case of s.N == 0. setRange doesn't handle
  1013  					// it and it's a no-op anyway.
  1014  					if s.N != 0 {
  1015  						chunk.scavenged.setRange(s.I, s.N)
  1016  					}
  1017  				}
  1018  			}
  1019  		}
  1020  
  1021  		// Apply alloc state.
  1022  		for _, s := range init {
  1023  			// Ignore the case of s.N == 0. allocRange doesn't handle
  1024  			// it and it's a no-op anyway.
  1025  			if s.N != 0 {
  1026  				chunk.allocRange(s.I, s.N)
  1027  
  1028  				// Make sure the scavenge index is updated.
  1029  				p.scav.index.alloc(ci, s.N)
  1030  			}
  1031  		}
  1032  
  1033  		// Update heap metadata for the allocRange calls above.
  1034  		systemstack(func() {
  1035  			lock(p.mheapLock)
  1036  			p.update(addr, pallocChunkPages, false, false)
  1037  			unlock(p.mheapLock)
  1038  		})
  1039  	}
  1040  
  1041  	return (*PageAlloc)(p)
  1042  }
  1043  
  1044  // FreePageAlloc releases hard OS resources owned by the pageAlloc. Once this
  1045  // is called the pageAlloc may no longer be used. The object itself will be
  1046  // collected by the garbage collector once it is no longer live.
  1047  func FreePageAlloc(pp *PageAlloc) {
  1048  	p := (*pageAlloc)(pp)
  1049  
  1050  	// Free all the mapped space for the summary levels.
  1051  	if pageAlloc64Bit != 0 {
  1052  		for l := 0; l < summaryLevels; l++ {
  1053  			// This isn't quite right, as some of this memory may
  1054  			// be Ready instead of Reserved. The mappedReady and
  1055  			// testSysStat adjustments below correct for the
  1056  			// difference.
  1057  			sysUnreserve(unsafe.Pointer(&p.summary[l][0]), uintptr(cap(p.summary[l]))*pallocSumBytes)
  1058  		}
  1059  	} else {
  1060  		resSize := uintptr(0)
  1061  		for _, s := range p.summary {
  1062  			resSize += uintptr(cap(s)) * pallocSumBytes
  1063  		}
  1064  		// See sysUnreserve comment above.
  1065  		sysUnreserve(unsafe.Pointer(&p.summary[0][0]), alignUp(resSize, physPageSize))
  1066  	}
  1067  
  1068  	// Subtract back out whatever we mapped for the summaries.
  1069  	// sysUsed adds to p.sysStat and memstats.mappedReady no matter what
  1070  	// (and in anger should actually be accounted for), and there's no other
  1071  	// way to figure out how much we actually mapped.
  1072  	gcController.mappedReady.Add(-int64(p.summaryMappedReady))
  1073  	testSysStat.add(-int64(p.summaryMappedReady))
  1074  
  1075  	// Free extra data structures.
  1076  	//
  1077  	// TODO(prattmic): As above, some of this may be Ready, so we should
  1078  	// manually adjust mappedReady and testSysStat?
  1079  	sysUnreserve(unsafe.Pointer(&p.scav.index.chunks[0]), uintptr(cap(p.scav.index.chunks))*unsafe.Sizeof(atomicScavChunkData{}))
  1080  
  1081  	// Free the mapped space for chunks.
  1082  	for i := range p.chunks {
  1083  		if x := p.chunks[i]; x != nil {
  1084  			p.chunks[i] = nil
  1085  			// This memory comes from sysAlloc and will always be page-aligned.
  1086  			sysFree(unsafe.Pointer(x), unsafe.Sizeof(*p.chunks[0]), testSysStat)
  1087  		}
  1088  	}
  1089  }
  1090  
  1091  // BaseChunkIdx is a convenient chunkIdx value which works on both
  1092  // 64 bit and 32 bit platforms, allowing the tests to share code
  1093  // between the two.
  1094  //
  1095  // This should not be higher than 0x100*pallocChunkBytes to support
  1096  // mips and mipsle, which only have 31-bit address spaces.
  1097  var BaseChunkIdx = func() ChunkIdx {
  1098  	var prefix uintptr
  1099  	if pageAlloc64Bit != 0 {
  1100  		prefix = 0xc000
  1101  	} else {
  1102  		prefix = 0x100
  1103  	}
  1104  	baseAddr := prefix * pallocChunkBytes
  1105  	if goos.IsAix != 0 {
  1106  		baseAddr += arenaBaseOffset
  1107  	}
  1108  	return ChunkIdx(chunkIndex(baseAddr))
  1109  }()
  1110  
  1111  // PageBase returns an address given a chunk index and a page index
  1112  // relative to that chunk.
  1113  func PageBase(c ChunkIdx, pageIdx uint) uintptr {
  1114  	return chunkBase(chunkIdx(c)) + uintptr(pageIdx)*pageSize
  1115  }
  1116  
  1117  type BitsMismatch struct {
  1118  	Base      uintptr
  1119  	Got, Want uint64
  1120  }
  1121  
  1122  func CheckScavengedBitsCleared(mismatches []BitsMismatch) (n int, ok bool) {
  1123  	ok = true
  1124  
  1125  	// Run on the system stack to avoid stack growth allocation.
  1126  	systemstack(func() {
  1127  		getg().m.mallocing++
  1128  
  1129  		// Lock so that we can safely access the bitmap.
  1130  		lock(&mheap_.lock)
  1131  	chunkLoop:
  1132  		for i := mheap_.pages.start; i < mheap_.pages.end; i++ {
  1133  			chunk := mheap_.pages.tryChunkOf(i)
  1134  			if chunk == nil {
  1135  				continue
  1136  			}
  1137  			for j := 0; j < pallocChunkPages/64; j++ {
  1138  				// Run over each 64-bit bitmap section and ensure
  1139  				// scavenged is being cleared properly on allocation.
  1140  				// If a used bit and scavenged bit are both set, that's
  1141  				// an error, and could indicate a larger problem, or
  1142  				// an accounting problem.
  1143  				want := chunk.scavenged[j] &^ chunk.pallocBits[j]
  1144  				got := chunk.scavenged[j]
  1145  				if want != got {
  1146  					ok = false
  1147  					if n >= len(mismatches) {
  1148  						break chunkLoop
  1149  					}
  1150  					mismatches[n] = BitsMismatch{
  1151  						Base: chunkBase(i) + uintptr(j)*64*pageSize,
  1152  						Got:  got,
  1153  						Want: want,
  1154  					}
  1155  					n++
  1156  				}
  1157  			}
  1158  		}
  1159  		unlock(&mheap_.lock)
  1160  
  1161  		getg().m.mallocing--
  1162  	})
  1163  	return
  1164  }
  1165  
  1166  func PageCachePagesLeaked() (leaked uintptr) {
  1167  	stw := stopTheWorld(stwForTestPageCachePagesLeaked)
  1168  
  1169  	// Walk over destroyed Ps and look for unflushed caches.
  1170  	deadp := allp[len(allp):cap(allp)]
  1171  	for _, p := range deadp {
  1172  		// Since we're going past len(allp) we may see nil Ps.
  1173  		// Just ignore them.
  1174  		if p != nil {
  1175  			leaked += uintptr(sys.OnesCount64(p.pcache.cache))
  1176  		}
  1177  	}
  1178  
  1179  	startTheWorld(stw)
  1180  	return
  1181  }
  1182  
  1183  var ProcYield = procyield
  1184  var OSYield = osyield
  1185  
  1186  type Mutex = mutex
  1187  
  1188  var Lock = lock
  1189  var Unlock = unlock
  1190  
  1191  var MutexContended = mutexContended
  1192  
  1193  func SemRootLock(addr *uint32) *mutex {
  1194  	root := semtable.rootFor(addr)
  1195  	return &root.lock
  1196  }
  1197  
  1198  var Semacquire = semacquire
  1199  var Semrelease1 = semrelease1
  1200  
  1201  func SemNwait(addr *uint32) uint32 {
  1202  	root := semtable.rootFor(addr)
  1203  	return root.nwait.Load()
  1204  }
  1205  
  1206  const SemTableSize = semTabSize
  1207  
  1208  // SemTable is a wrapper around semTable exported for testing.
  1209  type SemTable struct {
  1210  	semTable
  1211  }
  1212  
  1213  // Enqueue simulates enqueuing a waiter for a semaphore (or lock) at addr.
  1214  func (t *SemTable) Enqueue(addr *uint32) {
  1215  	s := acquireSudog()
  1216  	s.releasetime = 0
  1217  	s.acquiretime = 0
  1218  	s.ticket = 0
  1219  	t.semTable.rootFor(addr).queue(addr, s, false)
  1220  }
  1221  
  1222  // Dequeue simulates dequeuing a waiter for a semaphore (or lock) at addr.
  1223  //
  1224  // Returns true if there actually was a waiter to be dequeued.
  1225  func (t *SemTable) Dequeue(addr *uint32) bool {
  1226  	s, _, _ := t.semTable.rootFor(addr).dequeue(addr)
  1227  	if s != nil {
  1228  		releaseSudog(s)
  1229  		return true
  1230  	}
  1231  	return false
  1232  }
  1233  
  1234  // mspan wrapper for testing.
  1235  type MSpan mspan
  1236  
  1237  // Allocate an mspan for testing.
  1238  func AllocMSpan() *MSpan {
  1239  	var s *mspan
  1240  	systemstack(func() {
  1241  		lock(&mheap_.lock)
  1242  		s = (*mspan)(mheap_.spanalloc.alloc())
  1243  		s.init(0, 0)
  1244  		unlock(&mheap_.lock)
  1245  	})
  1246  	return (*MSpan)(s)
  1247  }
  1248  
  1249  // Free an allocated mspan.
  1250  func FreeMSpan(s *MSpan) {
  1251  	systemstack(func() {
  1252  		lock(&mheap_.lock)
  1253  		mheap_.spanalloc.free(unsafe.Pointer(s))
  1254  		unlock(&mheap_.lock)
  1255  	})
  1256  }
  1257  
  1258  func MSpanCountAlloc(ms *MSpan, bits []byte) int {
  1259  	s := (*mspan)(ms)
  1260  	s.nelems = uint16(len(bits) * 8)
  1261  	s.gcmarkBits = (*gcBits)(unsafe.Pointer(&bits[0]))
  1262  	result := s.countAlloc()
  1263  	s.gcmarkBits = nil
  1264  	return result
  1265  }
  1266  
  1267  type MSpanQueue mSpanQueue
  1268  
  1269  func (q *MSpanQueue) Size() int {
  1270  	return (*mSpanQueue)(q).n
  1271  }
  1272  
  1273  func (q *MSpanQueue) Push(s *MSpan) {
  1274  	(*mSpanQueue)(q).push((*mspan)(s))
  1275  }
  1276  
  1277  func (q *MSpanQueue) Pop() *MSpan {
  1278  	s := (*mSpanQueue)(q).pop()
  1279  	return (*MSpan)(s)
  1280  }
  1281  
  1282  func (q *MSpanQueue) TakeAll(p *MSpanQueue) {
  1283  	(*mSpanQueue)(q).takeAll((*mSpanQueue)(p))
  1284  }
  1285  
  1286  func (q *MSpanQueue) PopN(n int) MSpanQueue {
  1287  	p := (*mSpanQueue)(q).popN(n)
  1288  	return (MSpanQueue)(p)
  1289  }
  1290  
  1291  const (
  1292  	TimeHistSubBucketBits = timeHistSubBucketBits
  1293  	TimeHistNumSubBuckets = timeHistNumSubBuckets
  1294  	TimeHistNumBuckets    = timeHistNumBuckets
  1295  	TimeHistMinBucketBits = timeHistMinBucketBits
  1296  	TimeHistMaxBucketBits = timeHistMaxBucketBits
  1297  )
  1298  
  1299  type TimeHistogram timeHistogram
  1300  
  1301  // Count returns the counts for the given bucket, subBucket indices.
  1302  // Returns true if the bucket was valid, otherwise returns the counts
  1303  // for the overflow bucket if bucket > 0 or the underflow bucket if
  1304  // bucket < 0, and false.
  1305  func (th *TimeHistogram) Count(bucket, subBucket int) (uint64, bool) {
  1306  	t := (*timeHistogram)(th)
  1307  	if bucket < 0 {
  1308  		return t.underflow.Load(), false
  1309  	}
  1310  	i := bucket*TimeHistNumSubBuckets + subBucket
  1311  	if i >= len(t.counts) {
  1312  		return t.overflow.Load(), false
  1313  	}
  1314  	return t.counts[i].Load(), true
  1315  }
  1316  
  1317  func (th *TimeHistogram) Record(duration int64) {
  1318  	(*timeHistogram)(th).record(duration)
  1319  }
  1320  
  1321  var TimeHistogramMetricsBuckets = timeHistogramMetricsBuckets
  1322  
  1323  func SetIntArgRegs(a int) int {
  1324  	lock(&finlock)
  1325  	old := intArgRegs
  1326  	if a >= 0 {
  1327  		intArgRegs = a
  1328  	}
  1329  	unlock(&finlock)
  1330  	return old
  1331  }
  1332  
  1333  func FinalizerGAsleep() bool {
  1334  	return fingStatus.Load()&fingWait != 0
  1335  }
  1336  
  1337  // For GCTestMoveStackOnNextCall, it's important not to introduce an
  1338  // extra layer of call, since then there's a return before the "real"
  1339  // next call.
  1340  var GCTestMoveStackOnNextCall = gcTestMoveStackOnNextCall
  1341  
  1342  // For GCTestIsReachable, it's important that we do this as a call so
  1343  // escape analysis can see through it.
  1344  func GCTestIsReachable(ptrs ...unsafe.Pointer) (mask uint64) {
  1345  	return gcTestIsReachable(ptrs...)
  1346  }
  1347  
  1348  // For GCTestPointerClass, it's important that we do this as a call so
  1349  // escape analysis can see through it.
  1350  //
  1351  // This is nosplit because gcTestPointerClass is.
  1352  //
  1353  //go:nosplit
  1354  func GCTestPointerClass(p unsafe.Pointer) string {
  1355  	return gcTestPointerClass(p)
  1356  }
  1357  
  1358  const Raceenabled = raceenabled
  1359  
  1360  const (
  1361  	GCBackgroundUtilization            = gcBackgroundUtilization
  1362  	GCGoalUtilization                  = gcGoalUtilization
  1363  	DefaultHeapMinimum                 = defaultHeapMinimum
  1364  	MemoryLimitHeapGoalHeadroomPercent = memoryLimitHeapGoalHeadroomPercent
  1365  	MemoryLimitMinHeapGoalHeadroom     = memoryLimitMinHeapGoalHeadroom
  1366  )
  1367  
  1368  type GCController struct {
  1369  	gcControllerState
  1370  }
  1371  
  1372  func NewGCController(gcPercent int, memoryLimit int64) *GCController {
  1373  	// Force the controller to escape. We're going to
  1374  	// do 64-bit atomics on it, and if it gets stack-allocated
  1375  	// on a 32-bit architecture, it may get allocated unaligned
  1376  	// space.
  1377  	g := Escape(new(GCController))
  1378  	g.gcControllerState.test = true // Mark it as a test copy.
  1379  	g.init(int32(gcPercent), memoryLimit)
  1380  	return g
  1381  }
  1382  
  1383  func (c *GCController) StartCycle(stackSize, globalsSize uint64, scannableFrac float64, gomaxprocs int) {
  1384  	trigger, _ := c.trigger()
  1385  	if c.heapMarked > trigger {
  1386  		trigger = c.heapMarked
  1387  	}
  1388  	c.maxStackScan.Store(stackSize)
  1389  	c.globalsScan.Store(globalsSize)
  1390  	c.heapLive.Store(trigger)
  1391  	c.heapScan.Add(int64(float64(trigger-c.heapMarked) * scannableFrac))
  1392  	c.startCycle(0, gomaxprocs, gcTrigger{kind: gcTriggerHeap})
  1393  }
  1394  
  1395  func (c *GCController) AssistWorkPerByte() float64 {
  1396  	return c.assistWorkPerByte.Load()
  1397  }
  1398  
  1399  func (c *GCController) HeapGoal() uint64 {
  1400  	return c.heapGoal()
  1401  }
  1402  
  1403  func (c *GCController) HeapLive() uint64 {
  1404  	return c.heapLive.Load()
  1405  }
  1406  
  1407  func (c *GCController) HeapMarked() uint64 {
  1408  	return c.heapMarked
  1409  }
  1410  
  1411  func (c *GCController) Triggered() uint64 {
  1412  	return c.triggered
  1413  }
  1414  
  1415  type GCControllerReviseDelta struct {
  1416  	HeapLive        int64
  1417  	HeapScan        int64
  1418  	HeapScanWork    int64
  1419  	StackScanWork   int64
  1420  	GlobalsScanWork int64
  1421  }
  1422  
  1423  func (c *GCController) Revise(d GCControllerReviseDelta) {
  1424  	c.heapLive.Add(d.HeapLive)
  1425  	c.heapScan.Add(d.HeapScan)
  1426  	c.heapScanWork.Add(d.HeapScanWork)
  1427  	c.stackScanWork.Add(d.StackScanWork)
  1428  	c.globalsScanWork.Add(d.GlobalsScanWork)
  1429  	c.revise()
  1430  }
  1431  
  1432  func (c *GCController) EndCycle(bytesMarked uint64, assistTime, elapsed int64, gomaxprocs int) {
  1433  	c.assistTime.Store(assistTime)
  1434  	c.endCycle(elapsed, gomaxprocs, false)
  1435  	c.resetLive(bytesMarked)
  1436  	c.commit(false)
  1437  }
  1438  
  1439  func (c *GCController) AddIdleMarkWorker() bool {
  1440  	return c.addIdleMarkWorker()
  1441  }
  1442  
  1443  func (c *GCController) NeedIdleMarkWorker() bool {
  1444  	return c.needIdleMarkWorker()
  1445  }
  1446  
  1447  func (c *GCController) RemoveIdleMarkWorker() {
  1448  	c.removeIdleMarkWorker()
  1449  }
  1450  
  1451  func (c *GCController) SetMaxIdleMarkWorkers(max int32) {
  1452  	c.setMaxIdleMarkWorkers(max)
  1453  }
  1454  
  1455  var alwaysFalse bool
  1456  var escapeSink any
  1457  
  1458  func Escape[T any](x T) T {
  1459  	if alwaysFalse {
  1460  		escapeSink = x
  1461  	}
  1462  	return x
  1463  }
  1464  
  1465  // Acquirem blocks preemption.
  1466  func Acquirem() {
  1467  	acquirem()
  1468  }
  1469  
  1470  func Releasem() {
  1471  	releasem(getg().m)
  1472  }
  1473  
  1474  var Timediv = timediv
  1475  
  1476  type PIController struct {
  1477  	piController
  1478  }
  1479  
  1480  func NewPIController(kp, ti, tt, min, max float64) *PIController {
  1481  	return &PIController{piController{
  1482  		kp:  kp,
  1483  		ti:  ti,
  1484  		tt:  tt,
  1485  		min: min,
  1486  		max: max,
  1487  	}}
  1488  }
  1489  
  1490  func (c *PIController) Next(input, setpoint, period float64) (float64, bool) {
  1491  	return c.piController.next(input, setpoint, period)
  1492  }
  1493  
  1494  const (
  1495  	CapacityPerProc          = capacityPerProc
  1496  	GCCPULimiterUpdatePeriod = gcCPULimiterUpdatePeriod
  1497  )
  1498  
  1499  type GCCPULimiter struct {
  1500  	limiter gcCPULimiterState
  1501  }
  1502  
  1503  func NewGCCPULimiter(now int64, gomaxprocs int32) *GCCPULimiter {
  1504  	// Force the controller to escape. We're going to
  1505  	// do 64-bit atomics on it, and if it gets stack-allocated
  1506  	// on a 32-bit architecture, it may get allocated unaligned
  1507  	// space.
  1508  	l := Escape(new(GCCPULimiter))
  1509  	l.limiter.test = true
  1510  	l.limiter.resetCapacity(now, gomaxprocs)
  1511  	return l
  1512  }
  1513  
  1514  func (l *GCCPULimiter) Fill() uint64 {
  1515  	return l.limiter.bucket.fill
  1516  }
  1517  
  1518  func (l *GCCPULimiter) Capacity() uint64 {
  1519  	return l.limiter.bucket.capacity
  1520  }
  1521  
  1522  func (l *GCCPULimiter) Overflow() uint64 {
  1523  	return l.limiter.overflow
  1524  }
  1525  
  1526  func (l *GCCPULimiter) Limiting() bool {
  1527  	return l.limiter.limiting()
  1528  }
  1529  
  1530  func (l *GCCPULimiter) NeedUpdate(now int64) bool {
  1531  	return l.limiter.needUpdate(now)
  1532  }
  1533  
  1534  func (l *GCCPULimiter) StartGCTransition(enableGC bool, now int64) {
  1535  	l.limiter.startGCTransition(enableGC, now)
  1536  }
  1537  
  1538  func (l *GCCPULimiter) FinishGCTransition(now int64) {
  1539  	l.limiter.finishGCTransition(now)
  1540  }
  1541  
  1542  func (l *GCCPULimiter) Update(now int64) {
  1543  	l.limiter.update(now)
  1544  }
  1545  
  1546  func (l *GCCPULimiter) AddAssistTime(t int64) {
  1547  	l.limiter.addAssistTime(t)
  1548  }
  1549  
  1550  func (l *GCCPULimiter) ResetCapacity(now int64, nprocs int32) {
  1551  	l.limiter.resetCapacity(now, nprocs)
  1552  }
  1553  
  1554  const ScavengePercent = scavengePercent
  1555  
  1556  type Scavenger struct {
  1557  	Sleep      func(int64) int64
  1558  	Scavenge   func(uintptr) (uintptr, int64)
  1559  	ShouldStop func() bool
  1560  	GoMaxProcs func() int32
  1561  
  1562  	released  atomic.Uintptr
  1563  	scavenger scavengerState
  1564  	stop      chan<- struct{}
  1565  	done      <-chan struct{}
  1566  }
  1567  
  1568  func (s *Scavenger) Start() {
  1569  	if s.Sleep == nil || s.Scavenge == nil || s.ShouldStop == nil || s.GoMaxProcs == nil {
  1570  		panic("must populate all stubs")
  1571  	}
  1572  
  1573  	// Install hooks.
  1574  	s.scavenger.sleepStub = s.Sleep
  1575  	s.scavenger.scavenge = s.Scavenge
  1576  	s.scavenger.shouldStop = s.ShouldStop
  1577  	s.scavenger.gomaxprocs = s.GoMaxProcs
  1578  
  1579  	// Start up scavenger goroutine, and wait for it to be ready.
  1580  	stop := make(chan struct{})
  1581  	s.stop = stop
  1582  	done := make(chan struct{})
  1583  	s.done = done
  1584  	go func() {
  1585  		// This should match bgscavenge, loosely.
  1586  		s.scavenger.init()
  1587  		s.scavenger.park()
  1588  		for {
  1589  			select {
  1590  			case <-stop:
  1591  				close(done)
  1592  				return
  1593  			default:
  1594  			}
  1595  			released, workTime := s.scavenger.run()
  1596  			if released == 0 {
  1597  				s.scavenger.park()
  1598  				continue
  1599  			}
  1600  			s.released.Add(released)
  1601  			s.scavenger.sleep(workTime)
  1602  		}
  1603  	}()
  1604  	if !s.BlockUntilParked(1e9 /* 1 second */) {
  1605  		panic("timed out waiting for scavenger to get ready")
  1606  	}
  1607  }
  1608  
  1609  // BlockUntilParked blocks until the scavenger parks, or until
  1610  // timeout is exceeded. Returns true if the scavenger parked.
  1611  //
  1612  // Note that in testing, parked means something slightly different.
  1613  // In anger, the scavenger parks to sleep, too, but in testing,
  1614  // it only parks when it actually has no work to do.
  1615  func (s *Scavenger) BlockUntilParked(timeout int64) bool {
  1616  	// Just spin, waiting for it to park.
  1617  	//
  1618  	// The actual parking process is racy with respect to
  1619  	// wakeups, which is fine, but for testing we need something
  1620  	// a bit more robust.
  1621  	start := nanotime()
  1622  	for nanotime()-start < timeout {
  1623  		lock(&s.scavenger.lock)
  1624  		parked := s.scavenger.parked
  1625  		unlock(&s.scavenger.lock)
  1626  		if parked {
  1627  			return true
  1628  		}
  1629  		Gosched()
  1630  	}
  1631  	return false
  1632  }
  1633  
  1634  // Released returns how many bytes the scavenger released.
  1635  func (s *Scavenger) Released() uintptr {
  1636  	return s.released.Load()
  1637  }
  1638  
  1639  // Wake wakes up a parked scavenger to keep running.
  1640  func (s *Scavenger) Wake() {
  1641  	s.scavenger.wake()
  1642  }
  1643  
  1644  // Stop cleans up the scavenger's resources. The scavenger
  1645  // must be parked for this to work.
  1646  func (s *Scavenger) Stop() {
  1647  	lock(&s.scavenger.lock)
  1648  	parked := s.scavenger.parked
  1649  	unlock(&s.scavenger.lock)
  1650  	if !parked {
  1651  		panic("tried to clean up scavenger that is not parked")
  1652  	}
  1653  	close(s.stop)
  1654  	s.Wake()
  1655  	<-s.done
  1656  }
  1657  
  1658  type ScavengeIndex struct {
  1659  	i scavengeIndex
  1660  }
  1661  
  1662  func NewScavengeIndex(min, max ChunkIdx) *ScavengeIndex {
  1663  	s := new(ScavengeIndex)
  1664  	// This is a bit lazy but we easily guarantee we'll be able
  1665  	// to reference all the relevant chunks. The worst-case
  1666  	// memory usage here is 512 MiB, but tests generally use
  1667  	// small offsets from BaseChunkIdx, which results in ~100s
  1668  	// of KiB in memory use.
  1669  	//
  1670  	// This may still be worth making better, at least by sharing
  1671  	// this fairly large array across calls with a sync.Pool or
  1672  	// something. Currently, when the tests are run serially,
  1673  	// it takes around 0.5s. Not all that much, but if we have
  1674  	// a lot of tests like this it could add up.
  1675  	s.i.chunks = make([]atomicScavChunkData, max)
  1676  	s.i.min.Store(uintptr(min))
  1677  	s.i.max.Store(uintptr(max))
  1678  	s.i.minHeapIdx.Store(uintptr(min))
  1679  	s.i.test = true
  1680  	return s
  1681  }
  1682  
  1683  func (s *ScavengeIndex) Find(force bool) (ChunkIdx, uint) {
  1684  	ci, off := s.i.find(force)
  1685  	return ChunkIdx(ci), off
  1686  }
  1687  
  1688  func (s *ScavengeIndex) AllocRange(base, limit uintptr) {
  1689  	sc, ec := chunkIndex(base), chunkIndex(limit-1)
  1690  	si, ei := chunkPageIndex(base), chunkPageIndex(limit-1)
  1691  
  1692  	if sc == ec {
  1693  		// The range doesn't cross any chunk boundaries.
  1694  		s.i.alloc(sc, ei+1-si)
  1695  	} else {
  1696  		// The range crosses at least one chunk boundary.
  1697  		s.i.alloc(sc, pallocChunkPages-si)
  1698  		for c := sc + 1; c < ec; c++ {
  1699  			s.i.alloc(c, pallocChunkPages)
  1700  		}
  1701  		s.i.alloc(ec, ei+1)
  1702  	}
  1703  }
  1704  
  1705  func (s *ScavengeIndex) FreeRange(base, limit uintptr) {
  1706  	sc, ec := chunkIndex(base), chunkIndex(limit-1)
  1707  	si, ei := chunkPageIndex(base), chunkPageIndex(limit-1)
  1708  
  1709  	if sc == ec {
  1710  		// The range doesn't cross any chunk boundaries.
  1711  		s.i.free(sc, si, ei+1-si)
  1712  	} else {
  1713  		// The range crosses at least one chunk boundary.
  1714  		s.i.free(sc, si, pallocChunkPages-si)
  1715  		for c := sc + 1; c < ec; c++ {
  1716  			s.i.free(c, 0, pallocChunkPages)
  1717  		}
  1718  		s.i.free(ec, 0, ei+1)
  1719  	}
  1720  }
  1721  
  1722  func (s *ScavengeIndex) ResetSearchAddrs() {
  1723  	for _, a := range []*atomicOffAddr{&s.i.searchAddrBg, &s.i.searchAddrForce} {
  1724  		addr, marked := a.Load()
  1725  		if marked {
  1726  			a.StoreUnmark(addr, addr)
  1727  		}
  1728  		a.Clear()
  1729  	}
  1730  	s.i.freeHWM = minOffAddr
  1731  }
  1732  
  1733  func (s *ScavengeIndex) NextGen() {
  1734  	s.i.nextGen()
  1735  }
  1736  
  1737  func (s *ScavengeIndex) SetEmpty(ci ChunkIdx) {
  1738  	s.i.setEmpty(chunkIdx(ci))
  1739  }
  1740  
  1741  func CheckPackScavChunkData(gen uint32, inUse, lastInUse uint16, flags uint8) bool {
  1742  	sc0 := scavChunkData{
  1743  		gen:            gen,
  1744  		inUse:          inUse,
  1745  		lastInUse:      lastInUse,
  1746  		scavChunkFlags: scavChunkFlags(flags),
  1747  	}
  1748  	scp := sc0.pack()
  1749  	sc1 := unpackScavChunkData(scp)
  1750  	return sc0 == sc1
  1751  }
  1752  
  1753  const GTrackingPeriod = gTrackingPeriod
  1754  
  1755  var ZeroBase = unsafe.Pointer(&zerobase)
  1756  
  1757  const UserArenaChunkBytes = userArenaChunkBytes
  1758  
  1759  type UserArena struct {
  1760  	arena *userArena
  1761  }
  1762  
  1763  func NewUserArena() *UserArena {
  1764  	return &UserArena{newUserArena()}
  1765  }
  1766  
  1767  func (a *UserArena) New(out *any) {
  1768  	i := efaceOf(out)
  1769  	typ := i._type
  1770  	if typ.Kind_&abi.KindMask != abi.Pointer {
  1771  		panic("new result of non-ptr type")
  1772  	}
  1773  	typ = (*ptrtype)(unsafe.Pointer(typ)).Elem
  1774  	i.data = a.arena.new(typ)
  1775  }
  1776  
  1777  func (a *UserArena) Slice(sl any, cap int) {
  1778  	a.arena.slice(sl, cap)
  1779  }
  1780  
  1781  func (a *UserArena) Free() {
  1782  	a.arena.free()
  1783  }
  1784  
  1785  func GlobalWaitingArenaChunks() int {
  1786  	n := 0
  1787  	systemstack(func() {
  1788  		lock(&mheap_.lock)
  1789  		for s := mheap_.userArena.quarantineList.first; s != nil; s = s.next {
  1790  			n++
  1791  		}
  1792  		unlock(&mheap_.lock)
  1793  	})
  1794  	return n
  1795  }
  1796  
  1797  func UserArenaClone[T any](s T) T {
  1798  	return arena_heapify(s).(T)
  1799  }
  1800  
  1801  var AlignUp = alignUp
  1802  
  1803  func BlockUntilEmptyFinalizerQueue(timeout int64) bool {
  1804  	return blockUntilEmptyFinalizerQueue(timeout)
  1805  }
  1806  
  1807  func BlockUntilEmptyCleanupQueue(timeout int64) bool {
  1808  	return gcCleanups.blockUntilEmpty(timeout)
  1809  }
  1810  
  1811  func FrameStartLine(f *Frame) int {
  1812  	return f.startLine
  1813  }
  1814  
  1815  // PersistentAlloc allocates some memory that lives outside the Go heap.
  1816  // This memory will never be freed; use sparingly.
  1817  func PersistentAlloc(n, align uintptr) unsafe.Pointer {
  1818  	return persistentalloc(n, align, &memstats.other_sys)
  1819  }
  1820  
  1821  const TagAlign = tagAlign
  1822  
  1823  // FPCallers works like Callers and uses frame pointer unwinding to populate
  1824  // pcBuf with the return addresses of the physical frames on the stack.
  1825  func FPCallers(pcBuf []uintptr) int {
  1826  	return fpTracebackPCs(unsafe.Pointer(getfp()), pcBuf)
  1827  }
  1828  
  1829  const FramePointerEnabled = framepointer_enabled
  1830  
  1831  var (
  1832  	IsPinned      = isPinned
  1833  	GetPinCounter = pinnerGetPinCounter
  1834  )
  1835  
  1836  func SetPinnerLeakPanic(f func()) {
  1837  	pinnerLeakPanic = f
  1838  }
  1839  func GetPinnerLeakPanic() func() {
  1840  	return pinnerLeakPanic
  1841  }
  1842  
  1843  var testUintptr uintptr
  1844  
  1845  func MyGenericFunc[T any]() {
  1846  	systemstack(func() {
  1847  		testUintptr = 4
  1848  	})
  1849  }
  1850  
  1851  func UnsafePoint(pc uintptr) bool {
  1852  	fi := findfunc(pc)
  1853  	v := pcdatavalue(fi, abi.PCDATA_UnsafePoint, pc)
  1854  	switch v {
  1855  	case abi.UnsafePointUnsafe:
  1856  		return true
  1857  	case abi.UnsafePointSafe:
  1858  		return false
  1859  	case abi.UnsafePointRestart1, abi.UnsafePointRestart2, abi.UnsafePointRestartAtEntry:
  1860  		// These are all interruptible, they just encode a nonstandard
  1861  		// way of recovering when interrupted.
  1862  		return false
  1863  	default:
  1864  		var buf [20]byte
  1865  		panic("invalid unsafe point code " + string(itoa(buf[:], uint64(v))))
  1866  	}
  1867  }
  1868  
  1869  type TraceMap struct {
  1870  	traceMap
  1871  }
  1872  
  1873  func (m *TraceMap) PutString(s string) (uint64, bool) {
  1874  	return m.traceMap.put(unsafe.Pointer(unsafe.StringData(s)), uintptr(len(s)))
  1875  }
  1876  
  1877  func (m *TraceMap) Reset() {
  1878  	m.traceMap.reset()
  1879  }
  1880  
  1881  func SetSpinInGCMarkDone(spin bool) {
  1882  	gcDebugMarkDone.spinAfterRaggedBarrier.Store(spin)
  1883  }
  1884  
  1885  func GCMarkDoneRestarted() bool {
  1886  	// Only read this outside of the GC. If we're running during a GC, just report false.
  1887  	mp := acquirem()
  1888  	if gcphase != _GCoff {
  1889  		releasem(mp)
  1890  		return false
  1891  	}
  1892  	restarted := gcDebugMarkDone.restartedDueTo27993
  1893  	releasem(mp)
  1894  	return restarted
  1895  }
  1896  
  1897  func GCMarkDoneResetRestartFlag() {
  1898  	mp := acquirem()
  1899  	for gcphase != _GCoff {
  1900  		releasem(mp)
  1901  		Gosched()
  1902  		mp = acquirem()
  1903  	}
  1904  	gcDebugMarkDone.restartedDueTo27993 = false
  1905  	releasem(mp)
  1906  }
  1907  
  1908  type BitCursor struct {
  1909  	b bitCursor
  1910  }
  1911  
  1912  func NewBitCursor(buf *byte) BitCursor {
  1913  	return BitCursor{b: bitCursor{ptr: buf, n: 0}}
  1914  }
  1915  
  1916  func (b BitCursor) Write(data *byte, cnt uintptr) {
  1917  	b.b.write(data, cnt)
  1918  }
  1919  func (b BitCursor) Offset(cnt uintptr) BitCursor {
  1920  	return BitCursor{b: b.b.offset(cnt)}
  1921  }
  1922  
  1923  const (
  1924  	BubbleAssocUnbubbled     = bubbleAssocUnbubbled
  1925  	BubbleAssocCurrentBubble = bubbleAssocCurrentBubble
  1926  	BubbleAssocOtherBubble   = bubbleAssocOtherBubble
  1927  )
  1928  
  1929  type TraceStackTable traceStackTable
  1930  
  1931  func (t *TraceStackTable) Reset() {
  1932  	t.tab.reset()
  1933  }
  1934  
  1935  func TraceStack(gp *G, tab *TraceStackTable) {
  1936  	traceStack(0, gp, (*traceStackTable)(tab))
  1937  }
  1938  
  1939  var DebugDecorateMappings = &debug.decoratemappings
  1940  
  1941  func SetVMANameSupported() bool { return setVMANameSupported() }
  1942  

View as plain text