]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgc.go
runtime: refactor runtime->tracer API to appear more like a lock
[gostls13.git] / src / runtime / mgc.go
1 // Copyright 2009 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 // Garbage collector (GC).
6 //
7 // The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple
8 // GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is
9 // non-generational and non-compacting. Allocation is done using size segregated per P allocation
10 // areas to minimize fragmentation while eliminating locks in the common case.
11 //
12 // The algorithm decomposes into several steps.
13 // This is a high level description of the algorithm being used. For an overview of GC a good
14 // place to start is Richard Jones' gchandbook.org.
15 //
16 // The algorithm's intellectual heritage includes Dijkstra's on-the-fly algorithm, see
17 // Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, and E. F. M. Steffens. 1978.
18 // On-the-fly garbage collection: an exercise in cooperation. Commun. ACM 21, 11 (November 1978),
19 // 966-975.
20 // For journal quality proofs that these steps are complete, correct, and terminate see
21 // Hudson, R., and Moss, J.E.B. Copying Garbage Collection without stopping the world.
22 // Concurrency and Computation: Practice and Experience 15(3-5), 2003.
23 //
24 // 1. GC performs sweep termination.
25 //
26 //    a. Stop the world. This causes all Ps to reach a GC safe-point.
27 //
28 //    b. Sweep any unswept spans. There will only be unswept spans if
29 //    this GC cycle was forced before the expected time.
30 //
31 // 2. GC performs the mark phase.
32 //
33 //    a. Prepare for the mark phase by setting gcphase to _GCmark
34 //    (from _GCoff), enabling the write barrier, enabling mutator
35 //    assists, and enqueueing root mark jobs. No objects may be
36 //    scanned until all Ps have enabled the write barrier, which is
37 //    accomplished using STW.
38 //
39 //    b. Start the world. From this point, GC work is done by mark
40 //    workers started by the scheduler and by assists performed as
41 //    part of allocation. The write barrier shades both the
42 //    overwritten pointer and the new pointer value for any pointer
43 //    writes (see mbarrier.go for details). Newly allocated objects
44 //    are immediately marked black.
45 //
46 //    c. GC performs root marking jobs. This includes scanning all
47 //    stacks, shading all globals, and shading any heap pointers in
48 //    off-heap runtime data structures. Scanning a stack stops a
49 //    goroutine, shades any pointers found on its stack, and then
50 //    resumes the goroutine.
51 //
52 //    d. GC drains the work queue of grey objects, scanning each grey
53 //    object to black and shading all pointers found in the object
54 //    (which in turn may add those pointers to the work queue).
55 //
56 //    e. Because GC work is spread across local caches, GC uses a
57 //    distributed termination algorithm to detect when there are no
58 //    more root marking jobs or grey objects (see gcMarkDone). At this
59 //    point, GC transitions to mark termination.
60 //
61 // 3. GC performs mark termination.
62 //
63 //    a. Stop the world.
64 //
65 //    b. Set gcphase to _GCmarktermination, and disable workers and
66 //    assists.
67 //
68 //    c. Perform housekeeping like flushing mcaches.
69 //
70 // 4. GC performs the sweep phase.
71 //
72 //    a. Prepare for the sweep phase by setting gcphase to _GCoff,
73 //    setting up sweep state and disabling the write barrier.
74 //
75 //    b. Start the world. From this point on, newly allocated objects
76 //    are white, and allocating sweeps spans before use if necessary.
77 //
78 //    c. GC does concurrent sweeping in the background and in response
79 //    to allocation. See description below.
80 //
81 // 5. When sufficient allocation has taken place, replay the sequence
82 // starting with 1 above. See discussion of GC rate below.
83
84 // Concurrent sweep.
85 //
86 // The sweep phase proceeds concurrently with normal program execution.
87 // The heap is swept span-by-span both lazily (when a goroutine needs another span)
88 // and concurrently in a background goroutine (this helps programs that are not CPU bound).
89 // At the end of STW mark termination all spans are marked as "needs sweeping".
90 //
91 // The background sweeper goroutine simply sweeps spans one-by-one.
92 //
93 // To avoid requesting more OS memory while there are unswept spans, when a
94 // goroutine needs another span, it first attempts to reclaim that much memory
95 // by sweeping. When a goroutine needs to allocate a new small-object span, it
96 // sweeps small-object spans for the same object size until it frees at least
97 // one object. When a goroutine needs to allocate large-object span from heap,
98 // it sweeps spans until it frees at least that many pages into heap. There is
99 // one case where this may not suffice: if a goroutine sweeps and frees two
100 // nonadjacent one-page spans to the heap, it will allocate a new two-page
101 // span, but there can still be other one-page unswept spans which could be
102 // combined into a two-page span.
103 //
104 // It's critical to ensure that no operations proceed on unswept spans (that would corrupt
105 // mark bits in GC bitmap). During GC all mcaches are flushed into the central cache,
106 // so they are empty. When a goroutine grabs a new span into mcache, it sweeps it.
107 // When a goroutine explicitly frees an object or sets a finalizer, it ensures that
108 // the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish).
109 // The finalizer goroutine is kicked off only when all spans are swept.
110 // When the next GC starts, it sweeps all not-yet-swept spans (if any).
111
112 // GC rate.
113 // Next GC is after we've allocated an extra amount of memory proportional to
114 // the amount already in use. The proportion is controlled by GOGC environment variable
115 // (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M
116 // (this mark is computed by the gcController.heapGoal method). This keeps the GC cost in
117 // linear proportion to the allocation cost. Adjusting GOGC just changes the linear constant
118 // (and also the amount of extra memory used).
119
120 // Oblets
121 //
122 // In order to prevent long pauses while scanning large objects and to
123 // improve parallelism, the garbage collector breaks up scan jobs for
124 // objects larger than maxObletBytes into "oblets" of at most
125 // maxObletBytes. When scanning encounters the beginning of a large
126 // object, it scans only the first oblet and enqueues the remaining
127 // oblets as new scan jobs.
128
129 package runtime
130
131 import (
132         "internal/cpu"
133         "runtime/internal/atomic"
134         "unsafe"
135 )
136
137 const (
138         _DebugGC      = 0
139         _FinBlockSize = 4 * 1024
140
141         // concurrentSweep is a debug flag. Disabling this flag
142         // ensures all spans are swept while the world is stopped.
143         concurrentSweep = true
144
145         // debugScanConservative enables debug logging for stack
146         // frames that are scanned conservatively.
147         debugScanConservative = false
148
149         // sweepMinHeapDistance is a lower bound on the heap distance
150         // (in bytes) reserved for concurrent sweeping between GC
151         // cycles.
152         sweepMinHeapDistance = 1024 * 1024
153 )
154
155 // heapObjectsCanMove always returns false in the current garbage collector.
156 // It exists for go4.org/unsafe/assume-no-moving-gc, which is an
157 // unfortunate idea that had an even more unfortunate implementation.
158 // Every time a new Go release happened, the package stopped building,
159 // and the authors had to add a new file with a new //go:build line, and
160 // then the entire ecosystem of packages with that as a dependency had to
161 // explicitly update to the new version. Many packages depend on
162 // assume-no-moving-gc transitively, through paths like
163 // inet.af/netaddr -> go4.org/intern -> assume-no-moving-gc.
164 // This was causing a significant amount of friction around each new
165 // release, so we added this bool for the package to //go:linkname
166 // instead. The bool is still unfortunate, but it's not as bad as
167 // breaking the ecosystem on every new release.
168 //
169 // If the Go garbage collector ever does move heap objects, we can set
170 // this to true to break all the programs using assume-no-moving-gc.
171 //
172 //go:linkname heapObjectsCanMove
173 func heapObjectsCanMove() bool {
174         return false
175 }
176
177 func gcinit() {
178         if unsafe.Sizeof(workbuf{}) != _WorkbufSize {
179                 throw("size of Workbuf is suboptimal")
180         }
181         // No sweep on the first cycle.
182         sweep.active.state.Store(sweepDrainedMask)
183
184         // Initialize GC pacer state.
185         // Use the environment variable GOGC for the initial gcPercent value.
186         // Use the environment variable GOMEMLIMIT for the initial memoryLimit value.
187         gcController.init(readGOGC(), readGOMEMLIMIT())
188
189         work.startSema = 1
190         work.markDoneSema = 1
191         lockInit(&work.sweepWaiters.lock, lockRankSweepWaiters)
192         lockInit(&work.assistQueue.lock, lockRankAssistQueue)
193         lockInit(&work.wbufSpans.lock, lockRankWbufSpans)
194 }
195
196 // gcenable is called after the bulk of the runtime initialization,
197 // just before we're about to start letting user code run.
198 // It kicks off the background sweeper goroutine, the background
199 // scavenger goroutine, and enables GC.
200 func gcenable() {
201         // Kick off sweeping and scavenging.
202         c := make(chan int, 2)
203         go bgsweep(c)
204         go bgscavenge(c)
205         <-c
206         <-c
207         memstats.enablegc = true // now that runtime is initialized, GC is okay
208 }
209
210 // Garbage collector phase.
211 // Indicates to write barrier and synchronization task to perform.
212 var gcphase uint32
213
214 // The compiler knows about this variable.
215 // If you change it, you must change builtin/runtime.go, too.
216 // If you change the first four bytes, you must also change the write
217 // barrier insertion code.
218 var writeBarrier struct {
219         enabled bool    // compiler emits a check of this before calling write barrier
220         pad     [3]byte // compiler uses 32-bit load for "enabled" field
221         alignme uint64  // guarantee alignment so that compiler can use a 32 or 64-bit load
222 }
223
224 // gcBlackenEnabled is 1 if mutator assists and background mark
225 // workers are allowed to blacken objects. This must only be set when
226 // gcphase == _GCmark.
227 var gcBlackenEnabled uint32
228
229 const (
230         _GCoff             = iota // GC not running; sweeping in background, write barrier disabled
231         _GCmark                   // GC marking roots and workbufs: allocate black, write barrier ENABLED
232         _GCmarktermination        // GC mark termination: allocate black, P's help GC, write barrier ENABLED
233 )
234
235 //go:nosplit
236 func setGCPhase(x uint32) {
237         atomic.Store(&gcphase, x)
238         writeBarrier.enabled = gcphase == _GCmark || gcphase == _GCmarktermination
239 }
240
241 // gcMarkWorkerMode represents the mode that a concurrent mark worker
242 // should operate in.
243 //
244 // Concurrent marking happens through four different mechanisms. One
245 // is mutator assists, which happen in response to allocations and are
246 // not scheduled. The other three are variations in the per-P mark
247 // workers and are distinguished by gcMarkWorkerMode.
248 type gcMarkWorkerMode int
249
250 const (
251         // gcMarkWorkerNotWorker indicates that the next scheduled G is not
252         // starting work and the mode should be ignored.
253         gcMarkWorkerNotWorker gcMarkWorkerMode = iota
254
255         // gcMarkWorkerDedicatedMode indicates that the P of a mark
256         // worker is dedicated to running that mark worker. The mark
257         // worker should run without preemption.
258         gcMarkWorkerDedicatedMode
259
260         // gcMarkWorkerFractionalMode indicates that a P is currently
261         // running the "fractional" mark worker. The fractional worker
262         // is necessary when GOMAXPROCS*gcBackgroundUtilization is not
263         // an integer and using only dedicated workers would result in
264         // utilization too far from the target of gcBackgroundUtilization.
265         // The fractional worker should run until it is preempted and
266         // will be scheduled to pick up the fractional part of
267         // GOMAXPROCS*gcBackgroundUtilization.
268         gcMarkWorkerFractionalMode
269
270         // gcMarkWorkerIdleMode indicates that a P is running the mark
271         // worker because it has nothing else to do. The idle worker
272         // should run until it is preempted and account its time
273         // against gcController.idleMarkTime.
274         gcMarkWorkerIdleMode
275 )
276
277 // gcMarkWorkerModeStrings are the strings labels of gcMarkWorkerModes
278 // to use in execution traces.
279 var gcMarkWorkerModeStrings = [...]string{
280         "Not worker",
281         "GC (dedicated)",
282         "GC (fractional)",
283         "GC (idle)",
284 }
285
286 // pollFractionalWorkerExit reports whether a fractional mark worker
287 // should self-preempt. It assumes it is called from the fractional
288 // worker.
289 func pollFractionalWorkerExit() bool {
290         // This should be kept in sync with the fractional worker
291         // scheduler logic in findRunnableGCWorker.
292         now := nanotime()
293         delta := now - gcController.markStartTime
294         if delta <= 0 {
295                 return true
296         }
297         p := getg().m.p.ptr()
298         selfTime := p.gcFractionalMarkTime + (now - p.gcMarkWorkerStartTime)
299         // Add some slack to the utilization goal so that the
300         // fractional worker isn't behind again the instant it exits.
301         return float64(selfTime)/float64(delta) > 1.2*gcController.fractionalUtilizationGoal
302 }
303
304 var work workType
305
306 type workType struct {
307         full  lfstack          // lock-free list of full blocks workbuf
308         _     cpu.CacheLinePad // prevents false-sharing between full and empty
309         empty lfstack          // lock-free list of empty blocks workbuf
310         _     cpu.CacheLinePad // prevents false-sharing between empty and nproc/nwait
311
312         wbufSpans struct {
313                 lock mutex
314                 // free is a list of spans dedicated to workbufs, but
315                 // that don't currently contain any workbufs.
316                 free mSpanList
317                 // busy is a list of all spans containing workbufs on
318                 // one of the workbuf lists.
319                 busy mSpanList
320         }
321
322         // Restore 64-bit alignment on 32-bit.
323         _ uint32
324
325         // bytesMarked is the number of bytes marked this cycle. This
326         // includes bytes blackened in scanned objects, noscan objects
327         // that go straight to black, and permagrey objects scanned by
328         // markroot during the concurrent scan phase. This is updated
329         // atomically during the cycle. Updates may be batched
330         // arbitrarily, since the value is only read at the end of the
331         // cycle.
332         //
333         // Because of benign races during marking, this number may not
334         // be the exact number of marked bytes, but it should be very
335         // close.
336         //
337         // Put this field here because it needs 64-bit atomic access
338         // (and thus 8-byte alignment even on 32-bit architectures).
339         bytesMarked uint64
340
341         markrootNext uint32 // next markroot job
342         markrootJobs uint32 // number of markroot jobs
343
344         nproc  uint32
345         tstart int64
346         nwait  uint32
347
348         // Number of roots of various root types. Set by gcMarkRootPrepare.
349         //
350         // nStackRoots == len(stackRoots), but we have nStackRoots for
351         // consistency.
352         nDataRoots, nBSSRoots, nSpanRoots, nStackRoots int
353
354         // Base indexes of each root type. Set by gcMarkRootPrepare.
355         baseData, baseBSS, baseSpans, baseStacks, baseEnd uint32
356
357         // stackRoots is a snapshot of all of the Gs that existed
358         // before the beginning of concurrent marking. The backing
359         // store of this must not be modified because it might be
360         // shared with allgs.
361         stackRoots []*g
362
363         // Each type of GC state transition is protected by a lock.
364         // Since multiple threads can simultaneously detect the state
365         // transition condition, any thread that detects a transition
366         // condition must acquire the appropriate transition lock,
367         // re-check the transition condition and return if it no
368         // longer holds or perform the transition if it does.
369         // Likewise, any transition must invalidate the transition
370         // condition before releasing the lock. This ensures that each
371         // transition is performed by exactly one thread and threads
372         // that need the transition to happen block until it has
373         // happened.
374         //
375         // startSema protects the transition from "off" to mark or
376         // mark termination.
377         startSema uint32
378         // markDoneSema protects transitions from mark to mark termination.
379         markDoneSema uint32
380
381         bgMarkReady note   // signal background mark worker has started
382         bgMarkDone  uint32 // cas to 1 when at a background mark completion point
383         // Background mark completion signaling
384
385         // mode is the concurrency mode of the current GC cycle.
386         mode gcMode
387
388         // userForced indicates the current GC cycle was forced by an
389         // explicit user call.
390         userForced bool
391
392         // initialHeapLive is the value of gcController.heapLive at the
393         // beginning of this GC cycle.
394         initialHeapLive uint64
395
396         // assistQueue is a queue of assists that are blocked because
397         // there was neither enough credit to steal or enough work to
398         // do.
399         assistQueue struct {
400                 lock mutex
401                 q    gQueue
402         }
403
404         // sweepWaiters is a list of blocked goroutines to wake when
405         // we transition from mark termination to sweep.
406         sweepWaiters struct {
407                 lock mutex
408                 list gList
409         }
410
411         // cycles is the number of completed GC cycles, where a GC
412         // cycle is sweep termination, mark, mark termination, and
413         // sweep. This differs from memstats.numgc, which is
414         // incremented at mark termination.
415         cycles atomic.Uint32
416
417         // Timing/utilization stats for this cycle.
418         stwprocs, maxprocs                 int32
419         tSweepTerm, tMark, tMarkTerm, tEnd int64 // nanotime() of phase start
420
421         pauseNS    int64 // total STW time this cycle
422         pauseStart int64 // nanotime() of last STW
423
424         // debug.gctrace heap sizes for this cycle.
425         heap0, heap1, heap2 uint64
426
427         // Cumulative estimated CPU usage.
428         cpuStats
429 }
430
431 // GC runs a garbage collection and blocks the caller until the
432 // garbage collection is complete. It may also block the entire
433 // program.
434 func GC() {
435         // We consider a cycle to be: sweep termination, mark, mark
436         // termination, and sweep. This function shouldn't return
437         // until a full cycle has been completed, from beginning to
438         // end. Hence, we always want to finish up the current cycle
439         // and start a new one. That means:
440         //
441         // 1. In sweep termination, mark, or mark termination of cycle
442         // N, wait until mark termination N completes and transitions
443         // to sweep N.
444         //
445         // 2. In sweep N, help with sweep N.
446         //
447         // At this point we can begin a full cycle N+1.
448         //
449         // 3. Trigger cycle N+1 by starting sweep termination N+1.
450         //
451         // 4. Wait for mark termination N+1 to complete.
452         //
453         // 5. Help with sweep N+1 until it's done.
454         //
455         // This all has to be written to deal with the fact that the
456         // GC may move ahead on its own. For example, when we block
457         // until mark termination N, we may wake up in cycle N+2.
458
459         // Wait until the current sweep termination, mark, and mark
460         // termination complete.
461         n := work.cycles.Load()
462         gcWaitOnMark(n)
463
464         // We're now in sweep N or later. Trigger GC cycle N+1, which
465         // will first finish sweep N if necessary and then enter sweep
466         // termination N+1.
467         gcStart(gcTrigger{kind: gcTriggerCycle, n: n + 1})
468
469         // Wait for mark termination N+1 to complete.
470         gcWaitOnMark(n + 1)
471
472         // Finish sweep N+1 before returning. We do this both to
473         // complete the cycle and because runtime.GC() is often used
474         // as part of tests and benchmarks to get the system into a
475         // relatively stable and isolated state.
476         for work.cycles.Load() == n+1 && sweepone() != ^uintptr(0) {
477                 Gosched()
478         }
479
480         // Callers may assume that the heap profile reflects the
481         // just-completed cycle when this returns (historically this
482         // happened because this was a STW GC), but right now the
483         // profile still reflects mark termination N, not N+1.
484         //
485         // As soon as all of the sweep frees from cycle N+1 are done,
486         // we can go ahead and publish the heap profile.
487         //
488         // First, wait for sweeping to finish. (We know there are no
489         // more spans on the sweep queue, but we may be concurrently
490         // sweeping spans, so we have to wait.)
491         for work.cycles.Load() == n+1 && !isSweepDone() {
492                 Gosched()
493         }
494
495         // Now we're really done with sweeping, so we can publish the
496         // stable heap profile. Only do this if we haven't already hit
497         // another mark termination.
498         mp := acquirem()
499         cycle := work.cycles.Load()
500         if cycle == n+1 || (gcphase == _GCmark && cycle == n+2) {
501                 mProf_PostSweep()
502         }
503         releasem(mp)
504 }
505
506 // gcWaitOnMark blocks until GC finishes the Nth mark phase. If GC has
507 // already completed this mark phase, it returns immediately.
508 func gcWaitOnMark(n uint32) {
509         for {
510                 // Disable phase transitions.
511                 lock(&work.sweepWaiters.lock)
512                 nMarks := work.cycles.Load()
513                 if gcphase != _GCmark {
514                         // We've already completed this cycle's mark.
515                         nMarks++
516                 }
517                 if nMarks > n {
518                         // We're done.
519                         unlock(&work.sweepWaiters.lock)
520                         return
521                 }
522
523                 // Wait until sweep termination, mark, and mark
524                 // termination of cycle N complete.
525                 work.sweepWaiters.list.push(getg())
526                 goparkunlock(&work.sweepWaiters.lock, waitReasonWaitForGCCycle, traceBlockUntilGCEnds, 1)
527         }
528 }
529
530 // gcMode indicates how concurrent a GC cycle should be.
531 type gcMode int
532
533 const (
534         gcBackgroundMode gcMode = iota // concurrent GC and sweep
535         gcForceMode                    // stop-the-world GC now, concurrent sweep
536         gcForceBlockMode               // stop-the-world GC now and STW sweep (forced by user)
537 )
538
539 // A gcTrigger is a predicate for starting a GC cycle. Specifically,
540 // it is an exit condition for the _GCoff phase.
541 type gcTrigger struct {
542         kind gcTriggerKind
543         now  int64  // gcTriggerTime: current time
544         n    uint32 // gcTriggerCycle: cycle number to start
545 }
546
547 type gcTriggerKind int
548
549 const (
550         // gcTriggerHeap indicates that a cycle should be started when
551         // the heap size reaches the trigger heap size computed by the
552         // controller.
553         gcTriggerHeap gcTriggerKind = iota
554
555         // gcTriggerTime indicates that a cycle should be started when
556         // it's been more than forcegcperiod nanoseconds since the
557         // previous GC cycle.
558         gcTriggerTime
559
560         // gcTriggerCycle indicates that a cycle should be started if
561         // we have not yet started cycle number gcTrigger.n (relative
562         // to work.cycles).
563         gcTriggerCycle
564 )
565
566 // test reports whether the trigger condition is satisfied, meaning
567 // that the exit condition for the _GCoff phase has been met. The exit
568 // condition should be tested when allocating.
569 func (t gcTrigger) test() bool {
570         if !memstats.enablegc || panicking.Load() != 0 || gcphase != _GCoff {
571                 return false
572         }
573         switch t.kind {
574         case gcTriggerHeap:
575                 trigger, _ := gcController.trigger()
576                 return gcController.heapLive.Load() >= trigger
577         case gcTriggerTime:
578                 if gcController.gcPercent.Load() < 0 {
579                         return false
580                 }
581                 lastgc := int64(atomic.Load64(&memstats.last_gc_nanotime))
582                 return lastgc != 0 && t.now-lastgc > forcegcperiod
583         case gcTriggerCycle:
584                 // t.n > work.cycles, but accounting for wraparound.
585                 return int32(t.n-work.cycles.Load()) > 0
586         }
587         return true
588 }
589
590 // gcStart starts the GC. It transitions from _GCoff to _GCmark (if
591 // debug.gcstoptheworld == 0) or performs all of GC (if
592 // debug.gcstoptheworld != 0).
593 //
594 // This may return without performing this transition in some cases,
595 // such as when called on a system stack or with locks held.
596 func gcStart(trigger gcTrigger) {
597         // Since this is called from malloc and malloc is called in
598         // the guts of a number of libraries that might be holding
599         // locks, don't attempt to start GC in non-preemptible or
600         // potentially unstable situations.
601         mp := acquirem()
602         if gp := getg(); gp == mp.g0 || mp.locks > 1 || mp.preemptoff != "" {
603                 releasem(mp)
604                 return
605         }
606         releasem(mp)
607         mp = nil
608
609         // Pick up the remaining unswept/not being swept spans concurrently
610         //
611         // This shouldn't happen if we're being invoked in background
612         // mode since proportional sweep should have just finished
613         // sweeping everything, but rounding errors, etc, may leave a
614         // few spans unswept. In forced mode, this is necessary since
615         // GC can be forced at any point in the sweeping cycle.
616         //
617         // We check the transition condition continuously here in case
618         // this G gets delayed in to the next GC cycle.
619         for trigger.test() && sweepone() != ^uintptr(0) {
620         }
621
622         // Perform GC initialization and the sweep termination
623         // transition.
624         semacquire(&work.startSema)
625         // Re-check transition condition under transition lock.
626         if !trigger.test() {
627                 semrelease(&work.startSema)
628                 return
629         }
630
631         // In gcstoptheworld debug mode, upgrade the mode accordingly.
632         // We do this after re-checking the transition condition so
633         // that multiple goroutines that detect the heap trigger don't
634         // start multiple STW GCs.
635         mode := gcBackgroundMode
636         if debug.gcstoptheworld == 1 {
637                 mode = gcForceMode
638         } else if debug.gcstoptheworld == 2 {
639                 mode = gcForceBlockMode
640         }
641
642         // Ok, we're doing it! Stop everybody else
643         semacquire(&gcsema)
644         semacquire(&worldsema)
645
646         // For stats, check if this GC was forced by the user.
647         // Update it under gcsema to avoid gctrace getting wrong values.
648         work.userForced = trigger.kind == gcTriggerCycle
649
650         trace := traceAcquire()
651         if trace.ok() {
652                 trace.GCStart()
653                 traceRelease(trace)
654         }
655
656         // Check that all Ps have finished deferred mcache flushes.
657         for _, p := range allp {
658                 if fg := p.mcache.flushGen.Load(); fg != mheap_.sweepgen {
659                         println("runtime: p", p.id, "flushGen", fg, "!= sweepgen", mheap_.sweepgen)
660                         throw("p mcache not flushed")
661                 }
662         }
663
664         gcBgMarkStartWorkers()
665
666         systemstack(gcResetMarkState)
667
668         work.stwprocs, work.maxprocs = gomaxprocs, gomaxprocs
669         if work.stwprocs > ncpu {
670                 // This is used to compute CPU time of the STW phases,
671                 // so it can't be more than ncpu, even if GOMAXPROCS is.
672                 work.stwprocs = ncpu
673         }
674         work.heap0 = gcController.heapLive.Load()
675         work.pauseNS = 0
676         work.mode = mode
677
678         now := nanotime()
679         work.tSweepTerm = now
680         work.pauseStart = now
681         systemstack(func() { stopTheWorldWithSema(stwGCSweepTerm) })
682         // Finish sweep before we start concurrent scan.
683         systemstack(func() {
684                 finishsweep_m()
685         })
686
687         // clearpools before we start the GC. If we wait the memory will not be
688         // reclaimed until the next GC cycle.
689         clearpools()
690
691         work.cycles.Add(1)
692
693         // Assists and workers can start the moment we start
694         // the world.
695         gcController.startCycle(now, int(gomaxprocs), trigger)
696
697         // Notify the CPU limiter that assists may begin.
698         gcCPULimiter.startGCTransition(true, now)
699
700         // In STW mode, disable scheduling of user Gs. This may also
701         // disable scheduling of this goroutine, so it may block as
702         // soon as we start the world again.
703         if mode != gcBackgroundMode {
704                 schedEnableUser(false)
705         }
706
707         // Enter concurrent mark phase and enable
708         // write barriers.
709         //
710         // Because the world is stopped, all Ps will
711         // observe that write barriers are enabled by
712         // the time we start the world and begin
713         // scanning.
714         //
715         // Write barriers must be enabled before assists are
716         // enabled because they must be enabled before
717         // any non-leaf heap objects are marked. Since
718         // allocations are blocked until assists can
719         // happen, we want to enable assists as early as
720         // possible.
721         setGCPhase(_GCmark)
722
723         gcBgMarkPrepare() // Must happen before assists are enabled.
724         gcMarkRootPrepare()
725
726         // Mark all active tinyalloc blocks. Since we're
727         // allocating from these, they need to be black like
728         // other allocations. The alternative is to blacken
729         // the tiny block on every allocation from it, which
730         // would slow down the tiny allocator.
731         gcMarkTinyAllocs()
732
733         // At this point all Ps have enabled the write
734         // barrier, thus maintaining the no white to
735         // black invariant. Enable mutator assists to
736         // put back-pressure on fast allocating
737         // mutators.
738         atomic.Store(&gcBlackenEnabled, 1)
739
740         // In STW mode, we could block the instant systemstack
741         // returns, so make sure we're not preemptible.
742         mp = acquirem()
743
744         // Concurrent mark.
745         systemstack(func() {
746                 now = startTheWorldWithSema()
747                 work.pauseNS += now - work.pauseStart
748                 work.tMark = now
749                 memstats.gcPauseDist.record(now - work.pauseStart)
750
751                 sweepTermCpu := int64(work.stwprocs) * (work.tMark - work.tSweepTerm)
752                 work.cpuStats.gcPauseTime += sweepTermCpu
753                 work.cpuStats.gcTotalTime += sweepTermCpu
754
755                 // Release the CPU limiter.
756                 gcCPULimiter.finishGCTransition(now)
757         })
758
759         // Release the world sema before Gosched() in STW mode
760         // because we will need to reacquire it later but before
761         // this goroutine becomes runnable again, and we could
762         // self-deadlock otherwise.
763         semrelease(&worldsema)
764         releasem(mp)
765
766         // Make sure we block instead of returning to user code
767         // in STW mode.
768         if mode != gcBackgroundMode {
769                 Gosched()
770         }
771
772         semrelease(&work.startSema)
773 }
774
775 // gcMarkDoneFlushed counts the number of P's with flushed work.
776 //
777 // Ideally this would be a captured local in gcMarkDone, but forEachP
778 // escapes its callback closure, so it can't capture anything.
779 //
780 // This is protected by markDoneSema.
781 var gcMarkDoneFlushed uint32
782
783 // gcMarkDone transitions the GC from mark to mark termination if all
784 // reachable objects have been marked (that is, there are no grey
785 // objects and can be no more in the future). Otherwise, it flushes
786 // all local work to the global queues where it can be discovered by
787 // other workers.
788 //
789 // This should be called when all local mark work has been drained and
790 // there are no remaining workers. Specifically, when
791 //
792 //      work.nwait == work.nproc && !gcMarkWorkAvailable(p)
793 //
794 // The calling context must be preemptible.
795 //
796 // Flushing local work is important because idle Ps may have local
797 // work queued. This is the only way to make that work visible and
798 // drive GC to completion.
799 //
800 // It is explicitly okay to have write barriers in this function. If
801 // it does transition to mark termination, then all reachable objects
802 // have been marked, so the write barrier cannot shade any more
803 // objects.
804 func gcMarkDone() {
805         // Ensure only one thread is running the ragged barrier at a
806         // time.
807         semacquire(&work.markDoneSema)
808
809 top:
810         // Re-check transition condition under transition lock.
811         //
812         // It's critical that this checks the global work queues are
813         // empty before performing the ragged barrier. Otherwise,
814         // there could be global work that a P could take after the P
815         // has passed the ragged barrier.
816         if !(gcphase == _GCmark && work.nwait == work.nproc && !gcMarkWorkAvailable(nil)) {
817                 semrelease(&work.markDoneSema)
818                 return
819         }
820
821         // forEachP needs worldsema to execute, and we'll need it to
822         // stop the world later, so acquire worldsema now.
823         semacquire(&worldsema)
824
825         // Flush all local buffers and collect flushedWork flags.
826         gcMarkDoneFlushed = 0
827         systemstack(func() {
828                 gp := getg().m.curg
829                 // Mark the user stack as preemptible so that it may be scanned.
830                 // Otherwise, our attempt to force all P's to a safepoint could
831                 // result in a deadlock as we attempt to preempt a worker that's
832                 // trying to preempt us (e.g. for a stack scan).
833                 casGToWaiting(gp, _Grunning, waitReasonGCMarkTermination)
834                 forEachP(func(pp *p) {
835                         // Flush the write barrier buffer, since this may add
836                         // work to the gcWork.
837                         wbBufFlush1(pp)
838
839                         // Flush the gcWork, since this may create global work
840                         // and set the flushedWork flag.
841                         //
842                         // TODO(austin): Break up these workbufs to
843                         // better distribute work.
844                         pp.gcw.dispose()
845                         // Collect the flushedWork flag.
846                         if pp.gcw.flushedWork {
847                                 atomic.Xadd(&gcMarkDoneFlushed, 1)
848                                 pp.gcw.flushedWork = false
849                         }
850                 })
851                 casgstatus(gp, _Gwaiting, _Grunning)
852         })
853
854         if gcMarkDoneFlushed != 0 {
855                 // More grey objects were discovered since the
856                 // previous termination check, so there may be more
857                 // work to do. Keep going. It's possible the
858                 // transition condition became true again during the
859                 // ragged barrier, so re-check it.
860                 semrelease(&worldsema)
861                 goto top
862         }
863
864         // There was no global work, no local work, and no Ps
865         // communicated work since we took markDoneSema. Therefore
866         // there are no grey objects and no more objects can be
867         // shaded. Transition to mark termination.
868         now := nanotime()
869         work.tMarkTerm = now
870         work.pauseStart = now
871         getg().m.preemptoff = "gcing"
872         systemstack(func() { stopTheWorldWithSema(stwGCMarkTerm) })
873         // The gcphase is _GCmark, it will transition to _GCmarktermination
874         // below. The important thing is that the wb remains active until
875         // all marking is complete. This includes writes made by the GC.
876
877         // There is sometimes work left over when we enter mark termination due
878         // to write barriers performed after the completion barrier above.
879         // Detect this and resume concurrent mark. This is obviously
880         // unfortunate.
881         //
882         // See issue #27993 for details.
883         //
884         // Switch to the system stack to call wbBufFlush1, though in this case
885         // it doesn't matter because we're non-preemptible anyway.
886         restart := false
887         systemstack(func() {
888                 for _, p := range allp {
889                         wbBufFlush1(p)
890                         if !p.gcw.empty() {
891                                 restart = true
892                                 break
893                         }
894                 }
895         })
896         if restart {
897                 getg().m.preemptoff = ""
898                 systemstack(func() {
899                         now := startTheWorldWithSema()
900                         work.pauseNS += now - work.pauseStart
901                         memstats.gcPauseDist.record(now - work.pauseStart)
902                 })
903                 semrelease(&worldsema)
904                 goto top
905         }
906
907         gcComputeStartingStackSize()
908
909         // Disable assists and background workers. We must do
910         // this before waking blocked assists.
911         atomic.Store(&gcBlackenEnabled, 0)
912
913         // Notify the CPU limiter that GC assists will now cease.
914         gcCPULimiter.startGCTransition(false, now)
915
916         // Wake all blocked assists. These will run when we
917         // start the world again.
918         gcWakeAllAssists()
919
920         // Likewise, release the transition lock. Blocked
921         // workers and assists will run when we start the
922         // world again.
923         semrelease(&work.markDoneSema)
924
925         // In STW mode, re-enable user goroutines. These will be
926         // queued to run after we start the world.
927         schedEnableUser(true)
928
929         // endCycle depends on all gcWork cache stats being flushed.
930         // The termination algorithm above ensured that up to
931         // allocations since the ragged barrier.
932         gcController.endCycle(now, int(gomaxprocs), work.userForced)
933
934         // Perform mark termination. This will restart the world.
935         gcMarkTermination()
936 }
937
938 // World must be stopped and mark assists and background workers must be
939 // disabled.
940 func gcMarkTermination() {
941         // Start marktermination (write barrier remains enabled for now).
942         setGCPhase(_GCmarktermination)
943
944         work.heap1 = gcController.heapLive.Load()
945         startTime := nanotime()
946
947         mp := acquirem()
948         mp.preemptoff = "gcing"
949         mp.traceback = 2
950         curgp := mp.curg
951         casGToWaiting(curgp, _Grunning, waitReasonGarbageCollection)
952
953         // Run gc on the g0 stack. We do this so that the g stack
954         // we're currently running on will no longer change. Cuts
955         // the root set down a bit (g0 stacks are not scanned, and
956         // we don't need to scan gc's internal state).  We also
957         // need to switch to g0 so we can shrink the stack.
958         systemstack(func() {
959                 gcMark(startTime)
960                 // Must return immediately.
961                 // The outer function's stack may have moved
962                 // during gcMark (it shrinks stacks, including the
963                 // outer function's stack), so we must not refer
964                 // to any of its variables. Return back to the
965                 // non-system stack to pick up the new addresses
966                 // before continuing.
967         })
968
969         var stwSwept bool
970         systemstack(func() {
971                 work.heap2 = work.bytesMarked
972                 if debug.gccheckmark > 0 {
973                         // Run a full non-parallel, stop-the-world
974                         // mark using checkmark bits, to check that we
975                         // didn't forget to mark anything during the
976                         // concurrent mark process.
977                         startCheckmarks()
978                         gcResetMarkState()
979                         gcw := &getg().m.p.ptr().gcw
980                         gcDrain(gcw, 0)
981                         wbBufFlush1(getg().m.p.ptr())
982                         gcw.dispose()
983                         endCheckmarks()
984                 }
985
986                 // marking is complete so we can turn the write barrier off
987                 setGCPhase(_GCoff)
988                 stwSwept = gcSweep(work.mode)
989         })
990
991         mp.traceback = 0
992         casgstatus(curgp, _Gwaiting, _Grunning)
993
994         trace := traceAcquire()
995         if trace.ok() {
996                 trace.GCDone()
997                 traceRelease(trace)
998         }
999
1000         // all done
1001         mp.preemptoff = ""
1002
1003         if gcphase != _GCoff {
1004                 throw("gc done but gcphase != _GCoff")
1005         }
1006
1007         // Record heapInUse for scavenger.
1008         memstats.lastHeapInUse = gcController.heapInUse.load()
1009
1010         // Update GC trigger and pacing, as well as downstream consumers
1011         // of this pacing information, for the next cycle.
1012         systemstack(gcControllerCommit)
1013
1014         // Update timing memstats
1015         now := nanotime()
1016         sec, nsec, _ := time_now()
1017         unixNow := sec*1e9 + int64(nsec)
1018         work.pauseNS += now - work.pauseStart
1019         work.tEnd = now
1020         memstats.gcPauseDist.record(now - work.pauseStart)
1021         atomic.Store64(&memstats.last_gc_unix, uint64(unixNow)) // must be Unix time to make sense to user
1022         atomic.Store64(&memstats.last_gc_nanotime, uint64(now)) // monotonic time for us
1023         memstats.pause_ns[memstats.numgc%uint32(len(memstats.pause_ns))] = uint64(work.pauseNS)
1024         memstats.pause_end[memstats.numgc%uint32(len(memstats.pause_end))] = uint64(unixNow)
1025         memstats.pause_total_ns += uint64(work.pauseNS)
1026
1027         markTermCpu := int64(work.stwprocs) * (work.tEnd - work.tMarkTerm)
1028         work.cpuStats.gcPauseTime += markTermCpu
1029         work.cpuStats.gcTotalTime += markTermCpu
1030
1031         // Accumulate CPU stats.
1032         //
1033         // Pass gcMarkPhase=true so we can get all the latest GC CPU stats in there too.
1034         work.cpuStats.accumulate(now, true)
1035
1036         // Compute overall GC CPU utilization.
1037         // Omit idle marking time from the overall utilization here since it's "free".
1038         memstats.gc_cpu_fraction = float64(work.cpuStats.gcTotalTime-work.cpuStats.gcIdleTime) / float64(work.cpuStats.totalTime)
1039
1040         // Reset assist time and background time stats.
1041         //
1042         // Do this now, instead of at the start of the next GC cycle, because
1043         // these two may keep accumulating even if the GC is not active.
1044         scavenge.assistTime.Store(0)
1045         scavenge.backgroundTime.Store(0)
1046
1047         // Reset idle time stat.
1048         sched.idleTime.Store(0)
1049
1050         if work.userForced {
1051                 memstats.numforcedgc++
1052         }
1053
1054         // Bump GC cycle count and wake goroutines waiting on sweep.
1055         lock(&work.sweepWaiters.lock)
1056         memstats.numgc++
1057         injectglist(&work.sweepWaiters.list)
1058         unlock(&work.sweepWaiters.lock)
1059
1060         // Increment the scavenge generation now.
1061         //
1062         // This moment represents peak heap in use because we're
1063         // about to start sweeping.
1064         mheap_.pages.scav.index.nextGen()
1065
1066         // Release the CPU limiter.
1067         gcCPULimiter.finishGCTransition(now)
1068
1069         // Finish the current heap profiling cycle and start a new
1070         // heap profiling cycle. We do this before starting the world
1071         // so events don't leak into the wrong cycle.
1072         mProf_NextCycle()
1073
1074         // There may be stale spans in mcaches that need to be swept.
1075         // Those aren't tracked in any sweep lists, so we need to
1076         // count them against sweep completion until we ensure all
1077         // those spans have been forced out.
1078         //
1079         // If gcSweep fully swept the heap (for example if the sweep
1080         // is not concurrent due to a GODEBUG setting), then we expect
1081         // the sweepLocker to be invalid, since sweeping is done.
1082         //
1083         // N.B. Below we might duplicate some work from gcSweep; this is
1084         // fine as all that work is idempotent within a GC cycle, and
1085         // we're still holding worldsema so a new cycle can't start.
1086         sl := sweep.active.begin()
1087         if !stwSwept && !sl.valid {
1088                 throw("failed to set sweep barrier")
1089         } else if stwSwept && sl.valid {
1090                 throw("non-concurrent sweep failed to drain all sweep queues")
1091         }
1092
1093         systemstack(func() { startTheWorldWithSema() })
1094
1095         // Flush the heap profile so we can start a new cycle next GC.
1096         // This is relatively expensive, so we don't do it with the
1097         // world stopped.
1098         mProf_Flush()
1099
1100         // Prepare workbufs for freeing by the sweeper. We do this
1101         // asynchronously because it can take non-trivial time.
1102         prepareFreeWorkbufs()
1103
1104         // Free stack spans. This must be done between GC cycles.
1105         systemstack(freeStackSpans)
1106
1107         // Ensure all mcaches are flushed. Each P will flush its own
1108         // mcache before allocating, but idle Ps may not. Since this
1109         // is necessary to sweep all spans, we need to ensure all
1110         // mcaches are flushed before we start the next GC cycle.
1111         //
1112         // While we're here, flush the page cache for idle Ps to avoid
1113         // having pages get stuck on them. These pages are hidden from
1114         // the scavenger, so in small idle heaps a significant amount
1115         // of additional memory might be held onto.
1116         //
1117         // Also, flush the pinner cache, to avoid leaking that memory
1118         // indefinitely.
1119         systemstack(func() {
1120                 forEachP(func(pp *p) {
1121                         pp.mcache.prepareForSweep()
1122                         if pp.status == _Pidle {
1123                                 systemstack(func() {
1124                                         lock(&mheap_.lock)
1125                                         pp.pcache.flush(&mheap_.pages)
1126                                         unlock(&mheap_.lock)
1127                                 })
1128                         }
1129                         pp.pinnerCache = nil
1130                 })
1131         })
1132         if sl.valid {
1133                 // Now that we've swept stale spans in mcaches, they don't
1134                 // count against unswept spans.
1135                 //
1136                 // Note: this sweepLocker may not be valid if sweeping had
1137                 // already completed during the STW. See the corresponding
1138                 // begin() call that produced sl.
1139                 sweep.active.end(sl)
1140         }
1141
1142         // Print gctrace before dropping worldsema. As soon as we drop
1143         // worldsema another cycle could start and smash the stats
1144         // we're trying to print.
1145         if debug.gctrace > 0 {
1146                 util := int(memstats.gc_cpu_fraction * 100)
1147
1148                 var sbuf [24]byte
1149                 printlock()
1150                 print("gc ", memstats.numgc,
1151                         " @", string(itoaDiv(sbuf[:], uint64(work.tSweepTerm-runtimeInitTime)/1e6, 3)), "s ",
1152                         util, "%: ")
1153                 prev := work.tSweepTerm
1154                 for i, ns := range []int64{work.tMark, work.tMarkTerm, work.tEnd} {
1155                         if i != 0 {
1156                                 print("+")
1157                         }
1158                         print(string(fmtNSAsMS(sbuf[:], uint64(ns-prev))))
1159                         prev = ns
1160                 }
1161                 print(" ms clock, ")
1162                 for i, ns := range []int64{
1163                         int64(work.stwprocs) * (work.tMark - work.tSweepTerm),
1164                         gcController.assistTime.Load(),
1165                         gcController.dedicatedMarkTime.Load() + gcController.fractionalMarkTime.Load(),
1166                         gcController.idleMarkTime.Load(),
1167                         markTermCpu,
1168                 } {
1169                         if i == 2 || i == 3 {
1170                                 // Separate mark time components with /.
1171                                 print("/")
1172                         } else if i != 0 {
1173                                 print("+")
1174                         }
1175                         print(string(fmtNSAsMS(sbuf[:], uint64(ns))))
1176                 }
1177                 print(" ms cpu, ",
1178                         work.heap0>>20, "->", work.heap1>>20, "->", work.heap2>>20, " MB, ",
1179                         gcController.lastHeapGoal>>20, " MB goal, ",
1180                         gcController.lastStackScan.Load()>>20, " MB stacks, ",
1181                         gcController.globalsScan.Load()>>20, " MB globals, ",
1182                         work.maxprocs, " P")
1183                 if work.userForced {
1184                         print(" (forced)")
1185                 }
1186                 print("\n")
1187                 printunlock()
1188         }
1189
1190         // Set any arena chunks that were deferred to fault.
1191         lock(&userArenaState.lock)
1192         faultList := userArenaState.fault
1193         userArenaState.fault = nil
1194         unlock(&userArenaState.lock)
1195         for _, lc := range faultList {
1196                 lc.mspan.setUserArenaChunkToFault()
1197         }
1198
1199         // Enable huge pages on some metadata if we cross a heap threshold.
1200         if gcController.heapGoal() > minHeapForMetadataHugePages {
1201                 mheap_.enableMetadataHugePages()
1202         }
1203
1204         semrelease(&worldsema)
1205         semrelease(&gcsema)
1206         // Careful: another GC cycle may start now.
1207
1208         releasem(mp)
1209         mp = nil
1210
1211         // now that gc is done, kick off finalizer thread if needed
1212         if !concurrentSweep {
1213                 // give the queued finalizers, if any, a chance to run
1214                 Gosched()
1215         }
1216 }
1217
1218 // gcBgMarkStartWorkers prepares background mark worker goroutines. These
1219 // goroutines will not run until the mark phase, but they must be started while
1220 // the work is not stopped and from a regular G stack. The caller must hold
1221 // worldsema.
1222 func gcBgMarkStartWorkers() {
1223         // Background marking is performed by per-P G's. Ensure that each P has
1224         // a background GC G.
1225         //
1226         // Worker Gs don't exit if gomaxprocs is reduced. If it is raised
1227         // again, we can reuse the old workers; no need to create new workers.
1228         for gcBgMarkWorkerCount < gomaxprocs {
1229                 go gcBgMarkWorker()
1230
1231                 notetsleepg(&work.bgMarkReady, -1)
1232                 noteclear(&work.bgMarkReady)
1233                 // The worker is now guaranteed to be added to the pool before
1234                 // its P's next findRunnableGCWorker.
1235
1236                 gcBgMarkWorkerCount++
1237         }
1238 }
1239
1240 // gcBgMarkPrepare sets up state for background marking.
1241 // Mutator assists must not yet be enabled.
1242 func gcBgMarkPrepare() {
1243         // Background marking will stop when the work queues are empty
1244         // and there are no more workers (note that, since this is
1245         // concurrent, this may be a transient state, but mark
1246         // termination will clean it up). Between background workers
1247         // and assists, we don't really know how many workers there
1248         // will be, so we pretend to have an arbitrarily large number
1249         // of workers, almost all of which are "waiting". While a
1250         // worker is working it decrements nwait. If nproc == nwait,
1251         // there are no workers.
1252         work.nproc = ^uint32(0)
1253         work.nwait = ^uint32(0)
1254 }
1255
1256 // gcBgMarkWorkerNode is an entry in the gcBgMarkWorkerPool. It points to a single
1257 // gcBgMarkWorker goroutine.
1258 type gcBgMarkWorkerNode struct {
1259         // Unused workers are managed in a lock-free stack. This field must be first.
1260         node lfnode
1261
1262         // The g of this worker.
1263         gp guintptr
1264
1265         // Release this m on park. This is used to communicate with the unlock
1266         // function, which cannot access the G's stack. It is unused outside of
1267         // gcBgMarkWorker().
1268         m muintptr
1269 }
1270
1271 func gcBgMarkWorker() {
1272         gp := getg()
1273
1274         // We pass node to a gopark unlock function, so it can't be on
1275         // the stack (see gopark). Prevent deadlock from recursively
1276         // starting GC by disabling preemption.
1277         gp.m.preemptoff = "GC worker init"
1278         node := new(gcBgMarkWorkerNode)
1279         gp.m.preemptoff = ""
1280
1281         node.gp.set(gp)
1282
1283         node.m.set(acquirem())
1284         notewakeup(&work.bgMarkReady)
1285         // After this point, the background mark worker is generally scheduled
1286         // cooperatively by gcController.findRunnableGCWorker. While performing
1287         // work on the P, preemption is disabled because we are working on
1288         // P-local work buffers. When the preempt flag is set, this puts itself
1289         // into _Gwaiting to be woken up by gcController.findRunnableGCWorker
1290         // at the appropriate time.
1291         //
1292         // When preemption is enabled (e.g., while in gcMarkDone), this worker
1293         // may be preempted and schedule as a _Grunnable G from a runq. That is
1294         // fine; it will eventually gopark again for further scheduling via
1295         // findRunnableGCWorker.
1296         //
1297         // Since we disable preemption before notifying bgMarkReady, we
1298         // guarantee that this G will be in the worker pool for the next
1299         // findRunnableGCWorker. This isn't strictly necessary, but it reduces
1300         // latency between _GCmark starting and the workers starting.
1301
1302         for {
1303                 // Go to sleep until woken by
1304                 // gcController.findRunnableGCWorker.
1305                 gopark(func(g *g, nodep unsafe.Pointer) bool {
1306                         node := (*gcBgMarkWorkerNode)(nodep)
1307
1308                         if mp := node.m.ptr(); mp != nil {
1309                                 // The worker G is no longer running; release
1310                                 // the M.
1311                                 //
1312                                 // N.B. it is _safe_ to release the M as soon
1313                                 // as we are no longer performing P-local mark
1314                                 // work.
1315                                 //
1316                                 // However, since we cooperatively stop work
1317                                 // when gp.preempt is set, if we releasem in
1318                                 // the loop then the following call to gopark
1319                                 // would immediately preempt the G. This is
1320                                 // also safe, but inefficient: the G must
1321                                 // schedule again only to enter gopark and park
1322                                 // again. Thus, we defer the release until
1323                                 // after parking the G.
1324                                 releasem(mp)
1325                         }
1326
1327                         // Release this G to the pool.
1328                         gcBgMarkWorkerPool.push(&node.node)
1329                         // Note that at this point, the G may immediately be
1330                         // rescheduled and may be running.
1331                         return true
1332                 }, unsafe.Pointer(node), waitReasonGCWorkerIdle, traceBlockSystemGoroutine, 0)
1333
1334                 // Preemption must not occur here, or another G might see
1335                 // p.gcMarkWorkerMode.
1336
1337                 // Disable preemption so we can use the gcw. If the
1338                 // scheduler wants to preempt us, we'll stop draining,
1339                 // dispose the gcw, and then preempt.
1340                 node.m.set(acquirem())
1341                 pp := gp.m.p.ptr() // P can't change with preemption disabled.
1342
1343                 if gcBlackenEnabled == 0 {
1344                         println("worker mode", pp.gcMarkWorkerMode)
1345                         throw("gcBgMarkWorker: blackening not enabled")
1346                 }
1347
1348                 if pp.gcMarkWorkerMode == gcMarkWorkerNotWorker {
1349                         throw("gcBgMarkWorker: mode not set")
1350                 }
1351
1352                 startTime := nanotime()
1353                 pp.gcMarkWorkerStartTime = startTime
1354                 var trackLimiterEvent bool
1355                 if pp.gcMarkWorkerMode == gcMarkWorkerIdleMode {
1356                         trackLimiterEvent = pp.limiterEvent.start(limiterEventIdleMarkWork, startTime)
1357                 }
1358
1359                 decnwait := atomic.Xadd(&work.nwait, -1)
1360                 if decnwait == work.nproc {
1361                         println("runtime: work.nwait=", decnwait, "work.nproc=", work.nproc)
1362                         throw("work.nwait was > work.nproc")
1363                 }
1364
1365                 systemstack(func() {
1366                         // Mark our goroutine preemptible so its stack
1367                         // can be scanned. This lets two mark workers
1368                         // scan each other (otherwise, they would
1369                         // deadlock). We must not modify anything on
1370                         // the G stack. However, stack shrinking is
1371                         // disabled for mark workers, so it is safe to
1372                         // read from the G stack.
1373                         casGToWaiting(gp, _Grunning, waitReasonGCWorkerActive)
1374                         switch pp.gcMarkWorkerMode {
1375                         default:
1376                                 throw("gcBgMarkWorker: unexpected gcMarkWorkerMode")
1377                         case gcMarkWorkerDedicatedMode:
1378                                 gcDrainMarkWorkerDedicated(&pp.gcw, true)
1379                                 if gp.preempt {
1380                                         // We were preempted. This is
1381                                         // a useful signal to kick
1382                                         // everything out of the run
1383                                         // queue so it can run
1384                                         // somewhere else.
1385                                         if drainQ, n := runqdrain(pp); n > 0 {
1386                                                 lock(&sched.lock)
1387                                                 globrunqputbatch(&drainQ, int32(n))
1388                                                 unlock(&sched.lock)
1389                                         }
1390                                 }
1391                                 // Go back to draining, this time
1392                                 // without preemption.
1393                                 gcDrainMarkWorkerDedicated(&pp.gcw, false)
1394                         case gcMarkWorkerFractionalMode:
1395                                 gcDrainMarkWorkerFractional(&pp.gcw)
1396                         case gcMarkWorkerIdleMode:
1397                                 gcDrainMarkWorkerIdle(&pp.gcw)
1398                         }
1399                         casgstatus(gp, _Gwaiting, _Grunning)
1400                 })
1401
1402                 // Account for time and mark us as stopped.
1403                 now := nanotime()
1404                 duration := now - startTime
1405                 gcController.markWorkerStop(pp.gcMarkWorkerMode, duration)
1406                 if trackLimiterEvent {
1407                         pp.limiterEvent.stop(limiterEventIdleMarkWork, now)
1408                 }
1409                 if pp.gcMarkWorkerMode == gcMarkWorkerFractionalMode {
1410                         atomic.Xaddint64(&pp.gcFractionalMarkTime, duration)
1411                 }
1412
1413                 // Was this the last worker and did we run out
1414                 // of work?
1415                 incnwait := atomic.Xadd(&work.nwait, +1)
1416                 if incnwait > work.nproc {
1417                         println("runtime: p.gcMarkWorkerMode=", pp.gcMarkWorkerMode,
1418                                 "work.nwait=", incnwait, "work.nproc=", work.nproc)
1419                         throw("work.nwait > work.nproc")
1420                 }
1421
1422                 // We'll releasem after this point and thus this P may run
1423                 // something else. We must clear the worker mode to avoid
1424                 // attributing the mode to a different (non-worker) G in
1425                 // traceGoStart.
1426                 pp.gcMarkWorkerMode = gcMarkWorkerNotWorker
1427
1428                 // If this worker reached a background mark completion
1429                 // point, signal the main GC goroutine.
1430                 if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
1431                         // We don't need the P-local buffers here, allow
1432                         // preemption because we may schedule like a regular
1433                         // goroutine in gcMarkDone (block on locks, etc).
1434                         releasem(node.m.ptr())
1435                         node.m.set(nil)
1436
1437                         gcMarkDone()
1438                 }
1439         }
1440 }
1441
1442 // gcMarkWorkAvailable reports whether executing a mark worker
1443 // on p is potentially useful. p may be nil, in which case it only
1444 // checks the global sources of work.
1445 func gcMarkWorkAvailable(p *p) bool {
1446         if p != nil && !p.gcw.empty() {
1447                 return true
1448         }
1449         if !work.full.empty() {
1450                 return true // global work available
1451         }
1452         if work.markrootNext < work.markrootJobs {
1453                 return true // root scan work available
1454         }
1455         return false
1456 }
1457
1458 // gcMark runs the mark (or, for concurrent GC, mark termination)
1459 // All gcWork caches must be empty.
1460 // STW is in effect at this point.
1461 func gcMark(startTime int64) {
1462         if debug.allocfreetrace > 0 {
1463                 tracegc()
1464         }
1465
1466         if gcphase != _GCmarktermination {
1467                 throw("in gcMark expecting to see gcphase as _GCmarktermination")
1468         }
1469         work.tstart = startTime
1470
1471         // Check that there's no marking work remaining.
1472         if work.full != 0 || work.markrootNext < work.markrootJobs {
1473                 print("runtime: full=", hex(work.full), " next=", work.markrootNext, " jobs=", work.markrootJobs, " nDataRoots=", work.nDataRoots, " nBSSRoots=", work.nBSSRoots, " nSpanRoots=", work.nSpanRoots, " nStackRoots=", work.nStackRoots, "\n")
1474                 panic("non-empty mark queue after concurrent mark")
1475         }
1476
1477         if debug.gccheckmark > 0 {
1478                 // This is expensive when there's a large number of
1479                 // Gs, so only do it if checkmark is also enabled.
1480                 gcMarkRootCheck()
1481         }
1482
1483         // Drop allg snapshot. allgs may have grown, in which case
1484         // this is the only reference to the old backing store and
1485         // there's no need to keep it around.
1486         work.stackRoots = nil
1487
1488         // Clear out buffers and double-check that all gcWork caches
1489         // are empty. This should be ensured by gcMarkDone before we
1490         // enter mark termination.
1491         //
1492         // TODO: We could clear out buffers just before mark if this
1493         // has a non-negligible impact on STW time.
1494         for _, p := range allp {
1495                 // The write barrier may have buffered pointers since
1496                 // the gcMarkDone barrier. However, since the barrier
1497                 // ensured all reachable objects were marked, all of
1498                 // these must be pointers to black objects. Hence we
1499                 // can just discard the write barrier buffer.
1500                 if debug.gccheckmark > 0 {
1501                         // For debugging, flush the buffer and make
1502                         // sure it really was all marked.
1503                         wbBufFlush1(p)
1504                 } else {
1505                         p.wbBuf.reset()
1506                 }
1507
1508                 gcw := &p.gcw
1509                 if !gcw.empty() {
1510                         printlock()
1511                         print("runtime: P ", p.id, " flushedWork ", gcw.flushedWork)
1512                         if gcw.wbuf1 == nil {
1513                                 print(" wbuf1=<nil>")
1514                         } else {
1515                                 print(" wbuf1.n=", gcw.wbuf1.nobj)
1516                         }
1517                         if gcw.wbuf2 == nil {
1518                                 print(" wbuf2=<nil>")
1519                         } else {
1520                                 print(" wbuf2.n=", gcw.wbuf2.nobj)
1521                         }
1522                         print("\n")
1523                         throw("P has cached GC work at end of mark termination")
1524                 }
1525                 // There may still be cached empty buffers, which we
1526                 // need to flush since we're going to free them. Also,
1527                 // there may be non-zero stats because we allocated
1528                 // black after the gcMarkDone barrier.
1529                 gcw.dispose()
1530         }
1531
1532         // Flush scanAlloc from each mcache since we're about to modify
1533         // heapScan directly. If we were to flush this later, then scanAlloc
1534         // might have incorrect information.
1535         //
1536         // Note that it's not important to retain this information; we know
1537         // exactly what heapScan is at this point via scanWork.
1538         for _, p := range allp {
1539                 c := p.mcache
1540                 if c == nil {
1541                         continue
1542                 }
1543                 c.scanAlloc = 0
1544         }
1545
1546         // Reset controller state.
1547         gcController.resetLive(work.bytesMarked)
1548 }
1549
1550 // gcSweep must be called on the system stack because it acquires the heap
1551 // lock. See mheap for details.
1552 //
1553 // Returns true if the heap was fully swept by this function.
1554 //
1555 // The world must be stopped.
1556 //
1557 //go:systemstack
1558 func gcSweep(mode gcMode) bool {
1559         assertWorldStopped()
1560
1561         if gcphase != _GCoff {
1562                 throw("gcSweep being done but phase is not GCoff")
1563         }
1564
1565         lock(&mheap_.lock)
1566         mheap_.sweepgen += 2
1567         sweep.active.reset()
1568         mheap_.pagesSwept.Store(0)
1569         mheap_.sweepArenas = mheap_.allArenas
1570         mheap_.reclaimIndex.Store(0)
1571         mheap_.reclaimCredit.Store(0)
1572         unlock(&mheap_.lock)
1573
1574         sweep.centralIndex.clear()
1575
1576         if !concurrentSweep || mode == gcForceBlockMode {
1577                 // Special case synchronous sweep.
1578                 // Record that no proportional sweeping has to happen.
1579                 lock(&mheap_.lock)
1580                 mheap_.sweepPagesPerByte = 0
1581                 unlock(&mheap_.lock)
1582                 // Flush all mcaches.
1583                 for _, pp := range allp {
1584                         pp.mcache.prepareForSweep()
1585                 }
1586                 // Sweep all spans eagerly.
1587                 for sweepone() != ^uintptr(0) {
1588                 }
1589                 // Free workbufs eagerly.
1590                 prepareFreeWorkbufs()
1591                 for freeSomeWbufs(false) {
1592                 }
1593                 // All "free" events for this mark/sweep cycle have
1594                 // now happened, so we can make this profile cycle
1595                 // available immediately.
1596                 mProf_NextCycle()
1597                 mProf_Flush()
1598                 return true
1599         }
1600
1601         // Background sweep.
1602         lock(&sweep.lock)
1603         if sweep.parked {
1604                 sweep.parked = false
1605                 ready(sweep.g, 0, true)
1606         }
1607         unlock(&sweep.lock)
1608         return false
1609 }
1610
1611 // gcResetMarkState resets global state prior to marking (concurrent
1612 // or STW) and resets the stack scan state of all Gs.
1613 //
1614 // This is safe to do without the world stopped because any Gs created
1615 // during or after this will start out in the reset state.
1616 //
1617 // gcResetMarkState must be called on the system stack because it acquires
1618 // the heap lock. See mheap for details.
1619 //
1620 //go:systemstack
1621 func gcResetMarkState() {
1622         // This may be called during a concurrent phase, so lock to make sure
1623         // allgs doesn't change.
1624         forEachG(func(gp *g) {
1625                 gp.gcscandone = false // set to true in gcphasework
1626                 gp.gcAssistBytes = 0
1627         })
1628
1629         // Clear page marks. This is just 1MB per 64GB of heap, so the
1630         // time here is pretty trivial.
1631         lock(&mheap_.lock)
1632         arenas := mheap_.allArenas
1633         unlock(&mheap_.lock)
1634         for _, ai := range arenas {
1635                 ha := mheap_.arenas[ai.l1()][ai.l2()]
1636                 for i := range ha.pageMarks {
1637                         ha.pageMarks[i] = 0
1638                 }
1639         }
1640
1641         work.bytesMarked = 0
1642         work.initialHeapLive = gcController.heapLive.Load()
1643 }
1644
1645 // Hooks for other packages
1646
1647 var poolcleanup func()
1648 var boringCaches []unsafe.Pointer // for crypto/internal/boring
1649
1650 //go:linkname sync_runtime_registerPoolCleanup sync.runtime_registerPoolCleanup
1651 func sync_runtime_registerPoolCleanup(f func()) {
1652         poolcleanup = f
1653 }
1654
1655 //go:linkname boring_registerCache crypto/internal/boring/bcache.registerCache
1656 func boring_registerCache(p unsafe.Pointer) {
1657         boringCaches = append(boringCaches, p)
1658 }
1659
1660 func clearpools() {
1661         // clear sync.Pools
1662         if poolcleanup != nil {
1663                 poolcleanup()
1664         }
1665
1666         // clear boringcrypto caches
1667         for _, p := range boringCaches {
1668                 atomicstorep(p, nil)
1669         }
1670
1671         // Clear central sudog cache.
1672         // Leave per-P caches alone, they have strictly bounded size.
1673         // Disconnect cached list before dropping it on the floor,
1674         // so that a dangling ref to one entry does not pin all of them.
1675         lock(&sched.sudoglock)
1676         var sg, sgnext *sudog
1677         for sg = sched.sudogcache; sg != nil; sg = sgnext {
1678                 sgnext = sg.next
1679                 sg.next = nil
1680         }
1681         sched.sudogcache = nil
1682         unlock(&sched.sudoglock)
1683
1684         // Clear central defer pool.
1685         // Leave per-P pools alone, they have strictly bounded size.
1686         lock(&sched.deferlock)
1687         // disconnect cached list before dropping it on the floor,
1688         // so that a dangling ref to one entry does not pin all of them.
1689         var d, dlink *_defer
1690         for d = sched.deferpool; d != nil; d = dlink {
1691                 dlink = d.link
1692                 d.link = nil
1693         }
1694         sched.deferpool = nil
1695         unlock(&sched.deferlock)
1696 }
1697
1698 // Timing
1699
1700 // itoaDiv formats val/(10**dec) into buf.
1701 func itoaDiv(buf []byte, val uint64, dec int) []byte {
1702         i := len(buf) - 1
1703         idec := i - dec
1704         for val >= 10 || i >= idec {
1705                 buf[i] = byte(val%10 + '0')
1706                 i--
1707                 if i == idec {
1708                         buf[i] = '.'
1709                         i--
1710                 }
1711                 val /= 10
1712         }
1713         buf[i] = byte(val + '0')
1714         return buf[i:]
1715 }
1716
1717 // fmtNSAsMS nicely formats ns nanoseconds as milliseconds.
1718 func fmtNSAsMS(buf []byte, ns uint64) []byte {
1719         if ns >= 10e6 {
1720                 // Format as whole milliseconds.
1721                 return itoaDiv(buf, ns/1e6, 0)
1722         }
1723         // Format two digits of precision, with at most three decimal places.
1724         x := ns / 1e3
1725         if x == 0 {
1726                 buf[0] = '0'
1727                 return buf[:1]
1728         }
1729         dec := 3
1730         for x >= 100 {
1731                 x /= 10
1732                 dec--
1733         }
1734         return itoaDiv(buf, x, dec)
1735 }
1736
1737 // Helpers for testing GC.
1738
1739 // gcTestMoveStackOnNextCall causes the stack to be moved on a call
1740 // immediately following the call to this. It may not work correctly
1741 // if any other work appears after this call (such as returning).
1742 // Typically the following call should be marked go:noinline so it
1743 // performs a stack check.
1744 //
1745 // In rare cases this may not cause the stack to move, specifically if
1746 // there's a preemption between this call and the next.
1747 func gcTestMoveStackOnNextCall() {
1748         gp := getg()
1749         gp.stackguard0 = stackForceMove
1750 }
1751
1752 // gcTestIsReachable performs a GC and returns a bit set where bit i
1753 // is set if ptrs[i] is reachable.
1754 func gcTestIsReachable(ptrs ...unsafe.Pointer) (mask uint64) {
1755         // This takes the pointers as unsafe.Pointers in order to keep
1756         // them live long enough for us to attach specials. After
1757         // that, we drop our references to them.
1758
1759         if len(ptrs) > 64 {
1760                 panic("too many pointers for uint64 mask")
1761         }
1762
1763         // Block GC while we attach specials and drop our references
1764         // to ptrs. Otherwise, if a GC is in progress, it could mark
1765         // them reachable via this function before we have a chance to
1766         // drop them.
1767         semacquire(&gcsema)
1768
1769         // Create reachability specials for ptrs.
1770         specials := make([]*specialReachable, len(ptrs))
1771         for i, p := range ptrs {
1772                 lock(&mheap_.speciallock)
1773                 s := (*specialReachable)(mheap_.specialReachableAlloc.alloc())
1774                 unlock(&mheap_.speciallock)
1775                 s.special.kind = _KindSpecialReachable
1776                 if !addspecial(p, &s.special) {
1777                         throw("already have a reachable special (duplicate pointer?)")
1778                 }
1779                 specials[i] = s
1780                 // Make sure we don't retain ptrs.
1781                 ptrs[i] = nil
1782         }
1783
1784         semrelease(&gcsema)
1785
1786         // Force a full GC and sweep.
1787         GC()
1788
1789         // Process specials.
1790         for i, s := range specials {
1791                 if !s.done {
1792                         printlock()
1793                         println("runtime: object", i, "was not swept")
1794                         throw("IsReachable failed")
1795                 }
1796                 if s.reachable {
1797                         mask |= 1 << i
1798                 }
1799                 lock(&mheap_.speciallock)
1800                 mheap_.specialReachableAlloc.free(unsafe.Pointer(s))
1801                 unlock(&mheap_.speciallock)
1802         }
1803
1804         return mask
1805 }
1806
1807 // gcTestPointerClass returns the category of what p points to, one of:
1808 // "heap", "stack", "data", "bss", "other". This is useful for checking
1809 // that a test is doing what it's intended to do.
1810 //
1811 // This is nosplit simply to avoid extra pointer shuffling that may
1812 // complicate a test.
1813 //
1814 //go:nosplit
1815 func gcTestPointerClass(p unsafe.Pointer) string {
1816         p2 := uintptr(noescape(p))
1817         gp := getg()
1818         if gp.stack.lo <= p2 && p2 < gp.stack.hi {
1819                 return "stack"
1820         }
1821         if base, _, _ := findObject(p2, 0, 0); base != 0 {
1822                 return "heap"
1823         }
1824         for _, datap := range activeModules() {
1825                 if datap.data <= p2 && p2 < datap.edata || datap.noptrdata <= p2 && p2 < datap.enoptrdata {
1826                         return "data"
1827                 }
1828                 if datap.bss <= p2 && p2 < datap.ebss || datap.noptrbss <= p2 && p2 <= datap.enoptrbss {
1829                         return "bss"
1830                 }
1831         }
1832         KeepAlive(p)
1833         return "other"
1834 }