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).
63 // Map gccgo field names to gc field names.
64 // Slice aka __go_open_array.
65 #define array __values
66 #define cap __capacity
67 // Iface aka __go_interface
70 typedef struct __go_map Hmap
;
71 // Type aka __go_type_descriptor
72 #define string __reflection
73 #define KindPtr GO_PTR
74 #define KindNoPointers GO_NO_POINTERS
75 // PtrType aka __go_ptr_type
76 #define elem __element_type
78 #ifdef USING_SPLIT_STACK
80 extern void * __splitstack_find (void *, void *, size_t *, void **, void **,
83 extern void * __splitstack_find_context (void *context
[10], size_t *, void **,
93 WorkbufSize
= 16*1024,
94 FinBlockSize
= 4*1024,
97 IntermediateBufferCapacity
= 64,
99 // Bits in type information
102 PC_BITS
= PRECISE
| LOOP
,
112 #define GcpercentUnknown (-2)
114 // Initialized from $GOGC. GOGC=off means no gc.
115 static int32 gcpercent
= GcpercentUnknown
;
117 static FuncVal
* poolcleanup
;
119 void sync_runtime_registerPoolCleanup(FuncVal
*)
120 __asm__ (GOSYM_PREFIX
"sync.runtime_registerPoolCleanup");
123 sync_runtime_registerPoolCleanup(FuncVal
*f
)
135 if(poolcleanup
!= nil
) {
136 __go_set_closure(poolcleanup
);
140 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
141 // clear tinyalloc pool
152 // Holding worldsema grants an M the right to try to stop the world.
155 // runtime_semacquire(&runtime_worldsema);
157 // runtime_stoptheworld();
162 // runtime_semrelease(&runtime_worldsema);
163 // runtime_starttheworld();
165 uint32 runtime_worldsema
= 1;
167 typedef struct Workbuf Workbuf
;
170 #define SIZE (WorkbufSize-sizeof(LFNode)-sizeof(uintptr))
171 LFNode node
; // must be first
173 Obj obj
[SIZE
/sizeof(Obj
) - 1];
174 uint8 _padding
[SIZE
%sizeof(Obj
) + sizeof(Obj
)];
178 typedef struct Finalizer Finalizer
;
183 const struct __go_func_type
*ft
;
184 const struct __go_ptr_type
*ot
;
187 typedef struct FinBlock FinBlock
;
197 static Lock finlock
; // protects the following variables
198 static FinBlock
*finq
; // list of finalizers that are to be executed
199 static FinBlock
*finc
; // cache of free blocks
200 static FinBlock
*allfin
; // list of all blocks
201 bool runtime_fingwait
;
202 bool runtime_fingwake
;
207 static void runfinq(void*);
208 static void bgsweep(void*);
209 static Workbuf
* getempty(Workbuf
*);
210 static Workbuf
* getfull(Workbuf
*);
211 static void putempty(Workbuf
*);
212 static Workbuf
* handoff(Workbuf
*);
213 static void gchelperstart(void);
214 static void flushallmcaches(void);
215 static void addstackroots(G
*gp
, Workbuf
**wbufp
);
218 uint64 full
; // lock-free list of full blocks
219 uint64 empty
; // lock-free list of empty blocks
220 byte pad0
[CacheLineSize
]; // prevents false-sharing between full/empty and nproc/nwait
223 volatile uint32 nwait
;
224 volatile uint32 ndone
;
231 } work
__attribute__((aligned(8)));
234 GC_DEFAULT_PTR
= GC_NUM_INSTR
,
254 uint64 instr
[GC_NUM_INSTR2
];
271 // markonly marks an object. It returns true if the object
272 // has been marked by this function, false otherwise.
273 // This function doesn't append the object to any buffer.
275 markonly(const void *obj
)
278 uintptr
*bitp
, bits
, shift
, x
, xbits
, off
, j
;
282 // Words outside the arena cannot be pointers.
283 if((const byte
*)obj
< runtime_mheap
.arena_start
|| (const byte
*)obj
>= runtime_mheap
.arena_used
)
286 // obj may be a pointer to a live object.
287 // Try to find the beginning of the object.
289 // Round down to word boundary.
290 obj
= (const void*)((uintptr
)obj
& ~((uintptr
)PtrSize
-1));
292 // Find bits for this word.
293 off
= (const uintptr
*)obj
- (uintptr
*)runtime_mheap
.arena_start
;
294 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
295 shift
= off
% wordsPerBitmapWord
;
297 bits
= xbits
>> shift
;
299 // Pointing at the beginning of a block?
300 if((bits
& (bitAllocated
|bitBlockBoundary
)) != 0) {
302 runtime_xadd64(&gcstats
.markonly
.foundbit
, 1);
306 // Pointing just past the beginning?
307 // Scan backward a little to find a block boundary.
308 for(j
=shift
; j
-->0; ) {
309 if(((xbits
>>j
) & (bitAllocated
|bitBlockBoundary
)) != 0) {
313 runtime_xadd64(&gcstats
.markonly
.foundword
, 1);
318 // Otherwise consult span table to find beginning.
319 // (Manually inlined copy of MHeap_LookupMaybe.)
320 k
= (uintptr
)obj
>>PageShift
;
322 x
-= (uintptr
)runtime_mheap
.arena_start
>>PageShift
;
323 s
= runtime_mheap
.spans
[x
];
324 if(s
== nil
|| k
< s
->start
|| (const byte
*)obj
>= s
->limit
|| s
->state
!= MSpanInUse
)
326 p
= (byte
*)((uintptr
)s
->start
<<PageShift
);
327 if(s
->sizeclass
== 0) {
330 uintptr size
= s
->elemsize
;
331 int32 i
= ((const byte
*)obj
- p
)/size
;
335 // Now that we know the object header, reload bits.
336 off
= (const uintptr
*)obj
- (uintptr
*)runtime_mheap
.arena_start
;
337 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
338 shift
= off
% wordsPerBitmapWord
;
340 bits
= xbits
>> shift
;
342 runtime_xadd64(&gcstats
.markonly
.foundspan
, 1);
345 // Now we have bits, bitp, and shift correct for
346 // obj pointing at the base of the object.
347 // Only care about allocated and not marked.
348 if((bits
& (bitAllocated
|bitMarked
)) != bitAllocated
)
351 *bitp
|= bitMarked
<<shift
;
355 if(x
& (bitMarked
<<shift
))
357 if(runtime_casp((void**)bitp
, (void*)x
, (void*)(x
|(bitMarked
<<shift
))))
362 // The object is now marked
366 // PtrTarget is a structure used by intermediate buffers.
367 // The intermediate buffers hold GC data before it
368 // is moved/flushed to the work buffer (Workbuf).
369 // The size of an intermediate buffer is very small,
370 // such as 32 or 64 elements.
371 typedef struct PtrTarget PtrTarget
;
378 typedef struct Scanbuf Scanbuf
;
396 typedef struct BufferList BufferList
;
399 PtrTarget ptrtarget
[IntermediateBufferCapacity
];
400 Obj obj
[IntermediateBufferCapacity
];
402 byte pad
[CacheLineSize
];
404 static BufferList bufferList
[MaxGcproc
];
406 static Type
*itabtype
;
408 static void enqueue(Obj obj
, Workbuf
**_wbuf
, Obj
**_wp
, uintptr
*_nobj
);
410 // flushptrbuf moves data from the PtrTarget buffer to the work buffer.
411 // The PtrTarget buffer contains blocks irrespective of whether the blocks have been marked or scanned,
412 // while the work buffer contains blocks which have been marked
413 // and are prepared to be scanned by the garbage collector.
415 // _wp, _wbuf, _nobj are input/output parameters and are specifying the work buffer.
417 // A simplified drawing explaining how the todo-list moves from a structure to another:
421 // Obj ------> PtrTarget (pointer targets)
426 // (find block start, mark and enqueue)
428 flushptrbuf(Scanbuf
*sbuf
)
430 byte
*p
, *arena_start
, *obj
;
431 uintptr size
, *bitp
, bits
, shift
, j
, x
, xbits
, off
, nobj
, ti
, n
;
437 PtrTarget
*ptrbuf_end
;
439 arena_start
= runtime_mheap
.arena_start
;
445 ptrbuf
= sbuf
->ptr
.begin
;
446 ptrbuf_end
= sbuf
->ptr
.pos
;
447 n
= ptrbuf_end
- sbuf
->ptr
.begin
;
448 sbuf
->ptr
.pos
= sbuf
->ptr
.begin
;
451 runtime_xadd64(&gcstats
.ptr
.sum
, n
);
452 runtime_xadd64(&gcstats
.ptr
.cnt
, 1);
455 // If buffer is nearly full, get a new one.
456 if(wbuf
== nil
|| nobj
+n
>= nelem(wbuf
->obj
)) {
459 wbuf
= getempty(wbuf
);
463 if(n
>= nelem(wbuf
->obj
))
464 runtime_throw("ptrbuf has to be smaller than WorkBuf");
467 while(ptrbuf
< ptrbuf_end
) {
472 // obj belongs to interval [mheap.arena_start, mheap.arena_used).
474 if(obj
< runtime_mheap
.arena_start
|| obj
>= runtime_mheap
.arena_used
)
475 runtime_throw("object is outside of mheap");
478 // obj may be a pointer to a live object.
479 // Try to find the beginning of the object.
481 // Round down to word boundary.
482 if(((uintptr
)obj
& ((uintptr
)PtrSize
-1)) != 0) {
483 obj
= (void*)((uintptr
)obj
& ~((uintptr
)PtrSize
-1));
487 // Find bits for this word.
488 off
= (uintptr
*)obj
- (uintptr
*)arena_start
;
489 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
490 shift
= off
% wordsPerBitmapWord
;
492 bits
= xbits
>> shift
;
494 // Pointing at the beginning of a block?
495 if((bits
& (bitAllocated
|bitBlockBoundary
)) != 0) {
497 runtime_xadd64(&gcstats
.flushptrbuf
.foundbit
, 1);
503 // Pointing just past the beginning?
504 // Scan backward a little to find a block boundary.
505 for(j
=shift
; j
-->0; ) {
506 if(((xbits
>>j
) & (bitAllocated
|bitBlockBoundary
)) != 0) {
507 obj
= (byte
*)obj
- (shift
-j
)*PtrSize
;
511 runtime_xadd64(&gcstats
.flushptrbuf
.foundword
, 1);
516 // Otherwise consult span table to find beginning.
517 // (Manually inlined copy of MHeap_LookupMaybe.)
518 k
= (uintptr
)obj
>>PageShift
;
520 x
-= (uintptr
)arena_start
>>PageShift
;
521 s
= runtime_mheap
.spans
[x
];
522 if(s
== nil
|| k
< s
->start
|| obj
>= s
->limit
|| s
->state
!= MSpanInUse
)
524 p
= (byte
*)((uintptr
)s
->start
<<PageShift
);
525 if(s
->sizeclass
== 0) {
529 int32 i
= ((byte
*)obj
- p
)/size
;
533 // Now that we know the object header, reload bits.
534 off
= (uintptr
*)obj
- (uintptr
*)arena_start
;
535 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
536 shift
= off
% wordsPerBitmapWord
;
538 bits
= xbits
>> shift
;
540 runtime_xadd64(&gcstats
.flushptrbuf
.foundspan
, 1);
543 // Now we have bits, bitp, and shift correct for
544 // obj pointing at the base of the object.
545 // Only care about allocated and not marked.
546 if((bits
& (bitAllocated
|bitMarked
)) != bitAllocated
)
549 *bitp
|= bitMarked
<<shift
;
553 if(x
& (bitMarked
<<shift
))
555 if(runtime_casp((void**)bitp
, (void*)x
, (void*)(x
|(bitMarked
<<shift
))))
560 // If object has no pointers, don't need to scan further.
561 if((bits
& bitScan
) == 0)
564 // Ask span about size class.
565 // (Manually inlined copy of MHeap_Lookup.)
566 x
= (uintptr
)obj
>> PageShift
;
567 x
-= (uintptr
)arena_start
>>PageShift
;
568 s
= runtime_mheap
.spans
[x
];
572 *wp
= (Obj
){obj
, s
->elemsize
, ti
};
578 // If another proc wants a pointer, give it some.
579 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
581 wbuf
= handoff(wbuf
);
583 wp
= wbuf
->obj
+ nobj
;
592 flushobjbuf(Scanbuf
*sbuf
)
604 objbuf
= sbuf
->obj
.begin
;
605 objbuf_end
= sbuf
->obj
.pos
;
606 sbuf
->obj
.pos
= sbuf
->obj
.begin
;
608 while(objbuf
< objbuf_end
) {
611 // Align obj.b to a word boundary.
612 off
= (uintptr
)obj
.p
& (PtrSize
-1);
614 obj
.p
+= PtrSize
- off
;
615 obj
.n
-= PtrSize
- off
;
619 if(obj
.p
== nil
|| obj
.n
== 0)
622 // If buffer is full, get a new one.
623 if(wbuf
== nil
|| nobj
>= nelem(wbuf
->obj
)) {
626 wbuf
= getempty(wbuf
);
636 // If another proc wants a pointer, give it some.
637 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
639 wbuf
= handoff(wbuf
);
641 wp
= wbuf
->obj
+ nobj
;
649 // Program that scans the whole block and treats every block element as a potential pointer
650 static uintptr defaultProg
[2] = {PtrSize
, GC_DEFAULT_PTR
};
654 static uintptr chanProg
[2] = {0, GC_CHAN
};
657 // Local variables of a program fragment or loop
658 typedef struct Frame Frame
;
660 uintptr count
, elemsize
, b
;
661 uintptr
*loop_or_ret
;
664 // Sanity check for the derived type info objti.
666 checkptr(void *obj
, uintptr objti
)
668 uintptr type
, tisize
, i
, x
;
674 runtime_throw("checkptr is debug only");
676 if((byte
*)obj
< runtime_mheap
.arena_start
|| (byte
*)obj
>= runtime_mheap
.arena_used
)
678 type
= runtime_gettype(obj
);
679 t
= (Type
*)(type
& ~(uintptr
)(PtrSize
-1));
682 x
= (uintptr
)obj
>> PageShift
;
683 x
-= (uintptr
)(runtime_mheap
.arena_start
)>>PageShift
;
684 s
= runtime_mheap
.spans
[x
];
685 objstart
= (byte
*)((uintptr
)s
->start
<<PageShift
);
686 if(s
->sizeclass
!= 0) {
687 i
= ((byte
*)obj
- objstart
)/s
->elemsize
;
688 objstart
+= i
*s
->elemsize
;
690 tisize
= *(uintptr
*)objti
;
691 // Sanity check for object size: it should fit into the memory block.
692 if((byte
*)obj
+ tisize
> objstart
+ s
->elemsize
) {
693 runtime_printf("object of type '%S' at %p/%p does not fit in block %p/%p\n",
694 *t
->string
, obj
, tisize
, objstart
, s
->elemsize
);
695 runtime_throw("invalid gc type info");
699 // If obj points to the beginning of the memory block,
700 // check type info as well.
701 if(t
->string
== nil
||
702 // Gob allocates unsafe pointers for indirection.
703 (runtime_strcmp((const char *)t
->string
->str
, (const char*)"unsafe.Pointer") &&
704 // Runtime and gc think differently about closures.
705 runtime_strstr((const char *)t
->string
->str
, (const char*)"struct { F uintptr") != (const char *)t
->string
->str
)) {
707 pc1
= (uintptr
*)objti
;
708 pc2
= (uintptr
*)t
->gc
;
709 // A simple best-effort check until first GC_END.
710 for(j
= 1; pc1
[j
] != GC_END
&& pc2
[j
] != GC_END
; j
++) {
711 if(pc1
[j
] != pc2
[j
]) {
712 runtime_printf("invalid gc type info for '%s', type info %p [%d]=%p, block info %p [%d]=%p\n",
713 t
->string
? (const int8
*)t
->string
->str
: (const int8
*)"?", pc1
, (int32
)j
, pc1
[j
], pc2
, (int32
)j
, pc2
[j
]);
714 runtime_throw("invalid gc type info");
721 // scanblock scans a block of n bytes starting at pointer b for references
722 // to other objects, scanning any it finds recursively until there are no
723 // unscanned objects left. Instead of using an explicit recursion, it keeps
724 // a work list in the Workbuf* structures and loops in the main function
725 // body. Keeping an explicit work list is easier on the stack allocator and
728 scanblock(Workbuf
*wbuf
, bool keepworking
)
730 byte
*b
, *arena_start
, *arena_used
;
731 uintptr n
, i
, end_b
, elemsize
, size
, ti
, objti
, count
, /* type, */ nobj
;
732 uintptr
*pc
, precise_type
, nominal_size
;
734 uintptr
*chan_ret
, chancap
;
740 Frame
*stack_ptr
, stack_top
, stack
[GC_STACK_CAPACITY
+4];
741 BufferList
*scanbuffers
;
751 if(sizeof(Workbuf
) % WorkbufSize
!= 0)
752 runtime_throw("scanblock: size of Workbuf is suboptimal");
754 // Memory arena parameters.
755 arena_start
= runtime_mheap
.arena_start
;
756 arena_used
= runtime_mheap
.arena_used
;
758 stack_ptr
= stack
+nelem(stack
)-1;
760 precise_type
= false;
765 wp
= &wbuf
->obj
[nobj
];
772 scanbuffers
= &bufferList
[runtime_m()->helpgc
];
774 sbuf
.ptr
.begin
= sbuf
.ptr
.pos
= &scanbuffers
->ptrtarget
[0];
775 sbuf
.ptr
.end
= sbuf
.ptr
.begin
+ nelem(scanbuffers
->ptrtarget
);
777 sbuf
.obj
.begin
= sbuf
.obj
.pos
= &scanbuffers
->obj
[0];
778 sbuf
.obj
.end
= sbuf
.obj
.begin
+ nelem(scanbuffers
->obj
);
784 // (Silence the compiler)
794 // Each iteration scans the block b of length n, queueing pointers in
798 runtime_xadd64(&gcstats
.nbytes
, n
);
799 runtime_xadd64(&gcstats
.obj
.sum
, sbuf
.nobj
);
800 runtime_xadd64(&gcstats
.obj
.cnt
, 1);
803 if(ti
!= 0 && false) {
805 runtime_printf("scanblock %p %D ti %p\n", b
, (int64
)n
, ti
);
807 pc
= (uintptr
*)(ti
& ~(uintptr
)PC_BITS
);
808 precise_type
= (ti
& PRECISE
);
809 stack_top
.elemsize
= pc
[0];
811 nominal_size
= pc
[0];
813 stack_top
.count
= 0; // 0 means an infinite number of iterations
814 stack_top
.loop_or_ret
= pc
+1;
819 // Simple sanity check for provided type info ti:
820 // The declared size of the object must be not larger than the actual size
821 // (it can be smaller due to inferior pointers).
822 // It's difficult to make a comprehensive check due to inferior pointers,
823 // reflection, gob, etc.
825 runtime_printf("invalid gc type info: type info size %p, block size %p\n", pc
[0], n
);
826 runtime_throw("invalid gc type info");
829 } else if(UseSpanType
&& false) {
831 runtime_xadd64(&gcstats
.obj
.notype
, 1);
834 type
= runtime_gettype(b
);
837 runtime_xadd64(&gcstats
.obj
.typelookup
, 1);
839 t
= (Type
*)(type
& ~(uintptr
)(PtrSize
-1));
840 switch(type
& (PtrSize
-1)) {
841 case TypeInfo_SingleObject
:
842 pc
= (uintptr
*)t
->gc
;
843 precise_type
= true; // type information about 'b' is precise
845 stack_top
.elemsize
= pc
[0];
848 pc
= (uintptr
*)t
->gc
;
851 precise_type
= true; // type information about 'b' is precise
852 stack_top
.count
= 0; // 0 means an infinite number of iterations
853 stack_top
.elemsize
= pc
[0];
854 stack_top
.loop_or_ret
= pc
+1;
858 chantype
= (ChanType
*)t
;
864 runtime_printf("scanblock %p %D type %p %S\n", b
, (int64
)n
, type
, *t
->string
);
865 runtime_throw("scanblock: invalid type");
869 runtime_printf("scanblock %p %D type %p %S pc=%p\n", b
, (int64
)n
, type
, *t
->string
, pc
);
873 runtime_printf("scanblock %p %D unknown type\n", b
, (int64
)n
);
879 runtime_printf("scanblock %p %D no span types\n", b
, (int64
)n
);
886 stack_top
.b
= (uintptr
)b
;
887 end_b
= (uintptr
)b
+ n
- PtrSize
;
891 runtime_xadd64(&gcstats
.instr
[pc
[0]], 1);
897 obj
= *(void**)(stack_top
.b
+ pc
[1]);
900 runtime_printf("gc_ptr @%p: %p ti=%p\n", stack_top
.b
+pc
[1], obj
, objti
);
903 checkptr(obj
, objti
);
907 sliceptr
= (Slice
*)(stack_top
.b
+ pc
[1]);
909 runtime_printf("gc_slice @%p: %p/%D/%D\n", sliceptr
, sliceptr
->array
, (int64
)sliceptr
->__count
, (int64
)sliceptr
->cap
);
910 if(sliceptr
->cap
!= 0) {
911 obj
= sliceptr
->array
;
912 // Can't use slice element type for scanning,
913 // because if it points to an array embedded
914 // in the beginning of a struct,
915 // we will scan the whole struct as the slice.
916 // So just obtain type info from heap.
922 obj
= *(void**)(stack_top
.b
+ pc
[1]);
924 runtime_printf("gc_aptr @%p: %p\n", stack_top
.b
+pc
[1], obj
);
929 stringptr
= (String
*)(stack_top
.b
+ pc
[1]);
931 runtime_printf("gc_string @%p: %p/%D\n", stack_top
.b
+pc
[1], stringptr
->str
, (int64
)stringptr
->len
);
932 if(stringptr
->len
!= 0)
933 markonly(stringptr
->str
);
938 eface
= (Eface
*)(stack_top
.b
+ pc
[1]);
941 runtime_printf("gc_eface @%p: %p %p\n", stack_top
.b
+pc
[1], eface
->__type_descriptor
, eface
->__object
);
942 if(eface
->__type_descriptor
== nil
)
946 t
= eface
->__type_descriptor
;
947 if((const byte
*)t
>= arena_start
&& (const byte
*)t
< arena_used
) {
948 union { const Type
*tc
; Type
*tr
; } u
;
950 *sbuf
.ptr
.pos
++ = (PtrTarget
){u
.tr
, 0};
951 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
956 if((byte
*)eface
->__object
>= arena_start
&& (byte
*)eface
->__object
< arena_used
) {
957 if(t
->__size
<= sizeof(void*)) {
958 if((t
->__code
& KindNoPointers
))
961 obj
= eface
->__object
;
962 if((t
->__code
& ~KindNoPointers
) == KindPtr
) {
963 // Only use type information if it is a pointer-containing type.
964 // This matches the GC programs written by cmd/gc/reflect.c's
965 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
966 et
= ((const PtrType
*)t
)->elem
;
967 if(!(et
->__code
& KindNoPointers
))
968 // objti = (uintptr)((const PtrType*)t)->elem->gc;
972 obj
= eface
->__object
;
973 // objti = (uintptr)t->gc;
980 iface
= (Iface
*)(stack_top
.b
+ pc
[1]);
983 runtime_printf("gc_iface @%p: %p/%p %p\n", stack_top
.b
+pc
[1], iface
->__methods
[0], nil
, iface
->__object
);
984 if(iface
->tab
== nil
)
988 if((byte
*)iface
->tab
>= arena_start
&& (byte
*)iface
->tab
< arena_used
) {
989 *sbuf
.ptr
.pos
++ = (PtrTarget
){iface
->tab
, /* (uintptr)itabtype->gc */ 0};
990 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
995 if((byte
*)iface
->__object
>= arena_start
&& (byte
*)iface
->__object
< arena_used
) {
996 // t = iface->tab->type;
998 if(t
->__size
<= sizeof(void*)) {
999 if((t
->__code
& KindNoPointers
))
1002 obj
= iface
->__object
;
1003 if((t
->__code
& ~KindNoPointers
) == KindPtr
) {
1004 // Only use type information if it is a pointer-containing type.
1005 // This matches the GC programs written by cmd/gc/reflect.c's
1006 // dgcsym1 in case TPTR32/case TPTR64. See rationale there.
1007 et
= ((const PtrType
*)t
)->elem
;
1008 if(!(et
->__code
& KindNoPointers
))
1009 // objti = (uintptr)((const PtrType*)t)->elem->gc;
1013 obj
= iface
->__object
;
1014 // objti = (uintptr)t->gc;
1020 case GC_DEFAULT_PTR
:
1021 while(stack_top
.b
<= end_b
) {
1022 obj
= *(byte
**)stack_top
.b
;
1024 runtime_printf("gc_default_ptr @%p: %p\n", stack_top
.b
, obj
);
1025 stack_top
.b
+= PtrSize
;
1026 if((byte
*)obj
>= arena_start
&& (byte
*)obj
< arena_used
) {
1027 *sbuf
.ptr
.pos
++ = (PtrTarget
){obj
, 0};
1028 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
1035 if(--stack_top
.count
!= 0) {
1036 // Next iteration of a loop if possible.
1037 stack_top
.b
+= stack_top
.elemsize
;
1038 if(stack_top
.b
+ stack_top
.elemsize
<= end_b
+PtrSize
) {
1039 pc
= stack_top
.loop_or_ret
;
1044 // Stack pop if possible.
1045 if(stack_ptr
+1 < stack
+nelem(stack
)) {
1046 pc
= stack_top
.loop_or_ret
;
1047 stack_top
= *(++stack_ptr
);
1050 i
= (uintptr
)b
+ nominal_size
;
1053 // Quickly scan [b+i,b+n) for possible pointers.
1054 for(; i
<=end_b
; i
+=PtrSize
) {
1055 if(*(byte
**)i
!= nil
) {
1056 // Found a value that may be a pointer.
1057 // Do a rescan of the entire block.
1058 enqueue((Obj
){b
, n
, 0}, &sbuf
.wbuf
, &sbuf
.wp
, &sbuf
.nobj
);
1060 runtime_xadd64(&gcstats
.rescan
, 1);
1061 runtime_xadd64(&gcstats
.rescanbytes
, n
);
1069 case GC_ARRAY_START
:
1070 i
= stack_top
.b
+ pc
[1];
1076 *stack_ptr
-- = stack_top
;
1077 stack_top
= (Frame
){count
, elemsize
, i
, pc
};
1081 if(--stack_top
.count
!= 0) {
1082 stack_top
.b
+= stack_top
.elemsize
;
1083 pc
= stack_top
.loop_or_ret
;
1086 stack_top
= *(++stack_ptr
);
1093 *stack_ptr
-- = stack_top
;
1094 stack_top
= (Frame
){1, 0, stack_top
.b
+ pc
[1], pc
+3 /*return address*/};
1095 pc
= (uintptr
*)((byte
*)pc
+ *(int32
*)(pc
+2)); // target of the CALL instruction
1099 obj
= (void*)(stack_top
.b
+ pc
[1]);
1105 runtime_printf("gc_region @%p: %D %p\n", stack_top
.b
+pc
[1], (int64
)size
, objti
);
1106 *sbuf
.obj
.pos
++ = (Obj
){obj
, size
, objti
};
1107 if(sbuf
.obj
.pos
== sbuf
.obj
.end
)
1113 chan
= *(Hchan
**)(stack_top
.b
+ pc
[1]);
1114 if(Debug
> 2 && chan
!= nil
)
1115 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]);
1120 if(markonly(chan
)) {
1121 chantype
= (ChanType
*)pc
[2];
1122 if(!(chantype
->elem
->__code
& KindNoPointers
)) {
1133 // There are no heap pointers in struct Hchan,
1134 // so we can ignore the leading sizeof(Hchan) bytes.
1135 if(!(chantype
->elem
->__code
& KindNoPointers
)) {
1136 // Channel's buffer follows Hchan immediately in memory.
1137 // Size of buffer (cap(c)) is second int in the chan struct.
1138 chancap
= ((uintgo
*)chan
)[1];
1140 // TODO(atom): split into two chunks so that only the
1141 // in-use part of the circular buffer is scanned.
1142 // (Channel routines zero the unused part, so the current
1143 // code does not lead to leaks, it's just a little inefficient.)
1144 *sbuf
.obj
.pos
++ = (Obj
){(byte
*)chan
+runtime_Hchansize
, chancap
*chantype
->elem
->size
,
1145 (uintptr
)chantype
->elem
->gc
| PRECISE
| LOOP
};
1146 if(sbuf
.obj
.pos
== sbuf
.obj
.end
)
1157 runtime_printf("runtime: invalid GC instruction %p at %p\n", pc
[0], pc
);
1158 runtime_throw("scanblock: invalid GC instruction");
1162 if((byte
*)obj
>= arena_start
&& (byte
*)obj
< arena_used
) {
1163 *sbuf
.ptr
.pos
++ = (PtrTarget
){obj
, objti
};
1164 if(sbuf
.ptr
.pos
== sbuf
.ptr
.end
)
1170 // Done scanning [b, b+n). Prepare for the next iteration of
1171 // the loop by setting b, n, ti to the parameters for the next block.
1173 if(sbuf
.nobj
== 0) {
1177 if(sbuf
.nobj
== 0) {
1180 putempty(sbuf
.wbuf
);
1183 // Emptied our buffer: refill.
1184 sbuf
.wbuf
= getfull(sbuf
.wbuf
);
1185 if(sbuf
.wbuf
== nil
)
1187 sbuf
.nobj
= sbuf
.wbuf
->nobj
;
1188 sbuf
.wp
= sbuf
.wbuf
->obj
+ sbuf
.wbuf
->nobj
;
1192 // Fetch b from the work buffer.
1201 static struct root_list
* roots
;
1204 __go_register_gc_roots (struct root_list
* r
)
1206 // FIXME: This needs locking if multiple goroutines can call
1207 // dlopen simultaneously.
1212 // Append obj to the work buffer.
1213 // _wbuf, _wp, _nobj are input/output parameters and are specifying the work buffer.
1215 enqueue(Obj obj
, Workbuf
**_wbuf
, Obj
**_wp
, uintptr
*_nobj
)
1222 runtime_printf("append obj(%p %D %p)\n", obj
.p
, (int64
)obj
.n
, obj
.ti
);
1224 // Align obj.b to a word boundary.
1225 off
= (uintptr
)obj
.p
& (PtrSize
-1);
1227 obj
.p
+= PtrSize
- off
;
1228 obj
.n
-= PtrSize
- off
;
1232 if(obj
.p
== nil
|| obj
.n
== 0)
1235 // Load work buffer state
1240 // If another proc wants a pointer, give it some.
1241 if(work
.nwait
> 0 && nobj
> handoffThreshold
&& work
.full
== 0) {
1243 wbuf
= handoff(wbuf
);
1245 wp
= wbuf
->obj
+ nobj
;
1248 // If buffer is full, get a new one.
1249 if(wbuf
== nil
|| nobj
>= nelem(wbuf
->obj
)) {
1252 wbuf
= getempty(wbuf
);
1261 // Save work buffer state
1268 enqueue1(Workbuf
**wbufp
, Obj obj
)
1273 if(wbuf
->nobj
>= nelem(wbuf
->obj
))
1274 *wbufp
= wbuf
= getempty(wbuf
);
1275 wbuf
->obj
[wbuf
->nobj
++] = obj
;
1279 markroot(ParFor
*desc
, uint32 i
)
1284 MSpan
**allspans
, *s
;
1290 wbuf
= getempty(nil
);
1291 // Note: if you add a case here, please also update heapdump.c:dumproots.
1294 // For gccgo this is both data and bss.
1296 struct root_list
*pl
;
1298 for(pl
= roots
; pl
!= nil
; pl
= pl
->next
) {
1299 struct root
*pr
= &pl
->roots
[0];
1301 void *decl
= pr
->decl
;
1304 enqueue1(&wbuf
, (Obj
){decl
, pr
->size
, 0});
1312 // For gccgo we use this for all the other global roots.
1313 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_m0
, sizeof runtime_m0
, 0});
1314 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_g0
, sizeof runtime_g0
, 0});
1315 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allg
, sizeof runtime_allg
, 0});
1316 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allm
, sizeof runtime_allm
, 0});
1317 enqueue1(&wbuf
, (Obj
){(byte
*)&runtime_allp
, sizeof runtime_allp
, 0});
1318 enqueue1(&wbuf
, (Obj
){(byte
*)&work
, sizeof work
, 0});
1319 runtime_proc_scan(&wbuf
, enqueue1
);
1320 runtime_MProf_Mark(&wbuf
, enqueue1
);
1321 runtime_time_scan(&wbuf
, enqueue1
);
1322 runtime_netpoll_scan(&wbuf
, enqueue1
);
1325 case RootFinalizers
:
1326 for(fb
=allfin
; fb
; fb
=fb
->alllink
)
1327 enqueue1(&wbuf
, (Obj
){(byte
*)fb
->fin
, fb
->cnt
*sizeof(fb
->fin
[0]), 0});
1331 // mark span types and MSpan.specials (to walk spans only once)
1334 allspans
= h
->allspans
;
1335 for(spanidx
=0; spanidx
<runtime_mheap
.nspan
; spanidx
++) {
1337 SpecialFinalizer
*spf
;
1339 s
= allspans
[spanidx
];
1340 if(s
->sweepgen
!= sg
) {
1341 runtime_printf("sweep %d %d\n", s
->sweepgen
, sg
);
1342 runtime_throw("gc: unswept span");
1344 if(s
->state
!= MSpanInUse
)
1346 // The garbage collector ignores type pointers stored in MSpan.types:
1347 // - Compiler-generated types are stored outside of heap.
1348 // - The reflect package has runtime-generated types cached in its data structures.
1349 // The garbage collector relies on finding the references via that cache.
1350 if(s
->types
.compression
== MTypes_Words
|| s
->types
.compression
== MTypes_Bytes
)
1351 markonly((byte
*)s
->types
.data
);
1352 for(sp
= s
->specials
; sp
!= nil
; sp
= sp
->next
) {
1353 if(sp
->kind
!= KindSpecialFinalizer
)
1355 // don't mark finalized object, but scan it so we
1356 // retain everything it points to.
1357 spf
= (SpecialFinalizer
*)sp
;
1358 // A finalizer can be set for an inner byte of an object, find object beginning.
1359 p
= (void*)((s
->start
<< PageShift
) + spf
->offset
/s
->elemsize
*s
->elemsize
);
1360 enqueue1(&wbuf
, (Obj
){p
, s
->elemsize
, 0});
1361 enqueue1(&wbuf
, (Obj
){(void*)&spf
->fn
, PtrSize
, 0});
1362 enqueue1(&wbuf
, (Obj
){(void*)&spf
->ft
, PtrSize
, 0});
1363 enqueue1(&wbuf
, (Obj
){(void*)&spf
->ot
, PtrSize
, 0});
1368 case RootFlushCaches
:
1373 // the rest is scanning goroutine stacks
1374 if(i
- RootCount
>= runtime_allglen
)
1375 runtime_throw("markroot: bad index");
1376 gp
= runtime_allg
[i
- RootCount
];
1377 // remember when we've first observed the G blocked
1378 // needed only to output in traceback
1379 if((gp
->status
== Gwaiting
|| gp
->status
== Gsyscall
) && gp
->waitsince
== 0)
1380 gp
->waitsince
= work
.tstart
;
1381 addstackroots(gp
, &wbuf
);
1387 scanblock(wbuf
, false);
1390 // Get an empty work buffer off the work.empty list,
1391 // allocating new buffers as needed.
1393 getempty(Workbuf
*b
)
1396 runtime_lfstackpush(&work
.full
, &b
->node
);
1397 b
= (Workbuf
*)runtime_lfstackpop(&work
.empty
);
1399 // Need to allocate.
1400 runtime_lock(&work
);
1401 if(work
.nchunk
< sizeof *b
) {
1402 work
.nchunk
= 1<<20;
1403 work
.chunk
= runtime_SysAlloc(work
.nchunk
, &mstats
.gc_sys
);
1404 if(work
.chunk
== nil
)
1405 runtime_throw("runtime: cannot allocate memory");
1407 b
= (Workbuf
*)work
.chunk
;
1408 work
.chunk
+= sizeof *b
;
1409 work
.nchunk
-= sizeof *b
;
1410 runtime_unlock(&work
);
1417 putempty(Workbuf
*b
)
1420 runtime_xadd64(&gcstats
.putempty
, 1);
1422 runtime_lfstackpush(&work
.empty
, &b
->node
);
1425 // Get a full work buffer off the work.full list, or return nil.
1433 runtime_xadd64(&gcstats
.getfull
, 1);
1436 runtime_lfstackpush(&work
.empty
, &b
->node
);
1437 b
= (Workbuf
*)runtime_lfstackpop(&work
.full
);
1438 if(b
!= nil
|| work
.nproc
== 1)
1442 runtime_xadd(&work
.nwait
, +1);
1444 if(work
.full
!= 0) {
1445 runtime_xadd(&work
.nwait
, -1);
1446 b
= (Workbuf
*)runtime_lfstackpop(&work
.full
);
1449 runtime_xadd(&work
.nwait
, +1);
1451 if(work
.nwait
== work
.nproc
)
1454 m
->gcstats
.nprocyield
++;
1455 runtime_procyield(20);
1457 m
->gcstats
.nosyield
++;
1460 m
->gcstats
.nsleep
++;
1461 runtime_usleep(100);
1475 // Make new buffer with half of b's pointers.
1480 runtime_memmove(b1
->obj
, b
->obj
+b
->nobj
, n
*sizeof b1
->obj
[0]);
1481 m
->gcstats
.nhandoff
++;
1482 m
->gcstats
.nhandoffcnt
+= n
;
1484 // Put b on full list - let first half of b get stolen.
1485 runtime_lfstackpush(&work
.full
, &b
->node
);
1490 addstackroots(G
*gp
, Workbuf
**wbufp
)
1494 runtime_printf("unexpected G.status %d (goroutine %p %D)\n", gp
->status
, gp
, gp
->goid
);
1495 runtime_throw("mark - bad status");
1499 runtime_throw("mark - world not stopped");
1506 #ifdef USING_SPLIT_STACK
1514 if(gp
== runtime_g()) {
1515 // Scanning our own stack.
1516 sp
= __splitstack_find(nil
, nil
, &spsize
, &next_segment
,
1517 &next_sp
, &initial_sp
);
1518 } else if((mp
= gp
->m
) != nil
&& mp
->helpgc
) {
1519 // gchelper's stack is in active use and has no interesting pointers.
1522 // Scanning another goroutine's stack.
1523 // The goroutine is usually asleep (the world is stopped).
1525 // The exception is that if the goroutine is about to enter or might
1526 // have just exited a system call, it may be executing code such
1527 // as schedlock and may have needed to start a new stack segment.
1528 // Use the stack segment and stack pointer at the time of
1529 // the system call instead, since that won't change underfoot.
1530 if(gp
->gcstack
!= nil
) {
1532 spsize
= gp
->gcstack_size
;
1533 next_segment
= gp
->gcnext_segment
;
1534 next_sp
= gp
->gcnext_sp
;
1535 initial_sp
= gp
->gcinitial_sp
;
1537 sp
= __splitstack_find_context(&gp
->stack_context
[0],
1538 &spsize
, &next_segment
,
1539 &next_sp
, &initial_sp
);
1543 enqueue1(wbufp
, (Obj
){sp
, spsize
, 0});
1544 while((sp
= __splitstack_find(next_segment
, next_sp
,
1545 &spsize
, &next_segment
,
1546 &next_sp
, &initial_sp
)) != nil
)
1547 enqueue1(wbufp
, (Obj
){sp
, spsize
, 0});
1554 if(gp
== runtime_g()) {
1555 // Scanning our own stack.
1556 bottom
= (byte
*)&gp
;
1557 } else if((mp
= gp
->m
) != nil
&& mp
->helpgc
) {
1558 // gchelper's stack is in active use and has no interesting pointers.
1561 // Scanning another goroutine's stack.
1562 // The goroutine is usually asleep (the world is stopped).
1563 bottom
= (byte
*)gp
->gcnext_sp
;
1567 top
= (byte
*)gp
->gcinitial_sp
+ gp
->gcstack_size
;
1569 enqueue1(wbufp
, (Obj
){bottom
, top
- bottom
, 0});
1571 enqueue1(wbufp
, (Obj
){top
, bottom
- top
, 0});
1576 runtime_queuefinalizer(void *p
, FuncVal
*fn
, const FuncType
*ft
, const PtrType
*ot
)
1581 runtime_lock(&finlock
);
1582 if(finq
== nil
|| finq
->cnt
== finq
->cap
) {
1584 finc
= runtime_persistentalloc(FinBlockSize
, 0, &mstats
.gc_sys
);
1585 finc
->cap
= (FinBlockSize
- sizeof(FinBlock
)) / sizeof(Finalizer
) + 1;
1586 finc
->alllink
= allfin
;
1594 f
= &finq
->fin
[finq
->cnt
];
1600 runtime_fingwake
= true;
1601 runtime_unlock(&finlock
);
1605 runtime_iterate_finq(void (*callback
)(FuncVal
*, void*, const FuncType
*, const PtrType
*))
1611 for(fb
= allfin
; fb
; fb
= fb
->alllink
) {
1612 for(i
= 0; i
< fb
->cnt
; i
++) {
1614 callback(f
->fn
, f
->arg
, f
->ft
, f
->ot
);
1620 runtime_MSpan_EnsureSwept(MSpan
*s
)
1626 // Caller must disable preemption.
1627 // Otherwise when this function returns the span can become unswept again
1628 // (if GC is triggered on another goroutine).
1629 if(m
->locks
== 0 && m
->mallocing
== 0 && g
!= m
->g0
)
1630 runtime_throw("MSpan_EnsureSwept: m is not locked");
1632 sg
= runtime_mheap
.sweepgen
;
1633 if(runtime_atomicload(&s
->sweepgen
) == sg
)
1635 if(runtime_cas(&s
->sweepgen
, sg
-2, sg
-1)) {
1636 runtime_MSpan_Sweep(s
);
1639 // unfortunate condition, and we don't have efficient means to wait
1640 while(runtime_atomicload(&s
->sweepgen
) != sg
)
1644 // Sweep frees or collects finalizers for blocks not marked in the mark phase.
1645 // It clears the mark bits in preparation for the next GC round.
1646 // Returns true if the span was returned to heap.
1648 runtime_MSpan_Sweep(MSpan
*s
)
1651 int32 cl
, n
, npages
, nfree
;
1652 uintptr size
, off
, *bitp
, shift
, bits
;
1660 uintptr type_data_inc
;
1662 Special
*special
, **specialp
, *y
;
1663 bool res
, sweepgenset
;
1667 // It's critical that we enter this function with preemption disabled,
1668 // GC must not start while we are in the middle of this function.
1669 if(m
->locks
== 0 && m
->mallocing
== 0 && runtime_g() != m
->g0
)
1670 runtime_throw("MSpan_Sweep: m is not locked");
1671 sweepgen
= runtime_mheap
.sweepgen
;
1672 if(s
->state
!= MSpanInUse
|| s
->sweepgen
!= sweepgen
-1) {
1673 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1674 s
->state
, s
->sweepgen
, sweepgen
);
1675 runtime_throw("MSpan_Sweep: bad span state");
1677 arena_start
= runtime_mheap
.arena_start
;
1683 // Chunk full of small blocks.
1684 npages
= runtime_class_to_allocnpages
[cl
];
1685 n
= (npages
<< PageShift
) / size
;
1691 sweepgenset
= false;
1693 // mark any free objects in this span so we don't collect them
1694 for(x
= s
->freelist
; x
!= nil
; x
= x
->next
) {
1695 // This is markonly(x) but faster because we don't need
1696 // atomic access and we're guaranteed to be pointing at
1697 // the head of a valid object.
1698 off
= (uintptr
*)x
- (uintptr
*)runtime_mheap
.arena_start
;
1699 bitp
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
1700 shift
= off
% wordsPerBitmapWord
;
1701 *bitp
|= bitMarked
<<shift
;
1704 // Unlink & free special records for any objects we're about to free.
1705 specialp
= &s
->specials
;
1706 special
= *specialp
;
1707 while(special
!= nil
) {
1708 // A finalizer can be set for an inner byte of an object, find object beginning.
1709 p
= (byte
*)(s
->start
<< PageShift
) + special
->offset
/size
*size
;
1710 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1711 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1712 shift
= off
% wordsPerBitmapWord
;
1713 bits
= *bitp
>>shift
;
1714 if((bits
& (bitAllocated
|bitMarked
)) == bitAllocated
) {
1715 // Find the exact byte for which the special was setup
1716 // (as opposed to object beginning).
1717 p
= (byte
*)(s
->start
<< PageShift
) + special
->offset
;
1718 // about to free object: splice out special record
1720 special
= special
->next
;
1721 *specialp
= special
;
1722 if(!runtime_freespecial(y
, p
, size
, false)) {
1723 // stop freeing of object if it has a finalizer
1724 *bitp
|= bitMarked
<< shift
;
1727 // object is still live: keep special record
1728 specialp
= &special
->next
;
1729 special
= *specialp
;
1733 type_data
= (byte
*)s
->types
.data
;
1734 type_data_inc
= sizeof(uintptr
);
1735 compression
= s
->types
.compression
;
1736 switch(compression
) {
1738 type_data
+= 8*sizeof(uintptr
);
1743 // Sweep through n objects of given size starting at p.
1744 // This thread owns the span now, so it can manipulate
1745 // the block bitmap without atomic operations.
1746 p
= (byte
*)(s
->start
<< PageShift
);
1747 for(; n
> 0; n
--, p
+= size
, type_data
+=type_data_inc
) {
1748 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1749 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1750 shift
= off
% wordsPerBitmapWord
;
1751 bits
= *bitp
>>shift
;
1753 if((bits
& bitAllocated
) == 0)
1756 if((bits
& bitMarked
) != 0) {
1757 *bitp
&= ~(bitMarked
<<shift
);
1761 if(runtime_debug
.allocfreetrace
)
1762 runtime_tracefree(p
, size
);
1764 // Clear mark and scan bits.
1765 *bitp
&= ~((bitScan
|bitMarked
)<<shift
);
1769 runtime_unmarkspan(p
, 1<<PageShift
);
1771 // important to set sweepgen before returning it to heap
1772 runtime_atomicstore(&s
->sweepgen
, sweepgen
);
1774 // See note about SysFault vs SysFree in malloc.goc.
1775 if(runtime_debug
.efence
)
1776 runtime_SysFault(p
, size
);
1778 runtime_MHeap_Free(&runtime_mheap
, s
, 1);
1779 c
->local_nlargefree
++;
1780 c
->local_largefree
+= size
;
1781 runtime_xadd64(&mstats
.next_gc
, -(uint64
)(size
* (gcpercent
+ 100)/100));
1784 // Free small object.
1785 switch(compression
) {
1787 *(uintptr
*)type_data
= 0;
1790 *(byte
*)type_data
= 0;
1793 if(size
> 2*sizeof(uintptr
))
1794 ((uintptr
*)p
)[1] = (uintptr
)0xdeaddeaddeaddeadll
; // mark as "needs to be zeroed"
1795 else if(size
> sizeof(uintptr
))
1796 ((uintptr
*)p
)[1] = 0;
1798 end
->next
= (MLink
*)p
;
1804 // We need to set s->sweepgen = h->sweepgen only when all blocks are swept,
1805 // because of the potential for a concurrent free/SetFinalizer.
1806 // But we need to set it before we make the span available for allocation
1807 // (return it to heap or mcentral), because allocation code assumes that a
1808 // span is already swept if available for allocation.
1810 if(!sweepgenset
&& nfree
== 0) {
1811 // The span must be in our exclusive ownership until we update sweepgen,
1812 // check for potential races.
1813 if(s
->state
!= MSpanInUse
|| s
->sweepgen
!= sweepgen
-1) {
1814 runtime_printf("MSpan_Sweep: state=%d sweepgen=%d mheap.sweepgen=%d\n",
1815 s
->state
, s
->sweepgen
, sweepgen
);
1816 runtime_throw("MSpan_Sweep: bad span state after sweep");
1818 runtime_atomicstore(&s
->sweepgen
, sweepgen
);
1821 c
->local_nsmallfree
[cl
] += nfree
;
1822 c
->local_cachealloc
-= nfree
* size
;
1823 runtime_xadd64(&mstats
.next_gc
, -(uint64
)(nfree
* size
* (gcpercent
+ 100)/100));
1824 res
= runtime_MCentral_FreeSpan(&runtime_mheap
.central
[cl
], s
, nfree
, head
.next
, end
);
1825 //MCentral_FreeSpan updates sweepgen
1830 // State of background sweep.
1831 // Pretected by gclock.
1842 // background sweeping goroutine
1844 bgsweep(void* dummy
__attribute__ ((unused
)))
1846 runtime_g()->issystem
= 1;
1848 while(runtime_sweepone() != (uintptr
)-1) {
1852 runtime_lock(&gclock
);
1853 if(!runtime_mheap
.sweepdone
) {
1854 // It's possible if GC has happened between sweepone has
1855 // returned -1 and gclock lock.
1856 runtime_unlock(&gclock
);
1859 sweep
.parked
= true;
1860 runtime_g()->isbackground
= true;
1861 runtime_parkunlock(&gclock
, "GC sweep wait");
1862 runtime_g()->isbackground
= false;
1867 // returns number of pages returned to heap, or -1 if there is nothing to sweep
1869 runtime_sweepone(void)
1876 // increment locks to ensure that the goroutine is not preempted
1877 // in the middle of sweep thus leaving the span in an inconsistent state for next GC
1879 sg
= runtime_mheap
.sweepgen
;
1881 idx
= runtime_xadd(&sweep
.spanidx
, 1) - 1;
1882 if(idx
>= sweep
.nspan
) {
1883 runtime_mheap
.sweepdone
= true;
1887 s
= sweep
.spans
[idx
];
1888 if(s
->state
!= MSpanInUse
) {
1892 if(s
->sweepgen
!= sg
-2 || !runtime_cas(&s
->sweepgen
, sg
-2, sg
-1))
1895 runtime_throw("sweep of incache span");
1897 if(!runtime_MSpan_Sweep(s
))
1905 dumpspan(uint32 idx
)
1907 int32 sizeclass
, n
, npages
, i
, column
;
1914 s
= runtime_mheap
.allspans
[idx
];
1915 if(s
->state
!= MSpanInUse
)
1917 arena_start
= runtime_mheap
.arena_start
;
1918 p
= (byte
*)(s
->start
<< PageShift
);
1919 sizeclass
= s
->sizeclass
;
1921 if(sizeclass
== 0) {
1924 npages
= runtime_class_to_allocnpages
[sizeclass
];
1925 n
= (npages
<< PageShift
) / size
;
1928 runtime_printf("%p .. %p:\n", p
, p
+n
*size
);
1930 for(; n
>0; n
--, p
+=size
) {
1931 uintptr off
, *bitp
, shift
, bits
;
1933 off
= (uintptr
*)p
- (uintptr
*)arena_start
;
1934 bitp
= (uintptr
*)arena_start
- off
/wordsPerBitmapWord
- 1;
1935 shift
= off
% wordsPerBitmapWord
;
1936 bits
= *bitp
>>shift
;
1938 allocated
= ((bits
& bitAllocated
) != 0);
1940 for(i
=0; (uint32
)i
<size
; i
+=sizeof(void*)) {
1942 runtime_printf("\t");
1945 runtime_printf(allocated
? "(" : "[");
1946 runtime_printf("%p: ", p
+i
);
1948 runtime_printf(" ");
1951 runtime_printf("%p", *(void**)(p
+i
));
1953 if(i
+sizeof(void*) >= size
) {
1954 runtime_printf(allocated
? ") " : "] ");
1959 runtime_printf("\n");
1964 runtime_printf("\n");
1967 // A debugging function to dump the contents of memory
1969 runtime_memorydump(void)
1973 for(spanidx
=0; spanidx
<runtime_mheap
.nspan
; spanidx
++) {
1979 runtime_gchelper(void)
1983 runtime_m()->traceback
= 2;
1986 // parallel mark for over gc roots
1987 runtime_parfordo(work
.markfor
);
1989 // help other threads scan secondary blocks
1990 scanblock(nil
, true);
1992 bufferList
[runtime_m()->helpgc
].busy
= 0;
1993 nproc
= work
.nproc
; // work.nproc can change right after we increment work.ndone
1994 if(runtime_xadd(&work
.ndone
, +1) == nproc
-1)
1995 runtime_notewakeup(&work
.alldone
);
1996 runtime_m()->traceback
= 0;
2005 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
2009 runtime_purgecachedstats(c
);
2014 flushallmcaches(void)
2019 // Flush MCache's to MCentral.
2020 for(pp
=runtime_allp
; (p
=*pp
) != nil
; pp
++) {
2024 runtime_MCache_ReleaseAll(c
);
2029 runtime_updatememstats(GCStats
*stats
)
2034 uint64 stacks_inuse
, smallfree
;
2038 runtime_memclr((byte
*)stats
, sizeof(*stats
));
2040 for(mp
=runtime_allm
; mp
; mp
=mp
->alllink
) {
2041 //stacks_inuse += mp->stackinuse*FixedStack;
2043 src
= (uint64
*)&mp
->gcstats
;
2044 dst
= (uint64
*)stats
;
2045 for(i
=0; i
<sizeof(*stats
)/sizeof(uint64
); i
++)
2047 runtime_memclr((byte
*)&mp
->gcstats
, sizeof(mp
->gcstats
));
2050 mstats
.stacks_inuse
= stacks_inuse
;
2051 mstats
.mcache_inuse
= runtime_mheap
.cachealloc
.inuse
;
2052 mstats
.mspan_inuse
= runtime_mheap
.spanalloc
.inuse
;
2053 mstats
.sys
= mstats
.heap_sys
+ mstats
.stacks_sys
+ mstats
.mspan_sys
+
2054 mstats
.mcache_sys
+ mstats
.buckhash_sys
+ mstats
.gc_sys
+ mstats
.other_sys
;
2056 // Calculate memory allocator stats.
2057 // During program execution we only count number of frees and amount of freed memory.
2058 // Current number of alive object in the heap and amount of alive heap memory
2059 // are calculated by scanning all spans.
2060 // Total number of mallocs is calculated as number of frees plus number of alive objects.
2061 // Similarly, total amount of allocated memory is calculated as amount of freed memory
2062 // plus amount of alive heap memory.
2064 mstats
.total_alloc
= 0;
2067 for(i
= 0; i
< nelem(mstats
.by_size
); i
++) {
2068 mstats
.by_size
[i
].nmalloc
= 0;
2069 mstats
.by_size
[i
].nfree
= 0;
2072 // Flush MCache's to MCentral.
2075 // Aggregate local stats.
2078 // Scan all spans and count number of alive objects.
2079 for(i
= 0; i
< runtime_mheap
.nspan
; i
++) {
2080 s
= runtime_mheap
.allspans
[i
];
2081 if(s
->state
!= MSpanInUse
)
2083 if(s
->sizeclass
== 0) {
2085 mstats
.alloc
+= s
->elemsize
;
2087 mstats
.nmalloc
+= s
->ref
;
2088 mstats
.by_size
[s
->sizeclass
].nmalloc
+= s
->ref
;
2089 mstats
.alloc
+= s
->ref
*s
->elemsize
;
2093 // Aggregate by size class.
2095 mstats
.nfree
= runtime_mheap
.nlargefree
;
2096 for(i
= 0; i
< nelem(mstats
.by_size
); i
++) {
2097 mstats
.nfree
+= runtime_mheap
.nsmallfree
[i
];
2098 mstats
.by_size
[i
].nfree
= runtime_mheap
.nsmallfree
[i
];
2099 mstats
.by_size
[i
].nmalloc
+= runtime_mheap
.nsmallfree
[i
];
2100 smallfree
+= runtime_mheap
.nsmallfree
[i
] * runtime_class_to_size
[i
];
2102 mstats
.nmalloc
+= mstats
.nfree
;
2104 // Calculate derived stats.
2105 mstats
.total_alloc
= mstats
.alloc
+ runtime_mheap
.largefree
+ smallfree
;
2106 mstats
.heap_alloc
= mstats
.alloc
;
2107 mstats
.heap_objects
= mstats
.nmalloc
- mstats
.nfree
;
2110 // Structure of arguments passed to function gc().
2111 // This allows the arguments to be passed via runtime_mcall.
2114 int64 start_time
; // start time of GC in ns (just before stoptheworld)
2118 static void gc(struct gc_args
*args
);
2119 static void mgc(G
*gp
);
2126 p
= runtime_getenv("GOGC");
2127 if(p
== nil
|| p
[0] == '\0')
2129 if(runtime_strcmp((const char *)p
, "off") == 0)
2131 return runtime_atoi(p
);
2134 // force = 1 - do GC regardless of current heap usage
2135 // force = 2 - go GC and eager sweep
2137 runtime_gc(int32 force
)
2144 // The atomic operations are not atomic if the uint64s
2145 // are not aligned on uint64 boundaries. This has been
2146 // a problem in the past.
2147 if((((uintptr
)&work
.empty
) & 7) != 0)
2148 runtime_throw("runtime: gc work buffer is misaligned");
2149 if((((uintptr
)&work
.full
) & 7) != 0)
2150 runtime_throw("runtime: gc work buffer is misaligned");
2152 // Make sure all registers are saved on stack so that
2153 // scanstack sees them.
2154 __builtin_unwind_init();
2156 // The gc is turned off (via enablegc) until
2157 // the bootstrap has completed.
2158 // Also, malloc gets called in the guts
2159 // of a number of libraries that might be
2160 // holding locks. To avoid priority inversion
2161 // problems, don't bother trying to run gc
2162 // while holding a lock. The next mallocgc
2163 // without a lock will do the gc instead.
2165 if(!mstats
.enablegc
|| runtime_g() == m
->g0
|| m
->locks
> 0 || runtime_panicking
)
2168 if(gcpercent
== GcpercentUnknown
) { // first time through
2169 runtime_lock(&runtime_mheap
);
2170 if(gcpercent
== GcpercentUnknown
)
2171 gcpercent
= readgogc();
2172 runtime_unlock(&runtime_mheap
);
2177 runtime_semacquire(&runtime_worldsema
, false);
2178 if(force
==0 && mstats
.heap_alloc
< mstats
.next_gc
) {
2179 // typically threads which lost the race to grab
2180 // worldsema exit here when gc is done.
2181 runtime_semrelease(&runtime_worldsema
);
2185 // Ok, we're doing it! Stop everybody else
2186 a
.start_time
= runtime_nanotime();
2187 a
.eagersweep
= force
>= 2;
2189 runtime_stoptheworld();
2193 // Run gc on the g0 stack. We do this so that the g stack
2194 // we're currently running on will no longer change. Cuts
2195 // the root set down a bit (g0 stacks are not scanned, and
2196 // we don't need to scan gc's internal state). Also an
2197 // enabler for copyable stacks.
2198 for(i
= 0; i
< (runtime_debug
.gctrace
> 1 ? 2 : 1); i
++) {
2200 a
.start_time
= runtime_nanotime();
2201 // switch to g0, call gc(&a), then switch back
2204 g
->status
= Gwaiting
;
2205 g
->waitreason
= "garbage collection";
2212 runtime_semrelease(&runtime_worldsema
);
2213 runtime_starttheworld();
2216 // now that gc is done, kick off finalizer thread if needed
2217 if(!ConcurrentSweep
) {
2218 // give the queued finalizers, if any, a chance to run
2221 // For gccgo, let other goroutines run.
2231 gp
->status
= Grunning
;
2236 gc(struct gc_args
*args
)
2239 int64 t0
, t1
, t2
, t3
, t4
;
2240 uint64 heap0
, heap1
, obj
, ninstr
;
2247 if(runtime_debug
.allocfreetrace
)
2251 t0
= args
->start_time
;
2252 work
.tstart
= args
->start_time
;
2255 runtime_memclr((byte
*)&gcstats
, sizeof(gcstats
));
2257 m
->locks
++; // disable gc during mallocs in parforalloc
2258 if(work
.markfor
== nil
)
2259 work
.markfor
= runtime_parforalloc(MaxGcproc
);
2262 if(itabtype
== nil
) {
2263 // get C pointer to the Go type "itab"
2264 // runtime_gc_itab_ptr(&eface);
2265 // itabtype = ((PtrType*)eface.__type_descriptor)->elem;
2269 if(runtime_debug
.gctrace
)
2270 t1
= runtime_nanotime();
2272 // Sweep what is not sweeped by bgsweep.
2273 while(runtime_sweepone() != (uintptr
)-1)
2274 gcstats
.npausesweep
++;
2278 work
.nproc
= runtime_gcprocs();
2279 runtime_parforsetup(work
.markfor
, work
.nproc
, RootCount
+ runtime_allglen
, nil
, false, markroot
);
2280 if(work
.nproc
> 1) {
2281 runtime_noteclear(&work
.alldone
);
2282 runtime_helpgc(work
.nproc
);
2286 if(runtime_debug
.gctrace
)
2287 t2
= runtime_nanotime();
2290 runtime_parfordo(work
.markfor
);
2291 scanblock(nil
, true);
2294 if(runtime_debug
.gctrace
)
2295 t3
= runtime_nanotime();
2297 bufferList
[m
->helpgc
].busy
= 0;
2299 runtime_notesleep(&work
.alldone
);
2302 // next_gc calculation is tricky with concurrent sweep since we don't know size of live heap
2303 // estimate what was live heap size after previous GC (for tracing only)
2304 heap0
= mstats
.next_gc
*100/(gcpercent
+100);
2305 // conservatively set next_gc to high value assuming that everything is live
2306 // concurrent/lazy sweep will reduce this number while discovering new garbage
2307 mstats
.next_gc
= mstats
.heap_alloc
+mstats
.heap_alloc
*gcpercent
/100;
2309 t4
= runtime_nanotime();
2310 mstats
.last_gc
= runtime_unixnanotime(); // must be Unix time to make sense to user
2311 mstats
.pause_ns
[mstats
.numgc
%nelem(mstats
.pause_ns
)] = t4
- t0
;
2312 mstats
.pause_total_ns
+= t4
- t0
;
2315 runtime_printf("pause %D\n", t4
-t0
);
2317 if(runtime_debug
.gctrace
) {
2318 heap1
= mstats
.heap_alloc
;
2319 runtime_updatememstats(&stats
);
2320 if(heap1
!= mstats
.heap_alloc
) {
2321 runtime_printf("runtime: mstats skew: heap=%D/%D\n", heap1
, mstats
.heap_alloc
);
2322 runtime_throw("mstats skew");
2324 obj
= mstats
.nmalloc
- mstats
.nfree
;
2326 stats
.nprocyield
+= work
.markfor
->nprocyield
;
2327 stats
.nosyield
+= work
.markfor
->nosyield
;
2328 stats
.nsleep
+= work
.markfor
->nsleep
;
2330 runtime_printf("gc%d(%d): %D+%D+%D+%D us, %D -> %D MB, %D (%D-%D) objects,"
2332 " %D(%D) handoff, %D(%D) steal, %D/%D/%D yields\n",
2333 mstats
.numgc
, work
.nproc
, (t1
-t0
)/1000, (t2
-t1
)/1000, (t3
-t2
)/1000, (t4
-t3
)/1000,
2334 heap0
>>20, heap1
>>20, obj
,
2335 mstats
.nmalloc
, mstats
.nfree
,
2336 sweep
.nspan
, gcstats
.nbgsweep
, gcstats
.npausesweep
,
2337 stats
.nhandoff
, stats
.nhandoffcnt
,
2338 work
.markfor
->nsteal
, work
.markfor
->nstealcnt
,
2339 stats
.nprocyield
, stats
.nosyield
, stats
.nsleep
);
2340 gcstats
.nbgsweep
= gcstats
.npausesweep
= 0;
2342 runtime_printf("scan: %D bytes, %D objects, %D untyped, %D types from MSpan\n",
2343 gcstats
.nbytes
, gcstats
.obj
.cnt
, gcstats
.obj
.notype
, gcstats
.obj
.typelookup
);
2344 if(gcstats
.ptr
.cnt
!= 0)
2345 runtime_printf("avg ptrbufsize: %D (%D/%D)\n",
2346 gcstats
.ptr
.sum
/gcstats
.ptr
.cnt
, gcstats
.ptr
.sum
, gcstats
.ptr
.cnt
);
2347 if(gcstats
.obj
.cnt
!= 0)
2348 runtime_printf("avg nobj: %D (%D/%D)\n",
2349 gcstats
.obj
.sum
/gcstats
.obj
.cnt
, gcstats
.obj
.sum
, gcstats
.obj
.cnt
);
2350 runtime_printf("rescans: %D, %D bytes\n", gcstats
.rescan
, gcstats
.rescanbytes
);
2352 runtime_printf("instruction counts:\n");
2354 for(i
=0; i
<nelem(gcstats
.instr
); i
++) {
2355 runtime_printf("\t%d:\t%D\n", i
, gcstats
.instr
[i
]);
2356 ninstr
+= gcstats
.instr
[i
];
2358 runtime_printf("\ttotal:\t%D\n", ninstr
);
2360 runtime_printf("putempty: %D, getfull: %D\n", gcstats
.putempty
, gcstats
.getfull
);
2362 runtime_printf("markonly base lookup: bit %D word %D span %D\n", gcstats
.markonly
.foundbit
, gcstats
.markonly
.foundword
, gcstats
.markonly
.foundspan
);
2363 runtime_printf("flushptrbuf base lookup: bit %D word %D span %D\n", gcstats
.flushptrbuf
.foundbit
, gcstats
.flushptrbuf
.foundword
, gcstats
.flushptrbuf
.foundspan
);
2367 // We cache current runtime_mheap.allspans array in sweep.spans,
2368 // because the former can be resized and freed.
2369 // Otherwise we would need to take heap lock every time
2370 // we want to convert span index to span pointer.
2372 // Free the old cached array if necessary.
2373 if(sweep
.spans
&& sweep
.spans
!= runtime_mheap
.allspans
)
2374 runtime_SysFree(sweep
.spans
, sweep
.nspan
*sizeof(sweep
.spans
[0]), &mstats
.other_sys
);
2375 // Cache the current array.
2376 runtime_mheap
.sweepspans
= runtime_mheap
.allspans
;
2377 runtime_mheap
.sweepgen
+= 2;
2378 runtime_mheap
.sweepdone
= false;
2379 sweep
.spans
= runtime_mheap
.allspans
;
2380 sweep
.nspan
= runtime_mheap
.nspan
;
2383 // Temporary disable concurrent sweep, because we see failures on builders.
2384 if(ConcurrentSweep
&& !args
->eagersweep
) {
2385 runtime_lock(&gclock
);
2387 sweep
.g
= __go_go(bgsweep
, nil
);
2388 else if(sweep
.parked
) {
2389 sweep
.parked
= false;
2390 runtime_ready(sweep
.g
);
2392 runtime_unlock(&gclock
);
2394 // Sweep all spans eagerly.
2395 while(runtime_sweepone() != (uintptr
)-1)
2396 gcstats
.npausesweep
++;
2403 extern uintptr runtime_sizeof_C_MStats
2404 __asm__ (GOSYM_PREFIX
"runtime.Sizeof_C_MStats");
2406 void runtime_ReadMemStats(MStats
*)
2407 __asm__ (GOSYM_PREFIX
"runtime.ReadMemStats");
2410 runtime_ReadMemStats(MStats
*stats
)
2414 // Have to acquire worldsema to stop the world,
2415 // because stoptheworld can only be used by
2416 // one goroutine at a time, and there might be
2417 // a pending garbage collection already calling it.
2418 runtime_semacquire(&runtime_worldsema
, false);
2421 runtime_stoptheworld();
2422 runtime_updatememstats(nil
);
2423 // Size of the trailing by_size array differs between Go and C,
2424 // NumSizeClasses was changed, but we can not change Go struct because of backward compatibility.
2425 runtime_memmove(stats
, &mstats
, runtime_sizeof_C_MStats
);
2428 runtime_semrelease(&runtime_worldsema
);
2429 runtime_starttheworld();
2433 void runtime_debug_readGCStats(Slice
*)
2434 __asm__("runtime_debug.readGCStats");
2437 runtime_debug_readGCStats(Slice
*pauses
)
2442 // Calling code in runtime/debug should make the slice large enough.
2443 if((size_t)pauses
->cap
< nelem(mstats
.pause_ns
)+3)
2444 runtime_throw("runtime: short slice passed to readGCStats");
2446 // Pass back: pauses, last gc (absolute time), number of gc, total pause ns.
2447 p
= (uint64
*)pauses
->array
;
2448 runtime_lock(&runtime_mheap
);
2450 if(n
> nelem(mstats
.pause_ns
))
2451 n
= nelem(mstats
.pause_ns
);
2453 // The pause buffer is circular. The most recent pause is at
2454 // pause_ns[(numgc-1)%nelem(pause_ns)], and then backward
2455 // from there to go back farther in time. We deliver the times
2456 // most recent first (in p[0]).
2458 p
[i
] = mstats
.pause_ns
[(mstats
.numgc
-1-i
)%nelem(mstats
.pause_ns
)];
2460 p
[n
] = mstats
.last_gc
;
2461 p
[n
+1] = mstats
.numgc
;
2462 p
[n
+2] = mstats
.pause_total_ns
;
2463 runtime_unlock(&runtime_mheap
);
2464 pauses
->__count
= n
+3;
2468 runtime_setgcpercent(int32 in
) {
2471 runtime_lock(&runtime_mheap
);
2472 if(gcpercent
== GcpercentUnknown
)
2473 gcpercent
= readgogc();
2478 runtime_unlock(&runtime_mheap
);
2488 if(m
->helpgc
< 0 || m
->helpgc
>= MaxGcproc
)
2489 runtime_throw("gchelperstart: bad m->helpgc");
2490 if(runtime_xchg(&bufferList
[m
->helpgc
].busy
, 1))
2491 runtime_throw("gchelperstart: already busy");
2492 if(runtime_g() != m
->g0
)
2493 runtime_throw("gchelper not running on g0 stack");
2497 runfinq(void* dummy
__attribute__ ((unused
)))
2500 FinBlock
*fb
, *next
;
2505 // This function blocks for long periods of time, and because it is written in C
2506 // we have no liveness information. Zero everything so that uninitialized pointers
2507 // do not cause memory leaks.
2512 ef
.__type_descriptor
= nil
;
2515 // force flush to memory
2523 runtime_lock(&finlock
);
2527 runtime_fingwait
= true;
2528 runtime_g()->isbackground
= true;
2529 runtime_parkunlock(&finlock
, "finalizer wait");
2530 runtime_g()->isbackground
= false;
2533 runtime_unlock(&finlock
);
2535 runtime_racefingo();
2536 for(; fb
; fb
=next
) {
2538 for(i
=0; i
<(uint32
)fb
->cnt
; i
++) {
2543 fint
= ((const Type
**)f
->ft
->__in
.array
)[0];
2544 if(fint
->__code
== KindPtr
) {
2545 // direct use of pointer
2547 } else if(((const InterfaceType
*)fint
)->__methods
.__count
== 0) {
2548 // convert to empty interface
2549 ef
.__type_descriptor
= (const Type
*)f
->ot
;
2550 ef
.__object
= f
->arg
;
2553 // convert to interface with methods
2554 iface
.__methods
= __go_convert_interface_2((const Type
*)fint
,
2557 iface
.__object
= f
->arg
;
2558 if(iface
.__methods
== nil
)
2559 runtime_throw("invalid type conversion in runfinq");
2562 reflect_call(f
->ft
, f
->fn
, 0, 0, ¶m
, nil
);
2568 runtime_lock(&finlock
);
2571 runtime_unlock(&finlock
);
2574 // Zero everything that's dead, to avoid memory leaks.
2575 // See comment at top of function.
2580 ef
.__type_descriptor
= nil
;
2582 runtime_gc(1); // trigger another gc to clean up the finalized objects, if possible
2587 runtime_createfing(void)
2591 // Here we use gclock instead of finlock,
2592 // because newproc1 can allocate, which can cause on-demand span sweep,
2593 // which can queue finalizers, which would deadlock.
2594 runtime_lock(&gclock
);
2596 fing
= __go_go(runfinq
, nil
);
2597 runtime_unlock(&gclock
);
2601 runtime_wakefing(void)
2606 runtime_lock(&finlock
);
2607 if(runtime_fingwait
&& runtime_fingwake
) {
2608 runtime_fingwait
= false;
2609 runtime_fingwake
= false;
2612 runtime_unlock(&finlock
);
2617 runtime_marknogc(void *v
)
2619 uintptr
*b
, off
, shift
;
2621 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2622 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2623 shift
= off
% wordsPerBitmapWord
;
2624 *b
= (*b
& ~(bitAllocated
<<shift
)) | bitBlockBoundary
<<shift
;
2628 runtime_markscan(void *v
)
2630 uintptr
*b
, off
, shift
;
2632 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2633 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2634 shift
= off
% wordsPerBitmapWord
;
2635 *b
|= bitScan
<<shift
;
2638 // mark the block at v as freed.
2640 runtime_markfreed(void *v
)
2642 uintptr
*b
, off
, shift
;
2645 runtime_printf("markfreed %p\n", v
);
2647 if((byte
*)v
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2648 runtime_throw("markfreed: bad pointer");
2650 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2651 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2652 shift
= off
% wordsPerBitmapWord
;
2653 *b
= (*b
& ~(bitMask
<<shift
)) | (bitAllocated
<<shift
);
2656 // check that the block at v of size n is marked freed.
2658 runtime_checkfreed(void *v
, uintptr n
)
2660 uintptr
*b
, bits
, off
, shift
;
2662 if(!runtime_checking
)
2665 if((byte
*)v
+n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2666 return; // not allocated, so okay
2668 off
= (uintptr
*)v
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2669 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2670 shift
= off
% wordsPerBitmapWord
;
2673 if((bits
& bitAllocated
) != 0) {
2674 runtime_printf("checkfreed %p+%p: off=%p have=%p\n",
2675 v
, n
, off
, bits
& bitMask
);
2676 runtime_throw("checkfreed: not freed");
2680 // mark the span of memory at v as having n blocks of the given size.
2681 // if leftover is true, there is left over space at the end of the span.
2683 runtime_markspan(void *v
, uintptr size
, uintptr n
, bool leftover
)
2685 uintptr
*b
, *b0
, off
, shift
, i
, x
;
2688 if((byte
*)v
+size
*n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2689 runtime_throw("markspan: bad pointer");
2691 if(runtime_checking
) {
2692 // bits should be all zero at the start
2693 off
= (byte
*)v
+ size
- runtime_mheap
.arena_start
;
2694 b
= (uintptr
*)(runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
);
2695 for(i
= 0; i
< size
/PtrSize
/wordsPerBitmapWord
; i
++) {
2697 runtime_throw("markspan: span bits not zero");
2702 if(leftover
) // mark a boundary just past end of last block too
2707 for(; n
-- > 0; p
+= size
) {
2708 // Okay to use non-atomic ops here, because we control
2709 // the entire span, and each bitmap word has bits for only
2710 // one span, so no other goroutines are changing these
2712 off
= (uintptr
*)p
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2713 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2714 shift
= off
% wordsPerBitmapWord
;
2721 x
|= bitAllocated
<<shift
;
2726 // unmark the span of memory at v of length n bytes.
2728 runtime_unmarkspan(void *v
, uintptr n
)
2730 uintptr
*p
, *b
, off
;
2732 if((byte
*)v
+n
> (byte
*)runtime_mheap
.arena_used
|| (byte
*)v
< runtime_mheap
.arena_start
)
2733 runtime_throw("markspan: bad pointer");
2736 off
= p
- (uintptr
*)runtime_mheap
.arena_start
; // word offset
2737 if(off
% wordsPerBitmapWord
!= 0)
2738 runtime_throw("markspan: unaligned pointer");
2739 b
= (uintptr
*)runtime_mheap
.arena_start
- off
/wordsPerBitmapWord
- 1;
2741 if(n
%wordsPerBitmapWord
!= 0)
2742 runtime_throw("unmarkspan: unaligned length");
2743 // Okay to use non-atomic ops here, because we control
2744 // the entire span, and each bitmap word has bits for only
2745 // one span, so no other goroutines are changing these
2747 n
/= wordsPerBitmapWord
;
2753 runtime_MHeap_MapBits(MHeap
*h
)
2757 // Caller has added extra mappings to the arena.
2758 // Add extra mappings of bitmap words as needed.
2759 // We allocate extra bitmap pieces in chunks of bitmapChunk.
2765 n
= (h
->arena_used
- h
->arena_start
) / wordsPerBitmapWord
;
2766 n
= ROUND(n
, bitmapChunk
);
2767 n
= ROUND(n
, PageSize
);
2768 page_size
= getpagesize();
2769 n
= ROUND(n
, page_size
);
2770 if(h
->bitmap_mapped
>= n
)
2773 runtime_SysMap(h
->arena_start
- n
, n
- h
->bitmap_mapped
, h
->arena_reserved
, &mstats
.gc_sys
);
2774 h
->bitmap_mapped
= n
;