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