Use df_read_modify_subreg_p in cprop.c
[official-gcc.git] / libgo / runtime / mgc0.c
blobe5a9dfb07fe04983b15a06d42f2cc5a5f1a07d01
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 // Hmap aka __go_map
66 typedef struct __go_map Hmap;
67 // Type aka __go_type_descriptor
68 #define string __reflection
69 // PtrType aka __go_ptr_type
70 #define elem __element_type
72 #ifdef USING_SPLIT_STACK
74 extern void * __splitstack_find (void *, void *, size_t *, void **, void **,
75 void **);
77 extern void * __splitstack_find_context (void *context[10], size_t *, void **,
78 void **, void **);
80 #endif
82 enum {
83 Debug = 0,
84 CollectStats = 0,
85 ConcurrentSweep = 1,
87 WorkbufSize = 16*1024,
88 FinBlockSize = 4*1024,
90 handoffThreshold = 4,
91 IntermediateBufferCapacity = 64,
93 // Bits in type information
94 PRECISE = 1,
95 LOOP = 2,
96 PC_BITS = PRECISE | LOOP,
98 RootData = 0,
99 RootBss = 1,
100 RootFinalizers = 2,
101 RootSpanTypes = 3,
102 RootFlushCaches = 4,
103 RootCount = 5,
106 #define GcpercentUnknown (-2)
108 // Initialized from $GOGC. GOGC=off means no gc.
109 static int32 gcpercent = GcpercentUnknown;
111 static FuncVal* poolcleanup;
113 void sync_runtime_registerPoolCleanup(FuncVal*)
114 __asm__ (GOSYM_PREFIX "sync.runtime_registerPoolCleanup");
116 void
117 sync_runtime_registerPoolCleanup(FuncVal *f)
119 poolcleanup = f;
122 static void
123 clearpools(void)
125 P *p, **pp;
126 MCache *c;
128 // clear sync.Pool's
129 if(poolcleanup != nil) {
130 __builtin_call_with_static_chain(poolcleanup->fn(),
131 poolcleanup);
134 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
135 // clear tinyalloc pool
136 c = p->mcache;
137 if(c != nil) {
138 c->tiny = nil;
139 c->tinysize = 0;
141 // clear defer pools
142 p->deferpool = nil;
146 typedef struct Workbuf Workbuf;
147 struct Workbuf
149 #define SIZE (WorkbufSize-sizeof(LFNode)-sizeof(uintptr))
150 LFNode node; // must be first
151 uintptr nobj;
152 Obj obj[SIZE/sizeof(Obj) - 1];
153 uint8 _padding[SIZE%sizeof(Obj) + sizeof(Obj)];
154 #undef SIZE
157 typedef struct Finalizer Finalizer;
158 struct Finalizer
160 FuncVal *fn;
161 void *arg;
162 const struct __go_func_type *ft;
163 const PtrType *ot;
166 typedef struct FinBlock FinBlock;
167 struct FinBlock
169 FinBlock *alllink;
170 FinBlock *next;
171 int32 cnt;
172 int32 cap;
173 Finalizer fin[1];
176 static Lock finlock; // protects the following variables
177 static FinBlock *finq; // list of finalizers that are to be executed
178 static FinBlock *finc; // cache of free blocks
179 static FinBlock *allfin; // list of all blocks
180 bool runtime_fingwait;
181 bool runtime_fingwake;
183 static Lock gclock;
184 static G* fing;
186 static void runfinq(void*);
187 static void bgsweep(void*);
188 static Workbuf* getempty(Workbuf*);
189 static Workbuf* getfull(Workbuf*);
190 static void putempty(Workbuf*);
191 static Workbuf* handoff(Workbuf*);
192 static void gchelperstart(void);
193 static void flushallmcaches(void);
194 static void addstackroots(G *gp, Workbuf **wbufp);
196 static struct {
197 uint64 full; // lock-free list of full blocks
198 uint64 wempty; // lock-free list of empty blocks
199 byte pad0[CacheLineSize]; // prevents false-sharing between full/empty and nproc/nwait
200 uint32 nproc;
201 int64 tstart;
202 volatile uint32 nwait;
203 volatile uint32 ndone;
204 Note alldone;
205 ParFor *markfor;
207 Lock;
208 byte *chunk;
209 uintptr nchunk;
210 } work __attribute__((aligned(8)));
212 enum {
213 GC_DEFAULT_PTR = GC_NUM_INSTR,
214 GC_CHAN,
216 GC_NUM_INSTR2
219 static struct {
220 struct {
221 uint64 sum;
222 uint64 cnt;
223 } ptr;
224 uint64 nbytes;
225 struct {
226 uint64 sum;
227 uint64 cnt;
228 uint64 notype;
229 uint64 typelookup;
230 } obj;
231 uint64 rescan;
232 uint64 rescanbytes;
233 uint64 instr[GC_NUM_INSTR2];
234 uint64 putempty;
235 uint64 getfull;
236 struct {
237 uint64 foundbit;
238 uint64 foundword;
239 uint64 foundspan;
240 } flushptrbuf;
241 struct {
242 uint64 foundbit;
243 uint64 foundword;
244 uint64 foundspan;
245 } markonly;
246 uint32 nbgsweep;
247 uint32 npausesweep;
248 } gcstats;
250 // markonly marks an object. It returns true if the object
251 // has been marked by this function, false otherwise.
252 // This function doesn't append the object to any buffer.
253 static bool
254 markonly(const void *obj)
256 byte *p;
257 uintptr *bitp, bits, shift, x, xbits, off, j;
258 MSpan *s;
259 PageID k;
261 // Words outside the arena cannot be pointers.
262 if((const byte*)obj < runtime_mheap.arena_start || (const byte*)obj >= runtime_mheap.arena_used)
263 return false;
265 // obj may be a pointer to a live object.
266 // Try to find the beginning of the object.
268 // Round down to word boundary.
269 obj = (const void*)((uintptr)obj & ~((uintptr)PtrSize-1));
271 // Find bits for this word.
272 off = (const uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
273 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
274 shift = off % wordsPerBitmapWord;
275 xbits = *bitp;
276 bits = xbits >> shift;
278 // Pointing at the beginning of a block?
279 if((bits & (bitAllocated|bitBlockBoundary)) != 0) {
280 if(CollectStats)
281 runtime_xadd64(&gcstats.markonly.foundbit, 1);
282 goto found;
285 // Pointing just past the beginning?
286 // Scan backward a little to find a block boundary.
287 for(j=shift; j-->0; ) {
288 if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
289 shift = j;
290 bits = xbits>>shift;
291 if(CollectStats)
292 runtime_xadd64(&gcstats.markonly.foundword, 1);
293 goto found;
297 // Otherwise consult span table to find beginning.
298 // (Manually inlined copy of MHeap_LookupMaybe.)
299 k = (uintptr)obj>>PageShift;
300 x = k;
301 x -= (uintptr)runtime_mheap.arena_start>>PageShift;
302 s = runtime_mheap.spans[x];
303 if(s == nil || k < s->start || (uintptr)obj >= s->limit || s->state != MSpanInUse)
304 return false;
305 p = (byte*)((uintptr)s->start<<PageShift);
306 if(s->sizeclass == 0) {
307 obj = p;
308 } else {
309 uintptr size = s->elemsize;
310 int32 i = ((const byte*)obj - p)/size;
311 obj = p+i*size;
314 // Now that we know the object header, reload bits.
315 off = (const uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
316 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
317 shift = off % wordsPerBitmapWord;
318 xbits = *bitp;
319 bits = xbits >> shift;
320 if(CollectStats)
321 runtime_xadd64(&gcstats.markonly.foundspan, 1);
323 found:
324 // Now we have bits, bitp, and shift correct for
325 // obj pointing at the base of the object.
326 // Only care about allocated and not marked.
327 if((bits & (bitAllocated|bitMarked)) != bitAllocated)
328 return false;
329 if(work.nproc == 1)
330 *bitp |= bitMarked<<shift;
331 else {
332 for(;;) {
333 x = *bitp;
334 if(x & (bitMarked<<shift))
335 return false;
336 if(runtime_casp((void**)bitp, (void*)x, (void*)(x|(bitMarked<<shift))))
337 break;
341 // The object is now marked
342 return true;
345 // PtrTarget is a structure used by intermediate buffers.
346 // The intermediate buffers hold GC data before it
347 // is moved/flushed to the work buffer (Workbuf).
348 // The size of an intermediate buffer is very small,
349 // such as 32 or 64 elements.
350 typedef struct PtrTarget PtrTarget;
351 struct PtrTarget
353 void *p;
354 uintptr ti;
357 typedef struct Scanbuf Scanbuf;
358 struct Scanbuf
360 struct {
361 PtrTarget *begin;
362 PtrTarget *end;
363 PtrTarget *pos;
364 } ptr;
365 struct {
366 Obj *begin;
367 Obj *end;
368 Obj *pos;
369 } obj;
370 Workbuf *wbuf;
371 Obj *wp;
372 uintptr nobj;
375 typedef struct BufferList BufferList;
376 struct BufferList
378 PtrTarget ptrtarget[IntermediateBufferCapacity];
379 Obj obj[IntermediateBufferCapacity];
380 uint32 busy;
381 byte pad[CacheLineSize];
383 static BufferList bufferList[MaxGcproc];
385 static void enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj);
387 // flushptrbuf moves data from the PtrTarget buffer to the work buffer.
388 // The PtrTarget buffer contains blocks irrespective of whether the blocks have been marked or scanned,
389 // while the work buffer contains blocks which have been marked
390 // and are prepared to be scanned by the garbage collector.
392 // _wp, _wbuf, _nobj are input/output parameters and are specifying the work buffer.
394 // A simplified drawing explaining how the todo-list moves from a structure to another:
396 // scanblock
397 // (find pointers)
398 // Obj ------> PtrTarget (pointer targets)
399 // ↑ |
400 // | |
401 // `----------'
402 // flushptrbuf
403 // (find block start, mark and enqueue)
404 static void
405 flushptrbuf(Scanbuf *sbuf)
407 byte *p, *arena_start, *obj;
408 uintptr size, *bitp, bits, shift, j, x, xbits, off, nobj, ti, n;
409 MSpan *s;
410 PageID k;
411 Obj *wp;
412 Workbuf *wbuf;
413 PtrTarget *ptrbuf;
414 PtrTarget *ptrbuf_end;
416 arena_start = runtime_mheap.arena_start;
418 wp = sbuf->wp;
419 wbuf = sbuf->wbuf;
420 nobj = sbuf->nobj;
422 ptrbuf = sbuf->ptr.begin;
423 ptrbuf_end = sbuf->ptr.pos;
424 n = ptrbuf_end - sbuf->ptr.begin;
425 sbuf->ptr.pos = sbuf->ptr.begin;
427 if(CollectStats) {
428 runtime_xadd64(&gcstats.ptr.sum, n);
429 runtime_xadd64(&gcstats.ptr.cnt, 1);
432 // If buffer is nearly full, get a new one.
433 if(wbuf == nil || nobj+n >= nelem(wbuf->obj)) {
434 if(wbuf != nil)
435 wbuf->nobj = nobj;
436 wbuf = getempty(wbuf);
437 wp = wbuf->obj;
438 nobj = 0;
440 if(n >= nelem(wbuf->obj))
441 runtime_throw("ptrbuf has to be smaller than WorkBuf");
444 while(ptrbuf < ptrbuf_end) {
445 obj = ptrbuf->p;
446 ti = ptrbuf->ti;
447 ptrbuf++;
449 // obj belongs to interval [mheap.arena_start, mheap.arena_used).
450 if(Debug > 1) {
451 if(obj < runtime_mheap.arena_start || obj >= runtime_mheap.arena_used)
452 runtime_throw("object is outside of mheap");
455 // obj may be a pointer to a live object.
456 // Try to find the beginning of the object.
458 // Round down to word boundary.
459 if(((uintptr)obj & ((uintptr)PtrSize-1)) != 0) {
460 obj = (void*)((uintptr)obj & ~((uintptr)PtrSize-1));
461 ti = 0;
464 // Find bits for this word.
465 off = (uintptr*)obj - (uintptr*)arena_start;
466 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
467 shift = off % wordsPerBitmapWord;
468 xbits = *bitp;
469 bits = xbits >> shift;
471 // Pointing at the beginning of a block?
472 if((bits & (bitAllocated|bitBlockBoundary)) != 0) {
473 if(CollectStats)
474 runtime_xadd64(&gcstats.flushptrbuf.foundbit, 1);
475 goto found;
478 ti = 0;
480 // Pointing just past the beginning?
481 // Scan backward a little to find a block boundary.
482 for(j=shift; j-->0; ) {
483 if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
484 obj = (byte*)obj - (shift-j)*PtrSize;
485 shift = j;
486 bits = xbits>>shift;
487 if(CollectStats)
488 runtime_xadd64(&gcstats.flushptrbuf.foundword, 1);
489 goto found;
493 // Otherwise consult span table to find beginning.
494 // (Manually inlined copy of MHeap_LookupMaybe.)
495 k = (uintptr)obj>>PageShift;
496 x = k;
497 x -= (uintptr)arena_start>>PageShift;
498 s = runtime_mheap.spans[x];
499 if(s == nil || k < s->start || (uintptr)obj >= s->limit || s->state != MSpanInUse)
500 continue;
501 p = (byte*)((uintptr)s->start<<PageShift);
502 if(s->sizeclass == 0) {
503 obj = p;
504 } else {
505 size = s->elemsize;
506 int32 i = ((byte*)obj - p)/size;
507 obj = p+i*size;
510 // Now that we know the object header, reload bits.
511 off = (uintptr*)obj - (uintptr*)arena_start;
512 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
513 shift = off % wordsPerBitmapWord;
514 xbits = *bitp;
515 bits = xbits >> shift;
516 if(CollectStats)
517 runtime_xadd64(&gcstats.flushptrbuf.foundspan, 1);
519 found:
520 // Now we have bits, bitp, and shift correct for
521 // obj pointing at the base of the object.
522 // Only care about allocated and not marked.
523 if((bits & (bitAllocated|bitMarked)) != bitAllocated)
524 continue;
525 if(work.nproc == 1)
526 *bitp |= bitMarked<<shift;
527 else {
528 for(;;) {
529 x = *bitp;
530 if(x & (bitMarked<<shift))
531 goto continue_obj;
532 if(runtime_casp((void**)bitp, (void*)x, (void*)(x|(bitMarked<<shift))))
533 break;
537 // If object has no pointers, don't need to scan further.
538 if((bits & bitScan) == 0)
539 continue;
541 // Ask span about size class.
542 // (Manually inlined copy of MHeap_Lookup.)
543 x = (uintptr)obj >> PageShift;
544 x -= (uintptr)arena_start>>PageShift;
545 s = runtime_mheap.spans[x];
547 PREFETCH(obj);
549 *wp = (Obj){obj, s->elemsize, ti};
550 wp++;
551 nobj++;
552 continue_obj:;
555 // If another proc wants a pointer, give it some.
556 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
557 wbuf->nobj = nobj;
558 wbuf = handoff(wbuf);
559 nobj = wbuf->nobj;
560 wp = wbuf->obj + nobj;
563 sbuf->wp = wp;
564 sbuf->wbuf = wbuf;
565 sbuf->nobj = nobj;
568 static void
569 flushobjbuf(Scanbuf *sbuf)
571 uintptr nobj, off;
572 Obj *wp, obj;
573 Workbuf *wbuf;
574 Obj *objbuf;
575 Obj *objbuf_end;
577 wp = sbuf->wp;
578 wbuf = sbuf->wbuf;
579 nobj = sbuf->nobj;
581 objbuf = sbuf->obj.begin;
582 objbuf_end = sbuf->obj.pos;
583 sbuf->obj.pos = sbuf->obj.begin;
585 while(objbuf < objbuf_end) {
586 obj = *objbuf++;
588 // Align obj.b to a word boundary.
589 off = (uintptr)obj.p & (PtrSize-1);
590 if(off != 0) {
591 obj.p += PtrSize - off;
592 obj.n -= PtrSize - off;
593 obj.ti = 0;
596 if(obj.p == nil || obj.n == 0)
597 continue;
599 // If buffer is full, get a new one.
600 if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
601 if(wbuf != nil)
602 wbuf->nobj = nobj;
603 wbuf = getempty(wbuf);
604 wp = wbuf->obj;
605 nobj = 0;
608 *wp = obj;
609 wp++;
610 nobj++;
613 // If another proc wants a pointer, give it some.
614 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
615 wbuf->nobj = nobj;
616 wbuf = handoff(wbuf);
617 nobj = wbuf->nobj;
618 wp = wbuf->obj + nobj;
621 sbuf->wp = wp;
622 sbuf->wbuf = wbuf;
623 sbuf->nobj = nobj;
626 // Program that scans the whole block and treats every block element as a potential pointer
627 static uintptr defaultProg[2] = {PtrSize, GC_DEFAULT_PTR};
629 // Hchan program
630 static uintptr chanProg[2] = {0, GC_CHAN};
632 // Local variables of a program fragment or loop
633 typedef struct GCFrame GCFrame;
634 struct GCFrame {
635 uintptr count, elemsize, b;
636 const uintptr *loop_or_ret;
639 // Sanity check for the derived type info objti.
640 static void
641 checkptr(void *obj, uintptr objti)
643 uintptr *pc1, type, tisize, i, j, x;
644 const uintptr *pc2;
645 byte *objstart;
646 Type *t;
647 MSpan *s;
649 if(!Debug)
650 runtime_throw("checkptr is debug only");
652 if((byte*)obj < runtime_mheap.arena_start || (byte*)obj >= runtime_mheap.arena_used)
653 return;
654 type = runtime_gettype(obj);
655 t = (Type*)(type & ~(uintptr)(PtrSize-1));
656 if(t == nil)
657 return;
658 x = (uintptr)obj >> PageShift;
659 x -= (uintptr)(runtime_mheap.arena_start)>>PageShift;
660 s = runtime_mheap.spans[x];
661 objstart = (byte*)((uintptr)s->start<<PageShift);
662 if(s->sizeclass != 0) {
663 i = ((byte*)obj - objstart)/s->elemsize;
664 objstart += i*s->elemsize;
666 tisize = *(uintptr*)objti;
667 // Sanity check for object size: it should fit into the memory block.
668 if((byte*)obj + tisize > objstart + s->elemsize) {
669 runtime_printf("object of type '%S' at %p/%p does not fit in block %p/%p\n",
670 *t->string, obj, tisize, objstart, s->elemsize);
671 runtime_throw("invalid gc type info");
673 if(obj != objstart)
674 return;
675 // If obj points to the beginning of the memory block,
676 // check type info as well.
677 if(t->string == nil ||
678 // Gob allocates unsafe pointers for indirection.
679 (runtime_strcmp((const char *)t->string->str, (const char*)"unsafe.Pointer") &&
680 // Runtime and gc think differently about closures.
681 runtime_strstr((const char *)t->string->str, (const char*)"struct { F uintptr") != (const char *)t->string->str)) {
682 pc1 = (uintptr*)objti;
683 pc2 = (const uintptr*)t->__gc;
684 // A simple best-effort check until first GC_END.
685 for(j = 1; pc1[j] != GC_END && pc2[j] != GC_END; j++) {
686 if(pc1[j] != pc2[j]) {
687 runtime_printf("invalid gc type info for '%s', type info %p [%d]=%p, block info %p [%d]=%p\n",
688 t->string ? (const int8*)t->string->str : (const int8*)"?", pc1, (int32)j, pc1[j], pc2, (int32)j, pc2[j]);
689 runtime_throw("invalid gc type info");
695 // scanblock scans a block of n bytes starting at pointer b for references
696 // to other objects, scanning any it finds recursively until there are no
697 // unscanned objects left. Instead of using an explicit recursion, it keeps
698 // a work list in the Workbuf* structures and loops in the main function
699 // body. Keeping an explicit work list is easier on the stack allocator and
700 // more efficient.
701 static void
702 scanblock(Workbuf *wbuf, bool keepworking)
704 byte *b, *arena_start, *arena_used;
705 uintptr n, i, end_b, elemsize, size, ti, objti, count, type, nobj;
706 uintptr precise_type, nominal_size;
707 const uintptr *pc, *chan_ret;
708 uintptr chancap;
709 void *obj;
710 const Type *t, *et;
711 Slice *sliceptr;
712 String *stringptr;
713 GCFrame *stack_ptr, stack_top, stack[GC_STACK_CAPACITY+4];
714 BufferList *scanbuffers;
715 Scanbuf sbuf;
716 Eface *eface;
717 Iface *iface;
718 Hchan *chan;
719 const ChanType *chantype;
720 Obj *wp;
722 if(sizeof(Workbuf) % WorkbufSize != 0)
723 runtime_throw("scanblock: size of Workbuf is suboptimal");
725 // Memory arena parameters.
726 arena_start = runtime_mheap.arena_start;
727 arena_used = runtime_mheap.arena_used;
729 stack_ptr = stack+nelem(stack)-1;
731 precise_type = false;
732 nominal_size = 0;
734 if(wbuf) {
735 nobj = wbuf->nobj;
736 wp = &wbuf->obj[nobj];
737 } else {
738 nobj = 0;
739 wp = nil;
742 // Initialize sbuf
743 scanbuffers = &bufferList[runtime_m()->helpgc];
745 sbuf.ptr.begin = sbuf.ptr.pos = &scanbuffers->ptrtarget[0];
746 sbuf.ptr.end = sbuf.ptr.begin + nelem(scanbuffers->ptrtarget);
748 sbuf.obj.begin = sbuf.obj.pos = &scanbuffers->obj[0];
749 sbuf.obj.end = sbuf.obj.begin + nelem(scanbuffers->obj);
751 sbuf.wbuf = wbuf;
752 sbuf.wp = wp;
753 sbuf.nobj = nobj;
755 // (Silence the compiler)
756 chan = nil;
757 chantype = nil;
758 chan_ret = nil;
760 goto next_block;
762 for(;;) {
763 // Each iteration scans the block b of length n, queueing pointers in
764 // the work buffer.
766 if(CollectStats) {
767 runtime_xadd64(&gcstats.nbytes, n);
768 runtime_xadd64(&gcstats.obj.sum, sbuf.nobj);
769 runtime_xadd64(&gcstats.obj.cnt, 1);
772 if(ti != 0) {
773 if(Debug > 1) {
774 runtime_printf("scanblock %p %D ti %p\n", b, (int64)n, ti);
776 pc = (uintptr*)(ti & ~(uintptr)PC_BITS);
777 precise_type = (ti & PRECISE);
778 stack_top.elemsize = pc[0];
779 if(!precise_type)
780 nominal_size = pc[0];
781 if(ti & LOOP) {
782 stack_top.count = 0; // 0 means an infinite number of iterations
783 stack_top.loop_or_ret = pc+1;
784 } else {
785 stack_top.count = 1;
787 if(Debug) {
788 // Simple sanity check for provided type info ti:
789 // The declared size of the object must be not larger than the actual size
790 // (it can be smaller due to inferior pointers).
791 // It's difficult to make a comprehensive check due to inferior pointers,
792 // reflection, gob, etc.
793 if(pc[0] > n) {
794 runtime_printf("invalid gc type info: type info size %p, block size %p\n", pc[0], n);
795 runtime_throw("invalid gc type info");
798 } else if(UseSpanType) {
799 if(CollectStats)
800 runtime_xadd64(&gcstats.obj.notype, 1);
802 type = runtime_gettype(b);
803 if(type != 0) {
804 if(CollectStats)
805 runtime_xadd64(&gcstats.obj.typelookup, 1);
807 t = (Type*)(type & ~(uintptr)(PtrSize-1));
808 switch(type & (PtrSize-1)) {
809 case TypeInfo_SingleObject:
810 pc = (const uintptr*)t->__gc;
811 precise_type = true; // type information about 'b' is precise
812 stack_top.count = 1;
813 stack_top.elemsize = pc[0];
814 break;
815 case TypeInfo_Array:
816 pc = (const uintptr*)t->__gc;
817 if(pc[0] == 0)
818 goto next_block;
819 precise_type = true; // type information about 'b' is precise
820 stack_top.count = 0; // 0 means an infinite number of iterations
821 stack_top.elemsize = pc[0];
822 stack_top.loop_or_ret = pc+1;
823 break;
824 case TypeInfo_Chan:
825 chan = (Hchan*)b;
826 chantype = (const ChanType*)t;
827 chan_ret = nil;
828 pc = chanProg;
829 break;
830 default:
831 if(Debug > 1)
832 runtime_printf("scanblock %p %D type %p %S\n", b, (int64)n, type, *t->string);
833 runtime_throw("scanblock: invalid type");
834 return;
836 if(Debug > 1)
837 runtime_printf("scanblock %p %D type %p %S pc=%p\n", b, (int64)n, type, *t->string, pc);
838 } else {
839 pc = defaultProg;
840 if(Debug > 1)
841 runtime_printf("scanblock %p %D unknown type\n", b, (int64)n);
843 } else {
844 pc = defaultProg;
845 if(Debug > 1)
846 runtime_printf("scanblock %p %D no span types\n", b, (int64)n);
849 if(IgnorePreciseGC)
850 pc = defaultProg;
852 pc++;
853 stack_top.b = (uintptr)b;
854 end_b = (uintptr)b + n - PtrSize;
856 for(;;) {
857 if(CollectStats)
858 runtime_xadd64(&gcstats.instr[pc[0]], 1);
860 obj = nil;
861 objti = 0;
862 switch(pc[0]) {
863 case GC_PTR:
864 obj = *(void**)(stack_top.b + pc[1]);
865 objti = pc[2];
866 if(Debug > 2)
867 runtime_printf("gc_ptr @%p: %p ti=%p\n", stack_top.b+pc[1], obj, objti);
868 pc += 3;
869 if(Debug)
870 checkptr(obj, objti);
871 break;
873 case GC_SLICE:
874 sliceptr = (Slice*)(stack_top.b + pc[1]);
875 if(Debug > 2)
876 runtime_printf("gc_slice @%p: %p/%D/%D\n", sliceptr, sliceptr->array, (int64)sliceptr->__count, (int64)sliceptr->cap);
877 if(sliceptr->cap != 0) {
878 obj = sliceptr->array;
879 // Can't use slice element type for scanning,
880 // because if it points to an array embedded
881 // in the beginning of a struct,
882 // we will scan the whole struct as the slice.
883 // So just obtain type info from heap.
885 pc += 3;
886 break;
888 case GC_APTR:
889 obj = *(void**)(stack_top.b + pc[1]);
890 if(Debug > 2)
891 runtime_printf("gc_aptr @%p: %p\n", stack_top.b+pc[1], obj);
892 pc += 2;
893 break;
895 case GC_STRING:
896 stringptr = (String*)(stack_top.b + pc[1]);
897 if(Debug > 2)
898 runtime_printf("gc_string @%p: %p/%D\n", stack_top.b+pc[1], stringptr->str, (int64)stringptr->len);
899 if(stringptr->len != 0)
900 markonly(stringptr->str);
901 pc += 2;
902 continue;
904 case GC_EFACE:
905 eface = (Eface*)(stack_top.b + pc[1]);
906 pc += 2;
907 if(Debug > 2)
908 runtime_printf("gc_eface @%p: %p %p\n", stack_top.b+pc[1], eface->_type, eface->data);
909 if(eface->_type == nil)
910 continue;
912 // eface->type
913 t = eface->_type;
914 if((const byte*)t >= arena_start && (const byte*)t < arena_used) {
915 union { const Type *tc; Type *tr; } u;
916 u.tc = t;
917 *sbuf.ptr.pos++ = (PtrTarget){u.tr, 0};
918 if(sbuf.ptr.pos == sbuf.ptr.end)
919 flushptrbuf(&sbuf);
922 // eface->data
923 if((byte*)eface->data >= arena_start && (byte*)eface->data < arena_used) {
924 if(__go_is_pointer_type(t)) {
925 if((t->__code & kindNoPointers))
926 continue;
928 obj = eface->data;
929 if((t->__code & kindMask) == kindPtr) {
930 // Only use type information if it is a pointer-containing type.
931 // This matches the GC programs written by cmd/gc/reflect.c's
932 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
933 et = ((const PtrType*)t)->elem;
934 if(!(et->__code & kindNoPointers))
935 objti = (uintptr)((const PtrType*)t)->elem->__gc;
937 } else {
938 obj = eface->data;
939 objti = (uintptr)t->__gc;
942 break;
944 case GC_IFACE:
945 iface = (Iface*)(stack_top.b + pc[1]);
946 pc += 2;
947 if(Debug > 2)
948 runtime_printf("gc_iface @%p: %p/%p %p\n", stack_top.b+pc[1], *(Type**)iface->tab, nil, iface->data);
949 if(iface->tab == nil)
950 continue;
952 // iface->tab
953 if((byte*)iface->tab >= arena_start && (byte*)iface->tab < arena_used) {
954 *sbuf.ptr.pos++ = (PtrTarget){iface->tab, 0};
955 if(sbuf.ptr.pos == sbuf.ptr.end)
956 flushptrbuf(&sbuf);
959 // iface->data
960 if((byte*)iface->data >= arena_start && (byte*)iface->data < arena_used) {
961 t = *(Type**)iface->tab;
962 if(__go_is_pointer_type(t)) {
963 if((t->__code & kindNoPointers))
964 continue;
966 obj = iface->data;
967 if((t->__code & kindMask) == kindPtr) {
968 // Only use type information if it is a pointer-containing type.
969 // This matches the GC programs written by cmd/gc/reflect.c's
970 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
971 et = ((const PtrType*)t)->elem;
972 if(!(et->__code & kindNoPointers))
973 objti = (uintptr)((const PtrType*)t)->elem->__gc;
975 } else {
976 obj = iface->data;
977 objti = (uintptr)t->__gc;
980 break;
982 case GC_DEFAULT_PTR:
983 while(stack_top.b <= end_b) {
984 obj = *(byte**)stack_top.b;
985 if(Debug > 2)
986 runtime_printf("gc_default_ptr @%p: %p\n", stack_top.b, obj);
987 stack_top.b += PtrSize;
988 if((byte*)obj >= arena_start && (byte*)obj < arena_used) {
989 *sbuf.ptr.pos++ = (PtrTarget){obj, 0};
990 if(sbuf.ptr.pos == sbuf.ptr.end)
991 flushptrbuf(&sbuf);
994 goto next_block;
996 case GC_END:
997 if(--stack_top.count != 0) {
998 // Next iteration of a loop if possible.
999 stack_top.b += stack_top.elemsize;
1000 if(stack_top.b + stack_top.elemsize <= end_b+PtrSize) {
1001 pc = stack_top.loop_or_ret;
1002 continue;
1004 i = stack_top.b;
1005 } else {
1006 // Stack pop if possible.
1007 if(stack_ptr+1 < stack+nelem(stack)) {
1008 pc = stack_top.loop_or_ret;
1009 stack_top = *(++stack_ptr);
1010 continue;
1012 i = (uintptr)b + nominal_size;
1014 if(!precise_type) {
1015 // Quickly scan [b+i,b+n) for possible pointers.
1016 for(; i<=end_b; i+=PtrSize) {
1017 if(*(byte**)i != nil) {
1018 // Found a value that may be a pointer.
1019 // Do a rescan of the entire block.
1020 enqueue((Obj){b, n, 0}, &sbuf.wbuf, &sbuf.wp, &sbuf.nobj);
1021 if(CollectStats) {
1022 runtime_xadd64(&gcstats.rescan, 1);
1023 runtime_xadd64(&gcstats.rescanbytes, n);
1025 break;
1029 goto next_block;
1031 case GC_ARRAY_START:
1032 i = stack_top.b + pc[1];
1033 count = pc[2];
1034 elemsize = pc[3];
1035 pc += 4;
1037 // Stack push.
1038 *stack_ptr-- = stack_top;
1039 stack_top = (GCFrame){count, elemsize, i, pc};
1040 continue;
1042 case GC_ARRAY_NEXT:
1043 if(--stack_top.count != 0) {
1044 stack_top.b += stack_top.elemsize;
1045 pc = stack_top.loop_or_ret;
1046 } else {
1047 // Stack pop.
1048 stack_top = *(++stack_ptr);
1049 pc += 1;
1051 continue;
1053 case GC_CALL:
1054 // Stack push.
1055 *stack_ptr-- = stack_top;
1056 stack_top = (GCFrame){1, 0, stack_top.b + pc[1], pc+3 /*return address*/};
1057 pc = (const uintptr*)((const byte*)pc + *(const int32*)(pc+2)); // target of the CALL instruction
1058 continue;
1060 case GC_REGION:
1061 obj = (void*)(stack_top.b + pc[1]);
1062 size = pc[2];
1063 objti = pc[3];
1064 pc += 4;
1066 if(Debug > 2)
1067 runtime_printf("gc_region @%p: %D %p\n", stack_top.b+pc[1], (int64)size, objti);
1068 *sbuf.obj.pos++ = (Obj){obj, size, objti};
1069 if(sbuf.obj.pos == sbuf.obj.end)
1070 flushobjbuf(&sbuf);
1071 continue;
1073 case GC_CHAN_PTR:
1074 chan = *(Hchan**)(stack_top.b + pc[1]);
1075 if(Debug > 2 && chan != nil)
1076 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]);
1077 if(chan == nil) {
1078 pc += 3;
1079 continue;
1081 if(markonly(chan)) {
1082 chantype = (ChanType*)pc[2];
1083 if(!(chantype->elem->__code & kindNoPointers)) {
1084 // Start chanProg.
1085 chan_ret = pc+3;
1086 pc = chanProg+1;
1087 continue;
1090 pc += 3;
1091 continue;
1093 case GC_CHAN:
1094 // There are no heap pointers in struct Hchan,
1095 // so we can ignore the leading sizeof(Hchan) bytes.
1096 if(!(chantype->elem->__code & kindNoPointers)) {
1097 chancap = chan->dataqsiz;
1098 if(chancap > 0 && markonly(chan->buf)) {
1099 // TODO(atom): split into two chunks so that only the
1100 // in-use part of the circular buffer is scanned.
1101 // (Channel routines zero the unused part, so the current
1102 // code does not lead to leaks, it's just a little inefficient.)
1103 *sbuf.obj.pos++ = (Obj){chan->buf, chancap*chantype->elem->__size,
1104 (uintptr)chantype->elem->__gc | PRECISE | LOOP};
1105 if(sbuf.obj.pos == sbuf.obj.end)
1106 flushobjbuf(&sbuf);
1109 if(chan_ret == nil)
1110 goto next_block;
1111 pc = chan_ret;
1112 continue;
1114 default:
1115 runtime_printf("runtime: invalid GC instruction %p at %p\n", pc[0], pc);
1116 runtime_throw("scanblock: invalid GC instruction");
1117 return;
1120 if((byte*)obj >= arena_start && (byte*)obj < arena_used) {
1121 *sbuf.ptr.pos++ = (PtrTarget){obj, objti};
1122 if(sbuf.ptr.pos == sbuf.ptr.end)
1123 flushptrbuf(&sbuf);
1127 next_block:
1128 // Done scanning [b, b+n). Prepare for the next iteration of
1129 // the loop by setting b, n, ti to the parameters for the next block.
1131 if(sbuf.nobj == 0) {
1132 flushptrbuf(&sbuf);
1133 flushobjbuf(&sbuf);
1135 if(sbuf.nobj == 0) {
1136 if(!keepworking) {
1137 if(sbuf.wbuf)
1138 putempty(sbuf.wbuf);
1139 return;
1141 // Emptied our buffer: refill.
1142 sbuf.wbuf = getfull(sbuf.wbuf);
1143 if(sbuf.wbuf == nil)
1144 return;
1145 sbuf.nobj = sbuf.wbuf->nobj;
1146 sbuf.wp = sbuf.wbuf->obj + sbuf.wbuf->nobj;
1150 // Fetch b from the work buffer.
1151 --sbuf.wp;
1152 b = sbuf.wp->p;
1153 n = sbuf.wp->n;
1154 ti = sbuf.wp->ti;
1155 sbuf.nobj--;
1159 static struct root_list* roots;
1161 void
1162 __go_register_gc_roots (struct root_list* r)
1164 // FIXME: This needs locking if multiple goroutines can call
1165 // dlopen simultaneously.
1166 r->next = roots;
1167 roots = r;
1170 // Append obj to the work buffer.
1171 // _wbuf, _wp, _nobj are input/output parameters and are specifying the work buffer.
1172 static void
1173 enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj)
1175 uintptr nobj, off;
1176 Obj *wp;
1177 Workbuf *wbuf;
1179 if(Debug > 1)
1180 runtime_printf("append obj(%p %D %p)\n", obj.p, (int64)obj.n, obj.ti);
1182 // Align obj.b to a word boundary.
1183 off = (uintptr)obj.p & (PtrSize-1);
1184 if(off != 0) {
1185 obj.p += PtrSize - off;
1186 obj.n -= PtrSize - off;
1187 obj.ti = 0;
1190 if(obj.p == nil || obj.n == 0)
1191 return;
1193 // Load work buffer state
1194 wp = *_wp;
1195 wbuf = *_wbuf;
1196 nobj = *_nobj;
1198 // If another proc wants a pointer, give it some.
1199 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
1200 wbuf->nobj = nobj;
1201 wbuf = handoff(wbuf);
1202 nobj = wbuf->nobj;
1203 wp = wbuf->obj + nobj;
1206 // If buffer is full, get a new one.
1207 if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
1208 if(wbuf != nil)
1209 wbuf->nobj = nobj;
1210 wbuf = getempty(wbuf);
1211 wp = wbuf->obj;
1212 nobj = 0;
1215 *wp = obj;
1216 wp++;
1217 nobj++;
1219 // Save work buffer state
1220 *_wp = wp;
1221 *_wbuf = wbuf;
1222 *_nobj = nobj;
1225 static void
1226 enqueue1(Workbuf **wbufp, Obj obj)
1228 Workbuf *wbuf;
1230 wbuf = *wbufp;
1231 if(wbuf->nobj >= nelem(wbuf->obj))
1232 *wbufp = wbuf = getempty(wbuf);
1233 wbuf->obj[wbuf->nobj++] = obj;
1236 static void
1237 markroot(ParFor *desc, uint32 i)
1239 Workbuf *wbuf;
1240 FinBlock *fb;
1241 MHeap *h;
1242 MSpan **allspans, *s;
1243 uint32 spanidx, sg;
1244 G *gp;
1245 void *p;
1247 USED(&desc);
1248 wbuf = getempty(nil);
1249 // Note: if you add a case here, please also update heapdump.c:dumproots.
1250 switch(i) {
1251 case RootData:
1252 // For gccgo this is both data and bss.
1254 struct root_list *pl;
1256 for(pl = roots; pl != nil; pl = pl->next) {
1257 struct root *pr = &pl->roots[0];
1258 while(1) {
1259 void *decl = pr->decl;
1260 if(decl == nil)
1261 break;
1262 enqueue1(&wbuf, (Obj){decl, pr->size, 0});
1263 pr++;
1267 break;
1269 case RootBss:
1270 // For gccgo we use this for all the other global roots.
1271 enqueue1(&wbuf, (Obj){(byte*)&runtime_m0, sizeof runtime_m0, 0});
1272 enqueue1(&wbuf, (Obj){(byte*)&runtime_g0, sizeof runtime_g0, 0});
1273 enqueue1(&wbuf, (Obj){(byte*)&runtime_allg, sizeof runtime_allg, 0});
1274 enqueue1(&wbuf, (Obj){(byte*)&runtime_allm, sizeof runtime_allm, 0});
1275 enqueue1(&wbuf, (Obj){(byte*)&runtime_allp, sizeof runtime_allp, 0});
1276 enqueue1(&wbuf, (Obj){(byte*)&work, sizeof work, 0});
1277 runtime_proc_scan(&wbuf, enqueue1);
1278 break;
1280 case RootFinalizers:
1281 for(fb=allfin; fb; fb=fb->alllink)
1282 enqueue1(&wbuf, (Obj){(byte*)fb->fin, fb->cnt*sizeof(fb->fin[0]), 0});
1283 break;
1285 case RootSpanTypes:
1286 // mark span types and MSpan.specials (to walk spans only once)
1287 h = &runtime_mheap;
1288 sg = h->sweepgen;
1289 allspans = h->allspans;
1290 for(spanidx=0; spanidx<runtime_mheap.nspan; spanidx++) {
1291 Special *sp;
1292 SpecialFinalizer *spf;
1294 s = allspans[spanidx];
1295 if(s->sweepgen != sg) {
1296 runtime_printf("sweep %d %d\n", s->sweepgen, sg);
1297 runtime_throw("gc: unswept span");
1299 if(s->state != MSpanInUse)
1300 continue;
1301 // The garbage collector ignores type pointers stored in MSpan.types:
1302 // - Compiler-generated types are stored outside of heap.
1303 // - The reflect package has runtime-generated types cached in its data structures.
1304 // The garbage collector relies on finding the references via that cache.
1305 if(s->types.compression == MTypes_Words || s->types.compression == MTypes_Bytes)
1306 markonly((byte*)s->types.data);
1307 for(sp = s->specials; sp != nil; sp = sp->next) {
1308 if(sp->kind != KindSpecialFinalizer)
1309 continue;
1310 // don't mark finalized object, but scan it so we
1311 // retain everything it points to.
1312 spf = (SpecialFinalizer*)sp;
1313 // A finalizer can be set for an inner byte of an object, find object beginning.
1314 p = (void*)((s->start << PageShift) + spf->offset/s->elemsize*s->elemsize);
1315 enqueue1(&wbuf, (Obj){p, s->elemsize, 0});
1316 enqueue1(&wbuf, (Obj){(void*)&spf->fn, PtrSize, 0});
1317 enqueue1(&wbuf, (Obj){(void*)&spf->ft, PtrSize, 0});
1318 enqueue1(&wbuf, (Obj){(void*)&spf->ot, PtrSize, 0});
1321 break;
1323 case RootFlushCaches:
1324 flushallmcaches();
1325 break;
1327 default:
1328 // the rest is scanning goroutine stacks
1329 if(i - RootCount >= runtime_allglen)
1330 runtime_throw("markroot: bad index");
1331 gp = runtime_allg[i - RootCount];
1332 // remember when we've first observed the G blocked
1333 // needed only to output in traceback
1334 if((gp->atomicstatus == _Gwaiting || gp->atomicstatus == _Gsyscall) && gp->waitsince == 0)
1335 gp->waitsince = work.tstart;
1336 addstackroots(gp, &wbuf);
1337 break;
1341 if(wbuf)
1342 scanblock(wbuf, false);
1345 static const FuncVal markroot_funcval = { (void *) markroot };
1347 // Get an empty work buffer off the work.empty list,
1348 // allocating new buffers as needed.
1349 static Workbuf*
1350 getempty(Workbuf *b)
1352 if(b != nil)
1353 runtime_lfstackpush(&work.full, &b->node);
1354 b = (Workbuf*)runtime_lfstackpop(&work.wempty);
1355 if(b == nil) {
1356 // Need to allocate.
1357 runtime_lock(&work);
1358 if(work.nchunk < sizeof *b) {
1359 work.nchunk = 1<<20;
1360 work.chunk = runtime_SysAlloc(work.nchunk, &mstats()->gc_sys);
1361 if(work.chunk == nil)
1362 runtime_throw("runtime: cannot allocate memory");
1364 b = (Workbuf*)work.chunk;
1365 work.chunk += sizeof *b;
1366 work.nchunk -= sizeof *b;
1367 runtime_unlock(&work);
1369 b->nobj = 0;
1370 return b;
1373 static void
1374 putempty(Workbuf *b)
1376 if(CollectStats)
1377 runtime_xadd64(&gcstats.putempty, 1);
1379 runtime_lfstackpush(&work.wempty, &b->node);
1382 // Get a full work buffer off the work.full list, or return nil.
1383 static Workbuf*
1384 getfull(Workbuf *b)
1386 M *m;
1387 int32 i;
1389 if(CollectStats)
1390 runtime_xadd64(&gcstats.getfull, 1);
1392 if(b != nil)
1393 runtime_lfstackpush(&work.wempty, &b->node);
1394 b = (Workbuf*)runtime_lfstackpop(&work.full);
1395 if(b != nil || work.nproc == 1)
1396 return b;
1398 m = runtime_m();
1399 runtime_xadd(&work.nwait, +1);
1400 for(i=0;; i++) {
1401 if(work.full != 0) {
1402 runtime_xadd(&work.nwait, -1);
1403 b = (Workbuf*)runtime_lfstackpop(&work.full);
1404 if(b != nil)
1405 return b;
1406 runtime_xadd(&work.nwait, +1);
1408 if(work.nwait == work.nproc)
1409 return nil;
1410 if(i < 10) {
1411 m->gcstats.nprocyield++;
1412 runtime_procyield(20);
1413 } else if(i < 20) {
1414 m->gcstats.nosyield++;
1415 runtime_osyield();
1416 } else {
1417 m->gcstats.nsleep++;
1418 runtime_usleep(100);
1423 static Workbuf*
1424 handoff(Workbuf *b)
1426 M *m;
1427 int32 n;
1428 Workbuf *b1;
1430 m = runtime_m();
1432 // Make new buffer with half of b's pointers.
1433 b1 = getempty(nil);
1434 n = b->nobj/2;
1435 b->nobj -= n;
1436 b1->nobj = n;
1437 runtime_memmove(b1->obj, b->obj+b->nobj, n*sizeof b1->obj[0]);
1438 m->gcstats.nhandoff++;
1439 m->gcstats.nhandoffcnt += n;
1441 // Put b on full list - let first half of b get stolen.
1442 runtime_lfstackpush(&work.full, &b->node);
1443 return b1;
1446 static void
1447 addstackroots(G *gp, Workbuf **wbufp)
1449 switch(gp->atomicstatus){
1450 default:
1451 runtime_printf("unexpected G.status %d (goroutine %p %D)\n", gp->atomicstatus, gp, gp->goid);
1452 runtime_throw("mark - bad status");
1453 case _Gdead:
1454 return;
1455 case _Grunning:
1456 runtime_throw("mark - world not stopped");
1457 case _Grunnable:
1458 case _Gsyscall:
1459 case _Gwaiting:
1460 break;
1463 #ifdef USING_SPLIT_STACK
1464 M *mp;
1465 void* sp;
1466 size_t spsize;
1467 void* next_segment;
1468 void* next_sp;
1469 void* initial_sp;
1471 if(gp == runtime_g()) {
1472 // Scanning our own stack.
1473 sp = __splitstack_find(nil, nil, &spsize, &next_segment,
1474 &next_sp, &initial_sp);
1475 } else if((mp = gp->m) != nil && mp->helpgc) {
1476 // gchelper's stack is in active use and has no interesting pointers.
1477 return;
1478 } else {
1479 // Scanning another goroutine's stack.
1480 // The goroutine is usually asleep (the world is stopped).
1482 // The exception is that if the goroutine is about to enter or might
1483 // have just exited a system call, it may be executing code such
1484 // as schedlock and may have needed to start a new stack segment.
1485 // Use the stack segment and stack pointer at the time of
1486 // the system call instead, since that won't change underfoot.
1487 if(gp->gcstack != nil) {
1488 sp = gp->gcstack;
1489 spsize = gp->gcstacksize;
1490 next_segment = gp->gcnextsegment;
1491 next_sp = gp->gcnextsp;
1492 initial_sp = gp->gcinitialsp;
1493 } else {
1494 sp = __splitstack_find_context(&gp->stackcontext[0],
1495 &spsize, &next_segment,
1496 &next_sp, &initial_sp);
1499 if(sp != nil) {
1500 enqueue1(wbufp, (Obj){sp, spsize, 0});
1501 while((sp = __splitstack_find(next_segment, next_sp,
1502 &spsize, &next_segment,
1503 &next_sp, &initial_sp)) != nil)
1504 enqueue1(wbufp, (Obj){sp, spsize, 0});
1506 #else
1507 M *mp;
1508 byte* bottom;
1509 byte* top;
1511 if(gp == runtime_g()) {
1512 // Scanning our own stack.
1513 bottom = (byte*)&gp;
1514 } else if((mp = gp->m) != nil && mp->helpgc) {
1515 // gchelper's stack is in active use and has no interesting pointers.
1516 return;
1517 } else {
1518 // Scanning another goroutine's stack.
1519 // The goroutine is usually asleep (the world is stopped).
1520 bottom = (byte*)gp->gcnextsp;
1521 if(bottom == nil)
1522 return;
1524 top = (byte*)gp->gcinitialsp + gp->gcstacksize;
1525 if(top > bottom)
1526 enqueue1(wbufp, (Obj){bottom, top - bottom, 0});
1527 else
1528 enqueue1(wbufp, (Obj){top, bottom - top, 0});
1529 #endif
1532 void
1533 runtime_queuefinalizer(void *p, FuncVal *fn, const FuncType *ft, const PtrType *ot)
1535 FinBlock *block;
1536 Finalizer *f;
1538 runtime_lock(&finlock);
1539 if(finq == nil || finq->cnt == finq->cap) {
1540 if(finc == nil) {
1541 finc = runtime_persistentalloc(FinBlockSize, 0, &mstats()->gc_sys);
1542 finc->cap = (FinBlockSize - sizeof(FinBlock)) / sizeof(Finalizer) + 1;
1543 finc->alllink = allfin;
1544 allfin = finc;
1546 block = finc;
1547 finc = block->next;
1548 block->next = finq;
1549 finq = block;
1551 f = &finq->fin[finq->cnt];
1552 finq->cnt++;
1553 f->fn = fn;
1554 f->ft = ft;
1555 f->ot = ot;
1556 f->arg = p;
1557 runtime_fingwake = true;
1558 runtime_unlock(&finlock);
1561 void
1562 runtime_iterate_finq(void (*callback)(FuncVal*, void*, const FuncType*, const PtrType*))
1564 FinBlock *fb;
1565 Finalizer *f;
1566 int32 i;
1568 for(fb = allfin; fb; fb = fb->alllink) {
1569 for(i = 0; i < fb->cnt; i++) {
1570 f = &fb->fin[i];
1571 callback(f->fn, f->arg, f->ft, f->ot);
1576 void
1577 runtime_MSpan_EnsureSwept(MSpan *s)
1579 M *m = runtime_m();
1580 G *g = runtime_g();
1581 uint32 sg;
1583 // Caller must disable preemption.
1584 // Otherwise when this function returns the span can become unswept again
1585 // (if GC is triggered on another goroutine).
1586 if(m->locks == 0 && m->mallocing == 0 && g != m->g0)
1587 runtime_throw("MSpan_EnsureSwept: m is not locked");
1589 sg = runtime_mheap.sweepgen;
1590 if(runtime_atomicload(&s->sweepgen) == sg)
1591 return;
1592 if(runtime_cas(&s->sweepgen, sg-2, sg-1)) {
1593 runtime_MSpan_Sweep(s);
1594 return;
1596 // unfortunate condition, and we don't have efficient means to wait
1597 while(runtime_atomicload(&s->sweepgen) != sg)
1598 runtime_osyield();
1601 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
1602 // It clears the mark bits in preparation for the next GC round.
1603 // Returns true if the span was returned to heap.
1604 bool
1605 runtime_MSpan_Sweep(MSpan *s)
1607 M *m;
1608 int32 cl, n, npages, nfree;
1609 uintptr size, off, *bitp, shift, bits;
1610 uint32 sweepgen;
1611 byte *p;
1612 MCache *c;
1613 byte *arena_start;
1614 MLink head, *end;
1615 byte *type_data;
1616 byte compression;
1617 uintptr type_data_inc;
1618 MLink *x;
1619 Special *special, **specialp, *y;
1620 bool res, sweepgenset;
1622 m = runtime_m();
1624 // It's critical that we enter this function with preemption disabled,
1625 // GC must not start while we are in the middle of this function.
1626 if(m->locks == 0 && m->mallocing == 0 && runtime_g() != m->g0)
1627 runtime_throw("MSpan_Sweep: m is not locked");
1628 sweepgen = runtime_mheap.sweepgen;
1629 if(s->state != MSpanInUse || s->sweepgen != sweepgen-1) {
1630 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1631 s->state, s->sweepgen, sweepgen);
1632 runtime_throw("MSpan_Sweep: bad span state");
1634 arena_start = runtime_mheap.arena_start;
1635 cl = s->sizeclass;
1636 size = s->elemsize;
1637 if(cl == 0) {
1638 n = 1;
1639 } else {
1640 // Chunk full of small blocks.
1641 npages = runtime_class_to_allocnpages[cl];
1642 n = (npages << PageShift) / size;
1644 res = false;
1645 nfree = 0;
1646 end = &head;
1647 c = m->mcache;
1648 sweepgenset = false;
1650 // mark any free objects in this span so we don't collect them
1651 for(x = s->freelist; x != nil; x = x->next) {
1652 // This is markonly(x) but faster because we don't need
1653 // atomic access and we're guaranteed to be pointing at
1654 // the head of a valid object.
1655 off = (uintptr*)x - (uintptr*)runtime_mheap.arena_start;
1656 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
1657 shift = off % wordsPerBitmapWord;
1658 *bitp |= bitMarked<<shift;
1661 // Unlink & free special records for any objects we're about to free.
1662 specialp = &s->specials;
1663 special = *specialp;
1664 while(special != nil) {
1665 // A finalizer can be set for an inner byte of an object, find object beginning.
1666 p = (byte*)(s->start << PageShift) + special->offset/size*size;
1667 off = (uintptr*)p - (uintptr*)arena_start;
1668 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1669 shift = off % wordsPerBitmapWord;
1670 bits = *bitp>>shift;
1671 if((bits & (bitAllocated|bitMarked)) == bitAllocated) {
1672 // Find the exact byte for which the special was setup
1673 // (as opposed to object beginning).
1674 p = (byte*)(s->start << PageShift) + special->offset;
1675 // about to free object: splice out special record
1676 y = special;
1677 special = special->next;
1678 *specialp = special;
1679 if(!runtime_freespecial(y, p, size, false)) {
1680 // stop freeing of object if it has a finalizer
1681 *bitp |= bitMarked << shift;
1683 } else {
1684 // object is still live: keep special record
1685 specialp = &special->next;
1686 special = *specialp;
1690 type_data = (byte*)s->types.data;
1691 type_data_inc = sizeof(uintptr);
1692 compression = s->types.compression;
1693 switch(compression) {
1694 case MTypes_Bytes:
1695 type_data += 8*sizeof(uintptr);
1696 type_data_inc = 1;
1697 break;
1700 // Sweep through n objects of given size starting at p.
1701 // This thread owns the span now, so it can manipulate
1702 // the block bitmap without atomic operations.
1703 p = (byte*)(s->start << PageShift);
1704 for(; n > 0; n--, p += size, type_data+=type_data_inc) {
1705 off = (uintptr*)p - (uintptr*)arena_start;
1706 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1707 shift = off % wordsPerBitmapWord;
1708 bits = *bitp>>shift;
1710 if((bits & bitAllocated) == 0)
1711 continue;
1713 if((bits & bitMarked) != 0) {
1714 *bitp &= ~(bitMarked<<shift);
1715 continue;
1718 if(runtime_debug.allocfreetrace)
1719 runtime_tracefree(p, size);
1721 // Clear mark and scan bits.
1722 *bitp &= ~((bitScan|bitMarked)<<shift);
1724 if(cl == 0) {
1725 // Free large span.
1726 runtime_unmarkspan(p, 1<<PageShift);
1727 s->needzero = 1;
1728 // important to set sweepgen before returning it to heap
1729 runtime_atomicstore(&s->sweepgen, sweepgen);
1730 sweepgenset = true;
1731 // See note about SysFault vs SysFree in malloc.goc.
1732 if(runtime_debug.efence)
1733 runtime_SysFault(p, size);
1734 else
1735 runtime_MHeap_Free(&runtime_mheap, s, 1);
1736 c->local_nlargefree++;
1737 c->local_largefree += size;
1738 runtime_xadd64(&mstats()->next_gc, -(uint64)(size * (gcpercent + 100)/100));
1739 res = true;
1740 } else {
1741 // Free small object.
1742 switch(compression) {
1743 case MTypes_Words:
1744 *(uintptr*)type_data = 0;
1745 break;
1746 case MTypes_Bytes:
1747 *(byte*)type_data = 0;
1748 break;
1750 if(size > 2*sizeof(uintptr))
1751 ((uintptr*)p)[1] = (uintptr)0xdeaddeaddeaddeadll; // mark as "needs to be zeroed"
1752 else if(size > sizeof(uintptr))
1753 ((uintptr*)p)[1] = 0;
1755 end->next = (MLink*)p;
1756 end = (MLink*)p;
1757 nfree++;
1761 // We need to set s->sweepgen = h->sweepgen only when all blocks are swept,
1762 // because of the potential for a concurrent free/SetFinalizer.
1763 // But we need to set it before we make the span available for allocation
1764 // (return it to heap or mcentral), because allocation code assumes that a
1765 // span is already swept if available for allocation.
1767 if(!sweepgenset && nfree == 0) {
1768 // The span must be in our exclusive ownership until we update sweepgen,
1769 // check for potential races.
1770 if(s->state != MSpanInUse || s->sweepgen != sweepgen-1) {
1771 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1772 s->state, s->sweepgen, sweepgen);
1773 runtime_throw("MSpan_Sweep: bad span state after sweep");
1775 runtime_atomicstore(&s->sweepgen, sweepgen);
1777 if(nfree > 0) {
1778 c->local_nsmallfree[cl] += nfree;
1779 c->local_cachealloc -= nfree * size;
1780 runtime_xadd64(&mstats()->next_gc, -(uint64)(nfree * size * (gcpercent + 100)/100));
1781 res = runtime_MCentral_FreeSpan(&runtime_mheap.central[cl], s, nfree, head.next, end);
1782 //MCentral_FreeSpan updates sweepgen
1784 return res;
1787 // State of background sweep.
1788 // Protected by gclock.
1789 static struct
1791 G* g;
1792 bool parked;
1794 MSpan** spans;
1795 uint32 nspan;
1796 uint32 spanidx;
1797 } sweep;
1799 // background sweeping goroutine
1800 static void
1801 bgsweep(void* dummy __attribute__ ((unused)))
1803 runtime_g()->issystem = 1;
1804 for(;;) {
1805 while(runtime_sweepone() != (uintptr)-1) {
1806 gcstats.nbgsweep++;
1807 runtime_gosched();
1809 runtime_lock(&gclock);
1810 if(!runtime_mheap.sweepdone) {
1811 // It's possible if GC has happened between sweepone has
1812 // returned -1 and gclock lock.
1813 runtime_unlock(&gclock);
1814 continue;
1816 sweep.parked = true;
1817 runtime_g()->isbackground = true;
1818 runtime_parkunlock(&gclock, "GC sweep wait");
1819 runtime_g()->isbackground = false;
1823 // sweeps one span
1824 // returns number of pages returned to heap, or -1 if there is nothing to sweep
1825 uintptr
1826 runtime_sweepone(void)
1828 M *m = runtime_m();
1829 MSpan *s;
1830 uint32 idx, sg;
1831 uintptr npages;
1833 // increment locks to ensure that the goroutine is not preempted
1834 // in the middle of sweep thus leaving the span in an inconsistent state for next GC
1835 m->locks++;
1836 sg = runtime_mheap.sweepgen;
1837 for(;;) {
1838 idx = runtime_xadd(&sweep.spanidx, 1) - 1;
1839 if(idx >= sweep.nspan) {
1840 runtime_mheap.sweepdone = true;
1841 m->locks--;
1842 return (uintptr)-1;
1844 s = sweep.spans[idx];
1845 if(s->state != MSpanInUse) {
1846 s->sweepgen = sg;
1847 continue;
1849 if(s->sweepgen != sg-2 || !runtime_cas(&s->sweepgen, sg-2, sg-1))
1850 continue;
1851 if(s->incache)
1852 runtime_throw("sweep of incache span");
1853 npages = s->npages;
1854 if(!runtime_MSpan_Sweep(s))
1855 npages = 0;
1856 m->locks--;
1857 return npages;
1861 static void
1862 dumpspan(uint32 idx)
1864 int32 sizeclass, n, npages, i, column;
1865 uintptr size;
1866 byte *p;
1867 byte *arena_start;
1868 MSpan *s;
1869 bool allocated;
1871 s = runtime_mheap.allspans[idx];
1872 if(s->state != MSpanInUse)
1873 return;
1874 arena_start = runtime_mheap.arena_start;
1875 p = (byte*)(s->start << PageShift);
1876 sizeclass = s->sizeclass;
1877 size = s->elemsize;
1878 if(sizeclass == 0) {
1879 n = 1;
1880 } else {
1881 npages = runtime_class_to_allocnpages[sizeclass];
1882 n = (npages << PageShift) / size;
1885 runtime_printf("%p .. %p:\n", p, p+n*size);
1886 column = 0;
1887 for(; n>0; n--, p+=size) {
1888 uintptr off, *bitp, shift, bits;
1890 off = (uintptr*)p - (uintptr*)arena_start;
1891 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1892 shift = off % wordsPerBitmapWord;
1893 bits = *bitp>>shift;
1895 allocated = ((bits & bitAllocated) != 0);
1897 for(i=0; (uint32)i<size; i+=sizeof(void*)) {
1898 if(column == 0) {
1899 runtime_printf("\t");
1901 if(i == 0) {
1902 runtime_printf(allocated ? "(" : "[");
1903 runtime_printf("%p: ", p+i);
1904 } else {
1905 runtime_printf(" ");
1908 runtime_printf("%p", *(void**)(p+i));
1910 if(i+sizeof(void*) >= size) {
1911 runtime_printf(allocated ? ") " : "] ");
1914 column++;
1915 if(column == 8) {
1916 runtime_printf("\n");
1917 column = 0;
1921 runtime_printf("\n");
1924 // A debugging function to dump the contents of memory
1925 void
1926 runtime_memorydump(void)
1928 uint32 spanidx;
1930 for(spanidx=0; spanidx<runtime_mheap.nspan; spanidx++) {
1931 dumpspan(spanidx);
1935 void
1936 runtime_gchelper(void)
1938 uint32 nproc;
1940 runtime_m()->traceback = 2;
1941 gchelperstart();
1943 // parallel mark for over gc roots
1944 runtime_parfordo(work.markfor);
1946 // help other threads scan secondary blocks
1947 scanblock(nil, true);
1949 bufferList[runtime_m()->helpgc].busy = 0;
1950 nproc = work.nproc; // work.nproc can change right after we increment work.ndone
1951 if(runtime_xadd(&work.ndone, +1) == nproc-1)
1952 runtime_notewakeup(&work.alldone);
1953 runtime_m()->traceback = 0;
1956 static void
1957 cachestats(void)
1959 MCache *c;
1960 P *p, **pp;
1962 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
1963 c = p->mcache;
1964 if(c==nil)
1965 continue;
1966 runtime_purgecachedstats(c);
1970 static void
1971 flushallmcaches(void)
1973 P *p, **pp;
1974 MCache *c;
1976 // Flush MCache's to MCentral.
1977 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
1978 c = p->mcache;
1979 if(c==nil)
1980 continue;
1981 runtime_MCache_ReleaseAll(c);
1985 void
1986 runtime_updatememstats(GCStats *stats)
1988 M *mp;
1989 MSpan *s;
1990 uint32 i;
1991 uint64 stacks_inuse, smallfree;
1992 uint64 *src, *dst;
1993 MStats *pmstats;
1995 if(stats)
1996 runtime_memclr((byte*)stats, sizeof(*stats));
1997 stacks_inuse = 0;
1998 for(mp=runtime_allm; mp; mp=mp->alllink) {
1999 //stacks_inuse += mp->stackinuse*FixedStack;
2000 if(stats) {
2001 src = (uint64*)&mp->gcstats;
2002 dst = (uint64*)stats;
2003 for(i=0; i<sizeof(*stats)/sizeof(uint64); i++)
2004 dst[i] += src[i];
2005 runtime_memclr((byte*)&mp->gcstats, sizeof(mp->gcstats));
2008 pmstats = mstats();
2009 pmstats->stacks_inuse = stacks_inuse;
2010 pmstats->mcache_inuse = runtime_mheap.cachealloc.inuse;
2011 pmstats->mspan_inuse = runtime_mheap.spanalloc.inuse;
2012 pmstats->sys = pmstats->heap_sys + pmstats->stacks_sys + pmstats->mspan_sys +
2013 pmstats->mcache_sys + pmstats->buckhash_sys + pmstats->gc_sys + pmstats->other_sys;
2015 // Calculate memory allocator stats.
2016 // During program execution we only count number of frees and amount of freed memory.
2017 // Current number of alive object in the heap and amount of alive heap memory
2018 // are calculated by scanning all spans.
2019 // Total number of mallocs is calculated as number of frees plus number of alive objects.
2020 // Similarly, total amount of allocated memory is calculated as amount of freed memory
2021 // plus amount of alive heap memory.
2022 pmstats->alloc = 0;
2023 pmstats->total_alloc = 0;
2024 pmstats->nmalloc = 0;
2025 pmstats->nfree = 0;
2026 for(i = 0; i < nelem(pmstats->by_size); i++) {
2027 pmstats->by_size[i].nmalloc = 0;
2028 pmstats->by_size[i].nfree = 0;
2031 // Flush MCache's to MCentral.
2032 flushallmcaches();
2034 // Aggregate local stats.
2035 cachestats();
2037 // Scan all spans and count number of alive objects.
2038 for(i = 0; i < runtime_mheap.nspan; i++) {
2039 s = runtime_mheap.allspans[i];
2040 if(s->state != MSpanInUse)
2041 continue;
2042 if(s->sizeclass == 0) {
2043 pmstats->nmalloc++;
2044 pmstats->alloc += s->elemsize;
2045 } else {
2046 pmstats->nmalloc += s->ref;
2047 pmstats->by_size[s->sizeclass].nmalloc += s->ref;
2048 pmstats->alloc += s->ref*s->elemsize;
2052 // Aggregate by size class.
2053 smallfree = 0;
2054 pmstats->nfree = runtime_mheap.nlargefree;
2055 for(i = 0; i < nelem(pmstats->by_size); i++) {
2056 pmstats->nfree += runtime_mheap.nsmallfree[i];
2057 pmstats->by_size[i].nfree = runtime_mheap.nsmallfree[i];
2058 pmstats->by_size[i].nmalloc += runtime_mheap.nsmallfree[i];
2059 smallfree += runtime_mheap.nsmallfree[i] * runtime_class_to_size[i];
2061 pmstats->nmalloc += pmstats->nfree;
2063 // Calculate derived stats.
2064 pmstats->total_alloc = pmstats->alloc + runtime_mheap.largefree + smallfree;
2065 pmstats->heap_alloc = pmstats->alloc;
2066 pmstats->heap_objects = pmstats->nmalloc - pmstats->nfree;
2069 // Structure of arguments passed to function gc().
2070 // This allows the arguments to be passed via runtime_mcall.
2071 struct gc_args
2073 int64 start_time; // start time of GC in ns (just before stoptheworld)
2074 bool eagersweep;
2077 static void gc(struct gc_args *args);
2078 static void mgc(G *gp);
2080 static int32
2081 readgogc(void)
2083 String s;
2084 const byte *p;
2086 s = runtime_getenv("GOGC");
2087 if(s.len == 0)
2088 return 100;
2089 p = s.str;
2090 if(s.len == 3 && runtime_strcmp((const char *)p, "off") == 0)
2091 return -1;
2092 return runtime_atoi(p, s.len);
2095 // force = 1 - do GC regardless of current heap usage
2096 // force = 2 - go GC and eager sweep
2097 void
2098 runtime_gc(int32 force)
2100 M *m;
2101 G *g;
2102 struct gc_args a;
2103 int32 i;
2104 MStats *pmstats;
2106 // The atomic operations are not atomic if the uint64s
2107 // are not aligned on uint64 boundaries. This has been
2108 // a problem in the past.
2109 if((((uintptr)&work.wempty) & 7) != 0)
2110 runtime_throw("runtime: gc work buffer is misaligned");
2111 if((((uintptr)&work.full) & 7) != 0)
2112 runtime_throw("runtime: gc work buffer is misaligned");
2114 // Make sure all registers are saved on stack so that
2115 // scanstack sees them.
2116 __builtin_unwind_init();
2118 // The gc is turned off (via enablegc) until
2119 // the bootstrap has completed.
2120 // Also, malloc gets called in the guts
2121 // of a number of libraries that might be
2122 // holding locks. To avoid priority inversion
2123 // problems, don't bother trying to run gc
2124 // while holding a lock. The next mallocgc
2125 // without a lock will do the gc instead.
2126 m = runtime_m();
2127 pmstats = mstats();
2128 if(!pmstats->enablegc || runtime_g() == m->g0 || m->locks > 0 || runtime_panicking || m->preemptoff.len > 0)
2129 return;
2131 if(gcpercent == GcpercentUnknown) { // first time through
2132 runtime_lock(&runtime_mheap);
2133 if(gcpercent == GcpercentUnknown)
2134 gcpercent = readgogc();
2135 runtime_unlock(&runtime_mheap);
2137 if(gcpercent < 0)
2138 return;
2140 runtime_acquireWorldsema();
2141 if(force==0 && pmstats->heap_alloc < pmstats->next_gc) {
2142 // typically threads which lost the race to grab
2143 // worldsema exit here when gc is done.
2144 runtime_releaseWorldsema();
2145 return;
2148 // Ok, we're doing it! Stop everybody else
2149 a.start_time = runtime_nanotime();
2150 a.eagersweep = force >= 2;
2151 m->gcing = 1;
2152 runtime_stopTheWorldWithSema();
2154 clearpools();
2156 // Run gc on the g0 stack. We do this so that the g stack
2157 // we're currently running on will no longer change. Cuts
2158 // the root set down a bit (g0 stacks are not scanned, and
2159 // we don't need to scan gc's internal state). Also an
2160 // enabler for copyable stacks.
2161 for(i = 0; i < (runtime_debug.gctrace > 1 ? 2 : 1); i++) {
2162 if(i > 0)
2163 a.start_time = runtime_nanotime();
2164 // switch to g0, call gc(&a), then switch back
2165 g = runtime_g();
2166 g->param = &a;
2167 g->atomicstatus = _Gwaiting;
2168 g->waitreason = runtime_gostringnocopy((const byte*)"garbage collection");
2169 runtime_mcall(mgc);
2170 m = runtime_m();
2173 // all done
2174 m->gcing = 0;
2175 m->locks++;
2176 runtime_releaseWorldsema();
2177 runtime_startTheWorldWithSema();
2178 m->locks--;
2180 // now that gc is done, kick off finalizer thread if needed
2181 if(!ConcurrentSweep) {
2182 // give the queued finalizers, if any, a chance to run
2183 runtime_gosched();
2184 } else {
2185 // For gccgo, let other goroutines run.
2186 runtime_gosched();
2190 static void
2191 mgc(G *gp)
2193 gc(gp->param);
2194 gp->param = nil;
2195 gp->atomicstatus = _Grunning;
2196 runtime_gogo(gp);
2199 static void
2200 gc(struct gc_args *args)
2202 M *m;
2203 int64 tm0, tm1, tm2, tm3, tm4;
2204 uint64 heap0, heap1, obj, ninstr;
2205 GCStats stats;
2206 uint32 i;
2207 MStats *pmstats;
2208 // Eface eface;
2210 m = runtime_m();
2212 if(runtime_debug.allocfreetrace)
2213 runtime_tracegc();
2215 m->traceback = 2;
2216 tm0 = args->start_time;
2217 work.tstart = args->start_time;
2219 if(CollectStats)
2220 runtime_memclr((byte*)&gcstats, sizeof(gcstats));
2222 m->locks++; // disable gc during mallocs in parforalloc
2223 if(work.markfor == nil)
2224 work.markfor = runtime_parforalloc(MaxGcproc);
2225 m->locks--;
2227 tm1 = 0;
2228 if(runtime_debug.gctrace)
2229 tm1 = runtime_nanotime();
2231 // Sweep what is not sweeped by bgsweep.
2232 while(runtime_sweepone() != (uintptr)-1)
2233 gcstats.npausesweep++;
2235 work.nwait = 0;
2236 work.ndone = 0;
2237 work.nproc = runtime_gcprocs();
2238 runtime_parforsetup(work.markfor, work.nproc, RootCount + runtime_allglen, false, &markroot_funcval);
2239 if(work.nproc > 1) {
2240 runtime_noteclear(&work.alldone);
2241 runtime_helpgc(work.nproc);
2244 tm2 = 0;
2245 if(runtime_debug.gctrace)
2246 tm2 = runtime_nanotime();
2248 gchelperstart();
2249 runtime_parfordo(work.markfor);
2250 scanblock(nil, true);
2252 tm3 = 0;
2253 if(runtime_debug.gctrace)
2254 tm3 = runtime_nanotime();
2256 bufferList[m->helpgc].busy = 0;
2257 if(work.nproc > 1)
2258 runtime_notesleep(&work.alldone);
2260 cachestats();
2261 // next_gc calculation is tricky with concurrent sweep since we don't know size of live heap
2262 // estimate what was live heap size after previous GC (for tracing only)
2263 pmstats = mstats();
2264 heap0 = pmstats->next_gc*100/(gcpercent+100);
2265 // conservatively set next_gc to high value assuming that everything is live
2266 // concurrent/lazy sweep will reduce this number while discovering new garbage
2267 pmstats->next_gc = pmstats->heap_alloc+(pmstats->heap_alloc-runtime_stacks_sys)*gcpercent/100;
2269 tm4 = runtime_nanotime();
2270 pmstats->last_gc = runtime_unixnanotime(); // must be Unix time to make sense to user
2271 pmstats->pause_ns[pmstats->numgc%nelem(pmstats->pause_ns)] = tm4 - tm0;
2272 pmstats->pause_end[pmstats->numgc%nelem(pmstats->pause_end)] = pmstats->last_gc;
2273 pmstats->pause_total_ns += tm4 - tm0;
2274 pmstats->numgc++;
2275 if(pmstats->debuggc)
2276 runtime_printf("pause %D\n", tm4-tm0);
2278 if(runtime_debug.gctrace) {
2279 heap1 = pmstats->heap_alloc;
2280 runtime_updatememstats(&stats);
2281 if(heap1 != pmstats->heap_alloc) {
2282 runtime_printf("runtime: mstats skew: heap=%D/%D\n", heap1, pmstats->heap_alloc);
2283 runtime_throw("mstats skew");
2285 obj = pmstats->nmalloc - pmstats->nfree;
2287 stats.nprocyield += work.markfor->nprocyield;
2288 stats.nosyield += work.markfor->nosyield;
2289 stats.nsleep += work.markfor->nsleep;
2291 runtime_printf("gc%d(%d): %D+%D+%D+%D us, %D -> %D MB, %D (%D-%D) objects,"
2292 " %d/%d/%d sweeps,"
2293 " %D(%D) handoff, %D(%D) steal, %D/%D/%D yields\n",
2294 pmstats->numgc, work.nproc, (tm1-tm0)/1000, (tm2-tm1)/1000, (tm3-tm2)/1000, (tm4-tm3)/1000,
2295 heap0>>20, heap1>>20, obj,
2296 pmstats->nmalloc, pmstats->nfree,
2297 sweep.nspan, gcstats.nbgsweep, gcstats.npausesweep,
2298 stats.nhandoff, stats.nhandoffcnt,
2299 work.markfor->nsteal, work.markfor->nstealcnt,
2300 stats.nprocyield, stats.nosyield, stats.nsleep);
2301 gcstats.nbgsweep = gcstats.npausesweep = 0;
2302 if(CollectStats) {
2303 runtime_printf("scan: %D bytes, %D objects, %D untyped, %D types from MSpan\n",
2304 gcstats.nbytes, gcstats.obj.cnt, gcstats.obj.notype, gcstats.obj.typelookup);
2305 if(gcstats.ptr.cnt != 0)
2306 runtime_printf("avg ptrbufsize: %D (%D/%D)\n",
2307 gcstats.ptr.sum/gcstats.ptr.cnt, gcstats.ptr.sum, gcstats.ptr.cnt);
2308 if(gcstats.obj.cnt != 0)
2309 runtime_printf("avg nobj: %D (%D/%D)\n",
2310 gcstats.obj.sum/gcstats.obj.cnt, gcstats.obj.sum, gcstats.obj.cnt);
2311 runtime_printf("rescans: %D, %D bytes\n", gcstats.rescan, gcstats.rescanbytes);
2313 runtime_printf("instruction counts:\n");
2314 ninstr = 0;
2315 for(i=0; i<nelem(gcstats.instr); i++) {
2316 runtime_printf("\t%d:\t%D\n", i, gcstats.instr[i]);
2317 ninstr += gcstats.instr[i];
2319 runtime_printf("\ttotal:\t%D\n", ninstr);
2321 runtime_printf("putempty: %D, getfull: %D\n", gcstats.putempty, gcstats.getfull);
2323 runtime_printf("markonly base lookup: bit %D word %D span %D\n", gcstats.markonly.foundbit, gcstats.markonly.foundword, gcstats.markonly.foundspan);
2324 runtime_printf("flushptrbuf base lookup: bit %D word %D span %D\n", gcstats.flushptrbuf.foundbit, gcstats.flushptrbuf.foundword, gcstats.flushptrbuf.foundspan);
2328 // We cache current runtime_mheap.allspans array in sweep.spans,
2329 // because the former can be resized and freed.
2330 // Otherwise we would need to take heap lock every time
2331 // we want to convert span index to span pointer.
2333 // Free the old cached array if necessary.
2334 if(sweep.spans && sweep.spans != runtime_mheap.allspans)
2335 runtime_SysFree(sweep.spans, sweep.nspan*sizeof(sweep.spans[0]), &pmstats->other_sys);
2336 // Cache the current array.
2337 runtime_mheap.sweepspans = runtime_mheap.allspans;
2338 runtime_mheap.sweepgen += 2;
2339 runtime_mheap.sweepdone = false;
2340 sweep.spans = runtime_mheap.allspans;
2341 sweep.nspan = runtime_mheap.nspan;
2342 sweep.spanidx = 0;
2344 // Temporary disable concurrent sweep, because we see failures on builders.
2345 if(ConcurrentSweep && !args->eagersweep) {
2346 runtime_lock(&gclock);
2347 if(sweep.g == nil)
2348 sweep.g = __go_go(bgsweep, nil);
2349 else if(sweep.parked) {
2350 sweep.parked = false;
2351 runtime_ready(sweep.g);
2353 runtime_unlock(&gclock);
2354 } else {
2355 // Sweep all spans eagerly.
2356 while(runtime_sweepone() != (uintptr)-1)
2357 gcstats.npausesweep++;
2358 // Do an additional mProf_GC, because all 'free' events are now real as well.
2359 runtime_MProf_GC();
2362 runtime_MProf_GC();
2363 m->traceback = 0;
2366 void runtime_debug_readGCStats(Slice*)
2367 __asm__("runtime_debug.readGCStats");
2369 void
2370 runtime_debug_readGCStats(Slice *pauses)
2372 uint64 *p;
2373 uint32 i, n;
2374 MStats *pmstats;
2376 // Calling code in runtime/debug should make the slice large enough.
2377 pmstats = mstats();
2378 if((size_t)pauses->cap < nelem(pmstats->pause_ns)+3)
2379 runtime_throw("runtime: short slice passed to readGCStats");
2381 // Pass back: pauses, last gc (absolute time), number of gc, total pause ns.
2382 p = (uint64*)pauses->array;
2383 runtime_lock(&runtime_mheap);
2384 n = pmstats->numgc;
2385 if(n > nelem(pmstats->pause_ns))
2386 n = nelem(pmstats->pause_ns);
2388 // The pause buffer is circular. The most recent pause is at
2389 // pause_ns[(numgc-1)%nelem(pause_ns)], and then backward
2390 // from there to go back farther in time. We deliver the times
2391 // most recent first (in p[0]).
2392 for(i=0; i<n; i++) {
2393 p[i] = pmstats->pause_ns[(pmstats->numgc-1-i)%nelem(pmstats->pause_ns)];
2394 p[n+i] = pmstats->pause_end[(pmstats->numgc-1-i)%nelem(pmstats->pause_ns)];
2397 p[n+n] = pmstats->last_gc;
2398 p[n+n+1] = pmstats->numgc;
2399 p[n+n+2] = pmstats->pause_total_ns;
2400 runtime_unlock(&runtime_mheap);
2401 pauses->__count = n+n+3;
2404 int32
2405 runtime_setgcpercent(int32 in) {
2406 int32 out;
2408 runtime_lock(&runtime_mheap);
2409 if(gcpercent == GcpercentUnknown)
2410 gcpercent = readgogc();
2411 out = gcpercent;
2412 if(in < 0)
2413 in = -1;
2414 gcpercent = in;
2415 runtime_unlock(&runtime_mheap);
2416 return out;
2419 static void
2420 gchelperstart(void)
2422 M *m;
2424 m = runtime_m();
2425 if(m->helpgc < 0 || m->helpgc >= MaxGcproc)
2426 runtime_throw("gchelperstart: bad m->helpgc");
2427 if(runtime_xchg(&bufferList[m->helpgc].busy, 1))
2428 runtime_throw("gchelperstart: already busy");
2429 if(runtime_g() != m->g0)
2430 runtime_throw("gchelper not running on g0 stack");
2433 static void
2434 runfinq(void* dummy __attribute__ ((unused)))
2436 Finalizer *f;
2437 FinBlock *fb, *next;
2438 uint32 i;
2439 Eface ef;
2440 Iface iface;
2442 // This function blocks for long periods of time, and because it is written in C
2443 // we have no liveness information. Zero everything so that uninitialized pointers
2444 // do not cause memory leaks.
2445 f = nil;
2446 fb = nil;
2447 next = nil;
2448 i = 0;
2449 ef._type = nil;
2450 ef.data = nil;
2452 // force flush to memory
2453 USED(&f);
2454 USED(&fb);
2455 USED(&next);
2456 USED(&i);
2457 USED(&ef);
2459 for(;;) {
2460 runtime_lock(&finlock);
2461 fb = finq;
2462 finq = nil;
2463 if(fb == nil) {
2464 runtime_fingwait = true;
2465 runtime_g()->isbackground = true;
2466 runtime_parkunlock(&finlock, "finalizer wait");
2467 runtime_g()->isbackground = false;
2468 continue;
2470 runtime_unlock(&finlock);
2471 for(; fb; fb=next) {
2472 next = fb->next;
2473 for(i=0; i<(uint32)fb->cnt; i++) {
2474 const Type *fint;
2475 void *param;
2477 f = &fb->fin[i];
2478 fint = ((const Type**)f->ft->__in.array)[0];
2479 if((fint->__code & kindMask) == kindPtr) {
2480 // direct use of pointer
2481 param = &f->arg;
2482 } else if(((const InterfaceType*)fint)->__methods.__count == 0) {
2483 // convert to empty interface
2484 // using memcpy as const_cast.
2485 memcpy(&ef._type, &f->ot,
2486 sizeof ef._type);
2487 ef.data = f->arg;
2488 param = &ef;
2489 } else {
2490 // convert to interface with methods
2491 iface.tab = getitab(fint,
2492 (const Type*)f->ot,
2493 true);
2494 iface.data = f->arg;
2495 if(iface.data == nil)
2496 runtime_throw("invalid type conversion in runfinq");
2497 param = &iface;
2499 reflect_call(f->ft, f->fn, 0, 0, &param, nil);
2500 f->fn = nil;
2501 f->arg = nil;
2502 f->ot = nil;
2504 fb->cnt = 0;
2505 runtime_lock(&finlock);
2506 fb->next = finc;
2507 finc = fb;
2508 runtime_unlock(&finlock);
2511 // Zero everything that's dead, to avoid memory leaks.
2512 // See comment at top of function.
2513 f = nil;
2514 fb = nil;
2515 next = nil;
2516 i = 0;
2517 ef._type = nil;
2518 ef.data = nil;
2519 runtime_gc(1); // trigger another gc to clean up the finalized objects, if possible
2523 void
2524 runtime_createfing(void)
2526 if(fing != nil)
2527 return;
2528 // Here we use gclock instead of finlock,
2529 // because newproc1 can allocate, which can cause on-demand span sweep,
2530 // which can queue finalizers, which would deadlock.
2531 runtime_lock(&gclock);
2532 if(fing == nil)
2533 fing = __go_go(runfinq, nil);
2534 runtime_unlock(&gclock);
2538 runtime_wakefing(void)
2540 G *res;
2542 res = nil;
2543 runtime_lock(&finlock);
2544 if(runtime_fingwait && runtime_fingwake) {
2545 runtime_fingwait = false;
2546 runtime_fingwake = false;
2547 res = fing;
2549 runtime_unlock(&finlock);
2550 return res;
2553 void
2554 runtime_marknogc(void *v)
2556 uintptr *b, off, shift;
2558 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2559 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2560 shift = off % wordsPerBitmapWord;
2561 *b = (*b & ~(bitAllocated<<shift)) | bitBlockBoundary<<shift;
2564 void
2565 runtime_markscan(void *v)
2567 uintptr *b, off, shift;
2569 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2570 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2571 shift = off % wordsPerBitmapWord;
2572 *b |= bitScan<<shift;
2575 // mark the block at v as freed.
2576 void
2577 runtime_markfreed(void *v)
2579 uintptr *b, off, shift;
2581 if(0)
2582 runtime_printf("markfreed %p\n", v);
2584 if((byte*)v > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2585 runtime_throw("markfreed: bad pointer");
2587 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2588 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2589 shift = off % wordsPerBitmapWord;
2590 *b = (*b & ~(bitMask<<shift)) | (bitAllocated<<shift);
2593 // check that the block at v of size n is marked freed.
2594 void
2595 runtime_checkfreed(void *v, uintptr n)
2597 uintptr *b, bits, off, shift;
2599 if(!runtime_checking)
2600 return;
2602 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2603 return; // not allocated, so okay
2605 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2606 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2607 shift = off % wordsPerBitmapWord;
2609 bits = *b>>shift;
2610 if((bits & bitAllocated) != 0) {
2611 runtime_printf("checkfreed %p+%p: off=%p have=%p\n",
2612 v, n, off, bits & bitMask);
2613 runtime_throw("checkfreed: not freed");
2617 // mark the span of memory at v as having n blocks of the given size.
2618 // if leftover is true, there is left over space at the end of the span.
2619 void
2620 runtime_markspan(void *v, uintptr size, uintptr n, bool leftover)
2622 uintptr *b, *b0, off, shift, i, x;
2623 byte *p;
2625 if((byte*)v+size*n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2626 runtime_throw("markspan: bad pointer");
2628 if(runtime_checking) {
2629 // bits should be all zero at the start
2630 off = (byte*)v + size - runtime_mheap.arena_start;
2631 b = (uintptr*)(runtime_mheap.arena_start - off/wordsPerBitmapWord);
2632 for(i = 0; i < size/PtrSize/wordsPerBitmapWord; i++) {
2633 if(b[i] != 0)
2634 runtime_throw("markspan: span bits not zero");
2638 p = v;
2639 if(leftover) // mark a boundary just past end of last block too
2640 n++;
2642 b0 = nil;
2643 x = 0;
2644 for(; n-- > 0; p += size) {
2645 // Okay to use non-atomic ops here, because we control
2646 // the entire span, and each bitmap word has bits for only
2647 // one span, so no other goroutines are changing these
2648 // bitmap words.
2649 off = (uintptr*)p - (uintptr*)runtime_mheap.arena_start; // word offset
2650 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2651 shift = off % wordsPerBitmapWord;
2652 if(b0 != b) {
2653 if(b0 != nil)
2654 *b0 = x;
2655 b0 = b;
2656 x = 0;
2658 x |= bitAllocated<<shift;
2660 *b0 = x;
2663 // unmark the span of memory at v of length n bytes.
2664 void
2665 runtime_unmarkspan(void *v, uintptr n)
2667 uintptr *p, *b, off;
2669 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2670 runtime_throw("markspan: bad pointer");
2672 p = v;
2673 off = p - (uintptr*)runtime_mheap.arena_start; // word offset
2674 if(off % wordsPerBitmapWord != 0)
2675 runtime_throw("markspan: unaligned pointer");
2676 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2677 n /= PtrSize;
2678 if(n%wordsPerBitmapWord != 0)
2679 runtime_throw("unmarkspan: unaligned length");
2680 // Okay to use non-atomic ops here, because we control
2681 // the entire span, and each bitmap word has bits for only
2682 // one span, so no other goroutines are changing these
2683 // bitmap words.
2684 n /= wordsPerBitmapWord;
2685 while(n-- > 0)
2686 *b-- = 0;
2689 void
2690 runtime_MHeap_MapBits(MHeap *h)
2692 size_t page_size;
2694 // Caller has added extra mappings to the arena.
2695 // Add extra mappings of bitmap words as needed.
2696 // We allocate extra bitmap pieces in chunks of bitmapChunk.
2697 enum {
2698 bitmapChunk = 8192
2700 uintptr n;
2702 n = (h->arena_used - h->arena_start) / wordsPerBitmapWord;
2703 n = ROUND(n, bitmapChunk);
2704 n = ROUND(n, PageSize);
2705 page_size = getpagesize();
2706 n = ROUND(n, page_size);
2707 if(h->bitmap_mapped >= n)
2708 return;
2710 runtime_SysMap(h->arena_start - n, n - h->bitmap_mapped, h->arena_reserved, &mstats()->gc_sys);
2711 h->bitmap_mapped = n;
2714 // typedmemmove copies a value of type t to dst from src.
2716 extern void typedmemmove(const Type* td, void *dst, const void *src)
2717 __asm__ (GOSYM_PREFIX "reflect.typedmemmove");
2719 void
2720 typedmemmove(const Type* td, void *dst, const void *src)
2722 runtime_memmove(dst, src, td->__size);
2725 // typedslicecopy copies a slice of elemType values from src to dst,
2726 // returning the number of elements copied.
2728 extern intgo typedslicecopy(const Type* elem, Slice dst, Slice src)
2729 __asm__ (GOSYM_PREFIX "reflect.typedslicecopy");
2731 intgo
2732 typedslicecopy(const Type* elem, Slice dst, Slice src)
2734 intgo n;
2735 void *dstp;
2736 void *srcp;
2738 n = dst.__count;
2739 if (n > src.__count)
2740 n = src.__count;
2741 if (n == 0)
2742 return 0;
2743 dstp = dst.__values;
2744 srcp = src.__values;
2745 memmove(dstp, srcp, (uintptr_t)n * elem->__size);
2746 return n;