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