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