forked from tiancaiamao/go-internals
-
Notifications
You must be signed in to change notification settings - Fork 21
/
mgc0.c
2343 lines (2048 loc) · 60.7 KB
/
mgc0.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Garbage collector.
#include "runtime.h"
#include "arch_GOARCH.h"
#include "malloc.h"
#include "stack.h"
#include "mgc0.h"
#include "race.h"
#include "type.h"
#include "typekind.h"
#include "hashmap.h"
enum {
Debug = 0,
DebugMark = 0, // run second pass to check mark
CollectStats = 0,
// Four bits per word (see #defines below).
wordsPerBitmapWord = sizeof(void*)*8/4,
bitShift = sizeof(void*)*8/4,
handoffThreshold = 4,
IntermediateBufferCapacity = 64,
// Bits in type information
PRECISE = 1,
LOOP = 2,
PC_BITS = PRECISE | LOOP,
};
/* 每个机器字节(32位或64位)会对应4位的标记位.因此相当于64位系统中每个标记位图的字节对应16个堆字节.
字节中的位先根据类型,再根据堆中的分配位置进行打包,因此每个64位的标记位图从上到下依次包括:
16位特殊位,对应堆字节
16位垃圾回收的标记位
16字节的 无指针/块边界 的标记位
16位的 已分配 标记位
这样设计使得对一个类型的相应的位进行遍历很容易.
地址与它们的标记位图是分开存储和.以mheap.arena_start地址为边界,向上是实际的地址空间,向下是标记位图.
比如在64位系统中,计算某个地址的标记位的公式如下:
偏移 = 地址 - mheap.arena_start
标记位地址 = mheap.arena_start - 偏移/16 - 1
移位 = 偏移 % 16
标记位 = *标记位地址 >> 移位
*/
// Bits in per-word bitmap.
// #defines because enum might not be able to hold the values.
//
// Each word in the bitmap describes wordsPerBitmapWord words
// of heap memory. There are 4 bitmap bits dedicated to each heap word,
// so on a 64-bit system there is one bitmap word per 16 heap words.
// The bits in the word are packed together by type first, then by
// heap location, so each 64-bit bitmap word consists of, from top to bottom,
// the 16 bitSpecial bits for the corresponding heap words, then the 16 bitMarked bits,
// then the 16 bitNoPointers/bitBlockBoundary bits, then the 16 bitAllocated bits.
// This layout makes it easier to iterate over the bits of a given type.
//
// The bitmap starts at mheap.arena_start and extends *backward* from
// there. On a 64-bit system the off'th word in the arena is tracked by
// the off/16+1'th word before mheap.arena_start. (On a 32-bit system,
// the only difference is that the divisor is 8.)
//
// To pull out the bits corresponding to a given pointer p, we use:
//
// off = p - (uintptr*)mheap.arena_start; // word offset
// b = (uintptr*)mheap.arena_start - off/wordsPerBitmapWord - 1;
// shift = off % wordsPerBitmapWord
// bits = *b >> shift;
// /* then test bits & bitAllocated, bits & bitMarked, etc. */
//
#define bitAllocated ((uintptr)1<<(bitShift*0))
#define bitNoPointers ((uintptr)1<<(bitShift*1)) /* when bitAllocated is set */
#define bitMarked ((uintptr)1<<(bitShift*2)) /* when bitAllocated is set */
#define bitSpecial ((uintptr)1<<(bitShift*3)) /* when bitAllocated is set - has finalizer or being profiled */
#define bitBlockBoundary ((uintptr)1<<(bitShift*1)) /* when bitAllocated is NOT set */
#define bitMask (bitBlockBoundary | bitAllocated | bitMarked | bitSpecial)
// Holding worldsema grants an M the right to try to stop the world.
// The procedure is:
//
// runtime·semacquire(&runtime·worldsema);
// m->gcing = 1;
// runtime·stoptheworld();
//
// ... do stuff ...
//
// m->gcing = 0;
// runtime·semrelease(&runtime·worldsema);
// runtime·starttheworld();
//
uint32 runtime·worldsema = 1;
static int32 gctrace;
typedef struct Obj Obj;
struct Obj
{
byte *p; // data pointer
uintptr n; // size of data in bytes
/* 在文件type.h中,type结构体中有一个void *gc,是一个指向操作码的指针,gc过程中对不同的类型根据操作码进行gc操作
相当于内部有一个小的虚报机实现
*/
uintptr ti; // type info
};
// Workbuf的大小是N倍的内存页大小,放的是Obj的数组
typedef struct Workbuf Workbuf;
struct Workbuf
{
#define SIZE (2*PageSize-sizeof(LFNode)-sizeof(uintptr))
LFNode node; // must be first
uintptr nobj;
Obj obj[SIZE/sizeof(Obj) - 1];
uint8 _padding[SIZE%sizeof(Obj) + sizeof(Obj)];
#undef SIZE
};
typedef struct Finalizer Finalizer;
struct Finalizer
{
FuncVal *fn;
void *arg;
uintptr nret;
};
// 多个Finalizer组成一个FinBlock
typedef struct FinBlock FinBlock;
struct FinBlock
{
FinBlock *alllink;
FinBlock *next;
int32 cnt;
int32 cap;
Finalizer fin[1];
};
extern byte data[];
extern byte edata[];
extern byte bss[];
extern byte ebss[];
extern byte gcdata[];
extern byte gcbss[];
static G *fing;
static FinBlock *finq; // list of finalizers that are to be executed
static FinBlock *finc; // cache of free blocks
static FinBlock *allfin; // list of all blocks
static Lock finlock;
static int32 fingwait;
static void runfinq(void);
static Workbuf* getempty(Workbuf*);
static Workbuf* getfull(Workbuf*);
static void putempty(Workbuf*);
static Workbuf* handoff(Workbuf*);
static struct {
uint64 full; // lock-free list of full blocks
uint64 empty; // lock-free list of empty blocks
byte pad0[CacheLineSize]; // prevents false-sharing between full/empty and nproc/nwait //阻止full/empty和nproc/nwait之间伪共享
uint32 nproc;
volatile uint32 nwait;
volatile uint32 ndone;
volatile uint32 debugmarkdone;
Note alldone;
ParFor *markfor;
ParFor *sweepfor;
Lock;
byte *chunk;
uintptr nchunk;
Obj *roots;
uint32 nroot;
uint32 rootcap;
} work;
enum {
GC_DEFAULT_PTR = GC_NUM_INSTR,
GC_MAP_NEXT,
GC_CHAN,
GC_NUM_INSTR2
};
static struct {
struct {
uint64 sum;
uint64 cnt;
} ptr;
uint64 nbytes;
struct {
uint64 sum;
uint64 cnt;
uint64 notype;
uint64 typelookup;
} obj;
uint64 rescan;
uint64 rescanbytes;
uint64 instr[GC_NUM_INSTR2];
uint64 putempty;
uint64 getfull;
} gcstats;
// markonly marks an object. It returns true if the object
// has been marked by this function, false otherwise.
// This function isn't thread-safe and doesn't append the object to any buffer.
static bool
markonly(void *obj)
{
byte *p;
uintptr *bitp, bits, shift, x, xbits, off;
MSpan *s;
PageID k;
// Words outside the arena cannot be pointers.
if(obj < runtime·mheap->arena_start || obj >= runtime·mheap->arena_used)
return false;
// obj may be a pointer to a live object.
// Try to find the beginning of the object.
/* 由给定的指针找到对应的对象:先将地址取整到字边界
再在bitmap查找,看相应的位是否是分配且BlockBoundary
*/
// Round down to word boundary.
obj = (void*)((uintptr)obj & ~((uintptr)PtrSize-1));
// Find bits for this word.
off = (uintptr*)obj - (uintptr*)runtime·mheap->arena_start;
bitp = (uintptr*)runtime·mheap->arena_start - off/wordsPerBitmapWord - 1;
shift = off % wordsPerBitmapWord;
xbits = *bitp;
bits = xbits >> shift;
// Pointing at the beginning of a block?
if((bits & (bitAllocated|bitBlockBoundary)) != 0)
goto found;
// Otherwise consult span table to find beginning.
// (Manually inlined copy of MHeap_LookupMaybe.)
/* 下面这段代码跟MHeap_LookupMaybe功能一样的,就是给定一个指针,查找对应的MSpan */
k = (uintptr)obj>>PageShift;
x = k;
if(sizeof(void*) == 8)
x -= (uintptr)runtime·mheap->arena_start>>PageShift;
s = runtime·mheap->map[x];
if(s == nil || k < s->start || k - s->start >= s->npages || s->state != MSpanInUse)
return false;
/* 再由MSpan的对象尺寸类别,得到指针的对象边界 */
p = (byte*)((uintptr)s->start<<PageShift);
if(s->sizeclass == 0) {
obj = p;
} else {
if((byte*)obj >= (byte*)s->limit)
return false;
uintptr size = s->elemsize;
int32 i = ((byte*)obj - p)/size;
obj = p+i*size;
}
/* 得到对象头地址之后,重新加载位图中的标记位 */
// Now that we know the object header, reload bits.
off = (uintptr*)obj - (uintptr*)runtime·mheap->arena_start;
bitp = (uintptr*)runtime·mheap->arena_start - off/wordsPerBitmapWord - 1;
shift = off % wordsPerBitmapWord;
xbits = *bitp;
bits = xbits >> shift;
found:
// Now we have bits, bitp, and shift correct for
// obj pointing at the base of the object.
// Only care about allocated and not marked.
if((bits & (bitAllocated|bitMarked)) != bitAllocated)
return false;
/* 将Marked位置位以标记该对象 */
*bitp |= bitMarked<<shift;
// The object is now marked
return true;
}
// PtrTarget and BitTarget are structures used by intermediate buffers.
// The intermediate buffers hold GC data before it
// is moved/flushed to the work buffer (Workbuf).
// The size of an intermediate buffer is very small,
// such as 32 or 64 elements.
/* PtrTarget和BitTarget是临时缓存使用到的数据结构。
垃圾回收的数据在move/flush到工作缓存之前先放在临时缓存中
临时缓存大小很小,大概只有32或者64个。
*/
typedef struct PtrTarget PtrTarget;
struct PtrTarget
{
void *p;
uintptr ti;
};
typedef struct BitTarget BitTarget;
struct BitTarget
{
void *p;
uintptr ti;
uintptr *bitp, shift;
};
typedef struct BufferList BufferList;
struct BufferList
{
PtrTarget ptrtarget[IntermediateBufferCapacity];//大小为64个的数组
BitTarget bittarget[IntermediateBufferCapacity];
Obj obj[IntermediateBufferCapacity];
BufferList *next;
};
static BufferList *bufferList;
static Lock lock;
static Type *itabtype;
static void enqueue(Obj obj, Workbuf **_wbuf, Obj **_wp, uintptr *_nobj);
// flushptrbuf moves data from the PtrTarget buffer to the work buffer.
// The PtrTarget buffer contains blocks irrespective of whether the blocks have been marked or scanned,
// while the work buffer contains blocks which have been marked
// and are prepared to be scanned by the garbage collector.
/* PtrTarget缓存中包括的块与该块是否被标记或扫描过无关。
而工作缓存中包含的被标记过的块,并且是准备给垃圾收集器扫描的
*/
//
// _wp, _wbuf, _nobj are input/output parameters and are specifying the work buffer.
// bitbuf holds temporary data generated by this function.
//
// A simplified drawing explaining how the todo-list moves from a structure to another:
//
// scanblock
// (find pointers)
// Obj ------> PtrTarget (pointer targets)
// ↑ |
// | | flushptrbuf (1st part,
// | | find block start)
// | ↓
// `--------- BitTarget (pointer targets and the corresponding locations in bitmap)
// flushptrbuf
// (2nd part, mark and enqueue)
static void
flushptrbuf(PtrTarget *ptrbuf, PtrTarget **ptrbufpos, Obj **_wp, Workbuf **_wbuf, uintptr *_nobj, BitTarget *bitbuf)
{
byte *p, *arena_start, *obj;
uintptr size, *bitp, bits, shift, j, x, xbits, off, nobj, ti, n;
MSpan *s;
PageID k;
Obj *wp;
Workbuf *wbuf;
PtrTarget *ptrbuf_end;
BitTarget *bitbufpos, *bt;
arena_start = runtime·mheap->arena_start;
wp = *_wp;
wbuf = *_wbuf;
nobj = *_nobj;
ptrbuf_end = *ptrbufpos;
n = ptrbuf_end - ptrbuf;
*ptrbufpos = ptrbuf;
if(CollectStats) {
runtime·xadd64(&gcstats.ptr.sum, n);
runtime·xadd64(&gcstats.ptr.cnt, 1);
}
// If buffer is nearly full, get a new one.
if(wbuf == nil || nobj+n >= nelem(wbuf->obj)) {
if(wbuf != nil)
wbuf->nobj = nobj;
wbuf = getempty(wbuf);
wp = wbuf->obj;
nobj = 0;
if(n >= nelem(wbuf->obj))
runtime·throw("ptrbuf has to be smaller than WorkBuf");
}
// TODO(atom): This block is a branch of an if-then-else statement.
// The single-threaded branch may be added in a next CL.
{
// Multi-threaded version.
bitbufpos = bitbuf;
/* 接下来的这个while的代码是从PtrTarget到BitTarget
通过对象的指针找到相应的标记位,确定是否要将它放到bitbuff中
*/
while(ptrbuf < ptrbuf_end) {
obj = ptrbuf->p;
ti = ptrbuf->ti;
ptrbuf++;
// obj belongs to interval [mheap.arena_start, mheap.arena_used).
if(Debug > 1) {
if(obj < runtime·mheap->arena_start || obj >= runtime·mheap->arena_used)
runtime·throw("object is outside of mheap");
}
// obj may be a pointer to a live object.
// Try to find the beginning of the object.
/* 定位到object的头部 */
// Round down to word boundary.
if(((uintptr)obj & ((uintptr)PtrSize-1)) != 0) {
obj = (void*)((uintptr)obj & ~((uintptr)PtrSize-1));
ti = 0;
}
// Find bits for this word.找到这个字对应的位图的标记位
off = (uintptr*)obj - (uintptr*)arena_start;
bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
shift = off % wordsPerBitmapWord;
xbits = *bitp;
bits = xbits >> shift;
// Pointing at the beginning of a block? 看是否是分配且在块的头部,是的说明找到
if((bits & (bitAllocated|bitBlockBoundary)) != 0)
goto found;
ti = 0;
// Pointing just past the beginning?
// Scan backward a little to find a block boundary.直到找到块边界
for(j=shift; j-->0; ) {
if(((xbits>>j) & (bitAllocated|bitBlockBoundary)) != 0) {
obj = (byte*)obj - (shift-j)*PtrSize;
shift = j;
bits = xbits>>shift;
goto found;
}
}
/* 如果没有找到,则找地址所在的MSpan,然后通MSpan找地址所处的对象的边界
*/
// Otherwise consult span table to find beginning.
// (Manually inlined copy of MHeap_LookupMaybe.)
k = (uintptr)obj>>PageShift;
x = k;
if(sizeof(void*) == 8)
x -= (uintptr)arena_start>>PageShift;
s = runtime·mheap->map[x];
if(s == nil || k < s->start || k - s->start >= s->npages || s->state != MSpanInUse)
continue;
p = (byte*)((uintptr)s->start<<PageShift);
if(s->sizeclass == 0) {
obj = p;
} else {
if((byte*)obj >= (byte*)s->limit)
continue;
size = s->elemsize;
int32 i = ((byte*)obj - p)/size;
obj = p+i*size;
}
// Now that we know the object header, reload bits.找到对象边界后,重新加载标记位
off = (uintptr*)obj - (uintptr*)arena_start;
bitp = (uintptr*)arena_start - off/wordsPerBitmapWord - 1;
shift = off % wordsPerBitmapWord;
xbits = *bitp;
bits = xbits >> shift;
found:
// Now we have bits, bitp, and shift correct for
// obj pointing at the base of the object.
// Only care about allocated and not marked.
/* 找到了.确定它是标了分配位,没有标垃圾回收位的标记,则不用管
否则要加到bitbuff中
*/
if((bits & (bitAllocated|bitMarked)) != bitAllocated)
continue;
*bitbufpos++ = (BitTarget){obj, ti, bitp, shift};
}
/* 接下来的代码是将BitTarget进行标记,加上垃圾回收位
*/
runtime·lock(&lock);
for(bt=bitbuf; bt<bitbufpos; bt++){
xbits = *bt->bitp;
bits = xbits >> bt->shift;
if((bits & bitMarked) != 0)//已经有mark位的不用管
continue;
// Mark the block 否则要将块进行标记
*bt->bitp = xbits | (bitMarked << bt->shift);
// If object has no pointers, don't need to scan further.
/* 如果这个对象中不包含指针,则不会引用到其它对象.将它自身的垃圾回收位标上就可以了
否则,还要将从它出去的指针放到work缓存中递归地进行标记
*/
if((bits & bitNoPointers) != 0)
continue;
obj = bt->p;
// Ask span about size class.
// (Manually inlined copy of MHeap_Lookup.)
x = (uintptr)obj >> PageShift;
if(sizeof(void*) == 8)
x -= (uintptr)arena_start>>PageShift;
s = runtime·mheap->map[x];
PREFETCH(obj);
//放到work缓存中
*wp = (Obj){obj, s->elemsize, bt->ti};
wp++;
nobj++;
}
runtime·unlock(&lock);
// If another proc wants a pointer, give it some.
if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
wbuf->nobj = nobj;
wbuf = handoff(wbuf);
nobj = wbuf->nobj;
wp = wbuf->obj + nobj;
}
}
*_wp = wp;
*_wbuf = wbuf;
*_nobj = nobj;
}
static void
flushobjbuf(Obj *objbuf, Obj **objbufpos, Obj **_wp, Workbuf **_wbuf, uintptr *_nobj)
{
uintptr nobj, off;
Obj *wp, obj;
Workbuf *wbuf;
Obj *objbuf_end;
wp = *_wp;
wbuf = *_wbuf;
nobj = *_nobj;
objbuf_end = *objbufpos;
*objbufpos = objbuf;
while(objbuf < objbuf_end) {
obj = *objbuf++;
// Align obj.b to a word boundary.
off = (uintptr)obj.p & (PtrSize-1);
if(off != 0) {
obj.p += PtrSize - off;
obj.n -= PtrSize - off;
obj.ti = 0;
}
if(obj.p == nil || obj.n == 0)
continue;
// If buffer is full, get a new one.
if(wbuf == nil || nobj >= nelem(wbuf->obj)) {
if(wbuf != nil)
wbuf->nobj = nobj;
wbuf = getempty(wbuf);
wp = wbuf->obj;
nobj = 0;
}
*wp = obj;
wp++;
nobj++;
}
// If another proc wants a pointer, give it some.
if(work.nwait > 0 && nobj > handoffThreshold && work.full == 0) {
wbuf->nobj = nobj;
wbuf = handoff(wbuf);
nobj = wbuf->nobj;
wp = wbuf->obj + nobj;
}
*_wp = wp;
*_wbuf = wbuf;
*_nobj = nobj;
}
// Program that scans the whole block and treats every block element as a potential pointer
static uintptr defaultProg[2] = {PtrSize, GC_DEFAULT_PTR};
// Hashmap iterator program
static uintptr mapProg[2] = {0, GC_MAP_NEXT};
// Hchan program
static uintptr chanProg[2] = {0, GC_CHAN};
/* 这边的几个都是虚拟机的指令。这个Frame结构体其实是虚拟机的栈。
垃圾回收的工作由执行相应的操作码完成
*/
// Local variables of a program fragment or loop
typedef struct Frame Frame;
struct Frame {
uintptr count, elemsize, b;
uintptr *loop_or_ret;
};
// scanblock scans a block of n bytes starting at pointer b for references
// to other objects, scanning any it finds recursively until there are no
// unscanned objects left. Instead of using an explicit recursion, it keeps
// a work list in the Workbuf* structures and loops in the main function
// body. Keeping an explicit work list is easier on the stack allocator and
// more efficient.
//
// wbuf: current work buffer
// wp: storage for next queued pointer (write pointer)
// nobj: number of queued objects
static void
scanblock(Workbuf *wbuf, Obj *wp, uintptr nobj, bool keepworking)
{
byte *b, *arena_start, *arena_used;
uintptr n, i, end_b, elemsize, size, ti, objti, count, type;
uintptr *pc, precise_type, nominal_size;
uintptr *map_ret, mapkey_size, mapval_size, mapkey_ti, mapval_ti;
void *obj;
Type *t;
Slice *sliceptr;
Frame *stack_ptr, stack_top, stack[GC_STACK_CAPACITY+4];
BufferList *scanbuffers;
PtrTarget *ptrbuf, *ptrbuf_end, *ptrbufpos;
BitTarget *bitbuf;
Obj *objbuf, *objbuf_end, *objbufpos;
Eface *eface;
Iface *iface;
Hmap *hmap;
MapType *maptype;
bool didmark, mapkey_kind, mapval_kind;
struct hash_gciter map_iter;
struct hash_gciter_data d;
Hchan *chan;
ChanType *chantype;
if(sizeof(Workbuf) % PageSize != 0)
runtime·throw("scanblock: size of Workbuf is suboptimal");
// Memory arena parameters.
arena_start = runtime·mheap->arena_start;
arena_used = runtime·mheap->arena_used;
stack_ptr = stack+nelem(stack)-1;
precise_type = false;
nominal_size = 0;
// Allocate ptrbuf, bitbuf
/* 一个bufferList中有64个ptrTarget和64个bitTarget,还有64个Obj对象
bufferList是链起来的
*/
{
runtime·lock(&lock);
if(bufferList == nil) {
bufferList = runtime·SysAlloc(sizeof(*bufferList));
if(bufferList == nil)
runtime·throw("runtime: cannot allocate memory");
bufferList->next = nil;
}
scanbuffers = bufferList;
bufferList = bufferList->next;
ptrbuf = &scanbuffers->ptrtarget[0];
ptrbuf_end = &scanbuffers->ptrtarget[0] + nelem(scanbuffers->ptrtarget);
bitbuf = &scanbuffers->bittarget[0];
objbuf = &scanbuffers->obj[0];
objbuf_end = &scanbuffers->obj[0] + nelem(scanbuffers->obj);
runtime·unlock(&lock);
}
ptrbufpos = ptrbuf;
objbufpos = objbuf;
// (Silence the compiler)
map_ret = nil;
mapkey_size = mapval_size = 0;
mapkey_kind = mapval_kind = false;
mapkey_ti = mapval_ti = 0;
chan = nil;
chantype = nil;
goto next_block;
for(;;) {
// Each iteration scans the block b of length n, queueing pointers in
// the work buffer.
if(Debug > 1) {
runtime·printf("scanblock %p %D\n", b, (int64)n);
}
if(CollectStats) {
runtime·xadd64(&gcstats.nbytes, n);
runtime·xadd64(&gcstats.obj.sum, nobj);
runtime·xadd64(&gcstats.obj.cnt, 1);
}
if(ti != 0) {
/* ti是类型信息typeinfo的一个标记位
pc是类型信息中的虚拟机的代码段
*/
pc = (uintptr*)(ti & ~(uintptr)PC_BITS);
precise_type = (ti & PRECISE);
stack_top.elemsize = pc[0];
if(!precise_type)
nominal_size = pc[0];
if(ti & LOOP) {
stack_top.count = 0; // 0 means an infinite number of iterations
stack_top.loop_or_ret = pc+1;
} else {
stack_top.count = 1;
}
} else if(UseSpanType) {
if(CollectStats)
runtime·xadd64(&gcstats.obj.notype, 1);
type = runtime·gettype(b);//通过地址b,找到它的MSpan,然后看MSpan的type.compression
if(type != 0) {
if(CollectStats)
runtime·xadd64(&gcstats.obj.typelookup, 1);
/* type的低位是类型信息,通过type & (PtrSize-1)得到
type的高位是存的一个地址,该地址指向一个Type结构体。因为按字节对齐的,这是一种小的hack技巧哦~~
*/
t = (Type*)(type & ~(uintptr)(PtrSize-1));
switch(type & (PtrSize-1)) {
case TypeInfo_SingleObject:
pc = (uintptr*)t->gc;
precise_type = true; // type information about 'b' is precise
stack_top.count = 1;
stack_top.elemsize = pc[0];
break;
case TypeInfo_Array:
pc = (uintptr*)t->gc;
if(pc[0] == 0)
goto next_block;
precise_type = true; // type information about 'b' is precise
stack_top.count = 0; // 0 means an infinite number of iterations
stack_top.elemsize = pc[0];
stack_top.loop_or_ret = pc+1;
break;
case TypeInfo_Map:
hmap = (Hmap*)b;
maptype = (MapType*)t;
if(hash_gciter_init(hmap, &map_iter)) {
mapkey_size = maptype->key->size;
mapkey_kind = maptype->key->kind;
mapkey_ti = (uintptr)maptype->key->gc | PRECISE;
mapval_size = maptype->elem->size;
mapval_kind = maptype->elem->kind;
mapval_ti = (uintptr)maptype->elem->gc | PRECISE;
map_ret = 0;
pc = mapProg;
} else {
goto next_block;
}
break;
case TypeInfo_Chan:
chan = (Hchan*)b;
chantype = (ChanType*)t;
pc = chanProg;
break;
default:
runtime·throw("scanblock: invalid type");
return;
}
} else {
pc = defaultProg;
}
} else {
pc = defaultProg;
}
pc++;
stack_top.b = (uintptr)b;
end_b = (uintptr)b + n - PtrSize;
/* 下面这段开始是实现的一个虚拟机。垃圾回收的指令全部变成了操作码,相当于可执行文件的代码段
存放在typeinfo->gc中。每读一个操作码指令,执行对应的操作
*/
for(;;) {
if(CollectStats)
runtime·xadd64(&gcstats.instr[pc[0]], 1);
obj = nil;
objti = 0;
switch(pc[0]) {
case GC_PTR:
obj = *(void**)(stack_top.b + pc[1]);
objti = pc[2];
pc += 3;
break;
case GC_SLICE:
sliceptr = (Slice*)(stack_top.b + pc[1]);
if(sliceptr->cap != 0) {
obj = sliceptr->array;
objti = pc[2] | PRECISE | LOOP;
}
pc += 3;
break;
case GC_APTR:
obj = *(void**)(stack_top.b + pc[1]);
pc += 2;
break;
case GC_STRING:
obj = *(void**)(stack_top.b + pc[1]);
pc += 2;
break;
case GC_EFACE:
eface = (Eface*)(stack_top.b + pc[1]);
pc += 2;
if(eface->type != nil && (eface->data >= arena_start && eface->data < arena_used)) {
t = eface->type;
if(t->size <= sizeof(void*)) {
if((t->kind & KindNoPointers))
break;
obj = eface->data;
if((t->kind & ~KindNoPointers) == KindPtr)
objti = (uintptr)((PtrType*)t)->elem->gc;
} else {
obj = eface->data;
objti = (uintptr)t->gc;
}
}
break;
case GC_IFACE:
iface = (Iface*)(stack_top.b + pc[1]);
pc += 2;
if(iface->tab == nil)
break;
// iface->tab
if((void*)iface->tab >= arena_start && (void*)iface->tab < arena_used) {
*ptrbufpos++ = (PtrTarget){iface->tab, (uintptr)itabtype->gc};
if(ptrbufpos == ptrbuf_end)
flushptrbuf(ptrbuf, &ptrbufpos, &wp, &wbuf, &nobj, bitbuf);
}
// iface->data
if(iface->data >= arena_start && iface->data < arena_used) {
t = iface->tab->type;
if(t->size <= sizeof(void*)) {
if((t->kind & KindNoPointers))
break;
obj = iface->data;
if((t->kind & ~KindNoPointers) == KindPtr)
objti = (uintptr)((PtrType*)t)->elem->gc;
} else {
obj = iface->data;
objti = (uintptr)t->gc;
}
}
break;
case GC_DEFAULT_PTR:
while((i = stack_top.b) <= end_b) {
stack_top.b += PtrSize;
obj = *(byte**)i;
if(obj >= arena_start && obj < arena_used) {
*ptrbufpos++ = (PtrTarget){obj, 0};
if(ptrbufpos == ptrbuf_end)
flushptrbuf(ptrbuf, &ptrbufpos, &wp, &wbuf, &nobj, bitbuf);
}
}
goto next_block;
case GC_END:
if(--stack_top.count != 0) {
// Next iteration of a loop if possible.
elemsize = stack_top.elemsize;
stack_top.b += elemsize;
if(stack_top.b + elemsize <= end_b+PtrSize) {
pc = stack_top.loop_or_ret;
continue;
}
i = stack_top.b;
} else {
// Stack pop if possible.
if(stack_ptr+1 < stack+nelem(stack)) {
pc = stack_top.loop_or_ret;
stack_top = *(++stack_ptr);
continue;
}
i = (uintptr)b + nominal_size;
}
if(!precise_type) {
// Quickly scan [b+i,b+n) for possible pointers.
for(; i<=end_b; i+=PtrSize) {
if(*(byte**)i != nil) {
// Found a value that may be a pointer.
// Do a rescan of the entire block.
enqueue((Obj){b, n, 0}, &wbuf, &wp, &nobj);
if(CollectStats) {
runtime·xadd64(&gcstats.rescan, 1);
runtime·xadd64(&gcstats.rescanbytes, n);
}
break;
}
}
}
goto next_block;
case GC_ARRAY_START:
i = stack_top.b + pc[1];
count = pc[2];
elemsize = pc[3];
pc += 4;
// Stack push.
*stack_ptr-- = stack_top;
stack_top = (Frame){count, elemsize, i, pc};
continue;
case GC_ARRAY_NEXT:
if(--stack_top.count != 0) {
stack_top.b += stack_top.elemsize;
pc = stack_top.loop_or_ret;
} else {
// Stack pop.
stack_top = *(++stack_ptr);
pc += 1;
}
continue;
case GC_CALL:
// Stack push.
*stack_ptr-- = stack_top;
stack_top = (Frame){1, 0, stack_top.b + pc[1], pc+3 /*return address*/};
pc = (uintptr*)((byte*)pc + *(int32*)(pc+2)); // target of the CALL instruction
continue;
case GC_MAP_PTR:
hmap = *(Hmap**)(stack_top.b + pc[1]);
if(hmap == nil) {
pc += 3;
continue;
}
runtime·lock(&lock);
didmark = markonly(hmap);
runtime·unlock(&lock);
if(didmark) {
maptype = (MapType*)pc[2];
if(hash_gciter_init(hmap, &map_iter)) {
mapkey_size = maptype->key->size;
mapkey_kind = maptype->key->kind;
mapkey_ti = (uintptr)maptype->key->gc | PRECISE;
mapval_size = maptype->elem->size;
mapval_kind = maptype->elem->kind;
mapval_ti = (uintptr)maptype->elem->gc | PRECISE;
// Start mapProg.
map_ret = pc+3;
pc = mapProg+1;
} else {
pc += 3;
}
} else {
pc += 3;
}
continue;
case GC_MAP_NEXT:
// Add all keys and values to buffers, mark all subtables.
while(hash_gciter_next(&map_iter, &d)) {
// buffers: reserve space for 2 objects.
if(ptrbufpos+2 >= ptrbuf_end)
flushptrbuf(ptrbuf, &ptrbufpos, &wp, &wbuf, &nobj, bitbuf);
if(objbufpos+2 >= objbuf_end)
flushobjbuf(objbuf, &objbufpos, &wp, &wbuf, &nobj);
if(d.st != nil) {
runtime·lock(&lock);
markonly(d.st);
runtime·unlock(&lock);
}
if(d.key_data != nil) {
if(!(mapkey_kind & KindNoPointers) || d.indirectkey) {
if(!d.indirectkey)