1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Garbage collector (GC).
9 // - mostly precise (with the exception of some C-allocated objects, assembly frames/arguments, etc)
10 // - parallel (up to MaxGcproc threads)
11 // - partially concurrent (mark is stop-the-world, while sweep is concurrent)
12 // - non-moving/non-compacting
13 // - full (non-partial)
16 // Next GC is after we've allocated an extra amount of memory proportional to
17 // the amount already in use. The proportion is controlled by GOGC environment variable
18 // (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M
19 // (this mark is tracked in next_gc variable). This keeps the GC cost in linear
20 // proportion to the allocation cost. Adjusting GOGC just changes the linear constant
21 // (and also the amount of extra memory used).
24 // The sweep phase proceeds concurrently with normal program execution.
25 // The heap is swept span-by-span both lazily (when a goroutine needs another span)
26 // and concurrently in a background goroutine (this helps programs that are not CPU bound).
27 // However, at the end of the stop-the-world GC phase we don't know the size of the live heap,
28 // and so next_gc calculation is tricky and happens as follows.
29 // At the end of the stop-the-world phase next_gc is conservatively set based on total
30 // heap size; all spans are marked as "needs sweeping".
31 // Whenever a span is swept, next_gc is decremented by GOGC*newly_freed_memory.
32 // The background sweeper goroutine simply sweeps spans one-by-one bringing next_gc
33 // closer to the target value. However, this is not enough to avoid over-allocating memory.
34 // Consider that a goroutine wants to allocate a new span for a large object and
35 // there are no free swept spans, but there are small-object unswept spans.
36 // If the goroutine naively allocates a new span, it can surpass the yet-unknown
37 // target next_gc value. In order to prevent such cases (1) when a goroutine needs
38 // to allocate a new small-object span, it sweeps small-object spans for the same
39 // object size until it frees at least one object; (2) when a goroutine needs to
40 // allocate large-object span from heap, it sweeps spans until it frees at least
41 // that many pages into heap. Together these two measures ensure that we don't surpass
42 // target next_gc value by a large margin. There is an exception: if a goroutine sweeps
43 // and frees two nonadjacent one-page spans to the heap, it will allocate a new two-page span,
44 // but there can still be other one-page unswept spans which could be combined into a two-page span.
45 // It's critical to ensure that no operations proceed on unswept spans (that would corrupt
46 // mark bits in GC bitmap). During GC all mcaches are flushed into the central cache,
47 // so they are empty. When a goroutine grabs a new span into mcache, it sweeps it.
48 // When a goroutine explicitly frees an object or sets a finalizer, it ensures that
49 // the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish).
50 // The finalizer goroutine is kicked off only when all spans are swept.
51 // When the next GC starts, it sweeps all not-yet-swept spans (if any).
61 // Map gccgo field names to gc field names.
62 // Slice aka __go_open_array.
63 #define array __values
64 #define cap __capacity
66 typedef struct __go_map Hmap
;
67 // Type aka __go_type_descriptor
68 #define string __reflection
69 // PtrType aka __go_ptr_type
70 #define elem __element_type
72 #ifdef USING_SPLIT_STACK
74 extern void * __splitstack_find (void *, void *, size_t *, void **, void **,
77 extern void * __splitstack_find_context (void *context
[10], size_t *, void **,
87 WorkbufSize
= 16*1024,
88 FinBlockSize
= 4*1024,
91 IntermediateBufferCapacity
= 64,
93 // Bits in type information
96 PC_BITS
= PRECISE
| LOOP
,
106 #define GcpercentUnknown (-2)
108 // Initialized from $GOGC. GOGC=off means no gc.
109 static int32 gcpercent
= GcpercentUnknown
;
111 static FuncVal
* poolcleanup
;
113 void sync_runtime_registerPoolCleanup(FuncVal
*)
114 __asm__ (GOSYM_PREFIX
"sync.runtime_registerPoolCleanup");
117 sync_runtime_registerPoolCleanup(FuncVal
*f
)
130 if(poolcleanup
!= nil
) {
131 __builtin_call_with_static_chain(poolcleanup
->fn(),
135 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
136 // clear tinyalloc pool
144 // Clear central defer pools.
145 // Leave per-P pools alone, they have strictly bounded size.
146 runtime_lock(&runtime_sched
->deferlock
);
147 for(d
= runtime_sched
->deferpool
; d
!= nil
; d
= dlink
) {
151 runtime_sched
->deferpool
= nil
;
152 runtime_unlock(&runtime_sched
->deferlock
);
155 typedef struct Workbuf Workbuf
;
158 #define SIZE (WorkbufSize-sizeof(LFNode)-sizeof(uintptr))
159 LFNode node
; // must be first
161 Obj obj
[SIZE
/sizeof(Obj
) - 1];
162 uint8 _padding
[SIZE
%sizeof(Obj
) + sizeof(Obj
)];
166 typedef struct Finalizer Finalizer
;
171 const struct __go_func_type
*ft
;
175 typedef struct FinBlock FinBlock
;
185 static Lock finlock
; // protects the following variables
186 static FinBlock
*finq
; // list of finalizers that are to be executed
187 static FinBlock
*finc
; // cache of free blocks
188 static FinBlock
*allfin
; // list of all blocks
189 bool runtime_fingwait
;
190 bool runtime_fingwake
;
195 static void runfinq(void*);
196 static void bgsweep(void*);
197 static Workbuf
* getempty(Workbuf
*);
198 static Workbuf
* getfull(Workbuf
*);
199 static void putempty(Workbuf
*);
200 static Workbuf
* handoff(Workbuf
*);
201 static void gchelperstart(void);
202 static void flushallmcaches(void);
203 static void addstackroots(G
*gp
, Workbuf
**wbufp
);
206 uint64 full
; // lock-free list of full blocks
207 uint64 wempty
; // lock-free list of empty blocks
208 byte pad0
[CacheLineSize
]; // prevents false-sharing between full/empty and nproc/nwait
211 volatile uint32 nwait
;
212 volatile uint32 ndone
;
219 } work
__attribute__((aligned(8)));
222 GC_DEFAULT_PTR
= GC_NUM_INSTR
,
242 uint64 instr
[GC_NUM_INSTR2
];
259 // markonly marks an object. It returns true if the object
260 // has been marked by this function, false otherwise.
261 // This function doesn't append the object to any buffer.
263 markonly(const void *obj
)
266 uintptr
*bitp
, bits
, shift
, x
, xbits
, off
, j
;
270 // Words outside the arena cannot be pointers.
271 if((const byte
*)obj
< runtime_mheap
.arena_start
|| (const byte
*)obj
>= runtime_mheap
.arena_used
)
274 // obj may be a pointer to a live object.
275 // Try to find the beginning of the object.
277 // Round down to word boundary.
278 obj
= (const void*)((uintptr
)obj
& ~((uintptr
)PtrSize
-1));
280 // Find bits for this word.
281 off
= (const uintptr
*)obj
- (uintptr
*)runtime_mheap
.arena_start
;
282 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
283 shift
= off
% wordsPerBitmapWord
;
285 bits
= xbits
>> shift
;
287 // Pointing at the beginning of a block?
288 if((bits
& (bitAllocated
|bitBlockBoundary
)) != 0) {
290 runtime_xadd64(&gcstats
.markonly
.foundbit
, 1);
294 // Pointing just past the beginning?
295 // Scan backward a little to find a block boundary.
296 for(j
=shift
; j
-->0; ) {
297 if(((xbits
>>j
) & (bitAllocated
|bitBlockBoundary
)) != 0) {
301 runtime_xadd64(&gcstats
.markonly
.foundword
, 1);
306 // Otherwise consult span table to find beginning.
307 // (Manually inlined copy of MHeap_LookupMaybe.)
308 k
= (uintptr
)obj
>>PageShift
;
310 x
-= (uintptr
)runtime_mheap
.arena_start
>>PageShift
;
311 s
= runtime_mheap
.spans
[x
];
312 if(s
== nil
|| k
< s
->start
|| (uintptr
)obj
>= s
->limit
|| s
->state
!= MSpanInUse
)
314 p
= (byte
*)((uintptr
)s
->start
<<PageShift
);
315 if(s
->sizeclass
== 0) {
318 uintptr size
= s
->elemsize
;
319 int32 i
= ((const byte
*)obj
- p
)/size
;
323 // Now that we know the object header, reload bits.
324 off
= (const uintptr
*)obj
- (uintptr
*)runtime_mheap
.arena_start
;
325 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
326 shift
= off
% wordsPerBitmapWord
;
328 bits
= xbits
>> shift
;
330 runtime_xadd64(&gcstats
.markonly
.foundspan
, 1);
333 // Now we have bits, bitp, and shift correct for
334 // obj pointing at the base of the object.
335 // Only care about allocated and not marked.
336 if((bits
& (bitAllocated
|bitMarked
)) != bitAllocated
)
339 *bitp
|= bitMarked
<<shift
;
343 if(x
& (bitMarked
<<shift
))
345 if(runtime_casp((void**)bitp
, (void*)x
, (void*)(x
|(bitMarked
<<shift
))))
350 // The object is now marked
354 // PtrTarget is a structure used by intermediate buffers.
355 // The intermediate buffers hold GC data before it
356 // is moved/flushed to the work buffer (Workbuf).
357 // The size of an intermediate buffer is very small,
358 // such as 32 or 64 elements.
359 typedef struct PtrTarget PtrTarget
;
366 typedef struct Scanbuf Scanbuf
;
384 typedef struct BufferList BufferList
;
387 PtrTarget ptrtarget
[IntermediateBufferCapacity
];
388 Obj obj
[IntermediateBufferCapacity
];
390 byte pad
[CacheLineSize
];
392 static BufferList bufferList
[MaxGcproc
];
394 static void enqueue(Obj obj
, Workbuf
**_wbuf
, Obj
**_wp
, uintptr
*_nobj
);
396 // flushptrbuf moves data from the PtrTarget buffer to the work buffer.
397 // The PtrTarget buffer contains blocks irrespective of whether the blocks have been marked or scanned,
398 // while the work buffer contains blocks which have been marked
399 // and are prepared to be scanned by the garbage collector.
401 // _wp, _wbuf, _nobj are input/output parameters and are specifying the work buffer.
403 // A simplified drawing explaining how the todo-list moves from a structure to another:
407 // Obj ------> PtrTarget (pointer targets)
412 // (find block start, mark and enqueue)
414 flushptrbuf(Scanbuf
*sbuf
)
416 byte
*p
, *arena_start
, *obj
;
417 uintptr size
, *bitp
, bits
, shift
, j
, x
, xbits
, off
, nobj
, ti
, n
;
423 PtrTarget
*ptrbuf_end
;
425 arena_start
= runtime_mheap
.arena_start
;
431 ptrbuf
= sbuf
->ptr
.begin
;
432 ptrbuf_end
= sbuf
->ptr
.pos
;
433 n
= ptrbuf_end
- sbuf
->ptr
.begin
;
434 sbuf
->ptr
.pos
= sbuf
->ptr
.begin
;
437 runtime_xadd64(&gcstats
.ptr
.sum
, n
);
438 runtime_xadd64(&gcstats
.ptr
.cnt
, 1);
441 // If buffer is nearly full, get a new one.
442 if(wbuf
== nil
|| nobj
+n
>= nelem(wbuf
->obj
)) {
445 wbuf
= getempty(wbuf
);
449 if(n
>= nelem(wbuf
->obj
))
450 runtime_throw("ptrbuf has to be smaller than WorkBuf");
453 while(ptrbuf
< ptrbuf_end
) {
458 // obj belongs to interval [mheap.arena_start, mheap.arena_used).
460 if(obj
< runtime_mheap
.arena_start
|| obj
>= runtime_mheap
.arena_used
)
461 runtime_throw("object is outside of mheap");
464 // obj may be a pointer to a live object.
465 // Try to find the beginning of the object.
467 // Round down to word boundary.
468 if(((uintptr
)obj
& ((uintptr
)PtrSize
-1)) != 0) {
469 obj
= (void*)((uintptr
)obj
& ~((uintptr
)PtrSize
-1));
473 // Find bits for this word.
474 off
= (uintptr
*)obj
- (uintptr
*)arena_start
;
475 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
476 shift
= off
% wordsPerBitmapWord
;
478 bits
= xbits
>> shift
;
480 // Pointing at the beginning of a block?
481 if((bits
& (bitAllocated
|bitBlockBoundary
)) != 0) {
483 runtime_xadd64(&gcstats
.flushptrbuf
.foundbit
, 1);
489 // Pointing just past the beginning?
490 // Scan backward a little to find a block boundary.
491 for(j
=shift
; j
-->0; ) {
492 if(((xbits
>>j
) & (bitAllocated
|bitBlockBoundary
)) != 0) {
493 obj
= (byte
*)obj
- (shift
-j
)*PtrSize
;
497 runtime_xadd64(&gcstats
.flushptrbuf
.foundword
, 1);
502 // Otherwise consult span table to find beginning.
503 // (Manually inlined copy of MHeap_LookupMaybe.)
504 k
= (uintptr
)obj
>>PageShift
;
506 x
-= (uintptr
)arena_start
>>PageShift
;
507 s
= runtime_mheap
.spans
[x
];
508 if(s
== nil
|| k
< s
->start
|| (uintptr
)obj
>= s
->limit
|| s
->state
!= MSpanInUse
)
510 p
= (byte
*)((uintptr
)s
->start
<<PageShift
);
511 if(s
->sizeclass
== 0) {
515 int32 i
= ((byte
*)obj
- p
)/size
;
519 // Now that we know the object header, reload bits.
520 off
= (uintptr
*)obj
- (uintptr
*)arena_start
;
521 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
522 shift
= off
% wordsPerBitmapWord
;
524 bits
= xbits
>> shift
;
526 runtime_xadd64(&gcstats
.flushptrbuf
.foundspan
, 1);
529 // Now we have bits, bitp, and shift correct for
530 // obj pointing at the base of the object.
531 // Only care about allocated and not marked.
532 if((bits
& (bitAllocated
|bitMarked
)) != bitAllocated
)
535 *bitp
|= bitMarked
<<shift
;
539 if(x
& (bitMarked
<<shift
))
541 if(runtime_casp((void**)bitp
, (void*)x
, (void*)(x
|(bitMarked
<<shift
))))
546 // If object has no pointers, don't need to scan further.
547 if((bits
& bitScan
) == 0)
550 // Ask span about size class.
551 // (Manually inlined copy of MHeap_Lookup.)
552 x
= (uintptr
)obj
>> PageShift
;
553 x
-= (uintptr
)arena_start
>>PageShift
;
554 s
= runtime_mheap
.spans
[x
];
558 *wp
= (Obj
){obj
, s
->elemsize
, ti
};
564 // If another proc wants a pointer, give it some.
565 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
567 wbuf
= handoff(wbuf
);
569 wp
= wbuf
->obj
+ nobj
;
578 flushobjbuf(Scanbuf
*sbuf
)
590 objbuf
= sbuf
->obj
.begin
;
591 objbuf_end
= sbuf
->obj
.pos
;
592 sbuf
->obj
.pos
= sbuf
->obj
.begin
;
594 while(objbuf
< objbuf_end
) {
597 // Align obj.b to a word boundary.
598 off
= (uintptr
)obj
.p
& (PtrSize
-1);
600 obj
.p
+= PtrSize
- off
;
601 obj
.n
-= PtrSize
- off
;
605 if(obj
.p
== nil
|| obj
.n
== 0)
608 // If buffer is full, get a new one.
609 if(wbuf
== nil
|| nobj
>= nelem(wbuf
->obj
)) {
612 wbuf
= getempty(wbuf
);
622 // If another proc wants a pointer, give it some.
623 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
625 wbuf
= handoff(wbuf
);
627 wp
= wbuf
->obj
+ nobj
;
635 // Program that scans the whole block and treats every block element as a potential pointer
636 static uintptr defaultProg
[2] = {PtrSize
, GC_DEFAULT_PTR
};
639 static uintptr chanProg
[2] = {0, GC_CHAN
};
641 // Local variables of a program fragment or loop
642 typedef struct GCFrame GCFrame
;
644 uintptr count
, elemsize
, b
;
645 const uintptr
*loop_or_ret
;
648 // Sanity check for the derived type info objti.
650 checkptr(void *obj
, uintptr objti
)
652 uintptr
*pc1
, type
, tisize
, i
, j
, x
;
659 runtime_throw("checkptr is debug only");
661 if((byte
*)obj
< runtime_mheap
.arena_start
|| (byte
*)obj
>= runtime_mheap
.arena_used
)
663 type
= runtime_gettype(obj
);
664 t
= (Type
*)(type
& ~(uintptr
)(PtrSize
-1));
667 x
= (uintptr
)obj
>> PageShift
;
668 x
-= (uintptr
)(runtime_mheap
.arena_start
)>>PageShift
;
669 s
= runtime_mheap
.spans
[x
];
670 objstart
= (byte
*)((uintptr
)s
->start
<<PageShift
);
671 if(s
->sizeclass
!= 0) {
672 i
= ((byte
*)obj
- objstart
)/s
->elemsize
;
673 objstart
+= i
*s
->elemsize
;
675 tisize
= *(uintptr
*)objti
;
676 // Sanity check for object size: it should fit into the memory block.
677 if((byte
*)obj
+ tisize
> objstart
+ s
->elemsize
) {
678 runtime_printf("object of type '%S' at %p/%p does not fit in block %p/%p\n",
679 *t
->string
, obj
, tisize
, objstart
, s
->elemsize
);
680 runtime_throw("invalid gc type info");
684 // If obj points to the beginning of the memory block,
685 // check type info as well.
686 if(t
->string
== nil
||
687 // Gob allocates unsafe pointers for indirection.
688 (runtime_strcmp((const char *)t
->string
->str
, (const char*)"unsafe.Pointer") &&
689 // Runtime and gc think differently about closures.
690 runtime_strstr((const char *)t
->string
->str
, (const char*)"struct { F uintptr") != (const char *)t
->string
->str
)) {
691 pc1
= (uintptr
*)objti
;
692 pc2
= (const uintptr
*)t
->__gc
;
693 // A simple best-effort check until first GC_END.
694 for(j
= 1; pc1
[j
] != GC_END
&& pc2
[j
] != GC_END
; j
++) {
695 if(pc1
[j
] != pc2
[j
]) {
696 runtime_printf("invalid gc type info for '%s', type info %p [%d]=%p, block info %p [%d]=%p\n",
697 t
->string
? (const int8
*)t
->string
->str
: (const int8
*)"?", pc1
, (int32
)j
, pc1
[j
], pc2
, (int32
)j
, pc2
[j
]);
698 runtime_throw("invalid gc type info");
704 // scanblock scans a block of n bytes starting at pointer b for references
705 // to other objects, scanning any it finds recursively until there are no
706 // unscanned objects left. Instead of using an explicit recursion, it keeps
707 // a work list in the Workbuf* structures and loops in the main function
708 // body. Keeping an explicit work list is easier on the stack allocator and
711 scanblock(Workbuf
*wbuf
, bool keepworking
)
713 byte
*b
, *arena_start
, *arena_used
;
714 uintptr n
, i
, end_b
, elemsize
, size
, ti
, objti
, count
, type
, nobj
;
715 uintptr precise_type
, nominal_size
;
716 const uintptr
*pc
, *chan_ret
;
722 GCFrame
*stack_ptr
, stack_top
, stack
[GC_STACK_CAPACITY
+4];
723 BufferList
*scanbuffers
;
728 const ChanType
*chantype
;
731 if(sizeof(Workbuf
) % WorkbufSize
!= 0)
732 runtime_throw("scanblock: size of Workbuf is suboptimal");
734 // Memory arena parameters.
735 arena_start
= runtime_mheap
.arena_start
;
736 arena_used
= runtime_mheap
.arena_used
;
738 stack_ptr
= stack
+nelem(stack
)-1;
740 precise_type
= false;
745 wp
= &wbuf
->obj
[nobj
];
752 scanbuffers
= &bufferList
[runtime_m()->helpgc
];
754 sbuf
.ptr
.begin
= sbuf
.ptr
.pos
= &scanbuffers
->ptrtarget
[0];
755 sbuf
.ptr
.end
= sbuf
.ptr
.begin
+ nelem(scanbuffers
->ptrtarget
);
757 sbuf
.obj
.begin
= sbuf
.obj
.pos
= &scanbuffers
->obj
[0];
758 sbuf
.obj
.end
= sbuf
.obj
.begin
+ nelem(scanbuffers
->obj
);
764 // (Silence the compiler)
772 // Each iteration scans the block b of length n, queueing pointers in
776 runtime_xadd64(&gcstats
.nbytes
, n
);
777 runtime_xadd64(&gcstats
.obj
.sum
, sbuf
.nobj
);
778 runtime_xadd64(&gcstats
.obj
.cnt
, 1);
783 runtime_printf("scanblock %p %D ti %p\n", b
, (int64
)n
, ti
);
785 pc
= (uintptr
*)(ti
& ~(uintptr
)PC_BITS
);
786 precise_type
= (ti
& PRECISE
);
787 stack_top
.elemsize
= pc
[0];
789 nominal_size
= pc
[0];
791 stack_top
.count
= 0; // 0 means an infinite number of iterations
792 stack_top
.loop_or_ret
= pc
+1;
797 // Simple sanity check for provided type info ti:
798 // The declared size of the object must be not larger than the actual size
799 // (it can be smaller due to inferior pointers).
800 // It's difficult to make a comprehensive check due to inferior pointers,
801 // reflection, gob, etc.
803 runtime_printf("invalid gc type info: type info size %p, block size %p\n", pc
[0], n
);
804 runtime_throw("invalid gc type info");
807 } else if(UseSpanType
) {
809 runtime_xadd64(&gcstats
.obj
.notype
, 1);
811 type
= runtime_gettype(b
);
814 runtime_xadd64(&gcstats
.obj
.typelookup
, 1);
816 t
= (Type
*)(type
& ~(uintptr
)(PtrSize
-1));
817 switch(type
& (PtrSize
-1)) {
818 case TypeInfo_SingleObject
:
819 pc
= (const uintptr
*)t
->__gc
;
820 precise_type
= true; // type information about 'b' is precise
822 stack_top
.elemsize
= pc
[0];
825 pc
= (const uintptr
*)t
->__gc
;
828 precise_type
= true; // type information about 'b' is precise
829 stack_top
.count
= 0; // 0 means an infinite number of iterations
830 stack_top
.elemsize
= pc
[0];
831 stack_top
.loop_or_ret
= pc
+1;
835 chantype
= (const ChanType
*)t
;
841 runtime_printf("scanblock %p %D type %p %S\n", b
, (int64
)n
, type
, *t
->string
);
842 runtime_throw("scanblock: invalid type");
846 runtime_printf("scanblock %p %D type %p %S pc=%p\n", b
, (int64
)n
, type
, *t
->string
, pc
);
850 runtime_printf("scanblock %p %D unknown type\n", b
, (int64
)n
);
855 runtime_printf("scanblock %p %D no span types\n", b
, (int64
)n
);
862 stack_top
.b
= (uintptr
)b
;
863 end_b
= (uintptr
)b
+ n
- PtrSize
;
867 runtime_xadd64(&gcstats
.instr
[pc
[0]], 1);
873 obj
= *(void**)(stack_top
.b
+ pc
[1]);
876 runtime_printf("gc_ptr @%p: %p ti=%p\n", stack_top
.b
+pc
[1], obj
, objti
);
879 checkptr(obj
, objti
);
883 sliceptr
= (Slice
*)(stack_top
.b
+ pc
[1]);
885 runtime_printf("gc_slice @%p: %p/%D/%D\n", sliceptr
, sliceptr
->array
, (int64
)sliceptr
->__count
, (int64
)sliceptr
->cap
);
886 if(sliceptr
->cap
!= 0) {
887 obj
= sliceptr
->array
;
888 // Can't use slice element type for scanning,
889 // because if it points to an array embedded
890 // in the beginning of a struct,
891 // we will scan the whole struct as the slice.
892 // So just obtain type info from heap.
898 obj
= *(void**)(stack_top
.b
+ pc
[1]);
900 runtime_printf("gc_aptr @%p: %p\n", stack_top
.b
+pc
[1], obj
);
905 stringptr
= (String
*)(stack_top
.b
+ pc
[1]);
907 runtime_printf("gc_string @%p: %p/%D\n", stack_top
.b
+pc
[1], stringptr
->str
, (int64
)stringptr
->len
);
908 if(stringptr
->len
!= 0)
909 markonly(stringptr
->str
);
914 eface
= (Eface
*)(stack_top
.b
+ pc
[1]);
917 runtime_printf("gc_eface @%p: %p %p\n", stack_top
.b
+pc
[1], eface
->_type
, eface
->data
);
918 if(eface
->_type
== nil
)
923 if((const byte
*)t
>= arena_start
&& (const byte
*)t
< arena_used
) {
924 union { const Type
*tc
; Type
*tr
; } u
;
926 *sbuf
.ptr
.pos
++ = (PtrTarget
){u
.tr
, 0};
927 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
932 if((byte
*)eface
->data
>= arena_start
&& (byte
*)eface
->data
< arena_used
) {
933 if(__go_is_pointer_type(t
)) {
934 if((t
->__code
& kindNoPointers
))
938 if((t
->__code
& kindMask
) == kindPtr
) {
939 // Only use type information if it is a pointer-containing type.
940 // This matches the GC programs written by cmd/gc/reflect.c's
941 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
942 et
= ((const PtrType
*)t
)->elem
;
943 if(!(et
->__code
& kindNoPointers
))
944 objti
= (uintptr
)((const PtrType
*)t
)->elem
->__gc
;
948 objti
= (uintptr
)t
->__gc
;
954 iface
= (Iface
*)(stack_top
.b
+ pc
[1]);
957 runtime_printf("gc_iface @%p: %p/%p %p\n", stack_top
.b
+pc
[1], *(Type
**)iface
->tab
, nil
, iface
->data
);
958 if(iface
->tab
== nil
)
962 if((byte
*)iface
->tab
>= arena_start
&& (byte
*)iface
->tab
< arena_used
) {
963 *sbuf
.ptr
.pos
++ = (PtrTarget
){iface
->tab
, 0};
964 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
969 if((byte
*)iface
->data
>= arena_start
&& (byte
*)iface
->data
< arena_used
) {
970 t
= *(Type
**)iface
->tab
;
971 if(__go_is_pointer_type(t
)) {
972 if((t
->__code
& kindNoPointers
))
976 if((t
->__code
& kindMask
) == kindPtr
) {
977 // Only use type information if it is a pointer-containing type.
978 // This matches the GC programs written by cmd/gc/reflect.c's
979 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
980 et
= ((const PtrType
*)t
)->elem
;
981 if(!(et
->__code
& kindNoPointers
))
982 objti
= (uintptr
)((const PtrType
*)t
)->elem
->__gc
;
986 objti
= (uintptr
)t
->__gc
;
992 while(stack_top
.b
<= end_b
) {
993 obj
= *(byte
**)stack_top
.b
;
995 runtime_printf("gc_default_ptr @%p: %p\n", stack_top
.b
, obj
);
996 stack_top
.b
+= PtrSize
;
997 if((byte
*)obj
>= arena_start
&& (byte
*)obj
< arena_used
) {
998 *sbuf
.ptr
.pos
++ = (PtrTarget
){obj
, 0};
999 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
1006 if(--stack_top
.count
!= 0) {
1007 // Next iteration of a loop if possible.
1008 stack_top
.b
+= stack_top
.elemsize
;
1009 if(stack_top
.b
+ stack_top
.elemsize
<= end_b
+PtrSize
) {
1010 pc
= stack_top
.loop_or_ret
;
1015 // Stack pop if possible.
1016 if(stack_ptr
+1 < stack
+nelem(stack
)) {
1017 pc
= stack_top
.loop_or_ret
;
1018 stack_top
= *(++stack_ptr
);
1021 i
= (uintptr
)b
+ nominal_size
;
1024 // Quickly scan [b+i,b+n) for possible pointers.
1025 for(; i
<=end_b
; i
+=PtrSize
) {
1026 if(*(byte
**)i
!= nil
) {
1027 // Found a value that may be a pointer.
1028 // Do a rescan of the entire block.
1029 enqueue((Obj
){b
, n
, 0}, &sbuf
.wbuf
, &sbuf
.wp
, &sbuf
.nobj
);
1031 runtime_xadd64(&gcstats
.rescan
, 1);
1032 runtime_xadd64(&gcstats
.rescanbytes
, n
);
1040 case GC_ARRAY_START
:
1041 i
= stack_top
.b
+ pc
[1];
1047 *stack_ptr
-- = stack_top
;
1048 stack_top
= (GCFrame
){count
, elemsize
, i
, pc
};
1052 if(--stack_top
.count
!= 0) {
1053 stack_top
.b
+= stack_top
.elemsize
;
1054 pc
= stack_top
.loop_or_ret
;
1057 stack_top
= *(++stack_ptr
);
1064 *stack_ptr
-- = stack_top
;
1065 stack_top
= (GCFrame
){1, 0, stack_top
.b
+ pc
[1], pc
+3 /*return address*/};
1066 pc
= (const uintptr
*)((const byte
*)pc
+ *(const int32
*)(pc
+2)); // target of the CALL instruction
1070 obj
= (void*)(stack_top
.b
+ pc
[1]);
1076 runtime_printf("gc_region @%p: %D %p\n", stack_top
.b
+pc
[1], (int64
)size
, objti
);
1077 *sbuf
.obj
.pos
++ = (Obj
){obj
, size
, objti
};
1078 if(sbuf
.obj
.pos
== sbuf
.obj
.end
)
1083 chan
= *(Hchan
**)(stack_top
.b
+ pc
[1]);
1084 if(Debug
> 2 && chan
!= nil
)
1085 runtime_printf("gc_chan_ptr @%p: %p/%D/%D %p\n", stack_top
.b
+pc
[1], chan
, (int64
)chan
->qcount
, (int64
)chan
->dataqsiz
, pc
[2]);
1090 if(markonly(chan
)) {
1091 chantype
= (ChanType
*)pc
[2];
1092 if(!(chantype
->elem
->__code
& kindNoPointers
)) {
1103 // There are no heap pointers in struct Hchan,
1104 // so we can ignore the leading sizeof(Hchan) bytes.
1105 if(!(chantype
->elem
->__code
& kindNoPointers
)) {
1106 chancap
= chan
->dataqsiz
;
1107 if(chancap
> 0 && markonly(chan
->buf
)) {
1108 // TODO(atom): split into two chunks so that only the
1109 // in-use part of the circular buffer is scanned.
1110 // (Channel routines zero the unused part, so the current
1111 // code does not lead to leaks, it's just a little inefficient.)
1112 *sbuf
.obj
.pos
++ = (Obj
){chan
->buf
, chancap
*chantype
->elem
->__size
,
1113 (uintptr
)chantype
->elem
->__gc
| PRECISE
| LOOP
};
1114 if(sbuf
.obj
.pos
== sbuf
.obj
.end
)
1124 runtime_printf("runtime: invalid GC instruction %p at %p\n", pc
[0], pc
);
1125 runtime_throw("scanblock: invalid GC instruction");
1129 if((byte
*)obj
>= arena_start
&& (byte
*)obj
< arena_used
) {
1130 *sbuf
.ptr
.pos
++ = (PtrTarget
){obj
, objti
};
1131 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
1137 // Done scanning [b, b+n). Prepare for the next iteration of
1138 // the loop by setting b, n, ti to the parameters for the next block.
1140 if(sbuf
.nobj
== 0) {
1144 if(sbuf
.nobj
== 0) {
1147 putempty(sbuf
.wbuf
);
1150 // Emptied our buffer: refill.
1151 sbuf
.wbuf
= getfull(sbuf
.wbuf
);
1152 if(sbuf
.wbuf
== nil
)
1154 sbuf
.nobj
= sbuf
.wbuf
->nobj
;
1155 sbuf
.wp
= sbuf
.wbuf
->obj
+ sbuf
.wbuf
->nobj
;
1159 // Fetch b from the work buffer.
1168 static struct root_list
* roots
;
1171 __go_register_gc_roots (struct root_list
* r
)
1173 // FIXME: This needs locking if multiple goroutines can call
1174 // dlopen simultaneously.
1179 // Append obj to the work buffer.
1180 // _wbuf, _wp, _nobj are input/output parameters and are specifying the work buffer.
1182 enqueue(Obj obj
, Workbuf
**_wbuf
, Obj
**_wp
, uintptr
*_nobj
)
1189 runtime_printf("append obj(%p %D %p)\n", obj
.p
, (int64
)obj
.n
, obj
.ti
);
1191 // Align obj.b to a word boundary.
1192 off
= (uintptr
)obj
.p
& (PtrSize
-1);
1194 obj
.p
+= PtrSize
- off
;
1195 obj
.n
-= PtrSize
- off
;
1199 if(obj
.p
== nil
|| obj
.n
== 0)
1202 // Load work buffer state
1207 // If another proc wants a pointer, give it some.
1208 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
1210 wbuf
= handoff(wbuf
);
1212 wp
= wbuf
->obj
+ nobj
;
1215 // If buffer is full, get a new one.
1216 if(wbuf
== nil
|| nobj
>= nelem(wbuf
->obj
)) {
1219 wbuf
= getempty(wbuf
);
1228 // Save work buffer state
1235 enqueue1(Workbuf
**wbufp
, Obj obj
)
1240 if(wbuf
->nobj
>= nelem(wbuf
->obj
))
1241 *wbufp
= wbuf
= getempty(wbuf
);
1242 wbuf
->obj
[wbuf
->nobj
++] = obj
;
1246 markroot(ParFor
*desc
, uint32 i
)
1251 MSpan
**allspans
, *s
;
1257 wbuf
= getempty(nil
);
1258 // Note: if you add a case here, please also update heapdump.c:dumproots.
1261 // For gccgo this is both data and bss.
1263 struct root_list
*pl
;
1265 for(pl
= roots
; pl
!= nil
; pl
= pl
->next
) {
1266 struct root
*pr
= &pl
->roots
[0];
1268 void *decl
= pr
->decl
;
1271 enqueue1(&wbuf
, (Obj
){decl
, pr
->size
, 0});
1279 // For gccgo we use this for all the other global roots.
1280 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_m0
, sizeof runtime_m0
, 0});
1281 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_g0
, sizeof runtime_g0
, 0});
1282 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allg
, sizeof runtime_allg
, 0});
1283 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allm
, sizeof runtime_allm
, 0});
1284 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allp
, sizeof runtime_allp
, 0});
1285 enqueue1(&wbuf
, (Obj
){(byte
*)&work
, sizeof work
, 0});
1288 case RootFinalizers
:
1289 for(fb
=allfin
; fb
; fb
=fb
->alllink
)
1290 enqueue1(&wbuf
, (Obj
){(byte
*)fb
->fin
, fb
->cnt
*sizeof(fb
->fin
[0]), 0});
1294 // mark span types and MSpan.specials (to walk spans only once)
1297 allspans
= h
->allspans
;
1298 for(spanidx
=0; spanidx
<runtime_mheap
.nspan
; spanidx
++) {
1300 SpecialFinalizer
*spf
;
1302 s
= allspans
[spanidx
];
1303 if(s
->sweepgen
!= sg
) {
1304 runtime_printf("sweep %d %d\n", s
->sweepgen
, sg
);
1305 runtime_throw("gc: unswept span");
1307 if(s
->state
!= MSpanInUse
)
1309 // The garbage collector ignores type pointers stored in MSpan.types:
1310 // - Compiler-generated types are stored outside of heap.
1311 // - The reflect package has runtime-generated types cached in its data structures.
1312 // The garbage collector relies on finding the references via that cache.
1313 if(s
->types
.compression
== MTypes_Words
|| s
->types
.compression
== MTypes_Bytes
)
1314 markonly((byte
*)s
->types
.data
);
1315 for(sp
= s
->specials
; sp
!= nil
; sp
= sp
->next
) {
1316 if(sp
->kind
!= KindSpecialFinalizer
)
1318 // don't mark finalized object, but scan it so we
1319 // retain everything it points to.
1320 spf
= (SpecialFinalizer
*)sp
;
1321 // A finalizer can be set for an inner byte of an object, find object beginning.
1322 p
= (void*)((s
->start
<< PageShift
) + spf
->offset
/s
->elemsize
*s
->elemsize
);
1323 enqueue1(&wbuf
, (Obj
){p
, s
->elemsize
, 0});
1324 enqueue1(&wbuf
, (Obj
){(void*)&spf
->fn
, PtrSize
, 0});
1325 enqueue1(&wbuf
, (Obj
){(void*)&spf
->ft
, PtrSize
, 0});
1326 enqueue1(&wbuf
, (Obj
){(void*)&spf
->ot
, PtrSize
, 0});
1331 case RootFlushCaches
:
1336 // the rest is scanning goroutine stacks
1337 if(i
- RootCount
>= runtime_allglen
)
1338 runtime_throw("markroot: bad index");
1339 gp
= runtime_allg
[i
- RootCount
];
1340 // remember when we've first observed the G blocked
1341 // needed only to output in traceback
1342 if((gp
->atomicstatus
== _Gwaiting
|| gp
->atomicstatus
== _Gsyscall
) && gp
->waitsince
== 0)
1343 gp
->waitsince
= work
.tstart
;
1344 addstackroots(gp
, &wbuf
);
1350 scanblock(wbuf
, false);
1353 static const FuncVal markroot_funcval
= { (void *) markroot
};
1355 // Get an empty work buffer off the work.empty list,
1356 // allocating new buffers as needed.
1358 getempty(Workbuf
*b
)
1361 runtime_lfstackpush(&work
.full
, &b
->node
);
1362 b
= (Workbuf
*)runtime_lfstackpop(&work
.wempty
);
1364 // Need to allocate.
1365 runtime_lock(&work
);
1366 if(work
.nchunk
< sizeof *b
) {
1367 work
.nchunk
= 1<<20;
1368 work
.chunk
= runtime_SysAlloc(work
.nchunk
, &mstats()->gc_sys
);
1369 if(work
.chunk
== nil
)
1370 runtime_throw("runtime: cannot allocate memory");
1372 b
= (Workbuf
*)work
.chunk
;
1373 work
.chunk
+= sizeof *b
;
1374 work
.nchunk
-= sizeof *b
;
1375 runtime_unlock(&work
);
1382 putempty(Workbuf
*b
)
1385 runtime_xadd64(&gcstats
.putempty
, 1);
1387 runtime_lfstackpush(&work
.wempty
, &b
->node
);
1390 // Get a full work buffer off the work.full list, or return nil.
1398 runtime_xadd64(&gcstats
.getfull
, 1);
1401 runtime_lfstackpush(&work
.wempty
, &b
->node
);
1402 b
= (Workbuf
*)runtime_lfstackpop(&work
.full
);
1403 if(b
!= nil
|| work
.nproc
== 1)
1407 runtime_xadd(&work
.nwait
, +1);
1409 if(work
.full
!= 0) {
1410 runtime_xadd(&work
.nwait
, -1);
1411 b
= (Workbuf
*)runtime_lfstackpop(&work
.full
);
1414 runtime_xadd(&work
.nwait
, +1);
1416 if(work
.nwait
== work
.nproc
)
1419 m
->gcstats
.nprocyield
++;
1420 runtime_procyield(20);
1422 m
->gcstats
.nosyield
++;
1425 m
->gcstats
.nsleep
++;
1426 runtime_usleep(100);
1440 // Make new buffer with half of b's pointers.
1445 runtime_memmove(b1
->obj
, b
->obj
+b
->nobj
, n
*sizeof b1
->obj
[0]);
1446 m
->gcstats
.nhandoff
++;
1447 m
->gcstats
.nhandoffcnt
+= n
;
1449 // Put b on full list - let first half of b get stolen.
1450 runtime_lfstackpush(&work
.full
, &b
->node
);
1455 addstackroots(G
*gp
, Workbuf
**wbufp
)
1457 switch(gp
->atomicstatus
){
1459 runtime_printf("unexpected G.status %d (goroutine %p %D)\n", gp
->atomicstatus
, gp
, gp
->goid
);
1460 runtime_throw("mark - bad status");
1464 runtime_throw("mark - world not stopped");
1471 #ifdef USING_SPLIT_STACK
1479 if(gp
== runtime_g()) {
1480 // Scanning our own stack.
1481 sp
= __splitstack_find(nil
, nil
, &spsize
, &next_segment
,
1482 &next_sp
, &initial_sp
);
1483 } else if((mp
= gp
->m
) != nil
&& mp
->helpgc
) {
1484 // gchelper's stack is in active use and has no interesting pointers.
1487 // Scanning another goroutine's stack.
1488 // The goroutine is usually asleep (the world is stopped).
1490 // The exception is that if the goroutine is about to enter or might
1491 // have just exited a system call, it may be executing code such
1492 // as schedlock and may have needed to start a new stack segment.
1493 // Use the stack segment and stack pointer at the time of
1494 // the system call instead, since that won't change underfoot.
1495 if(gp
->gcstack
!= nil
) {
1497 spsize
= gp
->gcstacksize
;
1498 next_segment
= gp
->gcnextsegment
;
1499 next_sp
= gp
->gcnextsp
;
1500 initial_sp
= gp
->gcinitialsp
;
1502 sp
= __splitstack_find_context(&gp
->stackcontext
[0],
1503 &spsize
, &next_segment
,
1504 &next_sp
, &initial_sp
);
1508 enqueue1(wbufp
, (Obj
){sp
, spsize
, 0});
1509 while((sp
= __splitstack_find(next_segment
, next_sp
,
1510 &spsize
, &next_segment
,
1511 &next_sp
, &initial_sp
)) != nil
)
1512 enqueue1(wbufp
, (Obj
){sp
, spsize
, 0});
1519 if(gp
== runtime_g()) {
1520 // Scanning our own stack.
1521 bottom
= (byte
*)&gp
;
1522 } else if((mp
= gp
->m
) != nil
&& mp
->helpgc
) {
1523 // gchelper's stack is in active use and has no interesting pointers.
1526 // Scanning another goroutine's stack.
1527 // The goroutine is usually asleep (the world is stopped).
1528 bottom
= (byte
*)gp
->gcnextsp
;
1532 top
= (byte
*)gp
->gcinitialsp
+ gp
->gcstacksize
;
1534 enqueue1(wbufp
, (Obj
){bottom
, top
- bottom
, 0});
1536 enqueue1(wbufp
, (Obj
){top
, bottom
- top
, 0});
1541 runtime_queuefinalizer(void *p
, FuncVal
*fn
, const FuncType
*ft
, const PtrType
*ot
)
1546 runtime_lock(&finlock
);
1547 if(finq
== nil
|| finq
->cnt
== finq
->cap
) {
1549 finc
= runtime_persistentalloc(FinBlockSize
, 0, &mstats()->gc_sys
);
1550 finc
->cap
= (FinBlockSize
- sizeof(FinBlock
)) / sizeof(Finalizer
) + 1;
1551 finc
->alllink
= allfin
;
1559 f
= &finq
->fin
[finq
->cnt
];
1565 runtime_fingwake
= true;
1566 runtime_unlock(&finlock
);
1570 runtime_iterate_finq(void (*callback
)(FuncVal
*, void*, const FuncType
*, const PtrType
*))
1576 for(fb
= allfin
; fb
; fb
= fb
->alllink
) {
1577 for(i
= 0; i
< fb
->cnt
; i
++) {
1579 callback(f
->fn
, f
->arg
, f
->ft
, f
->ot
);
1585 runtime_MSpan_EnsureSwept(MSpan
*s
)
1591 // Caller must disable preemption.
1592 // Otherwise when this function returns the span can become unswept again
1593 // (if GC is triggered on another goroutine).
1594 if(m
->locks
== 0 && m
->mallocing
== 0 && g
!= m
->g0
)
1595 runtime_throw("MSpan_EnsureSwept: m is not locked");
1597 sg
= runtime_mheap
.sweepgen
;
1598 if(runtime_atomicload(&s
->sweepgen
) == sg
)
1600 if(runtime_cas(&s
->sweepgen
, sg
-2, sg
-1)) {
1601 runtime_MSpan_Sweep(s
);
1604 // unfortunate condition, and we don't have efficient means to wait
1605 while(runtime_atomicload(&s
->sweepgen
) != sg
)
1609 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
1610 // It clears the mark bits in preparation for the next GC round.
1611 // Returns true if the span was returned to heap.
1613 runtime_MSpan_Sweep(MSpan
*s
)
1616 int32 cl
, n
, npages
, nfree
;
1617 uintptr size
, off
, *bitp
, shift
, bits
;
1625 uintptr type_data_inc
;
1627 Special
*special
, **specialp
, *y
;
1628 bool res
, sweepgenset
;
1632 // It's critical that we enter this function with preemption disabled,
1633 // GC must not start while we are in the middle of this function.
1634 if(m
->locks
== 0 && m
->mallocing
== 0 && runtime_g() != m
->g0
)
1635 runtime_throw("MSpan_Sweep: m is not locked");
1636 sweepgen
= runtime_mheap
.sweepgen
;
1637 if(s
->state
!= MSpanInUse
|| s
->sweepgen
!= sweepgen
-1) {
1638 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1639 s
->state
, s
->sweepgen
, sweepgen
);
1640 runtime_throw("MSpan_Sweep: bad span state");
1642 arena_start
= runtime_mheap
.arena_start
;
1648 // Chunk full of small blocks.
1649 npages
= runtime_class_to_allocnpages
[cl
];
1650 n
= (npages
<< PageShift
) / size
;
1656 sweepgenset
= false;
1658 // mark any free objects in this span so we don't collect them
1659 for(x
= s
->freelist
; x
!= nil
; x
= x
->next
) {
1660 // This is markonly(x) but faster because we don't need
1661 // atomic access and we're guaranteed to be pointing at
1662 // the head of a valid object.
1663 off
= (uintptr
*)x
- (uintptr
*)runtime_mheap
.arena_start
;
1664 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
1665 shift
= off
% wordsPerBitmapWord
;
1666 *bitp
|= bitMarked
<<shift
;
1669 // Unlink & free special records for any objects we're about to free.
1670 specialp
= &s
->specials
;
1671 special
= *specialp
;
1672 while(special
!= nil
) {
1673 // A finalizer can be set for an inner byte of an object, find object beginning.
1674 p
= (byte
*)(s
->start
<< PageShift
) + special
->offset
/size
*size
;
1675 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1676 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1677 shift
= off
% wordsPerBitmapWord
;
1678 bits
= *bitp
>>shift
;
1679 if((bits
& (bitAllocated
|bitMarked
)) == bitAllocated
) {
1680 // Find the exact byte for which the special was setup
1681 // (as opposed to object beginning).
1682 p
= (byte
*)(s
->start
<< PageShift
) + special
->offset
;
1683 // about to free object: splice out special record
1685 special
= special
->next
;
1686 *specialp
= special
;
1687 if(!runtime_freespecial(y
, p
, size
, false)) {
1688 // stop freeing of object if it has a finalizer
1689 *bitp
|= bitMarked
<< shift
;
1692 // object is still live: keep special record
1693 specialp
= &special
->next
;
1694 special
= *specialp
;
1698 type_data
= (byte
*)s
->types
.data
;
1699 type_data_inc
= sizeof(uintptr
);
1700 compression
= s
->types
.compression
;
1701 switch(compression
) {
1703 type_data
+= 8*sizeof(uintptr
);
1708 // Sweep through n objects of given size starting at p.
1709 // This thread owns the span now, so it can manipulate
1710 // the block bitmap without atomic operations.
1711 p
= (byte
*)(s
->start
<< PageShift
);
1712 for(; n
> 0; n
--, p
+= size
, type_data
+=type_data_inc
) {
1713 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1714 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1715 shift
= off
% wordsPerBitmapWord
;
1716 bits
= *bitp
>>shift
;
1718 if((bits
& bitAllocated
) == 0)
1721 if((bits
& bitMarked
) != 0) {
1722 *bitp
&= ~(bitMarked
<<shift
);
1726 if(runtime_debug
.allocfreetrace
)
1727 runtime_tracefree(p
, size
);
1729 // Clear mark and scan bits.
1730 *bitp
&= ~((bitScan
|bitMarked
)<<shift
);
1734 runtime_unmarkspan(p
, 1<<PageShift
);
1736 // important to set sweepgen before returning it to heap
1737 runtime_atomicstore(&s
->sweepgen
, sweepgen
);
1739 // See note about SysFault vs SysFree in malloc.goc.
1740 if(runtime_debug
.efence
)
1741 runtime_SysFault(p
, size
);
1743 runtime_MHeap_Free(&runtime_mheap
, s
, 1);
1744 c
->local_nlargefree
++;
1745 c
->local_largefree
+= size
;
1746 runtime_xadd64(&mstats()->next_gc
, -(uint64
)(size
* (gcpercent
+ 100)/100));
1749 // Free small object.
1750 switch(compression
) {
1752 *(uintptr
*)type_data
= 0;
1755 *(byte
*)type_data
= 0;
1758 if(size
> 2*sizeof(uintptr
))
1759 ((uintptr
*)p
)[1] = (uintptr
)0xdeaddeaddeaddeadll
; // mark as "needs to be zeroed"
1760 else if(size
> sizeof(uintptr
))
1761 ((uintptr
*)p
)[1] = 0;
1763 end
->next
= (MLink
*)p
;
1769 // We need to set s->sweepgen = h->sweepgen only when all blocks are swept,
1770 // because of the potential for a concurrent free/SetFinalizer.
1771 // But we need to set it before we make the span available for allocation
1772 // (return it to heap or mcentral), because allocation code assumes that a
1773 // span is already swept if available for allocation.
1775 if(!sweepgenset
&& nfree
== 0) {
1776 // The span must be in our exclusive ownership until we update sweepgen,
1777 // check for potential races.
1778 if(s
->state
!= MSpanInUse
|| s
->sweepgen
!= sweepgen
-1) {
1779 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1780 s
->state
, s
->sweepgen
, sweepgen
);
1781 runtime_throw("MSpan_Sweep: bad span state after sweep");
1783 runtime_atomicstore(&s
->sweepgen
, sweepgen
);
1786 c
->local_nsmallfree
[cl
] += nfree
;
1787 c
->local_cachealloc
-= nfree
* size
;
1788 runtime_xadd64(&mstats()->next_gc
, -(uint64
)(nfree
* size
* (gcpercent
+ 100)/100));
1789 res
= runtime_MCentral_FreeSpan(&runtime_mheap
.central
[cl
], s
, nfree
, head
.next
, end
);
1790 //MCentral_FreeSpan updates sweepgen
1795 // State of background sweep.
1796 // Protected by gclock.
1807 // background sweeping goroutine
1809 bgsweep(void* dummy
__attribute__ ((unused
)))
1811 runtime_g()->issystem
= 1;
1813 while(runtime_sweepone() != (uintptr
)-1) {
1817 runtime_lock(&gclock
);
1818 if(!runtime_mheap
.sweepdone
) {
1819 // It's possible if GC has happened between sweepone has
1820 // returned -1 and gclock lock.
1821 runtime_unlock(&gclock
);
1824 sweep
.parked
= true;
1825 runtime_g()->isbackground
= true;
1826 runtime_parkunlock(&gclock
, "GC sweep wait");
1827 runtime_g()->isbackground
= false;
1832 // returns number of pages returned to heap, or -1 if there is nothing to sweep
1834 runtime_sweepone(void)
1841 // increment locks to ensure that the goroutine is not preempted
1842 // in the middle of sweep thus leaving the span in an inconsistent state for next GC
1844 sg
= runtime_mheap
.sweepgen
;
1846 idx
= runtime_xadd(&sweep
.spanidx
, 1) - 1;
1847 if(idx
>= sweep
.nspan
) {
1848 runtime_mheap
.sweepdone
= true;
1852 s
= sweep
.spans
[idx
];
1853 if(s
->state
!= MSpanInUse
) {
1857 if(s
->sweepgen
!= sg
-2 || !runtime_cas(&s
->sweepgen
, sg
-2, sg
-1))
1860 runtime_throw("sweep of incache span");
1862 if(!runtime_MSpan_Sweep(s
))
1870 dumpspan(uint32 idx
)
1872 int32 sizeclass
, n
, npages
, i
, column
;
1879 s
= runtime_mheap
.allspans
[idx
];
1880 if(s
->state
!= MSpanInUse
)
1882 arena_start
= runtime_mheap
.arena_start
;
1883 p
= (byte
*)(s
->start
<< PageShift
);
1884 sizeclass
= s
->sizeclass
;
1886 if(sizeclass
== 0) {
1889 npages
= runtime_class_to_allocnpages
[sizeclass
];
1890 n
= (npages
<< PageShift
) / size
;
1893 runtime_printf("%p .. %p:\n", p
, p
+n
*size
);
1895 for(; n
>0; n
--, p
+=size
) {
1896 uintptr off
, *bitp
, shift
, bits
;
1898 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1899 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1900 shift
= off
% wordsPerBitmapWord
;
1901 bits
= *bitp
>>shift
;
1903 allocated
= ((bits
& bitAllocated
) != 0);
1905 for(i
=0; (uint32
)i
<size
; i
+=sizeof(void*)) {
1907 runtime_printf("\t");
1910 runtime_printf(allocated
? "(" : "[");
1911 runtime_printf("%p: ", p
+i
);
1913 runtime_printf(" ");
1916 runtime_printf("%p", *(void**)(p
+i
));
1918 if(i
+sizeof(void*) >= size
) {
1919 runtime_printf(allocated
? ") " : "] ");
1924 runtime_printf("\n");
1929 runtime_printf("\n");
1932 // A debugging function to dump the contents of memory
1934 runtime_memorydump(void)
1938 for(spanidx
=0; spanidx
<runtime_mheap
.nspan
; spanidx
++) {
1944 runtime_gchelper(void)
1948 runtime_m()->traceback
= 2;
1951 // parallel mark for over gc roots
1952 runtime_parfordo(work
.markfor
);
1954 // help other threads scan secondary blocks
1955 scanblock(nil
, true);
1957 bufferList
[runtime_m()->helpgc
].busy
= 0;
1958 nproc
= work
.nproc
; // work.nproc can change right after we increment work.ndone
1959 if(runtime_xadd(&work
.ndone
, +1) == nproc
-1)
1960 runtime_notewakeup(&work
.alldone
);
1961 runtime_m()->traceback
= 0;
1970 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
1974 runtime_purgecachedstats(c
);
1979 flushallmcaches(void)
1984 // Flush MCache's to MCentral.
1985 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
1989 runtime_MCache_ReleaseAll(c
);
1994 runtime_updatememstats(GCStats
*stats
)
1999 uint64 stacks_inuse
, smallfree
;
2004 runtime_memclr((byte
*)stats
, sizeof(*stats
));
2006 for(mp
=runtime_allm
; mp
; mp
=mp
->alllink
) {
2007 //stacks_inuse += mp->stackinuse*FixedStack;
2009 src
= (uint64
*)&mp
->gcstats
;
2010 dst
= (uint64
*)stats
;
2011 for(i
=0; i
<sizeof(*stats
)/sizeof(uint64
); i
++)
2013 runtime_memclr((byte
*)&mp
->gcstats
, sizeof(mp
->gcstats
));
2017 pmstats
->stacks_inuse
= stacks_inuse
;
2018 pmstats
->mcache_inuse
= runtime_mheap
.cachealloc
.inuse
;
2019 pmstats
->mspan_inuse
= runtime_mheap
.spanalloc
.inuse
;
2020 pmstats
->sys
= pmstats
->heap_sys
+ pmstats
->stacks_sys
+ pmstats
->mspan_sys
+
2021 pmstats
->mcache_sys
+ pmstats
->buckhash_sys
+ pmstats
->gc_sys
+ pmstats
->other_sys
;
2023 // Calculate memory allocator stats.
2024 // During program execution we only count number of frees and amount of freed memory.
2025 // Current number of alive object in the heap and amount of alive heap memory
2026 // are calculated by scanning all spans.
2027 // Total number of mallocs is calculated as number of frees plus number of alive objects.
2028 // Similarly, total amount of allocated memory is calculated as amount of freed memory
2029 // plus amount of alive heap memory.
2031 pmstats
->total_alloc
= 0;
2032 pmstats
->nmalloc
= 0;
2034 for(i
= 0; i
< nelem(pmstats
->by_size
); i
++) {
2035 pmstats
->by_size
[i
].nmalloc
= 0;
2036 pmstats
->by_size
[i
].nfree
= 0;
2039 // Flush MCache's to MCentral.
2042 // Aggregate local stats.
2045 // Scan all spans and count number of alive objects.
2046 for(i
= 0; i
< runtime_mheap
.nspan
; i
++) {
2047 s
= runtime_mheap
.allspans
[i
];
2048 if(s
->state
!= MSpanInUse
)
2050 if(s
->sizeclass
== 0) {
2052 pmstats
->alloc
+= s
->elemsize
;
2054 pmstats
->nmalloc
+= s
->ref
;
2055 pmstats
->by_size
[s
->sizeclass
].nmalloc
+= s
->ref
;
2056 pmstats
->alloc
+= s
->ref
*s
->elemsize
;
2060 // Aggregate by size class.
2062 pmstats
->nfree
= runtime_mheap
.nlargefree
;
2063 for(i
= 0; i
< nelem(pmstats
->by_size
); i
++) {
2064 pmstats
->nfree
+= runtime_mheap
.nsmallfree
[i
];
2065 pmstats
->by_size
[i
].nfree
= runtime_mheap
.nsmallfree
[i
];
2066 pmstats
->by_size
[i
].nmalloc
+= runtime_mheap
.nsmallfree
[i
];
2067 smallfree
+= runtime_mheap
.nsmallfree
[i
] * runtime_class_to_size
[i
];
2069 pmstats
->nmalloc
+= pmstats
->nfree
;
2071 // Calculate derived stats.
2072 pmstats
->total_alloc
= pmstats
->alloc
+ runtime_mheap
.largefree
+ smallfree
;
2073 pmstats
->heap_alloc
= pmstats
->alloc
;
2074 pmstats
->heap_objects
= pmstats
->nmalloc
- pmstats
->nfree
;
2077 // Structure of arguments passed to function gc().
2078 // This allows the arguments to be passed via runtime_mcall.
2081 int64 start_time
; // start time of GC in ns (just before stoptheworld)
2085 static void gc(struct gc_args
*args
);
2086 static void mgc(G
*gp
);
2094 s
= runtime_getenv("GOGC");
2098 if(s
.len
== 3 && runtime_strcmp((const char *)p
, "off") == 0)
2100 return runtime_atoi(p
, s
.len
);
2103 // force = 1 - do GC regardless of current heap usage
2104 // force = 2 - go GC and eager sweep
2106 runtime_gc(int32 force
)
2114 // The atomic operations are not atomic if the uint64s
2115 // are not aligned on uint64 boundaries. This has been
2116 // a problem in the past.
2117 if((((uintptr
)&work
.wempty
) & 7) != 0)
2118 runtime_throw("runtime: gc work buffer is misaligned");
2119 if((((uintptr
)&work
.full
) & 7) != 0)
2120 runtime_throw("runtime: gc work buffer is misaligned");
2122 // Make sure all registers are saved on stack so that
2123 // scanstack sees them.
2124 __builtin_unwind_init();
2126 // The gc is turned off (via enablegc) until
2127 // the bootstrap has completed.
2128 // Also, malloc gets called in the guts
2129 // of a number of libraries that might be
2130 // holding locks. To avoid priority inversion
2131 // problems, don't bother trying to run gc
2132 // while holding a lock. The next mallocgc
2133 // without a lock will do the gc instead.
2136 if(!pmstats
->enablegc
|| runtime_g() == m
->g0
|| m
->locks
> 0 || runtime_panicking() || m
->preemptoff
.len
> 0)
2139 if(gcpercent
== GcpercentUnknown
) { // first time through
2140 runtime_lock(&runtime_mheap
);
2141 if(gcpercent
== GcpercentUnknown
)
2142 gcpercent
= readgogc();
2143 runtime_unlock(&runtime_mheap
);
2148 runtime_acquireWorldsema();
2149 if(force
==0 && pmstats
->heap_alloc
< pmstats
->next_gc
) {
2150 // typically threads which lost the race to grab
2151 // worldsema exit here when gc is done.
2152 runtime_releaseWorldsema();
2156 // Ok, we're doing it! Stop everybody else
2157 a
.start_time
= runtime_nanotime();
2158 a
.eagersweep
= force
>= 2;
2160 runtime_stopTheWorldWithSema();
2164 // Run gc on the g0 stack. We do this so that the g stack
2165 // we're currently running on will no longer change. Cuts
2166 // the root set down a bit (g0 stacks are not scanned, and
2167 // we don't need to scan gc's internal state). Also an
2168 // enabler for copyable stacks.
2169 for(i
= 0; i
< (runtime_debug
.gctrace
> 1 ? 2 : 1); i
++) {
2171 a
.start_time
= runtime_nanotime();
2172 // switch to g0, call gc(&a), then switch back
2175 g
->atomicstatus
= _Gwaiting
;
2176 g
->waitreason
= runtime_gostringnocopy((const byte
*)"garbage collection");
2184 runtime_releaseWorldsema();
2185 runtime_startTheWorldWithSema();
2188 // now that gc is done, kick off finalizer thread if needed
2189 if(!ConcurrentSweep
) {
2190 // give the queued finalizers, if any, a chance to run
2193 // For gccgo, let other goroutines run.
2203 gp
->atomicstatus
= _Grunning
;
2208 gc(struct gc_args
*args
)
2211 int64 tm0
, tm1
, tm2
, tm3
, tm4
;
2212 uint64 heap0
, heap1
, obj
, ninstr
;
2220 if(runtime_debug
.allocfreetrace
)
2224 tm0
= args
->start_time
;
2225 work
.tstart
= args
->start_time
;
2228 runtime_memclr((byte
*)&gcstats
, sizeof(gcstats
));
2230 m
->locks
++; // disable gc during mallocs in parforalloc
2231 if(work
.markfor
== nil
)
2232 work
.markfor
= runtime_parforalloc(MaxGcproc
);
2236 if(runtime_debug
.gctrace
)
2237 tm1
= runtime_nanotime();
2239 // Sweep what is not sweeped by bgsweep.
2240 while(runtime_sweepone() != (uintptr
)-1)
2241 gcstats
.npausesweep
++;
2245 work
.nproc
= runtime_gcprocs();
2246 runtime_parforsetup(work
.markfor
, work
.nproc
, RootCount
+ runtime_allglen
, false, &markroot_funcval
);
2247 if(work
.nproc
> 1) {
2248 runtime_noteclear(&work
.alldone
);
2249 runtime_helpgc(work
.nproc
);
2253 if(runtime_debug
.gctrace
)
2254 tm2
= runtime_nanotime();
2257 runtime_parfordo(work
.markfor
);
2258 scanblock(nil
, true);
2261 if(runtime_debug
.gctrace
)
2262 tm3
= runtime_nanotime();
2264 bufferList
[m
->helpgc
].busy
= 0;
2266 runtime_notesleep(&work
.alldone
);
2269 // next_gc calculation is tricky with concurrent sweep since we don't know size of live heap
2270 // estimate what was live heap size after previous GC (for tracing only)
2272 heap0
= pmstats
->next_gc
*100/(gcpercent
+100);
2273 // conservatively set next_gc to high value assuming that everything is live
2274 // concurrent/lazy sweep will reduce this number while discovering new garbage
2275 pmstats
->next_gc
= pmstats
->heap_alloc
+(pmstats
->heap_alloc
-runtime_stacks_sys
)*gcpercent
/100;
2277 tm4
= runtime_nanotime();
2278 pmstats
->last_gc
= runtime_unixnanotime(); // must be Unix time to make sense to user
2279 pmstats
->pause_ns
[pmstats
->numgc
%nelem(pmstats
->pause_ns
)] = tm4
- tm0
;
2280 pmstats
->pause_end
[pmstats
->numgc
%nelem(pmstats
->pause_end
)] = pmstats
->last_gc
;
2281 pmstats
->pause_total_ns
+= tm4
- tm0
;
2283 if(pmstats
->debuggc
)
2284 runtime_printf("pause %D\n", tm4
-tm0
);
2286 if(runtime_debug
.gctrace
) {
2287 heap1
= pmstats
->heap_alloc
;
2288 runtime_updatememstats(&stats
);
2289 if(heap1
!= pmstats
->heap_alloc
) {
2290 runtime_printf("runtime: mstats skew: heap=%D/%D\n", heap1
, pmstats
->heap_alloc
);
2291 runtime_throw("mstats skew");
2293 obj
= pmstats
->nmalloc
- pmstats
->nfree
;
2295 stats
.nprocyield
+= work
.markfor
->nprocyield
;
2296 stats
.nosyield
+= work
.markfor
->nosyield
;
2297 stats
.nsleep
+= work
.markfor
->nsleep
;
2299 runtime_printf("gc%d(%d): %D+%D+%D+%D us, %D -> %D MB, %D (%D-%D) objects,"
2301 " %D(%D) handoff, %D(%D) steal, %D/%D/%D yields\n",
2302 pmstats
->numgc
, work
.nproc
, (tm1
-tm0
)/1000, (tm2
-tm1
)/1000, (tm3
-tm2
)/1000, (tm4
-tm3
)/1000,
2303 heap0
>>20, heap1
>>20, obj
,
2304 pmstats
->nmalloc
, pmstats
->nfree
,
2305 sweep
.nspan
, gcstats
.nbgsweep
, gcstats
.npausesweep
,
2306 stats
.nhandoff
, stats
.nhandoffcnt
,
2307 work
.markfor
->nsteal
, work
.markfor
->nstealcnt
,
2308 stats
.nprocyield
, stats
.nosyield
, stats
.nsleep
);
2309 gcstats
.nbgsweep
= gcstats
.npausesweep
= 0;
2311 runtime_printf("scan: %D bytes, %D objects, %D untyped, %D types from MSpan\n",
2312 gcstats
.nbytes
, gcstats
.obj
.cnt
, gcstats
.obj
.notype
, gcstats
.obj
.typelookup
);
2313 if(gcstats
.ptr
.cnt
!= 0)
2314 runtime_printf("avg ptrbufsize: %D (%D/%D)\n",
2315 gcstats
.ptr
.sum
/gcstats
.ptr
.cnt
, gcstats
.ptr
.sum
, gcstats
.ptr
.cnt
);
2316 if(gcstats
.obj
.cnt
!= 0)
2317 runtime_printf("avg nobj: %D (%D/%D)\n",
2318 gcstats
.obj
.sum
/gcstats
.obj
.cnt
, gcstats
.obj
.sum
, gcstats
.obj
.cnt
);
2319 runtime_printf("rescans: %D, %D bytes\n", gcstats
.rescan
, gcstats
.rescanbytes
);
2321 runtime_printf("instruction counts:\n");
2323 for(i
=0; i
<nelem(gcstats
.instr
); i
++) {
2324 runtime_printf("\t%d:\t%D\n", i
, gcstats
.instr
[i
]);
2325 ninstr
+= gcstats
.instr
[i
];
2327 runtime_printf("\ttotal:\t%D\n", ninstr
);
2329 runtime_printf("putempty: %D, getfull: %D\n", gcstats
.putempty
, gcstats
.getfull
);
2331 runtime_printf("markonly base lookup: bit %D word %D span %D\n", gcstats
.markonly
.foundbit
, gcstats
.markonly
.foundword
, gcstats
.markonly
.foundspan
);
2332 runtime_printf("flushptrbuf base lookup: bit %D word %D span %D\n", gcstats
.flushptrbuf
.foundbit
, gcstats
.flushptrbuf
.foundword
, gcstats
.flushptrbuf
.foundspan
);
2336 // We cache current runtime_mheap.allspans array in sweep.spans,
2337 // because the former can be resized and freed.
2338 // Otherwise we would need to take heap lock every time
2339 // we want to convert span index to span pointer.
2341 // Free the old cached array if necessary.
2342 if(sweep
.spans
&& sweep
.spans
!= runtime_mheap
.allspans
)
2343 runtime_SysFree(sweep
.spans
, sweep
.nspan
*sizeof(sweep
.spans
[0]), &pmstats
->other_sys
);
2344 // Cache the current array.
2345 runtime_mheap
.sweepspans
= runtime_mheap
.allspans
;
2346 runtime_mheap
.sweepgen
+= 2;
2347 runtime_mheap
.sweepdone
= false;
2348 sweep
.spans
= runtime_mheap
.allspans
;
2349 sweep
.nspan
= runtime_mheap
.nspan
;
2352 // Temporary disable concurrent sweep, because we see failures on builders.
2353 if(ConcurrentSweep
&& !args
->eagersweep
) {
2354 runtime_lock(&gclock
);
2356 sweep
.g
= __go_go(bgsweep
, nil
);
2357 else if(sweep
.parked
) {
2358 sweep
.parked
= false;
2359 runtime_ready(sweep
.g
);
2361 runtime_unlock(&gclock
);
2363 // Sweep all spans eagerly.
2364 while(runtime_sweepone() != (uintptr
)-1)
2365 gcstats
.npausesweep
++;
2366 // Do an additional mProf_GC, because all 'free' events are now real as well.
2374 void runtime_debug_readGCStats(Slice
*)
2375 __asm__("runtime_debug.readGCStats");
2378 runtime_debug_readGCStats(Slice
*pauses
)
2384 // Calling code in runtime/debug should make the slice large enough.
2386 if((size_t)pauses
->cap
< nelem(pmstats
->pause_ns
)+3)
2387 runtime_throw("runtime: short slice passed to readGCStats");
2389 // Pass back: pauses, last gc (absolute time), number of gc, total pause ns.
2390 p
= (uint64
*)pauses
->array
;
2391 runtime_lock(&runtime_mheap
);
2393 if(n
> nelem(pmstats
->pause_ns
))
2394 n
= nelem(pmstats
->pause_ns
);
2396 // The pause buffer is circular. The most recent pause is at
2397 // pause_ns[(numgc-1)%nelem(pause_ns)], and then backward
2398 // from there to go back farther in time. We deliver the times
2399 // most recent first (in p[0]).
2400 for(i
=0; i
<n
; i
++) {
2401 p
[i
] = pmstats
->pause_ns
[(pmstats
->numgc
-1-i
)%nelem(pmstats
->pause_ns
)];
2402 p
[n
+i
] = pmstats
->pause_end
[(pmstats
->numgc
-1-i
)%nelem(pmstats
->pause_ns
)];
2405 p
[n
+n
] = pmstats
->last_gc
;
2406 p
[n
+n
+1] = pmstats
->numgc
;
2407 p
[n
+n
+2] = pmstats
->pause_total_ns
;
2408 runtime_unlock(&runtime_mheap
);
2409 pauses
->__count
= n
+n
+3;
2413 runtime_setgcpercent(int32 in
) {
2416 runtime_lock(&runtime_mheap
);
2417 if(gcpercent
== GcpercentUnknown
)
2418 gcpercent
= readgogc();
2423 runtime_unlock(&runtime_mheap
);
2433 if(m
->helpgc
< 0 || m
->helpgc
>= MaxGcproc
)
2434 runtime_throw("gchelperstart: bad m->helpgc");
2435 if(runtime_xchg(&bufferList
[m
->helpgc
].busy
, 1))
2436 runtime_throw("gchelperstart: already busy");
2437 if(runtime_g() != m
->g0
)
2438 runtime_throw("gchelper not running on g0 stack");
2442 runfinq(void* dummy
__attribute__ ((unused
)))
2445 FinBlock
*fb
, *next
;
2450 // This function blocks for long periods of time, and because it is written in C
2451 // we have no liveness information. Zero everything so that uninitialized pointers
2452 // do not cause memory leaks.
2460 // force flush to memory
2468 runtime_lock(&finlock
);
2472 runtime_fingwait
= true;
2473 runtime_g()->isbackground
= true;
2474 runtime_parkunlock(&finlock
, "finalizer wait");
2475 runtime_g()->isbackground
= false;
2478 runtime_unlock(&finlock
);
2479 for(; fb
; fb
=next
) {
2481 for(i
=0; i
<(uint32
)fb
->cnt
; i
++) {
2486 fint
= ((const Type
**)f
->ft
->__in
.array
)[0];
2487 if((fint
->__code
& kindMask
) == kindPtr
) {
2488 // direct use of pointer
2490 } else if(((const InterfaceType
*)fint
)->__methods
.__count
== 0) {
2491 // convert to empty interface
2492 // using memcpy as const_cast.
2493 memcpy(&ef
._type
, &f
->ot
,
2498 // convert to interface with methods
2499 iface
.tab
= getitab(fint
,
2502 iface
.data
= f
->arg
;
2503 if(iface
.data
== nil
)
2504 runtime_throw("invalid type conversion in runfinq");
2507 reflect_call(f
->ft
, f
->fn
, 0, 0, ¶m
, nil
);
2513 runtime_lock(&finlock
);
2516 runtime_unlock(&finlock
);
2519 // Zero everything that's dead, to avoid memory leaks.
2520 // See comment at top of function.
2527 runtime_gc(1); // trigger another gc to clean up the finalized objects, if possible
2532 runtime_createfing(void)
2536 // Here we use gclock instead of finlock,
2537 // because newproc1 can allocate, which can cause on-demand span sweep,
2538 // which can queue finalizers, which would deadlock.
2539 runtime_lock(&gclock
);
2541 fing
= __go_go(runfinq
, nil
);
2542 runtime_unlock(&gclock
);
2546 runtime_wakefing(void)
2551 runtime_lock(&finlock
);
2552 if(runtime_fingwait
&& runtime_fingwake
) {
2553 runtime_fingwait
= false;
2554 runtime_fingwake
= false;
2557 runtime_unlock(&finlock
);
2562 runtime_marknogc(void *v
)
2564 uintptr
*b
, off
, shift
;
2566 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2567 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2568 shift
= off
% wordsPerBitmapWord
;
2569 *b
= (*b
& ~(bitAllocated
<<shift
)) | bitBlockBoundary
<<shift
;
2573 runtime_markscan(void *v
)
2575 uintptr
*b
, off
, shift
;
2577 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2578 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2579 shift
= off
% wordsPerBitmapWord
;
2580 *b
|= bitScan
<<shift
;
2583 // mark the block at v as freed.
2585 runtime_markfreed(void *v
)
2587 uintptr
*b
, off
, shift
;
2590 runtime_printf("markfreed %p\n", v
);
2592 if((byte
*)v
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2593 runtime_throw("markfreed: bad pointer");
2595 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2596 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2597 shift
= off
% wordsPerBitmapWord
;
2598 *b
= (*b
& ~(bitMask
<<shift
)) | (bitAllocated
<<shift
);
2601 // check that the block at v of size n is marked freed.
2603 runtime_checkfreed(void *v
, uintptr n
)
2605 uintptr
*b
, bits
, off
, shift
;
2607 if(!runtime_checking
)
2610 if((byte
*)v
+n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2611 return; // not allocated, so okay
2613 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2614 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2615 shift
= off
% wordsPerBitmapWord
;
2618 if((bits
& bitAllocated
) != 0) {
2619 runtime_printf("checkfreed %p+%p: off=%p have=%p\n",
2620 v
, n
, off
, bits
& bitMask
);
2621 runtime_throw("checkfreed: not freed");
2625 // mark the span of memory at v as having n blocks of the given size.
2626 // if leftover is true, there is left over space at the end of the span.
2628 runtime_markspan(void *v
, uintptr size
, uintptr n
, bool leftover
)
2630 uintptr
*b
, *b0
, off
, shift
, i
, x
;
2633 if((byte
*)v
+size
*n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2634 runtime_throw("markspan: bad pointer");
2636 if(runtime_checking
) {
2637 // bits should be all zero at the start
2638 off
= (byte
*)v
+ size
- runtime_mheap
.arena_start
;
2639 b
= (uintptr
*)(runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
);
2640 for(i
= 0; i
< size
/PtrSize
/wordsPerBitmapWord
; i
++) {
2642 runtime_throw("markspan: span bits not zero");
2647 if(leftover
) // mark a boundary just past end of last block too
2652 for(; n
-- > 0; p
+= size
) {
2653 // Okay to use non-atomic ops here, because we control
2654 // the entire span, and each bitmap word has bits for only
2655 // one span, so no other goroutines are changing these
2657 off
= (uintptr
*)p
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2658 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2659 shift
= off
% wordsPerBitmapWord
;
2666 x
|= bitAllocated
<<shift
;
2671 // unmark the span of memory at v of length n bytes.
2673 runtime_unmarkspan(void *v
, uintptr n
)
2675 uintptr
*p
, *b
, off
;
2677 if((byte
*)v
+n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2678 runtime_throw("markspan: bad pointer");
2681 off
= p
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2682 if(off
% wordsPerBitmapWord
!= 0)
2683 runtime_throw("markspan: unaligned pointer");
2684 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2686 if(n
%wordsPerBitmapWord
!= 0)
2687 runtime_throw("unmarkspan: unaligned length");
2688 // Okay to use non-atomic ops here, because we control
2689 // the entire span, and each bitmap word has bits for only
2690 // one span, so no other goroutines are changing these
2692 n
/= wordsPerBitmapWord
;
2698 runtime_MHeap_MapBits(MHeap
*h
)
2702 // Caller has added extra mappings to the arena.
2703 // Add extra mappings of bitmap words as needed.
2704 // We allocate extra bitmap pieces in chunks of bitmapChunk.
2710 n
= (h
->arena_used
- h
->arena_start
) / wordsPerBitmapWord
;
2711 n
= ROUND(n
, bitmapChunk
);
2712 n
= ROUND(n
, PageSize
);
2713 page_size
= getpagesize();
2714 n
= ROUND(n
, page_size
);
2715 if(h
->bitmap_mapped
>= n
)
2718 runtime_SysMap(h
->arena_start
- n
, n
- h
->bitmap_mapped
, h
->arena_reserved
, &mstats()->gc_sys
);
2719 h
->bitmap_mapped
= n
;
2722 // typedmemmove copies a value of type t to dst from src.
2724 extern void typedmemmove(const Type
* td
, void *dst
, const void *src
)
2725 __asm__ (GOSYM_PREFIX
"reflect.typedmemmove");
2728 typedmemmove(const Type
* td
, void *dst
, const void *src
)
2730 runtime_memmove(dst
, src
, td
->__size
);
2733 // typedslicecopy copies a slice of elemType values from src to dst,
2734 // returning the number of elements copied.
2736 extern intgo
typedslicecopy(const Type
* elem
, Slice dst
, Slice src
)
2737 __asm__ (GOSYM_PREFIX
"reflect.typedslicecopy");
2740 typedslicecopy(const Type
* elem
, Slice dst
, Slice src
)
2747 if (n
> src
.__count
)
2751 dstp
= dst
.__values
;
2752 srcp
= src
.__values
;
2753 memmove(dstp
, srcp
, (uintptr_t)n
* elem
->__size
);