Debian Codegraph @

libgo/go/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/goarch"
11 "internal/goos"
12 "runtime/internal/atomic"
13 "runtime/internal/sys"
14 "unsafe"
15 )
16
17 //var Fadd64 = fadd64
18 //var Fsub64 = fsub64
19 //var Fmul64 = fmul64
20 //var Fdiv64 = fdiv64
21 //var F64to32 = f64to32
22 //var F32to64 = f32to64
23 //var Fcmp64 = fcmp64
24 //var Fintto64 = fintto64
25 //var F64toint = f64toint
26
27 var Entersyscall = entersyscall
28 var Exitsyscall = exitsyscall
29 var LockedOSThread = lockedOSThread
30 var Xadduintptr = atomic.Xadduintptr
31
32 var Fastlog2 = fastlog2
33
34 var Atoi = atoi
35 var Atoi32 = atoi32
36
37 var Nanotime = nanotime
38 var NetpollBreak = netpollBreak
39 var Usleep = usleep
40
41 var PhysPageSize = physPageSize
42 var PhysHugePageSize = physHugePageSize
43
44 var NetpollGenericInit = netpollGenericInit
45
46 var Memmove = memmove
47 var MemclrNoHeapPointers = memclrNoHeapPointers
48
49 var LockPartialOrder = lockPartialOrder
50
51 type LockRank lockRank
52
53 func (l LockRank) String() string {
54 return lockRank(l).String()
55 }
56
57 const PreemptMSupported = preemptMSupported
58
59 type LFNode struct {
60 Next uint64
61 Pushcnt uintptr
62 }
63
64 func LFStackPush(head *uint64, node *LFNode) {
65 (*lfstack)(head).push((*lfnode)(unsafe.Pointer(node)))
66 }
67
68 func LFStackPop(head *uint64) *LFNode {
69 return (*LFNode)(unsafe.Pointer((*lfstack)(head).pop()))
70 }
71
72 func Netpoll(delta int64) {
73 systemstack(func() {
74 netpoll(delta)
75 })
76 }
77
78 func GCMask(x any) (ret []byte) {
79 return nil
80 }
81
82 func RunSchedLocalQueueTest() {
83 _p_ := new(p)
84 gs := make([]g, len(_p_.runq))
85 for i := 0; i < len(_p_.runq); i++ {
86 if g, _ := runqget(_p_); g != nil {
87 throw("runq is not empty initially")
88 }
89 for j := 0; j < i; j++ {
90 runqput(_p_, &gs[i], false)
91 }
92 for j := 0; j < i; j++ {
93 if g, _ := runqget(_p_); g != &gs[i] {
94 print("bad element at iter ", i, "/", j, "\n")
95 throw("bad element")
96 }
97 }
98 if g, _ := runqget(_p_); g != nil {
99 throw("runq is not empty afterwards")
100 }
101 }
102 }
103
104 func RunSchedLocalQueueStealTest() {
105 p1 := new(p)
106 p2 := new(p)
107 gs := make([]g, len(p1.runq))
108 for i := 0; i < len(p1.runq); i++ {
109 for j := 0; j < i; j++ {
110 gs[j].sig = 0
111 runqput(p1, &gs[j], false)
112 }
113 gp := runqsteal(p2, p1, true)
114 s := 0
115 if gp != nil {
116 s++
117 gp.sig++
118 }
119 for {
120 gp, _ = runqget(p2)
121 if gp == nil {
122 break
123 }
124 s++
125 gp.sig++
126 }
127 for {
128 gp, _ = runqget(p1)
129 if gp == nil {
130 break
131 }
132 gp.sig++
133 }
134 for j := 0; j < i; j++ {
135 if gs[j].sig != 1 {
136 print("bad element ", j, "(", gs[j].sig, ") at iter ", i, "\n")
137 throw("bad element")
138 }
139 }
140 if s != i/2 && s != i/2+1 {
141 print("bad steal ", s, ", want ", i/2, " or ", i/2+1, ", iter ", i, "\n")
142 throw("bad steal")
143 }
144 }
145 }
146
147 func RunSchedLocalQueueEmptyTest(iters int) {
148
149 /* FIXME: gofrontend fails to compile this code because
150 p, next0, next1, and done escape to the heap, which is
151 not permitted in the runtime package.
152
153 // Test that runq is not spuriously reported as empty.
154 // Runq emptiness affects scheduling decisions and spurious emptiness
155 // can lead to underutilization (both runnable Gs and idle Ps coexist
156 // for arbitrary long time).
157 done := make(chan bool, 1)
158 p := new(p)
159 gs := make([]g, 2)
160 ready := new(uint32)
161 for i := 0; i < iters; i++ {
162 *ready = 0
163 next0 := (i & 1) == 0
164 next1 := (i & 2) == 0
165 runqput(p, &gs[0], next0)
166 go func() {
167 for atomic.Xadd(ready, 1); atomic.Load(ready) != 2; {
168 }
169 if runqempty(p) {
170 println("next:", next0, next1)
171 throw("queue is empty")
172 }
173 done <- true
174 }()
175 for atomic.Xadd(ready, 1); atomic.Load(ready) != 2; {
176 }
177 runqput(p, &gs[1], next1)
178 runqget(p)
179 <-done
180 runqget(p)
181 }
182
183 */
184 }
185
186 var (
187 StringHash = stringHash
188 BytesHash = bytesHash
189 Int32Hash = int32Hash
190 Int64Hash = int64Hash
191 MemHash = memhash
192 MemHash32 = memhash32
193 MemHash64 = memhash64
194 EfaceHash = efaceHash
195 IfaceHash = ifaceHash
196 )
197
198 var UseAeshash = &useAeshash
199
200 func MemclrBytes(b []byte) {
201 s := (*slice)(unsafe.Pointer(&b))
202 memclrNoHeapPointers(s.array, uintptr(s.len))
203 }
204
205 const HashLoad = hashLoad
206
207 // entry point for testing
208 //func GostringW(w []uint16) (s string) {
209 // s = gostringw(&w[0])
210 // return
211 //}
212
213 var Open = open
214 var Close = closefd
215 var Read = read
216 var Write = write
217
218 func Envs() []string { return envs }
219 func SetEnvs(e []string) { envs = e }
220
221 // For benchmarking.
222
223 func BenchSetType(n int, x any) {
224 e := *efaceOf(&x)
225 t := e._type
226 var size uintptr
227 var p unsafe.Pointer
228 switch t.kind & kindMask {
229 case kindPtr:
230 t = (*ptrtype)(unsafe.Pointer(t)).elem
231 size = t.size
232 p = e.data
233 case kindSlice:
234 slice := *(*struct {
235 ptr unsafe.Pointer
236 len, cap uintptr
237 })(e.data)
238 t = (*slicetype)(unsafe.Pointer(t)).elem
239 size = t.size * slice.len
240 p = slice.ptr
241 }
242 allocSize := roundupsize(size)
243 systemstack(func() {
244 for i := 0; i < n; i++ {
245 heapBitsSetType(uintptr(p), allocSize, size, t)
246 }
247 })
248 }
249
250 const PtrSize = goarch.PtrSize
251
252 var ForceGCPeriod = &forcegcperiod
253
254 // SetTracebackEnv is like runtime/debug.SetTraceback, but it raises
255 // the "environment" traceback level, so later calls to
256 // debug.SetTraceback (e.g., from testing timeouts) can't lower it.
257 func SetTracebackEnv(level string) {
258 setTraceback(level)
259 traceback_env = traceback_cache
260 }
261
262 var ReadUnaligned32 = readUnaligned32
263 var ReadUnaligned64 = readUnaligned64
264
265 func CountPagesInUse() (pagesInUse, counted uintptr) {
266 stopTheWorld("CountPagesInUse")
267
268 pagesInUse = uintptr(mheap_.pagesInUse.Load())
269
270 for _, s := range mheap_.allspans {
271 if s.state.get() == mSpanInUse {
272 counted += s.npages
273 }
274 }
275
276 startTheWorld()
277
278 return
279 }
280
281 func Fastrand() uint32 { return fastrand() }
282 func Fastrandn(n uint32) uint32 { return fastrandn(n) }
283
284 type ProfBuf profBuf
285
286 func NewProfBuf(hdrsize, bufwords, tags int) *ProfBuf {
287 return (*ProfBuf)(newProfBuf(hdrsize, bufwords, tags))
288 }
289
290 func (p *ProfBuf) Write(tag *unsafe.Pointer, now int64, hdr []uint64, stk []uintptr) {
291 (*profBuf)(p).write(tag, now, hdr, stk)
292 }
293
294 const (
295 ProfBufBlocking = profBufBlocking
296 ProfBufNonBlocking = profBufNonBlocking
297 )
298
299 func (p *ProfBuf) Read(mode profBufReadMode) ([]uint64, []unsafe.Pointer, bool) {
300 return (*profBuf)(p).read(profBufReadMode(mode))
301 }
302
303 func (p *ProfBuf) Close() {
304 (*profBuf)(p).close()
305 }
306
307 func ReadMetricsSlow(memStats *MemStats, samplesp unsafe.Pointer, len, cap int) {
308 stopTheWorld("ReadMetricsSlow")
309
310 // Initialize the metrics beforehand because this could
311 // allocate and skew the stats.
312 semacquire(&metricsSema)
313 initMetrics()
314 semrelease(&metricsSema)
315
316 systemstack(func() {
317 // Read memstats first. It's going to flush
318 // the mcaches which readMetrics does not do, so
319 // going the other way around may result in
320 // inconsistent statistics.
321 readmemstats_m(memStats)
322 })
323
324 // Read metrics off the system stack.
325 //
326 // The only part of readMetrics that could allocate
327 // and skew the stats is initMetrics.
328 readMetrics(samplesp, len, cap)
329
330 startTheWorld()
331 }
332
333 // ReadMemStatsSlow returns both the runtime-computed MemStats and
334 // MemStats accumulated by scanning the heap.
335 func ReadMemStatsSlow() (base, slow MemStats) {
336 stopTheWorld("ReadMemStatsSlow")
337
338 // Run on the system stack to avoid stack growth allocation.
339 systemstack(func() {
340 // Make sure stats don't change.
341 getg().m.mallocing++
342
343 readmemstats_m(&base)
344
345 // Initialize slow from base and zero the fields we're
346 // recomputing.
347 slow = base
348 slow.Alloc = 0
349 slow.TotalAlloc = 0
350 slow.Mallocs = 0
351 slow.Frees = 0
352 slow.HeapReleased = 0
353 var bySize [_NumSizeClasses]struct {
354 Mallocs, Frees uint64
355 }
356
357 // Add up current allocations in spans.
358 for _, s := range mheap_.allspans {
359 if s.state.get() != mSpanInUse {
360 continue
361 }
362 if sizeclass := s.spanclass.sizeclass(); sizeclass == 0 {
363 slow.Mallocs++
364 slow.Alloc += uint64(s.elemsize)
365 } else {
366 slow.Mallocs += uint64(s.allocCount)
367 slow.Alloc += uint64(s.allocCount) * uint64(s.elemsize)
368 bySize[sizeclass].Mallocs += uint64(s.allocCount)
369 }
370 }
371
372 // Add in frees by just reading the stats for those directly.
373 var m heapStatsDelta
374 memstats.heapStats.unsafeRead(&m)
375
376 // Collect per-sizeclass free stats.
377 var smallFree uint64
378 for i := 0; i < _NumSizeClasses; i++ {
379 slow.Frees += uint64(m.smallFreeCount[i])
380 bySize[i].Frees += uint64(m.smallFreeCount[i])
381 bySize[i].Mallocs += uint64(m.smallFreeCount[i])
382 smallFree += uint64(m.smallFreeCount[i]) * uint64(class_to_size[i])
383 }
384 slow.Frees += uint64(m.tinyAllocCount) + uint64(m.largeFreeCount)
385 slow.Mallocs += slow.Frees
386
387 slow.TotalAlloc = slow.Alloc + uint64(m.largeFree) + smallFree
388
389 for i := range slow.BySize {
390 slow.BySize[i].Mallocs = bySize[i].Mallocs
391 slow.BySize[i].Frees = bySize[i].Frees
392 }
393
394 for i := mheap_.pages.start; i < mheap_.pages.end; i++ {
395 chunk := mheap_.pages.tryChunkOf(i)
396 if chunk == nil {
397 continue
398 }
399 pg := chunk.scavenged.popcntRange(0, pallocChunkPages)
400 slow.HeapReleased += uint64(pg) * pageSize
401 }
402 for _, p := range allp {
403 pg := sys.OnesCount64(p.pcache.scav)
404 slow.HeapReleased += uint64(pg) * pageSize
405 }
406
407 getg().m.mallocing--
408 })
409
410 startTheWorld()
411 return
412 }
413
414 // BlockOnSystemStack switches to the system stack, prints "x\n" to
415 // stderr, and blocks in a stack containing
416 // "runtime.blockOnSystemStackInternal".
417 func BlockOnSystemStack() {
418 systemstack(blockOnSystemStackInternal)
419 }
420
421 func blockOnSystemStackInternal() {
422 print("x\n")
423 lock(&deadlock)
424 lock(&deadlock)
425 }
426
427 type RWMutex struct {
428 rw rwmutex
429 }
430
431 func (rw *RWMutex) RLock() {
432 rw.rw.rlock()
433 }
434
435 func (rw *RWMutex) RUnlock() {
436 rw.rw.runlock()
437 }
438
439 func (rw *RWMutex) Lock() {
440 rw.rw.lock()
441 }
442
443 func (rw *RWMutex) Unlock() {
444 rw.rw.unlock()
445 }
446
447 const RuntimeHmapSize = unsafe.Sizeof(hmap{})
448
449 func MapBucketsCount(m map[int]int) int {
450 h := *(**hmap)(unsafe.Pointer(&m))
451 return 1 << h.B
452 }
453
454 func MapBucketsPointerIsNil(m map[int]int) bool {
455 h := *(**hmap)(unsafe.Pointer(&m))
456 return h.buckets == nil
457 }
458
459 func LockOSCounts() (external, internal uint32) {
460 g := getg()
461 if g.m.lockedExt+g.m.lockedInt == 0 {
462 if g.lockedm != 0 {
463 panic("lockedm on non-locked goroutine")
464 }
465 } else {
466 if g.lockedm == 0 {
467 panic("nil lockedm on locked goroutine")
468 }
469 }
470 return g.m.lockedExt, g.m.lockedInt
471 }
472
473 //go:noinline
474 func TracebackSystemstack(stk []uintptr, i int) int {
475 if i == 0 {
476 return callersRaw(stk)
477 }
478 n := 0
479 systemstack(func() {
480 n = TracebackSystemstack(stk, i-1)
481 })
482 return n
483 }
484
485 func KeepNArenaHints(n int) {
486 hint := mheap_.arenaHints
487 for i := 1; i < n; i++ {
488 hint = hint.next
489 if hint == nil {
490 return
491 }
492 }
493 hint.next = nil
494 }
495
496 // MapNextArenaHint reserves a page at the next arena growth hint,
497 // preventing the arena from growing there, and returns the range of
498 // addresses that are no longer viable.
499 func MapNextArenaHint() (start, end uintptr) {
500 hint := mheap_.arenaHints
501 addr := hint.addr
502 if hint.down {
503 start, end = addr-heapArenaBytes, addr
504 addr -= physPageSize
505 } else {
506 start, end = addr, addr+heapArenaBytes
507 }
508 sysReserve(unsafe.Pointer(addr), physPageSize)
509 return
510 }
511
512 func GetNextArenaHint() uintptr {
513 return mheap_.arenaHints.addr
514 }
515
516 type G = g
517
518 type Sudog = sudog
519
520 func Getg() *G {
521 return getg()
522 }
523
524 //go:noinline
525 func PanicForTesting(b []byte, i int) byte {
526 return unexportedPanicForTesting(b, i)
527 }
528
529 //go:noinline
530 func unexportedPanicForTesting(b []byte, i int) byte {
531 return b[i]
532 }
533
534 func G0StackOverflow() {
535 systemstack(func() {
536 stackOverflow(nil)
537 })
538 }
539
540 func stackOverflow(x *byte) {
541 var buf [256]byte
542 stackOverflow(&buf[0])
543 }
544
545 func MapTombstoneCheck(m map[int]int) {
546 // Make sure emptyOne and emptyRest are distributed correctly.
547 // We should have a series of filled and emptyOne cells, followed by
548 // a series of emptyRest cells.
549 h := *(**hmap)(unsafe.Pointer(&m))
550 i := any(m)
551 t := *(**maptype)(unsafe.Pointer(&i))
552
553 for x := 0; x < 1<<h.B; x++ {
554 b0 := (*bmap)(add(h.buckets, uintptr(x)*uintptr(t.bucketsize)))
555 n := 0
556 for b := b0; b != nil; b = b.overflow(t) {
557 for i := 0; i < bucketCnt; i++ {
558 if b.tophash[i] != emptyRest {
559 n++
560 }
561 }
562 }
563 k := 0
564 for b := b0; b != nil; b = b.overflow(t) {
565 for i := 0; i < bucketCnt; i++ {
566 if k < n && b.tophash[i] == emptyRest {
567 panic("early emptyRest")
568 }
569 if k >= n && b.tophash[i] != emptyRest {
570 panic("late non-emptyRest")
571 }
572 if k == n-1 && b.tophash[i] == emptyOne {
573 panic("last non-emptyRest entry is emptyOne")
574 }
575 k++
576 }
577 }
578 }
579 }
580
581 func RunGetgThreadSwitchTest() {
582 // Test that getg works correctly with thread switch.
583 // With gccgo, if we generate getg inlined, the backend
584 // may cache the address of the TLS variable, which
585 // will become invalid after a thread switch. This test
586 // checks that the bad caching doesn't happen.
587
588 ch := make(chan int)
589 go func(ch chan int) {
590 ch <- 5
591 LockOSThread()
592 }(ch)
593
594 g1 := getg()
595
596 // Block on a receive. This is likely to get us a thread
597 // switch. If we yield to the sender goroutine, it will
598 // lock the thread, forcing us to resume on a different
599 // thread.
600 <-ch
601
602 g2 := getg()
603 if g1 != g2 {
604 panic("g1 != g2")
605 }
606
607 // Also test getg after some control flow, as the
608 // backend is sensitive to control flow.
609 g3 := getg()
610 if g1 != g3 {
611 panic("g1 != g3")
612 }
613 }
614
615 const (
616 PageSize = pageSize
617 PallocChunkPages = pallocChunkPages
618 PageAlloc64Bit = pageAlloc64Bit
619 PallocSumBytes = pallocSumBytes
620 )
621
622 // Expose pallocSum for testing.
623 type PallocSum pallocSum
624
625 func PackPallocSum(start, max, end uint) PallocSum { return PallocSum(packPallocSum(start, max, end)) }
626 func (m PallocSum) Start() uint { return pallocSum(m).start() }
627 func (m PallocSum) Max() uint { return pallocSum(m).max() }
628 func (m PallocSum) End() uint { return pallocSum(m).end() }
629
630 // Expose pallocBits for testing.
631 type PallocBits pallocBits
632
633 func (b *PallocBits) Find(npages uintptr, searchIdx uint) (uint, uint) {
634 return (*pallocBits)(b).find(npages, searchIdx)
635 }
636 func (b *PallocBits) AllocRange(i, n uint) { (*pallocBits)(b).allocRange(i, n) }
637 func (b *PallocBits) Free(i, n uint) { (*pallocBits)(b).free(i, n) }
638 func (b *PallocBits) Summarize() PallocSum { return PallocSum((*pallocBits)(b).summarize()) }
639 func (b *PallocBits) PopcntRange(i, n uint) uint { return (*pageBits)(b).popcntRange(i, n) }
640
641 // SummarizeSlow is a slow but more obviously correct implementation
642 // of (*pallocBits).summarize. Used for testing.
643 func SummarizeSlow(b *PallocBits) PallocSum {
644 var start, max, end uint
645
646 const N = uint(len(b)) * 64
647 for start < N && (*pageBits)(b).get(start) == 0 {
648 start++
649 }
650 for end < N && (*pageBits)(b).get(N-end-1) == 0 {
651 end++
652 }
653 run := uint(0)
654 for i := uint(0); i < N; i++ {
655 if (*pageBits)(b).get(i) == 0 {
656 run++
657 } else {
658 run = 0
659 }
660 if run > max {
661 max = run
662 }
663 }
664 return PackPallocSum(start, max, end)
665 }
666
667 // Expose non-trivial helpers for testing.
668 func FindBitRange64(c uint64, n uint) uint { return findBitRange64(c, n) }
669
670 // Given two PallocBits, returns a set of bit ranges where
671 // they differ.
672 func DiffPallocBits(a, b *PallocBits) []BitRange {
673 ba := (*pageBits)(a)
674 bb := (*pageBits)(b)
675
676 var d []BitRange
677 base, size := uint(0), uint(0)
678 for i := uint(0); i < uint(len(ba))*64; i++ {
679 if ba.get(i) != bb.get(i) {
680 if size == 0 {
681 base = i
682 }
683 size++
684 } else {
685 if size != 0 {
686 d = append(d, BitRange{base, size})
687 }
688 size = 0
689 }
690 }
691 if size != 0 {
692 d = append(d, BitRange{base, size})
693 }
694 return d
695 }
696
697 // StringifyPallocBits gets the bits in the bit range r from b,
698 // and returns a string containing the bits as ASCII 0 and 1
699 // characters.
700 func StringifyPallocBits(b *PallocBits, r BitRange) string {
701 str := ""
702 for j := r.I; j < r.I+r.N; j++ {
703 if (*pageBits)(b).get(j) != 0 {
704 str += "1"
705 } else {
706 str += "0"
707 }
708 }
709 return str
710 }
711
712 // Expose pallocData for testing.
713 type PallocData pallocData
714
715 func (d *PallocData) FindScavengeCandidate(searchIdx uint, min, max uintptr) (uint, uint) {
716 return (*pallocData)(d).findScavengeCandidate(searchIdx, min, max)
717 }
718 func (d *PallocData) AllocRange(i, n uint) { (*pallocData)(d).allocRange(i, n) }
719 func (d *PallocData) ScavengedSetRange(i, n uint) {
720 (*pallocData)(d).scavenged.setRange(i, n)
721 }
722 func (d *PallocData) PallocBits() *PallocBits {
723 return (*PallocBits)(&(*pallocData)(d).pallocBits)
724 }
725 func (d *PallocData) Scavenged() *PallocBits {
726 return (*PallocBits)(&(*pallocData)(d).scavenged)
727 }
728
729 // Expose fillAligned for testing.
730 func FillAligned(x uint64, m uint) uint64 { return fillAligned(x, m) }
731
732 // Expose pageCache for testing.
733 type PageCache pageCache
734
735 const PageCachePages = pageCachePages
736
737 func NewPageCache(base uintptr, cache, scav uint64) PageCache {
738 return PageCache(pageCache{base: base, cache: cache, scav: scav})
739 }
740 func (c *PageCache) Empty() bool { return (*pageCache)(c).empty() }
741 func (c *PageCache) Base() uintptr { return (*pageCache)(c).base }
742 func (c *PageCache) Cache() uint64 { return (*pageCache)(c).cache }
743 func (c *PageCache) Scav() uint64 { return (*pageCache)(c).scav }
744 func (c *PageCache) Alloc(npages uintptr) (uintptr, uintptr) {
745 return (*pageCache)(c).alloc(npages)
746 }
747 func (c *PageCache) Flush(s *PageAlloc) {
748 cp := (*pageCache)(c)
749 sp := (*pageAlloc)(s)
750
751 systemstack(func() {
752 // None of the tests need any higher-level locking, so we just
753 // take the lock internally.
754 lock(sp.mheapLock)
755 cp.flush(sp)
756 unlock(sp.mheapLock)
757 })
758 }
759
760 // Expose chunk index type.
761 type ChunkIdx chunkIdx
762
763 // Expose pageAlloc for testing. Note that because pageAlloc is
764 // not in the heap, so is PageAlloc.
765 type PageAlloc pageAlloc
766
767 func (p *PageAlloc) Alloc(npages uintptr) (uintptr, uintptr) {
768 pp := (*pageAlloc)(p)
769
770 var addr, scav uintptr
771 systemstack(func() {
772 // None of the tests need any higher-level locking, so we just
773 // take the lock internally.
774 lock(pp.mheapLock)
775 addr, scav = pp.alloc(npages)
776 unlock(pp.mheapLock)
777 })
778 return addr, scav
779 }
780 func (p *PageAlloc) AllocToCache() PageCache {
781 pp := (*pageAlloc)(p)
782
783 var c PageCache
784 systemstack(func() {
785 // None of the tests need any higher-level locking, so we just
786 // take the lock internally.
787 lock(pp.mheapLock)
788 c = PageCache(pp.allocToCache())
789 unlock(pp.mheapLock)
790 })
791 return c
792 }
793 func (p *PageAlloc) Free(base, npages uintptr) {
794 pp := (*pageAlloc)(p)
795
796 systemstack(func() {
797 // None of the tests need any higher-level locking, so we just
798 // take the lock internally.
799 lock(pp.mheapLock)
800 pp.free(base, npages, true)
801 unlock(pp.mheapLock)
802 })
803 }
804 func (p *PageAlloc) Bounds() (ChunkIdx, ChunkIdx) {
805 return ChunkIdx((*pageAlloc)(p).start), ChunkIdx((*pageAlloc)(p).end)
806 }
807 func (p *PageAlloc) Scavenge(nbytes uintptr) (r uintptr) {
808 pp := (*pageAlloc)(p)
809 systemstack(func() {
810 r = pp.scavenge(nbytes)
811 })
812 return
813 }
814 func (p *PageAlloc) InUse() []AddrRange {
815 ranges := make([]AddrRange, 0, len(p.inUse.ranges))
816 for _, r := range p.inUse.ranges {
817 ranges = append(ranges, AddrRange{r})
818 }
819 return ranges
820 }
821
822 // Returns nil if the PallocData's L2 is missing.
823 func (p *PageAlloc) PallocData(i ChunkIdx) *PallocData {
824 ci := chunkIdx(i)
825 return (*PallocData)((*pageAlloc)(p).tryChunkOf(ci))
826 }
827
828 // AddrRange is a wrapper around addrRange for testing.
829 type AddrRange struct {
830 addrRange
831 }
832
833 // MakeAddrRange creates a new address range.
834 func MakeAddrRange(base, limit uintptr) AddrRange {
835 return AddrRange{makeAddrRange(base, limit)}
836 }
837
838 // Base returns the virtual base address of the address range.
839 func (a AddrRange) Base() uintptr {
840 return a.addrRange.base.addr()
841 }
842
843 // Base returns the virtual address of the limit of the address range.
844 func (a AddrRange) Limit() uintptr {
845 return a.addrRange.limit.addr()
846 }
847
848 // Equals returns true if the two address ranges are exactly equal.
849 func (a AddrRange) Equals(b AddrRange) bool {
850 return a == b
851 }
852
853 // Size returns the size in bytes of the address range.
854 func (a AddrRange) Size() uintptr {
855 return a.addrRange.size()
856 }
857
858 // AddrRanges is a wrapper around addrRanges for testing.
859 type AddrRanges struct {
860 addrRanges
861 mutable bool
862 }
863
864 // NewAddrRanges creates a new empty addrRanges.
865 //
866 // Note that this initializes addrRanges just like in the
867 // runtime, so its memory is persistentalloc'd. Call this
868 // function sparingly since the memory it allocates is
869 // leaked.
870 //
871 // This AddrRanges is mutable, so we can test methods like
872 // Add.
873 func NewAddrRanges() AddrRanges {
874 r := addrRanges{}
875 r.init(new(sysMemStat))
876 return AddrRanges{r, true}
877 }
878
879 // MakeAddrRanges creates a new addrRanges populated with
880 // the ranges in a.
881 //
882 // The returned AddrRanges is immutable, so methods like
883 // Add will fail.
884 func MakeAddrRanges(a ...AddrRange) AddrRanges {
885 // Methods that manipulate the backing store of addrRanges.ranges should
886 // not be used on the result from this function (e.g. add) since they may
887 // trigger reallocation. That would normally be fine, except the new
888 // backing store won't come from the heap, but from persistentalloc, so
889 // we'll leak some memory implicitly.
890 ranges := make([]addrRange, 0, len(a))
891 total := uintptr(0)
892 for _, r := range a {
893 ranges = append(ranges, r.addrRange)
894 total += r.Size()
895 }
896 return AddrRanges{addrRanges{
897 ranges: ranges,
898 totalBytes: total,
899 sysStat: new(sysMemStat),
900 }, false}
901 }
902
903 // Ranges returns a copy of the ranges described by the
904 // addrRanges.
905 func (a *AddrRanges) Ranges() []AddrRange {
906 result := make([]AddrRange, 0, len(a.addrRanges.ranges))
907 for _, r := range a.addrRanges.ranges {
908 result = append(result, AddrRange{r})
909 }
910 return result
911 }
912
913 // FindSucc returns the successor to base. See addrRanges.findSucc
914 // for more details.
915 func (a *AddrRanges) FindSucc(base uintptr) int {
916 return a.findSucc(base)
917 }
918
919 // Add adds a new AddrRange to the AddrRanges.
920 //
921 // The AddrRange must be mutable (i.e. created by NewAddrRanges),
922 // otherwise this method will throw.
923 func (a *AddrRanges) Add(r AddrRange) {
924 if !a.mutable {
925 throw("attempt to mutate immutable AddrRanges")
926 }
927 a.add(r.addrRange)
928 }
929
930 // TotalBytes returns the totalBytes field of the addrRanges.
931 func (a *AddrRanges) TotalBytes() uintptr {
932 return a.addrRanges.totalBytes
933 }
934
935 // BitRange represents a range over a bitmap.
936 type BitRange struct {
937 I, N uint // bit index and length in bits
938 }
939
940 // NewPageAlloc creates a new page allocator for testing and
941 // initializes it with the scav and chunks maps. Each key in these maps
942 // represents a chunk index and each value is a series of bit ranges to
943 // set within each bitmap's chunk.
944 //
945 // The initialization of the pageAlloc preserves the invariant that if a
946 // scavenged bit is set the alloc bit is necessarily unset, so some
947 // of the bits described by scav may be cleared in the final bitmap if
948 // ranges in chunks overlap with them.
949 //
950 // scav is optional, and if nil, the scavenged bitmap will be cleared
951 // (as opposed to all 1s, which it usually is). Furthermore, every
952 // chunk index in scav must appear in chunks; ones that do not are
953 // ignored.
954 func NewPageAlloc(chunks, scav map[ChunkIdx][]BitRange) *PageAlloc {
955 p := new(pageAlloc)
956
957 // We've got an entry, so initialize the pageAlloc.
958 p.init(new(mutex), nil)
959 lockInit(p.mheapLock, lockRankMheap)
960 p.test = true
961
962 for i, init := range chunks {
963 addr := chunkBase(chunkIdx(i))
964
965 // Mark the chunk's existence in the pageAlloc.
966 systemstack(func() {
967 lock(p.mheapLock)
968 p.grow(addr, pallocChunkBytes)
969 unlock(p.mheapLock)
970 })
971
972 // Initialize the bitmap and update pageAlloc metadata.
973 chunk := p.chunkOf(chunkIndex(addr))
974
975 // Clear all the scavenged bits which grow set.
976 chunk.scavenged.clearRange(0, pallocChunkPages)
977
978 // Apply scavenge state if applicable.
979 if scav != nil {
980 if scvg, ok := scav[i]; ok {
981 for _, s := range scvg {
982 // Ignore the case of s.N == 0. setRange doesn't handle
983 // it and it's a no-op anyway.
984 if s.N != 0 {
985 chunk.scavenged.setRange(s.I, s.N)
986 }
987 }
988 }
989 }
990
991 // Apply alloc state.
992 for _, s := range init {
993 // Ignore the case of s.N == 0. allocRange doesn't handle
994 // it and it's a no-op anyway.
995 if s.N != 0 {
996 chunk.allocRange(s.I, s.N)
997 }
998 }
999
1000 // Update heap metadata for the allocRange calls above.
1001 systemstack(func() {
1002 lock(p.mheapLock)
1003 p.update(addr, pallocChunkPages, false, false)
1004 unlock(p.mheapLock)
1005 })
1006 }
1007
1008 systemstack(func() {
1009 lock(p.mheapLock)
1010 p.scavengeStartGen()
1011 unlock(p.mheapLock)
1012 })
1013
1014 return (*PageAlloc)(p)
1015 }
1016
1017 // FreePageAlloc releases hard OS resources owned by the pageAlloc. Once this
1018 // is called the pageAlloc may no longer be used. The object itself will be
1019 // collected by the garbage collector once it is no longer live.
1020 func FreePageAlloc(pp *PageAlloc) {
1021 p := (*pageAlloc)(pp)
1022
1023 // Free all the mapped space for the summary levels.
1024 if pageAlloc64Bit != 0 {
1025 for l := 0; l < summaryLevels; l++ {
1026 sysFree(unsafe.Pointer(&p.summary[l][0]), uintptr(cap(p.summary[l]))*pallocSumBytes, nil)
1027 }
1028 } else {
1029 resSize := uintptr(0)
1030 for _, s := range p.summary {
1031 resSize += uintptr(cap(s)) * pallocSumBytes
1032 }
1033 sysFree(unsafe.Pointer(&p.summary[0][0]), alignUp(resSize, physPageSize), nil)
1034 }
1035
1036 // Free the mapped space for chunks.
1037 for i := range p.chunks {
1038 if x := p.chunks[i]; x != nil {
1039 p.chunks[i] = nil
1040 // This memory comes from sysAlloc and will always be page-aligned.
1041 sysFree(unsafe.Pointer(x), unsafe.Sizeof(*p.chunks[0]), nil)
1042 }
1043 }
1044 }
1045
1046 // BaseChunkIdx is a convenient chunkIdx value which works on both
1047 // 64 bit and 32 bit platforms, allowing the tests to share code
1048 // between the two.
1049 //
1050 // This should not be higher than 0x100*pallocChunkBytes to support
1051 // mips and mipsle, which only have 31-bit address spaces.
1052 var BaseChunkIdx = func() ChunkIdx {
1053 var prefix uintptr
1054 if pageAlloc64Bit != 0 {
1055 prefix = 0xc000
1056 } else {
1057 prefix = 0x100
1058 }
1059 baseAddr := prefix * pallocChunkBytes
1060 if goos.IsAix != 0 {
1061 baseAddr += arenaBaseOffset
1062 }
1063 return ChunkIdx(chunkIndex(baseAddr))
1064 }()
1065
1066 // PageBase returns an address given a chunk index and a page index
1067 // relative to that chunk.
1068 func PageBase(c ChunkIdx, pageIdx uint) uintptr {
1069 return chunkBase(chunkIdx(c)) + uintptr(pageIdx)*pageSize
1070 }
1071
1072 type BitsMismatch struct {
1073 Base uintptr
1074 Got, Want uint64
1075 }
1076
1077 func CheckScavengedBitsCleared(mismatches []BitsMismatch) (n int, ok bool) {
1078 ok = true
1079
1080 // Run on the system stack to avoid stack growth allocation.
1081 systemstack(func() {
1082 getg().m.mallocing++
1083
1084 // Lock so that we can safely access the bitmap.
1085 lock(&mheap_.lock)
1086 chunkLoop:
1087 for i := mheap_.pages.start; i < mheap_.pages.end; i++ {
1088 chunk := mheap_.pages.tryChunkOf(i)
1089 if chunk == nil {
1090 continue
1091 }
1092 for j := 0; j < pallocChunkPages/64; j++ {
1093 // Run over each 64-bit bitmap section and ensure
1094 // scavenged is being cleared properly on allocation.
1095 // If a used bit and scavenged bit are both set, that's
1096 // an error, and could indicate a larger problem, or
1097 // an accounting problem.
1098 want := chunk.scavenged[j] &^ chunk.pallocBits[j]
1099 got := chunk.scavenged[j]
1100 if want != got {
1101 ok = false
1102 if n >= len(mismatches) {
1103 break chunkLoop
1104 }
1105 mismatches[n] = BitsMismatch{
1106 Base: chunkBase(i) + uintptr(j)*64*pageSize,
1107 Got: got,
1108 Want: want,
1109 }
1110 n++
1111 }
1112 }
1113 }
1114 unlock(&mheap_.lock)
1115
1116 getg().m.mallocing--
1117 })
1118 return
1119 }
1120
1121 func PageCachePagesLeaked() (leaked uintptr) {
1122 stopTheWorld("PageCachePagesLeaked")
1123
1124 // Walk over destroyed Ps and look for unflushed caches.
1125 deadp := allp[len(allp):cap(allp)]
1126 for _, p := range deadp {
1127 // Since we're going past len(allp) we may see nil Ps.
1128 // Just ignore them.
1129 if p != nil {
1130 leaked += uintptr(sys.OnesCount64(p.pcache.cache))
1131 }
1132 }
1133
1134 startTheWorld()
1135 return
1136 }
1137
1138 var Semacquire = semacquire
1139 var Semrelease1 = semrelease1
1140
1141 func SemNwait(addr *uint32) uint32 {
1142 root := semroot(addr)
1143 return atomic.Load(&root.nwait)
1144 }
1145
1146 // mspan wrapper for testing.
1147 //go:notinheap
1148 type MSpan mspan
1149
1150 // Allocate an mspan for testing.
1151 func AllocMSpan() *MSpan {
1152 var s *mspan
1153 systemstack(func() {
1154 lock(&mheap_.lock)
1155 s = (*mspan)(mheap_.spanalloc.alloc())
1156 unlock(&mheap_.lock)
1157 })
1158 return (*MSpan)(s)
1159 }
1160
1161 // Free an allocated mspan.
1162 func FreeMSpan(s *MSpan) {
1163 systemstack(func() {
1164 lock(&mheap_.lock)
1165 mheap_.spanalloc.free(unsafe.Pointer(s))
1166 unlock(&mheap_.lock)
1167 })
1168 }
1169
1170 func MSpanCountAlloc(ms *MSpan, bits []byte) int {
1171 s := (*mspan)(ms)
1172 s.nelems = uintptr(len(bits) * 8)
1173 s.gcmarkBits = (*gcBits)(unsafe.Pointer(&bits[0]))
1174 result := s.countAlloc()
1175 s.gcmarkBits = nil
1176 return result
1177 }
1178
1179 const (
1180 TimeHistSubBucketBits = timeHistSubBucketBits
1181 TimeHistNumSubBuckets = timeHistNumSubBuckets
1182 TimeHistNumSuperBuckets = timeHistNumSuperBuckets
1183 )
1184
1185 type TimeHistogram timeHistogram
1186
1187 // Counts returns the counts for the given bucket, subBucket indices.
1188 // Returns true if the bucket was valid, otherwise returns the counts
1189 // for the underflow bucket and false.
1190 func (th *TimeHistogram) Count(bucket, subBucket uint) (uint64, bool) {
1191 t := (*timeHistogram)(th)
1192 i := bucket*TimeHistNumSubBuckets + subBucket
1193 if i >= uint(len(t.counts)) {
1194 return t.underflow, false
1195 }
1196 return t.counts[i], true
1197 }
1198
1199 func (th *TimeHistogram) Record(duration int64) {
1200 (*timeHistogram)(th).record(duration)
1201 }
1202
1203 var Pusestackmaps = &usestackmaps
1204
1205 var TimeHistogramMetricsBuckets = timeHistogramMetricsBuckets
1206
1207 func FinalizerGAsleep() bool {
1208 lock(&finlock)
1209 result := fingwait
1210 unlock(&finlock)
1211 return result
1212 }
1213
1214 // For GCTestIsReachable, it's important that we do this as a call so
1215 // escape analysis can see through it.
1216 func GCTestIsReachable(ptrs ...unsafe.Pointer) (mask uint64) {
1217 return gcTestIsReachable(ptrs...)
1218 }
1219
1220 // For GCTestPointerClass, it's important that we do this as a call so
1221 // escape analysis can see through it.
1222 //
1223 // This is nosplit because gcTestPointerClass is.
1224 //
1225 //go:nosplit
1226 func GCTestPointerClass(p unsafe.Pointer) string {
1227 return gcTestPointerClass(p)
1228 }
1229
1230 const Raceenabled = raceenabled
1231
1232 const (
1233 GCBackgroundUtilization = gcBackgroundUtilization
1234 GCGoalUtilization = gcGoalUtilization
1235 )
1236
1237 type GCController struct {
1238 gcControllerState
1239 }
1240
1241 func NewGCController(gcPercent int) *GCController {
1242 // Force the controller to escape. We're going to
1243 // do 64-bit atomics on it, and if it gets stack-allocated
1244 // on a 32-bit architecture, it may get allocated unaligned
1245 // space.
1246 g := escape(new(GCController)).(*GCController)
1247 g.gcControllerState.test = true // Mark it as a test copy.
1248 g.init(int32(gcPercent))
1249 return g
1250 }
1251
1252 func (c *GCController) StartCycle(stackSize, globalsSize uint64, scannableFrac float64, gomaxprocs int) {
1253 c.scannableStackSize = stackSize
1254 c.globalsScan = globalsSize
1255 c.heapLive = c.trigger
1256 c.heapScan += uint64(float64(c.trigger-c.heapMarked) * scannableFrac)
1257 c.startCycle(0, gomaxprocs)
1258 }
1259
1260 func (c *GCController) AssistWorkPerByte() float64 {
1261 return c.assistWorkPerByte.Load()
1262 }
1263
1264 func (c *GCController) HeapGoal() uint64 {
1265 return c.heapGoal
1266 }
1267
1268 func (c *GCController) HeapLive() uint64 {
1269 return c.heapLive
1270 }
1271
1272 func (c *GCController) HeapMarked() uint64 {
1273 return c.heapMarked
1274 }
1275
1276 func (c *GCController) Trigger() uint64 {
1277 return c.trigger
1278 }
1279
1280 type GCControllerReviseDelta struct {
1281 HeapLive int64
1282 HeapScan int64
1283 HeapScanWork int64
1284 StackScanWork int64
1285 GlobalsScanWork int64
1286 }
1287
1288 func (c *GCController) Revise(d GCControllerReviseDelta) {
1289 c.heapLive += uint64(d.HeapLive)
1290 c.heapScan += uint64(d.HeapScan)
1291 c.heapScanWork.Add(d.HeapScanWork)
1292 c.stackScanWork.Add(d.StackScanWork)
1293 c.globalsScanWork.Add(d.GlobalsScanWork)
1294 c.revise()
1295 }
1296
1297 func (c *GCController) EndCycle(bytesMarked uint64, assistTime, elapsed int64, gomaxprocs int) {
1298 c.assistTime = assistTime
1299 triggerRatio := c.endCycle(elapsed, gomaxprocs, false)
1300 c.resetLive(bytesMarked)
1301 c.commit(triggerRatio)
1302 }
1303
1304 var escapeSink any
1305
1306 //go:noinline
1307 func escape(x any) any {
1308 escapeSink = x
1309 escapeSink = nil
1310 return x
1311 }
1312
1313 // Acquirem blocks preemption.
1314 func Acquirem() {
1315 acquirem()
1316 }
1317
1318 func Releasem() {
1319 releasem(getg().m)
1320 }
1321
1322 var Timediv = timediv
1323
1324 type PIController struct {
1325 piController
1326 }
1327
1328 func NewPIController(kp, ti, tt, min, max float64) *PIController {
1329 return &PIController{piController{
1330 kp: kp,
1331 ti: ti,
1332 tt: tt,
1333 min: min,
1334 max: max,
1335 }}
1336 }
1337
1338 func (c *PIController) Next(input, setpoint, period float64) (float64, bool) {
1339 return c.piController.next(input, setpoint, period)
1340 }