runtime: copy runtime package time code from Go 1.7
[official-gcc.git] / libgo / runtime / mgc0.c
blob0b96696ee4211bc4fb481f7b266102d605e46a18
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.
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 "go-type.h"
61 // Map gccgo field names to gc field names.
62 // Slice aka __go_open_array.
63 #define array __values
64 #define cap __capacity
65 // Iface aka __go_interface
66 #define tab __methods
67 // Hmap aka __go_map
68 typedef struct __go_map Hmap;
69 // Type aka __go_type_descriptor
70 #define string __reflection
71 // PtrType aka __go_ptr_type
72 #define elem __element_type
74 #ifdef USING_SPLIT_STACK
76 extern void * __splitstack_find (void *, void *, size_t *, void **, void **,
77 void **);
79 extern void * __splitstack_find_context (void *context[10], size_t *, void **,
80 void **, void **);
82 #endif
84 enum {
85 Debug = 0,
86 CollectStats = 0,
87 ConcurrentSweep = 1,
89 WorkbufSize = 16*1024,
90 FinBlockSize = 4*1024,
92 handoffThreshold = 4,
93 IntermediateBufferCapacity = 64,
95 // Bits in type information
96 PRECISE = 1,
97 LOOP = 2,
98 PC_BITS = PRECISE | LOOP,
100 RootData = 0,
101 RootBss = 1,
102 RootFinalizers = 2,
103 RootSpanTypes = 3,
104 RootFlushCaches = 4,
105 RootCount = 5,
108 #define GcpercentUnknown (-2)
110 // Initialized from $GOGC. GOGC=off means no gc.
111 static int32 gcpercent = GcpercentUnknown;
113 static FuncVal* poolcleanup;
115 void sync_runtime_registerPoolCleanup(FuncVal*)
116 __asm__ (GOSYM_PREFIX "sync.runtime_registerPoolCleanup");
118 void
119 sync_runtime_registerPoolCleanup(FuncVal *f)
121 poolcleanup = f;
124 static void
125 clearpools(void)
127 P *p, **pp;
128 MCache *c;
130 // clear sync.Pool's
131 if(poolcleanup != nil) {
132 __builtin_call_with_static_chain(poolcleanup->fn(),
133 poolcleanup);
136 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
137 // clear tinyalloc pool
138 c = p->mcache;
139 if(c != nil) {
140 c->tiny = nil;
141 c->tinysize = 0;
143 // clear defer pools
144 p->deferpool = nil;
148 typedef struct Workbuf Workbuf;
149 struct Workbuf
151 #define SIZE (WorkbufSize-sizeof(LFNode)-sizeof(uintptr))
152 LFNode node; // must be first
153 uintptr nobj;
154 Obj obj[SIZE/sizeof(Obj) - 1];
155 uint8 _padding[SIZE%sizeof(Obj) + sizeof(Obj)];
156 #undef SIZE
159 typedef struct Finalizer Finalizer;
160 struct Finalizer
162 FuncVal *fn;
163 void *arg;
164 const struct __go_func_type *ft;
165 const PtrType *ot;
168 typedef struct FinBlock FinBlock;
169 struct FinBlock
171 FinBlock *alllink;
172 FinBlock *next;
173 int32 cnt;
174 int32 cap;
175 Finalizer fin[1];
178 static Lock finlock; // protects the following variables
179 static FinBlock *finq; // list of finalizers that are to be executed
180 static FinBlock *finc; // cache of free blocks
181 static FinBlock *allfin; // list of all blocks
182 bool runtime_fingwait;
183 bool runtime_fingwake;
185 static Lock gclock;
186 static G* fing;
188 static void runfinq(void*);
189 static void bgsweep(void*);
190 static Workbuf* getempty(Workbuf*);
191 static Workbuf* getfull(Workbuf*);
192 static void putempty(Workbuf*);
193 static Workbuf* handoff(Workbuf*);
194 static void gchelperstart(void);
195 static void flushallmcaches(void);
196 static void addstackroots(G *gp, Workbuf **wbufp);
198 static struct {
199 uint64 full; // lock-free list of full blocks
200 uint64 wempty; // lock-free list of empty blocks
201 byte pad0[CacheLineSize]; // prevents false-sharing between full/empty and nproc/nwait
202 uint32 nproc;
203 int64 tstart;
204 volatile uint32 nwait;
205 volatile uint32 ndone;
206 Note alldone;
207 ParFor *markfor;
209 Lock;
210 byte *chunk;
211 uintptr nchunk;
212 } work __attribute__((aligned(8)));
214 enum {
215 GC_DEFAULT_PTR = GC_NUM_INSTR,
216 GC_CHAN,
218 GC_NUM_INSTR2
221 static struct {
222 struct {
223 uint64 sum;
224 uint64 cnt;
225 } ptr;
226 uint64 nbytes;
227 struct {
228 uint64 sum;
229 uint64 cnt;
230 uint64 notype;
231 uint64 typelookup;
232 } obj;
233 uint64 rescan;
234 uint64 rescanbytes;
235 uint64 instr[GC_NUM_INSTR2];
236 uint64 putempty;
237 uint64 getfull;
238 struct {
239 uint64 foundbit;
240 uint64 foundword;
241 uint64 foundspan;
242 } flushptrbuf;
243 struct {
244 uint64 foundbit;
245 uint64 foundword;
246 uint64 foundspan;
247 } markonly;
248 uint32 nbgsweep;
249 uint32 npausesweep;
250 } gcstats;
252 // markonly marks an object. It returns true if the object
253 // has been marked by this function, false otherwise.
254 // This function doesn't append the object to any buffer.
255 static bool
256 markonly(const void *obj)
258 byte *p;
259 uintptr *bitp, bits, shift, x, xbits, off, j;
260 MSpan *s;
261 PageID k;
263 // Words outside the arena cannot be pointers.
264 if((const byte*)obj < runtime_mheap.arena_start || (const byte*)obj >= runtime_mheap.arena_used)
265 return false;
267 // obj may be a pointer to a live object.
268 // Try to find the beginning of the object.
270 // Round down to word boundary.
271 obj = (const void*)((uintptr)obj & ~((uintptr)PtrSize-1));
273 // Find bits for this word.
274 off = (const uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
275 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
276 shift = off % wordsPerBitmapWord;
277 xbits = *bitp;
278 bits = xbits >> shift;
280 // Pointing at the beginning of a block?
281 if((bits & (bitAllocated|bitBlockBoundary)) != 0) {
282 if(CollectStats)
283 runtime_xadd64(&gcstats.markonly.foundbit, 1);
284 goto found;
287 // Pointing just past the beginning?
288 // Scan backward a little to find a block boundary.
289 for(j=shift; j-->0; ) {
290 if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
291 shift = j;
292 bits = xbits>>shift;
293 if(CollectStats)
294 runtime_xadd64(&gcstats.markonly.foundword, 1);
295 goto found;
299 // Otherwise consult span table to find beginning.
300 // (Manually inlined copy of MHeap_LookupMaybe.)
301 k = (uintptr)obj>>PageShift;
302 x = k;
303 x -= (uintptr)runtime_mheap.arena_start>>PageShift;
304 s = runtime_mheap.spans[x];
305 if(s == nil || k < s->start || (uintptr)obj >= s->limit || s->state != MSpanInUse)
306 return false;
307 p = (byte*)((uintptr)s->start<<PageShift);
308 if(s->sizeclass == 0) {
309 obj = p;
310 } else {
311 uintptr size = s->elemsize;
312 int32 i = ((const byte*)obj - p)/size;
313 obj = p+i*size;
316 // Now that we know the object header, reload bits.
317 off = (const uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
318 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
319 shift = off % wordsPerBitmapWord;
320 xbits = *bitp;
321 bits = xbits >> shift;
322 if(CollectStats)
323 runtime_xadd64(&gcstats.markonly.foundspan, 1);
325 found:
326 // Now we have bits, bitp, and shift correct for
327 // obj pointing at the base of the object.
328 // Only care about allocated and not marked.
329 if((bits & (bitAllocated|bitMarked)) != bitAllocated)
330 return false;
331 if(work.nproc == 1)
332 *bitp |= bitMarked<<shift;
333 else {
334 for(;;) {
335 x = *bitp;
336 if(x & (bitMarked<<shift))
337 return false;
338 if(runtime_casp((void**)bitp, (void*)x, (void*)(x|(bitMarked<<shift))))
339 break;
343 // The object is now marked
344 return true;
347 // PtrTarget is a structure used by intermediate buffers.
348 // The intermediate buffers hold GC data before it
349 // is moved/flushed to the work buffer (Workbuf).
350 // The size of an intermediate buffer is very small,
351 // such as 32 or 64 elements.
352 typedef struct PtrTarget PtrTarget;
353 struct PtrTarget
355 void *p;
356 uintptr ti;
359 typedef struct Scanbuf Scanbuf;
360 struct Scanbuf
362 struct {
363 PtrTarget *begin;
364 PtrTarget *end;
365 PtrTarget *pos;
366 } ptr;
367 struct {
368 Obj *begin;
369 Obj *end;
370 Obj *pos;
371 } obj;
372 Workbuf *wbuf;
373 Obj *wp;
374 uintptr nobj;
377 typedef struct BufferList BufferList;
378 struct BufferList
380 PtrTarget ptrtarget[IntermediateBufferCapacity];
381 Obj obj[IntermediateBufferCapacity];
382 uint32 busy;
383 byte pad[CacheLineSize];
385 static BufferList bufferList[MaxGcproc];
387 static void enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj);
389 // flushptrbuf moves data from the PtrTarget buffer to the work buffer.
390 // The PtrTarget buffer contains blocks irrespective of whether the blocks have been marked or scanned,
391 // while the work buffer contains blocks which have been marked
392 // and are prepared to be scanned by the garbage collector.
394 // _wp, _wbuf, _nobj are input/output parameters and are specifying the work buffer.
396 // A simplified drawing explaining how the todo-list moves from a structure to another:
398 // scanblock
399 // (find pointers)
400 // Obj ------> PtrTarget (pointer targets)
401 // ↑ |
402 // | |
403 // `----------'
404 // flushptrbuf
405 // (find block start, mark and enqueue)
406 static void
407 flushptrbuf(Scanbuf *sbuf)
409 byte *p, *arena_start, *obj;
410 uintptr size, *bitp, bits, shift, j, x, xbits, off, nobj, ti, n;
411 MSpan *s;
412 PageID k;
413 Obj *wp;
414 Workbuf *wbuf;
415 PtrTarget *ptrbuf;
416 PtrTarget *ptrbuf_end;
418 arena_start = runtime_mheap.arena_start;
420 wp = sbuf->wp;
421 wbuf = sbuf->wbuf;
422 nobj = sbuf->nobj;
424 ptrbuf = sbuf->ptr.begin;
425 ptrbuf_end = sbuf->ptr.pos;
426 n = ptrbuf_end - sbuf->ptr.begin;
427 sbuf->ptr.pos = sbuf->ptr.begin;
429 if(CollectStats) {
430 runtime_xadd64(&gcstats.ptr.sum, n);
431 runtime_xadd64(&gcstats.ptr.cnt, 1);
434 // If buffer is nearly full, get a new one.
435 if(wbuf == nil || nobj+n >= nelem(wbuf->obj)) {
436 if(wbuf != nil)
437 wbuf->nobj = nobj;
438 wbuf = getempty(wbuf);
439 wp = wbuf->obj;
440 nobj = 0;
442 if(n >= nelem(wbuf->obj))
443 runtime_throw("ptrbuf has to be smaller than WorkBuf");
446 while(ptrbuf < ptrbuf_end) {
447 obj = ptrbuf->p;
448 ti = ptrbuf->ti;
449 ptrbuf++;
451 // obj belongs to interval [mheap.arena_start, mheap.arena_used).
452 if(Debug > 1) {
453 if(obj < runtime_mheap.arena_start || obj >= runtime_mheap.arena_used)
454 runtime_throw("object is outside of mheap");
457 // obj may be a pointer to a live object.
458 // Try to find the beginning of the object.
460 // Round down to word boundary.
461 if(((uintptr)obj & ((uintptr)PtrSize-1)) != 0) {
462 obj = (void*)((uintptr)obj & ~((uintptr)PtrSize-1));
463 ti = 0;
466 // Find bits for this word.
467 off = (uintptr*)obj - (uintptr*)arena_start;
468 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
469 shift = off % wordsPerBitmapWord;
470 xbits = *bitp;
471 bits = xbits >> shift;
473 // Pointing at the beginning of a block?
474 if((bits & (bitAllocated|bitBlockBoundary)) != 0) {
475 if(CollectStats)
476 runtime_xadd64(&gcstats.flushptrbuf.foundbit, 1);
477 goto found;
480 ti = 0;
482 // Pointing just past the beginning?
483 // Scan backward a little to find a block boundary.
484 for(j=shift; j-->0; ) {
485 if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
486 obj = (byte*)obj - (shift-j)*PtrSize;
487 shift = j;
488 bits = xbits>>shift;
489 if(CollectStats)
490 runtime_xadd64(&gcstats.flushptrbuf.foundword, 1);
491 goto found;
495 // Otherwise consult span table to find beginning.
496 // (Manually inlined copy of MHeap_LookupMaybe.)
497 k = (uintptr)obj>>PageShift;
498 x = k;
499 x -= (uintptr)arena_start>>PageShift;
500 s = runtime_mheap.spans[x];
501 if(s == nil || k < s->start || (uintptr)obj >= s->limit || s->state != MSpanInUse)
502 continue;
503 p = (byte*)((uintptr)s->start<<PageShift);
504 if(s->sizeclass == 0) {
505 obj = p;
506 } else {
507 size = s->elemsize;
508 int32 i = ((byte*)obj - p)/size;
509 obj = p+i*size;
512 // Now that we know the object header, reload bits.
513 off = (uintptr*)obj - (uintptr*)arena_start;
514 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
515 shift = off % wordsPerBitmapWord;
516 xbits = *bitp;
517 bits = xbits >> shift;
518 if(CollectStats)
519 runtime_xadd64(&gcstats.flushptrbuf.foundspan, 1);
521 found:
522 // Now we have bits, bitp, and shift correct for
523 // obj pointing at the base of the object.
524 // Only care about allocated and not marked.
525 if((bits & (bitAllocated|bitMarked)) != bitAllocated)
526 continue;
527 if(work.nproc == 1)
528 *bitp |= bitMarked<<shift;
529 else {
530 for(;;) {
531 x = *bitp;
532 if(x & (bitMarked<<shift))
533 goto continue_obj;
534 if(runtime_casp((void**)bitp, (void*)x, (void*)(x|(bitMarked<<shift))))
535 break;
539 // If object has no pointers, don't need to scan further.
540 if((bits & bitScan) == 0)
541 continue;
543 // Ask span about size class.
544 // (Manually inlined copy of MHeap_Lookup.)
545 x = (uintptr)obj >> PageShift;
546 x -= (uintptr)arena_start>>PageShift;
547 s = runtime_mheap.spans[x];
549 PREFETCH(obj);
551 *wp = (Obj){obj, s->elemsize, ti};
552 wp++;
553 nobj++;
554 continue_obj:;
557 // If another proc wants a pointer, give it some.
558 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
559 wbuf->nobj = nobj;
560 wbuf = handoff(wbuf);
561 nobj = wbuf->nobj;
562 wp = wbuf->obj + nobj;
565 sbuf->wp = wp;
566 sbuf->wbuf = wbuf;
567 sbuf->nobj = nobj;
570 static void
571 flushobjbuf(Scanbuf *sbuf)
573 uintptr nobj, off;
574 Obj *wp, obj;
575 Workbuf *wbuf;
576 Obj *objbuf;
577 Obj *objbuf_end;
579 wp = sbuf->wp;
580 wbuf = sbuf->wbuf;
581 nobj = sbuf->nobj;
583 objbuf = sbuf->obj.begin;
584 objbuf_end = sbuf->obj.pos;
585 sbuf->obj.pos = sbuf->obj.begin;
587 while(objbuf < objbuf_end) {
588 obj = *objbuf++;
590 // Align obj.b to a word boundary.
591 off = (uintptr)obj.p & (PtrSize-1);
592 if(off != 0) {
593 obj.p += PtrSize - off;
594 obj.n -= PtrSize - off;
595 obj.ti = 0;
598 if(obj.p == nil || obj.n == 0)
599 continue;
601 // If buffer is full, get a new one.
602 if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
603 if(wbuf != nil)
604 wbuf->nobj = nobj;
605 wbuf = getempty(wbuf);
606 wp = wbuf->obj;
607 nobj = 0;
610 *wp = obj;
611 wp++;
612 nobj++;
615 // If another proc wants a pointer, give it some.
616 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
617 wbuf->nobj = nobj;
618 wbuf = handoff(wbuf);
619 nobj = wbuf->nobj;
620 wp = wbuf->obj + nobj;
623 sbuf->wp = wp;
624 sbuf->wbuf = wbuf;
625 sbuf->nobj = nobj;
628 // Program that scans the whole block and treats every block element as a potential pointer
629 static uintptr defaultProg[2] = {PtrSize, GC_DEFAULT_PTR};
631 // Hchan program
632 static uintptr chanProg[2] = {0, GC_CHAN};
634 // Local variables of a program fragment or loop
635 typedef struct GCFrame GCFrame;
636 struct GCFrame {
637 uintptr count, elemsize, b;
638 const uintptr *loop_or_ret;
641 // Sanity check for the derived type info objti.
642 static void
643 checkptr(void *obj, uintptr objti)
645 uintptr *pc1, type, tisize, i, j, x;
646 const uintptr *pc2;
647 byte *objstart;
648 Type *t;
649 MSpan *s;
651 if(!Debug)
652 runtime_throw("checkptr is debug only");
654 if((byte*)obj < runtime_mheap.arena_start || (byte*)obj >= runtime_mheap.arena_used)
655 return;
656 type = runtime_gettype(obj);
657 t = (Type*)(type & ~(uintptr)(PtrSize-1));
658 if(t == nil)
659 return;
660 x = (uintptr)obj >> PageShift;
661 x -= (uintptr)(runtime_mheap.arena_start)>>PageShift;
662 s = runtime_mheap.spans[x];
663 objstart = (byte*)((uintptr)s->start<<PageShift);
664 if(s->sizeclass != 0) {
665 i = ((byte*)obj - objstart)/s->elemsize;
666 objstart += i*s->elemsize;
668 tisize = *(uintptr*)objti;
669 // Sanity check for object size: it should fit into the memory block.
670 if((byte*)obj + tisize > objstart + s->elemsize) {
671 runtime_printf("object of type '%S' at %p/%p does not fit in block %p/%p\n",
672 *t->string, obj, tisize, objstart, s->elemsize);
673 runtime_throw("invalid gc type info");
675 if(obj != objstart)
676 return;
677 // If obj points to the beginning of the memory block,
678 // check type info as well.
679 if(t->string == nil ||
680 // Gob allocates unsafe pointers for indirection.
681 (runtime_strcmp((const char *)t->string->str, (const char*)"unsafe.Pointer") &&
682 // Runtime and gc think differently about closures.
683 runtime_strstr((const char *)t->string->str, (const char*)"struct { F uintptr") != (const char *)t->string->str)) {
684 pc1 = (uintptr*)objti;
685 pc2 = (const uintptr*)t->__gc;
686 // A simple best-effort check until first GC_END.
687 for(j = 1; pc1[j] != GC_END && pc2[j] != GC_END; j++) {
688 if(pc1[j] != pc2[j]) {
689 runtime_printf("invalid gc type info for '%s', type info %p [%d]=%p, block info %p [%d]=%p\n",
690 t->string ? (const int8*)t->string->str : (const int8*)"?", pc1, (int32)j, pc1[j], pc2, (int32)j, pc2[j]);
691 runtime_throw("invalid gc type info");
697 // scanblock scans a block of n bytes starting at pointer b for references
698 // to other objects, scanning any it finds recursively until there are no
699 // unscanned objects left. Instead of using an explicit recursion, it keeps
700 // a work list in the Workbuf* structures and loops in the main function
701 // body. Keeping an explicit work list is easier on the stack allocator and
702 // more efficient.
703 static void
704 scanblock(Workbuf *wbuf, bool keepworking)
706 byte *b, *arena_start, *arena_used;
707 uintptr n, i, end_b, elemsize, size, ti, objti, count, type, nobj;
708 uintptr precise_type, nominal_size;
709 const uintptr *pc, *chan_ret;
710 uintptr chancap;
711 void *obj;
712 const Type *t, *et;
713 Slice *sliceptr;
714 String *stringptr;
715 GCFrame *stack_ptr, stack_top, stack[GC_STACK_CAPACITY+4];
716 BufferList *scanbuffers;
717 Scanbuf sbuf;
718 Eface *eface;
719 Iface *iface;
720 Hchan *chan;
721 const ChanType *chantype;
722 Obj *wp;
724 if(sizeof(Workbuf) % WorkbufSize != 0)
725 runtime_throw("scanblock: size of Workbuf is suboptimal");
727 // Memory arena parameters.
728 arena_start = runtime_mheap.arena_start;
729 arena_used = runtime_mheap.arena_used;
731 stack_ptr = stack+nelem(stack)-1;
733 precise_type = false;
734 nominal_size = 0;
736 if(wbuf) {
737 nobj = wbuf->nobj;
738 wp = &wbuf->obj[nobj];
739 } else {
740 nobj = 0;
741 wp = nil;
744 // Initialize sbuf
745 scanbuffers = &bufferList[runtime_m()->helpgc];
747 sbuf.ptr.begin = sbuf.ptr.pos = &scanbuffers->ptrtarget[0];
748 sbuf.ptr.end = sbuf.ptr.begin + nelem(scanbuffers->ptrtarget);
750 sbuf.obj.begin = sbuf.obj.pos = &scanbuffers->obj[0];
751 sbuf.obj.end = sbuf.obj.begin + nelem(scanbuffers->obj);
753 sbuf.wbuf = wbuf;
754 sbuf.wp = wp;
755 sbuf.nobj = nobj;
757 // (Silence the compiler)
758 chan = nil;
759 chantype = nil;
760 chan_ret = nil;
762 goto next_block;
764 for(;;) {
765 // Each iteration scans the block b of length n, queueing pointers in
766 // the work buffer.
768 if(CollectStats) {
769 runtime_xadd64(&gcstats.nbytes, n);
770 runtime_xadd64(&gcstats.obj.sum, sbuf.nobj);
771 runtime_xadd64(&gcstats.obj.cnt, 1);
774 if(ti != 0) {
775 if(Debug > 1) {
776 runtime_printf("scanblock %p %D ti %p\n", b, (int64)n, ti);
778 pc = (uintptr*)(ti & ~(uintptr)PC_BITS);
779 precise_type = (ti & PRECISE);
780 stack_top.elemsize = pc[0];
781 if(!precise_type)
782 nominal_size = pc[0];
783 if(ti & LOOP) {
784 stack_top.count = 0; // 0 means an infinite number of iterations
785 stack_top.loop_or_ret = pc+1;
786 } else {
787 stack_top.count = 1;
789 if(Debug) {
790 // Simple sanity check for provided type info ti:
791 // The declared size of the object must be not larger than the actual size
792 // (it can be smaller due to inferior pointers).
793 // It's difficult to make a comprehensive check due to inferior pointers,
794 // reflection, gob, etc.
795 if(pc[0] > n) {
796 runtime_printf("invalid gc type info: type info size %p, block size %p\n", pc[0], n);
797 runtime_throw("invalid gc type info");
800 } else if(UseSpanType) {
801 if(CollectStats)
802 runtime_xadd64(&gcstats.obj.notype, 1);
804 type = runtime_gettype(b);
805 if(type != 0) {
806 if(CollectStats)
807 runtime_xadd64(&gcstats.obj.typelookup, 1);
809 t = (Type*)(type & ~(uintptr)(PtrSize-1));
810 switch(type & (PtrSize-1)) {
811 case TypeInfo_SingleObject:
812 pc = (const uintptr*)t->__gc;
813 precise_type = true; // type information about 'b' is precise
814 stack_top.count = 1;
815 stack_top.elemsize = pc[0];
816 break;
817 case TypeInfo_Array:
818 pc = (const uintptr*)t->__gc;
819 if(pc[0] == 0)
820 goto next_block;
821 precise_type = true; // type information about 'b' is precise
822 stack_top.count = 0; // 0 means an infinite number of iterations
823 stack_top.elemsize = pc[0];
824 stack_top.loop_or_ret = pc+1;
825 break;
826 case TypeInfo_Chan:
827 chan = (Hchan*)b;
828 chantype = (const ChanType*)t;
829 chan_ret = nil;
830 pc = chanProg;
831 break;
832 default:
833 if(Debug > 1)
834 runtime_printf("scanblock %p %D type %p %S\n", b, (int64)n, type, *t->string);
835 runtime_throw("scanblock: invalid type");
836 return;
838 if(Debug > 1)
839 runtime_printf("scanblock %p %D type %p %S pc=%p\n", b, (int64)n, type, *t->string, pc);
840 } else {
841 pc = defaultProg;
842 if(Debug > 1)
843 runtime_printf("scanblock %p %D unknown type\n", b, (int64)n);
845 } else {
846 pc = defaultProg;
847 if(Debug > 1)
848 runtime_printf("scanblock %p %D no span types\n", b, (int64)n);
851 if(IgnorePreciseGC)
852 pc = defaultProg;
854 pc++;
855 stack_top.b = (uintptr)b;
856 end_b = (uintptr)b + n - PtrSize;
858 for(;;) {
859 if(CollectStats)
860 runtime_xadd64(&gcstats.instr[pc[0]], 1);
862 obj = nil;
863 objti = 0;
864 switch(pc[0]) {
865 case GC_PTR:
866 obj = *(void**)(stack_top.b + pc[1]);
867 objti = pc[2];
868 if(Debug > 2)
869 runtime_printf("gc_ptr @%p: %p ti=%p\n", stack_top.b+pc[1], obj, objti);
870 pc += 3;
871 if(Debug)
872 checkptr(obj, objti);
873 break;
875 case GC_SLICE:
876 sliceptr = (Slice*)(stack_top.b + pc[1]);
877 if(Debug > 2)
878 runtime_printf("gc_slice @%p: %p/%D/%D\n", sliceptr, sliceptr->array, (int64)sliceptr->__count, (int64)sliceptr->cap);
879 if(sliceptr->cap != 0) {
880 obj = sliceptr->array;
881 // Can't use slice element type for scanning,
882 // because if it points to an array embedded
883 // in the beginning of a struct,
884 // we will scan the whole struct as the slice.
885 // So just obtain type info from heap.
887 pc += 3;
888 break;
890 case GC_APTR:
891 obj = *(void**)(stack_top.b + pc[1]);
892 if(Debug > 2)
893 runtime_printf("gc_aptr @%p: %p\n", stack_top.b+pc[1], obj);
894 pc += 2;
895 break;
897 case GC_STRING:
898 stringptr = (String*)(stack_top.b + pc[1]);
899 if(Debug > 2)
900 runtime_printf("gc_string @%p: %p/%D\n", stack_top.b+pc[1], stringptr->str, (int64)stringptr->len);
901 if(stringptr->len != 0)
902 markonly(stringptr->str);
903 pc += 2;
904 continue;
906 case GC_EFACE:
907 eface = (Eface*)(stack_top.b + pc[1]);
908 pc += 2;
909 if(Debug > 2)
910 runtime_printf("gc_eface @%p: %p %p\n", stack_top.b+pc[1], eface->__type_descriptor, eface->__object);
911 if(eface->__type_descriptor == nil)
912 continue;
914 // eface->type
915 t = eface->__type_descriptor;
916 if((const byte*)t >= arena_start && (const byte*)t < arena_used) {
917 union { const Type *tc; Type *tr; } u;
918 u.tc = t;
919 *sbuf.ptr.pos++ = (PtrTarget){u.tr, 0};
920 if(sbuf.ptr.pos == sbuf.ptr.end)
921 flushptrbuf(&sbuf);
924 // eface->__object
925 if((byte*)eface->__object >= arena_start && (byte*)eface->__object < arena_used) {
926 if(__go_is_pointer_type(t)) {
927 if((t->__code & kindNoPointers))
928 continue;
930 obj = eface->__object;
931 if((t->__code & kindMask) == kindPtr) {
932 // Only use type information if it is a pointer-containing type.
933 // This matches the GC programs written by cmd/gc/reflect.c's
934 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
935 et = ((const PtrType*)t)->elem;
936 if(!(et->__code & kindNoPointers))
937 objti = (uintptr)((const PtrType*)t)->elem->__gc;
939 } else {
940 obj = eface->__object;
941 objti = (uintptr)t->__gc;
944 break;
946 case GC_IFACE:
947 iface = (Iface*)(stack_top.b + pc[1]);
948 pc += 2;
949 if(Debug > 2)
950 runtime_printf("gc_iface @%p: %p/%p %p\n", stack_top.b+pc[1], iface->__methods[0], nil, iface->__object);
951 if(iface->tab == nil)
952 continue;
954 // iface->tab
955 if((byte*)iface->tab >= arena_start && (byte*)iface->tab < arena_used) {
956 *sbuf.ptr.pos++ = (PtrTarget){iface->tab, 0};
957 if(sbuf.ptr.pos == sbuf.ptr.end)
958 flushptrbuf(&sbuf);
961 // iface->data
962 if((byte*)iface->__object >= arena_start && (byte*)iface->__object < arena_used) {
963 t = (const Type*)iface->tab[0];
964 if(__go_is_pointer_type(t)) {
965 if((t->__code & kindNoPointers))
966 continue;
968 obj = iface->__object;
969 if((t->__code & kindMask) == kindPtr) {
970 // Only use type information if it is a pointer-containing type.
971 // This matches the GC programs written by cmd/gc/reflect.c's
972 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
973 et = ((const PtrType*)t)->elem;
974 if(!(et->__code & kindNoPointers))
975 objti = (uintptr)((const PtrType*)t)->elem->__gc;
977 } else {
978 obj = iface->__object;
979 objti = (uintptr)t->__gc;
982 break;
984 case GC_DEFAULT_PTR:
985 while(stack_top.b <= end_b) {
986 obj = *(byte**)stack_top.b;
987 if(Debug > 2)
988 runtime_printf("gc_default_ptr @%p: %p\n", stack_top.b, obj);
989 stack_top.b += PtrSize;
990 if((byte*)obj >= arena_start && (byte*)obj < arena_used) {
991 *sbuf.ptr.pos++ = (PtrTarget){obj, 0};
992 if(sbuf.ptr.pos == sbuf.ptr.end)
993 flushptrbuf(&sbuf);
996 goto next_block;
998 case GC_END:
999 if(--stack_top.count != 0) {
1000 // Next iteration of a loop if possible.
1001 stack_top.b += stack_top.elemsize;
1002 if(stack_top.b + stack_top.elemsize <= end_b+PtrSize) {
1003 pc = stack_top.loop_or_ret;
1004 continue;
1006 i = stack_top.b;
1007 } else {
1008 // Stack pop if possible.
1009 if(stack_ptr+1 < stack+nelem(stack)) {
1010 pc = stack_top.loop_or_ret;
1011 stack_top = *(++stack_ptr);
1012 continue;
1014 i = (uintptr)b + nominal_size;
1016 if(!precise_type) {
1017 // Quickly scan [b+i,b+n) for possible pointers.
1018 for(; i<=end_b; i+=PtrSize) {
1019 if(*(byte**)i != nil) {
1020 // Found a value that may be a pointer.
1021 // Do a rescan of the entire block.
1022 enqueue((Obj){b, n, 0}, &sbuf.wbuf, &sbuf.wp, &sbuf.nobj);
1023 if(CollectStats) {
1024 runtime_xadd64(&gcstats.rescan, 1);
1025 runtime_xadd64(&gcstats.rescanbytes, n);
1027 break;
1031 goto next_block;
1033 case GC_ARRAY_START:
1034 i = stack_top.b + pc[1];
1035 count = pc[2];
1036 elemsize = pc[3];
1037 pc += 4;
1039 // Stack push.
1040 *stack_ptr-- = stack_top;
1041 stack_top = (GCFrame){count, elemsize, i, pc};
1042 continue;
1044 case GC_ARRAY_NEXT:
1045 if(--stack_top.count != 0) {
1046 stack_top.b += stack_top.elemsize;
1047 pc = stack_top.loop_or_ret;
1048 } else {
1049 // Stack pop.
1050 stack_top = *(++stack_ptr);
1051 pc += 1;
1053 continue;
1055 case GC_CALL:
1056 // Stack push.
1057 *stack_ptr-- = stack_top;
1058 stack_top = (GCFrame){1, 0, stack_top.b + pc[1], pc+3 /*return address*/};
1059 pc = (const uintptr*)((const byte*)pc + *(const int32*)(pc+2)); // target of the CALL instruction
1060 continue;
1062 case GC_REGION:
1063 obj = (void*)(stack_top.b + pc[1]);
1064 size = pc[2];
1065 objti = pc[3];
1066 pc += 4;
1068 if(Debug > 2)
1069 runtime_printf("gc_region @%p: %D %p\n", stack_top.b+pc[1], (int64)size, objti);
1070 *sbuf.obj.pos++ = (Obj){obj, size, objti};
1071 if(sbuf.obj.pos == sbuf.obj.end)
1072 flushobjbuf(&sbuf);
1073 continue;
1075 case GC_CHAN_PTR:
1076 chan = *(Hchan**)(stack_top.b + pc[1]);
1077 if(Debug > 2 && chan != nil)
1078 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]);
1079 if(chan == nil) {
1080 pc += 3;
1081 continue;
1083 if(markonly(chan)) {
1084 chantype = (ChanType*)pc[2];
1085 if(!(chantype->elem->__code & kindNoPointers)) {
1086 // Start chanProg.
1087 chan_ret = pc+3;
1088 pc = chanProg+1;
1089 continue;
1092 pc += 3;
1093 continue;
1095 case GC_CHAN:
1096 // There are no heap pointers in struct Hchan,
1097 // so we can ignore the leading sizeof(Hchan) bytes.
1098 if(!(chantype->elem->__code & kindNoPointers)) {
1099 chancap = chan->dataqsiz;
1100 if(chancap > 0 && markonly(chan->buf)) {
1101 // TODO(atom): split into two chunks so that only the
1102 // in-use part of the circular buffer is scanned.
1103 // (Channel routines zero the unused part, so the current
1104 // code does not lead to leaks, it's just a little inefficient.)
1105 *sbuf.obj.pos++ = (Obj){chan->buf, chancap*chantype->elem->__size,
1106 (uintptr)chantype->elem->__gc | PRECISE | LOOP};
1107 if(sbuf.obj.pos == sbuf.obj.end)
1108 flushobjbuf(&sbuf);
1111 if(chan_ret == nil)
1112 goto next_block;
1113 pc = chan_ret;
1114 continue;
1116 default:
1117 runtime_printf("runtime: invalid GC instruction %p at %p\n", pc[0], pc);
1118 runtime_throw("scanblock: invalid GC instruction");
1119 return;
1122 if((byte*)obj >= arena_start && (byte*)obj < arena_used) {
1123 *sbuf.ptr.pos++ = (PtrTarget){obj, objti};
1124 if(sbuf.ptr.pos == sbuf.ptr.end)
1125 flushptrbuf(&sbuf);
1129 next_block:
1130 // Done scanning [b, b+n). Prepare for the next iteration of
1131 // the loop by setting b, n, ti to the parameters for the next block.
1133 if(sbuf.nobj == 0) {
1134 flushptrbuf(&sbuf);
1135 flushobjbuf(&sbuf);
1137 if(sbuf.nobj == 0) {
1138 if(!keepworking) {
1139 if(sbuf.wbuf)
1140 putempty(sbuf.wbuf);
1141 return;
1143 // Emptied our buffer: refill.
1144 sbuf.wbuf = getfull(sbuf.wbuf);
1145 if(sbuf.wbuf == nil)
1146 return;
1147 sbuf.nobj = sbuf.wbuf->nobj;
1148 sbuf.wp = sbuf.wbuf->obj + sbuf.wbuf->nobj;
1152 // Fetch b from the work buffer.
1153 --sbuf.wp;
1154 b = sbuf.wp->p;
1155 n = sbuf.wp->n;
1156 ti = sbuf.wp->ti;
1157 sbuf.nobj--;
1161 static struct root_list* roots;
1163 void
1164 __go_register_gc_roots (struct root_list* r)
1166 // FIXME: This needs locking if multiple goroutines can call
1167 // dlopen simultaneously.
1168 r->next = roots;
1169 roots = r;
1172 // Append obj to the work buffer.
1173 // _wbuf, _wp, _nobj are input/output parameters and are specifying the work buffer.
1174 static void
1175 enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj)
1177 uintptr nobj, off;
1178 Obj *wp;
1179 Workbuf *wbuf;
1181 if(Debug > 1)
1182 runtime_printf("append obj(%p %D %p)\n", obj.p, (int64)obj.n, obj.ti);
1184 // Align obj.b to a word boundary.
1185 off = (uintptr)obj.p & (PtrSize-1);
1186 if(off != 0) {
1187 obj.p += PtrSize - off;
1188 obj.n -= PtrSize - off;
1189 obj.ti = 0;
1192 if(obj.p == nil || obj.n == 0)
1193 return;
1195 // Load work buffer state
1196 wp = *_wp;
1197 wbuf = *_wbuf;
1198 nobj = *_nobj;
1200 // If another proc wants a pointer, give it some.
1201 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
1202 wbuf->nobj = nobj;
1203 wbuf = handoff(wbuf);
1204 nobj = wbuf->nobj;
1205 wp = wbuf->obj + nobj;
1208 // If buffer is full, get a new one.
1209 if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
1210 if(wbuf != nil)
1211 wbuf->nobj = nobj;
1212 wbuf = getempty(wbuf);
1213 wp = wbuf->obj;
1214 nobj = 0;
1217 *wp = obj;
1218 wp++;
1219 nobj++;
1221 // Save work buffer state
1222 *_wp = wp;
1223 *_wbuf = wbuf;
1224 *_nobj = nobj;
1227 static void
1228 enqueue1(Workbuf **wbufp, Obj obj)
1230 Workbuf *wbuf;
1232 wbuf = *wbufp;
1233 if(wbuf->nobj >= nelem(wbuf->obj))
1234 *wbufp = wbuf = getempty(wbuf);
1235 wbuf->obj[wbuf->nobj++] = obj;
1238 static void
1239 markroot(ParFor *desc, uint32 i)
1241 Workbuf *wbuf;
1242 FinBlock *fb;
1243 MHeap *h;
1244 MSpan **allspans, *s;
1245 uint32 spanidx, sg;
1246 G *gp;
1247 void *p;
1249 USED(&desc);
1250 wbuf = getempty(nil);
1251 // Note: if you add a case here, please also update heapdump.c:dumproots.
1252 switch(i) {
1253 case RootData:
1254 // For gccgo this is both data and bss.
1256 struct root_list *pl;
1258 for(pl = roots; pl != nil; pl = pl->next) {
1259 struct root *pr = &pl->roots[0];
1260 while(1) {
1261 void *decl = pr->decl;
1262 if(decl == nil)
1263 break;
1264 enqueue1(&wbuf, (Obj){decl, pr->size, 0});
1265 pr++;
1269 break;
1271 case RootBss:
1272 // For gccgo we use this for all the other global roots.
1273 enqueue1(&wbuf, (Obj){(byte*)&runtime_m0, sizeof runtime_m0, 0});
1274 enqueue1(&wbuf, (Obj){(byte*)&runtime_g0, sizeof runtime_g0, 0});
1275 enqueue1(&wbuf, (Obj){(byte*)&runtime_allg, sizeof runtime_allg, 0});
1276 enqueue1(&wbuf, (Obj){(byte*)&runtime_allm, sizeof runtime_allm, 0});
1277 enqueue1(&wbuf, (Obj){(byte*)&runtime_allp, sizeof runtime_allp, 0});
1278 enqueue1(&wbuf, (Obj){(byte*)&work, sizeof work, 0});
1279 runtime_proc_scan(&wbuf, enqueue1);
1280 runtime_netpoll_scan(&wbuf, enqueue1);
1281 break;
1283 case RootFinalizers:
1284 for(fb=allfin; fb; fb=fb->alllink)
1285 enqueue1(&wbuf, (Obj){(byte*)fb->fin, fb->cnt*sizeof(fb->fin[0]), 0});
1286 break;
1288 case RootSpanTypes:
1289 // mark span types and MSpan.specials (to walk spans only once)
1290 h = &runtime_mheap;
1291 sg = h->sweepgen;
1292 allspans = h->allspans;
1293 for(spanidx=0; spanidx<runtime_mheap.nspan; spanidx++) {
1294 Special *sp;
1295 SpecialFinalizer *spf;
1297 s = allspans[spanidx];
1298 if(s->sweepgen != sg) {
1299 runtime_printf("sweep %d %d\n", s->sweepgen, sg);
1300 runtime_throw("gc: unswept span");
1302 if(s->state != MSpanInUse)
1303 continue;
1304 // The garbage collector ignores type pointers stored in MSpan.types:
1305 // - Compiler-generated types are stored outside of heap.
1306 // - The reflect package has runtime-generated types cached in its data structures.
1307 // The garbage collector relies on finding the references via that cache.
1308 if(s->types.compression == MTypes_Words || s->types.compression == MTypes_Bytes)
1309 markonly((byte*)s->types.data);
1310 for(sp = s->specials; sp != nil; sp = sp->next) {
1311 if(sp->kind != KindSpecialFinalizer)
1312 continue;
1313 // don't mark finalized object, but scan it so we
1314 // retain everything it points to.
1315 spf = (SpecialFinalizer*)sp;
1316 // A finalizer can be set for an inner byte of an object, find object beginning.
1317 p = (void*)((s->start << PageShift) + spf->offset/s->elemsize*s->elemsize);
1318 enqueue1(&wbuf, (Obj){p, s->elemsize, 0});
1319 enqueue1(&wbuf, (Obj){(void*)&spf->fn, PtrSize, 0});
1320 enqueue1(&wbuf, (Obj){(void*)&spf->ft, PtrSize, 0});
1321 enqueue1(&wbuf, (Obj){(void*)&spf->ot, PtrSize, 0});
1324 break;
1326 case RootFlushCaches:
1327 flushallmcaches();
1328 break;
1330 default:
1331 // the rest is scanning goroutine stacks
1332 if(i - RootCount >= runtime_allglen)
1333 runtime_throw("markroot: bad index");
1334 gp = runtime_allg[i - RootCount];
1335 // remember when we've first observed the G blocked
1336 // needed only to output in traceback
1337 if((gp->atomicstatus == _Gwaiting || gp->atomicstatus == _Gsyscall) && gp->waitsince == 0)
1338 gp->waitsince = work.tstart;
1339 addstackroots(gp, &wbuf);
1340 break;
1344 if(wbuf)
1345 scanblock(wbuf, false);
1348 static const FuncVal markroot_funcval = { (void *) markroot };
1350 // Get an empty work buffer off the work.empty list,
1351 // allocating new buffers as needed.
1352 static Workbuf*
1353 getempty(Workbuf *b)
1355 if(b != nil)
1356 runtime_lfstackpush(&work.full, &b->node);
1357 b = (Workbuf*)runtime_lfstackpop(&work.wempty);
1358 if(b == nil) {
1359 // Need to allocate.
1360 runtime_lock(&work);
1361 if(work.nchunk < sizeof *b) {
1362 work.nchunk = 1<<20;
1363 work.chunk = runtime_SysAlloc(work.nchunk, &mstats()->gc_sys);
1364 if(work.chunk == nil)
1365 runtime_throw("runtime: cannot allocate memory");
1367 b = (Workbuf*)work.chunk;
1368 work.chunk += sizeof *b;
1369 work.nchunk -= sizeof *b;
1370 runtime_unlock(&work);
1372 b->nobj = 0;
1373 return b;
1376 static void
1377 putempty(Workbuf *b)
1379 if(CollectStats)
1380 runtime_xadd64(&gcstats.putempty, 1);
1382 runtime_lfstackpush(&work.wempty, &b->node);
1385 // Get a full work buffer off the work.full list, or return nil.
1386 static Workbuf*
1387 getfull(Workbuf *b)
1389 M *m;
1390 int32 i;
1392 if(CollectStats)
1393 runtime_xadd64(&gcstats.getfull, 1);
1395 if(b != nil)
1396 runtime_lfstackpush(&work.wempty, &b->node);
1397 b = (Workbuf*)runtime_lfstackpop(&work.full);
1398 if(b != nil || work.nproc == 1)
1399 return b;
1401 m = runtime_m();
1402 runtime_xadd(&work.nwait, +1);
1403 for(i=0;; i++) {
1404 if(work.full != 0) {
1405 runtime_xadd(&work.nwait, -1);
1406 b = (Workbuf*)runtime_lfstackpop(&work.full);
1407 if(b != nil)
1408 return b;
1409 runtime_xadd(&work.nwait, +1);
1411 if(work.nwait == work.nproc)
1412 return nil;
1413 if(i < 10) {
1414 m->gcstats.nprocyield++;
1415 runtime_procyield(20);
1416 } else if(i < 20) {
1417 m->gcstats.nosyield++;
1418 runtime_osyield();
1419 } else {
1420 m->gcstats.nsleep++;
1421 runtime_usleep(100);
1426 static Workbuf*
1427 handoff(Workbuf *b)
1429 M *m;
1430 int32 n;
1431 Workbuf *b1;
1433 m = runtime_m();
1435 // Make new buffer with half of b's pointers.
1436 b1 = getempty(nil);
1437 n = b->nobj/2;
1438 b->nobj -= n;
1439 b1->nobj = n;
1440 runtime_memmove(b1->obj, b->obj+b->nobj, n*sizeof b1->obj[0]);
1441 m->gcstats.nhandoff++;
1442 m->gcstats.nhandoffcnt += n;
1444 // Put b on full list - let first half of b get stolen.
1445 runtime_lfstackpush(&work.full, &b->node);
1446 return b1;
1449 static void
1450 addstackroots(G *gp, Workbuf **wbufp)
1452 switch(gp->atomicstatus){
1453 default:
1454 runtime_printf("unexpected G.status %d (goroutine %p %D)\n", gp->atomicstatus, gp, gp->goid);
1455 runtime_throw("mark - bad status");
1456 case _Gdead:
1457 return;
1458 case _Grunning:
1459 runtime_throw("mark - world not stopped");
1460 case _Grunnable:
1461 case _Gsyscall:
1462 case _Gwaiting:
1463 break;
1466 #ifdef USING_SPLIT_STACK
1467 M *mp;
1468 void* sp;
1469 size_t spsize;
1470 void* next_segment;
1471 void* next_sp;
1472 void* initial_sp;
1474 if(gp == runtime_g()) {
1475 // Scanning our own stack.
1476 sp = __splitstack_find(nil, nil, &spsize, &next_segment,
1477 &next_sp, &initial_sp);
1478 } else if((mp = gp->m) != nil && mp->helpgc) {
1479 // gchelper's stack is in active use and has no interesting pointers.
1480 return;
1481 } else {
1482 // Scanning another goroutine's stack.
1483 // The goroutine is usually asleep (the world is stopped).
1485 // The exception is that if the goroutine is about to enter or might
1486 // have just exited a system call, it may be executing code such
1487 // as schedlock and may have needed to start a new stack segment.
1488 // Use the stack segment and stack pointer at the time of
1489 // the system call instead, since that won't change underfoot.
1490 if(gp->gcstack != nil) {
1491 sp = gp->gcstack;
1492 spsize = gp->gcstacksize;
1493 next_segment = gp->gcnextsegment;
1494 next_sp = gp->gcnextsp;
1495 initial_sp = gp->gcinitialsp;
1496 } else {
1497 sp = __splitstack_find_context(&gp->stackcontext[0],
1498 &spsize, &next_segment,
1499 &next_sp, &initial_sp);
1502 if(sp != nil) {
1503 enqueue1(wbufp, (Obj){sp, spsize, 0});
1504 while((sp = __splitstack_find(next_segment, next_sp,
1505 &spsize, &next_segment,
1506 &next_sp, &initial_sp)) != nil)
1507 enqueue1(wbufp, (Obj){sp, spsize, 0});
1509 #else
1510 M *mp;
1511 byte* bottom;
1512 byte* top;
1514 if(gp == runtime_g()) {
1515 // Scanning our own stack.
1516 bottom = (byte*)&gp;
1517 } else if((mp = gp->m) != nil && mp->helpgc) {
1518 // gchelper's stack is in active use and has no interesting pointers.
1519 return;
1520 } else {
1521 // Scanning another goroutine's stack.
1522 // The goroutine is usually asleep (the world is stopped).
1523 bottom = (byte*)gp->gcnextsp;
1524 if(bottom == nil)
1525 return;
1527 top = (byte*)gp->gcinitialsp + gp->gcstacksize;
1528 if(top > bottom)
1529 enqueue1(wbufp, (Obj){bottom, top - bottom, 0});
1530 else
1531 enqueue1(wbufp, (Obj){top, bottom - top, 0});
1532 #endif
1535 void
1536 runtime_queuefinalizer(void *p, FuncVal *fn, const FuncType *ft, const PtrType *ot)
1538 FinBlock *block;
1539 Finalizer *f;
1541 runtime_lock(&finlock);
1542 if(finq == nil || finq->cnt == finq->cap) {
1543 if(finc == nil) {
1544 finc = runtime_persistentalloc(FinBlockSize, 0, &mstats()->gc_sys);
1545 finc->cap = (FinBlockSize - sizeof(FinBlock)) / sizeof(Finalizer) + 1;
1546 finc->alllink = allfin;
1547 allfin = finc;
1549 block = finc;
1550 finc = block->next;
1551 block->next = finq;
1552 finq = block;
1554 f = &finq->fin[finq->cnt];
1555 finq->cnt++;
1556 f->fn = fn;
1557 f->ft = ft;
1558 f->ot = ot;
1559 f->arg = p;
1560 runtime_fingwake = true;
1561 runtime_unlock(&finlock);
1564 void
1565 runtime_iterate_finq(void (*callback)(FuncVal*, void*, const FuncType*, const PtrType*))
1567 FinBlock *fb;
1568 Finalizer *f;
1569 int32 i;
1571 for(fb = allfin; fb; fb = fb->alllink) {
1572 for(i = 0; i < fb->cnt; i++) {
1573 f = &fb->fin[i];
1574 callback(f->fn, f->arg, f->ft, f->ot);
1579 void
1580 runtime_MSpan_EnsureSwept(MSpan *s)
1582 M *m = runtime_m();
1583 G *g = runtime_g();
1584 uint32 sg;
1586 // Caller must disable preemption.
1587 // Otherwise when this function returns the span can become unswept again
1588 // (if GC is triggered on another goroutine).
1589 if(m->locks == 0 && m->mallocing == 0 && g != m->g0)
1590 runtime_throw("MSpan_EnsureSwept: m is not locked");
1592 sg = runtime_mheap.sweepgen;
1593 if(runtime_atomicload(&s->sweepgen) == sg)
1594 return;
1595 if(runtime_cas(&s->sweepgen, sg-2, sg-1)) {
1596 runtime_MSpan_Sweep(s);
1597 return;
1599 // unfortunate condition, and we don't have efficient means to wait
1600 while(runtime_atomicload(&s->sweepgen) != sg)
1601 runtime_osyield();
1604 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
1605 // It clears the mark bits in preparation for the next GC round.
1606 // Returns true if the span was returned to heap.
1607 bool
1608 runtime_MSpan_Sweep(MSpan *s)
1610 M *m;
1611 int32 cl, n, npages, nfree;
1612 uintptr size, off, *bitp, shift, bits;
1613 uint32 sweepgen;
1614 byte *p;
1615 MCache *c;
1616 byte *arena_start;
1617 MLink head, *end;
1618 byte *type_data;
1619 byte compression;
1620 uintptr type_data_inc;
1621 MLink *x;
1622 Special *special, **specialp, *y;
1623 bool res, sweepgenset;
1625 m = runtime_m();
1627 // It's critical that we enter this function with preemption disabled,
1628 // GC must not start while we are in the middle of this function.
1629 if(m->locks == 0 && m->mallocing == 0 && runtime_g() != m->g0)
1630 runtime_throw("MSpan_Sweep: m is not locked");
1631 sweepgen = runtime_mheap.sweepgen;
1632 if(s->state != MSpanInUse || s->sweepgen != sweepgen-1) {
1633 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1634 s->state, s->sweepgen, sweepgen);
1635 runtime_throw("MSpan_Sweep: bad span state");
1637 arena_start = runtime_mheap.arena_start;
1638 cl = s->sizeclass;
1639 size = s->elemsize;
1640 if(cl == 0) {
1641 n = 1;
1642 } else {
1643 // Chunk full of small blocks.
1644 npages = runtime_class_to_allocnpages[cl];
1645 n = (npages << PageShift) / size;
1647 res = false;
1648 nfree = 0;
1649 end = &head;
1650 c = m->mcache;
1651 sweepgenset = false;
1653 // mark any free objects in this span so we don't collect them
1654 for(x = s->freelist; x != nil; x = x->next) {
1655 // This is markonly(x) but faster because we don't need
1656 // atomic access and we're guaranteed to be pointing at
1657 // the head of a valid object.
1658 off = (uintptr*)x - (uintptr*)runtime_mheap.arena_start;
1659 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
1660 shift = off % wordsPerBitmapWord;
1661 *bitp |= bitMarked<<shift;
1664 // Unlink & free special records for any objects we're about to free.
1665 specialp = &s->specials;
1666 special = *specialp;
1667 while(special != nil) {
1668 // A finalizer can be set for an inner byte of an object, find object beginning.
1669 p = (byte*)(s->start << PageShift) + special->offset/size*size;
1670 off = (uintptr*)p - (uintptr*)arena_start;
1671 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1672 shift = off % wordsPerBitmapWord;
1673 bits = *bitp>>shift;
1674 if((bits & (bitAllocated|bitMarked)) == bitAllocated) {
1675 // Find the exact byte for which the special was setup
1676 // (as opposed to object beginning).
1677 p = (byte*)(s->start << PageShift) + special->offset;
1678 // about to free object: splice out special record
1679 y = special;
1680 special = special->next;
1681 *specialp = special;
1682 if(!runtime_freespecial(y, p, size, false)) {
1683 // stop freeing of object if it has a finalizer
1684 *bitp |= bitMarked << shift;
1686 } else {
1687 // object is still live: keep special record
1688 specialp = &special->next;
1689 special = *specialp;
1693 type_data = (byte*)s->types.data;
1694 type_data_inc = sizeof(uintptr);
1695 compression = s->types.compression;
1696 switch(compression) {
1697 case MTypes_Bytes:
1698 type_data += 8*sizeof(uintptr);
1699 type_data_inc = 1;
1700 break;
1703 // Sweep through n objects of given size starting at p.
1704 // This thread owns the span now, so it can manipulate
1705 // the block bitmap without atomic operations.
1706 p = (byte*)(s->start << PageShift);
1707 for(; n > 0; n--, p += size, type_data+=type_data_inc) {
1708 off = (uintptr*)p - (uintptr*)arena_start;
1709 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1710 shift = off % wordsPerBitmapWord;
1711 bits = *bitp>>shift;
1713 if((bits & bitAllocated) == 0)
1714 continue;
1716 if((bits & bitMarked) != 0) {
1717 *bitp &= ~(bitMarked<<shift);
1718 continue;
1721 if(runtime_debug.allocfreetrace)
1722 runtime_tracefree(p, size);
1724 // Clear mark and scan bits.
1725 *bitp &= ~((bitScan|bitMarked)<<shift);
1727 if(cl == 0) {
1728 // Free large span.
1729 runtime_unmarkspan(p, 1<<PageShift);
1730 s->needzero = 1;
1731 // important to set sweepgen before returning it to heap
1732 runtime_atomicstore(&s->sweepgen, sweepgen);
1733 sweepgenset = true;
1734 // See note about SysFault vs SysFree in malloc.goc.
1735 if(runtime_debug.efence)
1736 runtime_SysFault(p, size);
1737 else
1738 runtime_MHeap_Free(&runtime_mheap, s, 1);
1739 c->local_nlargefree++;
1740 c->local_largefree += size;
1741 runtime_xadd64(&mstats()->next_gc, -(uint64)(size * (gcpercent + 100)/100));
1742 res = true;
1743 } else {
1744 // Free small object.
1745 switch(compression) {
1746 case MTypes_Words:
1747 *(uintptr*)type_data = 0;
1748 break;
1749 case MTypes_Bytes:
1750 *(byte*)type_data = 0;
1751 break;
1753 if(size > 2*sizeof(uintptr))
1754 ((uintptr*)p)[1] = (uintptr)0xdeaddeaddeaddeadll; // mark as "needs to be zeroed"
1755 else if(size > sizeof(uintptr))
1756 ((uintptr*)p)[1] = 0;
1758 end->next = (MLink*)p;
1759 end = (MLink*)p;
1760 nfree++;
1764 // We need to set s->sweepgen = h->sweepgen only when all blocks are swept,
1765 // because of the potential for a concurrent free/SetFinalizer.
1766 // But we need to set it before we make the span available for allocation
1767 // (return it to heap or mcentral), because allocation code assumes that a
1768 // span is already swept if available for allocation.
1770 if(!sweepgenset && nfree == 0) {
1771 // The span must be in our exclusive ownership until we update sweepgen,
1772 // check for potential races.
1773 if(s->state != MSpanInUse || s->sweepgen != sweepgen-1) {
1774 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1775 s->state, s->sweepgen, sweepgen);
1776 runtime_throw("MSpan_Sweep: bad span state after sweep");
1778 runtime_atomicstore(&s->sweepgen, sweepgen);
1780 if(nfree > 0) {
1781 c->local_nsmallfree[cl] += nfree;
1782 c->local_cachealloc -= nfree * size;
1783 runtime_xadd64(&mstats()->next_gc, -(uint64)(nfree * size * (gcpercent + 100)/100));
1784 res = runtime_MCentral_FreeSpan(&runtime_mheap.central[cl], s, nfree, head.next, end);
1785 //MCentral_FreeSpan updates sweepgen
1787 return res;
1790 // State of background sweep.
1791 // Protected by gclock.
1792 static struct
1794 G* g;
1795 bool parked;
1797 MSpan** spans;
1798 uint32 nspan;
1799 uint32 spanidx;
1800 } sweep;
1802 // background sweeping goroutine
1803 static void
1804 bgsweep(void* dummy __attribute__ ((unused)))
1806 runtime_g()->issystem = 1;
1807 for(;;) {
1808 while(runtime_sweepone() != (uintptr)-1) {
1809 gcstats.nbgsweep++;
1810 runtime_gosched();
1812 runtime_lock(&gclock);
1813 if(!runtime_mheap.sweepdone) {
1814 // It's possible if GC has happened between sweepone has
1815 // returned -1 and gclock lock.
1816 runtime_unlock(&gclock);
1817 continue;
1819 sweep.parked = true;
1820 runtime_g()->isbackground = true;
1821 runtime_parkunlock(&gclock, "GC sweep wait");
1822 runtime_g()->isbackground = false;
1826 // sweeps one span
1827 // returns number of pages returned to heap, or -1 if there is nothing to sweep
1828 uintptr
1829 runtime_sweepone(void)
1831 M *m = runtime_m();
1832 MSpan *s;
1833 uint32 idx, sg;
1834 uintptr npages;
1836 // increment locks to ensure that the goroutine is not preempted
1837 // in the middle of sweep thus leaving the span in an inconsistent state for next GC
1838 m->locks++;
1839 sg = runtime_mheap.sweepgen;
1840 for(;;) {
1841 idx = runtime_xadd(&sweep.spanidx, 1) - 1;
1842 if(idx >= sweep.nspan) {
1843 runtime_mheap.sweepdone = true;
1844 m->locks--;
1845 return (uintptr)-1;
1847 s = sweep.spans[idx];
1848 if(s->state != MSpanInUse) {
1849 s->sweepgen = sg;
1850 continue;
1852 if(s->sweepgen != sg-2 || !runtime_cas(&s->sweepgen, sg-2, sg-1))
1853 continue;
1854 if(s->incache)
1855 runtime_throw("sweep of incache span");
1856 npages = s->npages;
1857 if(!runtime_MSpan_Sweep(s))
1858 npages = 0;
1859 m->locks--;
1860 return npages;
1864 static void
1865 dumpspan(uint32 idx)
1867 int32 sizeclass, n, npages, i, column;
1868 uintptr size;
1869 byte *p;
1870 byte *arena_start;
1871 MSpan *s;
1872 bool allocated;
1874 s = runtime_mheap.allspans[idx];
1875 if(s->state != MSpanInUse)
1876 return;
1877 arena_start = runtime_mheap.arena_start;
1878 p = (byte*)(s->start << PageShift);
1879 sizeclass = s->sizeclass;
1880 size = s->elemsize;
1881 if(sizeclass == 0) {
1882 n = 1;
1883 } else {
1884 npages = runtime_class_to_allocnpages[sizeclass];
1885 n = (npages << PageShift) / size;
1888 runtime_printf("%p .. %p:\n", p, p+n*size);
1889 column = 0;
1890 for(; n>0; n--, p+=size) {
1891 uintptr off, *bitp, shift, bits;
1893 off = (uintptr*)p - (uintptr*)arena_start;
1894 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1895 shift = off % wordsPerBitmapWord;
1896 bits = *bitp>>shift;
1898 allocated = ((bits & bitAllocated) != 0);
1900 for(i=0; (uint32)i<size; i+=sizeof(void*)) {
1901 if(column == 0) {
1902 runtime_printf("\t");
1904 if(i == 0) {
1905 runtime_printf(allocated ? "(" : "[");
1906 runtime_printf("%p: ", p+i);
1907 } else {
1908 runtime_printf(" ");
1911 runtime_printf("%p", *(void**)(p+i));
1913 if(i+sizeof(void*) >= size) {
1914 runtime_printf(allocated ? ") " : "] ");
1917 column++;
1918 if(column == 8) {
1919 runtime_printf("\n");
1920 column = 0;
1924 runtime_printf("\n");
1927 // A debugging function to dump the contents of memory
1928 void
1929 runtime_memorydump(void)
1931 uint32 spanidx;
1933 for(spanidx=0; spanidx<runtime_mheap.nspan; spanidx++) {
1934 dumpspan(spanidx);
1938 void
1939 runtime_gchelper(void)
1941 uint32 nproc;
1943 runtime_m()->traceback = 2;
1944 gchelperstart();
1946 // parallel mark for over gc roots
1947 runtime_parfordo(work.markfor);
1949 // help other threads scan secondary blocks
1950 scanblock(nil, true);
1952 bufferList[runtime_m()->helpgc].busy = 0;
1953 nproc = work.nproc; // work.nproc can change right after we increment work.ndone
1954 if(runtime_xadd(&work.ndone, +1) == nproc-1)
1955 runtime_notewakeup(&work.alldone);
1956 runtime_m()->traceback = 0;
1959 static void
1960 cachestats(void)
1962 MCache *c;
1963 P *p, **pp;
1965 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
1966 c = p->mcache;
1967 if(c==nil)
1968 continue;
1969 runtime_purgecachedstats(c);
1973 static void
1974 flushallmcaches(void)
1976 P *p, **pp;
1977 MCache *c;
1979 // Flush MCache's to MCentral.
1980 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
1981 c = p->mcache;
1982 if(c==nil)
1983 continue;
1984 runtime_MCache_ReleaseAll(c);
1988 void
1989 runtime_updatememstats(GCStats *stats)
1991 M *mp;
1992 MSpan *s;
1993 uint32 i;
1994 uint64 stacks_inuse, smallfree;
1995 uint64 *src, *dst;
1996 MStats *pmstats;
1998 if(stats)
1999 runtime_memclr((byte*)stats, sizeof(*stats));
2000 stacks_inuse = 0;
2001 for(mp=runtime_allm; mp; mp=mp->alllink) {
2002 //stacks_inuse += mp->stackinuse*FixedStack;
2003 if(stats) {
2004 src = (uint64*)&mp->gcstats;
2005 dst = (uint64*)stats;
2006 for(i=0; i<sizeof(*stats)/sizeof(uint64); i++)
2007 dst[i] += src[i];
2008 runtime_memclr((byte*)&mp->gcstats, sizeof(mp->gcstats));
2011 pmstats = mstats();
2012 pmstats->stacks_inuse = stacks_inuse;
2013 pmstats->mcache_inuse = runtime_mheap.cachealloc.inuse;
2014 pmstats->mspan_inuse = runtime_mheap.spanalloc.inuse;
2015 pmstats->sys = pmstats->heap_sys + pmstats->stacks_sys + pmstats->mspan_sys +
2016 pmstats->mcache_sys + pmstats->buckhash_sys + pmstats->gc_sys + pmstats->other_sys;
2018 // Calculate memory allocator stats.
2019 // During program execution we only count number of frees and amount of freed memory.
2020 // Current number of alive object in the heap and amount of alive heap memory
2021 // are calculated by scanning all spans.
2022 // Total number of mallocs is calculated as number of frees plus number of alive objects.
2023 // Similarly, total amount of allocated memory is calculated as amount of freed memory
2024 // plus amount of alive heap memory.
2025 pmstats->alloc = 0;
2026 pmstats->total_alloc = 0;
2027 pmstats->nmalloc = 0;
2028 pmstats->nfree = 0;
2029 for(i = 0; i < nelem(pmstats->by_size); i++) {
2030 pmstats->by_size[i].nmalloc = 0;
2031 pmstats->by_size[i].nfree = 0;
2034 // Flush MCache's to MCentral.
2035 flushallmcaches();
2037 // Aggregate local stats.
2038 cachestats();
2040 // Scan all spans and count number of alive objects.
2041 for(i = 0; i < runtime_mheap.nspan; i++) {
2042 s = runtime_mheap.allspans[i];
2043 if(s->state != MSpanInUse)
2044 continue;
2045 if(s->sizeclass == 0) {
2046 pmstats->nmalloc++;
2047 pmstats->alloc += s->elemsize;
2048 } else {
2049 pmstats->nmalloc += s->ref;
2050 pmstats->by_size[s->sizeclass].nmalloc += s->ref;
2051 pmstats->alloc += s->ref*s->elemsize;
2055 // Aggregate by size class.
2056 smallfree = 0;
2057 pmstats->nfree = runtime_mheap.nlargefree;
2058 for(i = 0; i < nelem(pmstats->by_size); i++) {
2059 pmstats->nfree += runtime_mheap.nsmallfree[i];
2060 pmstats->by_size[i].nfree = runtime_mheap.nsmallfree[i];
2061 pmstats->by_size[i].nmalloc += runtime_mheap.nsmallfree[i];
2062 smallfree += runtime_mheap.nsmallfree[i] * runtime_class_to_size[i];
2064 pmstats->nmalloc += pmstats->nfree;
2066 // Calculate derived stats.
2067 pmstats->total_alloc = pmstats->alloc + runtime_mheap.largefree + smallfree;
2068 pmstats->heap_alloc = pmstats->alloc;
2069 pmstats->heap_objects = pmstats->nmalloc - pmstats->nfree;
2072 // Structure of arguments passed to function gc().
2073 // This allows the arguments to be passed via runtime_mcall.
2074 struct gc_args
2076 int64 start_time; // start time of GC in ns (just before stoptheworld)
2077 bool eagersweep;
2080 static void gc(struct gc_args *args);
2081 static void mgc(G *gp);
2083 static int32
2084 readgogc(void)
2086 String s;
2087 const byte *p;
2089 s = runtime_getenv("GOGC");
2090 if(s.len == 0)
2091 return 100;
2092 p = s.str;
2093 if(s.len == 3 && runtime_strcmp((const char *)p, "off") == 0)
2094 return -1;
2095 return runtime_atoi(p, s.len);
2098 // force = 1 - do GC regardless of current heap usage
2099 // force = 2 - go GC and eager sweep
2100 void
2101 runtime_gc(int32 force)
2103 M *m;
2104 G *g;
2105 struct gc_args a;
2106 int32 i;
2107 MStats *pmstats;
2109 // The atomic operations are not atomic if the uint64s
2110 // are not aligned on uint64 boundaries. This has been
2111 // a problem in the past.
2112 if((((uintptr)&work.wempty) & 7) != 0)
2113 runtime_throw("runtime: gc work buffer is misaligned");
2114 if((((uintptr)&work.full) & 7) != 0)
2115 runtime_throw("runtime: gc work buffer is misaligned");
2117 // Make sure all registers are saved on stack so that
2118 // scanstack sees them.
2119 __builtin_unwind_init();
2121 // The gc is turned off (via enablegc) until
2122 // the bootstrap has completed.
2123 // Also, malloc gets called in the guts
2124 // of a number of libraries that might be
2125 // holding locks. To avoid priority inversion
2126 // problems, don't bother trying to run gc
2127 // while holding a lock. The next mallocgc
2128 // without a lock will do the gc instead.
2129 m = runtime_m();
2130 pmstats = mstats();
2131 if(!pmstats->enablegc || runtime_g() == m->g0 || m->locks > 0 || runtime_panicking || m->preemptoff.len > 0)
2132 return;
2134 if(gcpercent == GcpercentUnknown) { // first time through
2135 runtime_lock(&runtime_mheap);
2136 if(gcpercent == GcpercentUnknown)
2137 gcpercent = readgogc();
2138 runtime_unlock(&runtime_mheap);
2140 if(gcpercent < 0)
2141 return;
2143 runtime_acquireWorldsema();
2144 if(force==0 && pmstats->heap_alloc < pmstats->next_gc) {
2145 // typically threads which lost the race to grab
2146 // worldsema exit here when gc is done.
2147 runtime_releaseWorldsema();
2148 return;
2151 // Ok, we're doing it! Stop everybody else
2152 a.start_time = runtime_nanotime();
2153 a.eagersweep = force >= 2;
2154 m->gcing = 1;
2155 runtime_stopTheWorldWithSema();
2157 clearpools();
2159 // Run gc on the g0 stack. We do this so that the g stack
2160 // we're currently running on will no longer change. Cuts
2161 // the root set down a bit (g0 stacks are not scanned, and
2162 // we don't need to scan gc's internal state). Also an
2163 // enabler for copyable stacks.
2164 for(i = 0; i < (runtime_debug.gctrace > 1 ? 2 : 1); i++) {
2165 if(i > 0)
2166 a.start_time = runtime_nanotime();
2167 // switch to g0, call gc(&a), then switch back
2168 g = runtime_g();
2169 g->param = &a;
2170 g->atomicstatus = _Gwaiting;
2171 g->waitreason = runtime_gostringnocopy((const byte*)"garbage collection");
2172 runtime_mcall(mgc);
2173 m = runtime_m();
2176 // all done
2177 m->gcing = 0;
2178 m->locks++;
2179 runtime_releaseWorldsema();
2180 runtime_startTheWorldWithSema();
2181 m->locks--;
2183 // now that gc is done, kick off finalizer thread if needed
2184 if(!ConcurrentSweep) {
2185 // give the queued finalizers, if any, a chance to run
2186 runtime_gosched();
2187 } else {
2188 // For gccgo, let other goroutines run.
2189 runtime_gosched();
2193 static void
2194 mgc(G *gp)
2196 gc(gp->param);
2197 gp->param = nil;
2198 gp->atomicstatus = _Grunning;
2199 runtime_gogo(gp);
2202 static void
2203 gc(struct gc_args *args)
2205 M *m;
2206 int64 tm0, tm1, tm2, tm3, tm4;
2207 uint64 heap0, heap1, obj, ninstr;
2208 GCStats stats;
2209 uint32 i;
2210 MStats *pmstats;
2211 // Eface eface;
2213 m = runtime_m();
2215 if(runtime_debug.allocfreetrace)
2216 runtime_tracegc();
2218 m->traceback = 2;
2219 tm0 = args->start_time;
2220 work.tstart = args->start_time;
2222 if(CollectStats)
2223 runtime_memclr((byte*)&gcstats, sizeof(gcstats));
2225 m->locks++; // disable gc during mallocs in parforalloc
2226 if(work.markfor == nil)
2227 work.markfor = runtime_parforalloc(MaxGcproc);
2228 m->locks--;
2230 tm1 = 0;
2231 if(runtime_debug.gctrace)
2232 tm1 = runtime_nanotime();
2234 // Sweep what is not sweeped by bgsweep.
2235 while(runtime_sweepone() != (uintptr)-1)
2236 gcstats.npausesweep++;
2238 work.nwait = 0;
2239 work.ndone = 0;
2240 work.nproc = runtime_gcprocs();
2241 runtime_parforsetup(work.markfor, work.nproc, RootCount + runtime_allglen, false, &markroot_funcval);
2242 if(work.nproc > 1) {
2243 runtime_noteclear(&work.alldone);
2244 runtime_helpgc(work.nproc);
2247 tm2 = 0;
2248 if(runtime_debug.gctrace)
2249 tm2 = runtime_nanotime();
2251 gchelperstart();
2252 runtime_parfordo(work.markfor);
2253 scanblock(nil, true);
2255 tm3 = 0;
2256 if(runtime_debug.gctrace)
2257 tm3 = runtime_nanotime();
2259 bufferList[m->helpgc].busy = 0;
2260 if(work.nproc > 1)
2261 runtime_notesleep(&work.alldone);
2263 cachestats();
2264 // next_gc calculation is tricky with concurrent sweep since we don't know size of live heap
2265 // estimate what was live heap size after previous GC (for tracing only)
2266 pmstats = mstats();
2267 heap0 = pmstats->next_gc*100/(gcpercent+100);
2268 // conservatively set next_gc to high value assuming that everything is live
2269 // concurrent/lazy sweep will reduce this number while discovering new garbage
2270 pmstats->next_gc = pmstats->heap_alloc+(pmstats->heap_alloc-runtime_stacks_sys)*gcpercent/100;
2272 tm4 = runtime_nanotime();
2273 pmstats->last_gc = runtime_unixnanotime(); // must be Unix time to make sense to user
2274 pmstats->pause_ns[pmstats->numgc%nelem(pmstats->pause_ns)] = tm4 - tm0;
2275 pmstats->pause_end[pmstats->numgc%nelem(pmstats->pause_end)] = pmstats->last_gc;
2276 pmstats->pause_total_ns += tm4 - tm0;
2277 pmstats->numgc++;
2278 if(pmstats->debuggc)
2279 runtime_printf("pause %D\n", tm4-tm0);
2281 if(runtime_debug.gctrace) {
2282 heap1 = pmstats->heap_alloc;
2283 runtime_updatememstats(&stats);
2284 if(heap1 != pmstats->heap_alloc) {
2285 runtime_printf("runtime: mstats skew: heap=%D/%D\n", heap1, pmstats->heap_alloc);
2286 runtime_throw("mstats skew");
2288 obj = pmstats->nmalloc - pmstats->nfree;
2290 stats.nprocyield += work.markfor->nprocyield;
2291 stats.nosyield += work.markfor->nosyield;
2292 stats.nsleep += work.markfor->nsleep;
2294 runtime_printf("gc%d(%d): %D+%D+%D+%D us, %D -> %D MB, %D (%D-%D) objects,"
2295 " %d/%d/%d sweeps,"
2296 " %D(%D) handoff, %D(%D) steal, %D/%D/%D yields\n",
2297 pmstats->numgc, work.nproc, (tm1-tm0)/1000, (tm2-tm1)/1000, (tm3-tm2)/1000, (tm4-tm3)/1000,
2298 heap0>>20, heap1>>20, obj,
2299 pmstats->nmalloc, pmstats->nfree,
2300 sweep.nspan, gcstats.nbgsweep, gcstats.npausesweep,
2301 stats.nhandoff, stats.nhandoffcnt,
2302 work.markfor->nsteal, work.markfor->nstealcnt,
2303 stats.nprocyield, stats.nosyield, stats.nsleep);
2304 gcstats.nbgsweep = gcstats.npausesweep = 0;
2305 if(CollectStats) {
2306 runtime_printf("scan: %D bytes, %D objects, %D untyped, %D types from MSpan\n",
2307 gcstats.nbytes, gcstats.obj.cnt, gcstats.obj.notype, gcstats.obj.typelookup);
2308 if(gcstats.ptr.cnt != 0)
2309 runtime_printf("avg ptrbufsize: %D (%D/%D)\n",
2310 gcstats.ptr.sum/gcstats.ptr.cnt, gcstats.ptr.sum, gcstats.ptr.cnt);
2311 if(gcstats.obj.cnt != 0)
2312 runtime_printf("avg nobj: %D (%D/%D)\n",
2313 gcstats.obj.sum/gcstats.obj.cnt, gcstats.obj.sum, gcstats.obj.cnt);
2314 runtime_printf("rescans: %D, %D bytes\n", gcstats.rescan, gcstats.rescanbytes);
2316 runtime_printf("instruction counts:\n");
2317 ninstr = 0;
2318 for(i=0; i<nelem(gcstats.instr); i++) {
2319 runtime_printf("\t%d:\t%D\n", i, gcstats.instr[i]);
2320 ninstr += gcstats.instr[i];
2322 runtime_printf("\ttotal:\t%D\n", ninstr);
2324 runtime_printf("putempty: %D, getfull: %D\n", gcstats.putempty, gcstats.getfull);
2326 runtime_printf("markonly base lookup: bit %D word %D span %D\n", gcstats.markonly.foundbit, gcstats.markonly.foundword, gcstats.markonly.foundspan);
2327 runtime_printf("flushptrbuf base lookup: bit %D word %D span %D\n", gcstats.flushptrbuf.foundbit, gcstats.flushptrbuf.foundword, gcstats.flushptrbuf.foundspan);
2331 // We cache current runtime_mheap.allspans array in sweep.spans,
2332 // because the former can be resized and freed.
2333 // Otherwise we would need to take heap lock every time
2334 // we want to convert span index to span pointer.
2336 // Free the old cached array if necessary.
2337 if(sweep.spans && sweep.spans != runtime_mheap.allspans)
2338 runtime_SysFree(sweep.spans, sweep.nspan*sizeof(sweep.spans[0]), &pmstats->other_sys);
2339 // Cache the current array.
2340 runtime_mheap.sweepspans = runtime_mheap.allspans;
2341 runtime_mheap.sweepgen += 2;
2342 runtime_mheap.sweepdone = false;
2343 sweep.spans = runtime_mheap.allspans;
2344 sweep.nspan = runtime_mheap.nspan;
2345 sweep.spanidx = 0;
2347 // Temporary disable concurrent sweep, because we see failures on builders.
2348 if(ConcurrentSweep && !args->eagersweep) {
2349 runtime_lock(&gclock);
2350 if(sweep.g == nil)
2351 sweep.g = __go_go(bgsweep, nil);
2352 else if(sweep.parked) {
2353 sweep.parked = false;
2354 runtime_ready(sweep.g);
2356 runtime_unlock(&gclock);
2357 } else {
2358 // Sweep all spans eagerly.
2359 while(runtime_sweepone() != (uintptr)-1)
2360 gcstats.npausesweep++;
2361 // Do an additional mProf_GC, because all 'free' events are now real as well.
2362 runtime_MProf_GC();
2365 runtime_MProf_GC();
2366 m->traceback = 0;
2369 void runtime_debug_readGCStats(Slice*)
2370 __asm__("runtime_debug.readGCStats");
2372 void
2373 runtime_debug_readGCStats(Slice *pauses)
2375 uint64 *p;
2376 uint32 i, n;
2377 MStats *pmstats;
2379 // Calling code in runtime/debug should make the slice large enough.
2380 pmstats = mstats();
2381 if((size_t)pauses->cap < nelem(pmstats->pause_ns)+3)
2382 runtime_throw("runtime: short slice passed to readGCStats");
2384 // Pass back: pauses, last gc (absolute time), number of gc, total pause ns.
2385 p = (uint64*)pauses->array;
2386 runtime_lock(&runtime_mheap);
2387 n = pmstats->numgc;
2388 if(n > nelem(pmstats->pause_ns))
2389 n = nelem(pmstats->pause_ns);
2391 // The pause buffer is circular. The most recent pause is at
2392 // pause_ns[(numgc-1)%nelem(pause_ns)], and then backward
2393 // from there to go back farther in time. We deliver the times
2394 // most recent first (in p[0]).
2395 for(i=0; i<n; i++)
2396 p[i] = pmstats->pause_ns[(pmstats->numgc-1-i)%nelem(pmstats->pause_ns)];
2398 p[n] = pmstats->last_gc;
2399 p[n+1] = pmstats->numgc;
2400 p[n+2] = pmstats->pause_total_ns;
2401 runtime_unlock(&runtime_mheap);
2402 pauses->__count = n+3;
2405 int32
2406 runtime_setgcpercent(int32 in) {
2407 int32 out;
2409 runtime_lock(&runtime_mheap);
2410 if(gcpercent == GcpercentUnknown)
2411 gcpercent = readgogc();
2412 out = gcpercent;
2413 if(in < 0)
2414 in = -1;
2415 gcpercent = in;
2416 runtime_unlock(&runtime_mheap);
2417 return out;
2420 static void
2421 gchelperstart(void)
2423 M *m;
2425 m = runtime_m();
2426 if(m->helpgc < 0 || m->helpgc >= MaxGcproc)
2427 runtime_throw("gchelperstart: bad m->helpgc");
2428 if(runtime_xchg(&bufferList[m->helpgc].busy, 1))
2429 runtime_throw("gchelperstart: already busy");
2430 if(runtime_g() != m->g0)
2431 runtime_throw("gchelper not running on g0 stack");
2434 static void
2435 runfinq(void* dummy __attribute__ ((unused)))
2437 Finalizer *f;
2438 FinBlock *fb, *next;
2439 uint32 i;
2440 Eface ef;
2441 Iface iface;
2443 // This function blocks for long periods of time, and because it is written in C
2444 // we have no liveness information. Zero everything so that uninitialized pointers
2445 // do not cause memory leaks.
2446 f = nil;
2447 fb = nil;
2448 next = nil;
2449 i = 0;
2450 ef.__type_descriptor = nil;
2451 ef.__object = nil;
2453 // force flush to memory
2454 USED(&f);
2455 USED(&fb);
2456 USED(&next);
2457 USED(&i);
2458 USED(&ef);
2460 for(;;) {
2461 runtime_lock(&finlock);
2462 fb = finq;
2463 finq = nil;
2464 if(fb == nil) {
2465 runtime_fingwait = true;
2466 runtime_g()->isbackground = true;
2467 runtime_parkunlock(&finlock, "finalizer wait");
2468 runtime_g()->isbackground = false;
2469 continue;
2471 runtime_unlock(&finlock);
2472 for(; fb; fb=next) {
2473 next = fb->next;
2474 for(i=0; i<(uint32)fb->cnt; i++) {
2475 const Type *fint;
2476 void *param;
2478 f = &fb->fin[i];
2479 fint = ((const Type**)f->ft->__in.array)[0];
2480 if((fint->__code & kindMask) == kindPtr) {
2481 // direct use of pointer
2482 param = &f->arg;
2483 } else if(((const InterfaceType*)fint)->__methods.__count == 0) {
2484 // convert to empty interface
2485 ef.__type_descriptor = (const Type*)f->ot;
2486 ef.__object = f->arg;
2487 param = &ef;
2488 } else {
2489 // convert to interface with methods
2490 iface.__methods = __go_convert_interface_2((const Type*)fint,
2491 (const Type*)f->ot,
2493 iface.__object = f->arg;
2494 if(iface.__methods == nil)
2495 runtime_throw("invalid type conversion in runfinq");
2496 param = &iface;
2498 reflect_call(f->ft, f->fn, 0, 0, &param, nil);
2499 f->fn = nil;
2500 f->arg = nil;
2501 f->ot = nil;
2503 fb->cnt = 0;
2504 runtime_lock(&finlock);
2505 fb->next = finc;
2506 finc = fb;
2507 runtime_unlock(&finlock);
2510 // Zero everything that's dead, to avoid memory leaks.
2511 // See comment at top of function.
2512 f = nil;
2513 fb = nil;
2514 next = nil;
2515 i = 0;
2516 ef.__type_descriptor = nil;
2517 ef.__object = nil;
2518 runtime_gc(1); // trigger another gc to clean up the finalized objects, if possible
2522 void
2523 runtime_createfing(void)
2525 if(fing != nil)
2526 return;
2527 // Here we use gclock instead of finlock,
2528 // because newproc1 can allocate, which can cause on-demand span sweep,
2529 // which can queue finalizers, which would deadlock.
2530 runtime_lock(&gclock);
2531 if(fing == nil)
2532 fing = __go_go(runfinq, nil);
2533 runtime_unlock(&gclock);
2537 runtime_wakefing(void)
2539 G *res;
2541 res = nil;
2542 runtime_lock(&finlock);
2543 if(runtime_fingwait && runtime_fingwake) {
2544 runtime_fingwait = false;
2545 runtime_fingwake = false;
2546 res = fing;
2548 runtime_unlock(&finlock);
2549 return res;
2552 void
2553 runtime_marknogc(void *v)
2555 uintptr *b, off, shift;
2557 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2558 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2559 shift = off % wordsPerBitmapWord;
2560 *b = (*b & ~(bitAllocated<<shift)) | bitBlockBoundary<<shift;
2563 void
2564 runtime_markscan(void *v)
2566 uintptr *b, off, shift;
2568 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2569 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2570 shift = off % wordsPerBitmapWord;
2571 *b |= bitScan<<shift;
2574 // mark the block at v as freed.
2575 void
2576 runtime_markfreed(void *v)
2578 uintptr *b, off, shift;
2580 if(0)
2581 runtime_printf("markfreed %p\n", v);
2583 if((byte*)v > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2584 runtime_throw("markfreed: bad pointer");
2586 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2587 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2588 shift = off % wordsPerBitmapWord;
2589 *b = (*b & ~(bitMask<<shift)) | (bitAllocated<<shift);
2592 // check that the block at v of size n is marked freed.
2593 void
2594 runtime_checkfreed(void *v, uintptr n)
2596 uintptr *b, bits, off, shift;
2598 if(!runtime_checking)
2599 return;
2601 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2602 return; // not allocated, so okay
2604 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2605 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2606 shift = off % wordsPerBitmapWord;
2608 bits = *b>>shift;
2609 if((bits & bitAllocated) != 0) {
2610 runtime_printf("checkfreed %p+%p: off=%p have=%p\n",
2611 v, n, off, bits & bitMask);
2612 runtime_throw("checkfreed: not freed");
2616 // mark the span of memory at v as having n blocks of the given size.
2617 // if leftover is true, there is left over space at the end of the span.
2618 void
2619 runtime_markspan(void *v, uintptr size, uintptr n, bool leftover)
2621 uintptr *b, *b0, off, shift, i, x;
2622 byte *p;
2624 if((byte*)v+size*n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2625 runtime_throw("markspan: bad pointer");
2627 if(runtime_checking) {
2628 // bits should be all zero at the start
2629 off = (byte*)v + size - runtime_mheap.arena_start;
2630 b = (uintptr*)(runtime_mheap.arena_start - off/wordsPerBitmapWord);
2631 for(i = 0; i < size/PtrSize/wordsPerBitmapWord; i++) {
2632 if(b[i] != 0)
2633 runtime_throw("markspan: span bits not zero");
2637 p = v;
2638 if(leftover) // mark a boundary just past end of last block too
2639 n++;
2641 b0 = nil;
2642 x = 0;
2643 for(; n-- > 0; p += size) {
2644 // Okay to use non-atomic ops here, because we control
2645 // the entire span, and each bitmap word has bits for only
2646 // one span, so no other goroutines are changing these
2647 // bitmap words.
2648 off = (uintptr*)p - (uintptr*)runtime_mheap.arena_start; // word offset
2649 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2650 shift = off % wordsPerBitmapWord;
2651 if(b0 != b) {
2652 if(b0 != nil)
2653 *b0 = x;
2654 b0 = b;
2655 x = 0;
2657 x |= bitAllocated<<shift;
2659 *b0 = x;
2662 // unmark the span of memory at v of length n bytes.
2663 void
2664 runtime_unmarkspan(void *v, uintptr n)
2666 uintptr *p, *b, off;
2668 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2669 runtime_throw("markspan: bad pointer");
2671 p = v;
2672 off = p - (uintptr*)runtime_mheap.arena_start; // word offset
2673 if(off % wordsPerBitmapWord != 0)
2674 runtime_throw("markspan: unaligned pointer");
2675 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2676 n /= PtrSize;
2677 if(n%wordsPerBitmapWord != 0)
2678 runtime_throw("unmarkspan: unaligned length");
2679 // Okay to use non-atomic ops here, because we control
2680 // the entire span, and each bitmap word has bits for only
2681 // one span, so no other goroutines are changing these
2682 // bitmap words.
2683 n /= wordsPerBitmapWord;
2684 while(n-- > 0)
2685 *b-- = 0;
2688 void
2689 runtime_MHeap_MapBits(MHeap *h)
2691 size_t page_size;
2693 // Caller has added extra mappings to the arena.
2694 // Add extra mappings of bitmap words as needed.
2695 // We allocate extra bitmap pieces in chunks of bitmapChunk.
2696 enum {
2697 bitmapChunk = 8192
2699 uintptr n;
2701 n = (h->arena_used - h->arena_start) / wordsPerBitmapWord;
2702 n = ROUND(n, bitmapChunk);
2703 n = ROUND(n, PageSize);
2704 page_size = getpagesize();
2705 n = ROUND(n, page_size);
2706 if(h->bitmap_mapped >= n)
2707 return;
2709 runtime_SysMap(h->arena_start - n, n - h->bitmap_mapped, h->arena_reserved, &mstats()->gc_sys);
2710 h->bitmap_mapped = n;
2713 // typedmemmove copies a value of type t to dst from src.
2715 extern void typedmemmove(const Type* td, void *dst, const void *src)
2716 __asm__ (GOSYM_PREFIX "reflect.typedmemmove");
2718 void
2719 typedmemmove(const Type* td, void *dst, const void *src)
2721 runtime_memmove(dst, src, td->__size);
2724 // typedslicecopy copies a slice of elemType values from src to dst,
2725 // returning the number of elements copied.
2727 extern intgo typedslicecopy(const Type* elem, Slice dst, Slice src)
2728 __asm__ (GOSYM_PREFIX "reflect.typedslicecopy");
2730 intgo
2731 typedslicecopy(const Type* elem, Slice dst, Slice src)
2733 intgo n;
2734 void *dstp;
2735 void *srcp;
2737 n = dst.__count;
2738 if (n > src.__count)
2739 n = src.__count;
2740 if (n == 0)
2741 return 0;
2742 dstp = dst.__values;
2743 srcp = src.__values;
2744 memmove(dstp, srcp, (uintptr_t)n * elem->__size);
2745 return n;