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