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