]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/mgc0.c
[dev.garbage] all: merge default (dd5014ed9b01) into dev.garbage
[gostls13.git] / src / 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 // The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple GC 
8 // thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is 
9 // non-generational and non-compacting. Allocation is done using size segregated per P allocation 
10 // areas to minimize fragmentation while eliminating locks in the common case. 
11 //
12 // The algorithm decomposes into several steps.
13 // This is a high level description of the algorithm being used. For an overview of GC a good
14 // place to start is Richard Jones' gchandbook.org.
15 // 
16 // The algorithm's intellectual heritage includes Dijkstra's on-the-fly algorithm, see
17 // Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, and E. F. M. Steffens. 1978. 
18 // On-the-fly garbage collection: an exercise in cooperation. Commun. ACM 21, 11 (November 1978), 966-975.
19 // For journal quality proofs that these steps are complete, correct, and terminate see
20 // Hudson, R., and Moss, J.E.B. Copying Garbage Collection without stopping the world. 
21 // Concurrency and Computation: Practice and Experience 15(3-5), 2003. 
22 //
23 //  0. Set phase = GCscan from GCoff.
24 //  1. Wait for all P's to acknowledge phase change.
25 //         At this point all goroutines have passed through a GC safepoint and
26 //         know we are in the GCscan phase.
27 //  2. GC scans all goroutine stacks, mark and enqueues all encountered pointers
28 //       (marking avoids most duplicate enqueuing but races may produce duplication which is benign).
29 //       Preempted goroutines are scanned before P schedules next goroutine.
30 //  3. Set phase = GCmark.
31 //  4. Wait for all P's to acknowledge phase change.
32 //  5. Now write barrier marks and enqueues black or grey to white pointers. If a pointer is
33 //       stored into a white slot, such pointer is not marked.
34 //       Malloc still allocates white (non-marked) objects.
35 //  6. Meanwhile GC transitively walks the heap marking reachable objects.
36 //  7. When GC finishes marking heap, it preempts P's one-by-one and
37 //       retakes partial wbufs (filled by write barrier or during a stack scan of the goroutine
38 //       currently scheduled on the P).
39 //  8. Once the GC has exhausted all available marking work it sets phase = marktermination.
40 //  9. Wait for all P's to acknowledge phase change.
41 // 10. Malloc now allocates black objects, so number of unmarked reachable objects
42 //        monotonically decreases.
43 // 11. GC preempts P's one-by-one taking partial wbufs and marks all unmarked yet reachable objects.
44 // 12. When GC completes a full cycle over P's and discovers no new grey
45 //         objects, (which means all reachable objects are marked) set phase = GCsweep.
46 // 13. Wait for all P's to acknowledge phase change.
47 // 14. Now malloc allocates white (but sweeps spans before use).
48 //         Write barrier becomes nop.
49 // 15. GC does background sweeping, see description below.
50 // 16. When sweeping is complete set phase to GCoff.
51 // 17. When sufficient allocation has taken place replay the sequence starting at 0 above, 
52 //         see discussion of GC rate below.
53
54 // Changing phases.
55 // Phases are changed by setting the gcphase to the next phase and possibly calling ackgcphase.
56 // All phase action must be benign in the presence of a change.
57 // Starting with GCoff
58 // GCoff to GCscan
59 //     GSscan scans stacks and globals greying them and never marks an object black.
60 //     Once all the P's are aware of the new phase they will scan gs on preemption.
61 //     This means that the scanning of preempted gs can't start until all the Ps
62 //     have acknowledged.
63 // GCscan to GCmark
64 //     GCMark turns on the write barrier which also only greys objects. No scanning
65 //     of objects (making them black) can happen until all the Ps have acknowledged 
66 //     the phase change.
67 // GCmark to GCmarktermination
68 //     The only change here is that we start allocating black so the Ps must acknowledge
69 //     the change before we begin the termination algorithm
70 // GCmarktermination to GSsweep
71 //     Object currently on the freelist must be marked black for this to work. 
72 //     Are things on the free lists black or white? How does the sweep phase work?
73
74 // Concurrent sweep.
75 // The sweep phase proceeds concurrently with normal program execution.
76 // The heap is swept span-by-span both lazily (when a goroutine needs another span)
77 // and concurrently in a background goroutine (this helps programs that are not CPU bound).
78 // However, at the end of the stop-the-world GC phase we don't know the size of the live heap,
79 // and so next_gc calculation is tricky and happens as follows.
80 // At the end of the stop-the-world phase next_gc is conservatively set based on total
81 // heap size; all spans are marked as "needs sweeping".
82 // Whenever a span is swept, next_gc is decremented by GOGC*newly_freed_memory.
83 // The background sweeper goroutine simply sweeps spans one-by-one bringing next_gc
84 // closer to the target value. However, this is not enough to avoid over-allocating memory.
85 // Consider that a goroutine wants to allocate a new span for a large object and
86 // there are no free swept spans, but there are small-object unswept spans.
87 // If the goroutine naively allocates a new span, it can surpass the yet-unknown
88 // target next_gc value. In order to prevent such cases (1) when a goroutine needs
89 // to allocate a new small-object span, it sweeps small-object spans for the same
90 // object size until it frees at least one object; (2) when a goroutine needs to
91 // allocate large-object span from heap, it sweeps spans until it frees at least
92 // that many pages into heap. Together these two measures ensure that we don't surpass
93 // target next_gc value by a large margin. There is an exception: if a goroutine sweeps
94 // and frees two nonadjacent one-page spans to the heap, it will allocate a new two-page span,
95 // but there can still be other one-page unswept spans which could be combined into a two-page span.
96 // It's critical to ensure that no operations proceed on unswept spans (that would corrupt
97 // mark bits in GC bitmap). During GC all mcaches are flushed into the central cache,
98 // so they are empty. When a goroutine grabs a new span into mcache, it sweeps it.
99 // When a goroutine explicitly frees an object or sets a finalizer, it ensures that
100 // the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish).
101 // The finalizer goroutine is kicked off only when all spans are swept.
102 // When the next GC starts, it sweeps all not-yet-swept spans (if any).
103
104 // GC rate.
105 // Next GC is after we've allocated an extra amount of memory proportional to
106 // the amount already in use. The proportion is controlled by GOGC environment variable
107 // (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M
108 // (this mark is tracked in next_gc variable). This keeps the GC cost in linear 
109 // proportion to the allocation cost. Adjusting GOGC just changes the linear constant   
110 // (and also the amount of extra memory used).
111
112 #include "runtime.h"
113 #include "arch_GOARCH.h"
114 #include "malloc.h"
115 #include "stack.h"
116 #include "mgc0.h"
117 #include "chan.h"
118 #include "race.h"
119 #include "type.h"
120 #include "typekind.h"
121 #include "funcdata.h"
122 #include "textflag.h"
123
124 enum {
125         Debug           = 0,
126         ConcurrentSweep = 1,
127
128         FinBlockSize    = 4*1024,
129         RootData        = 0,
130         RootBss         = 1,
131         RootFinalizers  = 2,
132         RootSpans       = 3,
133         RootFlushCaches = 4,
134         RootCount       = 5,
135 };
136
137 // ptrmask for an allocation containing a single pointer.
138 static byte oneptr[] = {BitsPointer};
139
140 // Initialized from $GOGC.  GOGC=off means no GC.
141 extern int32 runtime·gcpercent;
142
143 // Holding worldsema grants an M the right to try to stop the world.
144 // The procedure is:
145 //
146 //      runtime·semacquire(&runtime·worldsema);
147 //      m->gcing = 1;
148 //      runtime·stoptheworld();
149 //
150 //      ... do stuff ...
151 //
152 //      m->gcing = 0;
153 //      runtime·semrelease(&runtime·worldsema);
154 //      runtime·starttheworld();
155 //
156 uint32 runtime·worldsema = 1;
157
158 typedef struct Markbits Markbits;
159 struct Markbits {
160         byte *bitp; // pointer to the byte holding xbits
161         byte shift; // bits xbits needs to be shifted to get bits
162         byte xbits; // byte holding all the bits from *bitp
163         byte bits;  // bits relevant to corresponding slot.
164 };
165
166 extern byte runtime·data[];
167 extern byte runtime·edata[];
168 extern byte runtime·bss[];
169 extern byte runtime·ebss[];
170
171 extern byte runtime·gcdata[];
172 extern byte runtime·gcbss[];
173
174 Mutex   runtime·finlock;       // protects the following variables
175 G*      runtime·fing;          // goroutine that runs finalizers
176 FinBlock*       runtime·finq;  // list of finalizers that are to be executed
177 FinBlock*       runtime·finc;  // cache of free blocks
178 static byte finptrmask[FinBlockSize/PtrSize/PointersPerByte];
179 bool    runtime·fingwait;
180 bool    runtime·fingwake;
181 FinBlock        *runtime·allfin;       // list of all blocks
182
183 BitVector       runtime·gcdatamask;
184 BitVector       runtime·gcbssmask;
185
186 Mutex   runtime·gclock;
187
188 static Workbuf* getpartialorempty(void);
189 static void     putpartial(Workbuf*);
190 static Workbuf* getempty(Workbuf*);
191 static Workbuf* getfull(Workbuf*);
192 static void     putempty(Workbuf*);
193 static void     putfull(Workbuf*);
194 static Workbuf* handoff(Workbuf*);
195 static void     gchelperstart(void);
196 static void     flushallmcaches(void);
197 static bool     scanframe(Stkframe*, void*);
198 static void     scanstack(G*);
199 static BitVector        unrollglobgcprog(byte*, uintptr);
200 static void     scanblock(byte*, uintptr, byte*);
201 static byte*    objectstart(byte*, Markbits*);
202 static Workbuf* greyobject(byte*, Markbits*, Workbuf*);
203 static bool     inheap(byte*);
204 static bool     shaded(byte*);
205 static void     shade(byte*);
206 static void     slottombits(byte*, Markbits*);
207
208 void runtime·bgsweep(void);
209 void runtime·finishsweep_m(void);
210 static FuncVal bgsweepv = {runtime·bgsweep};
211
212 typedef struct WorkData WorkData;
213 struct WorkData {
214         uint64  full;    // lock-free list of full blocks
215         uint64  empty;   // lock-free list of empty blocks
216         uint64  partial; // lock-free list of partially filled blocks
217         byte    pad0[CacheLineSize]; // prevents false-sharing between full/empty and nproc/nwait
218         uint32  nproc;
219         int64   tstart;
220         volatile uint32 nwait;
221         volatile uint32 ndone;
222         Note    alldone;
223         ParFor* markfor;
224
225         // Copy of mheap.allspans for marker or sweeper.
226         MSpan** spans;
227         uint32  nspan;
228 };
229 WorkData runtime·work;
230
231 // Is address b in the known heap. If it doesn't have a valid gcmap
232 // returns false. For example pointers into stacks will return false.
233 static bool
234 inheap(byte *b)
235 {
236         MSpan *s;
237         pageID k;
238         uintptr x;
239
240         if(b == nil || b < runtime·mheap.arena_start || b >= runtime·mheap.arena_used)
241                 return false;
242         // Not a beginning of a block, consult span table to find the block beginning.
243         k = (uintptr)b>>PageShift;
244         x = k;
245         x -= (uintptr)runtime·mheap.arena_start>>PageShift;
246         s = runtime·mheap.spans[x];
247         if(s == nil || k < s->start || b >= s->limit || s->state != MSpanInUse)
248                 return false;
249         return true;
250 }
251
252 // Given an address in the heap return the relevant byte from the gcmap. This routine
253 // can be used on addresses to the start of an object or to the interior of the an object.
254 static void
255 slottombits(byte *obj, Markbits *mbits)
256 {
257         uintptr off;
258
259         off = (uintptr*)((uintptr)obj&~(PtrSize-1)) - (uintptr*)runtime·mheap.arena_start;
260         mbits->bitp = runtime·mheap.arena_start - off/wordsPerBitmapByte - 1;
261         mbits->shift = (off % wordsPerBitmapByte) * gcBits;
262         mbits->xbits = *mbits->bitp;
263         mbits->bits = (mbits->xbits >> mbits->shift) & bitMask;
264 }
265
266 // b is a pointer into the heap.
267 // Find the start of the object refered to by b.
268 // Set mbits to the associated bits from the bit map.
269 static byte*
270 objectstart(byte *b, Markbits *mbits)
271 {
272         byte *obj, *p;
273         MSpan *s;
274         pageID k;
275         uintptr x, size, idx;
276
277         obj = (byte*)((uintptr)b&~(PtrSize-1));
278         for(;;) {
279                 slottombits(obj, mbits);
280                 if(mbits->bits&bitBoundary == bitBoundary)
281                         break;
282                 
283                 // Not a beginning of a block, consult span table to find the block beginning.
284                 k = (uintptr)obj>>PageShift;
285                 x = k;
286                 x -= (uintptr)runtime·mheap.arena_start>>PageShift;
287                 s = runtime·mheap.spans[x];
288                 if(s == nil || k < s->start || obj >= s->limit || s->state != MSpanInUse){
289                         if(s->state == MSpanStack)
290                                 break; // This is legit.
291
292                         // The following is catching some bugs left over from
293                         // us not being rigerous about what data structures are
294                         // hold valid pointers and different parts of the system
295                         // considering different structures as roots. For example
296                         // if there is a pointer into a stack that is left in 
297                         // a global data structure but that part of the runtime knows that 
298                         // those structures will be reinitialized before they are 
299                         // reused. Unfortunately the GC believes these roots are valid.
300                         // Typically a stack gets moved and only the structures that part of
301                         // the system knows are alive are updated. The span is freed
302                         // after the stack copy and the pointer is still alive. This 
303                         // check is catching that bug but for now we will not throw, 
304                         // instead we will simply break out of this routine and depend
305                         // on the caller to recognize that this pointer is not a valid 
306                         // heap pointer. I leave the code that catches the bug so that once
307                         // resolved we can turn this check back on and throw.
308
309                         //runtime·printf("Runtime: Span weird: obj=%p, k=%p", obj, k);
310                         //if (s == nil)
311                         //      runtime·printf(" s=nil\n");
312                         //else
313                         //      runtime·printf(" s->start=%p s->limit=%p, s->state=%d\n", s->start*PageSize, s->limit, s->state);
314                         //runtime·throw("Blowup on weird span");
315                         break; // We are not in a real block throw??
316                 }
317                 p = (byte*)((uintptr)s->start<<PageShift);
318                 if(s->sizeclass != 0) {
319                         size = s->elemsize;
320                         idx = ((byte*)obj - p)/size;
321                         p = p+idx*size;
322                 }
323                 if(p == obj) {
324                         runtime·printf("runtime: failed to find block beginning for %p s=%p s->limit=%p\n",
325                                        p, s->start*PageSize, s->limit);
326                         runtime·throw("failed to find block beginning");
327                 }
328                 obj = p;
329         }
330         // if size(obj.firstfield) < PtrSize, the &obj.secondfield could map to the boundary bit
331         // Clear any low bits to get to the start of the object.
332         // greyobject depends on this.
333         return obj;
334 }
335
336 // obj is the start of an object with mark mbits.
337 // If it isn't already marked, mark it and enqueue into workbuf.
338 // Return possibly new workbuf to use.
339 static Workbuf*
340 greyobject(byte *obj, Markbits *mbits, Workbuf *wbuf) 
341 {
342         // obj should be start of allocation, and so must be at least pointer-aligned.
343         if(((uintptr)obj & (PtrSize-1)) != 0)
344                 runtime·throw("greyobject: obj not pointer-aligned");
345
346         // If marked we have nothing to do.
347         if((mbits->bits&bitMarked) != 0)
348                 return wbuf;
349
350         // Each byte of GC bitmap holds info for two words.
351         // If the current object is larger than two words, or if the object is one word
352         // but the object it shares the byte with is already marked,
353         // then all the possible concurrent updates are trying to set the same bit,
354         // so we can use a non-atomic update.
355         if((mbits->xbits&(bitMask|(bitMask<<gcBits))) != (bitBoundary|(bitBoundary<<gcBits)) || runtime·work.nproc == 1)
356                 *mbits->bitp = mbits->xbits | (bitMarked<<mbits->shift);
357         else
358                 runtime·atomicor8(mbits->bitp, bitMarked<<mbits->shift);
359         
360         if(((mbits->xbits>>(mbits->shift+2))&BitsMask) == BitsDead)
361                 return wbuf;  // noscan object
362
363         // Queue the obj for scanning. The PREFETCH(obj) logic has been removed but
364         // seems like a nice optimization that can be added back in.
365         // There needs to be time between the PREFETCH and the use.
366         // Previously we put the obj in an 8 element buffer that is drained at a rate
367         // to give the PREFETCH time to do its work.
368         // Use of PREFETCHNTA might be more appropriate than PREFETCH
369
370         // If workbuf is full, obtain an empty one.
371         if(wbuf->nobj >= nelem(wbuf->obj)) {
372                 wbuf = getempty(wbuf);
373         }
374
375         wbuf->obj[wbuf->nobj] = obj;
376         wbuf->nobj++;
377         return wbuf;                    
378 }
379
380 // Scan the object b of size n, adding pointers to wbuf.
381 // Return possibly new wbuf to use.
382 // If ptrmask != nil, it specifies where pointers are in b.
383 // If ptrmask == nil, the GC bitmap should be consulted.
384 // In this case, n may be an overestimate of the size; the GC bitmap
385 // must also be used to make sure the scan stops at the end of b.
386 static Workbuf*
387 scanobject(byte *b, uintptr n, byte *ptrmask, Workbuf *wbuf)
388 {
389         byte *obj, *arena_start, *arena_used, *ptrbitp;
390         uintptr i, j;
391         int32 bits;
392         Markbits mbits;
393
394         arena_start = (byte*)runtime·mheap.arena_start;
395         arena_used = runtime·mheap.arena_used;
396         ptrbitp = nil;
397
398         // Find bits of the beginning of the object.
399         if(ptrmask == nil) {
400                 b = objectstart(b, &mbits);
401                 ptrbitp = mbits.bitp; //arena_start - off/wordsPerBitmapByte - 1;
402         }
403         for(i = 0; i < n; i += PtrSize) {
404                 // Find bits for this word.
405                 if(ptrmask != nil) {
406                         // dense mask (stack or data)
407                         bits = (ptrmask[(i/PtrSize)/4]>>(((i/PtrSize)%4)*BitsPerPointer))&BitsMask;
408                 } else {
409                         // Check if we have reached end of span.
410                         if((((uintptr)b+i)%PageSize) == 0 &&
411                                 runtime·mheap.spans[(b-arena_start)>>PageShift] != runtime·mheap.spans[(b+i-arena_start)>>PageShift])
412                                 break;
413                         // Consult GC bitmap.
414                         bits = *ptrbitp;
415                         if(wordsPerBitmapByte != 2)
416                                 runtime·throw("alg doesn't work for wordsPerBitmapByte != 2");
417                         j = ((uintptr)b+i)/PtrSize & 1;
418                         bits >>= gcBits*j;
419                         if(i == 0)
420                                 bits &= ~bitBoundary;
421                         ptrbitp -= j;
422                 
423                         if((bits&bitBoundary) != 0 && i != 0)
424                                 break; // reached beginning of the next object
425                         bits = (bits>>2)&BitsMask;
426                         if(bits == BitsDead)
427                                 break; // reached no-scan part of the object
428                 } 
429
430                 if(bits <= BitsScalar) // Bits Scalar || BitsDead
431                         continue;
432                 if(bits != BitsPointer) {
433                         runtime·printf("gc bits=%x\n", bits);
434                         runtime·throw("unexpected garbage collection bits");
435                 }
436
437                 obj = *(byte**)(b+i);
438                 // At this point we have extracted the next potential pointer.
439                 // Check if it points into heap.
440                 if(obj == nil || obj < arena_start || obj >= arena_used)
441                         continue;
442                 // Mark the object. return some important bits.
443                 // We we combine the following two rotines we don't have to pass mbits or obj around.
444                 obj = objectstart(obj, &mbits);
445                 wbuf = greyobject(obj, &mbits, wbuf);
446         }
447         return wbuf;
448 }
449
450 // scanblock starts by scanning b as scanobject would.
451 // If the gcphase is GCscan, that's all scanblock does.
452 // Otherwise it traverses some fraction of the pointers it found in b, recursively.
453 // As a special case, scanblock(nil, 0, nil) means to scan previously queued work,
454 // stopping only when no work is left in the system.
455 static void
456 scanblock(byte *b, uintptr n, byte *ptrmask)
457 {
458         Workbuf *wbuf;
459         bool keepworking;
460
461         wbuf = getpartialorempty();
462         if(b != nil) {
463                 wbuf = scanobject(b, n, ptrmask, wbuf);
464                 if(runtime·gcphase == GCscan) {
465                         if(inheap(b) && !ptrmask)
466                                 // b is in heap, we are in GCscan so there should be a ptrmask.
467                                 runtime·throw("scanblock: In GCscan phase and inheap is true.");
468                         // GCscan only goes one level deep since mark wb not turned on.
469                         putpartial(wbuf);
470                         return;
471                 }
472         }
473         if(runtime·gcphase == GCscan) {
474                 runtime·throw("scanblock: In GCscan phase but no b passed in.");
475         }
476         
477         keepworking = b == nil;
478
479         // ptrmask can have 2 possible values:
480         // 1. nil - obtain pointer mask from GC bitmap.
481         // 2. pointer to a compact mask (for stacks and data).
482         for(;;) {
483                 if(wbuf->nobj == 0) {
484                         if(!keepworking) {
485                                 putempty(wbuf);
486                                 return;
487                         }
488                         // Refill workbuf from global queue.
489                         wbuf = getfull(wbuf);
490                         if(wbuf == nil) // nil means out of work barrier reached
491                                 return;
492
493                         if(wbuf->nobj<=0) {
494                                 runtime·throw("runtime:scanblock getfull returns empty buffer");
495                         }
496
497                 }
498
499                 // If another proc wants a pointer, give it some.
500                 if(runtime·work.nwait > 0 && wbuf->nobj > 4 && runtime·work.full == 0) {
501                         wbuf = handoff(wbuf);
502                 }
503
504                 // This might be a good place to add prefetch code...
505                 // if(wbuf->nobj > 4) {
506                 //         PREFETCH(wbuf->obj[wbuf->nobj - 3];
507                 //  }
508                 --wbuf->nobj;
509                 b = wbuf->obj[wbuf->nobj];
510                 wbuf = scanobject(b, runtime·mheap.arena_used - b, nil, wbuf);
511         }
512 }
513
514 static void
515 markroot(ParFor *desc, uint32 i)
516 {
517         FinBlock *fb;
518         MSpan *s;
519         uint32 spanidx, sg;
520         G *gp;
521         void *p;
522         uint32 status;
523         bool restart;
524  
525         USED(&desc);
526         // Note: if you add a case here, please also update heapdump.c:dumproots.
527         switch(i) {
528         case RootData:
529                 scanblock(runtime·data, runtime·edata - runtime·data, runtime·gcdatamask.bytedata);
530                 break;
531
532         case RootBss:
533                 scanblock(runtime·bss, runtime·ebss - runtime·bss, runtime·gcbssmask.bytedata);
534                 break;
535
536         case RootFinalizers:
537                 for(fb=runtime·allfin; fb; fb=fb->alllink)
538                         scanblock((byte*)fb->fin, fb->cnt*sizeof(fb->fin[0]), finptrmask);
539                 break;
540
541         case RootSpans:
542                 // mark MSpan.specials
543                 sg = runtime·mheap.sweepgen;
544                 for(spanidx=0; spanidx<runtime·work.nspan; spanidx++) {
545                         Special *sp;
546                         SpecialFinalizer *spf;
547
548                         s = runtime·work.spans[spanidx];
549                         if(s->state != MSpanInUse)
550                                 continue;
551                         if(s->sweepgen != sg) {
552                                 runtime·printf("sweep %d %d\n", s->sweepgen, sg);
553                                 runtime·throw("gc: unswept span");
554                         }
555                         for(sp = s->specials; sp != nil; sp = sp->next) {
556                                 if(sp->kind != KindSpecialFinalizer)
557                                         continue;
558                                 // don't mark finalized object, but scan it so we
559                                 // retain everything it points to.
560                                 spf = (SpecialFinalizer*)sp;
561                                 // A finalizer can be set for an inner byte of an object, find object beginning.
562                                 p = (void*)((s->start << PageShift) + spf->special.offset/s->elemsize*s->elemsize);
563                                 if(runtime·gcphase != GCscan)
564                                         scanblock(p, s->elemsize, nil); // Scanned during mark phase
565                                 scanblock((void*)&spf->fn, PtrSize, oneptr);
566                         }
567                 }
568                 break;
569
570         case RootFlushCaches:
571                 if (runtime·gcphase != GCscan) // Do not flush mcaches during GCscan phase.
572                         flushallmcaches();
573                 break;
574
575         default:
576                 // the rest is scanning goroutine stacks
577                 if(i - RootCount >= runtime·allglen)
578                         runtime·throw("markroot: bad index");
579                 gp = runtime·allg[i - RootCount];
580                 // remember when we've first observed the G blocked
581                 // needed only to output in traceback
582                 status = runtime·readgstatus(gp); // We are not in a scan state
583                 if((status == Gwaiting || status == Gsyscall) && gp->waitsince == 0)
584                         gp->waitsince = runtime·work.tstart;
585                 // Shrink a stack if not much of it is being used but not in the scan phase.
586                 if (runtime·gcphase != GCscan) // Do not shrink during GCscan phase.
587                         runtime·shrinkstack(gp);
588                 if(runtime·readgstatus(gp) == Gdead)
589                         gp->gcworkdone = true;
590                 else 
591                         gp->gcworkdone = false; 
592                 restart = runtime·stopg(gp);
593
594                 // goroutine will scan its own stack when it stops running.
595                 // Wait until it has.
596                 while(runtime·readgstatus(gp) == Grunning && !gp->gcworkdone) {
597                 }
598
599                 // scanstack(gp) is done as part of gcphasework
600                 // But to make sure we finished we need to make sure that
601                 // the stack traps have all responded so drop into
602                 // this while loop until they respond.
603                 while(!gp->gcworkdone){
604                         status = runtime·readgstatus(gp);
605                         if(status == Gdead) {
606                                 gp->gcworkdone = true; // scan is a noop
607                                 break;
608                                 //do nothing, scan not needed. 
609                         }
610                         if(status == Gwaiting || status == Grunnable)
611                                 restart = runtime·stopg(gp);
612                 }
613                 if(restart)
614                         runtime·restartg(gp);
615                 break;
616         }
617 }
618
619 // wblock is used for creating new empty work buffer blocks.
620 static Mutex wblock;
621
622 // Get an empty work buffer off the work.empty list,
623 // allocating new buffers as needed.
624 static Workbuf*
625 getempty(Workbuf *b)
626 {
627         if(b != nil) {
628                 putfull(b);
629                 b = nil;
630         }
631         if(runtime·work.empty)
632                 b = (Workbuf*)runtime·lfstackpop(&runtime·work.empty);
633
634         if(b && b->nobj != 0) {
635                 runtime·printf("m%d: getempty: popped b=%p with non-zero b->nobj=%d\n", g->m->id, b, (uint32)b->nobj);
636                 runtime·throw("getempty: workbuffer not empty, b->nobj not 0");
637         }
638         if(b == nil) {
639                 runtime·lock(&wblock);
640                 b = runtime·persistentalloc(sizeof(*b), CacheLineSize, &mstats.gc_sys);
641                 b->nobj = 0;
642                 runtime·unlock(&wblock);
643         }
644         return b;
645 }
646
647 static void
648 putempty(Workbuf *b)
649 {
650         if(b->nobj != 0) {
651                 runtime·throw("putempty: b->nobj not 0\n");
652         }
653         runtime·lfstackpush(&runtime·work.empty, &b->node);
654 }
655
656 // Put a full or partially full workbuf on the full list.
657 static void
658 putfull(Workbuf *b)
659 {
660         if(b->nobj <= 0) {
661                 runtime·throw("putfull: b->nobj <= 0\n");
662         }
663         runtime·lfstackpush(&runtime·work.full, &b->node);
664 }
665
666 // Get an partially empty work buffer
667 // if none are available get an empty one.
668 static Workbuf*
669 getpartialorempty(void)
670 {
671         Workbuf *b;
672
673         b = (Workbuf*)runtime·lfstackpop(&runtime·work.partial);
674         if(b == nil)
675                 b = getempty(nil);
676         return b;
677 }
678
679 static void
680 putpartial(Workbuf *b)
681 {
682
683         if(b->nobj == 0)
684                 runtime·lfstackpush(&runtime·work.empty, &b->node);
685         else if (b->nobj < nelem(b->obj))
686                 runtime·lfstackpush(&runtime·work.partial, &b->node);
687         else if (b->nobj == nelem(b->obj))
688                 runtime·lfstackpush(&runtime·work.full, &b->node);
689         else {
690                 runtime·printf("b=%p, b->nobj=%d, nelem(b->obj)=%d\n", b, (uint32)b->nobj, (uint32)nelem(b->obj));
691                 runtime·throw("putpartial: bad Workbuf b->nobj");
692         }
693 }
694
695 void
696 runtime·gcworkbuffree(Workbuf *b)
697 {
698         if(b == nil)
699                 return;
700         if(b->nobj == 0)
701                 putempty(b);
702         else
703                 putfull(b);
704 }
705
706 // Get a full work buffer off the work.full or a partially
707 // filled one off the work.partial list. If nothing is available
708 // wait until all the other gc helpers have finished and then
709 // return nil.
710 // getfull acts as a barrier for work.nproc helpers. As long as one
711 // gchelper is actively marking objects it
712 // may create a workbuffer that the other helpers can work on.
713 // The for loop either exits when a work buffer is found
714 // or when _all_ of the work.nproc GC helpers are in the loop 
715 // looking for work and thus not capable of creating new work.
716 // This is in fact the termination condition for the STW mark 
717 // phase.
718 static Workbuf*
719 getfull(Workbuf *b)
720 {
721         int32 i;
722
723         if(b != nil)
724                 putempty(b);
725
726         b = (Workbuf*)runtime·lfstackpop(&runtime·work.full);
727         if(b==nil)
728                 b = (Workbuf*)runtime·lfstackpop(&runtime·work.partial);
729         if(b != nil || runtime·work.nproc == 1)
730                 return b;
731
732         runtime·xadd(&runtime·work.nwait, +1);
733         for(i=0;; i++) {
734                 if(runtime·work.full != 0) {
735                         runtime·xadd(&runtime·work.nwait, -1);
736                         b = (Workbuf*)runtime·lfstackpop(&runtime·work.full);
737                         if(b==nil)
738                                 b = (Workbuf*)runtime·lfstackpop(&runtime·work.partial);
739                         if(b != nil) 
740                                 return b;
741                         runtime·xadd(&runtime·work.nwait, +1);
742                 }
743                 if(runtime·work.nwait == runtime·work.nproc)
744                         return nil;
745                 if(i < 10) {
746                         g->m->gcstats.nprocyield++;
747                         runtime·procyield(20);
748                 } else if(i < 20) {
749                         g->m->gcstats.nosyield++;
750                         runtime·osyield();
751                 } else {
752                         g->m->gcstats.nsleep++;
753                         runtime·usleep(100);
754                 }
755         }
756 }
757
758 static Workbuf*
759 handoff(Workbuf *b)
760 {
761         int32 n;
762         Workbuf *b1;
763
764         // Make new buffer with half of b's pointers.
765         b1 = getempty(nil);
766         n = b->nobj/2;
767         b->nobj -= n;
768         b1->nobj = n;
769         runtime·memmove(b1->obj, b->obj+b->nobj, n*sizeof b1->obj[0]);
770         g->m->gcstats.nhandoff++;
771         g->m->gcstats.nhandoffcnt += n;
772
773         // Put b on full list - let first half of b get stolen.
774         runtime·lfstackpush(&runtime·work.full, &b->node);
775         return b1;
776 }
777
778 BitVector
779 runtime·stackmapdata(StackMap *stackmap, int32 n)
780 {
781         if(n < 0 || n >= stackmap->n)
782                 runtime·throw("stackmapdata: index out of range");
783         return (BitVector){stackmap->nbit, stackmap->bytedata + n*((stackmap->nbit+31)/32*4)};
784 }
785
786 // Scan a stack frame: local variables and function arguments/results.
787 static bool
788 scanframe(Stkframe *frame, void *unused)
789 {
790         Func *f;
791         StackMap *stackmap;
792         BitVector bv;
793         uintptr size, minsize;
794         uintptr targetpc;
795         int32 pcdata;
796
797         USED(unused);
798         f = frame->fn;
799         targetpc = frame->continpc;
800         if(targetpc == 0) {
801                 // Frame is dead.
802                 return true;
803         }
804         if(Debug > 1)
805                 runtime·printf("scanframe %s\n", runtime·funcname(f));
806         if(targetpc != f->entry)
807                 targetpc--;
808         pcdata = runtime·pcdatavalue(f, PCDATA_StackMapIndex, targetpc);
809         if(pcdata == -1) {
810                 // We do not have a valid pcdata value but there might be a
811                 // stackmap for this function.  It is likely that we are looking
812                 // at the function prologue, assume so and hope for the best.
813                 pcdata = 0;
814         }
815
816         // Scan local variables if stack frame has been allocated.
817         size = frame->varp - frame->sp;
818         if(thechar != '6' && thechar != '8')
819                 minsize = sizeof(uintptr);
820         else
821                 minsize = 0;
822         if(size > minsize) {
823                 stackmap = runtime·funcdata(f, FUNCDATA_LocalsPointerMaps);
824                 if(stackmap == nil || stackmap->n <= 0) {
825                         runtime·printf("runtime: frame %s untyped locals %p+%p\n", runtime·funcname(f), (byte*)(frame->varp-size), size);
826                         runtime·throw("missing stackmap");
827                 }
828
829                 // Locals bitmap information, scan just the pointers in locals.
830                 if(pcdata < 0 || pcdata >= stackmap->n) {
831                         // don't know where we are
832                         runtime·printf("runtime: pcdata is %d and %d locals stack map entries for %s (targetpc=%p)\n",
833                                 pcdata, stackmap->n, runtime·funcname(f), targetpc);
834                         runtime·throw("scanframe: bad symbol table");
835                 }
836                 bv = runtime·stackmapdata(stackmap, pcdata);
837                 size = (bv.n * PtrSize) / BitsPerPointer;
838                 scanblock((byte*)(frame->varp - size), bv.n/BitsPerPointer*PtrSize, bv.bytedata);
839         }
840
841         // Scan arguments.
842         if(frame->arglen > 0) {
843                 if(frame->argmap != nil)
844                         bv = *frame->argmap;
845                 else {
846                         stackmap = runtime·funcdata(f, FUNCDATA_ArgsPointerMaps);
847                         if(stackmap == nil || stackmap->n <= 0) {
848                                 runtime·printf("runtime: frame %s untyped args %p+%p\n", runtime·funcname(f), frame->argp, (uintptr)frame->arglen);
849                                 runtime·throw("missing stackmap");
850                         }
851                         if(pcdata < 0 || pcdata >= stackmap->n) {
852                                 // don't know where we are
853                                 runtime·printf("runtime: pcdata is %d and %d args stack map entries for %s (targetpc=%p)\n",
854                                         pcdata, stackmap->n, runtime·funcname(f), targetpc);
855                                 runtime·throw("scanframe: bad symbol table");
856                         }
857                         bv = runtime·stackmapdata(stackmap, pcdata);
858                 }
859                 scanblock((byte*)frame->argp, bv.n/BitsPerPointer*PtrSize, bv.bytedata);
860         }
861         return true;
862 }
863
864 static void
865 scanstack(G *gp)
866 {
867         M *mp;
868         bool (*fn)(Stkframe*, void*);
869
870         if(runtime·readgstatus(gp)&Gscan == 0) {
871                 runtime·printf("runtime: gp=%p, goid=%D, gp->atomicstatus=%d\n", gp, gp->goid, runtime·readgstatus(gp));
872                 runtime·throw("mark - bad status");
873         }
874
875         switch(runtime·readgstatus(gp)&~Gscan) {
876         default:
877                 runtime·printf("runtime: gp=%p, goid=%D, gp->atomicstatus=%d\n", gp, gp->goid, runtime·readgstatus(gp));
878                 runtime·throw("mark - bad status");
879         case Gdead:
880                 return;
881         case Grunning:
882                 runtime·throw("scanstack: - goroutine not stopped");
883         case Grunnable:
884         case Gsyscall:
885         case Gwaiting:
886                 break;
887         }
888
889         if(gp == g)
890                 runtime·throw("can't scan our own stack");
891         if((mp = gp->m) != nil && mp->helpgc)
892                 runtime·throw("can't scan gchelper stack");
893
894         fn = scanframe;
895         runtime·gentraceback(~(uintptr)0, ~(uintptr)0, 0, gp, 0, nil, 0x7fffffff, &fn, nil, false);
896         runtime·tracebackdefers(gp, &fn, nil);
897 }
898
899 // If the slot is grey or black return true, if white return false.
900 // If the slot is not in the known heap and thus does not have a valid GC bitmap then
901 // it is considered grey. Globals and stacks can hold such slots.
902 // The slot is grey if its mark bit is set and it is enqueued to be scanned.
903 // The slot is black if it has already been scanned.
904 // It is white if it has a valid mark bit and the bit is not set. 
905 static bool
906 shaded(byte *slot)
907 {
908         Markbits mbits;
909
910         if(!inheap(slot)) // non-heap slots considered grey
911                 return true;
912
913         objectstart(slot, &mbits);
914         return (mbits.bits&bitMarked) != 0;
915 }
916
917 // Shade the object if it isn't already.
918 // The object is not nil and known to be in the heap.
919 static void
920 shade(byte *b)
921 {
922         byte *obj;
923         Workbuf *wbuf;
924         Markbits mbits;
925         
926         if(!inheap(b))
927                 runtime·throw("shade: passed an address not in the heap");
928         
929         wbuf = getpartialorempty();
930         // Mark the object, return some important bits.
931         // If we combine the following two rotines we don't have to pass mbits or obj around.
932         obj = objectstart(b, &mbits);
933         wbuf = greyobject(obj, &mbits, wbuf); // augments the wbuf
934         putpartial(wbuf);
935         return;
936 }
937
938 // This is the Dijkstra barrier coarsened to shade grey to white whereas
939 // the original Dijkstra barrier only shaded black to white.
940 //
941 // Shade indicates that it has seen a white pointer by adding the referent
942 // to wbuf.
943 void
944 runtime·markwb(void **slot, void *ptr)
945 {
946         // initial nil check avoids some needlesss loads
947         if(ptr != nil && inheap(ptr) && shaded((void*)slot))
948                 shade(ptr);
949         *slot = ptr;
950 }
951
952 // The gp has been moved to a GC safepoint. GC phase specific
953 // work is done here. 
954 void
955 runtime·gcphasework(G *gp)
956 {
957         switch(runtime·gcphase) {
958         default:
959                 runtime·throw("gcphasework in bad gcphase");
960         case GCoff:
961         case GCquiesce:
962         case GCstw:
963         case GCsweep:
964                 // No work.
965                 break;
966         case GCscan:
967                 // scan the stack, mark the objects, put pointers in work buffers
968                 // hanging off the P where this is being run.
969                 scanstack(gp);
970                 break;
971         case GCmark:
972         case GCmarktermination:
973                 scanstack(gp);
974                 // All available mark work will be emptied before returning.
975                 break;
976         }
977         gp->gcworkdone = true;
978 }
979
980 #pragma dataflag NOPTR
981 static byte finalizer1[] = {
982         // Each Finalizer is 5 words, ptr ptr uintptr ptr ptr.
983         // Each byte describes 4 words.
984         // Need 4 Finalizers described by 5 bytes before pattern repeats:
985         //      ptr ptr uintptr ptr ptr
986         //      ptr ptr uintptr ptr ptr
987         //      ptr ptr uintptr ptr ptr
988         //      ptr ptr uintptr ptr ptr
989         // aka
990         //      ptr ptr uintptr ptr
991         //      ptr ptr ptr uintptr
992         //      ptr ptr ptr ptr
993         //      uintptr ptr ptr ptr
994         //      ptr uintptr ptr ptr
995         // Assumptions about Finalizer layout checked below.
996         BitsPointer | BitsPointer<<2 | BitsScalar<<4 | BitsPointer<<6,
997         BitsPointer | BitsPointer<<2 | BitsPointer<<4 | BitsScalar<<6,
998         BitsPointer | BitsPointer<<2 | BitsPointer<<4 | BitsPointer<<6,
999         BitsScalar | BitsPointer<<2 | BitsPointer<<4 | BitsPointer<<6,
1000         BitsPointer | BitsScalar<<2 | BitsPointer<<4 | BitsPointer<<6,
1001 };
1002
1003 void
1004 runtime·queuefinalizer(byte *p, FuncVal *fn, uintptr nret, Type *fint, PtrType *ot)
1005 {
1006         FinBlock *block;
1007         Finalizer *f;
1008         int32 i;
1009
1010         runtime·lock(&runtime·finlock);
1011         if(runtime·finq == nil || runtime·finq->cnt == runtime·finq->cap) {
1012                 if(runtime·finc == nil) {
1013                         runtime·finc = runtime·persistentalloc(FinBlockSize, 0, &mstats.gc_sys);
1014                         runtime·finc->cap = (FinBlockSize - sizeof(FinBlock)) / sizeof(Finalizer) + 1;
1015                         runtime·finc->alllink = runtime·allfin;
1016                         runtime·allfin = runtime·finc;
1017                         if(finptrmask[0] == 0) {
1018                                 // Build pointer mask for Finalizer array in block.
1019                                 // Check assumptions made in finalizer1 array above.
1020                                 if(sizeof(Finalizer) != 5*PtrSize ||
1021                                         offsetof(Finalizer, fn) != 0 ||
1022                                         offsetof(Finalizer, arg) != PtrSize ||
1023                                         offsetof(Finalizer, nret) != 2*PtrSize ||
1024                                         offsetof(Finalizer, fint) != 3*PtrSize ||
1025                                         offsetof(Finalizer, ot) != 4*PtrSize ||
1026                                         BitsPerPointer != 2) {
1027                                         runtime·throw("finalizer out of sync");
1028                                 }
1029                                 for(i=0; i<nelem(finptrmask); i++)
1030                                         finptrmask[i] = finalizer1[i%nelem(finalizer1)];
1031                         }
1032                 }
1033                 block = runtime·finc;
1034                 runtime·finc = block->next;
1035                 block->next = runtime·finq;
1036                 runtime·finq = block;
1037         }
1038         f = &runtime·finq->fin[runtime·finq->cnt];
1039         runtime·finq->cnt++;
1040         f->fn = fn;
1041         f->nret = nret;
1042         f->fint = fint;
1043         f->ot = ot;
1044         f->arg = p;
1045         runtime·fingwake = true;
1046         runtime·unlock(&runtime·finlock);
1047 }
1048
1049 void
1050 runtime·iterate_finq(void (*callback)(FuncVal*, byte*, uintptr, Type*, PtrType*))
1051 {
1052         FinBlock *fb;
1053         Finalizer *f;
1054         uintptr i;
1055
1056         for(fb = runtime·allfin; fb; fb = fb->alllink) {
1057                 for(i = 0; i < fb->cnt; i++) {
1058                         f = &fb->fin[i];
1059                         callback(f->fn, f->arg, f->nret, f->fint, f->ot);
1060                 }
1061         }
1062 }
1063
1064 // Returns only when span s has been swept.
1065 void
1066 runtime·MSpan_EnsureSwept(MSpan *s)
1067 {
1068         uint32 sg;
1069
1070         // Caller must disable preemption.
1071         // Otherwise when this function returns the span can become unswept again
1072         // (if GC is triggered on another goroutine).
1073         if(g->m->locks == 0 && g->m->mallocing == 0 && g != g->m->g0)
1074                 runtime·throw("MSpan_EnsureSwept: m is not locked");
1075
1076         sg = runtime·mheap.sweepgen;
1077         if(runtime·atomicload(&s->sweepgen) == sg)
1078                 return;
1079         // The caller must be sure that the span is a MSpanInUse span.
1080         if(runtime·cas(&s->sweepgen, sg-2, sg-1)) {
1081                 runtime·MSpan_Sweep(s, false);
1082                 return;
1083         }
1084         // unfortunate condition, and we don't have efficient means to wait
1085         while(runtime·atomicload(&s->sweepgen) != sg)
1086                 runtime·osyield();
1087 }
1088
1089 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
1090 // It clears the mark bits in preparation for the next GC round.
1091 // Returns true if the span was returned to heap.
1092 // If preserve=true, don't return it to heap nor relink in MCentral lists;
1093 // caller takes care of it.
1094 bool
1095 runtime·MSpan_Sweep(MSpan *s, bool preserve)
1096 {
1097         int32 cl, n, npages, nfree;
1098         uintptr size, off, step;
1099         uint32 sweepgen;
1100         byte *p, *bitp, shift, xbits, bits;
1101         MCache *c;
1102         byte *arena_start;
1103         MLink head, *end, *link;
1104         Special *special, **specialp, *y;
1105         bool res, sweepgenset;
1106
1107         // It's critical that we enter this function with preemption disabled,
1108         // GC must not start while we are in the middle of this function.
1109         if(g->m->locks == 0 && g->m->mallocing == 0 && g != g->m->g0)
1110                 runtime·throw("MSpan_Sweep: m is not locked");
1111         sweepgen = runtime·mheap.sweepgen;
1112         if(s->state != MSpanInUse || s->sweepgen != sweepgen-1) {
1113                 runtime·printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1114                         s->state, s->sweepgen, sweepgen);
1115                 runtime·throw("MSpan_Sweep: bad span state");
1116         }
1117         arena_start = runtime·mheap.arena_start;
1118         cl = s->sizeclass;
1119         size = s->elemsize;
1120         if(cl == 0) {
1121                 n = 1;
1122         } else {
1123                 // Chunk full of small blocks.
1124                 npages = runtime·class_to_allocnpages[cl];
1125                 n = (npages << PageShift) / size;
1126         }
1127         res = false;
1128         nfree = 0;
1129         end = &head;
1130         c = g->m->mcache;
1131         sweepgenset = false;
1132
1133         // Mark any free objects in this span so we don't collect them.
1134         for(link = s->freelist; link != nil; link = link->next) {
1135                 off = (uintptr*)link - (uintptr*)arena_start;
1136                 bitp = arena_start - off/wordsPerBitmapByte - 1;
1137                 shift = (off % wordsPerBitmapByte) * gcBits;
1138                 *bitp |= bitMarked<<shift;
1139         }
1140
1141         // Unlink & free special records for any objects we're about to free.
1142         specialp = &s->specials;
1143         special = *specialp;
1144         while(special != nil) {
1145                 // A finalizer can be set for an inner byte of an object, find object beginning.
1146                 p = (byte*)(s->start << PageShift) + special->offset/size*size;
1147                 off = (uintptr*)p - (uintptr*)arena_start;
1148                 bitp = arena_start - off/wordsPerBitmapByte - 1;
1149                 shift = (off % wordsPerBitmapByte) * gcBits;
1150                 bits = (*bitp>>shift) & bitMask;
1151                 if((bits&bitMarked) == 0) {
1152                         // Find the exact byte for which the special was setup
1153                         // (as opposed to object beginning).
1154                         p = (byte*)(s->start << PageShift) + special->offset;
1155                         // about to free object: splice out special record
1156                         y = special;
1157                         special = special->next;
1158                         *specialp = special;
1159                         if(!runtime·freespecial(y, p, size, false)) {
1160                                 // stop freeing of object if it has a finalizer
1161                                 *bitp |= bitMarked << shift;
1162                         }
1163                 } else {
1164                         // object is still live: keep special record
1165                         specialp = &special->next;
1166                         special = *specialp;
1167                 }
1168         }
1169
1170         // Sweep through n objects of given size starting at p.
1171         // This thread owns the span now, so it can manipulate
1172         // the block bitmap without atomic operations.
1173         p = (byte*)(s->start << PageShift);
1174         // Find bits for the beginning of the span.
1175         off = (uintptr*)p - (uintptr*)arena_start;
1176         bitp = arena_start - off/wordsPerBitmapByte - 1;
1177         shift = 0;
1178         step = size/(PtrSize*wordsPerBitmapByte);
1179         // Rewind to the previous quadruple as we move to the next
1180         // in the beginning of the loop.
1181         bitp += step;
1182         if(step == 0) {
1183                 // 8-byte objects.
1184                 bitp++;
1185                 shift = gcBits;
1186         }
1187         for(; n > 0; n--, p += size) {
1188                 bitp -= step;
1189                 if(step == 0) {
1190                         if(shift != 0)
1191                                 bitp--;
1192                         shift = gcBits - shift;
1193                 }
1194
1195                 xbits = *bitp;
1196                 bits = (xbits>>shift) & bitMask;
1197
1198                 // Allocated and marked object, reset bits to allocated.
1199                 if((bits&bitMarked) != 0) {
1200                         *bitp &= ~(bitMarked<<shift);
1201                         continue;
1202                 }
1203                 // At this point we know that we are looking at garbage object
1204                 // that needs to be collected.
1205                 if(runtime·debug.allocfreetrace)
1206                         runtime·tracefree(p, size);
1207                 // Reset to allocated+noscan.
1208                 *bitp = (xbits & ~((bitMarked|(BitsMask<<2))<<shift)) | ((uintptr)BitsDead<<(shift+2));
1209                 if(cl == 0) {
1210                         // Free large span.
1211                         if(preserve)
1212                                 runtime·throw("can't preserve large span");
1213                         runtime·unmarkspan(p, s->npages<<PageShift);
1214                         s->needzero = 1;
1215                         // important to set sweepgen before returning it to heap
1216                         runtime·atomicstore(&s->sweepgen, sweepgen);
1217                         sweepgenset = true;
1218                         // NOTE(rsc,dvyukov): The original implementation of efence
1219                         // in CL 22060046 used SysFree instead of SysFault, so that
1220                         // the operating system would eventually give the memory
1221                         // back to us again, so that an efence program could run
1222                         // longer without running out of memory. Unfortunately,
1223                         // calling SysFree here without any kind of adjustment of the
1224                         // heap data structures means that when the memory does
1225                         // come back to us, we have the wrong metadata for it, either in
1226                         // the MSpan structures or in the garbage collection bitmap.
1227                         // Using SysFault here means that the program will run out of
1228                         // memory fairly quickly in efence mode, but at least it won't
1229                         // have mysterious crashes due to confused memory reuse.
1230                         // It should be possible to switch back to SysFree if we also
1231                         // implement and then call some kind of MHeap_DeleteSpan.
1232                         if(runtime·debug.efence) {
1233                                 s->limit = nil; // prevent mlookup from finding this span
1234                                 runtime·SysFault(p, size);
1235                         } else
1236                                 runtime·MHeap_Free(&runtime·mheap, s, 1);
1237                         c->local_nlargefree++;
1238                         c->local_largefree += size;
1239                         runtime·xadd64(&mstats.next_gc, -(uint64)(size * (runtime·gcpercent + 100)/100));
1240                         res = true;
1241                 } else {
1242                         // Free small object.
1243                         if(size > 2*sizeof(uintptr))
1244                                 ((uintptr*)p)[1] = (uintptr)0xdeaddeaddeaddeadll;       // mark as "needs to be zeroed"
1245                         else if(size > sizeof(uintptr))
1246                                 ((uintptr*)p)[1] = 0;
1247
1248                         end->next = (MLink*)p;
1249                         end = (MLink*)p;
1250                         nfree++;
1251                 }
1252         }
1253
1254         // We need to set s->sweepgen = h->sweepgen only when all blocks are swept,
1255         // because of the potential for a concurrent free/SetFinalizer.
1256         // But we need to set it before we make the span available for allocation
1257         // (return it to heap or mcentral), because allocation code assumes that a
1258         // span is already swept if available for allocation.
1259
1260         if(!sweepgenset && nfree == 0) {
1261                 // The span must be in our exclusive ownership until we update sweepgen,
1262                 // check for potential races.
1263                 if(s->state != MSpanInUse || s->sweepgen != sweepgen-1) {
1264                         runtime·printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1265                                 s->state, s->sweepgen, sweepgen);
1266                         runtime·throw("MSpan_Sweep: bad span state after sweep");
1267                 }
1268                 runtime·atomicstore(&s->sweepgen, sweepgen);
1269         }
1270         if(nfree > 0) {
1271                 c->local_nsmallfree[cl] += nfree;
1272                 c->local_cachealloc -= nfree * size;
1273                 runtime·xadd64(&mstats.next_gc, -(uint64)(nfree * size * (runtime·gcpercent + 100)/100));
1274                 res = runtime·MCentral_FreeSpan(&runtime·mheap.central[cl].mcentral, s, nfree, head.next, end, preserve);
1275                 // MCentral_FreeSpan updates sweepgen
1276         }
1277         return res;
1278 }
1279
1280 // State of background runtime·sweep.
1281 // Protected by runtime·gclock.
1282 typedef struct SweepData SweepData;
1283 struct SweepData
1284 {
1285         G*      g;
1286         bool    parked;
1287
1288         uint32  spanidx;        // background sweeper position
1289
1290         uint32  nbgsweep;
1291         uint32  npausesweep;
1292 };
1293 SweepData runtime·sweep;
1294
1295 // sweeps one span
1296 // returns number of pages returned to heap, or -1 if there is nothing to sweep
1297 uintptr
1298 runtime·sweepone(void)
1299 {
1300         MSpan *s;
1301         uint32 idx, sg;
1302         uintptr npages;
1303
1304         // increment locks to ensure that the goroutine is not preempted
1305         // in the middle of sweep thus leaving the span in an inconsistent state for next GC
1306         g->m->locks++;
1307         sg = runtime·mheap.sweepgen;
1308         for(;;) {
1309                 idx = runtime·xadd(&runtime·sweep.spanidx, 1) - 1;
1310                 if(idx >= runtime·work.nspan) {
1311                         runtime·mheap.sweepdone = true;
1312                         g->m->locks--;
1313                         return -1;
1314                 }
1315                 s = runtime·work.spans[idx];
1316                 if(s->state != MSpanInUse) {
1317                         s->sweepgen = sg;
1318                         continue;
1319                 }
1320                 if(s->sweepgen != sg-2 || !runtime·cas(&s->sweepgen, sg-2, sg-1))
1321                         continue;
1322                 npages = s->npages;
1323                 if(!runtime·MSpan_Sweep(s, false))
1324                         npages = 0;
1325                 g->m->locks--;
1326                 return npages;
1327         }
1328 }
1329
1330 static void
1331 sweepone_m(void)
1332 {
1333         g->m->scalararg[0] = runtime·sweepone();
1334 }
1335
1336 #pragma textflag NOSPLIT
1337 uintptr
1338 runtime·gosweepone(void)
1339 {
1340         void (*fn)(void);
1341         
1342         fn = sweepone_m;
1343         runtime·onM(&fn);
1344         return g->m->scalararg[0];
1345 }
1346
1347 #pragma textflag NOSPLIT
1348 bool
1349 runtime·gosweepdone(void)
1350 {
1351         return runtime·mheap.sweepdone;
1352 }
1353
1354
1355 void
1356 runtime·gchelper(void)
1357 {
1358         uint32 nproc;
1359
1360         g->m->traceback = 2;
1361         gchelperstart();
1362
1363         // parallel mark for over GC roots
1364         runtime·parfordo(runtime·work.markfor);
1365         if(runtime·gcphase != GCscan) 
1366                 scanblock(nil, 0, nil); // blocks in getfull
1367         nproc = runtime·work.nproc;  // work.nproc can change right after we increment work.ndone
1368         if(runtime·xadd(&runtime·work.ndone, +1) == nproc-1)
1369                 runtime·notewakeup(&runtime·work.alldone);
1370         g->m->traceback = 0;
1371 }
1372
1373 static void
1374 cachestats(void)
1375 {
1376         MCache *c;
1377         P *p, **pp;
1378
1379         for(pp=runtime·allp; p=*pp; pp++) {
1380                 c = p->mcache;
1381                 if(c==nil)
1382                         continue;
1383                 runtime·purgecachedstats(c);
1384         }
1385 }
1386
1387 static void
1388 flushallmcaches(void)
1389 {
1390         P *p, **pp;
1391         MCache *c;
1392
1393         // Flush MCache's to MCentral.
1394         for(pp=runtime·allp; p=*pp; pp++) {
1395                 c = p->mcache;
1396                 if(c==nil)
1397                         continue;
1398                 runtime·MCache_ReleaseAll(c);
1399                 runtime·stackcache_clear(c);
1400         }
1401 }
1402
1403 static void
1404 flushallmcaches_m(G *gp)
1405 {
1406         flushallmcaches();
1407         runtime·gogo(&gp->sched);
1408 }
1409
1410 void
1411 runtime·updatememstats(GCStats *stats)
1412 {
1413         M *mp;
1414         MSpan *s;
1415         int32 i;
1416         uint64 smallfree;
1417         uint64 *src, *dst;
1418         void (*fn)(G*);
1419
1420         if(stats)
1421                 runtime·memclr((byte*)stats, sizeof(*stats));
1422         for(mp=runtime·allm; mp; mp=mp->alllink) {
1423                 if(stats) {
1424                         src = (uint64*)&mp->gcstats;
1425                         dst = (uint64*)stats;
1426                         for(i=0; i<sizeof(*stats)/sizeof(uint64); i++)
1427                                 dst[i] += src[i];
1428                         runtime·memclr((byte*)&mp->gcstats, sizeof(mp->gcstats));
1429                 }
1430         }
1431         mstats.mcache_inuse = runtime·mheap.cachealloc.inuse;
1432         mstats.mspan_inuse = runtime·mheap.spanalloc.inuse;
1433         mstats.sys = mstats.heap_sys + mstats.stacks_sys + mstats.mspan_sys +
1434                 mstats.mcache_sys + mstats.buckhash_sys + mstats.gc_sys + mstats.other_sys;
1435         
1436         // Calculate memory allocator stats.
1437         // During program execution we only count number of frees and amount of freed memory.
1438         // Current number of alive object in the heap and amount of alive heap memory
1439         // are calculated by scanning all spans.
1440         // Total number of mallocs is calculated as number of frees plus number of alive objects.
1441         // Similarly, total amount of allocated memory is calculated as amount of freed memory
1442         // plus amount of alive heap memory.
1443         mstats.alloc = 0;
1444         mstats.total_alloc = 0;
1445         mstats.nmalloc = 0;
1446         mstats.nfree = 0;
1447         for(i = 0; i < nelem(mstats.by_size); i++) {
1448                 mstats.by_size[i].nmalloc = 0;
1449                 mstats.by_size[i].nfree = 0;
1450         }
1451
1452         // Flush MCache's to MCentral.
1453         if(g == g->m->g0)
1454                 flushallmcaches();
1455         else {
1456                 fn = flushallmcaches_m;
1457                 runtime·mcall(&fn);
1458         }
1459
1460         // Aggregate local stats.
1461         cachestats();
1462
1463         // Scan all spans and count number of alive objects.
1464         runtime·lock(&runtime·mheap.lock);
1465         for(i = 0; i < runtime·mheap.nspan; i++) {
1466                 s = runtime·mheap.allspans[i];
1467                 if(s->state != MSpanInUse)
1468                         continue;
1469                 if(s->sizeclass == 0) {
1470                         mstats.nmalloc++;
1471                         mstats.alloc += s->elemsize;
1472                 } else {
1473                         mstats.nmalloc += s->ref;
1474                         mstats.by_size[s->sizeclass].nmalloc += s->ref;
1475                         mstats.alloc += s->ref*s->elemsize;
1476                 }
1477         }
1478         runtime·unlock(&runtime·mheap.lock);
1479
1480         // Aggregate by size class.
1481         smallfree = 0;
1482         mstats.nfree = runtime·mheap.nlargefree;
1483         for(i = 0; i < nelem(mstats.by_size); i++) {
1484                 mstats.nfree += runtime·mheap.nsmallfree[i];
1485                 mstats.by_size[i].nfree = runtime·mheap.nsmallfree[i];
1486                 mstats.by_size[i].nmalloc += runtime·mheap.nsmallfree[i];
1487                 smallfree += runtime·mheap.nsmallfree[i] * runtime·class_to_size[i];
1488         }
1489         mstats.nfree += mstats.tinyallocs;
1490         mstats.nmalloc += mstats.nfree;
1491
1492         // Calculate derived stats.
1493         mstats.total_alloc = mstats.alloc + runtime·mheap.largefree + smallfree;
1494         mstats.heap_alloc = mstats.alloc;
1495         mstats.heap_objects = mstats.nmalloc - mstats.nfree;
1496 }
1497
1498 // Structure of arguments passed to function gc().
1499 // This allows the arguments to be passed via runtime·mcall.
1500 struct gc_args
1501 {
1502         int64 start_time; // start time of GC in ns (just before stoptheworld)
1503         bool  eagersweep;
1504 };
1505
1506 static void gc(struct gc_args *args);
1507
1508 int32
1509 runtime·readgogc(void)
1510 {
1511         byte *p;
1512
1513         p = runtime·getenv("GOGC");
1514         if(p == nil || p[0] == '\0')
1515                 return 100;
1516         if(runtime·strcmp(p, (byte*)"off") == 0)
1517                 return -1;
1518         return runtime·atoi(p);
1519 }
1520
1521 void
1522 runtime·gcinit(void)
1523 {
1524         if(sizeof(Workbuf) != WorkbufSize)
1525                 runtime·throw("runtime: size of Workbuf is suboptimal");
1526
1527         runtime·work.markfor = runtime·parforalloc(MaxGcproc);
1528         runtime·gcpercent = runtime·readgogc();
1529         runtime·gcdatamask = unrollglobgcprog(runtime·gcdata, runtime·edata - runtime·data);
1530         runtime·gcbssmask = unrollglobgcprog(runtime·gcbss, runtime·ebss - runtime·bss);
1531 }
1532
1533 // Called from malloc.go using onM, stopping and starting the world handled in caller.
1534 void
1535 runtime·gc_m(void)
1536 {
1537         struct gc_args a;
1538         G *gp;
1539
1540         gp = g->m->curg;
1541         runtime·casgstatus(gp, Grunning, Gwaiting);
1542         gp->waitreason = runtime·gostringnocopy((byte*)"garbage collection");
1543
1544         a.start_time = (uint64)(g->m->scalararg[0]) | ((uint64)(g->m->scalararg[1]) << 32);
1545         a.eagersweep = g->m->scalararg[2];
1546         gc(&a);
1547         runtime·casgstatus(gp, Gwaiting, Grunning);
1548 }
1549
1550 void
1551 runtime·finishsweep_m(void)
1552 {
1553         uint32 i, sg;
1554         MSpan *s;
1555
1556         // The world is stopped so we should be able to complete the sweeps 
1557         // quickly. 
1558         while(runtime·sweepone() != -1)
1559                 runtime·sweep.npausesweep++;
1560
1561         // There may be some other spans being swept concurrently that 
1562         // we need to wait for. If finishsweep_m is done with the world stopped
1563         // this code is not required.
1564         sg = runtime·mheap.sweepgen;
1565         for(i=0; i<runtime·work.nspan; i++) {
1566                 s = runtime·work.spans[i];
1567                 if(s->sweepgen == sg) {
1568                         continue;
1569                 }
1570                 if(s->state != MSpanInUse) // Span is not part of the GCed heap so no need to ensure it is swept.
1571                         continue;
1572                 runtime·MSpan_EnsureSwept(s);
1573         }       
1574 }
1575
1576 // Scan all of the stacks, greying (or graying if in America) the referents
1577 // but not blackening them since the mark write barrier isn't installed.
1578 void
1579 runtime·gcscan_m(void)
1580 {
1581         uint32 i, allglen, oldphase;
1582         G *gp, *mastergp, **allg;
1583
1584         // Grab the g that called us and potentially allow rescheduling.
1585         // This allows it to be scanned like other goroutines.
1586         mastergp = g->m->curg;
1587
1588         runtime·casgstatus(mastergp, Grunning, Gwaiting);
1589         mastergp->waitreason = runtime·gostringnocopy((byte*)"garbage collection scan");
1590
1591         // Span sweeping has been done by finishsweep_m.
1592         // Long term we will want to make this goroutine runnable 
1593         // by placing it onto a scanenqueue state and then calling 
1594         // runtime·restartg(mastergp) to make it Grunnable.  
1595         // At the bottom we will want to return this p back to the scheduler.
1596
1597         oldphase = runtime·gcphase;
1598
1599         runtime·lock(&runtime·allglock);
1600         allglen = runtime·allglen;
1601         allg = runtime·allg;
1602         // Prepare flag indicating that the scan has not been completed.
1603         for(i = 0; i < allglen; i++) {
1604                 gp = allg[i];
1605                 gp->gcworkdone = false;  // set to true in gcphasework
1606         }
1607         runtime·unlock(&runtime·allglock);
1608
1609         runtime·work.nwait = 0;
1610         runtime·work.ndone = 0;
1611         runtime·work.nproc = 1; // For now do not do this in parallel.
1612         runtime·gcphase = GCscan;
1613         //      ackgcphase is not needed since we are not scanning running goroutines.
1614         runtime·parforsetup(runtime·work.markfor, runtime·work.nproc, RootCount + allglen, nil, false, markroot);
1615         runtime·parfordo(runtime·work.markfor);
1616         
1617         runtime·lock(&runtime·allglock);      
1618
1619         allg = runtime·allg;
1620         // Check that gc work is done. 
1621         for(i = 0; i < allglen; i++) {
1622                 gp = allg[i];
1623                 if(!gp->gcworkdone) {
1624                         runtime·throw("scan missed a g");
1625                 }
1626         }
1627         runtime·unlock(&runtime·allglock);
1628
1629         runtime·gcphase = oldphase;
1630         runtime·casgstatus(mastergp, Gwaiting, Grunning);
1631         // Let the g that called us continue to run.
1632 }
1633
1634 static void
1635 gc(struct gc_args *args)
1636 {
1637         int64 t0, t1, t2, t3, t4;
1638         uint64 heap0, heap1, obj;
1639         GCStats stats;
1640         uint32 oldphase;
1641         uint32 i;
1642         G *gp;
1643
1644         if(runtime·debug.allocfreetrace)
1645                 runtime·tracegc();
1646
1647         g->m->traceback = 2;
1648         t0 = args->start_time;
1649         runtime·work.tstart = args->start_time; 
1650
1651         t1 = 0;
1652         if(runtime·debug.gctrace)
1653                 t1 = runtime·nanotime();
1654
1655         runtime·finishsweep_m();
1656
1657         // Cache runtime·mheap.allspans in work.spans to avoid conflicts with
1658         // resizing/freeing allspans.
1659         // New spans can be created while GC progresses, but they are not garbage for
1660         // this round:
1661         //  - new stack spans can be created even while the world is stopped.
1662         //  - new malloc spans can be created during the concurrent sweep
1663
1664         // Even if this is stop-the-world, a concurrent exitsyscall can allocate a stack from heap.
1665         runtime·lock(&runtime·mheap.lock);
1666         // Free the old cached sweep array if necessary.
1667         if(runtime·work.spans != nil && runtime·work.spans != runtime·mheap.allspans)
1668                 runtime·SysFree(runtime·work.spans, runtime·work.nspan*sizeof(runtime·work.spans[0]), &mstats.other_sys);
1669         // Cache the current array for marking.
1670         runtime·mheap.gcspans = runtime·mheap.allspans;
1671         runtime·work.spans = runtime·mheap.allspans;
1672         runtime·work.nspan = runtime·mheap.nspan;
1673         runtime·unlock(&runtime·mheap.lock);
1674         oldphase = runtime·gcphase;
1675
1676         runtime·work.nwait = 0;
1677         runtime·work.ndone = 0;
1678         runtime·work.nproc = runtime·gcprocs(); 
1679         runtime·gcphase = GCmark;
1680
1681         // World is stopped so allglen will not change.
1682         for(i = 0; i < runtime·allglen; i++) {
1683                 gp = runtime·allg[i];
1684                 gp->gcworkdone = false;  // set to true in gcphasework
1685         }
1686
1687         runtime·parforsetup(runtime·work.markfor, runtime·work.nproc, RootCount + runtime·allglen, nil, false, markroot);
1688         if(runtime·work.nproc > 1) {
1689                 runtime·noteclear(&runtime·work.alldone);
1690                 runtime·helpgc(runtime·work.nproc);
1691         }
1692
1693         t2 = 0;
1694         if(runtime·debug.gctrace)
1695                 t2 = runtime·nanotime();
1696
1697         gchelperstart();
1698         runtime·parfordo(runtime·work.markfor);
1699
1700         scanblock(nil, 0, nil);
1701
1702         if(runtime·work.full)
1703                 runtime·throw("runtime·work.full != nil");
1704         if(runtime·work.partial)
1705                 runtime·throw("runtime·work.partial != nil");
1706
1707         runtime·gcphase = oldphase;
1708         t3 = 0;
1709         if(runtime·debug.gctrace)
1710                 t3 = runtime·nanotime();
1711
1712         if(runtime·work.nproc > 1)
1713                 runtime·notesleep(&runtime·work.alldone);
1714
1715         runtime·shrinkfinish();
1716
1717         cachestats();
1718         // next_gc calculation is tricky with concurrent sweep since we don't know size of live heap
1719         // estimate what was live heap size after previous GC (for tracing only)
1720         heap0 = mstats.next_gc*100/(runtime·gcpercent+100);
1721         // conservatively set next_gc to high value assuming that everything is live
1722         // concurrent/lazy sweep will reduce this number while discovering new garbage
1723         mstats.next_gc = mstats.heap_alloc+mstats.heap_alloc*runtime·gcpercent/100;
1724
1725         t4 = runtime·nanotime();
1726         runtime·atomicstore64(&mstats.last_gc, runtime·unixnanotime());  // must be Unix time to make sense to user
1727         mstats.pause_ns[mstats.numgc%nelem(mstats.pause_ns)] = t4 - t0;
1728         mstats.pause_end[mstats.numgc%nelem(mstats.pause_end)] = t4;
1729         mstats.pause_total_ns += t4 - t0;
1730         mstats.numgc++;
1731         if(mstats.debuggc)
1732                 runtime·printf("pause %D\n", t4-t0);
1733
1734         if(runtime·debug.gctrace) {
1735                 heap1 = mstats.heap_alloc;
1736                 runtime·updatememstats(&stats);
1737                 if(heap1 != mstats.heap_alloc) {
1738                         runtime·printf("runtime: mstats skew: heap=%D/%D\n", heap1, mstats.heap_alloc);
1739                         runtime·throw("mstats skew");
1740                 }
1741                 obj = mstats.nmalloc - mstats.nfree;
1742
1743                 stats.nprocyield += runtime·work.markfor->nprocyield;
1744                 stats.nosyield += runtime·work.markfor->nosyield;
1745                 stats.nsleep += runtime·work.markfor->nsleep;
1746
1747                 runtime·printf("gc%d(%d): %D+%D+%D+%D us, %D -> %D MB, %D (%D-%D) objects,"
1748                                 " %d goroutines,"
1749                                 " %d/%d/%d sweeps,"
1750                                 " %D(%D) handoff, %D(%D) steal, %D/%D/%D yields\n",
1751                         mstats.numgc, runtime·work.nproc, (t1-t0)/1000, (t2-t1)/1000, (t3-t2)/1000, (t4-t3)/1000,
1752                         heap0>>20, heap1>>20, obj,
1753                         mstats.nmalloc, mstats.nfree,
1754                         runtime·gcount(),
1755                         runtime·work.nspan, runtime·sweep.nbgsweep, runtime·sweep.npausesweep,
1756                         stats.nhandoff, stats.nhandoffcnt,
1757                         runtime·work.markfor->nsteal, runtime·work.markfor->nstealcnt,
1758                         stats.nprocyield, stats.nosyield, stats.nsleep);
1759                 runtime·sweep.nbgsweep = runtime·sweep.npausesweep = 0;
1760         }
1761
1762         // See the comment in the beginning of this function as to why we need the following.
1763         // Even if this is still stop-the-world, a concurrent exitsyscall can allocate a stack from heap.
1764         runtime·lock(&runtime·mheap.lock);
1765         // Free the old cached mark array if necessary.
1766         if(runtime·work.spans != nil && runtime·work.spans != runtime·mheap.allspans)
1767                 runtime·SysFree(runtime·work.spans, runtime·work.nspan*sizeof(runtime·work.spans[0]), &mstats.other_sys);
1768         // Cache the current array for sweeping.
1769         runtime·mheap.gcspans = runtime·mheap.allspans;
1770         runtime·mheap.sweepgen += 2;
1771         runtime·mheap.sweepdone = false;
1772         runtime·work.spans = runtime·mheap.allspans;
1773         runtime·work.nspan = runtime·mheap.nspan;
1774         runtime·sweep.spanidx = 0;
1775         runtime·unlock(&runtime·mheap.lock);
1776
1777         if(ConcurrentSweep && !args->eagersweep) {
1778                 runtime·lock(&runtime·gclock);
1779                 if(runtime·sweep.g == nil)
1780                         runtime·sweep.g = runtime·newproc1(&bgsweepv, nil, 0, 0, gc);
1781                 else if(runtime·sweep.parked) {
1782                         runtime·sweep.parked = false;
1783                         runtime·ready(runtime·sweep.g);
1784                 }
1785                 runtime·unlock(&runtime·gclock);
1786         } else {
1787                 // Sweep all spans eagerly.
1788                 while(runtime·sweepone() != -1)
1789                         runtime·sweep.npausesweep++;
1790                 // Do an additional mProf_GC, because all 'free' events are now real as well.
1791                 runtime·mProf_GC();
1792         }
1793
1794         runtime·mProf_GC();
1795         g->m->traceback = 0;
1796 }
1797
1798 extern uintptr runtime·sizeof_C_MStats;
1799
1800 static void readmemstats_m(void);
1801
1802 void
1803 runtime·readmemstats_m(void)
1804 {
1805         MStats *stats;
1806         
1807         stats = g->m->ptrarg[0];
1808         g->m->ptrarg[0] = nil;
1809
1810         runtime·updatememstats(nil);
1811         // Size of the trailing by_size array differs between Go and C,
1812         // NumSizeClasses was changed, but we can not change Go struct because of backward compatibility.
1813         runtime·memmove(stats, &mstats, runtime·sizeof_C_MStats);
1814
1815         // Stack numbers are part of the heap numbers, separate those out for user consumption
1816         stats->stacks_sys = stats->stacks_inuse;
1817         stats->heap_inuse -= stats->stacks_inuse;
1818         stats->heap_sys -= stats->stacks_inuse;
1819 }
1820
1821 static void readgcstats_m(void);
1822
1823 #pragma textflag NOSPLIT
1824 void
1825 runtime∕debug·readGCStats(Slice *pauses)
1826 {
1827         void (*fn)(void);
1828         
1829         g->m->ptrarg[0] = pauses;
1830         fn = readgcstats_m;
1831         runtime·onM(&fn);
1832 }
1833
1834 static void
1835 readgcstats_m(void)
1836 {
1837         Slice *pauses;  
1838         uint64 *p;
1839         uint32 i, j, n;
1840         
1841         pauses = g->m->ptrarg[0];
1842         g->m->ptrarg[0] = nil;
1843
1844         // Calling code in runtime/debug should make the slice large enough.
1845         if(pauses->cap < nelem(mstats.pause_ns)+3)
1846                 runtime·throw("runtime: short slice passed to readGCStats");
1847
1848         // Pass back: pauses, pause ends, last gc (absolute time), number of gc, total pause ns.
1849         p = (uint64*)pauses->array;
1850         runtime·lock(&runtime·mheap.lock);
1851
1852         n = mstats.numgc;
1853         if(n > nelem(mstats.pause_ns))
1854                 n = nelem(mstats.pause_ns);
1855
1856         // The pause buffer is circular. The most recent pause is at
1857         // pause_ns[(numgc-1)%nelem(pause_ns)], and then backward
1858         // from there to go back farther in time. We deliver the times
1859         // most recent first (in p[0]).
1860         for(i=0; i<n; i++) {
1861                 j = (mstats.numgc-1-i)%nelem(mstats.pause_ns);
1862                 p[i] = mstats.pause_ns[j];
1863                 p[n+i] = mstats.pause_end[j];
1864         }
1865
1866         p[n+n] = mstats.last_gc;
1867         p[n+n+1] = mstats.numgc;
1868         p[n+n+2] = mstats.pause_total_ns;       
1869         runtime·unlock(&runtime·mheap.lock);
1870         pauses->len = n+n+3;
1871 }
1872
1873 void
1874 runtime·setgcpercent_m(void)
1875 {
1876         int32 in;
1877         int32 out;
1878
1879         in = (int32)(intptr)g->m->scalararg[0];
1880
1881         runtime·lock(&runtime·mheap.lock);
1882         out = runtime·gcpercent;
1883         if(in < 0)
1884                 in = -1;
1885         runtime·gcpercent = in;
1886         runtime·unlock(&runtime·mheap.lock);
1887
1888         g->m->scalararg[0] = (uintptr)(intptr)out;
1889 }
1890
1891 static void
1892 gchelperstart(void)
1893 {
1894         if(g->m->helpgc < 0 || g->m->helpgc >= MaxGcproc)
1895                 runtime·throw("gchelperstart: bad m->helpgc");
1896         if(g != g->m->g0)
1897                 runtime·throw("gchelper not running on g0 stack");
1898 }
1899
1900 G*
1901 runtime·wakefing(void)
1902 {
1903         G *res;
1904
1905         res = nil;
1906         runtime·lock(&runtime·finlock);
1907         if(runtime·fingwait && runtime·fingwake) {
1908                 runtime·fingwait = false;
1909                 runtime·fingwake = false;
1910                 res = runtime·fing;
1911         }
1912         runtime·unlock(&runtime·finlock);
1913         return res;
1914 }
1915
1916 // Recursively unrolls GC program in prog.
1917 // mask is where to store the result.
1918 // ppos is a pointer to position in mask, in bits.
1919 // sparse says to generate 4-bits per word mask for heap (2-bits for data/bss otherwise).
1920 static byte*
1921 unrollgcprog1(byte *mask, byte *prog, uintptr *ppos, bool inplace, bool sparse)
1922 {
1923         uintptr pos, siz, i, off;
1924         byte *arena_start, *prog1, v, *bitp, shift;
1925
1926         arena_start = runtime·mheap.arena_start;
1927         pos = *ppos;
1928         for(;;) {
1929                 switch(prog[0]) {
1930                 case insData:
1931                         prog++;
1932                         siz = prog[0];
1933                         prog++;
1934                         for(i = 0; i < siz; i++) {
1935                                 v = prog[i/PointersPerByte];
1936                                 v >>= (i%PointersPerByte)*BitsPerPointer;
1937                                 v &= BitsMask;
1938                                 if(inplace) {
1939                                         // Store directly into GC bitmap.
1940                                         off = (uintptr*)(mask+pos) - (uintptr*)arena_start;
1941                                         bitp = arena_start - off/wordsPerBitmapByte - 1;
1942                                         shift = (off % wordsPerBitmapByte) * gcBits;
1943                                         if(shift==0)
1944                                                 *bitp = 0;
1945                                         *bitp |= v<<(shift+2);
1946                                         pos += PtrSize;
1947                                 } else if(sparse) {
1948                                         // 4-bits per word
1949                                         v <<= (pos%8)+2;
1950                                         mask[pos/8] |= v;
1951                                         pos += gcBits;
1952                                 } else {
1953                                         // 2-bits per word
1954                                         v <<= pos%8;
1955                                         mask[pos/8] |= v;
1956                                         pos += BitsPerPointer;
1957                                 }
1958                         }
1959                         prog += ROUND(siz*BitsPerPointer, 8)/8;
1960                         break;
1961                 case insArray:
1962                         prog++;
1963                         siz = 0;
1964                         for(i = 0; i < PtrSize; i++)
1965                                 siz = (siz<<8) + prog[PtrSize-i-1];
1966                         prog += PtrSize;
1967                         prog1 = nil;
1968                         for(i = 0; i < siz; i++)
1969                                 prog1 = unrollgcprog1(mask, prog, &pos, inplace, sparse);
1970                         if(prog1[0] != insArrayEnd)
1971                                 runtime·throw("unrollgcprog: array does not end with insArrayEnd");
1972                         prog = prog1+1;
1973                         break;
1974                 case insArrayEnd:
1975                 case insEnd:
1976                         *ppos = pos;
1977                         return prog;
1978                 default:
1979                         runtime·throw("unrollgcprog: unknown instruction");
1980                 }
1981         }
1982 }
1983
1984 // Unrolls GC program prog for data/bss, returns dense GC mask.
1985 static BitVector
1986 unrollglobgcprog(byte *prog, uintptr size)
1987 {
1988         byte *mask;
1989         uintptr pos, masksize;
1990
1991         masksize = ROUND(ROUND(size, PtrSize)/PtrSize*BitsPerPointer, 8)/8;
1992         mask = runtime·persistentalloc(masksize+1, 0, &mstats.gc_sys);
1993         mask[masksize] = 0xa1;
1994         pos = 0;
1995         prog = unrollgcprog1(mask, prog, &pos, false, false);
1996         if(pos != size/PtrSize*BitsPerPointer) {
1997                 runtime·printf("unrollglobgcprog: bad program size, got %D, expect %D\n",
1998                         (uint64)pos, (uint64)size/PtrSize*BitsPerPointer);
1999                 runtime·throw("unrollglobgcprog: bad program size");
2000         }
2001         if(prog[0] != insEnd)
2002                 runtime·throw("unrollglobgcprog: program does not end with insEnd");
2003         if(mask[masksize] != 0xa1)
2004                 runtime·throw("unrollglobgcprog: overflow");
2005         return (BitVector){masksize*8, mask};
2006 }
2007
2008 void
2009 runtime·unrollgcproginplace_m(void)
2010 {
2011         uintptr size, size0, pos, off;
2012         byte *arena_start, *prog, *bitp, shift;
2013         Type *typ;
2014         void *v;
2015
2016         v = g->m->ptrarg[0];
2017         typ = g->m->ptrarg[1];
2018         size = g->m->scalararg[0];
2019         size0 = g->m->scalararg[1];
2020         g->m->ptrarg[0] = nil;
2021         g->m->ptrarg[1] = nil;
2022
2023         pos = 0;
2024         prog = (byte*)typ->gc[1];
2025         while(pos != size0)
2026                 unrollgcprog1(v, prog, &pos, true, true);
2027         // Mark first word as bitAllocated.
2028         arena_start = runtime·mheap.arena_start;
2029         off = (uintptr*)v - (uintptr*)arena_start;
2030         bitp = arena_start - off/wordsPerBitmapByte - 1;
2031         shift = (off % wordsPerBitmapByte) * gcBits;
2032         *bitp |= bitBoundary<<shift;
2033         // Mark word after last as BitsDead.
2034         if(size0 < size) {
2035                 off = (uintptr*)((byte*)v + size0) - (uintptr*)arena_start;
2036                 bitp = arena_start - off/wordsPerBitmapByte - 1;
2037                 shift = (off % wordsPerBitmapByte) * gcBits;
2038                 *bitp &= ~(bitPtrMask<<shift) | ((uintptr)BitsDead<<(shift+2));
2039         }
2040 }
2041
2042 // Unrolls GC program in typ->gc[1] into typ->gc[0]
2043 void
2044 runtime·unrollgcprog_m(void)
2045 {
2046         static Mutex lock;
2047         Type *typ;
2048         byte *mask, *prog;
2049         uintptr pos;
2050         uintptr x;
2051
2052         typ = g->m->ptrarg[0];
2053         g->m->ptrarg[0] = nil;
2054
2055         runtime·lock(&lock);
2056         mask = (byte*)typ->gc[0];
2057         if(mask[0] == 0) {
2058                 pos = 8;  // skip the unroll flag
2059                 prog = (byte*)typ->gc[1];
2060                 prog = unrollgcprog1(mask, prog, &pos, false, true);
2061                 if(prog[0] != insEnd)
2062                         runtime·throw("unrollgcprog: program does not end with insEnd");
2063                 if(((typ->size/PtrSize)%2) != 0) {
2064                         // repeat the program twice
2065                         prog = (byte*)typ->gc[1];
2066                         unrollgcprog1(mask, prog, &pos, false, true);
2067                 }
2068                 // atomic way to say mask[0] = 1
2069                 x = *(uintptr*)mask;
2070                 ((byte*)&x)[0] = 1;
2071                 runtime·atomicstorep((void**)mask, (void*)x);
2072         }
2073         runtime·unlock(&lock);
2074 }
2075
2076 // mark the span of memory at v as having n blocks of the given size.
2077 // if leftover is true, there is left over space at the end of the span.
2078 void
2079 runtime·markspan(void *v, uintptr size, uintptr n, bool leftover)
2080 {
2081         uintptr i, off, step;
2082         byte *b;
2083
2084         if((byte*)v+size*n > (byte*)runtime·mheap.arena_used || (byte*)v < runtime·mheap.arena_start)
2085                 runtime·throw("markspan: bad pointer");
2086
2087         // Find bits of the beginning of the span.
2088         off = (uintptr*)v - (uintptr*)runtime·mheap.arena_start;  // word offset
2089         b = runtime·mheap.arena_start - off/wordsPerBitmapByte - 1;
2090         if((off%wordsPerBitmapByte) != 0)
2091                 runtime·throw("markspan: unaligned length");
2092
2093         // Okay to use non-atomic ops here, because we control
2094         // the entire span, and each bitmap byte has bits for only
2095         // one span, so no other goroutines are changing these bitmap words.
2096
2097         if(size == PtrSize) {
2098                 // Possible only on 64-bits (minimal size class is 8 bytes).
2099                 // Poor man's memset(0x11).
2100                 if(0x11 != ((bitBoundary+BitsDead)<<gcBits) + (bitBoundary+BitsDead))
2101                         runtime·throw("markspan: bad bits");
2102                 if((n%(wordsPerBitmapByte*PtrSize)) != 0)
2103                         runtime·throw("markspan: unaligned length");
2104                 b = b - n/wordsPerBitmapByte + 1;       // find first byte
2105                 if(((uintptr)b%PtrSize) != 0)
2106                         runtime·throw("markspan: unaligned pointer");
2107                 for(i = 0; i != n; i += wordsPerBitmapByte*PtrSize, b += PtrSize)
2108                         *(uintptr*)b = (uintptr)0x1111111111111111ULL;  // bitBoundary+BitsDead
2109                 return;
2110         }
2111
2112         if(leftover)
2113                 n++;    // mark a boundary just past end of last block too
2114         step = size/(PtrSize*wordsPerBitmapByte);
2115         for(i = 0; i != n; i++, b -= step)
2116                 *b = bitBoundary|(BitsDead<<2);
2117 }
2118
2119 // unmark the span of memory at v of length n bytes.
2120 void
2121 runtime·unmarkspan(void *v, uintptr n)
2122 {
2123         uintptr off;
2124         byte *b;
2125
2126         if((byte*)v+n > (byte*)runtime·mheap.arena_used || (byte*)v < runtime·mheap.arena_start)
2127                 runtime·throw("markspan: bad pointer");
2128
2129         off = (uintptr*)v - (uintptr*)runtime·mheap.arena_start;  // word offset
2130         if((off % (PtrSize*wordsPerBitmapByte)) != 0)
2131                 runtime·throw("markspan: unaligned pointer");
2132         b = runtime·mheap.arena_start - off/wordsPerBitmapByte - 1;
2133         n /= PtrSize;
2134         if(n%(PtrSize*wordsPerBitmapByte) != 0)
2135                 runtime·throw("unmarkspan: unaligned length");
2136         // Okay to use non-atomic ops here, because we control
2137         // the entire span, and each bitmap word has bits for only
2138         // one span, so no other goroutines are changing these
2139         // bitmap words.
2140         n /= wordsPerBitmapByte;
2141         runtime·memclr(b - n + 1, n);
2142 }
2143
2144 void
2145 runtime·MHeap_MapBits(MHeap *h)
2146 {
2147         // Caller has added extra mappings to the arena.
2148         // Add extra mappings of bitmap words as needed.
2149         // We allocate extra bitmap pieces in chunks of bitmapChunk.
2150         enum {
2151                 bitmapChunk = 8192
2152         };
2153         uintptr n;
2154
2155         n = (h->arena_used - h->arena_start) / (PtrSize*wordsPerBitmapByte);
2156         n = ROUND(n, bitmapChunk);
2157         n = ROUND(n, PhysPageSize);
2158         if(h->bitmap_mapped >= n)
2159                 return;
2160
2161         runtime·SysMap(h->arena_start - n, n - h->bitmap_mapped, h->arena_reserved, &mstats.gc_sys);
2162         h->bitmap_mapped = n;
2163 }
2164
2165 static bool
2166 getgcmaskcb(Stkframe *frame, void *ctxt)
2167 {
2168         Stkframe *frame0;
2169
2170         frame0 = ctxt;
2171         if(frame->sp <= frame0->sp && frame0->sp < frame->varp) {
2172                 *frame0 = *frame;
2173                 return false;
2174         }
2175         return true;
2176 }
2177
2178 // Returns GC type info for object p for testing.
2179 void
2180 runtime·getgcmask(byte *p, Type *t, byte **mask, uintptr *len)
2181 {
2182         Stkframe frame;
2183         uintptr i, n, off;
2184         byte *base, bits, shift, *b;
2185         bool (*cb)(Stkframe*, void*);
2186
2187         *mask = nil;
2188         *len = 0;
2189
2190         // data
2191         if(p >= runtime·data && p < runtime·edata) {
2192                 n = ((PtrType*)t)->elem->size;
2193                 *len = n/PtrSize;
2194                 *mask = runtime·mallocgc(*len, nil, FlagNoScan);
2195                 for(i = 0; i < n; i += PtrSize) {
2196                         off = (p+i-runtime·data)/PtrSize;
2197                         bits = (runtime·gcdatamask.bytedata[off/PointersPerByte] >> ((off%PointersPerByte)*BitsPerPointer))&BitsMask;
2198                         (*mask)[i/PtrSize] = bits;
2199                 }
2200                 return;
2201         }
2202         // bss
2203         if(p >= runtime·bss && p < runtime·ebss) {
2204                 n = ((PtrType*)t)->elem->size;
2205                 *len = n/PtrSize;
2206                 *mask = runtime·mallocgc(*len, nil, FlagNoScan);
2207                 for(i = 0; i < n; i += PtrSize) {
2208                         off = (p+i-runtime·bss)/PtrSize;
2209                         bits = (runtime·gcbssmask.bytedata[off/PointersPerByte] >> ((off%PointersPerByte)*BitsPerPointer))&BitsMask;
2210                         (*mask)[i/PtrSize] = bits;
2211                 }
2212                 return;
2213         }
2214         // heap
2215         if(runtime·mlookup(p, &base, &n, nil)) {
2216                 *len = n/PtrSize;
2217                 *mask = runtime·mallocgc(*len, nil, FlagNoScan);
2218                 for(i = 0; i < n; i += PtrSize) {
2219                         off = (uintptr*)(base+i) - (uintptr*)runtime·mheap.arena_start;
2220                         b = runtime·mheap.arena_start - off/wordsPerBitmapByte - 1;
2221                         shift = (off % wordsPerBitmapByte) * gcBits;
2222                         bits = (*b >> (shift+2))&BitsMask;
2223                         (*mask)[i/PtrSize] = bits;
2224                 }
2225                 return;
2226         }
2227         // stack
2228         frame.fn = nil;
2229         frame.sp = (uintptr)p;
2230         cb = getgcmaskcb;
2231         runtime·gentraceback(g->m->curg->sched.pc, g->m->curg->sched.sp, 0, g->m->curg, 0, nil, 1000, &cb, &frame, false);
2232         if(frame.fn != nil) {
2233                 Func *f;
2234                 StackMap *stackmap;
2235                 BitVector bv;
2236                 uintptr size;
2237                 uintptr targetpc;
2238                 int32 pcdata;
2239
2240                 f = frame.fn;
2241                 targetpc = frame.continpc;
2242                 if(targetpc == 0)
2243                         return;
2244                 if(targetpc != f->entry)
2245                         targetpc--;
2246                 pcdata = runtime·pcdatavalue(f, PCDATA_StackMapIndex, targetpc);
2247                 if(pcdata == -1)
2248                         return;
2249                 stackmap = runtime·funcdata(f, FUNCDATA_LocalsPointerMaps);
2250                 if(stackmap == nil || stackmap->n <= 0)
2251                         return;
2252                 bv = runtime·stackmapdata(stackmap, pcdata);
2253                 size = bv.n/BitsPerPointer*PtrSize;
2254                 n = ((PtrType*)t)->elem->size;
2255                 *len = n/PtrSize;
2256                 *mask = runtime·mallocgc(*len, nil, FlagNoScan);
2257                 for(i = 0; i < n; i += PtrSize) {
2258                         off = (p+i-(byte*)frame.varp+size)/PtrSize;
2259                         bits = (bv.bytedata[off*BitsPerPointer/8] >> ((off*BitsPerPointer)%8))&BitsMask;
2260                         (*mask)[i/PtrSize] = bits;
2261                 }
2262         }
2263 }
2264
2265 void runtime·gc_unixnanotime(int64 *now);
2266
2267 int64
2268 runtime·unixnanotime(void)
2269 {
2270         int64 now;
2271
2272         runtime·gc_unixnanotime(&now);
2273         return now;
2274 }