Merged revisions 208012,208018-208019,208021,208023-208030,208033,208037,208040-20804...
[official-gcc.git] / main / libgo / runtime / mgc0.c
blobf963686e31359f8fa074b66e6b859d059d3f0d7d
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.
7 #include <unistd.h>
9 #include "runtime.h"
10 #include "arch.h"
11 #include "malloc.h"
12 #include "mgc0.h"
13 #include "race.h"
14 #include "go-type.h"
16 // Map gccgo field names to gc field names.
17 // Slice aka __go_open_array.
18 #define array __values
19 #define cap __capacity
20 // Iface aka __go_interface
21 #define tab __methods
22 // Eface aka __go_empty_interface.
23 #define type __type_descriptor
24 // Hmap aka __go_map
25 typedef struct __go_map Hmap;
26 // Type aka __go_type_descriptor
27 #define kind __code
28 #define string __reflection
29 #define KindPtr GO_PTR
30 #define KindNoPointers GO_NO_POINTERS
31 // PtrType aka __go_ptr_type
32 #define elem __element_type
34 #ifdef USING_SPLIT_STACK
36 extern void * __splitstack_find (void *, void *, size_t *, void **, void **,
37 void **);
39 extern void * __splitstack_find_context (void *context[10], size_t *, void **,
40 void **, void **);
42 #endif
44 enum {
45 Debug = 0,
46 DebugMark = 0, // run second pass to check mark
47 CollectStats = 0,
48 ScanStackByFrames = 0,
49 IgnorePreciseGC = 0,
51 // Four bits per word (see #defines below).
52 wordsPerBitmapWord = sizeof(void*)*8/4,
53 bitShift = sizeof(void*)*8/4,
55 handoffThreshold = 4,
56 IntermediateBufferCapacity = 64,
58 // Bits in type information
59 PRECISE = 1,
60 LOOP = 2,
61 PC_BITS = PRECISE | LOOP,
63 // Pointer map
64 BitsPerPointer = 2,
65 BitsNoPointer = 0,
66 BitsPointer = 1,
67 BitsIface = 2,
68 BitsEface = 3,
71 // Bits in per-word bitmap.
72 // #defines because enum might not be able to hold the values.
74 // Each word in the bitmap describes wordsPerBitmapWord words
75 // of heap memory. There are 4 bitmap bits dedicated to each heap word,
76 // so on a 64-bit system there is one bitmap word per 16 heap words.
77 // The bits in the word are packed together by type first, then by
78 // heap location, so each 64-bit bitmap word consists of, from top to bottom,
79 // the 16 bitSpecial bits for the corresponding heap words, then the 16 bitMarked bits,
80 // then the 16 bitNoScan/bitBlockBoundary bits, then the 16 bitAllocated bits.
81 // This layout makes it easier to iterate over the bits of a given type.
83 // The bitmap starts at mheap.arena_start and extends *backward* from
84 // there. On a 64-bit system the off'th word in the arena is tracked by
85 // the off/16+1'th word before mheap.arena_start. (On a 32-bit system,
86 // the only difference is that the divisor is 8.)
88 // To pull out the bits corresponding to a given pointer p, we use:
90 // off = p - (uintptr*)mheap.arena_start; // word offset
91 // b = (uintptr*)mheap.arena_start - off/wordsPerBitmapWord - 1;
92 // shift = off % wordsPerBitmapWord
93 // bits = *b >> shift;
94 // /* then test bits & bitAllocated, bits & bitMarked, etc. */
96 #define bitAllocated ((uintptr)1<<(bitShift*0))
97 #define bitNoScan ((uintptr)1<<(bitShift*1)) /* when bitAllocated is set */
98 #define bitMarked ((uintptr)1<<(bitShift*2)) /* when bitAllocated is set */
99 #define bitSpecial ((uintptr)1<<(bitShift*3)) /* when bitAllocated is set - has finalizer or being profiled */
100 #define bitBlockBoundary ((uintptr)1<<(bitShift*1)) /* when bitAllocated is NOT set */
102 #define bitMask (bitBlockBoundary | bitAllocated | bitMarked | bitSpecial)
104 // Holding worldsema grants an M the right to try to stop the world.
105 // The procedure is:
107 // runtime_semacquire(&runtime_worldsema);
108 // m->gcing = 1;
109 // runtime_stoptheworld();
111 // ... do stuff ...
113 // m->gcing = 0;
114 // runtime_semrelease(&runtime_worldsema);
115 // runtime_starttheworld();
117 uint32 runtime_worldsema = 1;
119 // The size of Workbuf is N*PageSize.
120 typedef struct Workbuf Workbuf;
121 struct Workbuf
123 #define SIZE (2*PageSize-sizeof(LFNode)-sizeof(uintptr))
124 LFNode node; // must be first
125 uintptr nobj;
126 Obj obj[SIZE/sizeof(Obj) - 1];
127 uint8 _padding[SIZE%sizeof(Obj) + sizeof(Obj)];
128 #undef SIZE
131 typedef struct Finalizer Finalizer;
132 struct Finalizer
134 FuncVal *fn;
135 void *arg;
136 const struct __go_func_type *ft;
137 const struct __go_ptr_type *ot;
140 typedef struct FinBlock FinBlock;
141 struct FinBlock
143 FinBlock *alllink;
144 FinBlock *next;
145 int32 cnt;
146 int32 cap;
147 Finalizer fin[1];
150 static G *fing;
151 static FinBlock *finq; // list of finalizers that are to be executed
152 static FinBlock *finc; // cache of free blocks
153 static FinBlock *allfin; // list of all blocks
154 static Lock finlock;
155 static int32 fingwait;
157 static void runfinq(void*);
158 static Workbuf* getempty(Workbuf*);
159 static Workbuf* getfull(Workbuf*);
160 static void putempty(Workbuf*);
161 static Workbuf* handoff(Workbuf*);
162 static void gchelperstart(void);
164 static struct {
165 uint64 full; // lock-free list of full blocks
166 uint64 empty; // lock-free list of empty blocks
167 byte pad0[CacheLineSize]; // prevents false-sharing between full/empty and nproc/nwait
168 uint32 nproc;
169 volatile uint32 nwait;
170 volatile uint32 ndone;
171 volatile uint32 debugmarkdone;
172 Note alldone;
173 ParFor *markfor;
174 ParFor *sweepfor;
176 Lock;
177 byte *chunk;
178 uintptr nchunk;
180 Obj *roots;
181 uint32 nroot;
182 uint32 rootcap;
183 } work __attribute__((aligned(8)));
185 enum {
186 GC_DEFAULT_PTR = GC_NUM_INSTR,
187 GC_CHAN,
189 GC_NUM_INSTR2
192 static struct {
193 struct {
194 uint64 sum;
195 uint64 cnt;
196 } ptr;
197 uint64 nbytes;
198 struct {
199 uint64 sum;
200 uint64 cnt;
201 uint64 notype;
202 uint64 typelookup;
203 } obj;
204 uint64 rescan;
205 uint64 rescanbytes;
206 uint64 instr[GC_NUM_INSTR2];
207 uint64 putempty;
208 uint64 getfull;
209 struct {
210 uint64 foundbit;
211 uint64 foundword;
212 uint64 foundspan;
213 } flushptrbuf;
214 struct {
215 uint64 foundbit;
216 uint64 foundword;
217 uint64 foundspan;
218 } markonly;
219 } gcstats;
221 // markonly marks an object. It returns true if the object
222 // has been marked by this function, false otherwise.
223 // This function doesn't append the object to any buffer.
224 static bool
225 markonly(void *obj)
227 byte *p;
228 uintptr *bitp, bits, shift, x, xbits, off, j;
229 MSpan *s;
230 PageID k;
232 // Words outside the arena cannot be pointers.
233 if((byte*)obj < runtime_mheap.arena_start || (byte*)obj >= runtime_mheap.arena_used)
234 return false;
236 // obj may be a pointer to a live object.
237 // Try to find the beginning of the object.
239 // Round down to word boundary.
240 obj = (void*)((uintptr)obj & ~((uintptr)PtrSize-1));
242 // Find bits for this word.
243 off = (uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
244 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
245 shift = off % wordsPerBitmapWord;
246 xbits = *bitp;
247 bits = xbits >> shift;
249 // Pointing at the beginning of a block?
250 if((bits & (bitAllocated|bitBlockBoundary)) != 0) {
251 if(CollectStats)
252 runtime_xadd64(&gcstats.markonly.foundbit, 1);
253 goto found;
256 // Pointing just past the beginning?
257 // Scan backward a little to find a block boundary.
258 for(j=shift; j-->0; ) {
259 if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
260 shift = j;
261 bits = xbits>>shift;
262 if(CollectStats)
263 runtime_xadd64(&gcstats.markonly.foundword, 1);
264 goto found;
268 // Otherwise consult span table to find beginning.
269 // (Manually inlined copy of MHeap_LookupMaybe.)
270 k = (uintptr)obj>>PageShift;
271 x = k;
272 x -= (uintptr)runtime_mheap.arena_start>>PageShift;
273 s = runtime_mheap.spans[x];
274 if(s == nil || k < s->start || (byte*)obj >= s->limit || s->state != MSpanInUse)
275 return false;
276 p = (byte*)((uintptr)s->start<<PageShift);
277 if(s->sizeclass == 0) {
278 obj = p;
279 } else {
280 uintptr size = s->elemsize;
281 int32 i = ((byte*)obj - p)/size;
282 obj = p+i*size;
285 // Now that we know the object header, reload bits.
286 off = (uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
287 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
288 shift = off % wordsPerBitmapWord;
289 xbits = *bitp;
290 bits = xbits >> shift;
291 if(CollectStats)
292 runtime_xadd64(&gcstats.markonly.foundspan, 1);
294 found:
295 // Now we have bits, bitp, and shift correct for
296 // obj pointing at the base of the object.
297 // Only care about allocated and not marked.
298 if((bits & (bitAllocated|bitMarked)) != bitAllocated)
299 return false;
300 if(work.nproc == 1)
301 *bitp |= bitMarked<<shift;
302 else {
303 for(;;) {
304 x = *bitp;
305 if(x & (bitMarked<<shift))
306 return false;
307 if(runtime_casp((void**)bitp, (void*)x, (void*)(x|(bitMarked<<shift))))
308 break;
312 // The object is now marked
313 return true;
316 // PtrTarget is a structure used by intermediate buffers.
317 // The intermediate buffers hold GC data before it
318 // is moved/flushed to the work buffer (Workbuf).
319 // The size of an intermediate buffer is very small,
320 // such as 32 or 64 elements.
321 typedef struct PtrTarget PtrTarget;
322 struct PtrTarget
324 void *p;
325 uintptr ti;
328 typedef struct BufferList BufferList;
329 struct BufferList
331 PtrTarget ptrtarget[IntermediateBufferCapacity];
332 Obj obj[IntermediateBufferCapacity];
333 uint32 busy;
334 byte pad[CacheLineSize];
336 static BufferList bufferList[MaxGcproc];
338 static Type *itabtype;
340 static void enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj);
342 // flushptrbuf moves data from the PtrTarget buffer to the work buffer.
343 // The PtrTarget buffer contains blocks irrespective of whether the blocks have been marked or scanned,
344 // while the work buffer contains blocks which have been marked
345 // and are prepared to be scanned by the garbage collector.
347 // _wp, _wbuf, _nobj are input/output parameters and are specifying the work buffer.
349 // A simplified drawing explaining how the todo-list moves from a structure to another:
351 // scanblock
352 // (find pointers)
353 // Obj ------> PtrTarget (pointer targets)
354 // ↑ |
355 // | |
356 // `----------'
357 // flushptrbuf
358 // (find block start, mark and enqueue)
359 static void
360 flushptrbuf(PtrTarget *ptrbuf, PtrTarget **ptrbufpos, Obj **_wp, Workbuf **_wbuf, uintptr *_nobj)
362 byte *p, *arena_start, *obj;
363 uintptr size, *bitp, bits, shift, j, x, xbits, off, nobj, ti, n;
364 MSpan *s;
365 PageID k;
366 Obj *wp;
367 Workbuf *wbuf;
368 PtrTarget *ptrbuf_end;
370 arena_start = runtime_mheap.arena_start;
372 wp = *_wp;
373 wbuf = *_wbuf;
374 nobj = *_nobj;
376 ptrbuf_end = *ptrbufpos;
377 n = ptrbuf_end - ptrbuf;
378 *ptrbufpos = ptrbuf;
380 if(CollectStats) {
381 runtime_xadd64(&gcstats.ptr.sum, n);
382 runtime_xadd64(&gcstats.ptr.cnt, 1);
385 // If buffer is nearly full, get a new one.
386 if(wbuf == nil || nobj+n >= nelem(wbuf->obj)) {
387 if(wbuf != nil)
388 wbuf->nobj = nobj;
389 wbuf = getempty(wbuf);
390 wp = wbuf->obj;
391 nobj = 0;
393 if(n >= nelem(wbuf->obj))
394 runtime_throw("ptrbuf has to be smaller than WorkBuf");
397 // TODO(atom): This block is a branch of an if-then-else statement.
398 // The single-threaded branch may be added in a next CL.
400 // Multi-threaded version.
402 while(ptrbuf < ptrbuf_end) {
403 obj = ptrbuf->p;
404 ti = ptrbuf->ti;
405 ptrbuf++;
407 // obj belongs to interval [mheap.arena_start, mheap.arena_used).
408 if(Debug > 1) {
409 if(obj < runtime_mheap.arena_start || obj >= runtime_mheap.arena_used)
410 runtime_throw("object is outside of mheap");
413 // obj may be a pointer to a live object.
414 // Try to find the beginning of the object.
416 // Round down to word boundary.
417 if(((uintptr)obj & ((uintptr)PtrSize-1)) != 0) {
418 obj = (void*)((uintptr)obj & ~((uintptr)PtrSize-1));
419 ti = 0;
422 // Find bits for this word.
423 off = (uintptr*)obj - (uintptr*)arena_start;
424 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
425 shift = off % wordsPerBitmapWord;
426 xbits = *bitp;
427 bits = xbits >> shift;
429 // Pointing at the beginning of a block?
430 if((bits & (bitAllocated|bitBlockBoundary)) != 0) {
431 if(CollectStats)
432 runtime_xadd64(&gcstats.flushptrbuf.foundbit, 1);
433 goto found;
436 ti = 0;
438 // Pointing just past the beginning?
439 // Scan backward a little to find a block boundary.
440 for(j=shift; j-->0; ) {
441 if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
442 obj = (byte*)obj - (shift-j)*PtrSize;
443 shift = j;
444 bits = xbits>>shift;
445 if(CollectStats)
446 runtime_xadd64(&gcstats.flushptrbuf.foundword, 1);
447 goto found;
451 // Otherwise consult span table to find beginning.
452 // (Manually inlined copy of MHeap_LookupMaybe.)
453 k = (uintptr)obj>>PageShift;
454 x = k;
455 x -= (uintptr)arena_start>>PageShift;
456 s = runtime_mheap.spans[x];
457 if(s == nil || k < s->start || obj >= s->limit || s->state != MSpanInUse)
458 continue;
459 p = (byte*)((uintptr)s->start<<PageShift);
460 if(s->sizeclass == 0) {
461 obj = p;
462 } else {
463 size = s->elemsize;
464 int32 i = ((byte*)obj - p)/size;
465 obj = p+i*size;
468 // Now that we know the object header, reload bits.
469 off = (uintptr*)obj - (uintptr*)arena_start;
470 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
471 shift = off % wordsPerBitmapWord;
472 xbits = *bitp;
473 bits = xbits >> shift;
474 if(CollectStats)
475 runtime_xadd64(&gcstats.flushptrbuf.foundspan, 1);
477 found:
478 // Now we have bits, bitp, and shift correct for
479 // obj pointing at the base of the object.
480 // Only care about allocated and not marked.
481 if((bits & (bitAllocated|bitMarked)) != bitAllocated)
482 continue;
483 if(work.nproc == 1)
484 *bitp |= bitMarked<<shift;
485 else {
486 for(;;) {
487 x = *bitp;
488 if(x & (bitMarked<<shift))
489 goto continue_obj;
490 if(runtime_casp((void**)bitp, (void*)x, (void*)(x|(bitMarked<<shift))))
491 break;
495 // If object has no pointers, don't need to scan further.
496 if((bits & bitNoScan) != 0)
497 continue;
499 // Ask span about size class.
500 // (Manually inlined copy of MHeap_Lookup.)
501 x = (uintptr)obj >> PageShift;
502 x -= (uintptr)arena_start>>PageShift;
503 s = runtime_mheap.spans[x];
505 PREFETCH(obj);
507 *wp = (Obj){obj, s->elemsize, ti};
508 wp++;
509 nobj++;
510 continue_obj:;
513 // If another proc wants a pointer, give it some.
514 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
515 wbuf->nobj = nobj;
516 wbuf = handoff(wbuf);
517 nobj = wbuf->nobj;
518 wp = wbuf->obj + nobj;
522 *_wp = wp;
523 *_wbuf = wbuf;
524 *_nobj = nobj;
527 static void
528 flushobjbuf(Obj *objbuf, Obj **objbufpos, Obj **_wp, Workbuf **_wbuf, uintptr *_nobj)
530 uintptr nobj, off;
531 Obj *wp, obj;
532 Workbuf *wbuf;
533 Obj *objbuf_end;
535 wp = *_wp;
536 wbuf = *_wbuf;
537 nobj = *_nobj;
539 objbuf_end = *objbufpos;
540 *objbufpos = objbuf;
542 while(objbuf < objbuf_end) {
543 obj = *objbuf++;
545 // Align obj.b to a word boundary.
546 off = (uintptr)obj.p & (PtrSize-1);
547 if(off != 0) {
548 obj.p += PtrSize - off;
549 obj.n -= PtrSize - off;
550 obj.ti = 0;
553 if(obj.p == nil || obj.n == 0)
554 continue;
556 // If buffer is full, get a new one.
557 if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
558 if(wbuf != nil)
559 wbuf->nobj = nobj;
560 wbuf = getempty(wbuf);
561 wp = wbuf->obj;
562 nobj = 0;
565 *wp = obj;
566 wp++;
567 nobj++;
570 // If another proc wants a pointer, give it some.
571 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
572 wbuf->nobj = nobj;
573 wbuf = handoff(wbuf);
574 nobj = wbuf->nobj;
575 wp = wbuf->obj + nobj;
578 *_wp = wp;
579 *_wbuf = wbuf;
580 *_nobj = nobj;
583 // Program that scans the whole block and treats every block element as a potential pointer
584 static uintptr defaultProg[2] = {PtrSize, GC_DEFAULT_PTR};
586 #if 0
587 // Hchan program
588 static uintptr chanProg[2] = {0, GC_CHAN};
589 #endif
591 // Local variables of a program fragment or loop
592 typedef struct Frame Frame;
593 struct Frame {
594 uintptr count, elemsize, b;
595 uintptr *loop_or_ret;
598 // Sanity check for the derived type info objti.
599 static void
600 checkptr(void *obj, uintptr objti)
602 uintptr type, tisize, i, x;
603 byte *objstart;
604 Type *t;
605 MSpan *s;
607 if(!Debug)
608 runtime_throw("checkptr is debug only");
610 if((byte*)obj < runtime_mheap.arena_start || (byte*)obj >= runtime_mheap.arena_used)
611 return;
612 type = runtime_gettype(obj);
613 t = (Type*)(type & ~(uintptr)(PtrSize-1));
614 if(t == nil)
615 return;
616 x = (uintptr)obj >> PageShift;
617 x -= (uintptr)(runtime_mheap.arena_start)>>PageShift;
618 s = runtime_mheap.spans[x];
619 objstart = (byte*)((uintptr)s->start<<PageShift);
620 if(s->sizeclass != 0) {
621 i = ((byte*)obj - objstart)/s->elemsize;
622 objstart += i*s->elemsize;
624 tisize = *(uintptr*)objti;
625 // Sanity check for object size: it should fit into the memory block.
626 if((byte*)obj + tisize > objstart + s->elemsize) {
627 runtime_printf("object of type '%S' at %p/%p does not fit in block %p/%p\n",
628 *t->string, obj, tisize, objstart, s->elemsize);
629 runtime_throw("invalid gc type info");
631 if(obj != objstart)
632 return;
633 // If obj points to the beginning of the memory block,
634 // check type info as well.
635 if(t->string == nil ||
636 // Gob allocates unsafe pointers for indirection.
637 (runtime_strcmp((const char *)t->string->str, (const char*)"unsafe.Pointer") &&
638 // Runtime and gc think differently about closures.
639 runtime_strstr((const char *)t->string->str, (const char*)"struct { F uintptr") != (const char *)t->string->str)) {
640 #if 0
641 pc1 = (uintptr*)objti;
642 pc2 = (uintptr*)t->gc;
643 // A simple best-effort check until first GC_END.
644 for(j = 1; pc1[j] != GC_END && pc2[j] != GC_END; j++) {
645 if(pc1[j] != pc2[j]) {
646 runtime_printf("invalid gc type info for '%s' at %p, type info %p, block info %p\n",
647 t->string ? (const int8*)t->string->str : (const int8*)"?", j, pc1[j], pc2[j]);
648 runtime_throw("invalid gc type info");
651 #endif
655 // scanblock scans a block of n bytes starting at pointer b for references
656 // to other objects, scanning any it finds recursively until there are no
657 // unscanned objects left. Instead of using an explicit recursion, it keeps
658 // a work list in the Workbuf* structures and loops in the main function
659 // body. Keeping an explicit work list is easier on the stack allocator and
660 // more efficient.
662 // wbuf: current work buffer
663 // wp: storage for next queued pointer (write pointer)
664 // nobj: number of queued objects
665 static void
666 scanblock(Workbuf *wbuf, Obj *wp, uintptr nobj, bool keepworking)
668 byte *b, *arena_start, *arena_used;
669 uintptr n, i, end_b, elemsize, size, ti, objti, count /* , type */;
670 uintptr *pc, precise_type, nominal_size;
671 #if 0
672 uintptr *chan_ret, chancap;
673 #endif
674 void *obj;
675 const Type *t;
676 Slice *sliceptr;
677 Frame *stack_ptr, stack_top, stack[GC_STACK_CAPACITY+4];
678 BufferList *scanbuffers;
679 PtrTarget *ptrbuf, *ptrbuf_end, *ptrbufpos;
680 Obj *objbuf, *objbuf_end, *objbufpos;
681 Eface *eface;
682 Iface *iface;
683 #if 0
684 Hchan *chan;
685 ChanType *chantype;
686 #endif
688 if(sizeof(Workbuf) % PageSize != 0)
689 runtime_throw("scanblock: size of Workbuf is suboptimal");
691 // Memory arena parameters.
692 arena_start = runtime_mheap.arena_start;
693 arena_used = runtime_mheap.arena_used;
695 stack_ptr = stack+nelem(stack)-1;
697 precise_type = false;
698 nominal_size = 0;
700 // Allocate ptrbuf
702 scanbuffers = &bufferList[runtime_m()->helpgc];
703 ptrbuf = &scanbuffers->ptrtarget[0];
704 ptrbuf_end = &scanbuffers->ptrtarget[0] + nelem(scanbuffers->ptrtarget);
705 objbuf = &scanbuffers->obj[0];
706 objbuf_end = &scanbuffers->obj[0] + nelem(scanbuffers->obj);
709 ptrbufpos = ptrbuf;
710 objbufpos = objbuf;
712 // (Silence the compiler)
713 #if 0
714 chan = nil;
715 chantype = nil;
716 chan_ret = nil;
717 #endif
719 goto next_block;
721 for(;;) {
722 // Each iteration scans the block b of length n, queueing pointers in
723 // the work buffer.
724 if(Debug > 1) {
725 runtime_printf("scanblock %p %D\n", b, (int64)n);
728 if(CollectStats) {
729 runtime_xadd64(&gcstats.nbytes, n);
730 runtime_xadd64(&gcstats.obj.sum, nobj);
731 runtime_xadd64(&gcstats.obj.cnt, 1);
734 if(ti != 0 && false) {
735 pc = (uintptr*)(ti & ~(uintptr)PC_BITS);
736 precise_type = (ti & PRECISE);
737 stack_top.elemsize = pc[0];
738 if(!precise_type)
739 nominal_size = pc[0];
740 if(ti & LOOP) {
741 stack_top.count = 0; // 0 means an infinite number of iterations
742 stack_top.loop_or_ret = pc+1;
743 } else {
744 stack_top.count = 1;
746 if(Debug) {
747 // Simple sanity check for provided type info ti:
748 // The declared size of the object must be not larger than the actual size
749 // (it can be smaller due to inferior pointers).
750 // It's difficult to make a comprehensive check due to inferior pointers,
751 // reflection, gob, etc.
752 if(pc[0] > n) {
753 runtime_printf("invalid gc type info: type info size %p, block size %p\n", pc[0], n);
754 runtime_throw("invalid gc type info");
757 } else if(UseSpanType && false) {
758 if(CollectStats)
759 runtime_xadd64(&gcstats.obj.notype, 1);
761 #if 0
762 type = runtime_gettype(b);
763 if(type != 0) {
764 if(CollectStats)
765 runtime_xadd64(&gcstats.obj.typelookup, 1);
767 t = (Type*)(type & ~(uintptr)(PtrSize-1));
768 switch(type & (PtrSize-1)) {
769 case TypeInfo_SingleObject:
770 pc = (uintptr*)t->gc;
771 precise_type = true; // type information about 'b' is precise
772 stack_top.count = 1;
773 stack_top.elemsize = pc[0];
774 break;
775 case TypeInfo_Array:
776 pc = (uintptr*)t->gc;
777 if(pc[0] == 0)
778 goto next_block;
779 precise_type = true; // type information about 'b' is precise
780 stack_top.count = 0; // 0 means an infinite number of iterations
781 stack_top.elemsize = pc[0];
782 stack_top.loop_or_ret = pc+1;
783 break;
784 case TypeInfo_Chan:
785 chan = (Hchan*)b;
786 chantype = (ChanType*)t;
787 chan_ret = nil;
788 pc = chanProg;
789 break;
790 default:
791 runtime_throw("scanblock: invalid type");
792 return;
794 } else {
795 pc = defaultProg;
797 #endif
798 } else {
799 pc = defaultProg;
802 if(IgnorePreciseGC)
803 pc = defaultProg;
805 pc++;
806 stack_top.b = (uintptr)b;
808 end_b = (uintptr)b + n - PtrSize;
810 for(;;) {
811 if(CollectStats)
812 runtime_xadd64(&gcstats.instr[pc[0]], 1);
814 obj = nil;
815 objti = 0;
816 switch(pc[0]) {
817 case GC_PTR:
818 obj = *(void**)(stack_top.b + pc[1]);
819 objti = pc[2];
820 pc += 3;
821 if(Debug)
822 checkptr(obj, objti);
823 break;
825 case GC_SLICE:
826 sliceptr = (Slice*)(stack_top.b + pc[1]);
827 if(sliceptr->cap != 0) {
828 obj = sliceptr->array;
829 // Can't use slice element type for scanning,
830 // because if it points to an array embedded
831 // in the beginning of a struct,
832 // we will scan the whole struct as the slice.
833 // So just obtain type info from heap.
835 pc += 3;
836 break;
838 case GC_APTR:
839 obj = *(void**)(stack_top.b + pc[1]);
840 pc += 2;
841 break;
843 case GC_STRING:
844 obj = *(void**)(stack_top.b + pc[1]);
845 markonly(obj);
846 pc += 2;
847 continue;
849 case GC_EFACE:
850 eface = (Eface*)(stack_top.b + pc[1]);
851 pc += 2;
852 if(eface->type == nil)
853 continue;
855 // eface->type
856 t = eface->type;
857 if((const byte*)t >= arena_start && (const byte*)t < arena_used) {
858 union { const Type *tc; Type *tr; } u;
859 u.tc = t;
860 *ptrbufpos++ = (struct PtrTarget){(void*)u.tr, 0};
861 if(ptrbufpos == ptrbuf_end)
862 flushptrbuf(ptrbuf, &ptrbufpos, &wp, &wbuf, &nobj);
865 // eface->__object
866 if((byte*)eface->__object >= arena_start && (byte*)eface->__object < arena_used) {
867 if(t->__size <= sizeof(void*)) {
868 if((t->kind & KindNoPointers))
869 continue;
871 obj = eface->__object;
872 if((t->kind & ~KindNoPointers) == KindPtr)
873 // objti = (uintptr)((PtrType*)t)->elem->gc;
874 objti = 0;
875 } else {
876 obj = eface->__object;
877 // objti = (uintptr)t->gc;
878 objti = 0;
881 break;
883 case GC_IFACE:
884 iface = (Iface*)(stack_top.b + pc[1]);
885 pc += 2;
886 if(iface->tab == nil)
887 continue;
889 // iface->tab
890 if((byte*)iface->tab >= arena_start && (byte*)iface->tab < arena_used) {
891 // *ptrbufpos++ = (struct PtrTarget){iface->tab, (uintptr)itabtype->gc};
892 *ptrbufpos++ = (struct PtrTarget){iface->tab, 0};
893 if(ptrbufpos == ptrbuf_end)
894 flushptrbuf(ptrbuf, &ptrbufpos, &wp, &wbuf, &nobj);
897 // iface->data
898 if((byte*)iface->__object >= arena_start && (byte*)iface->__object < arena_used) {
899 // t = iface->tab->type;
900 t = nil;
901 if(t->__size <= sizeof(void*)) {
902 if((t->kind & KindNoPointers))
903 continue;
905 obj = iface->__object;
906 if((t->kind & ~KindNoPointers) == KindPtr)
907 // objti = (uintptr)((const PtrType*)t)->elem->gc;
908 objti = 0;
909 } else {
910 obj = iface->__object;
911 // objti = (uintptr)t->gc;
912 objti = 0;
915 break;
917 case GC_DEFAULT_PTR:
918 while(stack_top.b <= end_b) {
919 obj = *(byte**)stack_top.b;
920 stack_top.b += PtrSize;
921 if((byte*)obj >= arena_start && (byte*)obj < arena_used) {
922 *ptrbufpos++ = (struct PtrTarget){obj, 0};
923 if(ptrbufpos == ptrbuf_end)
924 flushptrbuf(ptrbuf, &ptrbufpos, &wp, &wbuf, &nobj);
927 goto next_block;
929 case GC_END:
930 if(--stack_top.count != 0) {
931 // Next iteration of a loop if possible.
932 stack_top.b += stack_top.elemsize;
933 if(stack_top.b + stack_top.elemsize <= end_b+PtrSize) {
934 pc = stack_top.loop_or_ret;
935 continue;
937 i = stack_top.b;
938 } else {
939 // Stack pop if possible.
940 if(stack_ptr+1 < stack+nelem(stack)) {
941 pc = stack_top.loop_or_ret;
942 stack_top = *(++stack_ptr);
943 continue;
945 i = (uintptr)b + nominal_size;
947 if(!precise_type) {
948 // Quickly scan [b+i,b+n) for possible pointers.
949 for(; i<=end_b; i+=PtrSize) {
950 if(*(byte**)i != nil) {
951 // Found a value that may be a pointer.
952 // Do a rescan of the entire block.
953 enqueue((Obj){b, n, 0}, &wbuf, &wp, &nobj);
954 if(CollectStats) {
955 runtime_xadd64(&gcstats.rescan, 1);
956 runtime_xadd64(&gcstats.rescanbytes, n);
958 break;
962 goto next_block;
964 case GC_ARRAY_START:
965 i = stack_top.b + pc[1];
966 count = pc[2];
967 elemsize = pc[3];
968 pc += 4;
970 // Stack push.
971 *stack_ptr-- = stack_top;
972 stack_top = (Frame){count, elemsize, i, pc};
973 continue;
975 case GC_ARRAY_NEXT:
976 if(--stack_top.count != 0) {
977 stack_top.b += stack_top.elemsize;
978 pc = stack_top.loop_or_ret;
979 } else {
980 // Stack pop.
981 stack_top = *(++stack_ptr);
982 pc += 1;
984 continue;
986 case GC_CALL:
987 // Stack push.
988 *stack_ptr-- = stack_top;
989 stack_top = (Frame){1, 0, stack_top.b + pc[1], pc+3 /*return address*/};
990 pc = (uintptr*)((byte*)pc + *(int32*)(pc+2)); // target of the CALL instruction
991 continue;
993 case GC_REGION:
994 obj = (void*)(stack_top.b + pc[1]);
995 size = pc[2];
996 objti = pc[3];
997 pc += 4;
999 *objbufpos++ = (Obj){obj, size, objti};
1000 if(objbufpos == objbuf_end)
1001 flushobjbuf(objbuf, &objbufpos, &wp, &wbuf, &nobj);
1002 continue;
1004 #if 0
1005 case GC_CHAN_PTR:
1006 chan = *(Hchan**)(stack_top.b + pc[1]);
1007 if(chan == nil) {
1008 pc += 3;
1009 continue;
1011 if(markonly(chan)) {
1012 chantype = (ChanType*)pc[2];
1013 if(!(chantype->elem->kind & KindNoPointers)) {
1014 // Start chanProg.
1015 chan_ret = pc+3;
1016 pc = chanProg+1;
1017 continue;
1020 pc += 3;
1021 continue;
1023 case GC_CHAN:
1024 // There are no heap pointers in struct Hchan,
1025 // so we can ignore the leading sizeof(Hchan) bytes.
1026 if(!(chantype->elem->kind & KindNoPointers)) {
1027 // Channel's buffer follows Hchan immediately in memory.
1028 // Size of buffer (cap(c)) is second int in the chan struct.
1029 chancap = ((uintgo*)chan)[1];
1030 if(chancap > 0) {
1031 // TODO(atom): split into two chunks so that only the
1032 // in-use part of the circular buffer is scanned.
1033 // (Channel routines zero the unused part, so the current
1034 // code does not lead to leaks, it's just a little inefficient.)
1035 *objbufpos++ = (Obj){(byte*)chan+runtime_Hchansize, chancap*chantype->elem->size,
1036 (uintptr)chantype->elem->gc | PRECISE | LOOP};
1037 if(objbufpos == objbuf_end)
1038 flushobjbuf(objbuf, &objbufpos, &wp, &wbuf, &nobj);
1041 if(chan_ret == nil)
1042 goto next_block;
1043 pc = chan_ret;
1044 continue;
1045 #endif
1047 default:
1048 runtime_throw("scanblock: invalid GC instruction");
1049 return;
1052 if((byte*)obj >= arena_start && (byte*)obj < arena_used) {
1053 *ptrbufpos++ = (struct PtrTarget){obj, objti};
1054 if(ptrbufpos == ptrbuf_end)
1055 flushptrbuf(ptrbuf, &ptrbufpos, &wp, &wbuf, &nobj);
1059 next_block:
1060 // Done scanning [b, b+n). Prepare for the next iteration of
1061 // the loop by setting b, n, ti to the parameters for the next block.
1063 if(nobj == 0) {
1064 flushptrbuf(ptrbuf, &ptrbufpos, &wp, &wbuf, &nobj);
1065 flushobjbuf(objbuf, &objbufpos, &wp, &wbuf, &nobj);
1067 if(nobj == 0) {
1068 if(!keepworking) {
1069 if(wbuf)
1070 putempty(wbuf);
1071 goto endscan;
1073 // Emptied our buffer: refill.
1074 wbuf = getfull(wbuf);
1075 if(wbuf == nil)
1076 goto endscan;
1077 nobj = wbuf->nobj;
1078 wp = wbuf->obj + wbuf->nobj;
1082 // Fetch b from the work buffer.
1083 --wp;
1084 b = wp->p;
1085 n = wp->n;
1086 ti = wp->ti;
1087 nobj--;
1090 endscan:;
1093 // debug_scanblock is the debug copy of scanblock.
1094 // it is simpler, slower, single-threaded, recursive,
1095 // and uses bitSpecial as the mark bit.
1096 static void
1097 debug_scanblock(byte *b, uintptr n)
1099 byte *obj, *p;
1100 void **vp;
1101 uintptr size, *bitp, bits, shift, i, xbits, off;
1102 MSpan *s;
1104 if(!DebugMark)
1105 runtime_throw("debug_scanblock without DebugMark");
1107 if((intptr)n < 0) {
1108 runtime_printf("debug_scanblock %p %D\n", b, (int64)n);
1109 runtime_throw("debug_scanblock");
1112 // Align b to a word boundary.
1113 off = (uintptr)b & (PtrSize-1);
1114 if(off != 0) {
1115 b += PtrSize - off;
1116 n -= PtrSize - off;
1119 vp = (void**)b;
1120 n /= PtrSize;
1121 for(i=0; i<(uintptr)n; i++) {
1122 obj = (byte*)vp[i];
1124 // Words outside the arena cannot be pointers.
1125 if((byte*)obj < runtime_mheap.arena_start || (byte*)obj >= runtime_mheap.arena_used)
1126 continue;
1128 // Round down to word boundary.
1129 obj = (void*)((uintptr)obj & ~((uintptr)PtrSize-1));
1131 // Consult span table to find beginning.
1132 s = runtime_MHeap_LookupMaybe(&runtime_mheap, obj);
1133 if(s == nil)
1134 continue;
1136 p = (byte*)((uintptr)s->start<<PageShift);
1137 size = s->elemsize;
1138 if(s->sizeclass == 0) {
1139 obj = p;
1140 } else {
1141 int32 i = ((byte*)obj - p)/size;
1142 obj = p+i*size;
1145 // Now that we know the object header, reload bits.
1146 off = (uintptr*)obj - (uintptr*)runtime_mheap.arena_start;
1147 bitp = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
1148 shift = off % wordsPerBitmapWord;
1149 xbits = *bitp;
1150 bits = xbits >> shift;
1152 // Now we have bits, bitp, and shift correct for
1153 // obj pointing at the base of the object.
1154 // If not allocated or already marked, done.
1155 if((bits & bitAllocated) == 0 || (bits & bitSpecial) != 0) // NOTE: bitSpecial not bitMarked
1156 continue;
1157 *bitp |= bitSpecial<<shift;
1158 if(!(bits & bitMarked))
1159 runtime_printf("found unmarked block %p in %p\n", obj, vp+i);
1161 // If object has no pointers, don't need to scan further.
1162 if((bits & bitNoScan) != 0)
1163 continue;
1165 debug_scanblock(obj, size);
1169 // Append obj to the work buffer.
1170 // _wbuf, _wp, _nobj are input/output parameters and are specifying the work buffer.
1171 static void
1172 enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj)
1174 uintptr nobj, off;
1175 Obj *wp;
1176 Workbuf *wbuf;
1178 if(Debug > 1)
1179 runtime_printf("append obj(%p %D %p)\n", obj.p, (int64)obj.n, obj.ti);
1181 // Align obj.b to a word boundary.
1182 off = (uintptr)obj.p & (PtrSize-1);
1183 if(off != 0) {
1184 obj.p += PtrSize - off;
1185 obj.n -= PtrSize - off;
1186 obj.ti = 0;
1189 if(obj.p == nil || obj.n == 0)
1190 return;
1192 // Load work buffer state
1193 wp = *_wp;
1194 wbuf = *_wbuf;
1195 nobj = *_nobj;
1197 // If another proc wants a pointer, give it some.
1198 if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
1199 wbuf->nobj = nobj;
1200 wbuf = handoff(wbuf);
1201 nobj = wbuf->nobj;
1202 wp = wbuf->obj + nobj;
1205 // If buffer is full, get a new one.
1206 if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
1207 if(wbuf != nil)
1208 wbuf->nobj = nobj;
1209 wbuf = getempty(wbuf);
1210 wp = wbuf->obj;
1211 nobj = 0;
1214 *wp = obj;
1215 wp++;
1216 nobj++;
1218 // Save work buffer state
1219 *_wp = wp;
1220 *_wbuf = wbuf;
1221 *_nobj = nobj;
1224 static void
1225 markroot(ParFor *desc, uint32 i)
1227 Obj *wp;
1228 Workbuf *wbuf;
1229 uintptr nobj;
1231 USED(&desc);
1232 wp = nil;
1233 wbuf = nil;
1234 nobj = 0;
1235 enqueue(work.roots[i], &wbuf, &wp, &nobj);
1236 scanblock(wbuf, wp, nobj, false);
1239 // Get an empty work buffer off the work.empty list,
1240 // allocating new buffers as needed.
1241 static Workbuf*
1242 getempty(Workbuf *b)
1244 if(b != nil)
1245 runtime_lfstackpush(&work.full, &b->node);
1246 b = (Workbuf*)runtime_lfstackpop(&work.empty);
1247 if(b == nil) {
1248 // Need to allocate.
1249 runtime_lock(&work);
1250 if(work.nchunk < sizeof *b) {
1251 work.nchunk = 1<<20;
1252 work.chunk = runtime_SysAlloc(work.nchunk, &mstats.gc_sys);
1253 if(work.chunk == nil)
1254 runtime_throw("runtime: cannot allocate memory");
1256 b = (Workbuf*)work.chunk;
1257 work.chunk += sizeof *b;
1258 work.nchunk -= sizeof *b;
1259 runtime_unlock(&work);
1261 b->nobj = 0;
1262 return b;
1265 static void
1266 putempty(Workbuf *b)
1268 if(CollectStats)
1269 runtime_xadd64(&gcstats.putempty, 1);
1271 runtime_lfstackpush(&work.empty, &b->node);
1274 // Get a full work buffer off the work.full list, or return nil.
1275 static Workbuf*
1276 getfull(Workbuf *b)
1278 M *m;
1279 int32 i;
1281 if(CollectStats)
1282 runtime_xadd64(&gcstats.getfull, 1);
1284 if(b != nil)
1285 runtime_lfstackpush(&work.empty, &b->node);
1286 b = (Workbuf*)runtime_lfstackpop(&work.full);
1287 if(b != nil || work.nproc == 1)
1288 return b;
1290 m = runtime_m();
1291 runtime_xadd(&work.nwait, +1);
1292 for(i=0;; i++) {
1293 if(work.full != 0) {
1294 runtime_xadd(&work.nwait, -1);
1295 b = (Workbuf*)runtime_lfstackpop(&work.full);
1296 if(b != nil)
1297 return b;
1298 runtime_xadd(&work.nwait, +1);
1300 if(work.nwait == work.nproc)
1301 return nil;
1302 if(i < 10) {
1303 m->gcstats.nprocyield++;
1304 runtime_procyield(20);
1305 } else if(i < 20) {
1306 m->gcstats.nosyield++;
1307 runtime_osyield();
1308 } else {
1309 m->gcstats.nsleep++;
1310 runtime_usleep(100);
1315 static Workbuf*
1316 handoff(Workbuf *b)
1318 M *m;
1319 int32 n;
1320 Workbuf *b1;
1322 m = runtime_m();
1324 // Make new buffer with half of b's pointers.
1325 b1 = getempty(nil);
1326 n = b->nobj/2;
1327 b->nobj -= n;
1328 b1->nobj = n;
1329 runtime_memmove(b1->obj, b->obj+b->nobj, n*sizeof b1->obj[0]);
1330 m->gcstats.nhandoff++;
1331 m->gcstats.nhandoffcnt += n;
1333 // Put b on full list - let first half of b get stolen.
1334 runtime_lfstackpush(&work.full, &b->node);
1335 return b1;
1338 static void
1339 addroot(Obj obj)
1341 uint32 cap;
1342 Obj *new;
1344 if(work.nroot >= work.rootcap) {
1345 cap = PageSize/sizeof(Obj);
1346 if(cap < 2*work.rootcap)
1347 cap = 2*work.rootcap;
1348 new = (Obj*)runtime_SysAlloc(cap*sizeof(Obj), &mstats.gc_sys);
1349 if(new == nil)
1350 runtime_throw("runtime: cannot allocate memory");
1351 if(work.roots != nil) {
1352 runtime_memmove(new, work.roots, work.rootcap*sizeof(Obj));
1353 runtime_SysFree(work.roots, work.rootcap*sizeof(Obj), &mstats.gc_sys);
1355 work.roots = new;
1356 work.rootcap = cap;
1358 work.roots[work.nroot] = obj;
1359 work.nroot++;
1362 static void
1363 addstackroots(G *gp)
1365 #ifdef USING_SPLIT_STACK
1366 M *mp;
1367 void* sp;
1368 size_t spsize;
1369 void* next_segment;
1370 void* next_sp;
1371 void* initial_sp;
1373 if(gp == runtime_g()) {
1374 // Scanning our own stack.
1375 sp = __splitstack_find(nil, nil, &spsize, &next_segment,
1376 &next_sp, &initial_sp);
1377 } else if((mp = gp->m) != nil && mp->helpgc) {
1378 // gchelper's stack is in active use and has no interesting pointers.
1379 return;
1380 } else {
1381 // Scanning another goroutine's stack.
1382 // The goroutine is usually asleep (the world is stopped).
1384 // The exception is that if the goroutine is about to enter or might
1385 // have just exited a system call, it may be executing code such
1386 // as schedlock and may have needed to start a new stack segment.
1387 // Use the stack segment and stack pointer at the time of
1388 // the system call instead, since that won't change underfoot.
1389 if(gp->gcstack != nil) {
1390 sp = gp->gcstack;
1391 spsize = gp->gcstack_size;
1392 next_segment = gp->gcnext_segment;
1393 next_sp = gp->gcnext_sp;
1394 initial_sp = gp->gcinitial_sp;
1395 } else {
1396 sp = __splitstack_find_context(&gp->stack_context[0],
1397 &spsize, &next_segment,
1398 &next_sp, &initial_sp);
1401 if(sp != nil) {
1402 addroot((Obj){sp, spsize, 0});
1403 while((sp = __splitstack_find(next_segment, next_sp,
1404 &spsize, &next_segment,
1405 &next_sp, &initial_sp)) != nil)
1406 addroot((Obj){sp, spsize, 0});
1408 #else
1409 M *mp;
1410 byte* bottom;
1411 byte* top;
1413 if(gp == runtime_g()) {
1414 // Scanning our own stack.
1415 bottom = (byte*)&gp;
1416 } else if((mp = gp->m) != nil && mp->helpgc) {
1417 // gchelper's stack is in active use and has no interesting pointers.
1418 return;
1419 } else {
1420 // Scanning another goroutine's stack.
1421 // The goroutine is usually asleep (the world is stopped).
1422 bottom = (byte*)gp->gcnext_sp;
1423 if(bottom == nil)
1424 return;
1426 top = (byte*)gp->gcinitial_sp + gp->gcstack_size;
1427 if(top > bottom)
1428 addroot((Obj){bottom, top - bottom, 0});
1429 else
1430 addroot((Obj){top, bottom - top, 0});
1431 #endif
1434 static void
1435 addfinroots(void *v)
1437 uintptr size;
1438 void *base;
1440 size = 0;
1441 if(!runtime_mlookup(v, (byte**)&base, &size, nil) || !runtime_blockspecial(base))
1442 runtime_throw("mark - finalizer inconsistency");
1444 // do not mark the finalizer block itself. just mark the things it points at.
1445 addroot((Obj){base, size, 0});
1448 static struct root_list* roots;
1450 void
1451 __go_register_gc_roots (struct root_list* r)
1453 // FIXME: This needs locking if multiple goroutines can call
1454 // dlopen simultaneously.
1455 r->next = roots;
1456 roots = r;
1459 static void
1460 addroots(void)
1462 struct root_list *pl;
1463 G *gp;
1464 FinBlock *fb;
1465 MSpan *s, **allspans;
1466 uint32 spanidx;
1468 work.nroot = 0;
1470 // mark data+bss.
1471 for(pl = roots; pl != nil; pl = pl->next) {
1472 struct root* pr = &pl->roots[0];
1473 while(1) {
1474 void *decl = pr->decl;
1475 if(decl == nil)
1476 break;
1477 addroot((Obj){decl, pr->size, 0});
1478 pr++;
1482 addroot((Obj){(byte*)&runtime_m0, sizeof runtime_m0, 0});
1483 addroot((Obj){(byte*)&runtime_g0, sizeof runtime_g0, 0});
1484 addroot((Obj){(byte*)&runtime_allg, sizeof runtime_allg, 0});
1485 addroot((Obj){(byte*)&runtime_allm, sizeof runtime_allm, 0});
1486 addroot((Obj){(byte*)&runtime_allp, sizeof runtime_allp, 0});
1487 runtime_proc_scan(addroot);
1488 runtime_MProf_Mark(addroot);
1489 runtime_time_scan(addroot);
1490 runtime_netpoll_scan(addroot);
1492 // MSpan.types
1493 allspans = runtime_mheap.allspans;
1494 for(spanidx=0; spanidx<runtime_mheap.nspan; spanidx++) {
1495 s = allspans[spanidx];
1496 if(s->state == MSpanInUse) {
1497 // The garbage collector ignores type pointers stored in MSpan.types:
1498 // - Compiler-generated types are stored outside of heap.
1499 // - The reflect package has runtime-generated types cached in its data structures.
1500 // The garbage collector relies on finding the references via that cache.
1501 switch(s->types.compression) {
1502 case MTypes_Empty:
1503 case MTypes_Single:
1504 break;
1505 case MTypes_Words:
1506 case MTypes_Bytes:
1507 markonly((byte*)s->types.data);
1508 break;
1513 // stacks
1514 for(gp=runtime_allg; gp!=nil; gp=gp->alllink) {
1515 switch(gp->status){
1516 default:
1517 runtime_printf("unexpected G.status %d\n", gp->status);
1518 runtime_throw("mark - bad status");
1519 case Gdead:
1520 break;
1521 case Grunning:
1522 runtime_throw("mark - world not stopped");
1523 case Grunnable:
1524 case Gsyscall:
1525 case Gwaiting:
1526 addstackroots(gp);
1527 break;
1531 runtime_walkfintab(addfinroots, addroot);
1533 for(fb=allfin; fb; fb=fb->alllink)
1534 addroot((Obj){(byte*)fb->fin, fb->cnt*sizeof(fb->fin[0]), 0});
1536 addroot((Obj){(byte*)&work, sizeof work, 0});
1539 static bool
1540 handlespecial(byte *p, uintptr size)
1542 FuncVal *fn;
1543 const struct __go_func_type *ft;
1544 const struct __go_ptr_type *ot;
1545 FinBlock *block;
1546 Finalizer *f;
1548 if(!runtime_getfinalizer(p, true, &fn, &ft, &ot)) {
1549 runtime_setblockspecial(p, false);
1550 runtime_MProf_Free(p, size);
1551 return false;
1554 runtime_lock(&finlock);
1555 if(finq == nil || finq->cnt == finq->cap) {
1556 if(finc == nil) {
1557 finc = runtime_persistentalloc(PageSize, 0, &mstats.gc_sys);
1558 finc->cap = (PageSize - sizeof(FinBlock)) / sizeof(Finalizer) + 1;
1559 finc->alllink = allfin;
1560 allfin = finc;
1562 block = finc;
1563 finc = block->next;
1564 block->next = finq;
1565 finq = block;
1567 f = &finq->fin[finq->cnt];
1568 finq->cnt++;
1569 f->fn = fn;
1570 f->ft = ft;
1571 f->ot = ot;
1572 f->arg = p;
1573 runtime_unlock(&finlock);
1574 return true;
1577 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
1578 // It clears the mark bits in preparation for the next GC round.
1579 static void
1580 sweepspan(ParFor *desc, uint32 idx)
1582 M *m;
1583 int32 cl, n, npages;
1584 uintptr size;
1585 byte *p;
1586 MCache *c;
1587 byte *arena_start;
1588 MLink head, *end;
1589 int32 nfree;
1590 byte *type_data;
1591 byte compression;
1592 uintptr type_data_inc;
1593 MSpan *s;
1595 m = runtime_m();
1597 USED(&desc);
1598 s = runtime_mheap.allspans[idx];
1599 if(s->state != MSpanInUse)
1600 return;
1601 arena_start = runtime_mheap.arena_start;
1602 p = (byte*)(s->start << PageShift);
1603 cl = s->sizeclass;
1604 size = s->elemsize;
1605 if(cl == 0) {
1606 n = 1;
1607 } else {
1608 // Chunk full of small blocks.
1609 npages = runtime_class_to_allocnpages[cl];
1610 n = (npages << PageShift) / size;
1612 nfree = 0;
1613 end = &head;
1614 c = m->mcache;
1616 type_data = (byte*)s->types.data;
1617 type_data_inc = sizeof(uintptr);
1618 compression = s->types.compression;
1619 switch(compression) {
1620 case MTypes_Bytes:
1621 type_data += 8*sizeof(uintptr);
1622 type_data_inc = 1;
1623 break;
1626 // Sweep through n objects of given size starting at p.
1627 // This thread owns the span now, so it can manipulate
1628 // the block bitmap without atomic operations.
1629 for(; n > 0; n--, p += size, type_data+=type_data_inc) {
1630 uintptr off, *bitp, shift, bits;
1632 off = (uintptr*)p - (uintptr*)arena_start;
1633 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1634 shift = off % wordsPerBitmapWord;
1635 bits = *bitp>>shift;
1637 if((bits & bitAllocated) == 0)
1638 continue;
1640 if((bits & bitMarked) != 0) {
1641 if(DebugMark) {
1642 if(!(bits & bitSpecial))
1643 runtime_printf("found spurious mark on %p\n", p);
1644 *bitp &= ~(bitSpecial<<shift);
1646 *bitp &= ~(bitMarked<<shift);
1647 continue;
1650 // Special means it has a finalizer or is being profiled.
1651 // In DebugMark mode, the bit has been coopted so
1652 // we have to assume all blocks are special.
1653 if(DebugMark || (bits & bitSpecial) != 0) {
1654 if(handlespecial(p, size))
1655 continue;
1658 // Mark freed; restore block boundary bit.
1659 *bitp = (*bitp & ~(bitMask<<shift)) | (bitBlockBoundary<<shift);
1661 if(cl == 0) {
1662 // Free large span.
1663 runtime_unmarkspan(p, 1<<PageShift);
1664 *(uintptr*)p = (uintptr)0xdeaddeaddeaddeadll; // needs zeroing
1665 runtime_MHeap_Free(&runtime_mheap, s, 1);
1666 c->local_nlargefree++;
1667 c->local_largefree += size;
1668 } else {
1669 // Free small object.
1670 switch(compression) {
1671 case MTypes_Words:
1672 *(uintptr*)type_data = 0;
1673 break;
1674 case MTypes_Bytes:
1675 *(byte*)type_data = 0;
1676 break;
1678 if(size > sizeof(uintptr))
1679 ((uintptr*)p)[1] = (uintptr)0xdeaddeaddeaddeadll; // mark as "needs to be zeroed"
1681 end->next = (MLink*)p;
1682 end = (MLink*)p;
1683 nfree++;
1687 if(nfree) {
1688 c->local_nsmallfree[cl] += nfree;
1689 c->local_cachealloc -= nfree * size;
1690 runtime_MCentral_FreeSpan(&runtime_mheap.central[cl], s, nfree, head.next, end);
1694 static void
1695 dumpspan(uint32 idx)
1697 int32 sizeclass, n, npages, i, column;
1698 uintptr size;
1699 byte *p;
1700 byte *arena_start;
1701 MSpan *s;
1702 bool allocated, special;
1704 s = runtime_mheap.allspans[idx];
1705 if(s->state != MSpanInUse)
1706 return;
1707 arena_start = runtime_mheap.arena_start;
1708 p = (byte*)(s->start << PageShift);
1709 sizeclass = s->sizeclass;
1710 size = s->elemsize;
1711 if(sizeclass == 0) {
1712 n = 1;
1713 } else {
1714 npages = runtime_class_to_allocnpages[sizeclass];
1715 n = (npages << PageShift) / size;
1718 runtime_printf("%p .. %p:\n", p, p+n*size);
1719 column = 0;
1720 for(; n>0; n--, p+=size) {
1721 uintptr off, *bitp, shift, bits;
1723 off = (uintptr*)p - (uintptr*)arena_start;
1724 bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
1725 shift = off % wordsPerBitmapWord;
1726 bits = *bitp>>shift;
1728 allocated = ((bits & bitAllocated) != 0);
1729 special = ((bits & bitSpecial) != 0);
1731 for(i=0; (uint32)i<size; i+=sizeof(void*)) {
1732 if(column == 0) {
1733 runtime_printf("\t");
1735 if(i == 0) {
1736 runtime_printf(allocated ? "(" : "[");
1737 runtime_printf(special ? "@" : "");
1738 runtime_printf("%p: ", p+i);
1739 } else {
1740 runtime_printf(" ");
1743 runtime_printf("%p", *(void**)(p+i));
1745 if(i+sizeof(void*) >= size) {
1746 runtime_printf(allocated ? ") " : "] ");
1749 column++;
1750 if(column == 8) {
1751 runtime_printf("\n");
1752 column = 0;
1756 runtime_printf("\n");
1759 // A debugging function to dump the contents of memory
1760 void
1761 runtime_memorydump(void)
1763 uint32 spanidx;
1765 for(spanidx=0; spanidx<runtime_mheap.nspan; spanidx++) {
1766 dumpspan(spanidx);
1770 void
1771 runtime_gchelper(void)
1773 uint32 nproc;
1775 gchelperstart();
1777 // parallel mark for over gc roots
1778 runtime_parfordo(work.markfor);
1780 // help other threads scan secondary blocks
1781 scanblock(nil, nil, 0, true);
1783 if(DebugMark) {
1784 // wait while the main thread executes mark(debug_scanblock)
1785 while(runtime_atomicload(&work.debugmarkdone) == 0)
1786 runtime_usleep(10);
1789 runtime_parfordo(work.sweepfor);
1790 bufferList[runtime_m()->helpgc].busy = 0;
1791 nproc = work.nproc; // work.nproc can change right after we increment work.ndone
1792 if(runtime_xadd(&work.ndone, +1) == nproc-1)
1793 runtime_notewakeup(&work.alldone);
1796 #define GcpercentUnknown (-2)
1798 // Initialized from $GOGC. GOGC=off means no gc.
1800 // Next gc is after we've allocated an extra amount of
1801 // memory proportional to the amount already in use.
1802 // If gcpercent=100 and we're using 4M, we'll gc again
1803 // when we get to 8M. This keeps the gc cost in linear
1804 // proportion to the allocation cost. Adjusting gcpercent
1805 // just changes the linear constant (and also the amount of
1806 // extra memory used).
1807 static int32 gcpercent = GcpercentUnknown;
1809 static void
1810 cachestats(void)
1812 MCache *c;
1813 P *p, **pp;
1815 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
1816 c = p->mcache;
1817 if(c==nil)
1818 continue;
1819 runtime_purgecachedstats(c);
1823 static void
1824 updatememstats(GCStats *stats)
1826 M *mp;
1827 MSpan *s;
1828 MCache *c;
1829 P *p, **pp;
1830 uint32 i;
1831 uint64 stacks_inuse, smallfree;
1832 uint64 *src, *dst;
1834 if(stats)
1835 runtime_memclr((byte*)stats, sizeof(*stats));
1836 stacks_inuse = 0;
1837 for(mp=runtime_allm; mp; mp=mp->alllink) {
1838 //stacks_inuse += mp->stackinuse*FixedStack;
1839 if(stats) {
1840 src = (uint64*)&mp->gcstats;
1841 dst = (uint64*)stats;
1842 for(i=0; i<sizeof(*stats)/sizeof(uint64); i++)
1843 dst[i] += src[i];
1844 runtime_memclr((byte*)&mp->gcstats, sizeof(mp->gcstats));
1847 mstats.stacks_inuse = stacks_inuse;
1848 mstats.mcache_inuse = runtime_mheap.cachealloc.inuse;
1849 mstats.mspan_inuse = runtime_mheap.spanalloc.inuse;
1850 mstats.sys = mstats.heap_sys + mstats.stacks_sys + mstats.mspan_sys +
1851 mstats.mcache_sys + mstats.buckhash_sys + mstats.gc_sys + mstats.other_sys;
1853 // Calculate memory allocator stats.
1854 // During program execution we only count number of frees and amount of freed memory.
1855 // Current number of alive object in the heap and amount of alive heap memory
1856 // are calculated by scanning all spans.
1857 // Total number of mallocs is calculated as number of frees plus number of alive objects.
1858 // Similarly, total amount of allocated memory is calculated as amount of freed memory
1859 // plus amount of alive heap memory.
1860 mstats.alloc = 0;
1861 mstats.total_alloc = 0;
1862 mstats.nmalloc = 0;
1863 mstats.nfree = 0;
1864 for(i = 0; i < nelem(mstats.by_size); i++) {
1865 mstats.by_size[i].nmalloc = 0;
1866 mstats.by_size[i].nfree = 0;
1869 // Flush MCache's to MCentral.
1870 for(pp=runtime_allp; (p=*pp) != nil; pp++) {
1871 c = p->mcache;
1872 if(c==nil)
1873 continue;
1874 runtime_MCache_ReleaseAll(c);
1877 // Aggregate local stats.
1878 cachestats();
1880 // Scan all spans and count number of alive objects.
1881 for(i = 0; i < runtime_mheap.nspan; i++) {
1882 s = runtime_mheap.allspans[i];
1883 if(s->state != MSpanInUse)
1884 continue;
1885 if(s->sizeclass == 0) {
1886 mstats.nmalloc++;
1887 mstats.alloc += s->elemsize;
1888 } else {
1889 mstats.nmalloc += s->ref;
1890 mstats.by_size[s->sizeclass].nmalloc += s->ref;
1891 mstats.alloc += s->ref*s->elemsize;
1895 // Aggregate by size class.
1896 smallfree = 0;
1897 mstats.nfree = runtime_mheap.nlargefree;
1898 for(i = 0; i < nelem(mstats.by_size); i++) {
1899 mstats.nfree += runtime_mheap.nsmallfree[i];
1900 mstats.by_size[i].nfree = runtime_mheap.nsmallfree[i];
1901 mstats.by_size[i].nmalloc += runtime_mheap.nsmallfree[i];
1902 smallfree += runtime_mheap.nsmallfree[i] * runtime_class_to_size[i];
1904 mstats.nmalloc += mstats.nfree;
1906 // Calculate derived stats.
1907 mstats.total_alloc = mstats.alloc + runtime_mheap.largefree + smallfree;
1908 mstats.heap_alloc = mstats.alloc;
1909 mstats.heap_objects = mstats.nmalloc - mstats.nfree;
1912 // Structure of arguments passed to function gc().
1913 // This allows the arguments to be passed via runtime_mcall.
1914 struct gc_args
1916 int64 start_time; // start time of GC in ns (just before stoptheworld)
1919 static void gc(struct gc_args *args);
1920 static void mgc(G *gp);
1922 static int32
1923 readgogc(void)
1925 const byte *p;
1927 p = runtime_getenv("GOGC");
1928 if(p == nil || p[0] == '\0')
1929 return 100;
1930 if(runtime_strcmp((const char *)p, "off") == 0)
1931 return -1;
1932 return runtime_atoi(p);
1935 void
1936 runtime_gc(int32 force)
1938 M *m;
1939 G *g;
1940 struct gc_args a;
1941 int32 i;
1943 // The atomic operations are not atomic if the uint64s
1944 // are not aligned on uint64 boundaries. This has been
1945 // a problem in the past.
1946 if((((uintptr)&work.empty) & 7) != 0)
1947 runtime_throw("runtime: gc work buffer is misaligned");
1948 if((((uintptr)&work.full) & 7) != 0)
1949 runtime_throw("runtime: gc work buffer is misaligned");
1951 // Make sure all registers are saved on stack so that
1952 // scanstack sees them.
1953 __builtin_unwind_init();
1955 // The gc is turned off (via enablegc) until
1956 // the bootstrap has completed.
1957 // Also, malloc gets called in the guts
1958 // of a number of libraries that might be
1959 // holding locks. To avoid priority inversion
1960 // problems, don't bother trying to run gc
1961 // while holding a lock. The next mallocgc
1962 // without a lock will do the gc instead.
1963 m = runtime_m();
1964 if(!mstats.enablegc || runtime_g() == m->g0 || m->locks > 0 || runtime_panicking)
1965 return;
1967 if(gcpercent == GcpercentUnknown) { // first time through
1968 runtime_lock(&runtime_mheap);
1969 if(gcpercent == GcpercentUnknown)
1970 gcpercent = readgogc();
1971 runtime_unlock(&runtime_mheap);
1973 if(gcpercent < 0)
1974 return;
1976 runtime_semacquire(&runtime_worldsema, false);
1977 if(!force && mstats.heap_alloc < mstats.next_gc) {
1978 // typically threads which lost the race to grab
1979 // worldsema exit here when gc is done.
1980 runtime_semrelease(&runtime_worldsema);
1981 return;
1984 // Ok, we're doing it! Stop everybody else
1985 a.start_time = runtime_nanotime();
1986 m->gcing = 1;
1987 runtime_stoptheworld();
1989 // Run gc on the g0 stack. We do this so that the g stack
1990 // we're currently running on will no longer change. Cuts
1991 // the root set down a bit (g0 stacks are not scanned, and
1992 // we don't need to scan gc's internal state). Also an
1993 // enabler for copyable stacks.
1994 for(i = 0; i < (runtime_debug.gctrace > 1 ? 2 : 1); i++) {
1995 // switch to g0, call gc(&a), then switch back
1996 g = runtime_g();
1997 g->param = &a;
1998 g->status = Gwaiting;
1999 g->waitreason = "garbage collection";
2000 runtime_mcall(mgc);
2001 // record a new start time in case we're going around again
2002 a.start_time = runtime_nanotime();
2005 // all done
2006 m->gcing = 0;
2007 m->locks++;
2008 runtime_semrelease(&runtime_worldsema);
2009 runtime_starttheworld();
2010 m->locks--;
2012 // now that gc is done, kick off finalizer thread if needed
2013 if(finq != nil) {
2014 runtime_lock(&finlock);
2015 // kick off or wake up goroutine to run queued finalizers
2016 if(fing == nil)
2017 fing = __go_go(runfinq, nil);
2018 else if(fingwait) {
2019 fingwait = 0;
2020 runtime_ready(fing);
2022 runtime_unlock(&finlock);
2024 // give the queued finalizers, if any, a chance to run
2025 runtime_gosched();
2028 static void
2029 mgc(G *gp)
2031 gc(gp->param);
2032 gp->param = nil;
2033 gp->status = Grunning;
2034 runtime_gogo(gp);
2037 static void
2038 gc(struct gc_args *args)
2040 M *m;
2041 int64 t0, t1, t2, t3, t4;
2042 uint64 heap0, heap1, obj0, obj1, ninstr;
2043 GCStats stats;
2044 M *mp;
2045 uint32 i;
2046 // Eface eface;
2048 m = runtime_m();
2050 t0 = args->start_time;
2052 if(CollectStats)
2053 runtime_memclr((byte*)&gcstats, sizeof(gcstats));
2055 for(mp=runtime_allm; mp; mp=mp->alllink)
2056 runtime_settype_flush(mp);
2058 heap0 = 0;
2059 obj0 = 0;
2060 if(runtime_debug.gctrace) {
2061 updatememstats(nil);
2062 heap0 = mstats.heap_alloc;
2063 obj0 = mstats.nmalloc - mstats.nfree;
2066 m->locks++; // disable gc during mallocs in parforalloc
2067 if(work.markfor == nil)
2068 work.markfor = runtime_parforalloc(MaxGcproc);
2069 if(work.sweepfor == nil)
2070 work.sweepfor = runtime_parforalloc(MaxGcproc);
2071 m->locks--;
2073 if(itabtype == nil) {
2074 // get C pointer to the Go type "itab"
2075 // runtime_gc_itab_ptr(&eface);
2076 // itabtype = ((PtrType*)eface.type)->elem;
2079 work.nwait = 0;
2080 work.ndone = 0;
2081 work.debugmarkdone = 0;
2082 work.nproc = runtime_gcprocs();
2083 addroots();
2084 runtime_parforsetup(work.markfor, work.nproc, work.nroot, nil, false, markroot);
2085 runtime_parforsetup(work.sweepfor, work.nproc, runtime_mheap.nspan, nil, true, sweepspan);
2086 if(work.nproc > 1) {
2087 runtime_noteclear(&work.alldone);
2088 runtime_helpgc(work.nproc);
2091 t1 = runtime_nanotime();
2093 gchelperstart();
2094 runtime_parfordo(work.markfor);
2095 scanblock(nil, nil, 0, true);
2097 if(DebugMark) {
2098 for(i=0; i<work.nroot; i++)
2099 debug_scanblock(work.roots[i].p, work.roots[i].n);
2100 runtime_atomicstore(&work.debugmarkdone, 1);
2102 t2 = runtime_nanotime();
2104 runtime_parfordo(work.sweepfor);
2105 bufferList[m->helpgc].busy = 0;
2106 t3 = runtime_nanotime();
2108 if(work.nproc > 1)
2109 runtime_notesleep(&work.alldone);
2111 cachestats();
2112 mstats.next_gc = mstats.heap_alloc+mstats.heap_alloc*gcpercent/100;
2114 t4 = runtime_nanotime();
2115 mstats.last_gc = t4;
2116 mstats.pause_ns[mstats.numgc%nelem(mstats.pause_ns)] = t4 - t0;
2117 mstats.pause_total_ns += t4 - t0;
2118 mstats.numgc++;
2119 if(mstats.debuggc)
2120 runtime_printf("pause %D\n", t4-t0);
2122 if(runtime_debug.gctrace) {
2123 updatememstats(&stats);
2124 heap1 = mstats.heap_alloc;
2125 obj1 = mstats.nmalloc - mstats.nfree;
2127 stats.nprocyield += work.sweepfor->nprocyield;
2128 stats.nosyield += work.sweepfor->nosyield;
2129 stats.nsleep += work.sweepfor->nsleep;
2131 runtime_printf("gc%d(%d): %D+%D+%D ms, %D -> %D MB %D -> %D (%D-%D) objects,"
2132 " %D(%D) handoff, %D(%D) steal, %D/%D/%D yields\n",
2133 mstats.numgc, work.nproc, (t2-t1)/1000000, (t3-t2)/1000000, (t1-t0+t4-t3)/1000000,
2134 heap0>>20, heap1>>20, obj0, obj1,
2135 mstats.nmalloc, mstats.nfree,
2136 stats.nhandoff, stats.nhandoffcnt,
2137 work.sweepfor->nsteal, work.sweepfor->nstealcnt,
2138 stats.nprocyield, stats.nosyield, stats.nsleep);
2139 if(CollectStats) {
2140 runtime_printf("scan: %D bytes, %D objects, %D untyped, %D types from MSpan\n",
2141 gcstats.nbytes, gcstats.obj.cnt, gcstats.obj.notype, gcstats.obj.typelookup);
2142 if(gcstats.ptr.cnt != 0)
2143 runtime_printf("avg ptrbufsize: %D (%D/%D)\n",
2144 gcstats.ptr.sum/gcstats.ptr.cnt, gcstats.ptr.sum, gcstats.ptr.cnt);
2145 if(gcstats.obj.cnt != 0)
2146 runtime_printf("avg nobj: %D (%D/%D)\n",
2147 gcstats.obj.sum/gcstats.obj.cnt, gcstats.obj.sum, gcstats.obj.cnt);
2148 runtime_printf("rescans: %D, %D bytes\n", gcstats.rescan, gcstats.rescanbytes);
2150 runtime_printf("instruction counts:\n");
2151 ninstr = 0;
2152 for(i=0; i<nelem(gcstats.instr); i++) {
2153 runtime_printf("\t%d:\t%D\n", i, gcstats.instr[i]);
2154 ninstr += gcstats.instr[i];
2156 runtime_printf("\ttotal:\t%D\n", ninstr);
2158 runtime_printf("putempty: %D, getfull: %D\n", gcstats.putempty, gcstats.getfull);
2160 runtime_printf("markonly base lookup: bit %D word %D span %D\n", gcstats.markonly.foundbit, gcstats.markonly.foundword, gcstats.markonly.foundspan);
2161 runtime_printf("flushptrbuf base lookup: bit %D word %D span %D\n", gcstats.flushptrbuf.foundbit, gcstats.flushptrbuf.foundword, gcstats.flushptrbuf.foundspan);
2165 runtime_MProf_GC();
2168 void runtime_ReadMemStats(MStats *)
2169 __asm__ (GOSYM_PREFIX "runtime.ReadMemStats");
2171 void
2172 runtime_ReadMemStats(MStats *stats)
2174 M *m;
2176 // Have to acquire worldsema to stop the world,
2177 // because stoptheworld can only be used by
2178 // one goroutine at a time, and there might be
2179 // a pending garbage collection already calling it.
2180 runtime_semacquire(&runtime_worldsema, false);
2181 m = runtime_m();
2182 m->gcing = 1;
2183 runtime_stoptheworld();
2184 updatememstats(nil);
2185 *stats = mstats;
2186 m->gcing = 0;
2187 m->locks++;
2188 runtime_semrelease(&runtime_worldsema);
2189 runtime_starttheworld();
2190 m->locks--;
2193 void runtime_debug_readGCStats(Slice*)
2194 __asm__("runtime_debug.readGCStats");
2196 void
2197 runtime_debug_readGCStats(Slice *pauses)
2199 uint64 *p;
2200 uint32 i, n;
2202 // Calling code in runtime/debug should make the slice large enough.
2203 if((size_t)pauses->cap < nelem(mstats.pause_ns)+3)
2204 runtime_throw("runtime: short slice passed to readGCStats");
2206 // Pass back: pauses, last gc (absolute time), number of gc, total pause ns.
2207 p = (uint64*)pauses->array;
2208 runtime_lock(&runtime_mheap);
2209 n = mstats.numgc;
2210 if(n > nelem(mstats.pause_ns))
2211 n = nelem(mstats.pause_ns);
2213 // The pause buffer is circular. The most recent pause is at
2214 // pause_ns[(numgc-1)%nelem(pause_ns)], and then backward
2215 // from there to go back farther in time. We deliver the times
2216 // most recent first (in p[0]).
2217 for(i=0; i<n; i++)
2218 p[i] = mstats.pause_ns[(mstats.numgc-1-i)%nelem(mstats.pause_ns)];
2220 p[n] = mstats.last_gc;
2221 p[n+1] = mstats.numgc;
2222 p[n+2] = mstats.pause_total_ns;
2223 runtime_unlock(&runtime_mheap);
2224 pauses->__count = n+3;
2227 intgo runtime_debug_setGCPercent(intgo)
2228 __asm__("runtime_debug.setGCPercent");
2230 intgo
2231 runtime_debug_setGCPercent(intgo in)
2233 intgo out;
2235 runtime_lock(&runtime_mheap);
2236 if(gcpercent == GcpercentUnknown)
2237 gcpercent = readgogc();
2238 out = gcpercent;
2239 if(in < 0)
2240 in = -1;
2241 gcpercent = in;
2242 runtime_unlock(&runtime_mheap);
2243 return out;
2246 static void
2247 gchelperstart(void)
2249 M *m;
2251 m = runtime_m();
2252 if(m->helpgc < 0 || m->helpgc >= MaxGcproc)
2253 runtime_throw("gchelperstart: bad m->helpgc");
2254 if(runtime_xchg(&bufferList[m->helpgc].busy, 1))
2255 runtime_throw("gchelperstart: already busy");
2256 if(runtime_g() != m->g0)
2257 runtime_throw("gchelper not running on g0 stack");
2260 static void
2261 runfinq(void* dummy __attribute__ ((unused)))
2263 Finalizer *f;
2264 FinBlock *fb, *next;
2265 uint32 i;
2266 Eface ef;
2267 Iface iface;
2269 for(;;) {
2270 runtime_lock(&finlock);
2271 fb = finq;
2272 finq = nil;
2273 if(fb == nil) {
2274 fingwait = 1;
2275 runtime_park(runtime_unlock, &finlock, "finalizer wait");
2276 continue;
2278 runtime_unlock(&finlock);
2279 if(raceenabled)
2280 runtime_racefingo();
2281 for(; fb; fb=next) {
2282 next = fb->next;
2283 for(i=0; i<(uint32)fb->cnt; i++) {
2284 const Type *fint;
2285 void *param;
2287 f = &fb->fin[i];
2288 fint = ((const Type**)f->ft->__in.array)[0];
2289 if(fint->kind == KindPtr) {
2290 // direct use of pointer
2291 param = &f->arg;
2292 } else if(((const InterfaceType*)fint)->__methods.__count == 0) {
2293 // convert to empty interface
2294 ef.type = (const Type*)f->ot;
2295 ef.__object = f->arg;
2296 param = &ef;
2297 } else {
2298 // convert to interface with methods
2299 iface.__methods = __go_convert_interface_2((const Type*)fint,
2300 (const Type*)f->ot,
2302 iface.__object = f->arg;
2303 if(iface.__methods == nil)
2304 runtime_throw("invalid type conversion in runfinq");
2305 param = &iface;
2307 reflect_call(f->ft, f->fn, 0, 0, &param, nil);
2308 f->fn = nil;
2309 f->arg = nil;
2310 f->ot = nil;
2312 fb->cnt = 0;
2313 fb->next = finc;
2314 finc = fb;
2316 runtime_gc(1); // trigger another gc to clean up the finalized objects, if possible
2320 // mark the block at v of size n as allocated.
2321 // If noscan is true, mark it as not needing scanning.
2322 void
2323 runtime_markallocated(void *v, uintptr n, bool noscan)
2325 uintptr *b, obits, bits, off, shift;
2327 if(0)
2328 runtime_printf("markallocated %p+%p\n", v, n);
2330 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2331 runtime_throw("markallocated: bad pointer");
2333 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2334 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2335 shift = off % wordsPerBitmapWord;
2337 for(;;) {
2338 obits = *b;
2339 bits = (obits & ~(bitMask<<shift)) | (bitAllocated<<shift);
2340 if(noscan)
2341 bits |= bitNoScan<<shift;
2342 if(runtime_gomaxprocs == 1) {
2343 *b = bits;
2344 break;
2345 } else {
2346 // more than one goroutine is potentially running: use atomic op
2347 if(runtime_casp((void**)b, (void*)obits, (void*)bits))
2348 break;
2353 // mark the block at v of size n as freed.
2354 void
2355 runtime_markfreed(void *v, uintptr n)
2357 uintptr *b, obits, bits, off, shift;
2359 if(0)
2360 runtime_printf("markfreed %p+%p\n", v, n);
2362 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2363 runtime_throw("markfreed: bad pointer");
2365 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2366 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2367 shift = off % wordsPerBitmapWord;
2369 for(;;) {
2370 obits = *b;
2371 bits = (obits & ~(bitMask<<shift)) | (bitBlockBoundary<<shift);
2372 if(runtime_gomaxprocs == 1) {
2373 *b = bits;
2374 break;
2375 } else {
2376 // more than one goroutine is potentially running: use atomic op
2377 if(runtime_casp((void**)b, (void*)obits, (void*)bits))
2378 break;
2383 // check that the block at v of size n is marked freed.
2384 void
2385 runtime_checkfreed(void *v, uintptr n)
2387 uintptr *b, bits, off, shift;
2389 if(!runtime_checking)
2390 return;
2392 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2393 return; // not allocated, so okay
2395 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start; // word offset
2396 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2397 shift = off % wordsPerBitmapWord;
2399 bits = *b>>shift;
2400 if((bits & bitAllocated) != 0) {
2401 runtime_printf("checkfreed %p+%p: off=%p have=%p\n",
2402 v, n, off, bits & bitMask);
2403 runtime_throw("checkfreed: not freed");
2407 // mark the span of memory at v as having n blocks of the given size.
2408 // if leftover is true, there is left over space at the end of the span.
2409 void
2410 runtime_markspan(void *v, uintptr size, uintptr n, bool leftover)
2412 uintptr *b, off, shift;
2413 byte *p;
2415 if((byte*)v+size*n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2416 runtime_throw("markspan: bad pointer");
2418 p = v;
2419 if(leftover) // mark a boundary just past end of last block too
2420 n++;
2421 for(; n-- > 0; p += size) {
2422 // Okay to use non-atomic ops here, because we control
2423 // the entire span, and each bitmap word has bits for only
2424 // one span, so no other goroutines are changing these
2425 // bitmap words.
2426 off = (uintptr*)p - (uintptr*)runtime_mheap.arena_start; // word offset
2427 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2428 shift = off % wordsPerBitmapWord;
2429 *b = (*b & ~(bitMask<<shift)) | (bitBlockBoundary<<shift);
2433 // unmark the span of memory at v of length n bytes.
2434 void
2435 runtime_unmarkspan(void *v, uintptr n)
2437 uintptr *p, *b, off;
2439 if((byte*)v+n > (byte*)runtime_mheap.arena_used || (byte*)v < runtime_mheap.arena_start)
2440 runtime_throw("markspan: bad pointer");
2442 p = v;
2443 off = p - (uintptr*)runtime_mheap.arena_start; // word offset
2444 if(off % wordsPerBitmapWord != 0)
2445 runtime_throw("markspan: unaligned pointer");
2446 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2447 n /= PtrSize;
2448 if(n%wordsPerBitmapWord != 0)
2449 runtime_throw("unmarkspan: unaligned length");
2450 // Okay to use non-atomic ops here, because we control
2451 // the entire span, and each bitmap word has bits for only
2452 // one span, so no other goroutines are changing these
2453 // bitmap words.
2454 n /= wordsPerBitmapWord;
2455 while(n-- > 0)
2456 *b-- = 0;
2459 bool
2460 runtime_blockspecial(void *v)
2462 uintptr *b, off, shift;
2464 if(DebugMark)
2465 return true;
2467 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start;
2468 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2469 shift = off % wordsPerBitmapWord;
2471 return (*b & (bitSpecial<<shift)) != 0;
2474 void
2475 runtime_setblockspecial(void *v, bool s)
2477 uintptr *b, off, shift, bits, obits;
2479 if(DebugMark)
2480 return;
2482 off = (uintptr*)v - (uintptr*)runtime_mheap.arena_start;
2483 b = (uintptr*)runtime_mheap.arena_start - off/wordsPerBitmapWord - 1;
2484 shift = off % wordsPerBitmapWord;
2486 for(;;) {
2487 obits = *b;
2488 if(s)
2489 bits = obits | (bitSpecial<<shift);
2490 else
2491 bits = obits & ~(bitSpecial<<shift);
2492 if(runtime_gomaxprocs == 1) {
2493 *b = bits;
2494 break;
2495 } else {
2496 // more than one goroutine is potentially running: use atomic op
2497 if(runtime_casp((void**)b, (void*)obits, (void*)bits))
2498 break;
2503 void
2504 runtime_MHeap_MapBits(MHeap *h)
2506 size_t page_size;
2508 // Caller has added extra mappings to the arena.
2509 // Add extra mappings of bitmap words as needed.
2510 // We allocate extra bitmap pieces in chunks of bitmapChunk.
2511 enum {
2512 bitmapChunk = 8192
2514 uintptr n;
2516 n = (h->arena_used - h->arena_start) / wordsPerBitmapWord;
2517 n = ROUND(n, bitmapChunk);
2518 if(h->bitmap_mapped >= n)
2519 return;
2521 page_size = getpagesize();
2522 n = (n+page_size-1) & ~(page_size-1);
2524 runtime_SysMap(h->arena_start - n, n - h->bitmap_mapped, &mstats.gc_sys);
2525 h->bitmap_mapped = n;