Source file
src/runtime/mgcmark.go
1
2
3
4
5
6
7 package runtime
8
9 import (
10 "internal/abi"
11 "internal/goarch"
12 "internal/goexperiment"
13 "internal/runtime/atomic"
14 "internal/runtime/sys"
15 "unsafe"
16 )
17
18 const (
19 fixedRootFinalizers = iota
20 fixedRootFreeGStacks
21 fixedRootCleanups
22 fixedRootCount
23
24
25
26 rootBlockBytes = 256 << 10
27
28
29
30
31
32
33
34
35 maxObletBytes = 128 << 10
36
37
38
39
40
41
42
43 drainCheckThreshold = 100000
44
45
46
47
48
49
50
51
52
53 pagesPerSpanRoot = min(512, pagesPerArena)
54 )
55
56
57
58
59
60
61 func (gp *g) internalBlocked() bool {
62 reason := gp.waitreason
63 return reason < waitReasonChanReceiveNilChan || waitReasonSyncWaitGroupWait < reason
64 }
65
66
67
68
69
70
71
72 func allGsSnapshotSortedForGC() ([]*g, int) {
73 assertWorldStoppedOrLockHeld(&allglock)
74
75
76
77 for _, gp := range allgs {
78 gp.atomicstatus.CompareAndSwap(_Gleaked, _Gwaiting)
79 }
80
81 allgsSorted := make([]*g, len(allgs))
82
83
84 var currIndex, blockedIndex = 0, len(allgsSorted) - 1
85 for _, gp := range allgs {
86
87
88 if status := readgstatus(gp); status != _Gwaiting || gp.internalBlocked() {
89 allgsSorted[currIndex] = gp
90 currIndex++
91 } else {
92 allgsSorted[blockedIndex] = gp
93 blockedIndex--
94 }
95 }
96
97
98
99
100
101
102 return allgsSorted, blockedIndex + 1
103 }
104
105
106
107
108
109 func gcPrepareMarkRoots() {
110 assertWorldStopped()
111
112
113 nBlocks := func(bytes uintptr) int {
114 return int(divRoundUp(bytes, rootBlockBytes))
115 }
116
117 work.nDataRoots = 0
118 work.nBSSRoots = 0
119
120
121 for _, datap := range activeModules() {
122 nDataRoots := nBlocks(datap.edata - datap.data)
123 if nDataRoots > work.nDataRoots {
124 work.nDataRoots = nDataRoots
125 }
126
127 nBSSRoots := nBlocks(datap.ebss - datap.bss)
128 if nBSSRoots > work.nBSSRoots {
129 work.nBSSRoots = nBSSRoots
130 }
131 }
132
133
134
135
136
137
138
139
140
141
142
143
144
145 mheap_.markArenas = mheap_.heapArenas[:len(mheap_.heapArenas):len(mheap_.heapArenas)]
146 work.nSpanRoots = len(mheap_.markArenas) * (pagesPerArena / pagesPerSpanRoot)
147
148
149
150
151
152
153
154 if work.goroutineLeak.enabled {
155
156
157 work.stackRoots, work.nMaybeRunnableStackRoots = allGsSnapshotSortedForGC()
158 } else {
159
160 work.stackRoots = allGsSnapshot()
161 work.nMaybeRunnableStackRoots = len(work.stackRoots)
162 }
163
164 work.nStackRoots = len(work.stackRoots)
165
166 work.markrootNext.Store(0)
167 work.markrootJobs.Store(uint32(fixedRootCount + work.nDataRoots + work.nBSSRoots + work.nSpanRoots + work.nMaybeRunnableStackRoots))
168
169
170 work.baseData = uint32(fixedRootCount)
171 work.baseBSS = work.baseData + uint32(work.nDataRoots)
172 work.baseSpans = work.baseBSS + uint32(work.nBSSRoots)
173 work.baseStacks = work.baseSpans + uint32(work.nSpanRoots)
174 work.baseEnd = work.baseStacks + uint32(work.nStackRoots)
175 }
176
177
178
179 func gcMarkRootCheck() {
180 if next, jobs := work.markrootNext.Load(), work.markrootJobs.Load(); next < jobs {
181 print(next, " of ", jobs, " markroot jobs done\n")
182 throw("left over markroot jobs")
183 }
184
185
186
187
188
189
190 i := 0
191 forEachGRace(func(gp *g) {
192 if i >= work.nStackRoots {
193 return
194 }
195
196 if !gp.gcscandone {
197 println("gp", gp, "goid", gp.goid,
198 "status", readgstatus(gp),
199 "gcscandone", gp.gcscandone)
200 throw("scan missed a g")
201 }
202
203 i++
204 })
205 }
206
207
208 var oneptrmask = [...]uint8{1}
209
210
211
212
213
214
215
216
217
218
219
220
221 func markroot(gcw *gcWork, i uint32, flushBgCredit bool) int64 {
222
223 var workDone int64
224 var workCounter *atomic.Int64
225 switch {
226 case work.baseData <= i && i < work.baseBSS:
227 workCounter = &gcController.globalsScanWork
228 for _, datap := range activeModules() {
229 workDone += markrootBlock(datap.data, datap.edata-datap.data, datap.gcdatamask.bytedata, gcw, int(i-work.baseData))
230 }
231
232 case work.baseBSS <= i && i < work.baseSpans:
233 workCounter = &gcController.globalsScanWork
234 for _, datap := range activeModules() {
235 workDone += markrootBlock(datap.bss, datap.ebss-datap.bss, datap.gcbssmask.bytedata, gcw, int(i-work.baseBSS))
236 }
237
238 case i == fixedRootFinalizers:
239 for fb := allfin; fb != nil; fb = fb.alllink {
240 cnt := uintptr(atomic.Load(&fb.cnt))
241 scanblock(uintptr(unsafe.Pointer(&fb.fin[0])), cnt*unsafe.Sizeof(fb.fin[0]), &finptrmask[0], gcw, nil)
242 }
243
244 case i == fixedRootFreeGStacks:
245
246
247 systemstack(markrootFreeGStacks)
248
249 case i == fixedRootCleanups:
250 for cb := (*cleanupBlock)(gcCleanups.all.Load()); cb != nil; cb = cb.alllink {
251
252
253 n := uintptr(atomic.Load(&cb.n))
254 scanblock(uintptr(unsafe.Pointer(&cb.cleanups[0])), n*unsafe.Sizeof(cleanupFn{}), &cleanupBlockPtrMask[0], gcw, nil)
255 }
256
257 case work.baseSpans <= i && i < work.baseStacks:
258
259 markrootSpans(gcw, int(i-work.baseSpans))
260
261 default:
262
263 workCounter = &gcController.stackScanWork
264 if i < work.baseStacks || work.baseEnd <= i {
265 printlock()
266 print("runtime: markroot index ", i, " not in stack roots range [", work.baseStacks, ", ", work.baseEnd, ")\n")
267 throw("markroot: bad index")
268 }
269 gp := work.stackRoots[i-work.baseStacks]
270
271
272
273 status := readgstatus(gp)
274 if (status == _Gwaiting || status == _Gsyscall) && gp.waitsince == 0 {
275 gp.waitsince = work.tstart
276 }
277
278
279
280 systemstack(func() {
281
282
283
284
285 userG := getg().m.curg
286 selfScan := gp == userG && readgstatus(userG) == _Grunning
287 if selfScan {
288 casGToWaitingForSuspendG(userG, _Grunning, waitReasonGarbageCollectionScan)
289 }
290
291
292
293
294
295
296
297
298 stopped := suspendG(gp)
299 if stopped.dead {
300 gp.gcscandone = true
301 return
302 }
303 if gp.gcscandone {
304 throw("g already scanned")
305 }
306 workDone += scanstack(gp, gcw)
307 gp.gcscandone = true
308 resumeG(stopped)
309
310 if selfScan {
311 casgstatus(userG, _Gwaiting, _Grunning)
312 }
313 })
314 }
315 if workCounter != nil && workDone != 0 {
316 workCounter.Add(workDone)
317 if flushBgCredit {
318 gcFlushBgCredit(workDone)
319 }
320 }
321 return workDone
322 }
323
324
325
326
327
328
329
330 func markrootBlock(b0, n0 uintptr, ptrmask0 *uint8, gcw *gcWork, shard int) int64 {
331 if rootBlockBytes%(8*goarch.PtrSize) != 0 {
332
333 throw("rootBlockBytes must be a multiple of 8*ptrSize")
334 }
335
336
337
338
339 off := uintptr(shard) * rootBlockBytes
340 if off >= n0 {
341 return 0
342 }
343 b := b0 + off
344 ptrmask := (*uint8)(add(unsafe.Pointer(ptrmask0), uintptr(shard)*(rootBlockBytes/(8*goarch.PtrSize))))
345 n := uintptr(rootBlockBytes)
346 if off+n > n0 {
347 n = n0 - off
348 }
349
350
351 scanblock(b, n, ptrmask, gcw, nil)
352 return int64(n)
353 }
354
355
356
357
358
359 func markrootFreeGStacks() {
360
361 lock(&sched.gFree.lock)
362 list := sched.gFree.stack
363 sched.gFree.stack = gList{}
364 unlock(&sched.gFree.lock)
365 if list.empty() {
366 return
367 }
368
369
370 var tail *g
371 for gp := list.head.ptr(); gp != nil; gp = gp.schedlink.ptr() {
372 tail = gp
373 stackfree(gp.stack)
374 gp.stack.lo = 0
375 gp.stack.hi = 0
376 if valgrindenabled {
377 valgrindDeregisterStack(gp)
378 }
379 }
380
381 q := gQueue{list.head, tail.guintptr(), list.size}
382
383
384 lock(&sched.gFree.lock)
385 sched.gFree.noStack.pushAll(q)
386 unlock(&sched.gFree.lock)
387 }
388
389
390
391
392 func markrootSpans(gcw *gcWork, shard int) {
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409 sg := mheap_.sweepgen
410
411
412 ai := mheap_.markArenas[shard/(pagesPerArena/pagesPerSpanRoot)]
413 ha := mheap_.arenas[ai.l1()][ai.l2()]
414 arenaPage := uint(uintptr(shard) * pagesPerSpanRoot % pagesPerArena)
415
416
417 specialsbits := ha.pageSpecials[arenaPage/8:]
418 specialsbits = specialsbits[:pagesPerSpanRoot/8]
419 for i := range specialsbits {
420
421 specials := atomic.Load8(&specialsbits[i])
422 if specials == 0 {
423 continue
424 }
425 for j := uint(0); j < 8; j++ {
426 if specials&(1<<j) == 0 {
427 continue
428 }
429
430
431
432
433
434
435 s := ha.spans[arenaPage+uint(i)*8+j]
436
437
438
439 if state := s.state.get(); state != mSpanInUse {
440 print("s.state = ", state, "\n")
441 throw("non in-use span found with specials bit set")
442 }
443
444 if !useCheckmark && !(s.sweepgen == sg || s.sweepgen == sg+3) {
445
446 print("sweep ", s.sweepgen, " ", sg, "\n")
447 throw("gc: unswept span")
448 }
449
450
451
452 lock(&s.speciallock)
453 for sp := s.specials; sp != nil; sp = sp.next {
454 switch sp.kind {
455 case _KindSpecialFinalizer:
456 gcScanFinalizer((*specialfinalizer)(unsafe.Pointer(sp)), s, gcw)
457 case _KindSpecialWeakHandle:
458
459 spw := (*specialWeakHandle)(unsafe.Pointer(sp))
460 scanblock(uintptr(unsafe.Pointer(&spw.handle)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
461 case _KindSpecialCleanup:
462 gcScanCleanup((*specialCleanup)(unsafe.Pointer(sp)), gcw)
463 }
464 }
465 unlock(&s.speciallock)
466 }
467 }
468 }
469
470
471 func gcScanFinalizer(spf *specialfinalizer, s *mspan, gcw *gcWork) {
472
473
474
475 p := s.base() + spf.special.offset/s.elemsize*s.elemsize
476
477
478
479
480 if !s.spanclass.noscan() {
481 scanObject(p, gcw)
482 }
483
484
485 scanblock(uintptr(unsafe.Pointer(&spf.fn)), goarch.PtrSize, &oneptrmask[0], gcw, nil)
486 }
487
488
489 func gcScanCleanup(spc *specialCleanup, gcw *gcWork) {
490
491 scanblock(uintptr(unsafe.Pointer(&spc.cleanup)), unsafe.Sizeof(cleanupFn{}), &cleanupFnPtrMask[0], gcw, nil)
492 }
493
494
495
496
497
498 func gcAssistAlloc(gp *g) {
499
500
501 if getg() == gp.m.g0 {
502 return
503 }
504 if mp := getg().m; mp.locks > 0 || mp.preemptoff != "" {
505 return
506 }
507
508 if gp := getg(); gp.bubble != nil {
509
510
511
512 bubble := gp.bubble
513 gp.bubble = nil
514 defer func() {
515 gp.bubble = bubble
516 }()
517 }
518
519
520
521
522
523
524
525
526
527
528
529
530
531 enteredMarkAssistForTracing := false
532 retry:
533 limiting := gcCPULimiter.limiting()
534 if limiting && (GOARCH == "wasm" || GOARCH == "wasm32") {
535
536
537
538 if now := nanotime(); gcCPULimiter.needUpdate(now) {
539 gcCPULimiter.update(now)
540 limiting = gcCPULimiter.limiting()
541 }
542 }
543 if limiting {
544
545
546 if enteredMarkAssistForTracing {
547 trace := traceAcquire()
548 if trace.ok() {
549 trace.GCMarkAssistDone()
550
551
552
553
554
555
556
557 gp.inMarkAssist = false
558 traceRelease(trace)
559 } else {
560
561
562
563 gp.inMarkAssist = false
564 }
565 }
566 return
567 }
568
569
570
571
572 assistWorkPerByte := gcController.assistWorkPerByte.Load()
573 assistBytesPerWork := gcController.assistBytesPerWork.Load()
574 debtBytes := -gp.gcAssistBytes
575 scanWork := int64(assistWorkPerByte * float64(debtBytes))
576 if scanWork < gcOverAssistWork {
577 scanWork = gcOverAssistWork
578 debtBytes = int64(assistBytesPerWork * float64(scanWork))
579 }
580
581
582
583
584
585
586
587 bgScanCredit := gcController.bgScanCredit.Load()
588 stolen := int64(0)
589 if bgScanCredit > 0 {
590 if bgScanCredit < scanWork {
591 stolen = bgScanCredit
592 gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(stolen))
593 } else {
594 stolen = scanWork
595 gp.gcAssistBytes += debtBytes
596 }
597 gcController.bgScanCredit.Add(-stolen)
598
599 scanWork -= stolen
600
601 if scanWork == 0 {
602
603
604 if enteredMarkAssistForTracing {
605 trace := traceAcquire()
606 if trace.ok() {
607 trace.GCMarkAssistDone()
608
609
610
611
612
613
614
615 gp.inMarkAssist = false
616 traceRelease(trace)
617 } else {
618
619
620
621 gp.inMarkAssist = false
622 }
623 }
624 return
625 }
626 }
627 if !enteredMarkAssistForTracing {
628 trace := traceAcquire()
629 if trace.ok() {
630 trace.GCMarkAssistStart()
631
632
633 gp.inMarkAssist = true
634 traceRelease(trace)
635 } else {
636 gp.inMarkAssist = true
637 }
638
639
640
641
642
643 enteredMarkAssistForTracing = true
644 }
645
646
647 systemstack(func() {
648 gcAssistAlloc1(gp, scanWork)
649
650
651 })
652
653 completed := gp.param != nil
654 gp.param = nil
655 if completed {
656 gcMarkDone()
657 }
658
659 if gp.gcAssistBytes < 0 {
660
661
662
663
664
665
666
667 if gp.preempt {
668 Gosched()
669 goto retry
670 }
671
672
673
674
675
676
677
678
679
680
681 if !gcParkAssist() {
682 goto retry
683 }
684
685
686
687 }
688 if enteredMarkAssistForTracing {
689 trace := traceAcquire()
690 if trace.ok() {
691 trace.GCMarkAssistDone()
692
693
694
695
696
697
698
699 gp.inMarkAssist = false
700 traceRelease(trace)
701 } else {
702
703
704
705 gp.inMarkAssist = false
706 }
707 }
708 }
709
710
711
712
713
714
715
716
717
718
719
720 func gcAssistAlloc1(gp *g, scanWork int64) {
721
722
723 gp.param = nil
724
725 if atomic.Load(&gcBlackenEnabled) == 0 {
726
727
728
729
730
731
732
733 gp.gcAssistBytes = 0
734 return
735 }
736
737
738
739
740
741
742
743 startTime := nanotime()
744 trackLimiterEvent := gp.m.p.ptr().limiterEvent.start(limiterEventMarkAssist, startTime)
745
746 gcBeginWork()
747
748
749 casGToWaitingForSuspendG(gp, _Grunning, waitReasonGCAssistMarking)
750
751
752
753 gcw := &getg().m.p.ptr().gcw
754 workDone := gcDrainN(gcw, scanWork)
755
756 casgstatus(gp, _Gwaiting, _Grunning)
757
758
759
760
761
762
763
764 assistBytesPerWork := gcController.assistBytesPerWork.Load()
765 gp.gcAssistBytes += 1 + int64(assistBytesPerWork*float64(workDone))
766
767
768
769 if gcEndWork() {
770
771
772
773
774 gp.param = unsafe.Pointer(gp)
775 }
776 now := nanotime()
777 duration := now - startTime
778 pp := gp.m.p.ptr()
779 pp.gcAssistTime += duration
780 if trackLimiterEvent {
781 pp.limiterEvent.stop(limiterEventMarkAssist, now)
782 }
783 if pp.gcAssistTime > gcAssistTimeSlack {
784 gcController.assistTime.Add(pp.gcAssistTime)
785 gcCPULimiter.update(now)
786 pp.gcAssistTime = 0
787 }
788 }
789
790
791
792
793 func gcWakeAllAssists() {
794 lock(&work.assistQueue.lock)
795 list := work.assistQueue.q.popList()
796 injectglist(&list)
797 unlock(&work.assistQueue.lock)
798 }
799
800
801
802
803
804 func gcParkAssist() bool {
805 lock(&work.assistQueue.lock)
806
807
808
809 if atomic.Load(&gcBlackenEnabled) == 0 {
810 unlock(&work.assistQueue.lock)
811 return true
812 }
813
814 gp := getg()
815 oldList := work.assistQueue.q
816 work.assistQueue.q.pushBack(gp)
817
818
819
820
821
822 if gcController.bgScanCredit.Load() > 0 {
823 work.assistQueue.q = oldList
824 if oldList.tail != 0 {
825 oldList.tail.ptr().schedlink.set(nil)
826 }
827 unlock(&work.assistQueue.lock)
828 return false
829 }
830
831 goparkunlock(&work.assistQueue.lock, waitReasonGCAssistWait, traceBlockGCMarkAssist, 2)
832 return true
833 }
834
835
836
837
838
839
840
841
842
843
844
845 func gcFlushBgCredit(scanWork int64) {
846 if work.assistQueue.q.empty() {
847
848
849
850
851 gcController.bgScanCredit.Add(scanWork)
852 return
853 }
854
855 assistBytesPerWork := gcController.assistBytesPerWork.Load()
856 scanBytes := int64(float64(scanWork) * assistBytesPerWork)
857
858 lock(&work.assistQueue.lock)
859 for !work.assistQueue.q.empty() && scanBytes > 0 {
860 gp := work.assistQueue.q.pop()
861
862
863 if scanBytes+gp.gcAssistBytes >= 0 {
864
865 scanBytes += gp.gcAssistBytes
866 gp.gcAssistBytes = 0
867
868
869
870
871
872
873 ready(gp, 0, false)
874 } else {
875
876 gp.gcAssistBytes += scanBytes
877 scanBytes = 0
878
879
880
881
882 work.assistQueue.q.pushBack(gp)
883 break
884 }
885 }
886
887 if scanBytes > 0 {
888
889 assistWorkPerByte := gcController.assistWorkPerByte.Load()
890 scanWork = int64(float64(scanBytes) * assistWorkPerByte)
891 gcController.bgScanCredit.Add(scanWork)
892 }
893 unlock(&work.assistQueue.lock)
894 }
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913 func scanstack(gp *g, gcw *gcWork) int64 {
914 if readgstatus(gp)&_Gscan == 0 {
915 print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "\n")
916 throw("scanstack - bad status")
917 }
918
919 switch readgstatus(gp) &^ _Gscan {
920 default:
921 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
922 throw("mark - bad status")
923 case _Gdead, _Gdeadextra:
924 return 0
925 case _Grunning:
926 print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "\n")
927 throw("scanstack: goroutine not stopped")
928 case _Grunnable, _Gsyscall, _Gwaiting, _Gleaked:
929
930 }
931
932 if gp == getg() {
933 throw("can't scan our own stack")
934 }
935
936
937
938
939 var sp uintptr
940 if gp.syscallsp != 0 {
941 sp = gp.syscallsp
942 } else {
943 sp = gp.sched.sp
944 }
945 scannedSize := gp.stack.hi - sp
946
947
948
949 p := getg().m.p.ptr()
950 p.scannedStackSize += uint64(scannedSize)
951 p.scannedStacks++
952
953 if isShrinkStackSafe(gp) {
954
955 shrinkstack(gp)
956 } else {
957
958 gp.preemptShrink = true
959 }
960
961 var state stackScanState
962 state.stack = gp.stack
963
964 if stackTraceDebug {
965 println("stack trace goroutine", gp.goid)
966 }
967
968 if debugScanConservative && gp.asyncSafePoint {
969 print("scanning async preempted goroutine ", gp.goid, " stack [", hex(gp.stack.lo), ",", hex(gp.stack.hi), ")\n")
970 }
971
972
973
974
975 if gp.sched.ctxt != nil {
976 scanblock(uintptr(unsafe.Pointer(&gp.sched.ctxt)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
977 }
978
979
980 if gp.asyncSafePoint {
981 xRegScan(gp, gcw, &state)
982 }
983
984
985 var u unwinder
986 for u.init(gp, 0); u.valid(); u.next() {
987 scanframeworker(&u.frame, &state, gcw)
988 }
989
990
991
992
993
994 for d := gp._defer; d != nil; d = d.link {
995 if d.fn != nil {
996
997
998 scanblock(uintptr(unsafe.Pointer(&d.fn)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
999 }
1000 if d.link != nil {
1001
1002
1003 scanblock(uintptr(unsafe.Pointer(&d.link)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
1004 }
1005
1006
1007
1008 if d.heap {
1009 scanblock(uintptr(unsafe.Pointer(&d)), goarch.PtrSize, &oneptrmask[0], gcw, &state)
1010 }
1011 }
1012 if gp._panic != nil {
1013
1014 state.putPtr(uintptr(unsafe.Pointer(gp._panic)), false)
1015 }
1016
1017
1018
1019
1020
1021
1022 state.buildIndex()
1023 for {
1024 p, conservative := state.getPtr()
1025 if p == 0 {
1026 break
1027 }
1028 obj := state.findObject(p)
1029 if obj == nil {
1030 continue
1031 }
1032 r := obj.r
1033 if r == nil {
1034
1035 continue
1036 }
1037 obj.setRecord(nil)
1038 if stackTraceDebug {
1039 printlock()
1040 print(" live stkobj at", hex(state.stack.lo+uintptr(obj.off)), "of size", obj.size)
1041 if conservative {
1042 print(" (conservative)")
1043 }
1044 println()
1045 printunlock()
1046 }
1047 ptrBytes, gcData := r.gcdata()
1048 b := state.stack.lo + uintptr(obj.off)
1049 if conservative {
1050 scanConservative(b, ptrBytes, gcData, gcw, &state)
1051 } else {
1052 scanblock(b, ptrBytes, gcData, gcw, &state)
1053 }
1054 }
1055
1056
1057
1058 for state.head != nil {
1059 x := state.head
1060 state.head = x.next
1061 if stackTraceDebug {
1062 for i := 0; i < x.nobj; i++ {
1063 obj := &x.obj[i]
1064 if obj.r == nil {
1065 continue
1066 }
1067 println(" dead stkobj at", hex(gp.stack.lo+uintptr(obj.off)), "of size", obj.r.size)
1068
1069 }
1070 }
1071 x.nobj = 0
1072 putempty((*workbuf)(unsafe.Pointer(x)))
1073 }
1074 if state.buf != nil || state.cbuf != nil || state.freeBuf != nil {
1075 throw("remaining pointer buffers")
1076 }
1077 return int64(scannedSize)
1078 }
1079
1080
1081
1082
1083 func scanframeworker(frame *stkframe, state *stackScanState, gcw *gcWork) {
1084 if _DebugGC > 1 && frame.continpc != 0 {
1085 print("scanframe ", funcname(frame.fn), "\n")
1086 }
1087
1088 isAsyncPreempt := frame.fn.valid() && frame.fn.funcID == abi.FuncID_asyncPreempt
1089 isDebugCall := frame.fn.valid() && frame.fn.funcID == abi.FuncID_debugCallV2
1090 if state.conservative || isAsyncPreempt || isDebugCall {
1091 if debugScanConservative {
1092 println("conservatively scanning function", funcname(frame.fn), "at PC", hex(frame.continpc))
1093 }
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103 if frame.varp != 0 {
1104 size := frame.varp - frame.sp
1105 if size > 0 {
1106 isSigPanic := frame.fn.valid() && frame.fn.funcID == abi.FuncID_sigpanic
1107 if usesLR && (isSigPanic || isAsyncPreempt || isDebugCall) {
1108
1109
1110
1111
1112
1113 size += alignUp(sys.MinFrameSize, sys.StackAlign)
1114 }
1115 scanConservative(frame.sp, size, nil, gcw, state)
1116 }
1117 }
1118
1119
1120 if n := frame.argBytes(); n != 0 {
1121
1122
1123 scanConservative(frame.argp, n, nil, gcw, state)
1124 }
1125
1126 if isAsyncPreempt || isDebugCall {
1127
1128
1129
1130
1131 state.conservative = true
1132 } else {
1133
1134
1135
1136 state.conservative = false
1137 }
1138 return
1139 }
1140
1141 locals, args, objs := frame.getStackMap(false)
1142
1143
1144 if locals.n > 0 {
1145 size := uintptr(locals.n) * goarch.PtrSize
1146 scanblock(frame.varp-size, size, locals.bytedata, gcw, state)
1147 }
1148
1149
1150 if args.n > 0 {
1151 scanblock(frame.argp, uintptr(args.n)*goarch.PtrSize, args.bytedata, gcw, state)
1152 }
1153
1154
1155 if frame.varp != 0 {
1156
1157
1158
1159 for i := range objs {
1160 obj := &objs[i]
1161 off := obj.off
1162 base := frame.varp
1163 if off >= 0 {
1164 base = frame.argp
1165 }
1166 ptr := base + uintptr(off)
1167 if ptr < frame.sp {
1168
1169 continue
1170 }
1171 if stackTraceDebug {
1172 println("stkobj at", hex(ptr), "of size", obj.size)
1173 }
1174 state.addObject(ptr, obj)
1175 }
1176 }
1177 }
1178
1179 type gcDrainFlags int
1180
1181 const (
1182 gcDrainUntilPreempt gcDrainFlags = 1 << iota
1183 gcDrainFlushBgCredit
1184 gcDrainIdle
1185 gcDrainFractional
1186 )
1187
1188
1189
1190 func gcDrainMarkWorkerIdle(gcw *gcWork) {
1191 gcDrain(gcw, gcDrainIdle|gcDrainUntilPreempt|gcDrainFlushBgCredit)
1192 }
1193
1194
1195
1196 func gcDrainMarkWorkerDedicated(gcw *gcWork, untilPreempt bool) {
1197 flags := gcDrainFlushBgCredit
1198 if untilPreempt {
1199 flags |= gcDrainUntilPreempt
1200 }
1201 gcDrain(gcw, flags)
1202 }
1203
1204
1205
1206 func gcDrainMarkWorkerFractional(gcw *gcWork) {
1207 gcDrain(gcw, gcDrainFractional|gcDrainUntilPreempt|gcDrainFlushBgCredit)
1208 }
1209
1210
1211
1212
1213
1214 func gcNextMarkRoot() (uint32, bool) {
1215 if !work.goroutineLeak.enabled {
1216
1217 job := work.markrootNext.Add(1) - 1
1218 return job, job < work.markrootJobs.Load()
1219 }
1220
1221
1222 for next, jobs := work.markrootNext.Load(), work.markrootJobs.Load(); next < jobs; next = work.markrootNext.Load() {
1223
1224 if work.markrootNext.CompareAndSwap(next, next+1) {
1225
1226 return next, true
1227 }
1228 }
1229 return 0, false
1230 }
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262 func gcDrain(gcw *gcWork, flags gcDrainFlags) {
1263 if !writeBarrier.enabled {
1264 throw("gcDrain phase incorrect")
1265 }
1266
1267
1268
1269 gp := getg().m.curg
1270 pp := gp.m.p.ptr()
1271 preemptible := flags&gcDrainUntilPreempt != 0
1272 flushBgCredit := flags&gcDrainFlushBgCredit != 0
1273 idle := flags&gcDrainIdle != 0
1274
1275 initScanWork := gcw.heapScanWork
1276
1277
1278
1279 checkWork := int64(1<<63 - 1)
1280 var check func() bool
1281 if flags&(gcDrainIdle|gcDrainFractional) != 0 {
1282 checkWork = initScanWork + drainCheckThreshold
1283 if idle {
1284 check = pollWork
1285 } else if flags&gcDrainFractional != 0 {
1286 check = pollFractionalWorkerExit
1287 }
1288 }
1289
1290 if work.markrootNext.Load() < work.markrootJobs.Load() {
1291
1292
1293 for !(gp.preempt && (preemptible || sched.gcwaiting.Load() || pp.runSafePointFn != 0)) {
1294 job, ok := gcNextMarkRoot()
1295 if !ok {
1296 break
1297 }
1298 markroot(gcw, job, flushBgCredit)
1299 if check != nil && check() {
1300 goto done
1301 }
1302
1303
1304 if goexperiment.GreenTeaGC && gcw.mayNeedWorker {
1305 gcw.mayNeedWorker = false
1306 if gcphase == _GCmark {
1307 gcController.enlistWorker()
1308 }
1309 }
1310 }
1311 }
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323 for !(gp.preempt && (preemptible || sched.gcwaiting.Load() || pp.runSafePointFn != 0)) {
1324
1325
1326
1327
1328
1329 if work.full == 0 {
1330 gcw.balance()
1331 }
1332
1333
1334 var b uintptr
1335 var s objptr
1336 if b = gcw.tryGetObjFast(); b == 0 {
1337 if s = gcw.tryGetSpanFast(); s == 0 {
1338 if b = gcw.tryGetObj(); b == 0 {
1339 if s = gcw.tryGetSpan(); s == 0 {
1340
1341
1342
1343 wbBufFlush()
1344 if b = gcw.tryGetObj(); b == 0 {
1345 if s = gcw.tryGetSpan(); s == 0 {
1346 s = gcw.tryStealSpan()
1347 }
1348 }
1349 }
1350 }
1351 }
1352 }
1353 if b != 0 {
1354 scanObject(b, gcw)
1355 } else if s != 0 {
1356 scanSpan(s, gcw)
1357 } else {
1358
1359 break
1360 }
1361
1362
1363 if goexperiment.GreenTeaGC && gcw.mayNeedWorker {
1364 gcw.mayNeedWorker = false
1365 if gcphase == _GCmark {
1366 gcController.enlistWorker()
1367 }
1368 }
1369
1370
1371
1372
1373 if gcw.heapScanWork >= gcCreditSlack {
1374 gcController.heapScanWork.Add(gcw.heapScanWork)
1375 if flushBgCredit {
1376 gcFlushBgCredit(gcw.heapScanWork - initScanWork)
1377 initScanWork = 0
1378 }
1379 checkWork -= gcw.heapScanWork
1380 gcw.heapScanWork = 0
1381
1382 if checkWork <= 0 {
1383 checkWork += drainCheckThreshold
1384 if check != nil && check() {
1385 break
1386 }
1387 }
1388 }
1389 }
1390
1391 done:
1392
1393 if gcw.heapScanWork > 0 {
1394 gcController.heapScanWork.Add(gcw.heapScanWork)
1395 if flushBgCredit {
1396 gcFlushBgCredit(gcw.heapScanWork - initScanWork)
1397 }
1398 gcw.heapScanWork = 0
1399 }
1400 }
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415 func gcDrainN(gcw *gcWork, scanWork int64) int64 {
1416 if !writeBarrier.enabled {
1417 throw("gcDrainN phase incorrect")
1418 }
1419
1420
1421
1422 workFlushed := -gcw.heapScanWork
1423
1424
1425
1426 gp := getg().m.curg
1427 for !gp.preempt && !gcCPULimiter.limiting() && workFlushed+gcw.heapScanWork < scanWork {
1428
1429 if work.full == 0 {
1430 gcw.balance()
1431 }
1432
1433
1434 var b uintptr
1435 var s objptr
1436 if b = gcw.tryGetObjFast(); b == 0 {
1437 if s = gcw.tryGetSpanFast(); s == 0 {
1438 if b = gcw.tryGetObj(); b == 0 {
1439 if s = gcw.tryGetSpan(); s == 0 {
1440
1441
1442
1443 wbBufFlush()
1444 if b = gcw.tryGetObj(); b == 0 {
1445 if s = gcw.tryGetSpan(); s == 0 {
1446
1447 if work.markrootNext.Load() < work.markrootJobs.Load() {
1448 job, ok := gcNextMarkRoot()
1449 if ok {
1450 workFlushed += markroot(gcw, job, false)
1451 continue
1452 }
1453 }
1454 s = gcw.tryStealSpan()
1455 }
1456 }
1457 }
1458 }
1459 }
1460 }
1461 if b != 0 {
1462 scanObject(b, gcw)
1463 } else if s != 0 {
1464 scanSpan(s, gcw)
1465 } else {
1466
1467 break
1468 }
1469
1470
1471 if gcw.heapScanWork >= gcCreditSlack {
1472 gcController.heapScanWork.Add(gcw.heapScanWork)
1473 workFlushed += gcw.heapScanWork
1474 gcw.heapScanWork = 0
1475 }
1476
1477
1478 if goexperiment.GreenTeaGC && gcw.mayNeedWorker {
1479 gcw.mayNeedWorker = false
1480 if gcphase == _GCmark {
1481 gcController.enlistWorker()
1482 }
1483 }
1484 }
1485
1486
1487
1488
1489
1490 return workFlushed + gcw.heapScanWork
1491 }
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502 func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork, stk *stackScanState) {
1503
1504
1505
1506 b := b0
1507 n := n0
1508
1509 for i := uintptr(0); i < n; {
1510
1511 bits := uint32(*addb(ptrmask, i/(goarch.PtrSize*8)))
1512 if bits == 0 {
1513 i += goarch.PtrSize * 8
1514 continue
1515 }
1516 for j := 0; j < 8 && i < n; j++ {
1517 if bits&1 != 0 {
1518
1519 p := *(*uintptr)(unsafe.Pointer(b + i))
1520 if p != 0 {
1521 if stk != nil && p >= stk.stack.lo && p < stk.stack.hi {
1522 stk.putPtr(p, false)
1523 } else {
1524 if !tryDeferToSpanScan(p, gcw) {
1525 if obj, span, objIndex := findObject(p, b, i); obj != 0 {
1526 greyobject(obj, b, i, span, gcw, objIndex)
1527 }
1528 }
1529 }
1530 }
1531 }
1532 bits >>= 1
1533 i += goarch.PtrSize
1534 }
1535 }
1536 }
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546 func scanConservative(b, n uintptr, ptrmask *uint8, gcw *gcWork, state *stackScanState) {
1547 if debugScanConservative {
1548 printlock()
1549 print("conservatively scanning [", hex(b), ",", hex(b+n), ")\n")
1550 hexdumpWords(b, n, func(p uintptr, m hexdumpMarker) {
1551 if ptrmask != nil {
1552 word := (p - b) / goarch.PtrSize
1553 bits := *addb(ptrmask, word/8)
1554 if (bits>>(word%8))&1 == 0 {
1555 return
1556 }
1557 }
1558
1559 val := *(*uintptr)(unsafe.Pointer(p))
1560 if state != nil && state.stack.lo <= val && val < state.stack.hi {
1561 m.start()
1562 println("ptr to stack")
1563 return
1564 }
1565
1566 span := spanOfHeap(val)
1567 if span == nil {
1568 return
1569 }
1570 idx := span.objIndex(val)
1571 if span.isFreeOrNewlyAllocated(idx) {
1572 return
1573 }
1574 m.start()
1575 println("ptr to heap")
1576 })
1577 printunlock()
1578 }
1579
1580 for i := uintptr(0); i < n; i += goarch.PtrSize {
1581 if ptrmask != nil {
1582 word := i / goarch.PtrSize
1583 bits := *addb(ptrmask, word/8)
1584 if bits == 0 {
1585
1586
1587
1588
1589
1590
1591 if i%(goarch.PtrSize*8) != 0 {
1592 throw("misaligned mask")
1593 }
1594 i += goarch.PtrSize*8 - goarch.PtrSize
1595 continue
1596 }
1597 if (bits>>(word%8))&1 == 0 {
1598 continue
1599 }
1600 }
1601
1602 val := *(*uintptr)(unsafe.Pointer(b + i))
1603
1604
1605 if state != nil && state.stack.lo <= val && val < state.stack.hi {
1606
1607
1608
1609
1610
1611
1612
1613
1614 state.putPtr(val, true)
1615 continue
1616 }
1617
1618
1619 span := spanOfHeap(val)
1620 if span == nil {
1621 continue
1622 }
1623
1624
1625
1626
1627
1628 idx := span.objIndex(val)
1629 if span.isFreeOrNewlyAllocated(idx) {
1630 continue
1631 }
1632
1633
1634 obj := span.base() + idx*span.elemsize
1635 if !tryDeferToSpanScan(obj, gcw) {
1636 greyobject(obj, b, i, span, gcw, idx)
1637 }
1638 }
1639 }
1640
1641
1642
1643
1644
1645
1646 func shade(b uintptr) {
1647 gcw := &getg().m.p.ptr().gcw
1648 if !tryDeferToSpanScan(b, gcw) {
1649 if obj, span, objIndex := findObject(b, 0, 0); obj != 0 {
1650 greyobject(obj, 0, 0, span, gcw, objIndex)
1651 }
1652 }
1653 }
1654
1655
1656
1657
1658
1659
1660
1661
1662 func greyobject(obj, base, off uintptr, span *mspan, gcw *gcWork, objIndex uintptr) {
1663
1664 if obj&(goarch.PtrSize-1) != 0 {
1665 throw("greyobject: obj not pointer-aligned")
1666 }
1667 mbits := span.markBitsForIndex(objIndex)
1668
1669 if useCheckmark {
1670 if setCheckmark(obj, base, off, mbits) {
1671
1672 return
1673 }
1674 if debug.checkfinalizers > 1 {
1675 print(" mark ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
1676 }
1677 } else {
1678 if debug.gccheckmark > 0 && span.isFree(objIndex) {
1679 print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")\n")
1680 gcDumpObject("base", base, off)
1681 gcDumpObject("obj", obj, ^uintptr(0))
1682 getg().m.traceback = 2
1683 throw("marking free object")
1684 }
1685
1686
1687 if mbits.isMarked() {
1688 return
1689 }
1690 mbits.setMarked()
1691
1692
1693 arena, pageIdx, pageMask := pageIndexOf(span.base())
1694 if arena.pageMarks[pageIdx]&pageMask == 0 {
1695 atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1696 }
1697 }
1698
1699
1700
1701 if span.spanclass.noscan() {
1702 gcw.bytesMarked += uint64(span.elemsize)
1703 return
1704 }
1705
1706
1707
1708
1709
1710 sys.Prefetch(obj)
1711
1712 if !gcw.putObjFast(obj) {
1713 gcw.putObj(obj)
1714 }
1715 }
1716
1717
1718
1719 func gcDumpObject(label string, obj, off uintptr) {
1720 s := spanOf(obj)
1721 print(label, "=", hex(obj))
1722 if s == nil {
1723 print(" s=nil\n")
1724 return
1725 }
1726 print(" s.base()=", hex(s.base()), " s.limit=", hex(s.limit), " s.spanclass=", s.spanclass, " s.elemsize=", s.elemsize, " s.state=")
1727 if state := s.state.get(); 0 <= state && int(state) < len(mSpanStateNames) {
1728 print(mSpanStateNames[state], "\n")
1729 } else {
1730 print("unknown(", state, ")\n")
1731 }
1732
1733 skipped := false
1734 size := s.elemsize
1735 if s.state.get() == mSpanManual && size == 0 {
1736
1737
1738
1739 size = off + goarch.PtrSize
1740 }
1741 for i := uintptr(0); i < size; i += goarch.PtrSize {
1742
1743
1744
1745 if !(i < 128*goarch.PtrSize || off-16*goarch.PtrSize < i && i < off+16*goarch.PtrSize) {
1746 skipped = true
1747 continue
1748 }
1749 if skipped {
1750 print(" ...\n")
1751 skipped = false
1752 }
1753 print(" *(", label, "+", i, ") = ", hex(*(*uintptr)(unsafe.Pointer(obj + i))))
1754 if i == off {
1755 print(" <==")
1756 }
1757 print("\n")
1758 }
1759 if skipped {
1760 print(" ...\n")
1761 }
1762 }
1763
1764
1765
1766
1767
1768
1769
1770
1771 func gcmarknewobject(span *mspan, obj uintptr) {
1772 if useCheckmark {
1773 throw("gcmarknewobject called while doing checkmark")
1774 }
1775 if gcphase == _GCmarktermination {
1776
1777 throw("mallocgc called with gcphase == _GCmarktermination")
1778 }
1779
1780
1781 objIndex := span.objIndex(obj)
1782 span.markBitsForIndex(objIndex).setMarked()
1783 if goexperiment.GreenTeaGC && gcUsesSpanInlineMarkBits(span.elemsize) {
1784
1785 span.scannedBitsForIndex(objIndex).setMarked()
1786 }
1787
1788
1789 arena, pageIdx, pageMask := pageIndexOf(span.base())
1790 if arena.pageMarks[pageIdx]&pageMask == 0 {
1791 atomic.Or8(&arena.pageMarks[pageIdx], pageMask)
1792 }
1793
1794 gcw := &getg().m.p.ptr().gcw
1795 gcw.bytesMarked += uint64(span.elemsize)
1796 }
1797
1798
1799
1800
1801 func gcMarkTinyAllocs() {
1802 assertWorldStopped()
1803
1804 for _, p := range allp {
1805 c := p.mcache
1806 if c == nil || c.tiny == 0 {
1807 continue
1808 }
1809 gcw := &p.gcw
1810 if !tryDeferToSpanScan(c.tiny, gcw) {
1811 _, span, objIndex := findObject(c.tiny, 0, 0)
1812 greyobject(c.tiny, 0, 0, span, gcw, objIndex)
1813 }
1814 }
1815 }
1816
View as plain text