mgc.go 55.8 KB
Newer Older
1 2 3 4 5 6 7 8 9
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// TODO(rsc): The code having to do with the heap bitmap needs very serious cleanup.
// It has gotten completely out of control.

// Garbage collector (GC).
//
10 11
// The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple
// GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is
12 13
// non-generational and non-compacting. Allocation is done using size segregated per P allocation
// areas to minimize fragmentation while eliminating locks in the common case.
14
//
15 16 17 18 19 20
// The algorithm decomposes into several steps.
// This is a high level description of the algorithm being used. For an overview of GC a good
// place to start is Richard Jones' gchandbook.org.
//
// The algorithm's intellectual heritage includes Dijkstra's on-the-fly algorithm, see
// Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, and E. F. M. Steffens. 1978.
21
// On-the-fly garbage collection: an exercise in cooperation. Commun. ACM 21, 11 (November 1978),
22
// 966-975.
23 24 25
// For journal quality proofs that these steps are complete, correct, and terminate see
// Hudson, R., and Moss, J.E.B. Copying Garbage Collection without stopping the world.
// Concurrency and Computation: Practice and Experience 15(3-5), 2003.
26
//
27 28 29 30 31
//  0. Set phase = GCscan from GCoff.
//  1. Wait for all P's to acknowledge phase change.
//         At this point all goroutines have passed through a GC safepoint and
//         know we are in the GCscan phase.
//  2. GC scans all goroutine stacks, mark and enqueues all encountered pointers
32
//       (marking avoids most duplicate enqueuing but races may produce benign duplication).
33 34 35 36 37 38 39 40 41 42 43 44 45
//       Preempted goroutines are scanned before P schedules next goroutine.
//  3. Set phase = GCmark.
//  4. Wait for all P's to acknowledge phase change.
//  5. Now write barrier marks and enqueues black, grey, or white to white pointers.
//       Malloc still allocates white (non-marked) objects.
//  6. Meanwhile GC transitively walks the heap marking reachable objects.
//  7. When GC finishes marking heap, it preempts P's one-by-one and
//       retakes partial wbufs (filled by write barrier or during a stack scan of the goroutine
//       currently scheduled on the P).
//  8. Once the GC has exhausted all available marking work it sets phase = marktermination.
//  9. Wait for all P's to acknowledge phase change.
// 10. Malloc now allocates black objects, so number of unmarked reachable objects
//        monotonically decreases.
46
// 11. GC preempts P's one-by-one taking partial wbufs and marks all unmarked yet
47
//        reachable objects.
48
// 12. When GC completes a full cycle over P's and discovers no new grey
49
//         objects, (which means all reachable objects are marked) set phase = GCoff.
50 51 52 53
// 13. Wait for all P's to acknowledge phase change.
// 14. Now malloc allocates white (but sweeps spans before use).
//         Write barrier becomes nop.
// 15. GC does background sweeping, see description below.
54
// 16. When sufficient allocation has taken place replay the sequence starting at 0 above,
55 56 57 58 59 60 61 62 63 64 65
//         see discussion of GC rate below.

// Changing phases.
// Phases are changed by setting the gcphase to the next phase and possibly calling ackgcphase.
// All phase action must be benign in the presence of a change.
// Starting with GCoff
// GCoff to GCscan
//     GSscan scans stacks and globals greying them and never marks an object black.
//     Once all the P's are aware of the new phase they will scan gs on preemption.
//     This means that the scanning of preempted gs can't start until all the Ps
//     have acknowledged.
66 67 68 69 70 71
//     When a stack is scanned, this phase also installs stack barriers to
//     track how much of the stack has been active.
//     This transition enables write barriers because stack barriers
//     assume that writes to higher frames will be tracked by write
//     barriers. Technically this only needs write barriers for writes
//     to stack slots, but we enable write barriers in general.
72
// GCscan to GCmark
73 74 75 76 77
//     In GCmark, work buffers are drained until there are no more
//     pointers to scan.
//     No scanning of objects (making them black) can happen until all
//     Ps have enabled the write barrier, but that already happened in
//     the transition to GCscan.
78 79 80 81 82 83 84
// GCmark to GCmarktermination
//     The only change here is that we start allocating black so the Ps must acknowledge
//     the change before we begin the termination algorithm
// GCmarktermination to GSsweep
//     Object currently on the freelist must be marked black for this to work.
//     Are things on the free lists black or white? How does the sweep phase work?

85
// Concurrent sweep.
86
//
87 88 89
// The sweep phase proceeds concurrently with normal program execution.
// The heap is swept span-by-span both lazily (when a goroutine needs another span)
// and concurrently in a background goroutine (this helps programs that are not CPU bound).
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
// At the end of STW mark termination all spans are marked as "needs sweeping".
//
// The background sweeper goroutine simply sweeps spans one-by-one.
//
// To avoid requesting more OS memory while there are unswept spans, when a
// goroutine needs another span, it first attempts to reclaim that much memory
// by sweeping. When a goroutine needs to allocate a new small-object span, it
// sweeps small-object spans for the same object size until it frees at least
// one object. When a goroutine needs to allocate large-object span from heap,
// it sweeps spans until it frees at least that many pages into heap. There is
// one case where this may not suffice: if a goroutine sweeps and frees two
// nonadjacent one-page spans to the heap, it will allocate a new two-page
// span, but there can still be other one-page unswept spans which could be
// combined into a two-page span.
//
105 106 107 108 109 110 111 112
// It's critical to ensure that no operations proceed on unswept spans (that would corrupt
// mark bits in GC bitmap). During GC all mcaches are flushed into the central cache,
// so they are empty. When a goroutine grabs a new span into mcache, it sweeps it.
// When a goroutine explicitly frees an object or sets a finalizer, it ensures that
// the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish).
// The finalizer goroutine is kicked off only when all spans are swept.
// When the next GC starts, it sweeps all not-yet-swept spans (if any).

113 114 115 116 117 118 119 120
// GC rate.
// Next GC is after we've allocated an extra amount of memory proportional to
// the amount already in use. The proportion is controlled by GOGC environment variable
// (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M
// (this mark is tracked in next_gc variable). This keeps the GC cost in linear
// proportion to the allocation cost. Adjusting GOGC just changes the linear constant
// (and also the amount of extra memory used).

121 122 123 124 125 126 127 128 129 130 131 132 133 134
package runtime

import "unsafe"

const (
	_DebugGC         = 0
	_ConcurrentSweep = true
	_FinBlockSize    = 4 * 1024
	_RootData        = 0
	_RootBss         = 1
	_RootFinalizers  = 2
	_RootSpans       = 3
	_RootFlushCaches = 4
	_RootCount       = 5
135 136 137 138 139 140 141 142 143 144 145 146 147

	// firstStackBarrierOffset is the approximate byte offset at
	// which to place the first stack barrier from the current SP.
	// This is a lower bound on how much stack will have to be
	// re-scanned during mark termination. Subsequent barriers are
	// placed at firstStackBarrierOffset * 2^n offsets.
	//
	// For debugging, this can be set to 0, which will install a
	// stack barrier at every frame. If you do this, you may also
	// have to raise _StackMin, since the stack barrier
	// bookkeeping will use a large amount of each stack.
	firstStackBarrierOffset = 1024
	debugStackBarrier       = false
148 149
)

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
// heapminimum is the minimum heap size at which to trigger GC.
// For small heaps, this overrides the usual GOGC*live set rule.
//
// When there is a very small live set but a lot of allocation, simply
// collecting when the heap reaches GOGC*live results in many GC
// cycles and high total per-GC overhead. This minimum amortizes this
// per-GC overhead while keeping the heap reasonably small.
//
// During initialization this is set to 4MB*GOGC/100. In the case of
// GOGC==0, this will set heapminimum to 0, resulting in constant
// collection even when the heap size is small, which is useful for
// debugging.
var heapminimum uint64 = defaultHeapMinimum

// defaultHeapMinimum is the value of heapminimum for GOGC==100.
const defaultHeapMinimum = 4 << 20
166

Russ Cox's avatar
Russ Cox committed
167 168
// Initialized from $GOGC.  GOGC=off means no GC.
var gcpercent int32
169

Russ Cox's avatar
Russ Cox committed
170 171 172
func gcinit() {
	if unsafe.Sizeof(workbuf{}) != _WorkbufSize {
		throw("size of Workbuf is suboptimal")
173
	}
174

Russ Cox's avatar
Russ Cox committed
175
	work.markfor = parforalloc(_MaxGcproc)
176
	_ = setGCPercent(readgogc())
177
	for datap := &firstmoduledata; datap != nil; datap = datap.next {
178 179
		datap.gcdatamask = progToPointerMask((*byte)(unsafe.Pointer(datap.gcdata)), datap.edata-datap.data)
		datap.gcbssmask = progToPointerMask((*byte)(unsafe.Pointer(datap.gcbss)), datap.ebss-datap.bss)
180
	}
Russ Cox's avatar
Russ Cox committed
181
	memstats.next_gc = heapminimum
182 183
}

184 185 186 187 188 189 190 191 192 193 194
func readgogc() int32 {
	p := gogetenv("GOGC")
	if p == "" {
		return 100
	}
	if p == "off" {
		return -1
	}
	return int32(atoi(p))
}

195 196 197 198 199 200 201 202 203 204
// gcenable is called after the bulk of the runtime initialization,
// just before we're about to start letting user code run.
// It kicks off the background sweeper goroutine and enables GC.
func gcenable() {
	c := make(chan int, 1)
	go bgsweep(c)
	<-c
	memstats.enablegc = true // now that runtime is initialized, GC is okay
}

Russ Cox's avatar
Russ Cox committed
205 206 207 208 209
func setGCPercent(in int32) (out int32) {
	lock(&mheap_.lock)
	out = gcpercent
	if in < 0 {
		in = -1
210
	}
Russ Cox's avatar
Russ Cox committed
211
	gcpercent = in
212
	heapminimum = defaultHeapMinimum * uint64(gcpercent) / 100
Russ Cox's avatar
Russ Cox committed
213 214
	unlock(&mheap_.lock)
	return out
215 216
}

217 218 219 220 221 222 223 224 225 226
// Garbage collector phase.
// Indicates to write barrier and sychronization task to preform.
var gcphase uint32
var writeBarrierEnabled bool // compiler emits references to this in write barriers

// gcBlackenEnabled is 1 if mutator assists and background mark
// workers are allowed to blacken objects. This must only be set when
// gcphase == _GCmark.
var gcBlackenEnabled uint32

227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
// gcBlackenPromptly indicates that optimizations that may
// hide work from the global work queue should be disabled.
//
// If gcBlackenPromptly is true, per-P gcWork caches should
// be flushed immediately and new objects should be allocated black.
//
// There is a tension between allocating objects white and
// allocating them black. If white and the objects die before being
// marked they can be collected during this GC cycle. On the other
// hand allocating them black will reduce _GCmarktermination latency
// since more work is done in the mark phase. This tension is resolved
// by allocating white until the mark phase is approaching its end and
// then allocating black for the remainder of the mark phase.
var gcBlackenPromptly bool

242
const (
243
	_GCoff             = iota // GC not running; sweeping in background, write barrier disabled
244
	_GCstw                    // unused state
245
	_GCscan                   // GC collecting roots into workbufs, write barrier ENABLED
246 247 248 249 250 251 252
	_GCmark                   // GC marking from workbufs, write barrier ENABLED
	_GCmarktermination        // GC mark termination: allocate black, P's help GC, write barrier ENABLED
)

//go:nosplit
func setGCPhase(x uint32) {
	atomicstore(&gcphase, x)
253
	writeBarrierEnabled = gcphase == _GCmark || gcphase == _GCmarktermination || gcphase == _GCscan
254 255
}

256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
// gcMarkWorkerMode represents the mode that a concurrent mark worker
// should operate in.
//
// Concurrent marking happens through four different mechanisms. One
// is mutator assists, which happen in response to allocations and are
// not scheduled. The other three are variations in the per-P mark
// workers and are distinguished by gcMarkWorkerMode.
type gcMarkWorkerMode int

const (
	// gcMarkWorkerDedicatedMode indicates that the P of a mark
	// worker is dedicated to running that mark worker. The mark
	// worker should run without preemption until concurrent mark
	// is done.
	gcMarkWorkerDedicatedMode gcMarkWorkerMode = iota

	// gcMarkWorkerFractionalMode indicates that a P is currently
	// running the "fractional" mark worker. The fractional worker
	// is necessary when GOMAXPROCS*gcGoalUtilization is not an
	// integer. The fractional worker should run until it is
	// preempted and will be scheduled to pick up the fractional
	// part of GOMAXPROCS*gcGoalUtilization.
	gcMarkWorkerFractionalMode

	// gcMarkWorkerIdleMode indicates that a P is running the mark
	// worker because it has nothing else to do. The idle worker
	// should run until it is preempted and account its time
	// against gcController.idleMarkTime.
	gcMarkWorkerIdleMode
)

287 288 289 290 291 292 293 294 295
// gcController implements the GC pacing controller that determines
// when to trigger concurrent garbage collection and how much marking
// work to do in mutator assists and background marking.
//
// It uses a feedback control algorithm to adjust the memstats.next_gc
// trigger based on the heap growth and GC CPU utilization each cycle.
// This algorithm optimizes for heap growth to match GOGC and for CPU
// utilization between assist and background marking to be 25% of
// GOMAXPROCS. The high-level design of this algorithm is documented
296
// at https://golang.org/s/go15gcpacing.
297
var gcController = gcControllerState{
298 299
	// Initial trigger ratio guess.
	triggerRatio: 7 / 8.0,
300
}
301 302 303 304 305 306

type gcControllerState struct {
	// scanWork is the total scan work performed this cycle. This
	// is updated atomically during the cycle. Updates may be
	// batched arbitrarily, since the value is only read at the
	// end of the cycle.
307 308 309 310
	//
	// Currently this is the bytes of heap scanned. For most uses,
	// this is an opaque unit of work, but for estimation the
	// definition is important.
311
	scanWork int64
312

313 314 315 316 317 318 319
	// bgScanCredit is the scan work credit accumulated by the
	// concurrent background scan. This credit is accumulated by
	// the background scan and stolen by mutator assists. This is
	// updated atomically. Updates occur in bounded batches, since
	// it is both written and read throughout the cycle.
	bgScanCredit int64

320 321 322 323 324 325
	// assistTime is the nanoseconds spent in mutator assists
	// during this cycle. This is updated atomically. Updates
	// occur in bounded batches, since it is both written and read
	// throughout the cycle.
	assistTime int64

326 327 328 329 330 331 332 333 334 335
	// dedicatedMarkTime is the nanoseconds spent in dedicated
	// mark workers during this cycle. This is updated atomically
	// at the end of the concurrent mark phase.
	dedicatedMarkTime int64

	// fractionalMarkTime is the nanoseconds spent in the
	// fractional mark worker during this cycle. This is updated
	// atomically throughout the cycle and will be up-to-date if
	// the fractional mark worker is not currently running.
	fractionalMarkTime int64
336 337

	// idleMarkTime is the nanoseconds spent in idle marking
338
	// during this cycle. This is updated atomically throughout
339 340 341 342 343 344 345
	// the cycle.
	idleMarkTime int64

	// bgMarkStartTime is the absolute start time in nanoseconds
	// that the background mark phase started.
	bgMarkStartTime int64

346 347 348 349
	// heapGoal is the goal memstats.heap_live for when this cycle
	// ends. This is computed at the beginning of each cycle.
	heapGoal uint64

350 351 352 353 354 355
	// dedicatedMarkWorkersNeeded is the number of dedicated mark
	// workers that need to be started. This is computed at the
	// beginning of each cycle and decremented atomically as
	// dedicated mark workers get started.
	dedicatedMarkWorkersNeeded int64

356 357 358 359
	// assistRatio is the ratio of allocated bytes to scan work
	// that should be performed by mutator assists. This is
	// computed at the beginning of each cycle.
	assistRatio float64
360

361 362 363 364 365 366 367 368 369
	// fractionalUtilizationGoal is the fraction of wall clock
	// time that should be spent in the fractional mark worker.
	// For example, if the overall mark utilization goal is 25%
	// and GOMAXPROCS is 6, one P will be a dedicated mark worker
	// and this will be set to 0.5 so that 50% of the time some P
	// is in a fractional mark worker. This is computed at the
	// beginning of each cycle.
	fractionalUtilizationGoal float64

370 371 372 373 374 375 376
	// triggerRatio is the heap growth ratio at which the garbage
	// collection cycle should start. E.g., if this is 0.6, then
	// GC should start when the live heap has reached 1.6 times
	// the heap size marked by the previous cycle. This is updated
	// at the end of of each cycle.
	triggerRatio float64

377 378 379 380
	// reviseTimer is a timer that triggers periodic revision of
	// control variables during the cycle.
	reviseTimer timer

381 382
	_ [_CacheLineSize]byte

383 384 385 386 387
	// fractionalMarkWorkersNeeded is the number of fractional
	// mark workers that need to be started. This is either 0 or
	// 1. This is potentially updated atomically at every
	// scheduling point (hence it gets its own cache line).
	fractionalMarkWorkersNeeded int64
388 389

	_ [_CacheLineSize]byte
390 391
}

392
// startCycle resets the GC controller's state and computes estimates
393
// for a new GC cycle. The caller must hold worldsema.
394 395
func (c *gcControllerState) startCycle() {
	c.scanWork = 0
396
	c.bgScanCredit = 0
397
	c.assistTime = 0
398 399
	c.dedicatedMarkTime = 0
	c.fractionalMarkTime = 0
400
	c.idleMarkTime = 0
401 402 403 404 405 406 407 408

	// If this is the first GC cycle or we're operating on a very
	// small heap, fake heap_marked so it looks like next_gc is
	// the appropriate growth from heap_marked, even though the
	// real heap_marked may not have a meaningful value (on the
	// first cycle) or may be much smaller (resulting in a large
	// error response).
	if memstats.next_gc <= heapminimum {
409
		memstats.heap_marked = uint64(float64(memstats.next_gc) / (1 + c.triggerRatio))
410
		memstats.heap_reachable = memstats.heap_marked
411 412
	}

413
	// Compute the heap goal for this cycle
414
	c.heapGoal = memstats.heap_reachable + memstats.heap_reachable*uint64(gcpercent)/100
415

416 417 418 419 420 421 422 423 424 425 426
	// Compute the total mark utilization goal and divide it among
	// dedicated and fractional workers.
	totalUtilizationGoal := float64(gomaxprocs) * gcGoalUtilization
	c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal)
	c.fractionalUtilizationGoal = totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)
	if c.fractionalUtilizationGoal > 0 {
		c.fractionalMarkWorkersNeeded = 1
	} else {
		c.fractionalMarkWorkersNeeded = 0
	}

427 428 429 430 431 432 433 434
	// Clear per-P state
	for _, p := range &allp {
		if p == nil {
			break
		}
		p.gcAssistTime = 0
	}

435 436 437 438 439 440 441 442 443 444 445
	// Compute initial values for controls that are updated
	// throughout the cycle.
	c.revise()

	// Set up a timer to revise periodically
	c.reviseTimer.f = func(interface{}, uintptr) {
		gcController.revise()
	}
	c.reviseTimer.period = 10 * 1000 * 1000
	c.reviseTimer.when = nanotime() + c.reviseTimer.period
	addtimer(&c.reviseTimer)
446 447
}

448 449 450 451
// revise updates the assist ratio during the GC cycle to account for
// improved estimates. This should be called periodically during
// concurrent mark.
func (c *gcControllerState) revise() {
452 453 454 455 456 457 458 459 460 461
	// Compute the expected scan work. This is a strict upper
	// bound on the possible scan work in the current heap.
	//
	// You might consider dividing this by 2 (or by
	// (100+GOGC)/100) to counter this over-estimation, but
	// benchmarks show that this has almost no effect on mean
	// mutator utilization, heap size, or assist time and it
	// introduces the danger of under-estimating and letting the
	// mutator outpace the garbage collector.
	scanWorkExpected := memstats.heap_scan
462 463 464 465

	// Compute the mutator assist ratio so by the time the mutator
	// allocates the remaining heap bytes up to next_gc, it will
	// have done (or stolen) the estimated amount of scan work.
466
	heapDistance := int64(c.heapGoal) - int64(work.initialHeapLive)
467 468 469 470 471 472 473 474 475 476 477 478
	if heapDistance <= 1024*1024 {
		// heapDistance can be negative if GC start is delayed
		// or if the allocation that pushed heap_live over
		// next_gc is large or if the trigger is really close
		// to GOGC. We don't want to set the assist negative
		// (or divide by zero, or set it really high), so
		// enforce a minimum on the distance.
		heapDistance = 1024 * 1024
	}
	c.assistRatio = float64(scanWorkExpected) / float64(heapDistance)
}

479 480 481
// endCycle updates the GC controller state at the end of the
// concurrent part of the GC cycle.
func (c *gcControllerState) endCycle() {
482 483
	h_t := c.triggerRatio // For debugging

484 485 486 487 488 489 490
	// Proportional response gain for the trigger controller. Must
	// be in [0, 1]. Lower values smooth out transient effects but
	// take longer to respond to phase changes. Higher values
	// react to phase changes quickly, but are more affected by
	// transient changes. Values near 1 may be unstable.
	const triggerGain = 0.5

491 492 493
	// Stop the revise timer
	deltimer(&c.reviseTimer)

494 495 496 497 498 499 500 501 502 503 504 505
	// Compute next cycle trigger ratio. First, this computes the
	// "error" for this cycle; that is, how far off the trigger
	// was from what it should have been, accounting for both heap
	// growth and GC CPU utilization. We computing the actual heap
	// growth during this cycle and scale that by how far off from
	// the goal CPU utilization we were (to estimate the heap
	// growth if we had the desired CPU utilization). The
	// difference between this estimate and the GOGC-based goal
	// heap growth is the error.
	goalGrowthRatio := float64(gcpercent) / 100
	actualGrowthRatio := float64(memstats.heap_live)/float64(memstats.heap_marked) - 1
	duration := nanotime() - c.bgMarkStartTime
506 507 508 509 510 511

	// Assume background mark hit its utilization goal.
	utilization := gcGoalUtilization
	// Add assist utilization; avoid divide by zero.
	if duration > 0 {
		utilization += float64(c.assistTime) / float64(duration*int64(gomaxprocs))
512
	}
513

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
	triggerError := goalGrowthRatio - c.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-c.triggerRatio)

	// Finally, we adjust the trigger for next time by this error,
	// damped by the proportional gain.
	c.triggerRatio += triggerGain * triggerError
	if c.triggerRatio < 0 {
		// This can happen if the mutator is allocating very
		// quickly or the GC is scanning very slowly.
		c.triggerRatio = 0
	} else if c.triggerRatio > goalGrowthRatio*0.95 {
		// Ensure there's always a little margin so that the
		// mutator assist ratio isn't infinity.
		c.triggerRatio = goalGrowthRatio * 0.95
	}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
	if debug.gcpacertrace > 0 {
		// Print controller state in terms of the design
		// document.
		H_m_prev := memstats.heap_marked
		H_T := memstats.next_gc
		h_a := actualGrowthRatio
		H_a := memstats.heap_live
		h_g := goalGrowthRatio
		H_g := int64(float64(H_m_prev) * (1 + h_g))
		u_a := utilization
		u_g := gcGoalUtilization
		W_a := c.scanWork
		print("pacer: H_m_prev=", H_m_prev,
			" h_t=", h_t, " H_T=", H_T,
			" h_a=", h_a, " H_a=", H_a,
			" h_g=", h_g, " H_g=", H_g,
			" u_a=", u_a, " u_g=", u_g,
546
			" W_a=", W_a,
547 548 549 550 551
			" goalΔ=", goalGrowthRatio-h_t,
			" actualΔ=", h_a-h_t,
			" u_a/u_g=", u_a/u_g,
			"\n")
	}
552 553
}

554
// findRunnableGCWorker returns the background mark worker for _p_ if it
555
// should be run. This must only be called when gcBlackenEnabled != 0.
556
func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
557 558
	if gcBlackenEnabled == 0 {
		throw("gcControllerState.findRunnable: blackening not enabled")
559 560 561 562
	}
	if _p_.gcBgMarkWorker == nil {
		throw("gcControllerState.findRunnable: no background mark worker")
	}
563
	if work.bgMark1.done != 0 && work.bgMark2.done != 0 {
564 565 566 567 568 569 570 571
		// Background mark is done. Don't schedule background
		// mark worker any more. (This is not just an
		// optimization. Without this we can spin scheduling
		// the background worker and having it return
		// immediately with no work to do.)
		return nil
	}

572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
	decIfPositive := func(ptr *int64) bool {
		if *ptr > 0 {
			if xaddint64(ptr, -1) >= 0 {
				return true
			}
			// We lost a race
			xaddint64(ptr, +1)
		}
		return false
	}

	if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
		// This P is now dedicated to marking until the end of
		// the concurrent mark phase.
		_p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
		// TODO(austin): This P isn't going to run anything
		// else for a while, so kick everything out of its run
		// queue.
590
	} else {
591
		if _p_.gcw.wbuf == 0 && work.full == 0 && work.partial == 0 {
592 593 594 595 596
			// No work to be done right now. This can
			// happen at the end of the mark phase when
			// there are still assists tapering off. Don't
			// bother running background mark because
			// it'll just return immediately.
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
			if work.nwait == work.nproc {
				// There are also no workers, which
				// means we've reached a completion point.
				// There may not be any workers to
				// signal it, so signal it here.
				readied := false
				if gcBlackenPromptly {
					if work.bgMark1.done == 0 {
						throw("completing mark 2, but bgMark1.done == 0")
					}
					readied = work.bgMark2.complete()
				} else {
					readied = work.bgMark1.complete()
				}
				if readied {
					// complete just called ready,
					// but we're inside the
					// scheduler. Let it know that
					// that's okay.
					resetspinning()
				}
			}
619 620 621 622 623 624 625
			return nil
		}
		if !decIfPositive(&c.fractionalMarkWorkersNeeded) {
			// No more workers are need right now.
			return nil
		}

626 627 628
		// This P has picked the token for the fractional worker.
		// Is the GC currently under or at the utilization goal?
		// If so, do more work.
629
		//
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
		// We used to check whether doing one time slice of work
		// would remain under the utilization goal, but that has the
		// effect of delaying work until the mutator has run for
		// enough time slices to pay for the work. During those time
		// slices, write barriers are enabled, so the mutator is running slower.
		// Now instead we do the work whenever we're under or at the
		// utilization work and pay for it by letting the mutator run later.
		// This doesn't change the overall utilization averages, but it
		// front loads the GC work so that the GC finishes earlier and
		// write barriers can be turned off sooner, effectively giving
		// the mutator a faster machine.
		//
		// The old, slower behavior can be restored by setting
		//	gcForcePreemptNS = forcePreemptNS.
		const gcForcePreemptNS = 0

646
		// TODO(austin): We could fast path this and basically
647
		// eliminate contention on c.fractionalMarkWorkersNeeded by
648 649 650 651 652
		// precomputing the minimum time at which it's worth
		// next scheduling the fractional worker. Then Ps
		// don't have to fight in the window where we've
		// passed that deadline and no one has started the
		// worker yet.
653
		//
654 655 656 657
		// TODO(austin): Shorter preemption interval for mark
		// worker to improve fairness and give this
		// finer-grained control over schedule?
		now := nanotime() - gcController.bgMarkStartTime
658 659 660
		then := now + gcForcePreemptNS
		timeUsed := c.fractionalMarkTime + gcForcePreemptNS
		if then > 0 && float64(timeUsed)/float64(then) > c.fractionalUtilizationGoal {
661 662 663
			// Nope, we'd overshoot the utilization goal
			xaddint64(&c.fractionalMarkWorkersNeeded, +1)
			return nil
664
		}
665
		_p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
666 667
	}

668 669 670 671 672 673 674
	// Run the background mark worker
	gp := _p_.gcBgMarkWorker
	casgstatus(gp, _Gwaiting, _Grunnable)
	if trace.enabled {
		traceGoUnpark(gp, 0)
	}
	return gp
675 676
}

677 678
// gcGoalUtilization is the goal CPU utilization for background
// marking as a fraction of GOMAXPROCS.
679 680
const gcGoalUtilization = 0.25

681 682 683 684 685 686 687
// gcBgCreditSlack is the amount of scan work credit background
// scanning can accumulate locally before updating
// gcController.bgScanCredit. Lower values give mutator assists more
// accurate accounting of background scanning. Higher values reduce
// memory contention.
const gcBgCreditSlack = 2000

688 689 690 691
// gcAssistTimeSlack is the nanoseconds of mutator assist time that
// can accumulate on a P before updating gcController.assistTime.
const gcAssistTimeSlack = 5000

Russ Cox's avatar
Russ Cox committed
692 693 694 695 696 697
// Determine whether to initiate a GC.
// If the GC is already working no need to trigger another one.
// This should establish a feedback loop where if the GC does not
// have sufficient time to complete then more memory will be
// requested from the OS increasing heap size thus allow future
// GCs more time to complete.
698
// memstat.heap_live read has a benign race.
Russ Cox's avatar
Russ Cox committed
699 700 701
// A false negative simple does not start a GC, a false positive
// will start a GC needlessly. Neither have correctness issues.
func shouldtriggergc() bool {
702
	return memstats.heap_live >= memstats.next_gc && atomicloaduint(&bggc.working) == 0
703 704
}

705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
// bgMarkSignal synchronizes the GC coordinator and background mark workers.
type bgMarkSignal struct {
	// Workers race to cas to 1. Winner signals coordinator.
	done uint32
	// Coordinator to wake up.
	lock mutex
	g    *g
	wake bool
}

func (s *bgMarkSignal) wait() {
	lock(&s.lock)
	if s.wake {
		// Wakeup already happened
		unlock(&s.lock)
	} else {
		s.g = getg()
		goparkunlock(&s.lock, "mark wait (idle)", traceEvGoBlock, 1)
	}
	s.wake = false
	s.g = nil
}

// complete signals the completion of this phase of marking. This can
// be called multiple times during a cycle; only the first call has
// any effect.
731 732 733 734
//
// The caller should arrange to deschedule itself as soon as possible
// after calling complete in order to let the coordinator goroutine
// run.
735
func (s *bgMarkSignal) complete() bool {
736 737 738 739 740 741 742 743 744 745 746
	if cas(&s.done, 0, 1) {
		// This is the first worker to reach this completion point.
		// Signal the main GC goroutine.
		lock(&s.lock)
		if s.g == nil {
			// It hasn't parked yet.
			s.wake = true
		} else {
			ready(s.g, 0)
		}
		unlock(&s.lock)
747
		return true
748
	}
749
	return false
750 751 752 753 754 755
}

func (s *bgMarkSignal) clear() {
	s.done = 0
}

Russ Cox's avatar
Russ Cox committed
756
var work struct {
Russ Cox's avatar
Russ Cox committed
757 758 759 760 761 762 763 764 765 766
	full    uint64                // lock-free list of full blocks workbuf
	empty   uint64                // lock-free list of empty blocks workbuf
	partial uint64                // lock-free list of partially filled blocks workbuf
	pad0    [_CacheLineSize]uint8 // prevents false-sharing between full/empty and nproc/nwait
	nproc   uint32
	tstart  int64
	nwait   uint32
	ndone   uint32
	alldone note
	markfor *parfor
767

768 769
	bgMarkReady note   // signal background mark worker has started
	bgMarkDone  uint32 // cas to 1 when at a background mark completion point
770
	// Background mark completion signaling
771 772 773 774

	// Coordination for the 2 parts of the mark phase.
	bgMark1 bgMarkSignal
	bgMark2 bgMarkSignal
775

Russ Cox's avatar
Russ Cox committed
776 777
	// Copy of mheap.allspans for marker or sweeper.
	spans []*mspan
778 779 780 781

	// totaltime is the CPU nanoseconds spent in GC since the
	// program started if debug.gctrace > 0.
	totaltime int64
782 783 784 785 786 787 788 789 790 791 792 793 794

	// bytesMarked is the number of bytes marked this cycle. This
	// includes bytes blackened in scanned objects, noscan objects
	// that go straight to black, and permagrey objects scanned by
	// markroot during the concurrent scan phase. This is updated
	// atomically during the cycle. Updates may be batched
	// arbitrarily, since the value is only read at the end of the
	// cycle.
	//
	// Because of benign races during marking, this number may not
	// be the exact number of marked bytes, but it should be very
	// close.
	bytesMarked uint64
795 796 797 798

	// initialHeapLive is the value of memstats.heap_live at the
	// beginning of this GC cycle.
	initialHeapLive uint64
799 800
}

801 802 803
// GC runs a garbage collection and blocks the caller until the
// garbage collection is complete. It may also block the entire
// program.
Russ Cox's avatar
Russ Cox committed
804
func GC() {
Russ Cox's avatar
Russ Cox committed
805
	startGC(gcForceBlockMode)
806 807
}

Russ Cox's avatar
Russ Cox committed
808 809 810 811 812 813 814
const (
	gcBackgroundMode = iota // concurrent GC
	gcForceMode             // stop-the-world GC now
	gcForceBlockMode        // stop-the-world GC now and wait for sweep
)

func startGC(mode int) {
Russ Cox's avatar
Russ Cox committed
815 816
	// The gc is turned off (via enablegc) until the bootstrap has completed.
	// Also, malloc gets called in the guts of a number of libraries that might be
817
	// holding locks. To avoid deadlocks during stop-the-world, don't bother
Russ Cox's avatar
Russ Cox committed
818 819 820
	// trying to run gc while holding a lock. The next mallocgc without a lock
	// will do the gc instead.
	mp := acquirem()
821
	if gp := getg(); gp == mp.g0 || mp.locks > 1 || mp.preemptoff != "" || !memstats.enablegc || panicking != 0 || gcpercent < 0 {
Russ Cox's avatar
Russ Cox committed
822
		releasem(mp)
823 824
		return
	}
Russ Cox's avatar
Russ Cox committed
825 826
	releasem(mp)
	mp = nil
827

828 829 830 831 832 833
	if debug.gcstoptheworld == 1 {
		mode = gcForceMode
	} else if debug.gcstoptheworld == 2 {
		mode = gcForceBlockMode
	}

Russ Cox's avatar
Russ Cox committed
834 835 836 837
	if mode != gcBackgroundMode {
		// special synchronous cases
		gc(mode)
		return
838
	}
Russ Cox's avatar
Russ Cox committed
839 840

	// trigger concurrent GC
841
	readied := false
Russ Cox's avatar
Russ Cox committed
842 843 844 845
	lock(&bggc.lock)
	if !bggc.started {
		bggc.working = 1
		bggc.started = true
846
		readied = true
Russ Cox's avatar
Russ Cox committed
847 848 849
		go backgroundgc()
	} else if bggc.working == 0 {
		bggc.working = 1
850 851
		readied = true
		ready(bggc.g, 0)
Russ Cox's avatar
Russ Cox committed
852 853
	}
	unlock(&bggc.lock)
854 855 856 857 858
	if readied {
		// This G just started or ready()d the GC goroutine.
		// Switch directly to it by yielding.
		Gosched()
	}
859 860
}

861 862 863 864 865 866 867 868
// State of the background concurrent GC goroutine.
var bggc struct {
	lock    mutex
	g       *g
	working uint
	started bool
}

Russ Cox's avatar
Russ Cox committed
869 870 871 872
// backgroundgc is running in a goroutine and does the concurrent GC work.
// bggc holds the state of the backgroundgc.
func backgroundgc() {
	bggc.g = getg()
873
	for {
Russ Cox's avatar
Russ Cox committed
874
		gc(gcBackgroundMode)
Russ Cox's avatar
Russ Cox committed
875 876
		lock(&bggc.lock)
		bggc.working = 0
877
		goparkunlock(&bggc.lock, "Concurrent GC wait", traceEvGoBlock, 1)
878 879 880
	}
}

Russ Cox's avatar
Russ Cox committed
881
func gc(mode int) {
882 883 884
	// debug.gctrace variables
	var stwprocs, maxprocs int32
	var tSweepTerm, tScan, tInstallWB, tMark, tMarkTerm int64
885
	var heap0, heap1, heap2, heapGoal uint64
886

887 888 889
	// memstats statistics
	var now, pauseStart, pauseNS int64

Russ Cox's avatar
Russ Cox committed
890
	// Ok, we're doing it!  Stop everybody else
Russ Cox's avatar
Russ Cox committed
891
	semacquire(&worldsema, false)
892

Russ Cox's avatar
Russ Cox committed
893
	// Pick up the remaining unswept/not being swept spans concurrently
894
	//
895 896 897 898 899
	// This shouldn't happen if we're being invoked in background
	// mode since proportional sweep should have just finished
	// sweeping everything, but rounding errors, etc, may leave a
	// few spans unswept. In forced mode, this is necessary since
	// GC can be forced at any point in the sweeping cycle.
Russ Cox's avatar
Russ Cox committed
900 901
	for gosweepone() != ^uintptr(0) {
		sweep.nbgsweep++
902
	}
903

904 905 906 907
	if trace.enabled {
		traceGCStart()
	}

Russ Cox's avatar
Russ Cox committed
908
	if mode == gcBackgroundMode {
909
		gcBgMarkStartWorkers()
910
	}
911
	now = nanotime()
912 913
	if debug.gctrace > 0 {
		stwprocs, maxprocs = gcprocs(), gomaxprocs
914
		tSweepTerm = now
915
		heap0 = memstats.heap_live
916
	}
917

918
	pauseStart = now
919
	systemstack(stopTheWorldWithSema)
Russ Cox's avatar
Russ Cox committed
920
	systemstack(finishsweep_m) // finish sweep before we start concurrent scan.
921 922 923
	// clearpools before we start the GC. If we wait they memory will not be
	// reclaimed until the next GC cycle.
	clearpools()
Russ Cox's avatar
Russ Cox committed
924

925
	gcResetMarkState()
926

Russ Cox's avatar
Russ Cox committed
927
	if mode == gcBackgroundMode { // Do as much work concurrently as possible
928
		gcController.startCycle()
929
		heapGoal = gcController.heapGoal
930

Russ Cox's avatar
Russ Cox committed
931
		systemstack(func() {
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
			// Enter scan phase. This enables write
			// barriers to track changes to stack frames
			// above the stack barrier.
			//
			// TODO: This has evolved to the point where
			// we carefully ensure invariants we no longer
			// depend on. Either:
			//
			// 1) Enable full write barriers for the scan,
			// but eliminate the ragged barrier below
			// (since the start the world ensures all Ps
			// have observed the write barrier enable) and
			// consider draining during the scan.
			//
			// 2) Only enable write barriers for writes to
			// the stack at this point, and then enable
			// write barriers for heap writes when we
			// enter the mark phase. This means we cannot
			// drain in the scan phase and must perform a
			// ragged barrier to ensure all Ps have
			// enabled heap write barriers before we drain
			// or enable assists.
			//
			// 3) Don't install stack barriers over frame
			// boundaries where there are up-pointers.
957
			setGCPhase(_GCscan)
Russ Cox's avatar
Russ Cox committed
958

959 960 961 962 963 964 965 966 967
			gcBgMarkPrepare() // Must happen before assist enable.

			// At this point all Ps have enabled the write
			// barrier, thus maintaining the no white to
			// black invariant. Enable mutator assists to
			// put back-pressure on fast allocating
			// mutators.
			atomicstore(&gcBlackenEnabled, 1)

Russ Cox's avatar
Russ Cox committed
968
			// Concurrent scan.
969
			startTheWorldWithSema()
970 971
			now = nanotime()
			pauseNS += now - pauseStart
972
			if debug.gctrace > 0 {
973
				tScan = now
974
			}
Russ Cox's avatar
Russ Cox committed
975 976
			gcscan_m()

977
			// Enter mark phase.
978 979 980
			if debug.gctrace > 0 {
				tInstallWB = nanotime()
			}
981
			setGCPhase(_GCmark)
982 983 984 985
			// Ensure all Ps have observed the phase
			// change and have write barriers enabled
			// before any blackening occurs.
			forEachP(func(*p) {})
Russ Cox's avatar
Russ Cox committed
986
		})
987
		// Concurrent mark.
988 989 990
		if debug.gctrace > 0 {
			tMark = nanotime()
		}
991

992 993 994
		// Enable background mark workers and wait for
		// background mark completion.
		gcController.bgMarkStartTime = nanotime()
995
		work.bgMark1.clear()
996 997 998 999 1000 1001 1002 1003 1004 1005
		work.bgMark1.wait()

		// The global work list is empty, but there can still be work
		// sitting in the per-P work caches and there can be more
		// objects reachable from global roots since they don't have write
		// barriers. Rescan some roots and flush work caches.
		systemstack(func() {
			// rescan global data and bss.
			markroot(nil, _RootData)
			markroot(nil, _RootBss)
1006 1007 1008 1009 1010 1011 1012

			// Disallow caching workbufs.
			gcBlackenPromptly = true

			// Flush all currently cached workbufs. This
			// also forces any remaining background
			// workers out of their loop.
1013 1014 1015 1016 1017
			forEachP(func(_p_ *p) {
				_p_.gcw.dispose()
			})
		})

1018 1019 1020
		// Wait for this more aggressive background mark to complete.
		work.bgMark2.clear()
		work.bgMark2.wait()
1021 1022

		// Begin mark termination.
1023
		now = nanotime()
1024
		if debug.gctrace > 0 {
1025
			tMarkTerm = now
1026
		}
1027
		pauseStart = now
1028
		systemstack(stopTheWorldWithSema)
1029 1030 1031
		// The gcphase is _GCmark, it will transition to _GCmarktermination
		// below. The important thing is that the wb remains active until
		// all marking is complete. This includes writes made by the GC.
1032

1033 1034 1035 1036 1037
		// Flush the gcWork caches. This must be done before
		// endCycle since endCycle depends on statistics kept
		// in these caches.
		gcFlushGCWork()

1038
		gcController.endCycle()
Russ Cox's avatar
Russ Cox committed
1039
	} else {
Russ Cox's avatar
Russ Cox committed
1040
		// For non-concurrent GC (mode != gcBackgroundMode)
1041
		// The g stacks have not been scanned so clear g state
Russ Cox's avatar
Russ Cox committed
1042
		// such that mark termination scans all stacks.
1043
		gcResetGState()
1044 1045 1046 1047

		if debug.gctrace > 0 {
			t := nanotime()
			tScan, tInstallWB, tMark, tMarkTerm = t, t, t, t
1048
			heapGoal = heap0
1049
		}
1050 1051
	}

1052 1053
	// World is stopped.
	// Start marktermination which includes enabling the write barrier.
1054
	atomicstore(&gcBlackenEnabled, 0)
1055
	gcBlackenPromptly = false
1056
	setGCPhase(_GCmarktermination)
1057

1058
	if debug.gctrace > 0 {
1059
		heap1 = memstats.heap_live
1060 1061
	}

Russ Cox's avatar
Russ Cox committed
1062
	startTime := nanotime()
1063

1064 1065
	mp := acquirem()
	mp.preemptoff = "gcing"
1066 1067 1068 1069 1070 1071
	_g_ := getg()
	_g_.m.traceback = 2
	gp := _g_.m.curg
	casgstatus(gp, _Grunning, _Gwaiting)
	gp.waitreason = "garbage collection"

Russ Cox's avatar
Russ Cox committed
1072 1073 1074 1075 1076
	// Run gc on the g0 stack.  We do this so that the g stack
	// we're currently running on will no longer change.  Cuts
	// the root set down a bit (g0 stacks are not scanned, and
	// we don't need to scan gc's internal state).  We also
	// need to switch to g0 so we can shrink the stack.
Russ Cox's avatar
Russ Cox committed
1077
	systemstack(func() {
1078
		gcMark(startTime)
1079 1080 1081
		if debug.gctrace > 0 {
			heap2 = work.bytesMarked
		}
1082 1083 1084 1085
		if debug.gccheckmark > 0 {
			// Run a full stop-the-world mark using checkmark bits,
			// to check that we didn't forget to mark anything during
			// the concurrent mark process.
1086
			gcResetGState() // Rescan stacks
1087
			gcResetMarkState()
1088 1089 1090
			initCheckmarks()
			gcMark(startTime)
			clearCheckmarks()
Russ Cox's avatar
Russ Cox committed
1091
		}
1092 1093

		// marking is complete so we can turn the write barrier off
1094
		setGCPhase(_GCoff)
1095
		gcSweep(mode)
Russ Cox's avatar
Russ Cox committed
1096

1097 1098
		if debug.gctrace > 1 {
			startTime = nanotime()
1099 1100 1101
			// The g stacks have been scanned so
			// they have gcscanvalid==true and gcworkdone==true.
			// Reset these so that all stacks will be rescanned.
1102
			gcResetGState()
1103
			gcResetMarkState()
1104
			finishsweep_m()
1105 1106 1107 1108

			// Still in STW but gcphase is _GCoff, reset to _GCmarktermination
			// At this point all objects will be found during the gcMark which
			// does a complete STW mark and object scan.
1109
			setGCPhase(_GCmarktermination)
1110
			gcMark(startTime)
1111
			setGCPhase(_GCoff) // marking is done, turn off wb.
1112
			gcSweep(mode)
Russ Cox's avatar
Russ Cox committed
1113
		}
Russ Cox's avatar
Russ Cox committed
1114
	})
1115

1116 1117
	_g_.m.traceback = 0
	casgstatus(gp, _Gwaiting, _Grunning)
Russ Cox's avatar
Russ Cox committed
1118

Russ Cox's avatar
Russ Cox committed
1119 1120 1121
	if trace.enabled {
		traceGCDone()
	}
1122

Russ Cox's avatar
Russ Cox committed
1123 1124
	// all done
	mp.preemptoff = ""
1125

1126 1127 1128 1129
	if gcphase != _GCoff {
		throw("gc done but gcphase != _GCoff")
	}

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
	// Update timing memstats
	now, unixNow := nanotime(), unixnanotime()
	pauseNS += now - pauseStart
	atomicstore64(&memstats.last_gc, uint64(unixNow)) // must be Unix time to make sense to user
	memstats.pause_ns[memstats.numgc%uint32(len(memstats.pause_ns))] = uint64(pauseNS)
	memstats.pause_end[memstats.numgc%uint32(len(memstats.pause_end))] = uint64(unixNow)
	memstats.pause_total_ns += uint64(pauseNS)

	memstats.numgc++

1140
	systemstack(startTheWorldWithSema)
1141
	semrelease(&worldsema)
1142

Russ Cox's avatar
Russ Cox committed
1143 1144
	releasem(mp)
	mp = nil
1145

1146 1147
	if debug.gctrace > 0 {
		tEnd := nanotime()
1148 1149 1150 1151

		// Update work.totaltime
		sweepTermCpu := int64(stwprocs) * (tScan - tSweepTerm)
		scanCpu := tInstallWB - tScan
1152
		installWBCpu := int64(0)
1153 1154
		// We report idle marking time below, but omit it from
		// the overall utilization here since it's "free".
1155
		markCpu := gcController.assistTime + gcController.dedicatedMarkTime + gcController.fractionalMarkTime
1156 1157 1158 1159 1160 1161 1162 1163
		markTermCpu := int64(stwprocs) * (tEnd - tMarkTerm)
		cycleCpu := sweepTermCpu + scanCpu + installWBCpu + markCpu + markTermCpu
		work.totaltime += cycleCpu

		// Compute overall utilization
		totalCpu := sched.totaltime + (tEnd-sched.procresizetime)*int64(gomaxprocs)
		util := work.totaltime * 100 / totalCpu

1164 1165
		var sbuf [24]byte
		printlock()
1166
		print("gc ", memstats.numgc,
1167
			" @", string(itoaDiv(sbuf[:], uint64(tSweepTerm-runtimeInitTime)/1e6, 3)), "s ",
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
			util, "%: ")
		prev := tSweepTerm
		for i, ns := range []int64{tScan, tInstallWB, tMark, tMarkTerm, tEnd} {
			if i != 0 {
				print("+")
			}
			print(string(fmtNSAsMS(sbuf[:], uint64(ns-prev))))
			prev = ns
		}
		print(" ms clock, ")
		for i, ns := range []int64{sweepTermCpu, scanCpu, installWBCpu, gcController.assistTime, gcController.dedicatedMarkTime + gcController.fractionalMarkTime, gcController.idleMarkTime, markTermCpu} {
			if i == 4 || i == 5 {
				// Separate mark time components with /.
				print("/")
			} else if i != 0 {
				print("+")
			}
			print(string(fmtNSAsMS(sbuf[:], uint64(ns))))
		}
		print(" ms cpu, ",
1188
			heap0>>20, "->", heap1>>20, "->", heap2>>20, " MB, ",
1189
			heapGoal>>20, " MB goal, ",
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
			maxprocs, " P")
		if mode != gcBackgroundMode {
			print(" (forced)")
		}
		print("\n")
		printunlock()
	}
	sweep.nbgsweep = 0
	sweep.npausesweep = 0

Russ Cox's avatar
Russ Cox committed
1200 1201 1202 1203
	// now that gc is done, kick off finalizer thread if needed
	if !concurrentSweep {
		// give the queued finalizers, if any, a chance to run
		Gosched()
1204 1205 1206
	}
}

1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
// gcBgMarkStartWorkers prepares background mark worker goroutines.
// These goroutines will not run until the mark phase, but they must
// be started while the work is not stopped and from a regular G
// stack. The caller must hold worldsema.
func gcBgMarkStartWorkers() {
	// Background marking is performed by per-P G's. Ensure that
	// each P has a background GC G.
	for _, p := range &allp {
		if p == nil || p.status == _Pdead {
			break
		}
		if p.gcBgMarkWorker == nil {
			go gcBgMarkWorker(p)
			notetsleepg(&work.bgMarkReady, -1)
			noteclear(&work.bgMarkReady)
		}
	}
}

// gcBgMarkPrepare sets up state for background marking.
// Mutator assists must not yet be enabled.
func gcBgMarkPrepare() {
	// Background marking will stop when the work queues are empty
	// and there are no more workers (note that, since this is
	// concurrent, this may be a transient state, but mark
	// termination will clean it up). Between background workers
	// and assists, we don't really know how many workers there
	// will be, so we pretend to have an arbitrarily large number
	// of workers, almost all of which are "waiting". While a
	// worker is working it decrements nwait. If nproc == nwait,
	// there are no workers.
	work.nproc = ^uint32(0)
	work.nwait = ^uint32(0)

1241
	// Reset background mark completion points.
1242 1243
	work.bgMark1.done = 1
	work.bgMark2.done = 1
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
}

func gcBgMarkWorker(p *p) {
	// Register this G as the background mark worker for p.
	if p.gcBgMarkWorker != nil {
		throw("P already has a background mark worker")
	}
	gp := getg()

	mp := acquirem()
	p.gcBgMarkWorker = gp
	// After this point, the background mark worker is scheduled
	// cooperatively by gcController.findRunnable. Hence, it must
	// never be preempted, as this would put it into _Grunnable
	// and put it on a run queue. Instead, when the preempt flag
	// is set, this puts itself into _Gwaiting to be woken up by
	// gcController.findRunnable at the appropriate time.
	notewakeup(&work.bgMarkReady)
	for {
		// Go to sleep until woken by gcContoller.findRunnable.
		// We can't releasem yet since even the call to gopark
		// may be preempted.
		gopark(func(g *g, mp unsafe.Pointer) bool {
			releasem((*m)(mp))
			return true
1269
		}, unsafe.Pointer(mp), "mark worker (idle)", traceEvGoBlock, 0)
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282

		// Loop until the P dies and disassociates this
		// worker. (The P may later be reused, in which case
		// it will get a new worker.)
		if p.gcBgMarkWorker != gp {
			break
		}

		// Disable preemption so we can use the gcw. If the
		// scheduler wants to preempt us, we'll stop draining,
		// dispose the gcw, and then preempt.
		mp = acquirem()

1283 1284 1285 1286
		if gcBlackenEnabled == 0 {
			throw("gcBgMarkWorker: blackening not enabled")
		}

1287 1288
		startTime := nanotime()

1289 1290 1291 1292 1293
		decnwait := xadd(&work.nwait, -1)
		if decnwait == work.nproc {
			println("runtime: work.nwait=", decnwait, "work.nproc=", work.nproc)
			throw("work.nwait was > work.nproc")
		}
1294

1295 1296
		done := false
		switch p.gcMarkWorkerMode {
1297 1298
		default:
			throw("gcBgMarkWorker: unexpected gcMarkWorkerMode")
1299
		case gcMarkWorkerDedicatedMode:
1300
			gcDrain(&p.gcw, gcBgCreditSlack)
1301 1302 1303 1304
			// gcDrain did the xadd(&work.nwait +1) to
			// match the decrement above. It only returns
			// at a mark completion point.
			done = true
1305 1306 1307
			if !p.gcw.empty() {
				throw("gcDrain returned with buffer")
			}
1308
		case gcMarkWorkerFractionalMode, gcMarkWorkerIdleMode:
1309
			gcDrainUntilPreempt(&p.gcw, gcBgCreditSlack)
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320

			// If we are nearing the end of mark, dispose
			// of the cache promptly. We must do this
			// before signaling that we're no longer
			// working so that other workers can't observe
			// no workers and no work while we have this
			// cached, and before we compute done.
			if gcBlackenPromptly {
				p.gcw.dispose()
			}

1321 1322
			// Was this the last worker and did we run out
			// of work?
1323 1324 1325 1326 1327 1328 1329 1330
			incnwait := xadd(&work.nwait, +1)
			if incnwait > work.nproc {
				println("runtime: p.gcMarkWorkerMode=", p.gcMarkWorkerMode,
					"work.nwait=", incnwait, "work.nproc=", work.nproc)
				throw("work.nwait > work.nproc")
			}
			done = incnwait == work.nproc && work.full == 0 && work.partial == 0
		}
1331

1332 1333 1334
		// If this worker reached a background mark completion
		// point, signal the main GC goroutine.
		if done {
1335 1336 1337 1338 1339 1340 1341 1342
			if gcBlackenPromptly {
				if work.bgMark1.done == 0 {
					throw("completing mark 2, but bgMark1.done == 0")
				}
				work.bgMark2.complete()
			} else {
				work.bgMark1.complete()
			}
1343 1344 1345
		}

		duration := nanotime() - startTime
1346 1347 1348
		switch p.gcMarkWorkerMode {
		case gcMarkWorkerDedicatedMode:
			xaddint64(&gcController.dedicatedMarkTime, duration)
1349
			xaddint64(&gcController.dedicatedMarkWorkersNeeded, 1)
1350 1351 1352 1353
		case gcMarkWorkerFractionalMode:
			xaddint64(&gcController.fractionalMarkTime, duration)
			xaddint64(&gcController.fractionalMarkWorkersNeeded, 1)
		case gcMarkWorkerIdleMode:
1354 1355 1356 1357 1358
			xaddint64(&gcController.idleMarkTime, duration)
		}
	}
}

1359 1360
// gcMarkWorkAvailable returns true if executing a mark worker
// on p is potentially useful.
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
func gcMarkWorkAvailable(p *p) bool {
	if !p.gcw.empty() {
		return true
	}
	if atomicload64(&work.full) != 0 || atomicload64(&work.partial) != 0 {
		return true // global work available
	}
	return false
}

1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
// gcFlushGCWork disposes the gcWork caches of all Ps. The world must
// be stopped.
//go:nowritebarrier
func gcFlushGCWork() {
	// Gather all cached GC work. All other Ps are stopped, so
	// it's safe to manipulate their GC work caches.
	for i := 0; i < int(gomaxprocs); i++ {
		allp[i].gcw.dispose()
	}
}

1382
// gcMark runs the mark (or, for concurrent GC, mark termination)
Russ Cox's avatar
Russ Cox committed
1383 1384
// STW is in effect at this point.
//TODO go:nowritebarrier
1385
func gcMark(start_time int64) {
1386 1387 1388 1389
	if debug.allocfreetrace > 0 {
		tracegc()
	}

1390 1391 1392
	if gcphase != _GCmarktermination {
		throw("in gcMark expecting to see gcphase as _GCmarktermination")
	}
1393
	work.tstart = start_time
1394

1395
	gcCopySpans() // TODO(rlh): should this be hoisted and done only once? Right now it is done for normal marking and also for checkmarking.
1396

1397
	// Make sure the per-P gcWork caches are empty. During mark
1398 1399
	// termination, these caches can still be used temporarily,
	// but must be disposed to the global lists immediately.
1400
	gcFlushGCWork()
1401

1402 1403 1404
	work.nwait = 0
	work.ndone = 0
	work.nproc = uint32(gcprocs())
1405

1406 1407 1408 1409
	if trace.enabled {
		traceGCScanStart()
	}

1410
	parforsetup(work.markfor, work.nproc, uint32(_RootCount+allglen), false, markroot)
1411 1412 1413 1414 1415 1416 1417
	if work.nproc > 1 {
		noteclear(&work.alldone)
		helpgc(int32(work.nproc))
	}

	gchelperstart()
	parfordo(work.markfor)
1418

1419
	var gcw gcWork
1420
	gcDrain(&gcw, -1)
1421
	gcw.dispose()
1422

1423
	if work.full != 0 {
1424
		throw("work.full != 0")
1425 1426
	}
	if work.partial != 0 {
1427
		throw("work.partial != 0")
1428 1429
	}

1430 1431 1432 1433
	if work.nproc > 1 {
		notesleep(&work.alldone)
	}

1434 1435 1436 1437 1438 1439
	for i := 0; i < int(gomaxprocs); i++ {
		if allp[i].gcw.wbuf != 0 {
			throw("P has cached GC work at end of mark termination")
		}
	}

1440 1441 1442 1443
	if trace.enabled {
		traceGCScanDone()
	}

1444 1445 1446 1447 1448
	// TODO(austin): This doesn't have to be done during STW, as
	// long as we block the next GC cycle until this is done. Move
	// it after we start the world, but before dropping worldsema.
	// (See issue #11465.)
	freeStackSpans()
1449 1450

	cachestats()
1451

1452 1453 1454 1455 1456 1457
	// Compute the reachable heap size at the beginning of the
	// cycle. This is approximately the marked heap size at the
	// end (which we know) minus the amount of marked heap that
	// was allocated after marking began (which we don't know, but
	// is approximately the amount of heap that was allocated
	// since marking began).
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
	allocatedDuringCycle := memstats.heap_live - work.initialHeapLive
	if work.bytesMarked >= allocatedDuringCycle {
		memstats.heap_reachable = work.bytesMarked - allocatedDuringCycle
	} else {
		// This can happen if most of the allocation during
		// the cycle never became reachable from the heap.
		// Just set the reachable heap appropriation to 0 and
		// let the heapminimum kick in below.
		memstats.heap_reachable = 0
	}
1468 1469 1470 1471 1472 1473

	// Trigger the next GC cycle when the allocated heap has grown
	// by triggerRatio over the reachable heap size. Assume that
	// we're in steady state, so the reachable heap size is the
	// same now as it was at the beginning of the GC cycle.
	memstats.next_gc = uint64(float64(memstats.heap_reachable) * (1 + gcController.triggerRatio))
1474 1475 1476
	if memstats.next_gc < heapminimum {
		memstats.next_gc = heapminimum
	}
1477 1478 1479 1480 1481 1482 1483 1484
	if int64(memstats.next_gc) < 0 {
		print("next_gc=", memstats.next_gc, " bytesMarked=", work.bytesMarked, " heap_live=", memstats.heap_live, " initialHeapLive=", work.initialHeapLive, "\n")
		throw("next_gc underflow")
	}

	// Update other GC heap size stats.
	memstats.heap_live = work.bytesMarked
	memstats.heap_marked = work.bytesMarked
1485
	memstats.heap_scan = uint64(gcController.scanWork)
1486

1487
	if trace.enabled {
1488
		traceHeapAlloc()
1489 1490
		traceNextGC()
	}
1491
}
1492

1493
func gcSweep(mode int) {
1494 1495 1496
	if gcphase != _GCoff {
		throw("gcSweep being done but phase is not GCoff")
	}
1497
	gcCopySpans()
1498

1499
	lock(&mheap_.lock)
1500 1501 1502 1503 1504
	mheap_.sweepgen += 2
	mheap_.sweepdone = 0
	sweep.spanidx = 0
	unlock(&mheap_.lock)

1505 1506
	if !_ConcurrentSweep || mode == gcForceBlockMode {
		// Special case synchronous sweep.
1507 1508 1509 1510 1511
		// Record that no proportional sweeping has to happen.
		lock(&mheap_.lock)
		mheap_.sweepPagesPerByte = 0
		mheap_.pagesSwept = 0
		unlock(&mheap_.lock)
1512 1513 1514 1515 1516 1517
		// Sweep all spans eagerly.
		for sweepone() != ^uintptr(0) {
			sweep.npausesweep++
		}
		// Do an additional mProf_GC, because all 'free' events are now real as well.
		mProf_GC()
1518 1519
		mProf_GC()
		return
1520 1521
	}

1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
	// Account how much sweeping needs to be done before the next
	// GC cycle and set up proportional sweep statistics.
	var pagesToSweep uintptr
	for _, s := range work.spans {
		if s.state == mSpanInUse {
			pagesToSweep += s.npages
		}
	}
	heapDistance := int64(memstats.next_gc) - int64(memstats.heap_live)
	// Add a little margin so rounding errors and concurrent
	// sweep are less likely to leave pages unswept when GC starts.
	heapDistance -= 1024 * 1024
	if heapDistance < _PageSize {
		// Avoid setting the sweep ratio extremely high
		heapDistance = _PageSize
	}
	lock(&mheap_.lock)
	mheap_.sweepPagesPerByte = float64(pagesToSweep) / float64(heapDistance)
	mheap_.pagesSwept = 0
	unlock(&mheap_.lock)

1543 1544
	// Background sweep.
	lock(&sweep.lock)
1545
	if sweep.parked {
1546
		sweep.parked = false
1547
		ready(sweep.g, 0)
1548 1549
	}
	unlock(&sweep.lock)
1550
	mProf_GC()
1551
}
1552

1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
func gcCopySpans() {
	// Cache runtime.mheap_.allspans in work.spans to avoid conflicts with
	// resizing/freeing allspans.
	// New spans can be created while GC progresses, but they are not garbage for
	// this round:
	//  - new stack spans can be created even while the world is stopped.
	//  - new malloc spans can be created during the concurrent sweep
	// Even if this is stop-the-world, a concurrent exitsyscall can allocate a stack from heap.
	lock(&mheap_.lock)
	// Free the old cached mark array if necessary.
	if work.spans != nil && &work.spans[0] != &h_allspans[0] {
		sysFree(unsafe.Pointer(&work.spans[0]), uintptr(len(work.spans))*unsafe.Sizeof(work.spans[0]), &memstats.other_sys)
1565
	}
1566 1567 1568 1569
	// Cache the current array for sweeping.
	mheap_.gcspans = mheap_.allspans
	work.spans = h_allspans
	unlock(&mheap_.lock)
1570 1571
}

1572 1573
// gcResetGState resets the GC state of all G's and returns the length
// of allgs.
1574
func gcResetGState() (numgs int) {
1575 1576 1577
	// This may be called during a concurrent phase, so make sure
	// allgs doesn't change.
	lock(&allglock)
1578
	for _, gp := range allgs {
Russ Cox's avatar
Russ Cox committed
1579
		gp.gcscandone = false  // set to true in gcphasework
1580
		gp.gcscanvalid = false // stack has not been scanned
1581 1582
		gp.gcalloc = 0
		gp.gcscanwork = 0
1583
	}
1584
	numgs = len(allgs)
1585
	unlock(&allglock)
1586
	return
1587 1588
}

1589 1590 1591 1592 1593 1594 1595 1596
// gcResetMarkState resets state prior to marking (concurrent or STW).
//
// TODO(austin): Merge with gcResetGState. See issue #11427.
func gcResetMarkState() {
	work.bytesMarked = 0
	work.initialHeapLive = memstats.heap_live
}

Russ Cox's avatar
Russ Cox committed
1597
// Hooks for other packages
1598

Russ Cox's avatar
Russ Cox committed
1599 1600 1601 1602 1603
var poolcleanup func()

//go:linkname sync_runtime_registerPoolCleanup sync.runtime_registerPoolCleanup
func sync_runtime_registerPoolCleanup(f func()) {
	poolcleanup = f
1604 1605
}

Russ Cox's avatar
Russ Cox committed
1606 1607 1608 1609
func clearpools() {
	// clear sync.Pools
	if poolcleanup != nil {
		poolcleanup()
1610 1611
	}

Dmitry Vyukov's avatar
Dmitry Vyukov committed
1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
	// Clear central sudog cache.
	// Leave per-P caches alone, they have strictly bounded size.
	// Disconnect cached list before dropping it on the floor,
	// so that a dangling ref to one entry does not pin all of them.
	lock(&sched.sudoglock)
	var sg, sgnext *sudog
	for sg = sched.sudogcache; sg != nil; sg = sgnext {
		sgnext = sg.next
		sg.next = nil
	}
	sched.sudogcache = nil
	unlock(&sched.sudoglock)

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
	// Clear central defer pools.
	// Leave per-P pools alone, they have strictly bounded size.
	lock(&sched.deferlock)
	for i := range sched.deferpool {
		// disconnect cached list before dropping it on the floor,
		// so that a dangling ref to one entry does not pin all of them.
		var d, dlink *_defer
		for d = sched.deferpool[i]; d != nil; d = dlink {
			dlink = d.link
			d.link = nil
		}
		sched.deferpool[i] = nil
	}
	unlock(&sched.deferlock)

Russ Cox's avatar
Russ Cox committed
1640 1641 1642 1643 1644 1645 1646 1647 1648
	for _, p := range &allp {
		if p == nil {
			break
		}
		// clear tinyalloc pool
		if c := p.mcache; c != nil {
			c.tiny = nil
			c.tinyoffset = 0
		}
1649
	}
Russ Cox's avatar
Russ Cox committed
1650 1651 1652
}

// Timing
1653

Russ Cox's avatar
Russ Cox committed
1654 1655 1656 1657 1658 1659 1660 1661
//go:nowritebarrier
func gchelper() {
	_g_ := getg()
	_g_.m.traceback = 2
	gchelperstart()

	if trace.enabled {
		traceGCScanStart()
1662 1663
	}

Russ Cox's avatar
Russ Cox committed
1664 1665 1666 1667
	// parallel mark for over GC roots
	parfordo(work.markfor)
	if gcphase != _GCscan {
		var gcw gcWork
1668
		gcDrain(&gcw, -1) // blocks in getfull
Russ Cox's avatar
Russ Cox committed
1669 1670
		gcw.dispose()
	}
1671

Russ Cox's avatar
Russ Cox committed
1672 1673
	if trace.enabled {
		traceGCScanDone()
1674
	}
Russ Cox's avatar
Russ Cox committed
1675 1676 1677 1678 1679 1680

	nproc := work.nproc // work.nproc can change right after we increment work.ndone
	if xadd(&work.ndone, +1) == nproc-1 {
		notewakeup(&work.alldone)
	}
	_g_.m.traceback = 0
1681 1682 1683 1684 1685 1686
}

func gchelperstart() {
	_g_ := getg()

	if _g_.m.helpgc < 0 || _g_.m.helpgc >= _MaxGcproc {
1687
		throw("gchelperstart: bad m->helpgc")
1688 1689
	}
	if _g_ != _g_.m.g0 {
1690
		throw("gchelper not running on g0 stack")
1691 1692 1693
	}
}

1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
// itoaDiv formats val/(10**dec) into buf.
func itoaDiv(buf []byte, val uint64, dec int) []byte {
	i := len(buf) - 1
	idec := i - dec
	for val >= 10 || i >= idec {
		buf[i] = byte(val%10 + '0')
		i--
		if i == idec {
			buf[i] = '.'
			i--
		}
		val /= 10
	}
	buf[i] = byte(val + '0')
	return buf[i:]
}
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729

// fmtNSAsMS nicely formats ns nanoseconds as milliseconds.
func fmtNSAsMS(buf []byte, ns uint64) []byte {
	if ns >= 10e6 {
		// Format as whole milliseconds.
		return itoaDiv(buf, ns/1e6, 0)
	}
	// Format two digits of precision, with at most three decimal places.
	x := ns / 1e3
	if x == 0 {
		buf[0] = '0'
		return buf[:1]
	}
	dec := 3
	for x >= 100 {
		x /= 10
		dec--
	}
	return itoaDiv(buf, x, dec)
}