2014-07-29 Ed Smith-Rowland <3dw4rd@verizon.net>
[official-gcc.git] / libgo / runtime / mgc0.c
blob4b78f3bda56a2d37651ce28a2dc03116dfb79285
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Garbage collector (GC).
6 //
7 // GC is:
8 // - mark&sweep
9 // - mostly precise (with the exception of some C-allocated objects, assembly frames/arguments, etc)
10 // - parallel (up to MaxGcproc threads)
11 // - partially concurrent (mark is stop-the-world, while sweep is concurrent)
12 // - non-moving/non-compacting
13 // - full (non-partial)
15 // GC rate.
16 // Next GC is after we've allocated an extra amount of memory proportional to
17 // the amount already in use. The proportion is controlled by GOGC environment variable
18 // (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M
19 // (this mark is tracked in next_gc variable). This keeps the GC cost in linear
20 // proportion to the allocation cost. Adjusting GOGC just changes the linear constant
21 // (and also the amount of extra memory used).
23 // Concurrent sweep.
24 // The sweep phase proceeds concurrently with normal program execution.
25 // The heap is swept span-by-span both lazily (when a goroutine needs another span)
26 // and concurrently in a background goroutine (this helps programs that are not CPU bound).
27 // However, at the end of the stop-the-world GC phase we don't know the size of the live heap,
28 // and so next_gc calculation is tricky and happens as follows.
29 // At the end of the stop-the-world phase next_gc is conservatively set based on total
30 // heap size; all spans are marked as "needs sweeping".
31 // Whenever a span is swept, next_gc is decremented by GOGC*newly_freed_memory.
32 // The background sweeper goroutine simply sweeps spans one-by-one bringing next_gc
33 // closer to the target value. However, this is not enough to avoid over-allocating memory.
34 // Consider that a goroutine wants to allocate a new span for a large object and
35 // there are no free swept spans, but there are small-object unswept spans.
36 // If the goroutine naively allocates a new span, it can surpass the yet-unknown
37 // target next_gc value. In order to prevent such cases (1) when a goroutine needs
38 // to allocate a new small-object span, it sweeps small-object spans for the same
39 // object size until it frees at least one object; (2) when a goroutine needs to
40 // allocate large-object span from heap, it sweeps spans until it frees at least
41 // that many pages into heap. Together these two measures ensure that we don't surpass
42 // target next_gc value by a large margin. There is an exception: if a goroutine sweeps
43 // and frees two nonadjacent one-page spans to the heap, it will allocate a new two-page span,
44 // but there can still be other one-page unswept spans which could be combined into a two-page span.
45 // It's critical to ensure that no operations proceed on unswept spans (that would corrupt
46 // mark bits in GC bitmap). During GC all mcaches are flushed into the central cache,
47 // so they are empty. When a goroutine grabs a new span into mcache, it sweeps it.
48 // When a goroutine explicitly frees an object or sets a finalizer, it ensures that
49 // the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish).
50 // The finalizer goroutine is kicked off only when all spans are swept.
51 // When the next GC starts, it sweeps all not-yet-swept spans (if any).
53 #include <unistd.h>
55 #include "runtime.h"
56 #include "arch.h"
57 #include "malloc.h"
58 #include "mgc0.h"
59 #include "chan.h"
60 #include "race.h"
61 #include "go-type.h"
63 // Map gccgo field names to gc field names.
64 // Slice aka __go_open_array.
65 #define array __values
66 #define cap __capacity
67 // Iface aka __go_interface
68 #define tab __methods
69 // Hmap aka __go_map
70 typedef struct __go_map Hmap;
71 // Type aka __go_type_descriptor
72 #define string __reflection
73 #define KindPtr GO_PTR
74 #define KindNoPointers GO_NO_POINTERS
75 // PtrType aka __go_ptr_type
76 #define elem __element_type
78 #ifdef USING_SPLIT_STACK
80 extern void * __splitstack_find (void *, void *, size_t *, void **, void **,
81 void **);
83 extern void * __splitstack_find_context (void *context[10], size_t *, void **,
84 void **, void **);
86 #endif
88 enum {
89 Debug = 0,
90 CollectStats = 0,
91 ConcurrentSweep = 1,
93 WorkbufSize = 16*1024,
94 FinBlockSize = 4*1024,
96 handoffThreshold = 4,
97 IntermediateBufferCapacity = 64,
99 // Bits in type information
100 PRECISE = 1,
101 LOOP = 2,
102 PC_BITS = PRECISE | LOOP,
104 RootData = 0,
105 RootBss = 1,
106 RootFinalizers = 2,
107 RootSpanTypes = 3,
108 RootFlushCaches = 4,
109 RootCount = 5,
112 #define GcpercentUnknown (-2)
114 // Initialized from $GOGC. GOGC=off means no gc.
115 static int32 gcpercent = GcpercentUnknown;
117 static FuncVal* poolcleanup;
119 void sync_runtime_registerPoolCleanup(FuncVal*)
120 __asm__ (GOSYM_PREFIX "sync.runtime_registerPoolCleanup");
122 void
123 sync_runtime_registerPoolCleanup(FuncVal *f)
125 poolcleanup = f;
128 static void
129 clearpools(void)
131 P *p, **pp;
132 MCache *c;
134 // clear sync.Pool's
135 if(poolcleanup != nil) {
136 __go_set_closure(poolcleanup);
137 poolcleanup->fn();
140 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
141 // clear tinyalloc pool
142 c = p->mcache;
143 if(c != nil) {
144 c->tiny = nil;
145 c->tinysize = 0;
147 // clear defer pools
148 p->deferpool = nil;
152 // Holding worldsema grants an M the right to try to stop the world.
153 // The procedure is:
155 // runtime_semacquire(&runtime_worldsema);
156 // m->gcing = 1;
157 // runtime_stoptheworld();
159 // ... do stuff ...
161 // m->gcing = 0;
162 // runtime_semrelease(&runtime_worldsema);
163 // runtime_starttheworld();
165 uint32 runtime_worldsema = 1;
167 typedef struct Workbuf Workbuf;
168 struct Workbuf
170 #define SIZE (WorkbufSize-sizeof(LFNode)-sizeof(uintptr))
171 LFNode node; // must be first
172 uintptr nobj;
173 Obj obj[SIZE/sizeof(Obj) - 1];
174 uint8 _padding[SIZE%sizeof(Obj) + sizeof(Obj)];
175 #undef SIZE
178 typedef struct Finalizer Finalizer;
179 struct Finalizer
181 FuncVal *fn;
182 void *arg;
183 const struct __go_func_type *ft;
184 const struct __go_ptr_type *ot;
187 typedef struct FinBlock FinBlock;
188 struct FinBlock
190 FinBlock *alllink;
191 FinBlock *next;
192 int32 cnt;
193 int32 cap;
194 Finalizer fin[1];
197 static Lock finlock; // protects the following variables
198 static FinBlock *finq; // list of finalizers that are to be executed
199 static FinBlock *finc; // cache of free blocks
200 static FinBlock *allfin; // list of all blocks
201 bool runtime_fingwait;
202 bool runtime_fingwake;
204 static Lock gclock;
205 static G* fing;
207 static void runfinq(void*);
208 static void bgsweep(void*);
209 static Workbuf* getempty(Workbuf*);
210 static Workbuf* getfull(Workbuf*);
211 static void putempty(Workbuf*);
212 static Workbuf* handoff(Workbuf*);
213 static void gchelperstart(void);
214 static void flushallmcaches(void);
215 static void addstackroots(G *gp, Workbuf **wbufp);
217 static struct {
218 uint64 full; // lock-free list of full blocks
219 uint64 empty; // lock-free list of empty blocks
220 byte pad0[CacheLineSize]; // prevents false-sharing between full/empty and nproc/nwait
221 uint32 nproc;
222 int64 tstart;
223 volatile uint32 nwait;
224 volatile uint32 ndone;
225 Note alldone;
226 ParFor *markfor;
228 Lock;
229 byte *chunk;
230 uintptr nchunk;
231 } work __attribute__((aligned(8)));
233 enum {
234 GC_DEFAULT_PTR = GC_NUM_INSTR,
235 GC_CHAN,
237 GC_NUM_INSTR2
240 static struct {
241 struct {
242 uint64 sum;
243 uint64 cnt;
244 } ptr;
245 uint64 nbytes;
246 struct {
247 uint64 sum;
248 uint64 cnt;
249 uint64 notype;
250 uint64 typelookup;
251 } obj;
252 uint64 rescan;
253 uint64 rescanbytes;
254 uint64 instr[GC_NUM_INSTR2];
255 uint64 putempty;
256 uint64 getfull;
257 struct {
258 uint64 foundbit;
259 uint64 foundword;
260 uint64 foundspan;
261 } flushptrbuf;
262 struct {
263 uint64 foundbit;
264 uint64 foundword;
265 uint64 foundspan;
266 } markonly;
267 uint32 nbgsweep;
268 uint32 npausesweep;
269 } gcstats;
271 // markonly marks an object. It returns true if the object
272 // has been marked by this function, false otherwise.
273 // This function doesn't append the object to any buffer.
274 static bool
275 markonly(const void *obj)
277 byte *p;
278 uintptr *bitp, bits, shift, x, xbits, off, j;
279 MSpan *s;
280 PageID k;
282 // Words outside the arena cannot be pointers.
283 if((const byte*)obj < runtime_mheap.arena_start || (const byte*)obj >= runtime_mheap.arena_used)
284 return false;
286 // obj may be a pointer to a live object.
287 // Try to find the beginning of the object.
289 // Round down to word boundary.
290 obj = (const void*)((uintptr)obj & ~((uintptr)PtrSize-1));
292 // Find bits for this word.
293 off = (const uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
294 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
295 shift = off % wordsPerBitmapWord;
296 xbits = *bitp;
297 bits = xbits >> shift;
299 // Pointing at the beginning of a block?
300 if((bits & (bitAllocated|bitBlockBoundary)) != 0) {
301 if(CollectStats)
302 runtime_xadd64(&gcstats.markonly.foundbit, 1);
303 goto found;
306 // Pointing just past the beginning?
307 // Scan backward a little to find a block boundary.
308 for(j=shift; j-->0; ) {
309 if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
310 shift = j;
311 bits = xbits>>shift;
312 if(CollectStats)
313 runtime_xadd64(&gcstats.markonly.foundword, 1);
314 goto found;
318 // Otherwise consult span table to find beginning.
319 // (Manually inlined copy of MHeap_LookupMaybe.)
320 k = (uintptr)obj>>PageShift;
321 x = k;
322 x -= (uintptr)runtime_mheap.arena_start>>PageShift;
323 s = runtime_mheap.spans[x];
324 if(s == nil || k < s->start || (const byte*)obj >= s->limit || s->state != MSpanInUse)
325 return false;
326 p = (byte*)((uintptr)s->start<<PageShift);
327 if(s->sizeclass == 0) {
328 obj = p;
329 } else {
330 uintptr size = s->elemsize;
331 int32 i = ((const byte*)obj - p)/size;
332 obj = p+i*size;
335 // Now that we know the object header, reload bits.
336 off = (const uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
337 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
338 shift = off % wordsPerBitmapWord;
339 xbits = *bitp;
340 bits = xbits >> shift;
341 if(CollectStats)
342 runtime_xadd64(&gcstats.markonly.foundspan, 1);
344 found:
345 // Now we have bits, bitp, and shift correct for
346 // obj pointing at the base of the object.
347 // Only care about allocated and not marked.
348 if((bits & (bitAllocated|bitMarked)) != bitAllocated)
349 return false;
350 if(work.nproc == 1)
351 *bitp |= bitMarked<<shift;
352 else {
353 for(;;) {
354 x = *bitp;
355 if(x & (bitMarked<<shift))
356 return false;
357 if(runtime_casp((void**)bitp, (void*)x, (void*)(x|(bitMarked<<shift))))
358 break;
362 // The object is now marked
363 return true;
366 // PtrTarget is a structure used by intermediate buffers.
367 // The intermediate buffers hold GC data before it
368 // is moved/flushed to the work buffer (Workbuf).
369 // The size of an intermediate buffer is very small,
370 // such as 32 or 64 elements.
371 typedef struct PtrTarget PtrTarget;
372 struct PtrTarget
374 void *p;
375 uintptr ti;
378 typedef struct Scanbuf Scanbuf;
379 struct Scanbuf
381 struct {
382 PtrTarget *begin;
383 PtrTarget *end;
384 PtrTarget *pos;
385 } ptr;
386 struct {
387 Obj *begin;
388 Obj *end;
389 Obj *pos;
390 } obj;
391 Workbuf *wbuf;
392 Obj *wp;
393 uintptr nobj;
396 typedef struct BufferList BufferList;
397 struct BufferList
399 PtrTarget ptrtarget[IntermediateBufferCapacity];
400 Obj obj[IntermediateBufferCapacity];
401 uint32 busy;
402 byte pad[CacheLineSize];
404 static BufferList bufferList[MaxGcproc];
406 static Type *itabtype;
408 static void enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj);
410 // flushptrbuf moves data from the PtrTarget buffer to the work buffer.
411 // The PtrTarget buffer contains blocks irrespective of whether the blocks have been marked or scanned,
412 // while the work buffer contains blocks which have been marked
413 // and are prepared to be scanned by the garbage collector.
415 // _wp, _wbuf, _nobj are input/output parameters and are specifying the work buffer.
417 // A simplified drawing explaining how the todo-list moves from a structure to another:
419 // scanblock
420 // (find pointers)
421 // Obj ------> PtrTarget (pointer targets)
422 // ↑ |
423 // | |
424 // `----------'
425 // flushptrbuf
426 // (find block start, mark and enqueue)
427 static void
428 flushptrbuf(Scanbuf *sbuf)
430 byte *p, *arena_start, *obj;
431 uintptr size, *bitp, bits, shift, j, x, xbits, off, nobj, ti, n;
432 MSpan *s;
433 PageID k;
434 Obj *wp;
435 Workbuf *wbuf;
436 PtrTarget *ptrbuf;
437 PtrTarget *ptrbuf_end;
439 arena_start = runtime_mheap.arena_start;
441 wp = sbuf->wp;
442 wbuf = sbuf->wbuf;
443 nobj = sbuf->nobj;
445 ptrbuf = sbuf->ptr.begin;
446 ptrbuf_end = sbuf->ptr.pos;
447 n = ptrbuf_end - sbuf->ptr.begin;
448 sbuf->ptr.pos = sbuf->ptr.begin;
450 if(CollectStats) {
451 runtime_xadd64(&gcstats.ptr.sum, n);
452 runtime_xadd64(&gcstats.ptr.cnt, 1);
455 // If buffer is nearly full, get a new one.
456 if(wbuf == nil || nobj+n >= nelem(wbuf->obj)) {
457 if(wbuf != nil)
458 wbuf->nobj = nobj;
459 wbuf = getempty(wbuf);
460 wp = wbuf->obj;
461 nobj = 0;
463 if(n >= nelem(wbuf->obj))
464 runtime_throw("ptrbuf has to be smaller than WorkBuf");
467 while(ptrbuf < ptrbuf_end) {
468 obj = ptrbuf->p;
469 ti = ptrbuf->ti;
470 ptrbuf++;
472 // obj belongs to interval [mheap.arena_start, mheap.arena_used).
473 if(Debug > 1) {
474 if(obj < runtime_mheap.arena_start || obj >= runtime_mheap.arena_used)
475 runtime_throw("object is outside of mheap");
478 // obj may be a pointer to a live object.
479 // Try to find the beginning of the object.
481 // Round down to word boundary.
482 if(((uintptr)obj & ((uintptr)PtrSize-1)) != 0) {
483 obj = (void*)((uintptr)obj & ~((uintptr)PtrSize-1));
484 ti = 0;
487 // Find bits for this word.
488 off = (uintptr*)obj - (uintptr*)arena_start;
489 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
490 shift = off % wordsPerBitmapWord;
491 xbits = *bitp;
492 bits = xbits >> shift;
494 // Pointing at the beginning of a block?
495 if((bits & (bitAllocated|bitBlockBoundary)) != 0) {
496 if(CollectStats)
497 runtime_xadd64(&gcstats.flushptrbuf.foundbit, 1);
498 goto found;
501 ti = 0;
503 // Pointing just past the beginning?
504 // Scan backward a little to find a block boundary.
505 for(j=shift; j-->0; ) {
506 if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
507 obj = (byte*)obj - (shift-j)*PtrSize;
508 shift = j;
509 bits = xbits>>shift;
510 if(CollectStats)
511 runtime_xadd64(&gcstats.flushptrbuf.foundword, 1);
512 goto found;
516 // Otherwise consult span table to find beginning.
517 // (Manually inlined copy of MHeap_LookupMaybe.)
518 k = (uintptr)obj>>PageShift;
519 x = k;
520 x -= (uintptr)arena_start>>PageShift;
521 s = runtime_mheap.spans[x];
522 if(s == nil || k < s->start || obj >= s->limit || s->state != MSpanInUse)
523 continue;
524 p = (byte*)((uintptr)s->start<<PageShift);
525 if(s->sizeclass == 0) {
526 obj = p;
527 } else {
528 size = s->elemsize;
529 int32 i = ((byte*)obj - p)/size;
530 obj = p+i*size;
533 // Now that we know the object header, reload bits.
534 off = (uintptr*)obj - (uintptr*)arena_start;
535 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
536 shift = off % wordsPerBitmapWord;
537 xbits = *bitp;
538 bits = xbits >> shift;
539 if(CollectStats)
540 runtime_xadd64(&gcstats.flushptrbuf.foundspan, 1);
542 found:
543 // Now we have bits, bitp, and shift correct for
544 // obj pointing at the base of the object.
545 // Only care about allocated and not marked.
546 if((bits & (bitAllocated|bitMarked)) != bitAllocated)
547 continue;
548 if(work.nproc == 1)
549 *bitp |= bitMarked<<shift;
550 else {
551 for(;;) {
552 x = *bitp;
553 if(x & (bitMarked<<shift))
554 goto continue_obj;
555 if(runtime_casp((void**)bitp, (void*)x, (void*)(x|(bitMarked<<shift))))
556 break;
560 // If object has no pointers, don't need to scan further.
561 if((bits & bitScan) == 0)
562 continue;
564 // Ask span about size class.
565 // (Manually inlined copy of MHeap_Lookup.)
566 x = (uintptr)obj >> PageShift;
567 x -= (uintptr)arena_start>>PageShift;
568 s = runtime_mheap.spans[x];
570 PREFETCH(obj);
572 *wp = (Obj){obj, s->elemsize, ti};
573 wp++;
574 nobj++;
575 continue_obj:;
578 // If another proc wants a pointer, give it some.
579 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
580 wbuf->nobj = nobj;
581 wbuf = handoff(wbuf);
582 nobj = wbuf->nobj;
583 wp = wbuf->obj + nobj;
586 sbuf->wp = wp;
587 sbuf->wbuf = wbuf;
588 sbuf->nobj = nobj;
591 static void
592 flushobjbuf(Scanbuf *sbuf)
594 uintptr nobj, off;
595 Obj *wp, obj;
596 Workbuf *wbuf;
597 Obj *objbuf;
598 Obj *objbuf_end;
600 wp = sbuf->wp;
601 wbuf = sbuf->wbuf;
602 nobj = sbuf->nobj;
604 objbuf = sbuf->obj.begin;
605 objbuf_end = sbuf->obj.pos;
606 sbuf->obj.pos = sbuf->obj.begin;
608 while(objbuf < objbuf_end) {
609 obj = *objbuf++;
611 // Align obj.b to a word boundary.
612 off = (uintptr)obj.p & (PtrSize-1);
613 if(off != 0) {
614 obj.p += PtrSize - off;
615 obj.n -= PtrSize - off;
616 obj.ti = 0;
619 if(obj.p == nil || obj.n == 0)
620 continue;
622 // If buffer is full, get a new one.
623 if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
624 if(wbuf != nil)
625 wbuf->nobj = nobj;
626 wbuf = getempty(wbuf);
627 wp = wbuf->obj;
628 nobj = 0;
631 *wp = obj;
632 wp++;
633 nobj++;
636 // If another proc wants a pointer, give it some.
637 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
638 wbuf->nobj = nobj;
639 wbuf = handoff(wbuf);
640 nobj = wbuf->nobj;
641 wp = wbuf->obj + nobj;
644 sbuf->wp = wp;
645 sbuf->wbuf = wbuf;
646 sbuf->nobj = nobj;
649 // Program that scans the whole block and treats every block element as a potential pointer
650 static uintptr defaultProg[2] = {PtrSize, GC_DEFAULT_PTR};
652 #if 0
653 // Hchan program
654 static uintptr chanProg[2] = {0, GC_CHAN};
655 #endif
657 // Local variables of a program fragment or loop
658 typedef struct Frame Frame;
659 struct Frame {
660 uintptr count, elemsize, b;
661 uintptr *loop_or_ret;
664 // Sanity check for the derived type info objti.
665 static void
666 checkptr(void *obj, uintptr objti)
668 uintptr type, tisize, i, x;
669 byte *objstart;
670 Type *t;
671 MSpan *s;
673 if(!Debug)
674 runtime_throw("checkptr is debug only");
676 if((byte*)obj < runtime_mheap.arena_start || (byte*)obj >= runtime_mheap.arena_used)
677 return;
678 type = runtime_gettype(obj);
679 t = (Type*)(type & ~(uintptr)(PtrSize-1));
680 if(t == nil)
681 return;
682 x = (uintptr)obj >> PageShift;
683 x -= (uintptr)(runtime_mheap.arena_start)>>PageShift;
684 s = runtime_mheap.spans[x];
685 objstart = (byte*)((uintptr)s->start<<PageShift);
686 if(s->sizeclass != 0) {
687 i = ((byte*)obj - objstart)/s->elemsize;
688 objstart += i*s->elemsize;
690 tisize = *(uintptr*)objti;
691 // Sanity check for object size: it should fit into the memory block.
692 if((byte*)obj + tisize > objstart + s->elemsize) {
693 runtime_printf("object of type '%S' at %p/%p does not fit in block %p/%p\n",
694 *t->string, obj, tisize, objstart, s->elemsize);
695 runtime_throw("invalid gc type info");
697 if(obj != objstart)
698 return;
699 // If obj points to the beginning of the memory block,
700 // check type info as well.
701 if(t->string == nil ||
702 // Gob allocates unsafe pointers for indirection.
703 (runtime_strcmp((const char *)t->string->str, (const char*)"unsafe.Pointer") &&
704 // Runtime and gc think differently about closures.
705 runtime_strstr((const char *)t->string->str, (const char*)"struct { F uintptr") != (const char *)t->string->str)) {
706 #if 0
707 pc1 = (uintptr*)objti;
708 pc2 = (uintptr*)t->gc;
709 // A simple best-effort check until first GC_END.
710 for(j = 1; pc1[j] != GC_END && pc2[j] != GC_END; j++) {
711 if(pc1[j] != pc2[j]) {
712 runtime_printf("invalid gc type info for '%s', type info %p [%d]=%p, block info %p [%d]=%p\n",
713 t->string ? (const int8*)t->string->str : (const int8*)"?", pc1, (int32)j, pc1[j], pc2, (int32)j, pc2[j]);
714 runtime_throw("invalid gc type info");
717 #endif
721 // scanblock scans a block of n bytes starting at pointer b for references
722 // to other objects, scanning any it finds recursively until there are no
723 // unscanned objects left. Instead of using an explicit recursion, it keeps
724 // a work list in the Workbuf* structures and loops in the main function
725 // body. Keeping an explicit work list is easier on the stack allocator and
726 // more efficient.
727 static void
728 scanblock(Workbuf *wbuf, bool keepworking)
730 byte *b, *arena_start, *arena_used;
731 uintptr n, i, end_b, elemsize, size, ti, objti, count, /* type, */ nobj;
732 uintptr *pc, precise_type, nominal_size;
733 #if 0
734 uintptr *chan_ret, chancap;
735 #endif
736 void *obj;
737 const Type *t, *et;
738 Slice *sliceptr;
739 String *stringptr;
740 Frame *stack_ptr, stack_top, stack[GC_STACK_CAPACITY+4];
741 BufferList *scanbuffers;
742 Scanbuf sbuf;
743 Eface *eface;
744 Iface *iface;
745 #if 0
746 Hchan *chan;
747 ChanType *chantype;
748 #endif
749 Obj *wp;
751 if(sizeof(Workbuf) % WorkbufSize != 0)
752 runtime_throw("scanblock: size of Workbuf is suboptimal");
754 // Memory arena parameters.
755 arena_start = runtime_mheap.arena_start;
756 arena_used = runtime_mheap.arena_used;
758 stack_ptr = stack+nelem(stack)-1;
760 precise_type = false;
761 nominal_size = 0;
763 if(wbuf) {
764 nobj = wbuf->nobj;
765 wp = &wbuf->obj[nobj];
766 } else {
767 nobj = 0;
768 wp = nil;
771 // Initialize sbuf
772 scanbuffers = &bufferList[runtime_m()->helpgc];
774 sbuf.ptr.begin = sbuf.ptr.pos = &scanbuffers->ptrtarget[0];
775 sbuf.ptr.end = sbuf.ptr.begin + nelem(scanbuffers->ptrtarget);
777 sbuf.obj.begin = sbuf.obj.pos = &scanbuffers->obj[0];
778 sbuf.obj.end = sbuf.obj.begin + nelem(scanbuffers->obj);
780 sbuf.wbuf = wbuf;
781 sbuf.wp = wp;
782 sbuf.nobj = nobj;
784 // (Silence the compiler)
785 #if 0
786 chan = nil;
787 chantype = nil;
788 chan_ret = nil;
789 #endif
791 goto next_block;
793 for(;;) {
794 // Each iteration scans the block b of length n, queueing pointers in
795 // the work buffer.
797 if(CollectStats) {
798 runtime_xadd64(&gcstats.nbytes, n);
799 runtime_xadd64(&gcstats.obj.sum, sbuf.nobj);
800 runtime_xadd64(&gcstats.obj.cnt, 1);
803 if(ti != 0 && false) {
804 if(Debug > 1) {
805 runtime_printf("scanblock %p %D ti %p\n", b, (int64)n, ti);
807 pc = (uintptr*)(ti & ~(uintptr)PC_BITS);
808 precise_type = (ti & PRECISE);
809 stack_top.elemsize = pc[0];
810 if(!precise_type)
811 nominal_size = pc[0];
812 if(ti & LOOP) {
813 stack_top.count = 0; // 0 means an infinite number of iterations
814 stack_top.loop_or_ret = pc+1;
815 } else {
816 stack_top.count = 1;
818 if(Debug) {
819 // Simple sanity check for provided type info ti:
820 // The declared size of the object must be not larger than the actual size
821 // (it can be smaller due to inferior pointers).
822 // It's difficult to make a comprehensive check due to inferior pointers,
823 // reflection, gob, etc.
824 if(pc[0] > n) {
825 runtime_printf("invalid gc type info: type info size %p, block size %p\n", pc[0], n);
826 runtime_throw("invalid gc type info");
829 } else if(UseSpanType && false) {
830 if(CollectStats)
831 runtime_xadd64(&gcstats.obj.notype, 1);
833 #if 0
834 type = runtime_gettype(b);
835 if(type != 0) {
836 if(CollectStats)
837 runtime_xadd64(&gcstats.obj.typelookup, 1);
839 t = (Type*)(type & ~(uintptr)(PtrSize-1));
840 switch(type & (PtrSize-1)) {
841 case TypeInfo_SingleObject:
842 pc = (uintptr*)t->gc;
843 precise_type = true; // type information about 'b' is precise
844 stack_top.count = 1;
845 stack_top.elemsize = pc[0];
846 break;
847 case TypeInfo_Array:
848 pc = (uintptr*)t->gc;
849 if(pc[0] == 0)
850 goto next_block;
851 precise_type = true; // type information about 'b' is precise
852 stack_top.count = 0; // 0 means an infinite number of iterations
853 stack_top.elemsize = pc[0];
854 stack_top.loop_or_ret = pc+1;
855 break;
856 case TypeInfo_Chan:
857 chan = (Hchan*)b;
858 chantype = (ChanType*)t;
859 chan_ret = nil;
860 pc = chanProg;
861 break;
862 default:
863 if(Debug > 1)
864 runtime_printf("scanblock %p %D type %p %S\n", b, (int64)n, type, *t->string);
865 runtime_throw("scanblock: invalid type");
866 return;
868 if(Debug > 1)
869 runtime_printf("scanblock %p %D type %p %S pc=%p\n", b, (int64)n, type, *t->string, pc);
870 } else {
871 pc = defaultProg;
872 if(Debug > 1)
873 runtime_printf("scanblock %p %D unknown type\n", b, (int64)n);
875 #endif
876 } else {
877 pc = defaultProg;
878 if(Debug > 1)
879 runtime_printf("scanblock %p %D no span types\n", b, (int64)n);
882 if(IgnorePreciseGC)
883 pc = defaultProg;
885 pc++;
886 stack_top.b = (uintptr)b;
887 end_b = (uintptr)b + n - PtrSize;
889 for(;;) {
890 if(CollectStats)
891 runtime_xadd64(&gcstats.instr[pc[0]], 1);
893 obj = nil;
894 objti = 0;
895 switch(pc[0]) {
896 case GC_PTR:
897 obj = *(void**)(stack_top.b + pc[1]);
898 objti = pc[2];
899 if(Debug > 2)
900 runtime_printf("gc_ptr @%p: %p ti=%p\n", stack_top.b+pc[1], obj, objti);
901 pc += 3;
902 if(Debug)
903 checkptr(obj, objti);
904 break;
906 case GC_SLICE:
907 sliceptr = (Slice*)(stack_top.b + pc[1]);
908 if(Debug > 2)
909 runtime_printf("gc_slice @%p: %p/%D/%D\n", sliceptr, sliceptr->array, (int64)sliceptr->__count, (int64)sliceptr->cap);
910 if(sliceptr->cap != 0) {
911 obj = sliceptr->array;
912 // Can't use slice element type for scanning,
913 // because if it points to an array embedded
914 // in the beginning of a struct,
915 // we will scan the whole struct as the slice.
916 // So just obtain type info from heap.
918 pc += 3;
919 break;
921 case GC_APTR:
922 obj = *(void**)(stack_top.b + pc[1]);
923 if(Debug > 2)
924 runtime_printf("gc_aptr @%p: %p\n", stack_top.b+pc[1], obj);
925 pc += 2;
926 break;
928 case GC_STRING:
929 stringptr = (String*)(stack_top.b + pc[1]);
930 if(Debug > 2)
931 runtime_printf("gc_string @%p: %p/%D\n", stack_top.b+pc[1], stringptr->str, (int64)stringptr->len);
932 if(stringptr->len != 0)
933 markonly(stringptr->str);
934 pc += 2;
935 continue;
937 case GC_EFACE:
938 eface = (Eface*)(stack_top.b + pc[1]);
939 pc += 2;
940 if(Debug > 2)
941 runtime_printf("gc_eface @%p: %p %p\n", stack_top.b+pc[1], eface->__type_descriptor, eface->__object);
942 if(eface->__type_descriptor == nil)
943 continue;
945 // eface->type
946 t = eface->__type_descriptor;
947 if((const byte*)t >= arena_start && (const byte*)t < arena_used) {
948 union { const Type *tc; Type *tr; } u;
949 u.tc = t;
950 *sbuf.ptr.pos++ = (PtrTarget){u.tr, 0};
951 if(sbuf.ptr.pos == sbuf.ptr.end)
952 flushptrbuf(&sbuf);
955 // eface->__object
956 if((byte*)eface->__object >= arena_start && (byte*)eface->__object < arena_used) {
957 if(t->__size <= sizeof(void*)) {
958 if((t->__code & KindNoPointers))
959 continue;
961 obj = eface->__object;
962 if((t->__code & ~KindNoPointers) == KindPtr) {
963 // Only use type information if it is a pointer-containing type.
964 // This matches the GC programs written by cmd/gc/reflect.c's
965 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
966 et = ((const PtrType*)t)->elem;
967 if(!(et->__code & KindNoPointers))
968 // objti = (uintptr)((const PtrType*)t)->elem->gc;
969 objti = 0;
971 } else {
972 obj = eface->__object;
973 // objti = (uintptr)t->gc;
974 objti = 0;
977 break;
979 case GC_IFACE:
980 iface = (Iface*)(stack_top.b + pc[1]);
981 pc += 2;
982 if(Debug > 2)
983 runtime_printf("gc_iface @%p: %p/%p %p\n", stack_top.b+pc[1], iface->__methods[0], nil, iface->__object);
984 if(iface->tab == nil)
985 continue;
987 // iface->tab
988 if((byte*)iface->tab >= arena_start && (byte*)iface->tab < arena_used) {
989 *sbuf.ptr.pos++ = (PtrTarget){iface->tab, /* (uintptr)itabtype->gc */ 0};
990 if(sbuf.ptr.pos == sbuf.ptr.end)
991 flushptrbuf(&sbuf);
994 // iface->data
995 if((byte*)iface->__object >= arena_start && (byte*)iface->__object < arena_used) {
996 // t = iface->tab->type;
997 t = nil;
998 if(t->__size <= sizeof(void*)) {
999 if((t->__code & KindNoPointers))
1000 continue;
1002 obj = iface->__object;
1003 if((t->__code & ~KindNoPointers) == KindPtr) {
1004 // Only use type information if it is a pointer-containing type.
1005 // This matches the GC programs written by cmd/gc/reflect.c's
1006 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
1007 et = ((const PtrType*)t)->elem;
1008 if(!(et->__code & KindNoPointers))
1009 // objti = (uintptr)((const PtrType*)t)->elem->gc;
1010 objti = 0;
1012 } else {
1013 obj = iface->__object;
1014 // objti = (uintptr)t->gc;
1015 objti = 0;
1018 break;
1020 case GC_DEFAULT_PTR:
1021 while(stack_top.b <= end_b) {
1022 obj = *(byte**)stack_top.b;
1023 if(Debug > 2)
1024 runtime_printf("gc_default_ptr @%p: %p\n", stack_top.b, obj);
1025 stack_top.b += PtrSize;
1026 if((byte*)obj >= arena_start && (byte*)obj < arena_used) {
1027 *sbuf.ptr.pos++ = (PtrTarget){obj, 0};
1028 if(sbuf.ptr.pos == sbuf.ptr.end)
1029 flushptrbuf(&sbuf);
1032 goto next_block;
1034 case GC_END:
1035 if(--stack_top.count != 0) {
1036 // Next iteration of a loop if possible.
1037 stack_top.b += stack_top.elemsize;
1038 if(stack_top.b + stack_top.elemsize <= end_b+PtrSize) {
1039 pc = stack_top.loop_or_ret;
1040 continue;
1042 i = stack_top.b;
1043 } else {
1044 // Stack pop if possible.
1045 if(stack_ptr+1 < stack+nelem(stack)) {
1046 pc = stack_top.loop_or_ret;
1047 stack_top = *(++stack_ptr);
1048 continue;
1050 i = (uintptr)b + nominal_size;
1052 if(!precise_type) {
1053 // Quickly scan [b+i,b+n) for possible pointers.
1054 for(; i<=end_b; i+=PtrSize) {
1055 if(*(byte**)i != nil) {
1056 // Found a value that may be a pointer.
1057 // Do a rescan of the entire block.
1058 enqueue((Obj){b, n, 0}, &sbuf.wbuf, &sbuf.wp, &sbuf.nobj);
1059 if(CollectStats) {
1060 runtime_xadd64(&gcstats.rescan, 1);
1061 runtime_xadd64(&gcstats.rescanbytes, n);
1063 break;
1067 goto next_block;
1069 case GC_ARRAY_START:
1070 i = stack_top.b + pc[1];
1071 count = pc[2];
1072 elemsize = pc[3];
1073 pc += 4;
1075 // Stack push.
1076 *stack_ptr-- = stack_top;
1077 stack_top = (Frame){count, elemsize, i, pc};
1078 continue;
1080 case GC_ARRAY_NEXT:
1081 if(--stack_top.count != 0) {
1082 stack_top.b += stack_top.elemsize;
1083 pc = stack_top.loop_or_ret;
1084 } else {
1085 // Stack pop.
1086 stack_top = *(++stack_ptr);
1087 pc += 1;
1089 continue;
1091 case GC_CALL:
1092 // Stack push.
1093 *stack_ptr-- = stack_top;
1094 stack_top = (Frame){1, 0, stack_top.b + pc[1], pc+3 /*return address*/};
1095 pc = (uintptr*)((byte*)pc + *(int32*)(pc+2)); // target of the CALL instruction
1096 continue;
1098 case GC_REGION:
1099 obj = (void*)(stack_top.b + pc[1]);
1100 size = pc[2];
1101 objti = pc[3];
1102 pc += 4;
1104 if(Debug > 2)
1105 runtime_printf("gc_region @%p: %D %p\n", stack_top.b+pc[1], (int64)size, objti);
1106 *sbuf.obj.pos++ = (Obj){obj, size, objti};
1107 if(sbuf.obj.pos == sbuf.obj.end)
1108 flushobjbuf(&sbuf);
1109 continue;
1111 #if 0
1112 case GC_CHAN_PTR:
1113 chan = *(Hchan**)(stack_top.b + pc[1]);
1114 if(Debug > 2 && chan != nil)
1115 runtime_printf("gc_chan_ptr @%p: %p/%D/%D %p\n", stack_top.b+pc[1], chan, (int64)chan->qcount, (int64)chan->dataqsiz, pc[2]);
1116 if(chan == nil) {
1117 pc += 3;
1118 continue;
1120 if(markonly(chan)) {
1121 chantype = (ChanType*)pc[2];
1122 if(!(chantype->elem->__code & KindNoPointers)) {
1123 // Start chanProg.
1124 chan_ret = pc+3;
1125 pc = chanProg+1;
1126 continue;
1129 pc += 3;
1130 continue;
1132 case GC_CHAN:
1133 // There are no heap pointers in struct Hchan,
1134 // so we can ignore the leading sizeof(Hchan) bytes.
1135 if(!(chantype->elem->__code & KindNoPointers)) {
1136 // Channel's buffer follows Hchan immediately in memory.
1137 // Size of buffer (cap(c)) is second int in the chan struct.
1138 chancap = ((uintgo*)chan)[1];
1139 if(chancap > 0) {
1140 // TODO(atom): split into two chunks so that only the
1141 // in-use part of the circular buffer is scanned.
1142 // (Channel routines zero the unused part, so the current
1143 // code does not lead to leaks, it's just a little inefficient.)
1144 *sbuf.obj.pos++ = (Obj){(byte*)chan+runtime_Hchansize, chancap*chantype->elem->size,
1145 (uintptr)chantype->elem->gc | PRECISE | LOOP};
1146 if(sbuf.obj.pos == sbuf.obj.end)
1147 flushobjbuf(&sbuf);
1150 if(chan_ret == nil)
1151 goto next_block;
1152 pc = chan_ret;
1153 continue;
1154 #endif
1156 default:
1157 runtime_printf("runtime: invalid GC instruction %p at %p\n", pc[0], pc);
1158 runtime_throw("scanblock: invalid GC instruction");
1159 return;
1162 if((byte*)obj >= arena_start && (byte*)obj < arena_used) {
1163 *sbuf.ptr.pos++ = (PtrTarget){obj, objti};
1164 if(sbuf.ptr.pos == sbuf.ptr.end)
1165 flushptrbuf(&sbuf);
1169 next_block:
1170 // Done scanning [b, b+n). Prepare for the next iteration of
1171 // the loop by setting b, n, ti to the parameters for the next block.
1173 if(sbuf.nobj == 0) {
1174 flushptrbuf(&sbuf);
1175 flushobjbuf(&sbuf);
1177 if(sbuf.nobj == 0) {
1178 if(!keepworking) {
1179 if(sbuf.wbuf)
1180 putempty(sbuf.wbuf);
1181 return;
1183 // Emptied our buffer: refill.
1184 sbuf.wbuf = getfull(sbuf.wbuf);
1185 if(sbuf.wbuf == nil)
1186 return;
1187 sbuf.nobj = sbuf.wbuf->nobj;
1188 sbuf.wp = sbuf.wbuf->obj + sbuf.wbuf->nobj;
1192 // Fetch b from the work buffer.
1193 --sbuf.wp;
1194 b = sbuf.wp->p;
1195 n = sbuf.wp->n;
1196 ti = sbuf.wp->ti;
1197 sbuf.nobj--;
1201 static struct root_list* roots;
1203 void
1204 __go_register_gc_roots (struct root_list* r)
1206 // FIXME: This needs locking if multiple goroutines can call
1207 // dlopen simultaneously.
1208 r->next = roots;
1209 roots = r;
1212 // Append obj to the work buffer.
1213 // _wbuf, _wp, _nobj are input/output parameters and are specifying the work buffer.
1214 static void
1215 enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj)
1217 uintptr nobj, off;
1218 Obj *wp;
1219 Workbuf *wbuf;
1221 if(Debug > 1)
1222 runtime_printf("append obj(%p %D %p)\n", obj.p, (int64)obj.n, obj.ti);
1224 // Align obj.b to a word boundary.
1225 off = (uintptr)obj.p & (PtrSize-1);
1226 if(off != 0) {
1227 obj.p += PtrSize - off;
1228 obj.n -= PtrSize - off;
1229 obj.ti = 0;
1232 if(obj.p == nil || obj.n == 0)
1233 return;
1235 // Load work buffer state
1236 wp = *_wp;
1237 wbuf = *_wbuf;
1238 nobj = *_nobj;
1240 // If another proc wants a pointer, give it some.
1241 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
1242 wbuf->nobj = nobj;
1243 wbuf = handoff(wbuf);
1244 nobj = wbuf->nobj;
1245 wp = wbuf->obj + nobj;
1248 // If buffer is full, get a new one.
1249 if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
1250 if(wbuf != nil)
1251 wbuf->nobj = nobj;
1252 wbuf = getempty(wbuf);
1253 wp = wbuf->obj;
1254 nobj = 0;
1257 *wp = obj;
1258 wp++;
1259 nobj++;
1261 // Save work buffer state
1262 *_wp = wp;
1263 *_wbuf = wbuf;
1264 *_nobj = nobj;
1267 static void
1268 enqueue1(Workbuf **wbufp, Obj obj)
1270 Workbuf *wbuf;
1272 wbuf = *wbufp;
1273 if(wbuf->nobj >= nelem(wbuf->obj))
1274 *wbufp = wbuf = getempty(wbuf);
1275 wbuf->obj[wbuf->nobj++] = obj;
1278 static void
1279 markroot(ParFor *desc, uint32 i)
1281 Workbuf *wbuf;
1282 FinBlock *fb;
1283 MHeap *h;
1284 MSpan **allspans, *s;
1285 uint32 spanidx, sg;
1286 G *gp;
1287 void *p;
1289 USED(&desc);
1290 wbuf = getempty(nil);
1291 // Note: if you add a case here, please also update heapdump.c:dumproots.
1292 switch(i) {
1293 case RootData:
1294 // For gccgo this is both data and bss.
1296 struct root_list *pl;
1298 for(pl = roots; pl != nil; pl = pl->next) {
1299 struct root *pr = &pl->roots[0];
1300 while(1) {
1301 void *decl = pr->decl;
1302 if(decl == nil)
1303 break;
1304 enqueue1(&wbuf, (Obj){decl, pr->size, 0});
1305 pr++;
1309 break;
1311 case RootBss:
1312 // For gccgo we use this for all the other global roots.
1313 enqueue1(&wbuf, (Obj){(byte*)&runtime_m0, sizeof runtime_m0, 0});
1314 enqueue1(&wbuf, (Obj){(byte*)&runtime_g0, sizeof runtime_g0, 0});
1315 enqueue1(&wbuf, (Obj){(byte*)&runtime_allg, sizeof runtime_allg, 0});
1316 enqueue1(&wbuf, (Obj){(byte*)&runtime_allm, sizeof runtime_allm, 0});
1317 enqueue1(&wbuf, (Obj){(byte*)&runtime_allp, sizeof runtime_allp, 0});
1318 enqueue1(&wbuf, (Obj){(byte*)&work, sizeof work, 0});
1319 runtime_proc_scan(&wbuf, enqueue1);
1320 runtime_MProf_Mark(&wbuf, enqueue1);
1321 runtime_time_scan(&wbuf, enqueue1);
1322 runtime_netpoll_scan(&wbuf, enqueue1);
1323 break;
1325 case RootFinalizers:
1326 for(fb=allfin; fb; fb=fb->alllink)
1327 enqueue1(&wbuf, (Obj){(byte*)fb->fin, fb->cnt*sizeof(fb->fin[0]), 0});
1328 break;
1330 case RootSpanTypes:
1331 // mark span types and MSpan.specials (to walk spans only once)
1332 h = &runtime_mheap;
1333 sg = h->sweepgen;
1334 allspans = h->allspans;
1335 for(spanidx=0; spanidx<runtime_mheap.nspan; spanidx++) {
1336 Special *sp;
1337 SpecialFinalizer *spf;
1339 s = allspans[spanidx];
1340 if(s->sweepgen != sg) {
1341 runtime_printf("sweep %d %d\n", s->sweepgen, sg);
1342 runtime_throw("gc: unswept span");
1344 if(s->state != MSpanInUse)
1345 continue;
1346 // The garbage collector ignores type pointers stored in MSpan.types:
1347 // - Compiler-generated types are stored outside of heap.
1348 // - The reflect package has runtime-generated types cached in its data structures.
1349 // The garbage collector relies on finding the references via that cache.
1350 if(s->types.compression == MTypes_Words || s->types.compression == MTypes_Bytes)
1351 markonly((byte*)s->types.data);
1352 for(sp = s->specials; sp != nil; sp = sp->next) {
1353 if(sp->kind != KindSpecialFinalizer)
1354 continue;
1355 // don't mark finalized object, but scan it so we
1356 // retain everything it points to.
1357 spf = (SpecialFinalizer*)sp;
1358 // A finalizer can be set for an inner byte of an object, find object beginning.
1359 p = (void*)((s->start << PageShift) + spf->offset/s->elemsize*s->elemsize);
1360 enqueue1(&wbuf, (Obj){p, s->elemsize, 0});
1361 enqueue1(&wbuf, (Obj){(void*)&spf->fn, PtrSize, 0});
1362 enqueue1(&wbuf, (Obj){(void*)&spf->ft, PtrSize, 0});
1363 enqueue1(&wbuf, (Obj){(void*)&spf->ot, PtrSize, 0});
1366 break;
1368 case RootFlushCaches:
1369 flushallmcaches();
1370 break;
1372 default:
1373 // the rest is scanning goroutine stacks
1374 if(i - RootCount >= runtime_allglen)
1375 runtime_throw("markroot: bad index");
1376 gp = runtime_allg[i - RootCount];
1377 // remember when we've first observed the G blocked
1378 // needed only to output in traceback
1379 if((gp->status == Gwaiting || gp->status == Gsyscall) && gp->waitsince == 0)
1380 gp->waitsince = work.tstart;
1381 addstackroots(gp, &wbuf);
1382 break;
1386 if(wbuf)
1387 scanblock(wbuf, false);
1390 // Get an empty work buffer off the work.empty list,
1391 // allocating new buffers as needed.
1392 static Workbuf*
1393 getempty(Workbuf *b)
1395 if(b != nil)
1396 runtime_lfstackpush(&work.full, &b->node);
1397 b = (Workbuf*)runtime_lfstackpop(&work.empty);
1398 if(b == nil) {
1399 // Need to allocate.
1400 runtime_lock(&work);
1401 if(work.nchunk < sizeof *b) {
1402 work.nchunk = 1<<20;
1403 work.chunk = runtime_SysAlloc(work.nchunk, &mstats.gc_sys);
1404 if(work.chunk == nil)
1405 runtime_throw("runtime: cannot allocate memory");
1407 b = (Workbuf*)work.chunk;
1408 work.chunk += sizeof *b;
1409 work.nchunk -= sizeof *b;
1410 runtime_unlock(&work);
1412 b->nobj = 0;
1413 return b;
1416 static void
1417 putempty(Workbuf *b)
1419 if(CollectStats)
1420 runtime_xadd64(&gcstats.putempty, 1);
1422 runtime_lfstackpush(&work.empty, &b->node);
1425 // Get a full work buffer off the work.full list, or return nil.
1426 static Workbuf*
1427 getfull(Workbuf *b)
1429 M *m;
1430 int32 i;
1432 if(CollectStats)
1433 runtime_xadd64(&gcstats.getfull, 1);
1435 if(b != nil)
1436 runtime_lfstackpush(&work.empty, &b->node);
1437 b = (Workbuf*)runtime_lfstackpop(&work.full);
1438 if(b != nil || work.nproc == 1)
1439 return b;
1441 m = runtime_m();
1442 runtime_xadd(&work.nwait, +1);
1443 for(i=0;; i++) {
1444 if(work.full != 0) {
1445 runtime_xadd(&work.nwait, -1);
1446 b = (Workbuf*)runtime_lfstackpop(&work.full);
1447 if(b != nil)
1448 return b;
1449 runtime_xadd(&work.nwait, +1);
1451 if(work.nwait == work.nproc)
1452 return nil;
1453 if(i < 10) {
1454 m->gcstats.nprocyield++;
1455 runtime_procyield(20);
1456 } else if(i < 20) {
1457 m->gcstats.nosyield++;
1458 runtime_osyield();
1459 } else {
1460 m->gcstats.nsleep++;
1461 runtime_usleep(100);
1466 static Workbuf*
1467 handoff(Workbuf *b)
1469 M *m;
1470 int32 n;
1471 Workbuf *b1;
1473 m = runtime_m();
1475 // Make new buffer with half of b's pointers.
1476 b1 = getempty(nil);
1477 n = b->nobj/2;
1478 b->nobj -= n;
1479 b1->nobj = n;
1480 runtime_memmove(b1->obj, b->obj+b->nobj, n*sizeof b1->obj[0]);
1481 m->gcstats.nhandoff++;
1482 m->gcstats.nhandoffcnt += n;
1484 // Put b on full list - let first half of b get stolen.
1485 runtime_lfstackpush(&work.full, &b->node);
1486 return b1;
1489 static void
1490 addstackroots(G *gp, Workbuf **wbufp)
1492 switch(gp->status){
1493 default:
1494 runtime_printf("unexpected G.status %d (goroutine %p %D)\n", gp->status, gp, gp->goid);
1495 runtime_throw("mark - bad status");
1496 case Gdead:
1497 return;
1498 case Grunning:
1499 runtime_throw("mark - world not stopped");
1500 case Grunnable:
1501 case Gsyscall:
1502 case Gwaiting:
1503 break;
1506 #ifdef USING_SPLIT_STACK
1507 M *mp;
1508 void* sp;
1509 size_t spsize;
1510 void* next_segment;
1511 void* next_sp;
1512 void* initial_sp;
1514 if(gp == runtime_g()) {
1515 // Scanning our own stack.
1516 sp = __splitstack_find(nil, nil, &spsize, &next_segment,
1517 &next_sp, &initial_sp);
1518 } else if((mp = gp->m) != nil && mp->helpgc) {
1519 // gchelper's stack is in active use and has no interesting pointers.
1520 return;
1521 } else {
1522 // Scanning another goroutine's stack.
1523 // The goroutine is usually asleep (the world is stopped).
1525 // The exception is that if the goroutine is about to enter or might
1526 // have just exited a system call, it may be executing code such
1527 // as schedlock and may have needed to start a new stack segment.
1528 // Use the stack segment and stack pointer at the time of
1529 // the system call instead, since that won't change underfoot.
1530 if(gp->gcstack != nil) {
1531 sp = gp->gcstack;
1532 spsize = gp->gcstack_size;
1533 next_segment = gp->gcnext_segment;
1534 next_sp = gp->gcnext_sp;
1535 initial_sp = gp->gcinitial_sp;
1536 } else {
1537 sp = __splitstack_find_context(&gp->stack_context[0],
1538 &spsize, &next_segment,
1539 &next_sp, &initial_sp);
1542 if(sp != nil) {
1543 enqueue1(wbufp, (Obj){sp, spsize, 0});
1544 while((sp = __splitstack_find(next_segment, next_sp,
1545 &spsize, &next_segment,
1546 &next_sp, &initial_sp)) != nil)
1547 enqueue1(wbufp, (Obj){sp, spsize, 0});
1549 #else
1550 M *mp;
1551 byte* bottom;
1552 byte* top;
1554 if(gp == runtime_g()) {
1555 // Scanning our own stack.
1556 bottom = (byte*)&gp;
1557 } else if((mp = gp->m) != nil && mp->helpgc) {
1558 // gchelper's stack is in active use and has no interesting pointers.
1559 return;
1560 } else {
1561 // Scanning another goroutine's stack.
1562 // The goroutine is usually asleep (the world is stopped).
1563 bottom = (byte*)gp->gcnext_sp;
1564 if(bottom == nil)
1565 return;
1567 top = (byte*)gp->gcinitial_sp + gp->gcstack_size;
1568 if(top > bottom)
1569 enqueue1(wbufp, (Obj){bottom, top - bottom, 0});
1570 else
1571 enqueue1(wbufp, (Obj){top, bottom - top, 0});
1572 #endif
1575 void
1576 runtime_queuefinalizer(void *p, FuncVal *fn, const FuncType *ft, const PtrType *ot)
1578 FinBlock *block;
1579 Finalizer *f;
1581 runtime_lock(&finlock);
1582 if(finq == nil || finq->cnt == finq->cap) {
1583 if(finc == nil) {
1584 finc = runtime_persistentalloc(FinBlockSize, 0, &mstats.gc_sys);
1585 finc->cap = (FinBlockSize - sizeof(FinBlock)) / sizeof(Finalizer) + 1;
1586 finc->alllink = allfin;
1587 allfin = finc;
1589 block = finc;
1590 finc = block->next;
1591 block->next = finq;
1592 finq = block;
1594 f = &finq->fin[finq->cnt];
1595 finq->cnt++;
1596 f->fn = fn;
1597 f->ft = ft;
1598 f->ot = ot;
1599 f->arg = p;
1600 runtime_fingwake = true;
1601 runtime_unlock(&finlock);
1604 void
1605 runtime_iterate_finq(void (*callback)(FuncVal*, void*, const FuncType*, const PtrType*))
1607 FinBlock *fb;
1608 Finalizer *f;
1609 int32 i;
1611 for(fb = allfin; fb; fb = fb->alllink) {
1612 for(i = 0; i < fb->cnt; i++) {
1613 f = &fb->fin[i];
1614 callback(f->fn, f->arg, f->ft, f->ot);
1619 void
1620 runtime_MSpan_EnsureSwept(MSpan *s)
1622 M *m = runtime_m();
1623 G *g = runtime_g();
1624 uint32 sg;
1626 // Caller must disable preemption.
1627 // Otherwise when this function returns the span can become unswept again
1628 // (if GC is triggered on another goroutine).
1629 if(m->locks == 0 && m->mallocing == 0 && g != m->g0)
1630 runtime_throw("MSpan_EnsureSwept: m is not locked");
1632 sg = runtime_mheap.sweepgen;
1633 if(runtime_atomicload(&s->sweepgen) == sg)
1634 return;
1635 if(runtime_cas(&s->sweepgen, sg-2, sg-1)) {
1636 runtime_MSpan_Sweep(s);
1637 return;
1639 // unfortunate condition, and we don't have efficient means to wait
1640 while(runtime_atomicload(&s->sweepgen) != sg)
1641 runtime_osyield();
1644 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
1645 // It clears the mark bits in preparation for the next GC round.
1646 // Returns true if the span was returned to heap.
1647 bool
1648 runtime_MSpan_Sweep(MSpan *s)
1650 M *m;
1651 int32 cl, n, npages, nfree;
1652 uintptr size, off, *bitp, shift, bits;
1653 uint32 sweepgen;
1654 byte *p;
1655 MCache *c;
1656 byte *arena_start;
1657 MLink head, *end;
1658 byte *type_data;
1659 byte compression;
1660 uintptr type_data_inc;
1661 MLink *x;
1662 Special *special, **specialp, *y;
1663 bool res, sweepgenset;
1665 m = runtime_m();
1667 // It's critical that we enter this function with preemption disabled,
1668 // GC must not start while we are in the middle of this function.
1669 if(m->locks == 0 && m->mallocing == 0 && runtime_g() != m->g0)
1670 runtime_throw("MSpan_Sweep: m is not locked");
1671 sweepgen = runtime_mheap.sweepgen;
1672 if(s->state != MSpanInUse || s->sweepgen != sweepgen-1) {
1673 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1674 s->state, s->sweepgen, sweepgen);
1675 runtime_throw("MSpan_Sweep: bad span state");
1677 arena_start = runtime_mheap.arena_start;
1678 cl = s->sizeclass;
1679 size = s->elemsize;
1680 if(cl == 0) {
1681 n = 1;
1682 } else {
1683 // Chunk full of small blocks.
1684 npages = runtime_class_to_allocnpages[cl];
1685 n = (npages << PageShift) / size;
1687 res = false;
1688 nfree = 0;
1689 end = &head;
1690 c = m->mcache;
1691 sweepgenset = false;
1693 // mark any free objects in this span so we don't collect them
1694 for(x = s->freelist; x != nil; x = x->next) {
1695 // This is markonly(x) but faster because we don't need
1696 // atomic access and we're guaranteed to be pointing at
1697 // the head of a valid object.
1698 off = (uintptr*)x - (uintptr*)runtime_mheap.arena_start;
1699 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
1700 shift = off % wordsPerBitmapWord;
1701 *bitp |= bitMarked<<shift;
1704 // Unlink & free special records for any objects we're about to free.
1705 specialp = &s->specials;
1706 special = *specialp;
1707 while(special != nil) {
1708 // A finalizer can be set for an inner byte of an object, find object beginning.
1709 p = (byte*)(s->start << PageShift) + special->offset/size*size;
1710 off = (uintptr*)p - (uintptr*)arena_start;
1711 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1712 shift = off % wordsPerBitmapWord;
1713 bits = *bitp>>shift;
1714 if((bits & (bitAllocated|bitMarked)) == bitAllocated) {
1715 // Find the exact byte for which the special was setup
1716 // (as opposed to object beginning).
1717 p = (byte*)(s->start << PageShift) + special->offset;
1718 // about to free object: splice out special record
1719 y = special;
1720 special = special->next;
1721 *specialp = special;
1722 if(!runtime_freespecial(y, p, size, false)) {
1723 // stop freeing of object if it has a finalizer
1724 *bitp |= bitMarked << shift;
1726 } else {
1727 // object is still live: keep special record
1728 specialp = &special->next;
1729 special = *specialp;
1733 type_data = (byte*)s->types.data;
1734 type_data_inc = sizeof(uintptr);
1735 compression = s->types.compression;
1736 switch(compression) {
1737 case MTypes_Bytes:
1738 type_data += 8*sizeof(uintptr);
1739 type_data_inc = 1;
1740 break;
1743 // Sweep through n objects of given size starting at p.
1744 // This thread owns the span now, so it can manipulate
1745 // the block bitmap without atomic operations.
1746 p = (byte*)(s->start << PageShift);
1747 for(; n > 0; n--, p += size, type_data+=type_data_inc) {
1748 off = (uintptr*)p - (uintptr*)arena_start;
1749 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1750 shift = off % wordsPerBitmapWord;
1751 bits = *bitp>>shift;
1753 if((bits & bitAllocated) == 0)
1754 continue;
1756 if((bits & bitMarked) != 0) {
1757 *bitp &= ~(bitMarked<<shift);
1758 continue;
1761 if(runtime_debug.allocfreetrace)
1762 runtime_tracefree(p, size);
1764 // Clear mark and scan bits.
1765 *bitp &= ~((bitScan|bitMarked)<<shift);
1767 if(cl == 0) {
1768 // Free large span.
1769 runtime_unmarkspan(p, 1<<PageShift);
1770 s->needzero = 1;
1771 // important to set sweepgen before returning it to heap
1772 runtime_atomicstore(&s->sweepgen, sweepgen);
1773 sweepgenset = true;
1774 // See note about SysFault vs SysFree in malloc.goc.
1775 if(runtime_debug.efence)
1776 runtime_SysFault(p, size);
1777 else
1778 runtime_MHeap_Free(&runtime_mheap, s, 1);
1779 c->local_nlargefree++;
1780 c->local_largefree += size;
1781 runtime_xadd64(&mstats.next_gc, -(uint64)(size * (gcpercent + 100)/100));
1782 res = true;
1783 } else {
1784 // Free small object.
1785 switch(compression) {
1786 case MTypes_Words:
1787 *(uintptr*)type_data = 0;
1788 break;
1789 case MTypes_Bytes:
1790 *(byte*)type_data = 0;
1791 break;
1793 if(size > 2*sizeof(uintptr))
1794 ((uintptr*)p)[1] = (uintptr)0xdeaddeaddeaddeadll; // mark as "needs to be zeroed"
1795 else if(size > sizeof(uintptr))
1796 ((uintptr*)p)[1] = 0;
1798 end->next = (MLink*)p;
1799 end = (MLink*)p;
1800 nfree++;
1804 // We need to set s->sweepgen = h->sweepgen only when all blocks are swept,
1805 // because of the potential for a concurrent free/SetFinalizer.
1806 // But we need to set it before we make the span available for allocation
1807 // (return it to heap or mcentral), because allocation code assumes that a
1808 // span is already swept if available for allocation.
1810 if(!sweepgenset && nfree == 0) {
1811 // The span must be in our exclusive ownership until we update sweepgen,
1812 // check for potential races.
1813 if(s->state != MSpanInUse || s->sweepgen != sweepgen-1) {
1814 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1815 s->state, s->sweepgen, sweepgen);
1816 runtime_throw("MSpan_Sweep: bad span state after sweep");
1818 runtime_atomicstore(&s->sweepgen, sweepgen);
1820 if(nfree > 0) {
1821 c->local_nsmallfree[cl] += nfree;
1822 c->local_cachealloc -= nfree * size;
1823 runtime_xadd64(&mstats.next_gc, -(uint64)(nfree * size * (gcpercent + 100)/100));
1824 res = runtime_MCentral_FreeSpan(&runtime_mheap.central[cl], s, nfree, head.next, end);
1825 //MCentral_FreeSpan updates sweepgen
1827 return res;
1830 // State of background sweep.
1831 // Pretected by gclock.
1832 static struct
1834 G* g;
1835 bool parked;
1837 MSpan** spans;
1838 uint32 nspan;
1839 uint32 spanidx;
1840 } sweep;
1842 // background sweeping goroutine
1843 static void
1844 bgsweep(void* dummy __attribute__ ((unused)))
1846 runtime_g()->issystem = 1;
1847 for(;;) {
1848 while(runtime_sweepone() != (uintptr)-1) {
1849 gcstats.nbgsweep++;
1850 runtime_gosched();
1852 runtime_lock(&gclock);
1853 if(!runtime_mheap.sweepdone) {
1854 // It's possible if GC has happened between sweepone has
1855 // returned -1 and gclock lock.
1856 runtime_unlock(&gclock);
1857 continue;
1859 sweep.parked = true;
1860 runtime_g()->isbackground = true;
1861 runtime_parkunlock(&gclock, "GC sweep wait");
1862 runtime_g()->isbackground = false;
1866 // sweeps one span
1867 // returns number of pages returned to heap, or -1 if there is nothing to sweep
1868 uintptr
1869 runtime_sweepone(void)
1871 M *m = runtime_m();
1872 MSpan *s;
1873 uint32 idx, sg;
1874 uintptr npages;
1876 // increment locks to ensure that the goroutine is not preempted
1877 // in the middle of sweep thus leaving the span in an inconsistent state for next GC
1878 m->locks++;
1879 sg = runtime_mheap.sweepgen;
1880 for(;;) {
1881 idx = runtime_xadd(&sweep.spanidx, 1) - 1;
1882 if(idx >= sweep.nspan) {
1883 runtime_mheap.sweepdone = true;
1884 m->locks--;
1885 return (uintptr)-1;
1887 s = sweep.spans[idx];
1888 if(s->state != MSpanInUse) {
1889 s->sweepgen = sg;
1890 continue;
1892 if(s->sweepgen != sg-2 || !runtime_cas(&s->sweepgen, sg-2, sg-1))
1893 continue;
1894 if(s->incache)
1895 runtime_throw("sweep of incache span");
1896 npages = s->npages;
1897 if(!runtime_MSpan_Sweep(s))
1898 npages = 0;
1899 m->locks--;
1900 return npages;
1904 static void
1905 dumpspan(uint32 idx)
1907 int32 sizeclass, n, npages, i, column;
1908 uintptr size;
1909 byte *p;
1910 byte *arena_start;
1911 MSpan *s;
1912 bool allocated;
1914 s = runtime_mheap.allspans[idx];
1915 if(s->state != MSpanInUse)
1916 return;
1917 arena_start = runtime_mheap.arena_start;
1918 p = (byte*)(s->start << PageShift);
1919 sizeclass = s->sizeclass;
1920 size = s->elemsize;
1921 if(sizeclass == 0) {
1922 n = 1;
1923 } else {
1924 npages = runtime_class_to_allocnpages[sizeclass];
1925 n = (npages << PageShift) / size;
1928 runtime_printf("%p .. %p:\n", p, p+n*size);
1929 column = 0;
1930 for(; n>0; n--, p+=size) {
1931 uintptr off, *bitp, shift, bits;
1933 off = (uintptr*)p - (uintptr*)arena_start;
1934 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1935 shift = off % wordsPerBitmapWord;
1936 bits = *bitp>>shift;
1938 allocated = ((bits & bitAllocated) != 0);
1940 for(i=0; (uint32)i<size; i+=sizeof(void*)) {
1941 if(column == 0) {
1942 runtime_printf("\t");
1944 if(i == 0) {
1945 runtime_printf(allocated ? "(" : "[");
1946 runtime_printf("%p: ", p+i);
1947 } else {
1948 runtime_printf(" ");
1951 runtime_printf("%p", *(void**)(p+i));
1953 if(i+sizeof(void*) >= size) {
1954 runtime_printf(allocated ? ") " : "] ");
1957 column++;
1958 if(column == 8) {
1959 runtime_printf("\n");
1960 column = 0;
1964 runtime_printf("\n");
1967 // A debugging function to dump the contents of memory
1968 void
1969 runtime_memorydump(void)
1971 uint32 spanidx;
1973 for(spanidx=0; spanidx<runtime_mheap.nspan; spanidx++) {
1974 dumpspan(spanidx);
1978 void
1979 runtime_gchelper(void)
1981 uint32 nproc;
1983 runtime_m()->traceback = 2;
1984 gchelperstart();
1986 // parallel mark for over gc roots
1987 runtime_parfordo(work.markfor);
1989 // help other threads scan secondary blocks
1990 scanblock(nil, true);
1992 bufferList[runtime_m()->helpgc].busy = 0;
1993 nproc = work.nproc; // work.nproc can change right after we increment work.ndone
1994 if(runtime_xadd(&work.ndone, +1) == nproc-1)
1995 runtime_notewakeup(&work.alldone);
1996 runtime_m()->traceback = 0;
1999 static void
2000 cachestats(void)
2002 MCache *c;
2003 P *p, **pp;
2005 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
2006 c = p->mcache;
2007 if(c==nil)
2008 continue;
2009 runtime_purgecachedstats(c);
2013 static void
2014 flushallmcaches(void)
2016 P *p, **pp;
2017 MCache *c;
2019 // Flush MCache's to MCentral.
2020 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
2021 c = p->mcache;
2022 if(c==nil)
2023 continue;
2024 runtime_MCache_ReleaseAll(c);
2028 void
2029 runtime_updatememstats(GCStats *stats)
2031 M *mp;
2032 MSpan *s;
2033 uint32 i;
2034 uint64 stacks_inuse, smallfree;
2035 uint64 *src, *dst;
2037 if(stats)
2038 runtime_memclr((byte*)stats, sizeof(*stats));
2039 stacks_inuse = 0;
2040 for(mp=runtime_allm; mp; mp=mp->alllink) {
2041 //stacks_inuse += mp->stackinuse*FixedStack;
2042 if(stats) {
2043 src = (uint64*)&mp->gcstats;
2044 dst = (uint64*)stats;
2045 for(i=0; i<sizeof(*stats)/sizeof(uint64); i++)
2046 dst[i] += src[i];
2047 runtime_memclr((byte*)&mp->gcstats, sizeof(mp->gcstats));
2050 mstats.stacks_inuse = stacks_inuse;
2051 mstats.mcache_inuse = runtime_mheap.cachealloc.inuse;
2052 mstats.mspan_inuse = runtime_mheap.spanalloc.inuse;
2053 mstats.sys = mstats.heap_sys + mstats.stacks_sys + mstats.mspan_sys +
2054 mstats.mcache_sys + mstats.buckhash_sys + mstats.gc_sys + mstats.other_sys;
2056 // Calculate memory allocator stats.
2057 // During program execution we only count number of frees and amount of freed memory.
2058 // Current number of alive object in the heap and amount of alive heap memory
2059 // are calculated by scanning all spans.
2060 // Total number of mallocs is calculated as number of frees plus number of alive objects.
2061 // Similarly, total amount of allocated memory is calculated as amount of freed memory
2062 // plus amount of alive heap memory.
2063 mstats.alloc = 0;
2064 mstats.total_alloc = 0;
2065 mstats.nmalloc = 0;
2066 mstats.nfree = 0;
2067 for(i = 0; i < nelem(mstats.by_size); i++) {
2068 mstats.by_size[i].nmalloc = 0;
2069 mstats.by_size[i].nfree = 0;
2072 // Flush MCache's to MCentral.
2073 flushallmcaches();
2075 // Aggregate local stats.
2076 cachestats();
2078 // Scan all spans and count number of alive objects.
2079 for(i = 0; i < runtime_mheap.nspan; i++) {
2080 s = runtime_mheap.allspans[i];
2081 if(s->state != MSpanInUse)
2082 continue;
2083 if(s->sizeclass == 0) {
2084 mstats.nmalloc++;
2085 mstats.alloc += s->elemsize;
2086 } else {
2087 mstats.nmalloc += s->ref;
2088 mstats.by_size[s->sizeclass].nmalloc += s->ref;
2089 mstats.alloc += s->ref*s->elemsize;
2093 // Aggregate by size class.
2094 smallfree = 0;
2095 mstats.nfree = runtime_mheap.nlargefree;
2096 for(i = 0; i < nelem(mstats.by_size); i++) {
2097 mstats.nfree += runtime_mheap.nsmallfree[i];
2098 mstats.by_size[i].nfree = runtime_mheap.nsmallfree[i];
2099 mstats.by_size[i].nmalloc += runtime_mheap.nsmallfree[i];
2100 smallfree += runtime_mheap.nsmallfree[i] * runtime_class_to_size[i];
2102 mstats.nmalloc += mstats.nfree;
2104 // Calculate derived stats.
2105 mstats.total_alloc = mstats.alloc + runtime_mheap.largefree + smallfree;
2106 mstats.heap_alloc = mstats.alloc;
2107 mstats.heap_objects = mstats.nmalloc - mstats.nfree;
2110 // Structure of arguments passed to function gc().
2111 // This allows the arguments to be passed via runtime_mcall.
2112 struct gc_args
2114 int64 start_time; // start time of GC in ns (just before stoptheworld)
2115 bool eagersweep;
2118 static void gc(struct gc_args *args);
2119 static void mgc(G *gp);
2121 static int32
2122 readgogc(void)
2124 const byte *p;
2126 p = runtime_getenv("GOGC");
2127 if(p == nil || p[0] == '\0')
2128 return 100;
2129 if(runtime_strcmp((const char *)p, "off") == 0)
2130 return -1;
2131 return runtime_atoi(p);
2134 // force = 1 - do GC regardless of current heap usage
2135 // force = 2 - go GC and eager sweep
2136 void
2137 runtime_gc(int32 force)
2139 M *m;
2140 G *g;
2141 struct gc_args a;
2142 int32 i;
2144 // The atomic operations are not atomic if the uint64s
2145 // are not aligned on uint64 boundaries. This has been
2146 // a problem in the past.
2147 if((((uintptr)&work.empty) & 7) != 0)
2148 runtime_throw("runtime: gc work buffer is misaligned");
2149 if((((uintptr)&work.full) & 7) != 0)
2150 runtime_throw("runtime: gc work buffer is misaligned");
2152 // Make sure all registers are saved on stack so that
2153 // scanstack sees them.
2154 __builtin_unwind_init();
2156 // The gc is turned off (via enablegc) until
2157 // the bootstrap has completed.
2158 // Also, malloc gets called in the guts
2159 // of a number of libraries that might be
2160 // holding locks. To avoid priority inversion
2161 // problems, don't bother trying to run gc
2162 // while holding a lock. The next mallocgc
2163 // without a lock will do the gc instead.
2164 m = runtime_m();
2165 if(!mstats.enablegc || runtime_g() == m->g0 || m->locks > 0 || runtime_panicking)
2166 return;
2168 if(gcpercent == GcpercentUnknown) { // first time through
2169 runtime_lock(&runtime_mheap);
2170 if(gcpercent == GcpercentUnknown)
2171 gcpercent = readgogc();
2172 runtime_unlock(&runtime_mheap);
2174 if(gcpercent < 0)
2175 return;
2177 runtime_semacquire(&runtime_worldsema, false);
2178 if(force==0 && mstats.heap_alloc < mstats.next_gc) {
2179 // typically threads which lost the race to grab
2180 // worldsema exit here when gc is done.
2181 runtime_semrelease(&runtime_worldsema);
2182 return;
2185 // Ok, we're doing it! Stop everybody else
2186 a.start_time = runtime_nanotime();
2187 a.eagersweep = force >= 2;
2188 m->gcing = 1;
2189 runtime_stoptheworld();
2191 clearpools();
2193 // Run gc on the g0 stack. We do this so that the g stack
2194 // we're currently running on will no longer change. Cuts
2195 // the root set down a bit (g0 stacks are not scanned, and
2196 // we don't need to scan gc's internal state). Also an
2197 // enabler for copyable stacks.
2198 for(i = 0; i < (runtime_debug.gctrace > 1 ? 2 : 1); i++) {
2199 if(i > 0)
2200 a.start_time = runtime_nanotime();
2201 // switch to g0, call gc(&a), then switch back
2202 g = runtime_g();
2203 g->param = &a;
2204 g->status = Gwaiting;
2205 g->waitreason = "garbage collection";
2206 runtime_mcall(mgc);
2209 // all done
2210 m->gcing = 0;
2211 m->locks++;
2212 runtime_semrelease(&runtime_worldsema);
2213 runtime_starttheworld();
2214 m->locks--;
2216 // now that gc is done, kick off finalizer thread if needed
2217 if(!ConcurrentSweep) {
2218 // give the queued finalizers, if any, a chance to run
2219 runtime_gosched();
2220 } else {
2221 // For gccgo, let other goroutines run.
2222 runtime_gosched();
2226 static void
2227 mgc(G *gp)
2229 gc(gp->param);
2230 gp->param = nil;
2231 gp->status = Grunning;
2232 runtime_gogo(gp);
2235 static void
2236 gc(struct gc_args *args)
2238 M *m;
2239 int64 t0, t1, t2, t3, t4;
2240 uint64 heap0, heap1, obj, ninstr;
2241 GCStats stats;
2242 uint32 i;
2243 // Eface eface;
2245 m = runtime_m();
2247 if(runtime_debug.allocfreetrace)
2248 runtime_tracegc();
2250 m->traceback = 2;
2251 t0 = args->start_time;
2252 work.tstart = args->start_time;
2254 if(CollectStats)
2255 runtime_memclr((byte*)&gcstats, sizeof(gcstats));
2257 m->locks++; // disable gc during mallocs in parforalloc
2258 if(work.markfor == nil)
2259 work.markfor = runtime_parforalloc(MaxGcproc);
2260 m->locks--;
2262 if(itabtype == nil) {
2263 // get C pointer to the Go type "itab"
2264 // runtime_gc_itab_ptr(&eface);
2265 // itabtype = ((PtrType*)eface.__type_descriptor)->elem;
2268 t1 = 0;
2269 if(runtime_debug.gctrace)
2270 t1 = runtime_nanotime();
2272 // Sweep what is not sweeped by bgsweep.
2273 while(runtime_sweepone() != (uintptr)-1)
2274 gcstats.npausesweep++;
2276 work.nwait = 0;
2277 work.ndone = 0;
2278 work.nproc = runtime_gcprocs();
2279 runtime_parforsetup(work.markfor, work.nproc, RootCount + runtime_allglen, nil, false, markroot);
2280 if(work.nproc > 1) {
2281 runtime_noteclear(&work.alldone);
2282 runtime_helpgc(work.nproc);
2285 t2 = 0;
2286 if(runtime_debug.gctrace)
2287 t2 = runtime_nanotime();
2289 gchelperstart();
2290 runtime_parfordo(work.markfor);
2291 scanblock(nil, true);
2293 t3 = 0;
2294 if(runtime_debug.gctrace)
2295 t3 = runtime_nanotime();
2297 bufferList[m->helpgc].busy = 0;
2298 if(work.nproc > 1)
2299 runtime_notesleep(&work.alldone);
2301 cachestats();
2302 // next_gc calculation is tricky with concurrent sweep since we don't know size of live heap
2303 // estimate what was live heap size after previous GC (for tracing only)
2304 heap0 = mstats.next_gc*100/(gcpercent+100);
2305 // conservatively set next_gc to high value assuming that everything is live
2306 // concurrent/lazy sweep will reduce this number while discovering new garbage
2307 mstats.next_gc = mstats.heap_alloc+mstats.heap_alloc*gcpercent/100;
2309 t4 = runtime_nanotime();
2310 mstats.last_gc = runtime_unixnanotime(); // must be Unix time to make sense to user
2311 mstats.pause_ns[mstats.numgc%nelem(mstats.pause_ns)] = t4 - t0;
2312 mstats.pause_total_ns += t4 - t0;
2313 mstats.numgc++;
2314 if(mstats.debuggc)
2315 runtime_printf("pause %D\n", t4-t0);
2317 if(runtime_debug.gctrace) {
2318 heap1 = mstats.heap_alloc;
2319 runtime_updatememstats(&stats);
2320 if(heap1 != mstats.heap_alloc) {
2321 runtime_printf("runtime: mstats skew: heap=%D/%D\n", heap1, mstats.heap_alloc);
2322 runtime_throw("mstats skew");
2324 obj = mstats.nmalloc - mstats.nfree;
2326 stats.nprocyield += work.markfor->nprocyield;
2327 stats.nosyield += work.markfor->nosyield;
2328 stats.nsleep += work.markfor->nsleep;
2330 runtime_printf("gc%d(%d): %D+%D+%D+%D us, %D -> %D MB, %D (%D-%D) objects,"
2331 " %d/%d/%d sweeps,"
2332 " %D(%D) handoff, %D(%D) steal, %D/%D/%D yields\n",
2333 mstats.numgc, work.nproc, (t1-t0)/1000, (t2-t1)/1000, (t3-t2)/1000, (t4-t3)/1000,
2334 heap0>>20, heap1>>20, obj,
2335 mstats.nmalloc, mstats.nfree,
2336 sweep.nspan, gcstats.nbgsweep, gcstats.npausesweep,
2337 stats.nhandoff, stats.nhandoffcnt,
2338 work.markfor->nsteal, work.markfor->nstealcnt,
2339 stats.nprocyield, stats.nosyield, stats.nsleep);
2340 gcstats.nbgsweep = gcstats.npausesweep = 0;
2341 if(CollectStats) {
2342 runtime_printf("scan: %D bytes, %D objects, %D untyped, %D types from MSpan\n",
2343 gcstats.nbytes, gcstats.obj.cnt, gcstats.obj.notype, gcstats.obj.typelookup);
2344 if(gcstats.ptr.cnt != 0)
2345 runtime_printf("avg ptrbufsize: %D (%D/%D)\n",
2346 gcstats.ptr.sum/gcstats.ptr.cnt, gcstats.ptr.sum, gcstats.ptr.cnt);
2347 if(gcstats.obj.cnt != 0)
2348 runtime_printf("avg nobj: %D (%D/%D)\n",
2349 gcstats.obj.sum/gcstats.obj.cnt, gcstats.obj.sum, gcstats.obj.cnt);
2350 runtime_printf("rescans: %D, %D bytes\n", gcstats.rescan, gcstats.rescanbytes);
2352 runtime_printf("instruction counts:\n");
2353 ninstr = 0;
2354 for(i=0; i<nelem(gcstats.instr); i++) {
2355 runtime_printf("\t%d:\t%D\n", i, gcstats.instr[i]);
2356 ninstr += gcstats.instr[i];
2358 runtime_printf("\ttotal:\t%D\n", ninstr);
2360 runtime_printf("putempty: %D, getfull: %D\n", gcstats.putempty, gcstats.getfull);
2362 runtime_printf("markonly base lookup: bit %D word %D span %D\n", gcstats.markonly.foundbit, gcstats.markonly.foundword, gcstats.markonly.foundspan);
2363 runtime_printf("flushptrbuf base lookup: bit %D word %D span %D\n", gcstats.flushptrbuf.foundbit, gcstats.flushptrbuf.foundword, gcstats.flushptrbuf.foundspan);
2367 // We cache current runtime_mheap.allspans array in sweep.spans,
2368 // because the former can be resized and freed.
2369 // Otherwise we would need to take heap lock every time
2370 // we want to convert span index to span pointer.
2372 // Free the old cached array if necessary.
2373 if(sweep.spans && sweep.spans != runtime_mheap.allspans)
2374 runtime_SysFree(sweep.spans, sweep.nspan*sizeof(sweep.spans[0]), &mstats.other_sys);
2375 // Cache the current array.
2376 runtime_mheap.sweepspans = runtime_mheap.allspans;
2377 runtime_mheap.sweepgen += 2;
2378 runtime_mheap.sweepdone = false;
2379 sweep.spans = runtime_mheap.allspans;
2380 sweep.nspan = runtime_mheap.nspan;
2381 sweep.spanidx = 0;
2383 // Temporary disable concurrent sweep, because we see failures on builders.
2384 if(ConcurrentSweep && !args->eagersweep) {
2385 runtime_lock(&gclock);
2386 if(sweep.g == nil)
2387 sweep.g = __go_go(bgsweep, nil);
2388 else if(sweep.parked) {
2389 sweep.parked = false;
2390 runtime_ready(sweep.g);
2392 runtime_unlock(&gclock);
2393 } else {
2394 // Sweep all spans eagerly.
2395 while(runtime_sweepone() != (uintptr)-1)
2396 gcstats.npausesweep++;
2399 runtime_MProf_GC();
2400 m->traceback = 0;
2403 extern uintptr runtime_sizeof_C_MStats
2404 __asm__ (GOSYM_PREFIX "runtime.Sizeof_C_MStats");
2406 void runtime_ReadMemStats(MStats *)
2407 __asm__ (GOSYM_PREFIX "runtime.ReadMemStats");
2409 void
2410 runtime_ReadMemStats(MStats *stats)
2412 M *m;
2414 // Have to acquire worldsema to stop the world,
2415 // because stoptheworld can only be used by
2416 // one goroutine at a time, and there might be
2417 // a pending garbage collection already calling it.
2418 runtime_semacquire(&runtime_worldsema, false);
2419 m = runtime_m();
2420 m->gcing = 1;
2421 runtime_stoptheworld();
2422 runtime_updatememstats(nil);
2423 // Size of the trailing by_size array differs between Go and C,
2424 // NumSizeClasses was changed, but we can not change Go struct because of backward compatibility.
2425 runtime_memmove(stats, &mstats, runtime_sizeof_C_MStats);
2426 m->gcing = 0;
2427 m->locks++;
2428 runtime_semrelease(&runtime_worldsema);
2429 runtime_starttheworld();
2430 m->locks--;
2433 void runtime_debug_readGCStats(Slice*)
2434 __asm__("runtime_debug.readGCStats");
2436 void
2437 runtime_debug_readGCStats(Slice *pauses)
2439 uint64 *p;
2440 uint32 i, n;
2442 // Calling code in runtime/debug should make the slice large enough.
2443 if((size_t)pauses->cap < nelem(mstats.pause_ns)+3)
2444 runtime_throw("runtime: short slice passed to readGCStats");
2446 // Pass back: pauses, last gc (absolute time), number of gc, total pause ns.
2447 p = (uint64*)pauses->array;
2448 runtime_lock(&runtime_mheap);
2449 n = mstats.numgc;
2450 if(n > nelem(mstats.pause_ns))
2451 n = nelem(mstats.pause_ns);
2453 // The pause buffer is circular. The most recent pause is at
2454 // pause_ns[(numgc-1)%nelem(pause_ns)], and then backward
2455 // from there to go back farther in time. We deliver the times
2456 // most recent first (in p[0]).
2457 for(i=0; i<n; i++)
2458 p[i] = mstats.pause_ns[(mstats.numgc-1-i)%nelem(mstats.pause_ns)];
2460 p[n] = mstats.last_gc;
2461 p[n+1] = mstats.numgc;
2462 p[n+2] = mstats.pause_total_ns;
2463 runtime_unlock(&runtime_mheap);
2464 pauses->__count = n+3;
2467 int32
2468 runtime_setgcpercent(int32 in) {
2469 int32 out;
2471 runtime_lock(&runtime_mheap);
2472 if(gcpercent == GcpercentUnknown)
2473 gcpercent = readgogc();
2474 out = gcpercent;
2475 if(in < 0)
2476 in = -1;
2477 gcpercent = in;
2478 runtime_unlock(&runtime_mheap);
2479 return out;
2482 static void
2483 gchelperstart(void)
2485 M *m;
2487 m = runtime_m();
2488 if(m->helpgc < 0 || m->helpgc >= MaxGcproc)
2489 runtime_throw("gchelperstart: bad m->helpgc");
2490 if(runtime_xchg(&bufferList[m->helpgc].busy, 1))
2491 runtime_throw("gchelperstart: already busy");
2492 if(runtime_g() != m->g0)
2493 runtime_throw("gchelper not running on g0 stack");
2496 static void
2497 runfinq(void* dummy __attribute__ ((unused)))
2499 Finalizer *f;
2500 FinBlock *fb, *next;
2501 uint32 i;
2502 Eface ef;
2503 Iface iface;
2505 // This function blocks for long periods of time, and because it is written in C
2506 // we have no liveness information. Zero everything so that uninitialized pointers
2507 // do not cause memory leaks.
2508 f = nil;
2509 fb = nil;
2510 next = nil;
2511 i = 0;
2512 ef.__type_descriptor = nil;
2513 ef.__object = nil;
2515 // force flush to memory
2516 USED(&f);
2517 USED(&fb);
2518 USED(&next);
2519 USED(&i);
2520 USED(&ef);
2522 for(;;) {
2523 runtime_lock(&finlock);
2524 fb = finq;
2525 finq = nil;
2526 if(fb == nil) {
2527 runtime_fingwait = true;
2528 runtime_g()->isbackground = true;
2529 runtime_parkunlock(&finlock, "finalizer wait");
2530 runtime_g()->isbackground = false;
2531 continue;
2533 runtime_unlock(&finlock);
2534 if(raceenabled)
2535 runtime_racefingo();
2536 for(; fb; fb=next) {
2537 next = fb->next;
2538 for(i=0; i<(uint32)fb->cnt; i++) {
2539 const Type *fint;
2540 void *param;
2542 f = &fb->fin[i];
2543 fint = ((const Type**)f->ft->__in.array)[0];
2544 if(fint->__code == KindPtr) {
2545 // direct use of pointer
2546 param = &f->arg;
2547 } else if(((const InterfaceType*)fint)->__methods.__count == 0) {
2548 // convert to empty interface
2549 ef.__type_descriptor = (const Type*)f->ot;
2550 ef.__object = f->arg;
2551 param = &ef;
2552 } else {
2553 // convert to interface with methods
2554 iface.__methods = __go_convert_interface_2((const Type*)fint,
2555 (const Type*)f->ot,
2557 iface.__object = f->arg;
2558 if(iface.__methods == nil)
2559 runtime_throw("invalid type conversion in runfinq");
2560 param = &iface;
2562 reflect_call(f->ft, f->fn, 0, 0, &param, nil);
2563 f->fn = nil;
2564 f->arg = nil;
2565 f->ot = nil;
2567 fb->cnt = 0;
2568 runtime_lock(&finlock);
2569 fb->next = finc;
2570 finc = fb;
2571 runtime_unlock(&finlock);
2574 // Zero everything that's dead, to avoid memory leaks.
2575 // See comment at top of function.
2576 f = nil;
2577 fb = nil;
2578 next = nil;
2579 i = 0;
2580 ef.__type_descriptor = nil;
2581 ef.__object = nil;
2582 runtime_gc(1); // trigger another gc to clean up the finalized objects, if possible
2586 void
2587 runtime_createfing(void)
2589 if(fing != nil)
2590 return;
2591 // Here we use gclock instead of finlock,
2592 // because newproc1 can allocate, which can cause on-demand span sweep,
2593 // which can queue finalizers, which would deadlock.
2594 runtime_lock(&gclock);
2595 if(fing == nil)
2596 fing = __go_go(runfinq, nil);
2597 runtime_unlock(&gclock);
2601 runtime_wakefing(void)
2603 G *res;
2605 res = nil;
2606 runtime_lock(&finlock);
2607 if(runtime_fingwait && runtime_fingwake) {
2608 runtime_fingwait = false;
2609 runtime_fingwake = false;
2610 res = fing;
2612 runtime_unlock(&finlock);
2613 return res;
2616 void
2617 runtime_marknogc(void *v)
2619 uintptr *b, off, shift;
2621 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2622 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2623 shift = off % wordsPerBitmapWord;
2624 *b = (*b & ~(bitAllocated<<shift)) | bitBlockBoundary<<shift;
2627 void
2628 runtime_markscan(void *v)
2630 uintptr *b, off, shift;
2632 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2633 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2634 shift = off % wordsPerBitmapWord;
2635 *b |= bitScan<<shift;
2638 // mark the block at v as freed.
2639 void
2640 runtime_markfreed(void *v)
2642 uintptr *b, off, shift;
2644 if(0)
2645 runtime_printf("markfreed %p\n", v);
2647 if((byte*)v > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2648 runtime_throw("markfreed: bad pointer");
2650 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2651 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2652 shift = off % wordsPerBitmapWord;
2653 *b = (*b & ~(bitMask<<shift)) | (bitAllocated<<shift);
2656 // check that the block at v of size n is marked freed.
2657 void
2658 runtime_checkfreed(void *v, uintptr n)
2660 uintptr *b, bits, off, shift;
2662 if(!runtime_checking)
2663 return;
2665 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2666 return; // not allocated, so okay
2668 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2669 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2670 shift = off % wordsPerBitmapWord;
2672 bits = *b>>shift;
2673 if((bits & bitAllocated) != 0) {
2674 runtime_printf("checkfreed %p+%p: off=%p have=%p\n",
2675 v, n, off, bits & bitMask);
2676 runtime_throw("checkfreed: not freed");
2680 // mark the span of memory at v as having n blocks of the given size.
2681 // if leftover is true, there is left over space at the end of the span.
2682 void
2683 runtime_markspan(void *v, uintptr size, uintptr n, bool leftover)
2685 uintptr *b, *b0, off, shift, i, x;
2686 byte *p;
2688 if((byte*)v+size*n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2689 runtime_throw("markspan: bad pointer");
2691 if(runtime_checking) {
2692 // bits should be all zero at the start
2693 off = (byte*)v + size - runtime_mheap.arena_start;
2694 b = (uintptr*)(runtime_mheap.arena_start - off/wordsPerBitmapWord);
2695 for(i = 0; i < size/PtrSize/wordsPerBitmapWord; i++) {
2696 if(b[i] != 0)
2697 runtime_throw("markspan: span bits not zero");
2701 p = v;
2702 if(leftover) // mark a boundary just past end of last block too
2703 n++;
2705 b0 = nil;
2706 x = 0;
2707 for(; n-- > 0; p += size) {
2708 // Okay to use non-atomic ops here, because we control
2709 // the entire span, and each bitmap word has bits for only
2710 // one span, so no other goroutines are changing these
2711 // bitmap words.
2712 off = (uintptr*)p - (uintptr*)runtime_mheap.arena_start; // word offset
2713 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2714 shift = off % wordsPerBitmapWord;
2715 if(b0 != b) {
2716 if(b0 != nil)
2717 *b0 = x;
2718 b0 = b;
2719 x = 0;
2721 x |= bitAllocated<<shift;
2723 *b0 = x;
2726 // unmark the span of memory at v of length n bytes.
2727 void
2728 runtime_unmarkspan(void *v, uintptr n)
2730 uintptr *p, *b, off;
2732 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2733 runtime_throw("markspan: bad pointer");
2735 p = v;
2736 off = p - (uintptr*)runtime_mheap.arena_start; // word offset
2737 if(off % wordsPerBitmapWord != 0)
2738 runtime_throw("markspan: unaligned pointer");
2739 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2740 n /= PtrSize;
2741 if(n%wordsPerBitmapWord != 0)
2742 runtime_throw("unmarkspan: unaligned length");
2743 // Okay to use non-atomic ops here, because we control
2744 // the entire span, and each bitmap word has bits for only
2745 // one span, so no other goroutines are changing these
2746 // bitmap words.
2747 n /= wordsPerBitmapWord;
2748 while(n-- > 0)
2749 *b-- = 0;
2752 void
2753 runtime_MHeap_MapBits(MHeap *h)
2755 size_t page_size;
2757 // Caller has added extra mappings to the arena.
2758 // Add extra mappings of bitmap words as needed.
2759 // We allocate extra bitmap pieces in chunks of bitmapChunk.
2760 enum {
2761 bitmapChunk = 8192
2763 uintptr n;
2765 n = (h->arena_used - h->arena_start) / wordsPerBitmapWord;
2766 n = ROUND(n, bitmapChunk);
2767 n = ROUND(n, PageSize);
2768 page_size = getpagesize();
2769 n = ROUND(n, page_size);
2770 if(h->bitmap_mapped >= n)
2771 return;
2773 runtime_SysMap(h->arena_start - n, n - h->bitmap_mapped, h->arena_reserved, &mstats.gc_sys);
2774 h->bitmap_mapped = n;