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