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
)
129 if(poolcleanup
!= nil
) {
130 __builtin_call_with_static_chain(poolcleanup
->fn(),
134 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
135 // clear tinyalloc pool
146 typedef struct Workbuf Workbuf
;
149 #define SIZE (WorkbufSize-sizeof(LFNode)-sizeof(uintptr))
150 LFNode node
; // must be first
152 Obj obj
[SIZE
/sizeof(Obj
) - 1];
153 uint8 _padding
[SIZE
%sizeof(Obj
) + sizeof(Obj
)];
157 typedef struct Finalizer Finalizer
;
162 const struct __go_func_type
*ft
;
166 typedef struct FinBlock FinBlock
;
176 static Lock finlock
; // protects the following variables
177 static FinBlock
*finq
; // list of finalizers that are to be executed
178 static FinBlock
*finc
; // cache of free blocks
179 static FinBlock
*allfin
; // list of all blocks
180 bool runtime_fingwait
;
181 bool runtime_fingwake
;
186 static void runfinq(void*);
187 static void bgsweep(void*);
188 static Workbuf
* getempty(Workbuf
*);
189 static Workbuf
* getfull(Workbuf
*);
190 static void putempty(Workbuf
*);
191 static Workbuf
* handoff(Workbuf
*);
192 static void gchelperstart(void);
193 static void flushallmcaches(void);
194 static void addstackroots(G
*gp
, Workbuf
**wbufp
);
197 uint64 full
; // lock-free list of full blocks
198 uint64 wempty
; // lock-free list of empty blocks
199 byte pad0
[CacheLineSize
]; // prevents false-sharing between full/empty and nproc/nwait
202 volatile uint32 nwait
;
203 volatile uint32 ndone
;
210 } work
__attribute__((aligned(8)));
213 GC_DEFAULT_PTR
= GC_NUM_INSTR
,
233 uint64 instr
[GC_NUM_INSTR2
];
250 // markonly marks an object. It returns true if the object
251 // has been marked by this function, false otherwise.
252 // This function doesn't append the object to any buffer.
254 markonly(const void *obj
)
257 uintptr
*bitp
, bits
, shift
, x
, xbits
, off
, j
;
261 // Words outside the arena cannot be pointers.
262 if((const byte
*)obj
< runtime_mheap
.arena_start
|| (const byte
*)obj
>= runtime_mheap
.arena_used
)
265 // obj may be a pointer to a live object.
266 // Try to find the beginning of the object.
268 // Round down to word boundary.
269 obj
= (const void*)((uintptr
)obj
& ~((uintptr
)PtrSize
-1));
271 // Find bits for this word.
272 off
= (const uintptr
*)obj
- (uintptr
*)runtime_mheap
.arena_start
;
273 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
274 shift
= off
% wordsPerBitmapWord
;
276 bits
= xbits
>> shift
;
278 // Pointing at the beginning of a block?
279 if((bits
& (bitAllocated
|bitBlockBoundary
)) != 0) {
281 runtime_xadd64(&gcstats
.markonly
.foundbit
, 1);
285 // Pointing just past the beginning?
286 // Scan backward a little to find a block boundary.
287 for(j
=shift
; j
-->0; ) {
288 if(((xbits
>>j
) & (bitAllocated
|bitBlockBoundary
)) != 0) {
292 runtime_xadd64(&gcstats
.markonly
.foundword
, 1);
297 // Otherwise consult span table to find beginning.
298 // (Manually inlined copy of MHeap_LookupMaybe.)
299 k
= (uintptr
)obj
>>PageShift
;
301 x
-= (uintptr
)runtime_mheap
.arena_start
>>PageShift
;
302 s
= runtime_mheap
.spans
[x
];
303 if(s
== nil
|| k
< s
->start
|| (uintptr
)obj
>= s
->limit
|| s
->state
!= MSpanInUse
)
305 p
= (byte
*)((uintptr
)s
->start
<<PageShift
);
306 if(s
->sizeclass
== 0) {
309 uintptr size
= s
->elemsize
;
310 int32 i
= ((const byte
*)obj
- p
)/size
;
314 // Now that we know the object header, reload bits.
315 off
= (const uintptr
*)obj
- (uintptr
*)runtime_mheap
.arena_start
;
316 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
317 shift
= off
% wordsPerBitmapWord
;
319 bits
= xbits
>> shift
;
321 runtime_xadd64(&gcstats
.markonly
.foundspan
, 1);
324 // Now we have bits, bitp, and shift correct for
325 // obj pointing at the base of the object.
326 // Only care about allocated and not marked.
327 if((bits
& (bitAllocated
|bitMarked
)) != bitAllocated
)
330 *bitp
|= bitMarked
<<shift
;
334 if(x
& (bitMarked
<<shift
))
336 if(runtime_casp((void**)bitp
, (void*)x
, (void*)(x
|(bitMarked
<<shift
))))
341 // The object is now marked
345 // PtrTarget is a structure used by intermediate buffers.
346 // The intermediate buffers hold GC data before it
347 // is moved/flushed to the work buffer (Workbuf).
348 // The size of an intermediate buffer is very small,
349 // such as 32 or 64 elements.
350 typedef struct PtrTarget PtrTarget
;
357 typedef struct Scanbuf Scanbuf
;
375 typedef struct BufferList BufferList
;
378 PtrTarget ptrtarget
[IntermediateBufferCapacity
];
379 Obj obj
[IntermediateBufferCapacity
];
381 byte pad
[CacheLineSize
];
383 static BufferList bufferList
[MaxGcproc
];
385 static void enqueue(Obj obj
, Workbuf
**_wbuf
, Obj
**_wp
, uintptr
*_nobj
);
387 // flushptrbuf moves data from the PtrTarget buffer to the work buffer.
388 // The PtrTarget buffer contains blocks irrespective of whether the blocks have been marked or scanned,
389 // while the work buffer contains blocks which have been marked
390 // and are prepared to be scanned by the garbage collector.
392 // _wp, _wbuf, _nobj are input/output parameters and are specifying the work buffer.
394 // A simplified drawing explaining how the todo-list moves from a structure to another:
398 // Obj ------> PtrTarget (pointer targets)
403 // (find block start, mark and enqueue)
405 flushptrbuf(Scanbuf
*sbuf
)
407 byte
*p
, *arena_start
, *obj
;
408 uintptr size
, *bitp
, bits
, shift
, j
, x
, xbits
, off
, nobj
, ti
, n
;
414 PtrTarget
*ptrbuf_end
;
416 arena_start
= runtime_mheap
.arena_start
;
422 ptrbuf
= sbuf
->ptr
.begin
;
423 ptrbuf_end
= sbuf
->ptr
.pos
;
424 n
= ptrbuf_end
- sbuf
->ptr
.begin
;
425 sbuf
->ptr
.pos
= sbuf
->ptr
.begin
;
428 runtime_xadd64(&gcstats
.ptr
.sum
, n
);
429 runtime_xadd64(&gcstats
.ptr
.cnt
, 1);
432 // If buffer is nearly full, get a new one.
433 if(wbuf
== nil
|| nobj
+n
>= nelem(wbuf
->obj
)) {
436 wbuf
= getempty(wbuf
);
440 if(n
>= nelem(wbuf
->obj
))
441 runtime_throw("ptrbuf has to be smaller than WorkBuf");
444 while(ptrbuf
< ptrbuf_end
) {
449 // obj belongs to interval [mheap.arena_start, mheap.arena_used).
451 if(obj
< runtime_mheap
.arena_start
|| obj
>= runtime_mheap
.arena_used
)
452 runtime_throw("object is outside of mheap");
455 // obj may be a pointer to a live object.
456 // Try to find the beginning of the object.
458 // Round down to word boundary.
459 if(((uintptr
)obj
& ((uintptr
)PtrSize
-1)) != 0) {
460 obj
= (void*)((uintptr
)obj
& ~((uintptr
)PtrSize
-1));
464 // Find bits for this word.
465 off
= (uintptr
*)obj
- (uintptr
*)arena_start
;
466 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
467 shift
= off
% wordsPerBitmapWord
;
469 bits
= xbits
>> shift
;
471 // Pointing at the beginning of a block?
472 if((bits
& (bitAllocated
|bitBlockBoundary
)) != 0) {
474 runtime_xadd64(&gcstats
.flushptrbuf
.foundbit
, 1);
480 // Pointing just past the beginning?
481 // Scan backward a little to find a block boundary.
482 for(j
=shift
; j
-->0; ) {
483 if(((xbits
>>j
) & (bitAllocated
|bitBlockBoundary
)) != 0) {
484 obj
= (byte
*)obj
- (shift
-j
)*PtrSize
;
488 runtime_xadd64(&gcstats
.flushptrbuf
.foundword
, 1);
493 // Otherwise consult span table to find beginning.
494 // (Manually inlined copy of MHeap_LookupMaybe.)
495 k
= (uintptr
)obj
>>PageShift
;
497 x
-= (uintptr
)arena_start
>>PageShift
;
498 s
= runtime_mheap
.spans
[x
];
499 if(s
== nil
|| k
< s
->start
|| (uintptr
)obj
>= s
->limit
|| s
->state
!= MSpanInUse
)
501 p
= (byte
*)((uintptr
)s
->start
<<PageShift
);
502 if(s
->sizeclass
== 0) {
506 int32 i
= ((byte
*)obj
- p
)/size
;
510 // Now that we know the object header, reload bits.
511 off
= (uintptr
*)obj
- (uintptr
*)arena_start
;
512 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
513 shift
= off
% wordsPerBitmapWord
;
515 bits
= xbits
>> shift
;
517 runtime_xadd64(&gcstats
.flushptrbuf
.foundspan
, 1);
520 // Now we have bits, bitp, and shift correct for
521 // obj pointing at the base of the object.
522 // Only care about allocated and not marked.
523 if((bits
& (bitAllocated
|bitMarked
)) != bitAllocated
)
526 *bitp
|= bitMarked
<<shift
;
530 if(x
& (bitMarked
<<shift
))
532 if(runtime_casp((void**)bitp
, (void*)x
, (void*)(x
|(bitMarked
<<shift
))))
537 // If object has no pointers, don't need to scan further.
538 if((bits
& bitScan
) == 0)
541 // Ask span about size class.
542 // (Manually inlined copy of MHeap_Lookup.)
543 x
= (uintptr
)obj
>> PageShift
;
544 x
-= (uintptr
)arena_start
>>PageShift
;
545 s
= runtime_mheap
.spans
[x
];
549 *wp
= (Obj
){obj
, s
->elemsize
, ti
};
555 // If another proc wants a pointer, give it some.
556 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
558 wbuf
= handoff(wbuf
);
560 wp
= wbuf
->obj
+ nobj
;
569 flushobjbuf(Scanbuf
*sbuf
)
581 objbuf
= sbuf
->obj
.begin
;
582 objbuf_end
= sbuf
->obj
.pos
;
583 sbuf
->obj
.pos
= sbuf
->obj
.begin
;
585 while(objbuf
< objbuf_end
) {
588 // Align obj.b to a word boundary.
589 off
= (uintptr
)obj
.p
& (PtrSize
-1);
591 obj
.p
+= PtrSize
- off
;
592 obj
.n
-= PtrSize
- off
;
596 if(obj
.p
== nil
|| obj
.n
== 0)
599 // If buffer is full, get a new one.
600 if(wbuf
== nil
|| nobj
>= nelem(wbuf
->obj
)) {
603 wbuf
= getempty(wbuf
);
613 // If another proc wants a pointer, give it some.
614 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
616 wbuf
= handoff(wbuf
);
618 wp
= wbuf
->obj
+ nobj
;
626 // Program that scans the whole block and treats every block element as a potential pointer
627 static uintptr defaultProg
[2] = {PtrSize
, GC_DEFAULT_PTR
};
630 static uintptr chanProg
[2] = {0, GC_CHAN
};
632 // Local variables of a program fragment or loop
633 typedef struct GCFrame GCFrame
;
635 uintptr count
, elemsize
, b
;
636 const uintptr
*loop_or_ret
;
639 // Sanity check for the derived type info objti.
641 checkptr(void *obj
, uintptr objti
)
643 uintptr
*pc1
, type
, tisize
, i
, j
, x
;
650 runtime_throw("checkptr is debug only");
652 if((byte
*)obj
< runtime_mheap
.arena_start
|| (byte
*)obj
>= runtime_mheap
.arena_used
)
654 type
= runtime_gettype(obj
);
655 t
= (Type
*)(type
& ~(uintptr
)(PtrSize
-1));
658 x
= (uintptr
)obj
>> PageShift
;
659 x
-= (uintptr
)(runtime_mheap
.arena_start
)>>PageShift
;
660 s
= runtime_mheap
.spans
[x
];
661 objstart
= (byte
*)((uintptr
)s
->start
<<PageShift
);
662 if(s
->sizeclass
!= 0) {
663 i
= ((byte
*)obj
- objstart
)/s
->elemsize
;
664 objstart
+= i
*s
->elemsize
;
666 tisize
= *(uintptr
*)objti
;
667 // Sanity check for object size: it should fit into the memory block.
668 if((byte
*)obj
+ tisize
> objstart
+ s
->elemsize
) {
669 runtime_printf("object of type '%S' at %p/%p does not fit in block %p/%p\n",
670 *t
->string
, obj
, tisize
, objstart
, s
->elemsize
);
671 runtime_throw("invalid gc type info");
675 // If obj points to the beginning of the memory block,
676 // check type info as well.
677 if(t
->string
== nil
||
678 // Gob allocates unsafe pointers for indirection.
679 (runtime_strcmp((const char *)t
->string
->str
, (const char*)"unsafe.Pointer") &&
680 // Runtime and gc think differently about closures.
681 runtime_strstr((const char *)t
->string
->str
, (const char*)"struct { F uintptr") != (const char *)t
->string
->str
)) {
682 pc1
= (uintptr
*)objti
;
683 pc2
= (const uintptr
*)t
->__gc
;
684 // A simple best-effort check until first GC_END.
685 for(j
= 1; pc1
[j
] != GC_END
&& pc2
[j
] != GC_END
; j
++) {
686 if(pc1
[j
] != pc2
[j
]) {
687 runtime_printf("invalid gc type info for '%s', type info %p [%d]=%p, block info %p [%d]=%p\n",
688 t
->string
? (const int8
*)t
->string
->str
: (const int8
*)"?", pc1
, (int32
)j
, pc1
[j
], pc2
, (int32
)j
, pc2
[j
]);
689 runtime_throw("invalid gc type info");
695 // scanblock scans a block of n bytes starting at pointer b for references
696 // to other objects, scanning any it finds recursively until there are no
697 // unscanned objects left. Instead of using an explicit recursion, it keeps
698 // a work list in the Workbuf* structures and loops in the main function
699 // body. Keeping an explicit work list is easier on the stack allocator and
702 scanblock(Workbuf
*wbuf
, bool keepworking
)
704 byte
*b
, *arena_start
, *arena_used
;
705 uintptr n
, i
, end_b
, elemsize
, size
, ti
, objti
, count
, type
, nobj
;
706 uintptr precise_type
, nominal_size
;
707 const uintptr
*pc
, *chan_ret
;
713 GCFrame
*stack_ptr
, stack_top
, stack
[GC_STACK_CAPACITY
+4];
714 BufferList
*scanbuffers
;
719 const ChanType
*chantype
;
722 if(sizeof(Workbuf
) % WorkbufSize
!= 0)
723 runtime_throw("scanblock: size of Workbuf is suboptimal");
725 // Memory arena parameters.
726 arena_start
= runtime_mheap
.arena_start
;
727 arena_used
= runtime_mheap
.arena_used
;
729 stack_ptr
= stack
+nelem(stack
)-1;
731 precise_type
= false;
736 wp
= &wbuf
->obj
[nobj
];
743 scanbuffers
= &bufferList
[runtime_m()->helpgc
];
745 sbuf
.ptr
.begin
= sbuf
.ptr
.pos
= &scanbuffers
->ptrtarget
[0];
746 sbuf
.ptr
.end
= sbuf
.ptr
.begin
+ nelem(scanbuffers
->ptrtarget
);
748 sbuf
.obj
.begin
= sbuf
.obj
.pos
= &scanbuffers
->obj
[0];
749 sbuf
.obj
.end
= sbuf
.obj
.begin
+ nelem(scanbuffers
->obj
);
755 // (Silence the compiler)
763 // Each iteration scans the block b of length n, queueing pointers in
767 runtime_xadd64(&gcstats
.nbytes
, n
);
768 runtime_xadd64(&gcstats
.obj
.sum
, sbuf
.nobj
);
769 runtime_xadd64(&gcstats
.obj
.cnt
, 1);
774 runtime_printf("scanblock %p %D ti %p\n", b
, (int64
)n
, ti
);
776 pc
= (uintptr
*)(ti
& ~(uintptr
)PC_BITS
);
777 precise_type
= (ti
& PRECISE
);
778 stack_top
.elemsize
= pc
[0];
780 nominal_size
= pc
[0];
782 stack_top
.count
= 0; // 0 means an infinite number of iterations
783 stack_top
.loop_or_ret
= pc
+1;
788 // Simple sanity check for provided type info ti:
789 // The declared size of the object must be not larger than the actual size
790 // (it can be smaller due to inferior pointers).
791 // It's difficult to make a comprehensive check due to inferior pointers,
792 // reflection, gob, etc.
794 runtime_printf("invalid gc type info: type info size %p, block size %p\n", pc
[0], n
);
795 runtime_throw("invalid gc type info");
798 } else if(UseSpanType
) {
800 runtime_xadd64(&gcstats
.obj
.notype
, 1);
802 type
= runtime_gettype(b
);
805 runtime_xadd64(&gcstats
.obj
.typelookup
, 1);
807 t
= (Type
*)(type
& ~(uintptr
)(PtrSize
-1));
808 switch(type
& (PtrSize
-1)) {
809 case TypeInfo_SingleObject
:
810 pc
= (const uintptr
*)t
->__gc
;
811 precise_type
= true; // type information about 'b' is precise
813 stack_top
.elemsize
= pc
[0];
816 pc
= (const uintptr
*)t
->__gc
;
819 precise_type
= true; // type information about 'b' is precise
820 stack_top
.count
= 0; // 0 means an infinite number of iterations
821 stack_top
.elemsize
= pc
[0];
822 stack_top
.loop_or_ret
= pc
+1;
826 chantype
= (const ChanType
*)t
;
832 runtime_printf("scanblock %p %D type %p %S\n", b
, (int64
)n
, type
, *t
->string
);
833 runtime_throw("scanblock: invalid type");
837 runtime_printf("scanblock %p %D type %p %S pc=%p\n", b
, (int64
)n
, type
, *t
->string
, pc
);
841 runtime_printf("scanblock %p %D unknown type\n", b
, (int64
)n
);
846 runtime_printf("scanblock %p %D no span types\n", b
, (int64
)n
);
853 stack_top
.b
= (uintptr
)b
;
854 end_b
= (uintptr
)b
+ n
- PtrSize
;
858 runtime_xadd64(&gcstats
.instr
[pc
[0]], 1);
864 obj
= *(void**)(stack_top
.b
+ pc
[1]);
867 runtime_printf("gc_ptr @%p: %p ti=%p\n", stack_top
.b
+pc
[1], obj
, objti
);
870 checkptr(obj
, objti
);
874 sliceptr
= (Slice
*)(stack_top
.b
+ pc
[1]);
876 runtime_printf("gc_slice @%p: %p/%D/%D\n", sliceptr
, sliceptr
->array
, (int64
)sliceptr
->__count
, (int64
)sliceptr
->cap
);
877 if(sliceptr
->cap
!= 0) {
878 obj
= sliceptr
->array
;
879 // Can't use slice element type for scanning,
880 // because if it points to an array embedded
881 // in the beginning of a struct,
882 // we will scan the whole struct as the slice.
883 // So just obtain type info from heap.
889 obj
= *(void**)(stack_top
.b
+ pc
[1]);
891 runtime_printf("gc_aptr @%p: %p\n", stack_top
.b
+pc
[1], obj
);
896 stringptr
= (String
*)(stack_top
.b
+ pc
[1]);
898 runtime_printf("gc_string @%p: %p/%D\n", stack_top
.b
+pc
[1], stringptr
->str
, (int64
)stringptr
->len
);
899 if(stringptr
->len
!= 0)
900 markonly(stringptr
->str
);
905 eface
= (Eface
*)(stack_top
.b
+ pc
[1]);
908 runtime_printf("gc_eface @%p: %p %p\n", stack_top
.b
+pc
[1], eface
->_type
, eface
->data
);
909 if(eface
->_type
== nil
)
914 if((const byte
*)t
>= arena_start
&& (const byte
*)t
< arena_used
) {
915 union { const Type
*tc
; Type
*tr
; } u
;
917 *sbuf
.ptr
.pos
++ = (PtrTarget
){u
.tr
, 0};
918 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
923 if((byte
*)eface
->data
>= arena_start
&& (byte
*)eface
->data
< arena_used
) {
924 if(__go_is_pointer_type(t
)) {
925 if((t
->__code
& kindNoPointers
))
929 if((t
->__code
& kindMask
) == kindPtr
) {
930 // Only use type information if it is a pointer-containing type.
931 // This matches the GC programs written by cmd/gc/reflect.c's
932 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
933 et
= ((const PtrType
*)t
)->elem
;
934 if(!(et
->__code
& kindNoPointers
))
935 objti
= (uintptr
)((const PtrType
*)t
)->elem
->__gc
;
939 objti
= (uintptr
)t
->__gc
;
945 iface
= (Iface
*)(stack_top
.b
+ pc
[1]);
948 runtime_printf("gc_iface @%p: %p/%p %p\n", stack_top
.b
+pc
[1], *(Type
**)iface
->tab
, nil
, iface
->data
);
949 if(iface
->tab
== nil
)
953 if((byte
*)iface
->tab
>= arena_start
&& (byte
*)iface
->tab
< arena_used
) {
954 *sbuf
.ptr
.pos
++ = (PtrTarget
){iface
->tab
, 0};
955 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
960 if((byte
*)iface
->data
>= arena_start
&& (byte
*)iface
->data
< arena_used
) {
961 t
= *(Type
**)iface
->tab
;
962 if(__go_is_pointer_type(t
)) {
963 if((t
->__code
& kindNoPointers
))
967 if((t
->__code
& kindMask
) == kindPtr
) {
968 // Only use type information if it is a pointer-containing type.
969 // This matches the GC programs written by cmd/gc/reflect.c's
970 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
971 et
= ((const PtrType
*)t
)->elem
;
972 if(!(et
->__code
& kindNoPointers
))
973 objti
= (uintptr
)((const PtrType
*)t
)->elem
->__gc
;
977 objti
= (uintptr
)t
->__gc
;
983 while(stack_top
.b
<= end_b
) {
984 obj
= *(byte
**)stack_top
.b
;
986 runtime_printf("gc_default_ptr @%p: %p\n", stack_top
.b
, obj
);
987 stack_top
.b
+= PtrSize
;
988 if((byte
*)obj
>= arena_start
&& (byte
*)obj
< arena_used
) {
989 *sbuf
.ptr
.pos
++ = (PtrTarget
){obj
, 0};
990 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
997 if(--stack_top
.count
!= 0) {
998 // Next iteration of a loop if possible.
999 stack_top
.b
+= stack_top
.elemsize
;
1000 if(stack_top
.b
+ stack_top
.elemsize
<= end_b
+PtrSize
) {
1001 pc
= stack_top
.loop_or_ret
;
1006 // Stack pop if possible.
1007 if(stack_ptr
+1 < stack
+nelem(stack
)) {
1008 pc
= stack_top
.loop_or_ret
;
1009 stack_top
= *(++stack_ptr
);
1012 i
= (uintptr
)b
+ nominal_size
;
1015 // Quickly scan [b+i,b+n) for possible pointers.
1016 for(; i
<=end_b
; i
+=PtrSize
) {
1017 if(*(byte
**)i
!= nil
) {
1018 // Found a value that may be a pointer.
1019 // Do a rescan of the entire block.
1020 enqueue((Obj
){b
, n
, 0}, &sbuf
.wbuf
, &sbuf
.wp
, &sbuf
.nobj
);
1022 runtime_xadd64(&gcstats
.rescan
, 1);
1023 runtime_xadd64(&gcstats
.rescanbytes
, n
);
1031 case GC_ARRAY_START
:
1032 i
= stack_top
.b
+ pc
[1];
1038 *stack_ptr
-- = stack_top
;
1039 stack_top
= (GCFrame
){count
, elemsize
, i
, pc
};
1043 if(--stack_top
.count
!= 0) {
1044 stack_top
.b
+= stack_top
.elemsize
;
1045 pc
= stack_top
.loop_or_ret
;
1048 stack_top
= *(++stack_ptr
);
1055 *stack_ptr
-- = stack_top
;
1056 stack_top
= (GCFrame
){1, 0, stack_top
.b
+ pc
[1], pc
+3 /*return address*/};
1057 pc
= (const uintptr
*)((const byte
*)pc
+ *(const int32
*)(pc
+2)); // target of the CALL instruction
1061 obj
= (void*)(stack_top
.b
+ pc
[1]);
1067 runtime_printf("gc_region @%p: %D %p\n", stack_top
.b
+pc
[1], (int64
)size
, objti
);
1068 *sbuf
.obj
.pos
++ = (Obj
){obj
, size
, objti
};
1069 if(sbuf
.obj
.pos
== sbuf
.obj
.end
)
1074 chan
= *(Hchan
**)(stack_top
.b
+ pc
[1]);
1075 if(Debug
> 2 && chan
!= nil
)
1076 runtime_printf("gc_chan_ptr @%p: %p/%D/%D %p\n", stack_top
.b
+pc
[1], chan
, (int64
)chan
->qcount
, (int64
)chan
->dataqsiz
, pc
[2]);
1081 if(markonly(chan
)) {
1082 chantype
= (ChanType
*)pc
[2];
1083 if(!(chantype
->elem
->__code
& kindNoPointers
)) {
1094 // There are no heap pointers in struct Hchan,
1095 // so we can ignore the leading sizeof(Hchan) bytes.
1096 if(!(chantype
->elem
->__code
& kindNoPointers
)) {
1097 chancap
= chan
->dataqsiz
;
1098 if(chancap
> 0 && markonly(chan
->buf
)) {
1099 // TODO(atom): split into two chunks so that only the
1100 // in-use part of the circular buffer is scanned.
1101 // (Channel routines zero the unused part, so the current
1102 // code does not lead to leaks, it's just a little inefficient.)
1103 *sbuf
.obj
.pos
++ = (Obj
){chan
->buf
, chancap
*chantype
->elem
->__size
,
1104 (uintptr
)chantype
->elem
->__gc
| PRECISE
| LOOP
};
1105 if(sbuf
.obj
.pos
== sbuf
.obj
.end
)
1115 runtime_printf("runtime: invalid GC instruction %p at %p\n", pc
[0], pc
);
1116 runtime_throw("scanblock: invalid GC instruction");
1120 if((byte
*)obj
>= arena_start
&& (byte
*)obj
< arena_used
) {
1121 *sbuf
.ptr
.pos
++ = (PtrTarget
){obj
, objti
};
1122 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
1128 // Done scanning [b, b+n). Prepare for the next iteration of
1129 // the loop by setting b, n, ti to the parameters for the next block.
1131 if(sbuf
.nobj
== 0) {
1135 if(sbuf
.nobj
== 0) {
1138 putempty(sbuf
.wbuf
);
1141 // Emptied our buffer: refill.
1142 sbuf
.wbuf
= getfull(sbuf
.wbuf
);
1143 if(sbuf
.wbuf
== nil
)
1145 sbuf
.nobj
= sbuf
.wbuf
->nobj
;
1146 sbuf
.wp
= sbuf
.wbuf
->obj
+ sbuf
.wbuf
->nobj
;
1150 // Fetch b from the work buffer.
1159 static struct root_list
* roots
;
1162 __go_register_gc_roots (struct root_list
* r
)
1164 // FIXME: This needs locking if multiple goroutines can call
1165 // dlopen simultaneously.
1170 // Append obj to the work buffer.
1171 // _wbuf, _wp, _nobj are input/output parameters and are specifying the work buffer.
1173 enqueue(Obj obj
, Workbuf
**_wbuf
, Obj
**_wp
, uintptr
*_nobj
)
1180 runtime_printf("append obj(%p %D %p)\n", obj
.p
, (int64
)obj
.n
, obj
.ti
);
1182 // Align obj.b to a word boundary.
1183 off
= (uintptr
)obj
.p
& (PtrSize
-1);
1185 obj
.p
+= PtrSize
- off
;
1186 obj
.n
-= PtrSize
- off
;
1190 if(obj
.p
== nil
|| obj
.n
== 0)
1193 // Load work buffer state
1198 // If another proc wants a pointer, give it some.
1199 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
1201 wbuf
= handoff(wbuf
);
1203 wp
= wbuf
->obj
+ nobj
;
1206 // If buffer is full, get a new one.
1207 if(wbuf
== nil
|| nobj
>= nelem(wbuf
->obj
)) {
1210 wbuf
= getempty(wbuf
);
1219 // Save work buffer state
1226 enqueue1(Workbuf
**wbufp
, Obj obj
)
1231 if(wbuf
->nobj
>= nelem(wbuf
->obj
))
1232 *wbufp
= wbuf
= getempty(wbuf
);
1233 wbuf
->obj
[wbuf
->nobj
++] = obj
;
1237 markroot(ParFor
*desc
, uint32 i
)
1242 MSpan
**allspans
, *s
;
1248 wbuf
= getempty(nil
);
1249 // Note: if you add a case here, please also update heapdump.c:dumproots.
1252 // For gccgo this is both data and bss.
1254 struct root_list
*pl
;
1256 for(pl
= roots
; pl
!= nil
; pl
= pl
->next
) {
1257 struct root
*pr
= &pl
->roots
[0];
1259 void *decl
= pr
->decl
;
1262 enqueue1(&wbuf
, (Obj
){decl
, pr
->size
, 0});
1270 // For gccgo we use this for all the other global roots.
1271 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_m0
, sizeof runtime_m0
, 0});
1272 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_g0
, sizeof runtime_g0
, 0});
1273 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allg
, sizeof runtime_allg
, 0});
1274 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allm
, sizeof runtime_allm
, 0});
1275 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allp
, sizeof runtime_allp
, 0});
1276 enqueue1(&wbuf
, (Obj
){(byte
*)&work
, sizeof work
, 0});
1277 runtime_proc_scan(&wbuf
, enqueue1
);
1280 case RootFinalizers
:
1281 for(fb
=allfin
; fb
; fb
=fb
->alllink
)
1282 enqueue1(&wbuf
, (Obj
){(byte
*)fb
->fin
, fb
->cnt
*sizeof(fb
->fin
[0]), 0});
1286 // mark span types and MSpan.specials (to walk spans only once)
1289 allspans
= h
->allspans
;
1290 for(spanidx
=0; spanidx
<runtime_mheap
.nspan
; spanidx
++) {
1292 SpecialFinalizer
*spf
;
1294 s
= allspans
[spanidx
];
1295 if(s
->sweepgen
!= sg
) {
1296 runtime_printf("sweep %d %d\n", s
->sweepgen
, sg
);
1297 runtime_throw("gc: unswept span");
1299 if(s
->state
!= MSpanInUse
)
1301 // The garbage collector ignores type pointers stored in MSpan.types:
1302 // - Compiler-generated types are stored outside of heap.
1303 // - The reflect package has runtime-generated types cached in its data structures.
1304 // The garbage collector relies on finding the references via that cache.
1305 if(s
->types
.compression
== MTypes_Words
|| s
->types
.compression
== MTypes_Bytes
)
1306 markonly((byte
*)s
->types
.data
);
1307 for(sp
= s
->specials
; sp
!= nil
; sp
= sp
->next
) {
1308 if(sp
->kind
!= KindSpecialFinalizer
)
1310 // don't mark finalized object, but scan it so we
1311 // retain everything it points to.
1312 spf
= (SpecialFinalizer
*)sp
;
1313 // A finalizer can be set for an inner byte of an object, find object beginning.
1314 p
= (void*)((s
->start
<< PageShift
) + spf
->offset
/s
->elemsize
*s
->elemsize
);
1315 enqueue1(&wbuf
, (Obj
){p
, s
->elemsize
, 0});
1316 enqueue1(&wbuf
, (Obj
){(void*)&spf
->fn
, PtrSize
, 0});
1317 enqueue1(&wbuf
, (Obj
){(void*)&spf
->ft
, PtrSize
, 0});
1318 enqueue1(&wbuf
, (Obj
){(void*)&spf
->ot
, PtrSize
, 0});
1323 case RootFlushCaches
:
1328 // the rest is scanning goroutine stacks
1329 if(i
- RootCount
>= runtime_allglen
)
1330 runtime_throw("markroot: bad index");
1331 gp
= runtime_allg
[i
- RootCount
];
1332 // remember when we've first observed the G blocked
1333 // needed only to output in traceback
1334 if((gp
->atomicstatus
== _Gwaiting
|| gp
->atomicstatus
== _Gsyscall
) && gp
->waitsince
== 0)
1335 gp
->waitsince
= work
.tstart
;
1336 addstackroots(gp
, &wbuf
);
1342 scanblock(wbuf
, false);
1345 static const FuncVal markroot_funcval
= { (void *) markroot
};
1347 // Get an empty work buffer off the work.empty list,
1348 // allocating new buffers as needed.
1350 getempty(Workbuf
*b
)
1353 runtime_lfstackpush(&work
.full
, &b
->node
);
1354 b
= (Workbuf
*)runtime_lfstackpop(&work
.wempty
);
1356 // Need to allocate.
1357 runtime_lock(&work
);
1358 if(work
.nchunk
< sizeof *b
) {
1359 work
.nchunk
= 1<<20;
1360 work
.chunk
= runtime_SysAlloc(work
.nchunk
, &mstats()->gc_sys
);
1361 if(work
.chunk
== nil
)
1362 runtime_throw("runtime: cannot allocate memory");
1364 b
= (Workbuf
*)work
.chunk
;
1365 work
.chunk
+= sizeof *b
;
1366 work
.nchunk
-= sizeof *b
;
1367 runtime_unlock(&work
);
1374 putempty(Workbuf
*b
)
1377 runtime_xadd64(&gcstats
.putempty
, 1);
1379 runtime_lfstackpush(&work
.wempty
, &b
->node
);
1382 // Get a full work buffer off the work.full list, or return nil.
1390 runtime_xadd64(&gcstats
.getfull
, 1);
1393 runtime_lfstackpush(&work
.wempty
, &b
->node
);
1394 b
= (Workbuf
*)runtime_lfstackpop(&work
.full
);
1395 if(b
!= nil
|| work
.nproc
== 1)
1399 runtime_xadd(&work
.nwait
, +1);
1401 if(work
.full
!= 0) {
1402 runtime_xadd(&work
.nwait
, -1);
1403 b
= (Workbuf
*)runtime_lfstackpop(&work
.full
);
1406 runtime_xadd(&work
.nwait
, +1);
1408 if(work
.nwait
== work
.nproc
)
1411 m
->gcstats
.nprocyield
++;
1412 runtime_procyield(20);
1414 m
->gcstats
.nosyield
++;
1417 m
->gcstats
.nsleep
++;
1418 runtime_usleep(100);
1432 // Make new buffer with half of b's pointers.
1437 runtime_memmove(b1
->obj
, b
->obj
+b
->nobj
, n
*sizeof b1
->obj
[0]);
1438 m
->gcstats
.nhandoff
++;
1439 m
->gcstats
.nhandoffcnt
+= n
;
1441 // Put b on full list - let first half of b get stolen.
1442 runtime_lfstackpush(&work
.full
, &b
->node
);
1447 addstackroots(G
*gp
, Workbuf
**wbufp
)
1449 switch(gp
->atomicstatus
){
1451 runtime_printf("unexpected G.status %d (goroutine %p %D)\n", gp
->atomicstatus
, gp
, gp
->goid
);
1452 runtime_throw("mark - bad status");
1456 runtime_throw("mark - world not stopped");
1463 #ifdef USING_SPLIT_STACK
1471 if(gp
== runtime_g()) {
1472 // Scanning our own stack.
1473 sp
= __splitstack_find(nil
, nil
, &spsize
, &next_segment
,
1474 &next_sp
, &initial_sp
);
1475 } else if((mp
= gp
->m
) != nil
&& mp
->helpgc
) {
1476 // gchelper's stack is in active use and has no interesting pointers.
1479 // Scanning another goroutine's stack.
1480 // The goroutine is usually asleep (the world is stopped).
1482 // The exception is that if the goroutine is about to enter or might
1483 // have just exited a system call, it may be executing code such
1484 // as schedlock and may have needed to start a new stack segment.
1485 // Use the stack segment and stack pointer at the time of
1486 // the system call instead, since that won't change underfoot.
1487 if(gp
->gcstack
!= nil
) {
1489 spsize
= gp
->gcstacksize
;
1490 next_segment
= gp
->gcnextsegment
;
1491 next_sp
= gp
->gcnextsp
;
1492 initial_sp
= gp
->gcinitialsp
;
1494 sp
= __splitstack_find_context(&gp
->stackcontext
[0],
1495 &spsize
, &next_segment
,
1496 &next_sp
, &initial_sp
);
1500 enqueue1(wbufp
, (Obj
){sp
, spsize
, 0});
1501 while((sp
= __splitstack_find(next_segment
, next_sp
,
1502 &spsize
, &next_segment
,
1503 &next_sp
, &initial_sp
)) != nil
)
1504 enqueue1(wbufp
, (Obj
){sp
, spsize
, 0});
1511 if(gp
== runtime_g()) {
1512 // Scanning our own stack.
1513 bottom
= (byte
*)&gp
;
1514 } else if((mp
= gp
->m
) != nil
&& mp
->helpgc
) {
1515 // gchelper's stack is in active use and has no interesting pointers.
1518 // Scanning another goroutine's stack.
1519 // The goroutine is usually asleep (the world is stopped).
1520 bottom
= (byte
*)gp
->gcnextsp
;
1524 top
= (byte
*)gp
->gcinitialsp
+ gp
->gcstacksize
;
1526 enqueue1(wbufp
, (Obj
){bottom
, top
- bottom
, 0});
1528 enqueue1(wbufp
, (Obj
){top
, bottom
- top
, 0});
1533 runtime_queuefinalizer(void *p
, FuncVal
*fn
, const FuncType
*ft
, const PtrType
*ot
)
1538 runtime_lock(&finlock
);
1539 if(finq
== nil
|| finq
->cnt
== finq
->cap
) {
1541 finc
= runtime_persistentalloc(FinBlockSize
, 0, &mstats()->gc_sys
);
1542 finc
->cap
= (FinBlockSize
- sizeof(FinBlock
)) / sizeof(Finalizer
) + 1;
1543 finc
->alllink
= allfin
;
1551 f
= &finq
->fin
[finq
->cnt
];
1557 runtime_fingwake
= true;
1558 runtime_unlock(&finlock
);
1562 runtime_iterate_finq(void (*callback
)(FuncVal
*, void*, const FuncType
*, const PtrType
*))
1568 for(fb
= allfin
; fb
; fb
= fb
->alllink
) {
1569 for(i
= 0; i
< fb
->cnt
; i
++) {
1571 callback(f
->fn
, f
->arg
, f
->ft
, f
->ot
);
1577 runtime_MSpan_EnsureSwept(MSpan
*s
)
1583 // Caller must disable preemption.
1584 // Otherwise when this function returns the span can become unswept again
1585 // (if GC is triggered on another goroutine).
1586 if(m
->locks
== 0 && m
->mallocing
== 0 && g
!= m
->g0
)
1587 runtime_throw("MSpan_EnsureSwept: m is not locked");
1589 sg
= runtime_mheap
.sweepgen
;
1590 if(runtime_atomicload(&s
->sweepgen
) == sg
)
1592 if(runtime_cas(&s
->sweepgen
, sg
-2, sg
-1)) {
1593 runtime_MSpan_Sweep(s
);
1596 // unfortunate condition, and we don't have efficient means to wait
1597 while(runtime_atomicload(&s
->sweepgen
) != sg
)
1601 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
1602 // It clears the mark bits in preparation for the next GC round.
1603 // Returns true if the span was returned to heap.
1605 runtime_MSpan_Sweep(MSpan
*s
)
1608 int32 cl
, n
, npages
, nfree
;
1609 uintptr size
, off
, *bitp
, shift
, bits
;
1617 uintptr type_data_inc
;
1619 Special
*special
, **specialp
, *y
;
1620 bool res
, sweepgenset
;
1624 // It's critical that we enter this function with preemption disabled,
1625 // GC must not start while we are in the middle of this function.
1626 if(m
->locks
== 0 && m
->mallocing
== 0 && runtime_g() != m
->g0
)
1627 runtime_throw("MSpan_Sweep: m is not locked");
1628 sweepgen
= runtime_mheap
.sweepgen
;
1629 if(s
->state
!= MSpanInUse
|| s
->sweepgen
!= sweepgen
-1) {
1630 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1631 s
->state
, s
->sweepgen
, sweepgen
);
1632 runtime_throw("MSpan_Sweep: bad span state");
1634 arena_start
= runtime_mheap
.arena_start
;
1640 // Chunk full of small blocks.
1641 npages
= runtime_class_to_allocnpages
[cl
];
1642 n
= (npages
<< PageShift
) / size
;
1648 sweepgenset
= false;
1650 // mark any free objects in this span so we don't collect them
1651 for(x
= s
->freelist
; x
!= nil
; x
= x
->next
) {
1652 // This is markonly(x) but faster because we don't need
1653 // atomic access and we're guaranteed to be pointing at
1654 // the head of a valid object.
1655 off
= (uintptr
*)x
- (uintptr
*)runtime_mheap
.arena_start
;
1656 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
1657 shift
= off
% wordsPerBitmapWord
;
1658 *bitp
|= bitMarked
<<shift
;
1661 // Unlink & free special records for any objects we're about to free.
1662 specialp
= &s
->specials
;
1663 special
= *specialp
;
1664 while(special
!= nil
) {
1665 // A finalizer can be set for an inner byte of an object, find object beginning.
1666 p
= (byte
*)(s
->start
<< PageShift
) + special
->offset
/size
*size
;
1667 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1668 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1669 shift
= off
% wordsPerBitmapWord
;
1670 bits
= *bitp
>>shift
;
1671 if((bits
& (bitAllocated
|bitMarked
)) == bitAllocated
) {
1672 // Find the exact byte for which the special was setup
1673 // (as opposed to object beginning).
1674 p
= (byte
*)(s
->start
<< PageShift
) + special
->offset
;
1675 // about to free object: splice out special record
1677 special
= special
->next
;
1678 *specialp
= special
;
1679 if(!runtime_freespecial(y
, p
, size
, false)) {
1680 // stop freeing of object if it has a finalizer
1681 *bitp
|= bitMarked
<< shift
;
1684 // object is still live: keep special record
1685 specialp
= &special
->next
;
1686 special
= *specialp
;
1690 type_data
= (byte
*)s
->types
.data
;
1691 type_data_inc
= sizeof(uintptr
);
1692 compression
= s
->types
.compression
;
1693 switch(compression
) {
1695 type_data
+= 8*sizeof(uintptr
);
1700 // Sweep through n objects of given size starting at p.
1701 // This thread owns the span now, so it can manipulate
1702 // the block bitmap without atomic operations.
1703 p
= (byte
*)(s
->start
<< PageShift
);
1704 for(; n
> 0; n
--, p
+= size
, type_data
+=type_data_inc
) {
1705 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1706 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1707 shift
= off
% wordsPerBitmapWord
;
1708 bits
= *bitp
>>shift
;
1710 if((bits
& bitAllocated
) == 0)
1713 if((bits
& bitMarked
) != 0) {
1714 *bitp
&= ~(bitMarked
<<shift
);
1718 if(runtime_debug
.allocfreetrace
)
1719 runtime_tracefree(p
, size
);
1721 // Clear mark and scan bits.
1722 *bitp
&= ~((bitScan
|bitMarked
)<<shift
);
1726 runtime_unmarkspan(p
, 1<<PageShift
);
1728 // important to set sweepgen before returning it to heap
1729 runtime_atomicstore(&s
->sweepgen
, sweepgen
);
1731 // See note about SysFault vs SysFree in malloc.goc.
1732 if(runtime_debug
.efence
)
1733 runtime_SysFault(p
, size
);
1735 runtime_MHeap_Free(&runtime_mheap
, s
, 1);
1736 c
->local_nlargefree
++;
1737 c
->local_largefree
+= size
;
1738 runtime_xadd64(&mstats()->next_gc
, -(uint64
)(size
* (gcpercent
+ 100)/100));
1741 // Free small object.
1742 switch(compression
) {
1744 *(uintptr
*)type_data
= 0;
1747 *(byte
*)type_data
= 0;
1750 if(size
> 2*sizeof(uintptr
))
1751 ((uintptr
*)p
)[1] = (uintptr
)0xdeaddeaddeaddeadll
; // mark as "needs to be zeroed"
1752 else if(size
> sizeof(uintptr
))
1753 ((uintptr
*)p
)[1] = 0;
1755 end
->next
= (MLink
*)p
;
1761 // We need to set s->sweepgen = h->sweepgen only when all blocks are swept,
1762 // because of the potential for a concurrent free/SetFinalizer.
1763 // But we need to set it before we make the span available for allocation
1764 // (return it to heap or mcentral), because allocation code assumes that a
1765 // span is already swept if available for allocation.
1767 if(!sweepgenset
&& nfree
== 0) {
1768 // The span must be in our exclusive ownership until we update sweepgen,
1769 // check for potential races.
1770 if(s
->state
!= MSpanInUse
|| s
->sweepgen
!= sweepgen
-1) {
1771 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1772 s
->state
, s
->sweepgen
, sweepgen
);
1773 runtime_throw("MSpan_Sweep: bad span state after sweep");
1775 runtime_atomicstore(&s
->sweepgen
, sweepgen
);
1778 c
->local_nsmallfree
[cl
] += nfree
;
1779 c
->local_cachealloc
-= nfree
* size
;
1780 runtime_xadd64(&mstats()->next_gc
, -(uint64
)(nfree
* size
* (gcpercent
+ 100)/100));
1781 res
= runtime_MCentral_FreeSpan(&runtime_mheap
.central
[cl
], s
, nfree
, head
.next
, end
);
1782 //MCentral_FreeSpan updates sweepgen
1787 // State of background sweep.
1788 // Protected by gclock.
1799 // background sweeping goroutine
1801 bgsweep(void* dummy
__attribute__ ((unused
)))
1803 runtime_g()->issystem
= 1;
1805 while(runtime_sweepone() != (uintptr
)-1) {
1809 runtime_lock(&gclock
);
1810 if(!runtime_mheap
.sweepdone
) {
1811 // It's possible if GC has happened between sweepone has
1812 // returned -1 and gclock lock.
1813 runtime_unlock(&gclock
);
1816 sweep
.parked
= true;
1817 runtime_g()->isbackground
= true;
1818 runtime_parkunlock(&gclock
, "GC sweep wait");
1819 runtime_g()->isbackground
= false;
1824 // returns number of pages returned to heap, or -1 if there is nothing to sweep
1826 runtime_sweepone(void)
1833 // increment locks to ensure that the goroutine is not preempted
1834 // in the middle of sweep thus leaving the span in an inconsistent state for next GC
1836 sg
= runtime_mheap
.sweepgen
;
1838 idx
= runtime_xadd(&sweep
.spanidx
, 1) - 1;
1839 if(idx
>= sweep
.nspan
) {
1840 runtime_mheap
.sweepdone
= true;
1844 s
= sweep
.spans
[idx
];
1845 if(s
->state
!= MSpanInUse
) {
1849 if(s
->sweepgen
!= sg
-2 || !runtime_cas(&s
->sweepgen
, sg
-2, sg
-1))
1852 runtime_throw("sweep of incache span");
1854 if(!runtime_MSpan_Sweep(s
))
1862 dumpspan(uint32 idx
)
1864 int32 sizeclass
, n
, npages
, i
, column
;
1871 s
= runtime_mheap
.allspans
[idx
];
1872 if(s
->state
!= MSpanInUse
)
1874 arena_start
= runtime_mheap
.arena_start
;
1875 p
= (byte
*)(s
->start
<< PageShift
);
1876 sizeclass
= s
->sizeclass
;
1878 if(sizeclass
== 0) {
1881 npages
= runtime_class_to_allocnpages
[sizeclass
];
1882 n
= (npages
<< PageShift
) / size
;
1885 runtime_printf("%p .. %p:\n", p
, p
+n
*size
);
1887 for(; n
>0; n
--, p
+=size
) {
1888 uintptr off
, *bitp
, shift
, bits
;
1890 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1891 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1892 shift
= off
% wordsPerBitmapWord
;
1893 bits
= *bitp
>>shift
;
1895 allocated
= ((bits
& bitAllocated
) != 0);
1897 for(i
=0; (uint32
)i
<size
; i
+=sizeof(void*)) {
1899 runtime_printf("\t");
1902 runtime_printf(allocated
? "(" : "[");
1903 runtime_printf("%p: ", p
+i
);
1905 runtime_printf(" ");
1908 runtime_printf("%p", *(void**)(p
+i
));
1910 if(i
+sizeof(void*) >= size
) {
1911 runtime_printf(allocated
? ") " : "] ");
1916 runtime_printf("\n");
1921 runtime_printf("\n");
1924 // A debugging function to dump the contents of memory
1926 runtime_memorydump(void)
1930 for(spanidx
=0; spanidx
<runtime_mheap
.nspan
; spanidx
++) {
1936 runtime_gchelper(void)
1940 runtime_m()->traceback
= 2;
1943 // parallel mark for over gc roots
1944 runtime_parfordo(work
.markfor
);
1946 // help other threads scan secondary blocks
1947 scanblock(nil
, true);
1949 bufferList
[runtime_m()->helpgc
].busy
= 0;
1950 nproc
= work
.nproc
; // work.nproc can change right after we increment work.ndone
1951 if(runtime_xadd(&work
.ndone
, +1) == nproc
-1)
1952 runtime_notewakeup(&work
.alldone
);
1953 runtime_m()->traceback
= 0;
1962 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
1966 runtime_purgecachedstats(c
);
1971 flushallmcaches(void)
1976 // Flush MCache's to MCentral.
1977 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
1981 runtime_MCache_ReleaseAll(c
);
1986 runtime_updatememstats(GCStats
*stats
)
1991 uint64 stacks_inuse
, smallfree
;
1996 runtime_memclr((byte
*)stats
, sizeof(*stats
));
1998 for(mp
=runtime_allm
; mp
; mp
=mp
->alllink
) {
1999 //stacks_inuse += mp->stackinuse*FixedStack;
2001 src
= (uint64
*)&mp
->gcstats
;
2002 dst
= (uint64
*)stats
;
2003 for(i
=0; i
<sizeof(*stats
)/sizeof(uint64
); i
++)
2005 runtime_memclr((byte
*)&mp
->gcstats
, sizeof(mp
->gcstats
));
2009 pmstats
->stacks_inuse
= stacks_inuse
;
2010 pmstats
->mcache_inuse
= runtime_mheap
.cachealloc
.inuse
;
2011 pmstats
->mspan_inuse
= runtime_mheap
.spanalloc
.inuse
;
2012 pmstats
->sys
= pmstats
->heap_sys
+ pmstats
->stacks_sys
+ pmstats
->mspan_sys
+
2013 pmstats
->mcache_sys
+ pmstats
->buckhash_sys
+ pmstats
->gc_sys
+ pmstats
->other_sys
;
2015 // Calculate memory allocator stats.
2016 // During program execution we only count number of frees and amount of freed memory.
2017 // Current number of alive object in the heap and amount of alive heap memory
2018 // are calculated by scanning all spans.
2019 // Total number of mallocs is calculated as number of frees plus number of alive objects.
2020 // Similarly, total amount of allocated memory is calculated as amount of freed memory
2021 // plus amount of alive heap memory.
2023 pmstats
->total_alloc
= 0;
2024 pmstats
->nmalloc
= 0;
2026 for(i
= 0; i
< nelem(pmstats
->by_size
); i
++) {
2027 pmstats
->by_size
[i
].nmalloc
= 0;
2028 pmstats
->by_size
[i
].nfree
= 0;
2031 // Flush MCache's to MCentral.
2034 // Aggregate local stats.
2037 // Scan all spans and count number of alive objects.
2038 for(i
= 0; i
< runtime_mheap
.nspan
; i
++) {
2039 s
= runtime_mheap
.allspans
[i
];
2040 if(s
->state
!= MSpanInUse
)
2042 if(s
->sizeclass
== 0) {
2044 pmstats
->alloc
+= s
->elemsize
;
2046 pmstats
->nmalloc
+= s
->ref
;
2047 pmstats
->by_size
[s
->sizeclass
].nmalloc
+= s
->ref
;
2048 pmstats
->alloc
+= s
->ref
*s
->elemsize
;
2052 // Aggregate by size class.
2054 pmstats
->nfree
= runtime_mheap
.nlargefree
;
2055 for(i
= 0; i
< nelem(pmstats
->by_size
); i
++) {
2056 pmstats
->nfree
+= runtime_mheap
.nsmallfree
[i
];
2057 pmstats
->by_size
[i
].nfree
= runtime_mheap
.nsmallfree
[i
];
2058 pmstats
->by_size
[i
].nmalloc
+= runtime_mheap
.nsmallfree
[i
];
2059 smallfree
+= runtime_mheap
.nsmallfree
[i
] * runtime_class_to_size
[i
];
2061 pmstats
->nmalloc
+= pmstats
->nfree
;
2063 // Calculate derived stats.
2064 pmstats
->total_alloc
= pmstats
->alloc
+ runtime_mheap
.largefree
+ smallfree
;
2065 pmstats
->heap_alloc
= pmstats
->alloc
;
2066 pmstats
->heap_objects
= pmstats
->nmalloc
- pmstats
->nfree
;
2069 // Structure of arguments passed to function gc().
2070 // This allows the arguments to be passed via runtime_mcall.
2073 int64 start_time
; // start time of GC in ns (just before stoptheworld)
2077 static void gc(struct gc_args
*args
);
2078 static void mgc(G
*gp
);
2086 s
= runtime_getenv("GOGC");
2090 if(s
.len
== 3 && runtime_strcmp((const char *)p
, "off") == 0)
2092 return runtime_atoi(p
, s
.len
);
2095 // force = 1 - do GC regardless of current heap usage
2096 // force = 2 - go GC and eager sweep
2098 runtime_gc(int32 force
)
2106 // The atomic operations are not atomic if the uint64s
2107 // are not aligned on uint64 boundaries. This has been
2108 // a problem in the past.
2109 if((((uintptr
)&work
.wempty
) & 7) != 0)
2110 runtime_throw("runtime: gc work buffer is misaligned");
2111 if((((uintptr
)&work
.full
) & 7) != 0)
2112 runtime_throw("runtime: gc work buffer is misaligned");
2114 // Make sure all registers are saved on stack so that
2115 // scanstack sees them.
2116 __builtin_unwind_init();
2118 // The gc is turned off (via enablegc) until
2119 // the bootstrap has completed.
2120 // Also, malloc gets called in the guts
2121 // of a number of libraries that might be
2122 // holding locks. To avoid priority inversion
2123 // problems, don't bother trying to run gc
2124 // while holding a lock. The next mallocgc
2125 // without a lock will do the gc instead.
2128 if(!pmstats
->enablegc
|| runtime_g() == m
->g0
|| m
->locks
> 0 || runtime_panicking
|| m
->preemptoff
.len
> 0)
2131 if(gcpercent
== GcpercentUnknown
) { // first time through
2132 runtime_lock(&runtime_mheap
);
2133 if(gcpercent
== GcpercentUnknown
)
2134 gcpercent
= readgogc();
2135 runtime_unlock(&runtime_mheap
);
2140 runtime_acquireWorldsema();
2141 if(force
==0 && pmstats
->heap_alloc
< pmstats
->next_gc
) {
2142 // typically threads which lost the race to grab
2143 // worldsema exit here when gc is done.
2144 runtime_releaseWorldsema();
2148 // Ok, we're doing it! Stop everybody else
2149 a
.start_time
= runtime_nanotime();
2150 a
.eagersweep
= force
>= 2;
2152 runtime_stopTheWorldWithSema();
2156 // Run gc on the g0 stack. We do this so that the g stack
2157 // we're currently running on will no longer change. Cuts
2158 // the root set down a bit (g0 stacks are not scanned, and
2159 // we don't need to scan gc's internal state). Also an
2160 // enabler for copyable stacks.
2161 for(i
= 0; i
< (runtime_debug
.gctrace
> 1 ? 2 : 1); i
++) {
2163 a
.start_time
= runtime_nanotime();
2164 // switch to g0, call gc(&a), then switch back
2167 g
->atomicstatus
= _Gwaiting
;
2168 g
->waitreason
= runtime_gostringnocopy((const byte
*)"garbage collection");
2176 runtime_releaseWorldsema();
2177 runtime_startTheWorldWithSema();
2180 // now that gc is done, kick off finalizer thread if needed
2181 if(!ConcurrentSweep
) {
2182 // give the queued finalizers, if any, a chance to run
2185 // For gccgo, let other goroutines run.
2195 gp
->atomicstatus
= _Grunning
;
2200 gc(struct gc_args
*args
)
2203 int64 tm0
, tm1
, tm2
, tm3
, tm4
;
2204 uint64 heap0
, heap1
, obj
, ninstr
;
2212 if(runtime_debug
.allocfreetrace
)
2216 tm0
= args
->start_time
;
2217 work
.tstart
= args
->start_time
;
2220 runtime_memclr((byte
*)&gcstats
, sizeof(gcstats
));
2222 m
->locks
++; // disable gc during mallocs in parforalloc
2223 if(work
.markfor
== nil
)
2224 work
.markfor
= runtime_parforalloc(MaxGcproc
);
2228 if(runtime_debug
.gctrace
)
2229 tm1
= runtime_nanotime();
2231 // Sweep what is not sweeped by bgsweep.
2232 while(runtime_sweepone() != (uintptr
)-1)
2233 gcstats
.npausesweep
++;
2237 work
.nproc
= runtime_gcprocs();
2238 runtime_parforsetup(work
.markfor
, work
.nproc
, RootCount
+ runtime_allglen
, false, &markroot_funcval
);
2239 if(work
.nproc
> 1) {
2240 runtime_noteclear(&work
.alldone
);
2241 runtime_helpgc(work
.nproc
);
2245 if(runtime_debug
.gctrace
)
2246 tm2
= runtime_nanotime();
2249 runtime_parfordo(work
.markfor
);
2250 scanblock(nil
, true);
2253 if(runtime_debug
.gctrace
)
2254 tm3
= runtime_nanotime();
2256 bufferList
[m
->helpgc
].busy
= 0;
2258 runtime_notesleep(&work
.alldone
);
2261 // next_gc calculation is tricky with concurrent sweep since we don't know size of live heap
2262 // estimate what was live heap size after previous GC (for tracing only)
2264 heap0
= pmstats
->next_gc
*100/(gcpercent
+100);
2265 // conservatively set next_gc to high value assuming that everything is live
2266 // concurrent/lazy sweep will reduce this number while discovering new garbage
2267 pmstats
->next_gc
= pmstats
->heap_alloc
+(pmstats
->heap_alloc
-runtime_stacks_sys
)*gcpercent
/100;
2269 tm4
= runtime_nanotime();
2270 pmstats
->last_gc
= runtime_unixnanotime(); // must be Unix time to make sense to user
2271 pmstats
->pause_ns
[pmstats
->numgc
%nelem(pmstats
->pause_ns
)] = tm4
- tm0
;
2272 pmstats
->pause_end
[pmstats
->numgc
%nelem(pmstats
->pause_end
)] = pmstats
->last_gc
;
2273 pmstats
->pause_total_ns
+= tm4
- tm0
;
2275 if(pmstats
->debuggc
)
2276 runtime_printf("pause %D\n", tm4
-tm0
);
2278 if(runtime_debug
.gctrace
) {
2279 heap1
= pmstats
->heap_alloc
;
2280 runtime_updatememstats(&stats
);
2281 if(heap1
!= pmstats
->heap_alloc
) {
2282 runtime_printf("runtime: mstats skew: heap=%D/%D\n", heap1
, pmstats
->heap_alloc
);
2283 runtime_throw("mstats skew");
2285 obj
= pmstats
->nmalloc
- pmstats
->nfree
;
2287 stats
.nprocyield
+= work
.markfor
->nprocyield
;
2288 stats
.nosyield
+= work
.markfor
->nosyield
;
2289 stats
.nsleep
+= work
.markfor
->nsleep
;
2291 runtime_printf("gc%d(%d): %D+%D+%D+%D us, %D -> %D MB, %D (%D-%D) objects,"
2293 " %D(%D) handoff, %D(%D) steal, %D/%D/%D yields\n",
2294 pmstats
->numgc
, work
.nproc
, (tm1
-tm0
)/1000, (tm2
-tm1
)/1000, (tm3
-tm2
)/1000, (tm4
-tm3
)/1000,
2295 heap0
>>20, heap1
>>20, obj
,
2296 pmstats
->nmalloc
, pmstats
->nfree
,
2297 sweep
.nspan
, gcstats
.nbgsweep
, gcstats
.npausesweep
,
2298 stats
.nhandoff
, stats
.nhandoffcnt
,
2299 work
.markfor
->nsteal
, work
.markfor
->nstealcnt
,
2300 stats
.nprocyield
, stats
.nosyield
, stats
.nsleep
);
2301 gcstats
.nbgsweep
= gcstats
.npausesweep
= 0;
2303 runtime_printf("scan: %D bytes, %D objects, %D untyped, %D types from MSpan\n",
2304 gcstats
.nbytes
, gcstats
.obj
.cnt
, gcstats
.obj
.notype
, gcstats
.obj
.typelookup
);
2305 if(gcstats
.ptr
.cnt
!= 0)
2306 runtime_printf("avg ptrbufsize: %D (%D/%D)\n",
2307 gcstats
.ptr
.sum
/gcstats
.ptr
.cnt
, gcstats
.ptr
.sum
, gcstats
.ptr
.cnt
);
2308 if(gcstats
.obj
.cnt
!= 0)
2309 runtime_printf("avg nobj: %D (%D/%D)\n",
2310 gcstats
.obj
.sum
/gcstats
.obj
.cnt
, gcstats
.obj
.sum
, gcstats
.obj
.cnt
);
2311 runtime_printf("rescans: %D, %D bytes\n", gcstats
.rescan
, gcstats
.rescanbytes
);
2313 runtime_printf("instruction counts:\n");
2315 for(i
=0; i
<nelem(gcstats
.instr
); i
++) {
2316 runtime_printf("\t%d:\t%D\n", i
, gcstats
.instr
[i
]);
2317 ninstr
+= gcstats
.instr
[i
];
2319 runtime_printf("\ttotal:\t%D\n", ninstr
);
2321 runtime_printf("putempty: %D, getfull: %D\n", gcstats
.putempty
, gcstats
.getfull
);
2323 runtime_printf("markonly base lookup: bit %D word %D span %D\n", gcstats
.markonly
.foundbit
, gcstats
.markonly
.foundword
, gcstats
.markonly
.foundspan
);
2324 runtime_printf("flushptrbuf base lookup: bit %D word %D span %D\n", gcstats
.flushptrbuf
.foundbit
, gcstats
.flushptrbuf
.foundword
, gcstats
.flushptrbuf
.foundspan
);
2328 // We cache current runtime_mheap.allspans array in sweep.spans,
2329 // because the former can be resized and freed.
2330 // Otherwise we would need to take heap lock every time
2331 // we want to convert span index to span pointer.
2333 // Free the old cached array if necessary.
2334 if(sweep
.spans
&& sweep
.spans
!= runtime_mheap
.allspans
)
2335 runtime_SysFree(sweep
.spans
, sweep
.nspan
*sizeof(sweep
.spans
[0]), &pmstats
->other_sys
);
2336 // Cache the current array.
2337 runtime_mheap
.sweepspans
= runtime_mheap
.allspans
;
2338 runtime_mheap
.sweepgen
+= 2;
2339 runtime_mheap
.sweepdone
= false;
2340 sweep
.spans
= runtime_mheap
.allspans
;
2341 sweep
.nspan
= runtime_mheap
.nspan
;
2344 // Temporary disable concurrent sweep, because we see failures on builders.
2345 if(ConcurrentSweep
&& !args
->eagersweep
) {
2346 runtime_lock(&gclock
);
2348 sweep
.g
= __go_go(bgsweep
, nil
);
2349 else if(sweep
.parked
) {
2350 sweep
.parked
= false;
2351 runtime_ready(sweep
.g
);
2353 runtime_unlock(&gclock
);
2355 // Sweep all spans eagerly.
2356 while(runtime_sweepone() != (uintptr
)-1)
2357 gcstats
.npausesweep
++;
2358 // Do an additional mProf_GC, because all 'free' events are now real as well.
2366 void runtime_debug_readGCStats(Slice
*)
2367 __asm__("runtime_debug.readGCStats");
2370 runtime_debug_readGCStats(Slice
*pauses
)
2376 // Calling code in runtime/debug should make the slice large enough.
2378 if((size_t)pauses
->cap
< nelem(pmstats
->pause_ns
)+3)
2379 runtime_throw("runtime: short slice passed to readGCStats");
2381 // Pass back: pauses, last gc (absolute time), number of gc, total pause ns.
2382 p
= (uint64
*)pauses
->array
;
2383 runtime_lock(&runtime_mheap
);
2385 if(n
> nelem(pmstats
->pause_ns
))
2386 n
= nelem(pmstats
->pause_ns
);
2388 // The pause buffer is circular. The most recent pause is at
2389 // pause_ns[(numgc-1)%nelem(pause_ns)], and then backward
2390 // from there to go back farther in time. We deliver the times
2391 // most recent first (in p[0]).
2392 for(i
=0; i
<n
; i
++) {
2393 p
[i
] = pmstats
->pause_ns
[(pmstats
->numgc
-1-i
)%nelem(pmstats
->pause_ns
)];
2394 p
[n
+i
] = pmstats
->pause_end
[(pmstats
->numgc
-1-i
)%nelem(pmstats
->pause_ns
)];
2397 p
[n
+n
] = pmstats
->last_gc
;
2398 p
[n
+n
+1] = pmstats
->numgc
;
2399 p
[n
+n
+2] = pmstats
->pause_total_ns
;
2400 runtime_unlock(&runtime_mheap
);
2401 pauses
->__count
= n
+n
+3;
2405 runtime_setgcpercent(int32 in
) {
2408 runtime_lock(&runtime_mheap
);
2409 if(gcpercent
== GcpercentUnknown
)
2410 gcpercent
= readgogc();
2415 runtime_unlock(&runtime_mheap
);
2425 if(m
->helpgc
< 0 || m
->helpgc
>= MaxGcproc
)
2426 runtime_throw("gchelperstart: bad m->helpgc");
2427 if(runtime_xchg(&bufferList
[m
->helpgc
].busy
, 1))
2428 runtime_throw("gchelperstart: already busy");
2429 if(runtime_g() != m
->g0
)
2430 runtime_throw("gchelper not running on g0 stack");
2434 runfinq(void* dummy
__attribute__ ((unused
)))
2437 FinBlock
*fb
, *next
;
2442 // This function blocks for long periods of time, and because it is written in C
2443 // we have no liveness information. Zero everything so that uninitialized pointers
2444 // do not cause memory leaks.
2452 // force flush to memory
2460 runtime_lock(&finlock
);
2464 runtime_fingwait
= true;
2465 runtime_g()->isbackground
= true;
2466 runtime_parkunlock(&finlock
, "finalizer wait");
2467 runtime_g()->isbackground
= false;
2470 runtime_unlock(&finlock
);
2471 for(; fb
; fb
=next
) {
2473 for(i
=0; i
<(uint32
)fb
->cnt
; i
++) {
2478 fint
= ((const Type
**)f
->ft
->__in
.array
)[0];
2479 if((fint
->__code
& kindMask
) == kindPtr
) {
2480 // direct use of pointer
2482 } else if(((const InterfaceType
*)fint
)->__methods
.__count
== 0) {
2483 // convert to empty interface
2484 // using memcpy as const_cast.
2485 memcpy(&ef
._type
, &f
->ot
,
2490 // convert to interface with methods
2491 iface
.tab
= getitab(fint
,
2494 iface
.data
= f
->arg
;
2495 if(iface
.data
== nil
)
2496 runtime_throw("invalid type conversion in runfinq");
2499 reflect_call(f
->ft
, f
->fn
, 0, 0, ¶m
, nil
);
2505 runtime_lock(&finlock
);
2508 runtime_unlock(&finlock
);
2511 // Zero everything that's dead, to avoid memory leaks.
2512 // See comment at top of function.
2519 runtime_gc(1); // trigger another gc to clean up the finalized objects, if possible
2524 runtime_createfing(void)
2528 // Here we use gclock instead of finlock,
2529 // because newproc1 can allocate, which can cause on-demand span sweep,
2530 // which can queue finalizers, which would deadlock.
2531 runtime_lock(&gclock
);
2533 fing
= __go_go(runfinq
, nil
);
2534 runtime_unlock(&gclock
);
2538 runtime_wakefing(void)
2543 runtime_lock(&finlock
);
2544 if(runtime_fingwait
&& runtime_fingwake
) {
2545 runtime_fingwait
= false;
2546 runtime_fingwake
= false;
2549 runtime_unlock(&finlock
);
2554 runtime_marknogc(void *v
)
2556 uintptr
*b
, off
, shift
;
2558 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2559 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2560 shift
= off
% wordsPerBitmapWord
;
2561 *b
= (*b
& ~(bitAllocated
<<shift
)) | bitBlockBoundary
<<shift
;
2565 runtime_markscan(void *v
)
2567 uintptr
*b
, off
, shift
;
2569 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2570 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2571 shift
= off
% wordsPerBitmapWord
;
2572 *b
|= bitScan
<<shift
;
2575 // mark the block at v as freed.
2577 runtime_markfreed(void *v
)
2579 uintptr
*b
, off
, shift
;
2582 runtime_printf("markfreed %p\n", v
);
2584 if((byte
*)v
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2585 runtime_throw("markfreed: bad pointer");
2587 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2588 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2589 shift
= off
% wordsPerBitmapWord
;
2590 *b
= (*b
& ~(bitMask
<<shift
)) | (bitAllocated
<<shift
);
2593 // check that the block at v of size n is marked freed.
2595 runtime_checkfreed(void *v
, uintptr n
)
2597 uintptr
*b
, bits
, off
, shift
;
2599 if(!runtime_checking
)
2602 if((byte
*)v
+n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2603 return; // not allocated, so okay
2605 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2606 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2607 shift
= off
% wordsPerBitmapWord
;
2610 if((bits
& bitAllocated
) != 0) {
2611 runtime_printf("checkfreed %p+%p: off=%p have=%p\n",
2612 v
, n
, off
, bits
& bitMask
);
2613 runtime_throw("checkfreed: not freed");
2617 // mark the span of memory at v as having n blocks of the given size.
2618 // if leftover is true, there is left over space at the end of the span.
2620 runtime_markspan(void *v
, uintptr size
, uintptr n
, bool leftover
)
2622 uintptr
*b
, *b0
, off
, shift
, i
, x
;
2625 if((byte
*)v
+size
*n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2626 runtime_throw("markspan: bad pointer");
2628 if(runtime_checking
) {
2629 // bits should be all zero at the start
2630 off
= (byte
*)v
+ size
- runtime_mheap
.arena_start
;
2631 b
= (uintptr
*)(runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
);
2632 for(i
= 0; i
< size
/PtrSize
/wordsPerBitmapWord
; i
++) {
2634 runtime_throw("markspan: span bits not zero");
2639 if(leftover
) // mark a boundary just past end of last block too
2644 for(; n
-- > 0; p
+= size
) {
2645 // Okay to use non-atomic ops here, because we control
2646 // the entire span, and each bitmap word has bits for only
2647 // one span, so no other goroutines are changing these
2649 off
= (uintptr
*)p
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2650 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2651 shift
= off
% wordsPerBitmapWord
;
2658 x
|= bitAllocated
<<shift
;
2663 // unmark the span of memory at v of length n bytes.
2665 runtime_unmarkspan(void *v
, uintptr n
)
2667 uintptr
*p
, *b
, off
;
2669 if((byte
*)v
+n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2670 runtime_throw("markspan: bad pointer");
2673 off
= p
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2674 if(off
% wordsPerBitmapWord
!= 0)
2675 runtime_throw("markspan: unaligned pointer");
2676 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2678 if(n
%wordsPerBitmapWord
!= 0)
2679 runtime_throw("unmarkspan: unaligned length");
2680 // Okay to use non-atomic ops here, because we control
2681 // the entire span, and each bitmap word has bits for only
2682 // one span, so no other goroutines are changing these
2684 n
/= wordsPerBitmapWord
;
2690 runtime_MHeap_MapBits(MHeap
*h
)
2694 // Caller has added extra mappings to the arena.
2695 // Add extra mappings of bitmap words as needed.
2696 // We allocate extra bitmap pieces in chunks of bitmapChunk.
2702 n
= (h
->arena_used
- h
->arena_start
) / wordsPerBitmapWord
;
2703 n
= ROUND(n
, bitmapChunk
);
2704 n
= ROUND(n
, PageSize
);
2705 page_size
= getpagesize();
2706 n
= ROUND(n
, page_size
);
2707 if(h
->bitmap_mapped
>= n
)
2710 runtime_SysMap(h
->arena_start
- n
, n
- h
->bitmap_mapped
, h
->arena_reserved
, &mstats()->gc_sys
);
2711 h
->bitmap_mapped
= n
;
2714 // typedmemmove copies a value of type t to dst from src.
2716 extern void typedmemmove(const Type
* td
, void *dst
, const void *src
)
2717 __asm__ (GOSYM_PREFIX
"reflect.typedmemmove");
2720 typedmemmove(const Type
* td
, void *dst
, const void *src
)
2722 runtime_memmove(dst
, src
, td
->__size
);
2725 // typedslicecopy copies a slice of elemType values from src to dst,
2726 // returning the number of elements copied.
2728 extern intgo
typedslicecopy(const Type
* elem
, Slice dst
, Slice src
)
2729 __asm__ (GOSYM_PREFIX
"reflect.typedslicecopy");
2732 typedslicecopy(const Type
* elem
, Slice dst
, Slice src
)
2739 if (n
> src
.__count
)
2743 dstp
= dst
.__values
;
2744 srcp
= src
.__values
;
2745 memmove(dstp
, srcp
, (uintptr_t)n
* elem
->__size
);