Debian Codegraph @

libgo/go/runtime/mgcsweep.go

raw
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: sweeping
6
7 // The sweeper consists of two different algorithms:
8 //
9 // * The object reclaimer finds and frees unmarked slots in spans. It
10 // can free a whole span if none of the objects are marked, but that
11 // isn't its goal. This can be driven either synchronously by
12 // mcentral.cacheSpan for mcentral spans, or asynchronously by
13 // sweepone, which looks at all the mcentral lists.
14 //
15 // * The span reclaimer looks for spans that contain no marked objects
16 // and frees whole spans. This is a separate algorithm because
17 // freeing whole spans is the hardest task for the object reclaimer,
18 // but is critical when allocating new spans. The entry point for
19 // this is mheap_.reclaim and it's driven by a sequential scan of
20 // the page marks bitmap in the heap arenas.
21 //
22 // Both algorithms ultimately call mspan.sweep, which sweeps a single
23 // heap span.
24
25 package runtime
26
27 import (
28 "runtime/internal/atomic"
29 "unsafe"
30 )
31
32 var sweep sweepdata
33
34 // State of background sweep.
35 type sweepdata struct {
36 lock mutex
37 g *g
38 parked bool
39 started bool
40
41 nbgsweep uint32
42 npausesweep uint32
43
44 // active tracks outstanding sweepers and the sweep
45 // termination condition.
46 active activeSweep
47
48 // centralIndex is the current unswept span class.
49 // It represents an index into the mcentral span
50 // sets. Accessed and updated via its load and
51 // update methods. Not protected by a lock.
52 //
53 // Reset at mark termination.
54 // Used by mheap.nextSpanForSweep.
55 centralIndex sweepClass
56 }
57
58 // sweepClass is a spanClass and one bit to represent whether we're currently
59 // sweeping partial or full spans.
60 type sweepClass uint32
61
62 const (
63 numSweepClasses = numSpanClasses * 2
64 sweepClassDone sweepClass = sweepClass(^uint32(0))
65 )
66
67 func (s *sweepClass) load() sweepClass {
68 return sweepClass(atomic.Load((*uint32)(s)))
69 }
70
71 func (s *sweepClass) update(sNew sweepClass) {
72 // Only update *s if its current value is less than sNew,
73 // since *s increases monotonically.
74 sOld := s.load()
75 for sOld < sNew && !atomic.Cas((*uint32)(s), uint32(sOld), uint32(sNew)) {
76 sOld = s.load()
77 }
78 // TODO(mknyszek): This isn't the only place we have
79 // an atomic monotonically increasing counter. It would
80 // be nice to have an "atomic max" which is just implemented
81 // as the above on most architectures. Some architectures
82 // like RISC-V however have native support for an atomic max.
83 }
84
85 func (s *sweepClass) clear() {
86 atomic.Store((*uint32)(s), 0)
87 }
88
89 // split returns the underlying span class as well as
90 // whether we're interested in the full or partial
91 // unswept lists for that class, indicated as a boolean
92 // (true means "full").
93 func (s sweepClass) split() (spc spanClass, full bool) {
94 return spanClass(s >> 1), s&1 == 0
95 }
96
97 // nextSpanForSweep finds and pops the next span for sweeping from the
98 // central sweep buffers. It returns ownership of the span to the caller.
99 // Returns nil if no such span exists.
100 func (h *mheap) nextSpanForSweep() *mspan {
101 sg := h.sweepgen
102 for sc := sweep.centralIndex.load(); sc < numSweepClasses; sc++ {
103 spc, full := sc.split()
104 c := &h.central[spc].mcentral
105 var s *mspan
106 if full {
107 s = c.fullUnswept(sg).pop()
108 } else {
109 s = c.partialUnswept(sg).pop()
110 }
111 if s != nil {
112 // Write down that we found something so future sweepers
113 // can start from here.
114 sweep.centralIndex.update(sc)
115 return s
116 }
117 }
118 // Write down that we found nothing.
119 sweep.centralIndex.update(sweepClassDone)
120 return nil
121 }
122
123 const sweepDrainedMask = 1 << 31
124
125 // activeSweep is a type that captures whether sweeping
126 // is done, and whether there are any outstanding sweepers.
127 //
128 // Every potential sweeper must call begin() before they look
129 // for work, and end() after they've finished sweeping.
130 type activeSweep struct {
131 // state is divided into two parts.
132 //
133 // The top bit (masked by sweepDrainedMask) is a boolean
134 // value indicating whether all the sweep work has been
135 // drained from the queue.
136 //
137 // The rest of the bits are a counter, indicating the
138 // number of outstanding concurrent sweepers.
139 state atomic.Uint32
140 }
141
142 // begin registers a new sweeper. Returns a sweepLocker
143 // for acquiring spans for sweeping. Any outstanding sweeper blocks
144 // sweep termination.
145 //
146 // If the sweepLocker is invalid, the caller can be sure that all
147 // outstanding sweep work has been drained, so there is nothing left
148 // to sweep. Note that there may be sweepers currently running, so
149 // this does not indicate that all sweeping has completed.
150 //
151 // Even if the sweepLocker is invalid, its sweepGen is always valid.
152 func (a *activeSweep) begin() sweepLocker {
153 for {
154 state := a.state.Load()
155 if state&sweepDrainedMask != 0 {
156 return sweepLocker{mheap_.sweepgen, false}
157 }
158 if a.state.CompareAndSwap(state, state+1) {
159 return sweepLocker{mheap_.sweepgen, true}
160 }
161 }
162 }
163
164 // end deregisters a sweeper. Must be called once for each time
165 // begin is called if the sweepLocker is valid.
166 func (a *activeSweep) end(sl sweepLocker) {
167 if sl.sweepGen != mheap_.sweepgen {
168 throw("sweeper left outstanding across sweep generations")
169 }
170 for {
171 state := a.state.Load()
172 if (state&^sweepDrainedMask)-1 >= sweepDrainedMask {
173 throw("mismatched begin/end of activeSweep")
174 }
175 if a.state.CompareAndSwap(state, state-1) {
176 if state != sweepDrainedMask {
177 return
178 }
179 if debug.gcpacertrace > 0 {
180 print("pacer: sweep done at heap size ", gcController.heapLive>>20, "MB; allocated ", (gcController.heapLive-mheap_.sweepHeapLiveBasis)>>20, "MB during sweep; swept ", mheap_.pagesSwept.Load(), " pages at ", mheap_.sweepPagesPerByte, " pages/byte\n")
181 }
182 return
183 }
184 }
185 }
186
187 // markDrained marks the active sweep cycle as having drained
188 // all remaining work. This is safe to be called concurrently
189 // with all other methods of activeSweep, though may race.
190 //
191 // Returns true if this call was the one that actually performed
192 // the mark.
193 func (a *activeSweep) markDrained() bool {
194 for {
195 state := a.state.Load()
196 if state&sweepDrainedMask != 0 {
197 return false
198 }
199 if a.state.CompareAndSwap(state, state|sweepDrainedMask) {
200 return true
201 }
202 }
203 }
204
205 // sweepers returns the current number of active sweepers.
206 func (a *activeSweep) sweepers() uint32 {
207 return a.state.Load() &^ sweepDrainedMask
208 }
209
210 // isDone returns true if all sweep work has been drained and no more
211 // outstanding sweepers exist. That is, when the sweep phase is
212 // completely done.
213 func (a *activeSweep) isDone() bool {
214 return a.state.Load() == sweepDrainedMask
215 }
216
217 // reset sets up the activeSweep for the next sweep cycle.
218 //
219 // The world must be stopped.
220 func (a *activeSweep) reset() {
221 assertWorldStopped()
222 a.state.Store(0)
223 }
224
225 // finishsweep_m ensures that all spans are swept.
226 //
227 // The world must be stopped. This ensures there are no sweeps in
228 // progress.
229 //
230 //go:nowritebarrier
231 func finishsweep_m() {
232 assertWorldStopped()
233
234 // Sweeping must be complete before marking commences, so
235 // sweep any unswept spans. If this is a concurrent GC, there
236 // shouldn't be any spans left to sweep, so this should finish
237 // instantly. If GC was forced before the concurrent sweep
238 // finished, there may be spans to sweep.
239 for sweepone() != ^uintptr(0) {
240 sweep.npausesweep++
241 }
242
243 // Make sure there aren't any outstanding sweepers left.
244 // At this point, with the world stopped, it means one of two
245 // things. Either we were able to preempt a sweeper, or that
246 // a sweeper didn't call sweep.active.end when it should have.
247 // Both cases indicate a bug, so throw.
248 if sweep.active.sweepers() != 0 {
249 throw("active sweepers found at start of mark phase")
250 }
251
252 // Reset all the unswept buffers, which should be empty.
253 // Do this in sweep termination as opposed to mark termination
254 // so that we can catch unswept spans and reclaim blocks as
255 // soon as possible.
256 sg := mheap_.sweepgen
257 for i := range mheap_.central {
258 c := &mheap_.central[i].mcentral
259 c.partialUnswept(sg).reset()
260 c.fullUnswept(sg).reset()
261 }
262
263 // Sweeping is done, so if the scavenger isn't already awake,
264 // wake it up. There's definitely work for it to do at this
265 // point.
266 wakeScavenger()
267
268 nextMarkBitArenaEpoch()
269 }
270
271 func bgsweep(c chan int) {
272 setSystemGoroutine()
273
274 sweep.g = getg()
275
276 lockInit(&sweep.lock, lockRankSweep)
277 lock(&sweep.lock)
278 sweep.parked = true
279 c <- 1
280 goparkunlock(&sweep.lock, waitReasonGCSweepWait, traceEvGoBlock, 1)
281
282 for {
283 for sweepone() != ^uintptr(0) {
284 sweep.nbgsweep++
285 Gosched()
286 }
287 for freeSomeWbufs(true) {
288 Gosched()
289 }
290 lock(&sweep.lock)
291 if !isSweepDone() {
292 // This can happen if a GC runs between
293 // gosweepone returning ^0 above
294 // and the lock being acquired.
295 unlock(&sweep.lock)
296
297 // We need a preemption point for gofrontend.
298 Gosched()
299
300 continue
301 }
302 sweep.parked = true
303 goparkunlock(&sweep.lock, waitReasonGCSweepWait, traceEvGoBlock, 1)
304 }
305 }
306
307 // sweepLocker acquires sweep ownership of spans.
308 type sweepLocker struct {
309 // sweepGen is the sweep generation of the heap.
310 sweepGen uint32
311 valid bool
312 }
313
314 // sweepLocked represents sweep ownership of a span.
315 type sweepLocked struct {
316 *mspan
317 }
318
319 // tryAcquire attempts to acquire sweep ownership of span s. If it
320 // successfully acquires ownership, it blocks sweep completion.
321 func (l *sweepLocker) tryAcquire(s *mspan) (sweepLocked, bool) {
322 if !l.valid {
323 throw("use of invalid sweepLocker")
324 }
325 // Check before attempting to CAS.
326 if atomic.Load(&s.sweepgen) != l.sweepGen-2 {
327 return sweepLocked{}, false
328 }
329 // Attempt to acquire sweep ownership of s.
330 if !atomic.Cas(&s.sweepgen, l.sweepGen-2, l.sweepGen-1) {
331 return sweepLocked{}, false
332 }
333 return sweepLocked{s}, true
334 }
335
336 // sweepone sweeps some unswept heap span and returns the number of pages returned
337 // to the heap, or ^uintptr(0) if there was nothing to sweep.
338 func sweepone() uintptr {
339 gp := getg()
340
341 // Increment locks to ensure that the goroutine is not preempted
342 // in the middle of sweep thus leaving the span in an inconsistent state for next GC
343 gp.m.locks++
344
345 // TODO(austin): sweepone is almost always called in a loop;
346 // lift the sweepLocker into its callers.
347 sl := sweep.active.begin()
348 if !sl.valid {
349 gp.m.locks--
350 return ^uintptr(0)
351 }
352
353 // Find a span to sweep.
354 npages := ^uintptr(0)
355 var noMoreWork bool
356 for {
357 s := mheap_.nextSpanForSweep()
358 if s == nil {
359 noMoreWork = sweep.active.markDrained()
360 break
361 }
362 if state := s.state.get(); state != mSpanInUse {
363 // This can happen if direct sweeping already
364 // swept this span, but in that case the sweep
365 // generation should always be up-to-date.
366 if !(s.sweepgen == sl.sweepGen || s.sweepgen == sl.sweepGen+3) {
367 print("runtime: bad span s.state=", state, " s.sweepgen=", s.sweepgen, " sweepgen=", sl.sweepGen, "\n")
368 throw("non in-use span in unswept list")
369 }
370 continue
371 }
372 if s, ok := sl.tryAcquire(s); ok {
373 // Sweep the span we found.
374 npages = s.npages
375 if s.sweep(false) {
376 // Whole span was freed. Count it toward the
377 // page reclaimer credit since these pages can
378 // now be used for span allocation.
379 mheap_.reclaimCredit.Add(npages)
380 } else {
381 // Span is still in-use, so this returned no
382 // pages to the heap and the span needs to
383 // move to the swept in-use list.
384 npages = 0
385 }
386 break
387 }
388 }
389 sweep.active.end(sl)
390
391 if noMoreWork {
392 // The sweep list is empty. There may still be
393 // concurrent sweeps running, but we're at least very
394 // close to done sweeping.
395
396 // Move the scavenge gen forward (signalling
397 // that there's new work to do) and wake the scavenger.
398 //
399 // The scavenger is signaled by the last sweeper because once
400 // sweeping is done, we will definitely have useful work for
401 // the scavenger to do, since the scavenger only runs over the
402 // heap once per GC cycle. This update is not done during sweep
403 // termination because in some cases there may be a long delay
404 // between sweep done and sweep termination (e.g. not enough
405 // allocations to trigger a GC) which would be nice to fill in
406 // with scavenging work.
407 systemstack(func() {
408 lock(&mheap_.lock)
409 mheap_.pages.scavengeStartGen()
410 unlock(&mheap_.lock)
411 })
412 // Since we might sweep in an allocation path, it's not possible
413 // for us to wake the scavenger directly via wakeScavenger, since
414 // it could allocate. Ask sysmon to do it for us instead.
415 readyForScavenger()
416 }
417
418 gp.m.locks--
419 return npages
420 }
421
422 // isSweepDone reports whether all spans are swept.
423 //
424 // Note that this condition may transition from false to true at any
425 // time as the sweeper runs. It may transition from true to false if a
426 // GC runs; to prevent that the caller must be non-preemptible or must
427 // somehow block GC progress.
428 func isSweepDone() bool {
429 return sweep.active.isDone()
430 }
431
432 // Returns only when span s has been swept.
433 //go:nowritebarrier
434 func (s *mspan) ensureSwept() {
435 // Caller must disable preemption.
436 // Otherwise when this function returns the span can become unswept again
437 // (if GC is triggered on another goroutine).
438 _g_ := getg()
439 if _g_.m.locks == 0 && _g_.m.mallocing == 0 && _g_ != _g_.m.g0 {
440 throw("mspan.ensureSwept: m is not locked")
441 }
442
443 // If this operation fails, then that means that there are
444 // no more spans to be swept. In this case, either s has already
445 // been swept, or is about to be acquired for sweeping and swept.
446 sl := sweep.active.begin()
447 if sl.valid {
448 // The caller must be sure that the span is a mSpanInUse span.
449 if s, ok := sl.tryAcquire(s); ok {
450 s.sweep(false)
451 sweep.active.end(sl)
452 return
453 }
454 sweep.active.end(sl)
455 }
456
457 // Unfortunately we can't sweep the span ourselves. Somebody else
458 // got to it first. We don't have efficient means to wait, but that's
459 // OK, it will be swept fairly soon.
460 for {
461 spangen := atomic.Load(&s.sweepgen)
462 if spangen == sl.sweepGen || spangen == sl.sweepGen+3 {
463 break
464 }
465 osyield()
466 }
467 }
468
469 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
470 // It clears the mark bits in preparation for the next GC round.
471 // Returns true if the span was returned to heap.
472 // If preserve=true, don't return it to heap nor relink in mcentral lists;
473 // caller takes care of it.
474 func (sl *sweepLocked) sweep(preserve bool) bool {
475 // It's critical that we enter this function with preemption disabled,
476 // GC must not start while we are in the middle of this function.
477 _g_ := getg()
478 if _g_.m.locks == 0 && _g_.m.mallocing == 0 && _g_ != _g_.m.g0 {
479 throw("mspan.sweep: m is not locked")
480 }
481
482 s := sl.mspan
483 if !preserve {
484 // We'll release ownership of this span. Nil it out to
485 // prevent the caller from accidentally using it.
486 sl.mspan = nil
487 }
488
489 sweepgen := mheap_.sweepgen
490 if state := s.state.get(); state != mSpanInUse || s.sweepgen != sweepgen-1 {
491 print("mspan.sweep: state=", state, " sweepgen=", s.sweepgen, " mheap.sweepgen=", sweepgen, "\n")
492 throw("mspan.sweep: bad span state")
493 }
494
495 if trace.enabled {
496 traceGCSweepSpan(s.npages * _PageSize)
497 }
498
499 mheap_.pagesSwept.Add(int64(s.npages))
500
501 spc := s.spanclass
502 size := s.elemsize
503
504 // The allocBits indicate which unmarked objects don't need to be
505 // processed since they were free at the end of the last GC cycle
506 // and were not allocated since then.
507 // If the allocBits index is >= s.freeindex and the bit
508 // is not marked then the object remains unallocated
509 // since the last GC.
510 // This situation is analogous to being on a freelist.
511
512 // Unlink & free special records for any objects we're about to free.
513 // Two complications here:
514 // 1. An object can have both finalizer and profile special records.
515 // In such case we need to queue finalizer for execution,
516 // mark the object as live and preserve the profile special.
517 // 2. A tiny object can have several finalizers setup for different offsets.
518 // If such object is not marked, we need to queue all finalizers at once.
519 // Both 1 and 2 are possible at the same time.
520 hadSpecials := s.specials != nil
521 siter := newSpecialsIter(s)
522 for siter.valid() {
523 // A finalizer can be set for an inner byte of an object, find object beginning.
524 objIndex := uintptr(siter.s.offset) / size
525 p := s.base() + objIndex*size
526 mbits := s.markBitsForIndex(objIndex)
527 if !mbits.isMarked() {
528 // This object is not marked and has at least one special record.
529 // Pass 1: see if it has at least one finalizer.
530 hasFin := false
531 endOffset := p - s.base() + size
532 for tmp := siter.s; tmp != nil && uintptr(tmp.offset) < endOffset; tmp = tmp.next {
533 if tmp.kind == _KindSpecialFinalizer {
534 // Stop freeing of object if it has a finalizer.
535 mbits.setMarkedNonAtomic()
536 hasFin = true
537 break
538 }
539 }
540 // Pass 2: queue all finalizers _or_ handle profile record.
541 for siter.valid() && uintptr(siter.s.offset) < endOffset {
542 // Find the exact byte for which the special was setup
543 // (as opposed to object beginning).
544 special := siter.s
545 p := s.base() + uintptr(special.offset)
546 if special.kind == _KindSpecialFinalizer || !hasFin {
547 siter.unlinkAndNext()
548 freeSpecial(special, unsafe.Pointer(p), size)
549 } else {
550 // The object has finalizers, so we're keeping it alive.
551 // All other specials only apply when an object is freed,
552 // so just keep the special record.
553 siter.next()
554 }
555 }
556 } else {
557 // object is still live
558 if siter.s.kind == _KindSpecialReachable {
559 special := siter.unlinkAndNext()
560 (*specialReachable)(unsafe.Pointer(special)).reachable = true
561 freeSpecial(special, unsafe.Pointer(p), size)
562 } else {
563 // keep special record
564 siter.next()
565 }
566 }
567 }
568 if hadSpecials && s.specials == nil {
569 spanHasNoSpecials(s)
570 }
571
572 if debug.allocfreetrace != 0 || debug.clobberfree != 0 || raceenabled || msanenabled || asanenabled {
573 // Find all newly freed objects. This doesn't have to
574 // efficient; allocfreetrace has massive overhead.
575 mbits := s.markBitsForBase()
576 abits := s.allocBitsForIndex(0)
577 for i := uintptr(0); i < s.nelems; i++ {
578 if !mbits.isMarked() && (abits.index < s.freeindex || abits.isMarked()) {
579 x := s.base() + i*s.elemsize
580 if debug.allocfreetrace != 0 {
581 tracefree(unsafe.Pointer(x), size)
582 }
583 if debug.clobberfree != 0 {
584 clobberfree(unsafe.Pointer(x), size)
585 }
586 if raceenabled {
587 racefree(unsafe.Pointer(x), size)
588 }
589 if msanenabled {
590 msanfree(unsafe.Pointer(x), size)
591 }
592 if asanenabled {
593 asanpoison(unsafe.Pointer(x), size)
594 }
595 }
596 mbits.advance()
597 abits.advance()
598 }
599 }
600
601 // Check for zombie objects.
602 if s.freeindex < s.nelems {
603 // Everything < freeindex is allocated and hence
604 // cannot be zombies.
605 //
606 // Check the first bitmap byte, where we have to be
607 // careful with freeindex.
608 obj := s.freeindex
609 if (*s.gcmarkBits.bytep(obj / 8)&^*s.allocBits.bytep(obj / 8))>>(obj%8) != 0 {
610 s.reportZombies()
611 }
612 // Check remaining bytes.
613 for i := obj/8 + 1; i < divRoundUp(s.nelems, 8); i++ {
614 if *s.gcmarkBits.bytep(i)&^*s.allocBits.bytep(i) != 0 {
615 s.reportZombies()
616 }
617 }
618 }
619
620 // Count the number of free objects in this span.
621 nalloc := uint16(s.countAlloc())
622 nfreed := s.allocCount - nalloc
623 if nalloc > s.allocCount {
624 // The zombie check above should have caught this in
625 // more detail.
626 print("runtime: nelems=", s.nelems, " nalloc=", nalloc, " previous allocCount=", s.allocCount, " nfreed=", nfreed, "\n")
627 throw("sweep increased allocation count")
628 }
629
630 s.allocCount = nalloc
631 s.freeindex = 0 // reset allocation index to start of span.
632 if trace.enabled {
633 getg().m.p.ptr().traceReclaimed += uintptr(nfreed) * s.elemsize
634 }
635
636 // gcmarkBits becomes the allocBits.
637 // get a fresh cleared gcmarkBits in preparation for next GC
638 s.allocBits = s.gcmarkBits
639 s.gcmarkBits = newMarkBits(s.nelems)
640
641 // Initialize alloc bits cache.
642 s.refillAllocCache(0)
643
644 // The span must be in our exclusive ownership until we update sweepgen,
645 // check for potential races.
646 if state := s.state.get(); state != mSpanInUse || s.sweepgen != sweepgen-1 {
647 print("mspan.sweep: state=", state, " sweepgen=", s.sweepgen, " mheap.sweepgen=", sweepgen, "\n")
648 throw("mspan.sweep: bad span state after sweep")
649 }
650 if s.sweepgen == sweepgen+1 || s.sweepgen == sweepgen+3 {
651 throw("swept cached span")
652 }
653
654 // We need to set s.sweepgen = h.sweepgen only when all blocks are swept,
655 // because of the potential for a concurrent free/SetFinalizer.
656 //
657 // But we need to set it before we make the span available for allocation
658 // (return it to heap or mcentral), because allocation code assumes that a
659 // span is already swept if available for allocation.
660 //
661 // Serialization point.
662 // At this point the mark bits are cleared and allocation ready
663 // to go so release the span.
664 atomic.Store(&s.sweepgen, sweepgen)
665
666 if spc.sizeclass() != 0 {
667 // Handle spans for small objects.
668 if nfreed > 0 {
669 // Only mark the span as needing zeroing if we've freed any
670 // objects, because a fresh span that had been allocated into,
671 // wasn't totally filled, but then swept, still has all of its
672 // free slots zeroed.
673 s.needzero = 1
674 stats := memstats.heapStats.acquire()
675 atomic.Xadduintptr(&stats.smallFreeCount[spc.sizeclass()], uintptr(nfreed))
676 memstats.heapStats.release()
677 }
678 if !preserve {
679 // The caller may not have removed this span from whatever
680 // unswept set its on but taken ownership of the span for
681 // sweeping by updating sweepgen. If this span still is in
682 // an unswept set, then the mcentral will pop it off the
683 // set, check its sweepgen, and ignore it.
684 if nalloc == 0 {
685 // Free totally free span directly back to the heap.
686 mheap_.freeSpan(s)
687 return true
688 }
689 // Return span back to the right mcentral list.
690 if uintptr(nalloc) == s.nelems {
691 mheap_.central[spc].mcentral.fullSwept(sweepgen).push(s)
692 } else {
693 mheap_.central[spc].mcentral.partialSwept(sweepgen).push(s)
694 }
695 }
696 } else if !preserve {
697 // Handle spans for large objects.
698 if nfreed != 0 {
699 // Free large object span to heap.
700
701 // NOTE(rsc,dvyukov): The original implementation of efence
702 // in CL 22060046 used sysFree instead of sysFault, so that
703 // the operating system would eventually give the memory
704 // back to us again, so that an efence program could run
705 // longer without running out of memory. Unfortunately,
706 // calling sysFree here without any kind of adjustment of the
707 // heap data structures means that when the memory does
708 // come back to us, we have the wrong metadata for it, either in
709 // the mspan structures or in the garbage collection bitmap.
710 // Using sysFault here means that the program will run out of
711 // memory fairly quickly in efence mode, but at least it won't
712 // have mysterious crashes due to confused memory reuse.
713 // It should be possible to switch back to sysFree if we also
714 // implement and then call some kind of mheap.deleteSpan.
715 if debug.efence > 0 {
716 s.limit = 0 // prevent mlookup from finding this span
717 sysFault(unsafe.Pointer(s.base()), size)
718 } else {
719 mheap_.freeSpan(s)
720 }
721 stats := memstats.heapStats.acquire()
722 atomic.Xadduintptr(&stats.largeFreeCount, 1)
723 atomic.Xadduintptr(&stats.largeFree, size)
724 memstats.heapStats.release()
725 return true
726 }
727
728 // Add a large span directly onto the full+swept list.
729 mheap_.central[spc].mcentral.fullSwept(sweepgen).push(s)
730 }
731 return false
732 }
733
734 // reportZombies reports any marked but free objects in s and throws.
735 //
736 // This generally means one of the following:
737 //
738 // 1. User code converted a pointer to a uintptr and then back
739 // unsafely, and a GC ran while the uintptr was the only reference to
740 // an object.
741 //
742 // 2. User code (or a compiler bug) constructed a bad pointer that
743 // points to a free slot, often a past-the-end pointer.
744 //
745 // 3. The GC two cycles ago missed a pointer and freed a live object,
746 // but it was still live in the last cycle, so this GC cycle found a
747 // pointer to that object and marked it.
748 func (s *mspan) reportZombies() {
749 printlock()
750 print("runtime: marked free object in span ", s, ", elemsize=", s.elemsize, " freeindex=", s.freeindex, " (bad use of unsafe.Pointer? try -d=checkptr)\n")
751 mbits := s.markBitsForBase()
752 abits := s.allocBitsForIndex(0)
753 for i := uintptr(0); i < s.nelems; i++ {
754 addr := s.base() + i*s.elemsize
755 print(hex(addr))
756 alloc := i < s.freeindex || abits.isMarked()
757 if alloc {
758 print(" alloc")
759 } else {
760 print(" free ")
761 }
762 if mbits.isMarked() {
763 print(" marked ")
764 } else {
765 print(" unmarked")
766 }
767 zombie := mbits.isMarked() && !alloc
768 if zombie {
769 print(" zombie")
770 }
771 print("\n")
772 if zombie {
773 length := s.elemsize
774 if length > 1024 {
775 length = 1024
776 }
777 hexdumpWords(addr, addr+length, nil)
778 }
779 mbits.advance()
780 abits.advance()
781 }
782 throw("found pointer to free object")
783 }
784
785 // deductSweepCredit deducts sweep credit for allocating a span of
786 // size spanBytes. This must be performed *before* the span is
787 // allocated to ensure the system has enough credit. If necessary, it
788 // performs sweeping to prevent going in to debt. If the caller will
789 // also sweep pages (e.g., for a large allocation), it can pass a
790 // non-zero callerSweepPages to leave that many pages unswept.
791 //
792 // deductSweepCredit makes a worst-case assumption that all spanBytes
793 // bytes of the ultimately allocated span will be available for object
794 // allocation.
795 //
796 // deductSweepCredit is the core of the "proportional sweep" system.
797 // It uses statistics gathered by the garbage collector to perform
798 // enough sweeping so that all pages are swept during the concurrent
799 // sweep phase between GC cycles.
800 //
801 // mheap_ must NOT be locked.
802 func deductSweepCredit(spanBytes uintptr, callerSweepPages uintptr) {
803 if mheap_.sweepPagesPerByte == 0 {
804 // Proportional sweep is done or disabled.
805 return
806 }
807
808 if trace.enabled {
809 traceGCSweepStart()
810 }
811
812 retry:
813 sweptBasis := mheap_.pagesSweptBasis.Load()
814
815 // Fix debt if necessary.
816 newHeapLive := uintptr(atomic.Load64(&gcController.heapLive)-mheap_.sweepHeapLiveBasis) + spanBytes
817 pagesTarget := int64(mheap_.sweepPagesPerByte*float64(newHeapLive)) - int64(callerSweepPages)
818 for pagesTarget > int64(mheap_.pagesSwept.Load()-sweptBasis) {
819 if sweepone() == ^uintptr(0) {
820 mheap_.sweepPagesPerByte = 0
821 break
822 }
823 if mheap_.pagesSweptBasis.Load() != sweptBasis {
824 // Sweep pacing changed. Recompute debt.
825 goto retry
826 }
827 }
828
829 if trace.enabled {
830 traceGCSweepDone()
831 }
832 }
833
834 // clobberfree sets the memory content at x to bad content, for debugging
835 // purposes.
836 func clobberfree(x unsafe.Pointer, size uintptr) {
837 // size (span.elemsize) is always a multiple of 4.
838 for i := uintptr(0); i < size; i += 4 {
839 *(*uint32)(add(x, i)) = 0xdeadbeef
840 }
841 }
842
843 // gcPaceSweeper updates the sweeper's pacing parameters.
844 //
845 // Must be called whenever the GC's pacing is updated.
846 //
847 // The world must be stopped, or mheap_.lock must be held.
848 func gcPaceSweeper(trigger uint64) {
849 assertWorldStoppedOrLockHeld(&mheap_.lock)
850
851 // Update sweep pacing.
852 if isSweepDone() {
853 mheap_.sweepPagesPerByte = 0
854 } else {
855 // Concurrent sweep needs to sweep all of the in-use
856 // pages by the time the allocated heap reaches the GC
857 // trigger. Compute the ratio of in-use pages to sweep
858 // per byte allocated, accounting for the fact that
859 // some might already be swept.
860 heapLiveBasis := atomic.Load64(&gcController.heapLive)
861 heapDistance := int64(trigger) - int64(heapLiveBasis)
862 // Add a little margin so rounding errors and
863 // concurrent sweep are less likely to leave pages
864 // unswept when GC starts.
865 heapDistance -= 1024 * 1024
866 if heapDistance < _PageSize {
867 // Avoid setting the sweep ratio extremely high
868 heapDistance = _PageSize
869 }
870 pagesSwept := mheap_.pagesSwept.Load()
871 pagesInUse := mheap_.pagesInUse.Load()
872 sweepDistancePages := int64(pagesInUse) - int64(pagesSwept)
873 if sweepDistancePages <= 0 {
874 mheap_.sweepPagesPerByte = 0
875 } else {
876 mheap_.sweepPagesPerByte = float64(sweepDistancePages) / float64(heapDistance)
877 mheap_.sweepHeapLiveBasis = heapLiveBasis
878 // Write pagesSweptBasis last, since this
879 // signals concurrent sweeps to recompute
880 // their debt.
881 mheap_.pagesSweptBasis.Store(pagesSwept)
882 }
883 }
884 }