Golang从1.5开始引入了三色GC, 经过多次改进, 当前的1.9版本的GC停顿时间已经可以做到极短.
停顿时间的减少意味着"最大响应时间"的缩短, 这也让go更适合编写网络服务程序.
这篇文章将通过分析golang的源代码来讲解go中的三色GC的实现原理.
这个系列分析的golang源代码是Google官方的实现的1.9.2版本, 不适用于其他版本和gccgo等其他实现,
运行环境是Ubuntu 16.04 LTS 64bit.
首先会讲解基础概念, 然后讲解分配器, 再讲解收集器的实现.
基础概念
内存结构
go在程序启动时会分配一块虚拟内存地址是连续的内存, 结构如下:
这一块内存分为了3个区域, 在X64上大小分别是512M, 16G和512G, 它们的作用如下:
arena
arena区域就是我们通常说的heap, go从heap分配的内存都在这个区域中.
bitmap
bitmap区域用于表示arena区域中哪些地址保存了对象, 并且对象中哪些地址包含了指针.
bitmap区域中一个byte(8 bit)对应了arena区域中的四个指针大小的内存, 也就是2 bit对应一个指针大小的内存.
所以bitmap区域的大小是 512GB / 指针大小(8 byte) / 4 = 16GB.
bitmap区域中的一个byte对应arena区域的四个指针大小的内存的结构如下,
每一个指针大小的内存都会有两个bit分别表示是否应该继续扫描和是否包含指针:
bitmap中的byte和arena的对应关系从末尾开始, 也就是随着内存分配会向两边扩展:
spans
spans区域用于表示arena区中的某一页(Page)属于哪个span, 什么是span将在下面介绍.
spans区域中一个指针(8 byte)对应了arena区域中的一页(在go中一页=8KB).
所以spans的大小是 512GB / 页大小(8KB) * 指针大小(8 byte) = 512MB.
spans区域的一个指针对应arena区域的一页的结构如下, 和bitmap不一样的是对应关系会从开头开始:
什么时候从Heap分配对象
很多讲解go的文章和书籍中都提到过, go会自动确定哪些对象应该放在栈上, 哪些对象应该放在堆上.
简单的来说, 当一个对象的内容可能在生成该对象的函数结束后被访问, 那么这个对象就会分配在堆上.
在堆上分配对象的情况包括:
返回对象的指针
传递了对象的指针到其他函数
在闭包中使用了对象并且需要修改对象
使用new
在C语言中函数返回在栈上的对象的指针是非常危险的事情, 但在go中却是安全的, 因为这个对象会自动在堆上分配.
go决定是否使用堆分配对象的过程也叫"逃逸分析".
GC Bitmap
GC在标记时需要知道哪些地方包含了指针, 例如上面提到的bitmap区域涵盖了arena区域中的指针信息.
除此之外, GC还需要知道栈空间上哪些地方包含了指针,
因为栈空间不属于arena区域, 栈空间的指针信息将会在函数信息里面.
另外, GC在分配对象时也需要根据对象的类型设置bitmap区域, 来源的指针信息将会在类型信息里面.
总结起来go中有以下的GC Bitmap:
bitmap区域: 涵盖了arena区域, 使用2 bit表示一个指针大小的内存
函数信息: 涵盖了函数的栈空间, 使用1 bit表示一个指针大小的内存 (位于stackmap.bytedata)
类型信息: 在分配对象时会复制到bitmap区域, 使用1 bit表示一个指针大小的内存 (位于_type.gcdata)
Span
span是用于分配对象的区块, 下图是简单说明了Span的内部结构:
通常一个span包含了多个大小相同的元素, 一个元素会保存一个对象, 除非:
span用于保存大对象, 这种情况span只有一个元素
span用于保存极小对象且不包含指针的对象(tiny object), 这种情况span会用一个元素保存多个对象
span中有一个freeindex标记下一次分配对象时应该开始搜索的地址, 分配后freeindex会增加,
在freeindex之前的元素都是已分配的, 在freeindex之后的元素有可能已分配, 也有可能未分配.
span每次GC以后都可能会回收掉一些元素, allocBits用于标记哪些元素是已分配的, 哪些元素是未分配的.
使用freeindex + allocBits可以在分配时跳过已分配的元素, 把对象设置在未分配的元素中,
但因为每次都去访问allocBits效率会比较慢, span中有一个整数型的allocCache用于缓存freeindex开始的bitmap, 缓存的bit值与原值相反.
gcmarkBits用于在gc时标记哪些对象存活, 每次gc以后gcmarkBits会变为allocBits.
需要注意的是span结构本身的内存是从系统分配的, 上面提到的spans区域和bitmap区域都只是一个索引.
Span的类型
span根据大小可以分为67个类型, 如下:
// class bytes/obj bytes/span objects tail waste max waste
// 1 8 8192 1024 0 87.50%
// 2 16 8192 512 0 43.75%
// 3 32 8192 256 0 46.88%
// 4 48 8192 170 32 31.52%
// 5 64 8192 128 0 23.44%
// 6 80 8192 102 32 19.07%
// 7 96 8192 85 32 15.95%
// 8 112 8192 73 16 13.56%
// 9 128 8192 64 0 11.72%
// 10 144 8192 56 128 11.82%
// 11 160 8192 51 32 9.73%
// 12 176 8192 46 96 9.59%
// 13 192 8192 42 128 9.25%
// 14 208 8192 39 80 8.12%
// 15 224 8192 36 128 8.15%
// 16 240 8192 34 32 6.62%
// 17 256 8192 32 0 5.86%
// 18 288 8192 28 128 12.16%
// 19 320 8192 25 192 11.80%
// 20 352 8192 23 96 9.88%
// 21 384 8192 21 128 9.51%
// 22 416 8192 19 288 10.71%
// 23 448 8192 18 128 8.37%
// 24 480 8192 17 32 6.82%
// 25 512 8192 16 0 6.05%
// 26 576 8192 14 128 12.33%
// 27 640 8192 12 512 15.48%
// 28 704 8192 11 448 13.93%
// 29 768 8192 10 512 13.94%
// 30 896 8192 9 128 15.52%
// 31 1024 8192 8 0 12.40%
// 32 1152 8192 7 128 12.41%
// 33 1280 8192 6 512 15.55%
// 34 1408 16384 11 896 14.00%
// 35 1536 8192 5 512 14.00%
// 36 1792 16384 9 256 15.57%
// 37 2048 8192 4 0 12.45%
// 38 2304 16384 7 256 12.46%
// 39 2688 8192 3 128 15.59%
// 40 3072 24576 8 0 12.47%
// 41 3200 16384 5 384 6.22%
// 42 3456 24576 7 384 8.83%
// 43 4096 8192 2 0 15.60%
// 44 4864 24576 5 256 16.65%
// 45 5376 16384 3 256 10.92%
// 46 6144 24576 4 0 12.48%
// 47 6528 32768 5 128 6.23%
// 48 6784 40960 6 256 4.36%
// 49 6912 49152 7 768 3.37%
// 50 8192 8192 1 0 15.61%
// 51 9472 57344 6 512 14.28%
// 52 9728 49152 5 512 3.64%
// 53 10240 40960 4 0 4.99%
// 54 10880 32768 3 128 6.24%
// 55 12288 24576 2 0 11.45%
// 56 13568 40960 3 256 9.99%
// 57 14336 57344 4 0 5.35%
// 58 16384 16384 1 0 12.49%
// 59 18432 73728 4 0 11.11%
// 60 19072 57344 3 128 3.57%
// 61 20480 40960 2 0 6.87%
// 62 21760 65536 3 256 6.25%
// 63 24576 24576 1 0 11.45%
// 64 27264 81920 3 128 10.00%
// 65 28672 57344 2 0 4.91%
// 66 32768 32768 1 0 12.50%
以类型(class)为1的span为例,
span中的元素大小是8 byte, span本身占1页也就是8K, 一共可以保存1024个对象.
在分配对象时, 会根据对象的大小决定使用什么类型的span,
例如16 byte的对象会使用span 2, 17 byte的对象会使用span 3, 32 byte的对象会使用span 3.
从这个例子也可以看到, 分配17和32 byte的对象都会使用span 3, 也就是说部分大小的对象在分配时会浪费一定的空间.
有人可能会注意到, 上面最大的span的元素大小是32K, 那么分配超过32K的对象会在哪里分配呢?
超过32K的对象称为"大对象", 分配大对象时, 会直接从heap分配一个特殊的span,
这个特殊的span的类型(class)是0, 只包含了一个大对象, span的大小由对象的大小决定.
特殊的span加上的66个标准的span, 一共组成了67个span类型.
Span的位置
在前一篇中我提到了P是一个虚拟的资源, 同一时间只能有一个线程访问同一个P, 所以P中的数据不需要锁.
为了分配对象时有更好的性能, 各个P中都有span的缓存(也叫mcache), 缓存的结构如下:
各个P中按span类型的不同, 有67*2=134个span的缓存,
其中scan和noscan的区别在于,
如果对象包含了指针, 分配对象时会使用scan的span,
如果对象不包含指针, 分配对象时会使用noscan的span.
把span分为scan和noscan的意义在于,
GC扫描对象的时候对于noscan的span可以不去查看bitmap区域来标记子对象, 这样可以大幅提升标记的效率.
在分配对象时将会从以下的位置获取适合的span用于分配:
首先从P的缓存(mcache)获取, 如果有缓存的span并且未满则使用, 这个步骤不需要锁
然后从全局缓存(mcentral)获取, 如果获取成功则设置到P, 这个步骤需要锁
最后从mheap获取, 获取后设置到全局缓存, 这个步骤需要锁
在P中缓存span的做法跟CoreCLR中线程缓存分配上下文(Allocation Context)的做法相似,
都可以让分配对象时大部分时候不需要线程锁, 改进分配的性能.
分配对象的处理
分配对象的流程
go从堆分配对象时会调用newobject函数, 这个函数的流程大致如下:
首先会检查GC是否在工作中, 如果GC在工作中并且当前的G分配了一定大小的内存则需要协助GC做一定的工作,
这个机制叫GC Assist, 用于防止分配内存太快导致GC回收跟不上的情况发生.
之后会判断是小对象还是大对象, 如果是大对象则直接调用largeAlloc从堆中分配,
如果是小对象分3个阶段获取可用的span, 然后从span中分配对象:
首先从P的缓存(mcache)获取
然后从全局缓存(mcentral)获取, 全局缓存中有可用的span的列表
最后从mheap获取, mheap中也有span的自由列表, 如果都获取失败则从arena区域分配
这三个阶段的详细结构如下图:
数据类型的定义
分配对象涉及的数据类型包含:
p: 前一篇提到过, P是协程中的用于运行go代码的虚拟资源
m: 前一篇提到过, M目前代表系统线程
g: 前一篇提到过, G就是goroutine
mspan: 用于分配对象的区块
mcentral: 全局的mspan缓存, 一共有67*2=134个
mheap: 用于管理heap的对象, 全局只有一个
源代码分析
go从堆分配对象时会调用newobject函数, 先从这个函数看起:
1// implementation of new builtin
2// compiler (both frontend and SSA backend) knows the signature
3// of this function
4func newobject(typ *_type) unsafe.Pointer {
5 return mallocgc(typ.size, typ, true)
6}
7newobject调用了mallocgc函数:
8// Allocate an object of size bytes.
9// Small objects are allocated from the per-P cache's free lists.
10// Large objects (> 32 kB) are allocated straight from the heap.
11func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
12 if gcphase == _GCmarktermination {
13 throw("mallocgc called with gcphase == _GCmarktermination")
14 }
15 if size == 0 {
16 return unsafe.Pointer(&zerobase)
17 }
18 if debug.sbrk != 0 {
19 align := uintptr(16)
20 if typ != nil {
21 align = uintptr(typ.align)
22 }
23 return persistentalloc(size, align, &memstats.other_sys)
24 }
25 // 判断是否要辅助GC工作
26 // gcBlackenEnabled在GC的标记阶段会开启
27 // assistG is the G to charge for this allocation, or nil if
28 // GC is not currently active.
29 var assistG *g
30 if gcBlackenEnabled != 0 {
31 // Charge the current user G for this allocation.
32 assistG = getg()
33 if assistG.m.curg != nil {
34 assistG = assistG.m.curg
35 }
36 // Charge the allocation against the G. We'll account
37 // for internal fragmentation at the end of mallocgc.
38 assistG.gcAssistBytes -= int64(size)
39 // 会按分配的大小判断需要协助GC完成多少工作
40 // 具体的算法将在下面讲解收集器时说明
41 if assistG.gcAssistBytes < 0 {
42 // This G is in debt. Assist the GC to correct
43 // this before allocating. This must happen
44 // before disabling preemption.
45 gcAssistAlloc(assistG)
46 }
47 }
48 // 增加当前G对应的M的lock计数, 防止这个G被抢占
49 // Set mp.mallocing to keep from being preempted by GC.
50 mp := acquirem()
51 if mp.mallocing != 0 {
52 throw("malloc deadlock")
53 }
54 if mp.gsignal == getg() {
55 throw("malloc during signal")
56 }
57 mp.mallocing = 1
58 shouldhelpgc := false
59 dataSize := size
60 // 获取当前G对应的M对应的P的本地span缓存(mcache)
61 // 因为M在拥有P后会把P的mcache设到M中, 这里返回的是getg().m.mcache
62 c := gomcache()
63 var x unsafe.Pointer
64 noscan := typ == nil || typ.kind&kindNoPointers != 0
65 // 判断是否小对象, maxSmallSize当前的值是32K
66 if size <= maxSmallSize {
67 // 如果对象不包含指针, 并且对象的大小小于16 bytes, 可以做特殊处理
68 // 这里是针对非常小的对象的优化, 因为span的元素最小只能是8 byte, 如果对象更小那么很多空间都会被浪费掉
69 // 非常小的对象可以整合在"class 2 noscan"的元素(大小为16 byte)中
70 if noscan && size < maxTinySize {
71 // Tiny allocator.
72 //
73 // Tiny allocator combines several tiny allocation requests
74 // into a single memory block. The resulting memory block
75 // is freed when all subobjects are unreachable. The subobjects
76 // must be noscan (don't have pointers), this ensures that
77 // the amount of potentially wasted memory is bounded.
78 //
79 // Size of the memory block used for combining (maxTinySize) is tunable.
80 // Current setting is 16 bytes, which relates to 2x worst case memory
81 // wastage (when all but one subobjects are unreachable).
82 // 8 bytes would result in no wastage at all, but provides less
83 // opportunities for combining.
84 // 32 bytes provides more opportunities for combining,
85 // but can lead to 4x worst case wastage.
86 // The best case winning is 8x regardless of block size.
87 //
88 // Objects obtained from tiny allocator must not be freed explicitly.
89 // So when an object will be freed explicitly, we ensure that
90 // its size >= maxTinySize.
91 //
92 // SetFinalizer has a special case for objects potentially coming
93 // from tiny allocator, it such case it allows to set finalizers
94 // for an inner byte of a memory block.
95 //
96 // The main targets of tiny allocator are small strings and
97 // standalone escaping variables. On a json benchmark
98 // the allocator reduces number of allocations by ~12% and
99 // reduces heap size by ~20%.
100 off := c.tinyoffset
101 // Align tiny pointer for required (conservative) alignment.
102 if size&7 == 0 {
103 off = round(off, 8)
104 } else if size&3 == 0 {
105 off = round(off, 4)
106 } else if size&1 == 0 {
107 off = round(off, 2)
108 }
109 if off+size <= maxTinySize && c.tiny != 0 {
110 // The object fits into existing tiny block.
111 x = unsafe.Pointer(c.tiny + off)
112 c.tinyoffset = off + size
113 c.local_tinyallocs++
114 mp.mallocing = 0
115 releasem(mp)
116 return x
117 }
118 // Allocate a new maxTinySize block.
119 span := c.alloc[tinySpanClass]
120 v := nextFreeFast(span)
121 if v == 0 {
122 v, _, shouldhelpgc = c.nextFree(tinySpanClass)
123 }
124 x = unsafe.Pointer(v)
125 (*[2]uint64)(x)[0] = 0
126 (*[2]uint64)(x)[1] = 0
127 // See if we need to replace the existing tiny block with the new one
128 // based on amount of remaining free space.
129 if size < c.tinyoffset || c.tiny == 0 {
130 c.tiny = uintptr(x)
131 c.tinyoffset = size
132 }
133 size = maxTinySize
134 } else {
135 // 否则按普通的小对象分配
136 // 首先获取对象的大小应该使用哪个span类型
137 var sizeclass uint8
138 if size <= smallSizeMax-8 {
139 sizeclass = size_to_class8[(size+smallSizeDiv-1)/smallSizeDiv]
140 } else {
141 sizeclass = size_to_class128[(size-smallSizeMax+largeSizeDiv-1)/largeSizeDiv]
142 }
143 size = uintptr(class_to_size[sizeclass])
144 // 等于sizeclass * 2 + (noscan ? 1 : 0)
145 spc := makeSpanClass(sizeclass, noscan)
146 span := c.alloc[spc]
147 // 尝试快速的从这个span中分配
148 v := nextFreeFast(span)
149 if v == 0 {
150 // 分配失败, 可能需要从mcentral或者mheap中获取
151 // 如果从mcentral或者mheap获取了新的span, 则shouldhelpgc会等于true
152 // shouldhelpgc会等于true时会在下面判断是否要触发GC
153 v, span, shouldhelpgc = c.nextFree(spc)
154 }
155 x = unsafe.Pointer(v)
156 if needzero && span.needzero != 0 {
157 memclrNoHeapPointers(unsafe.Pointer(v), size)
158 }
159 }
160 } else {
161 // 大对象直接从mheap分配, 这里的s是一个特殊的span, 它的class是0
162 var s *mspan
163 shouldhelpgc = true
164 systemstack(func() {
165 s = largeAlloc(size, needzero, noscan)
166 })
167 s.freeindex = 1
168 s.allocCount = 1
169 x = unsafe.Pointer(s.base())
170 size = s.elemsize
171 }
172 // 设置arena对应的bitmap, 记录哪些位置包含了指针, GC会使用bitmap扫描所有可到达的对象
173 var scanSize uintptr
174 if !noscan {
175 // If allocating a defer+arg block, now that we've picked a malloc size
176 // large enough to hold everything, cut the "asked for" size down to
177 // just the defer header, so that the GC bitmap will record the arg block
178 // as containing nothing at all (as if it were unused space at the end of
179 // a malloc block caused by size rounding).
180 // The defer arg areas are scanned as part of scanstack.
181 if typ == deferType {
182 dataSize = unsafe.Sizeof(_defer{})
183 }
184 // 这个函数非常的长, 有兴趣的可以看
185 // https://github.com/golang/go/blob/go1.9.2/src/runtime/mbitmap.go#L855
186 // 虽然代码很长但是设置的内容跟上面说过的bitmap区域的结构一样
187 // 根据类型信息设置scan bit跟pointer bit, scan bit成立表示应该继续扫描, pointer bit成立表示该位置是指针
188 // 需要注意的地方有
189 // - 如果一个类型只有开头的地方包含指针, 例如[ptr, ptr, large non-pointer data]
190 // 那么后面的部分的scan bit将会为0, 这样可以大幅提升标记的效率
191 // - 第二个slot的scan bit用途比较特殊, 它并不用于标记是否继续scan, 而是标记checkmark
192 // 什么是checkmark
193 // - 因为go的并行GC比较复杂, 为了检查实现是否正确, go需要在有一个检查所有应该被标记的对象是否被标记的机制
194 // 这个机制就是checkmark, 在开启checkmark时go会在标记阶段的最后停止整个世界然后重新执行一次标记
195 // 上面的第二个slot的scan bit就是用于标记对象在checkmark标记中是否被标记的
196 // - 有的人可能会发现第二个slot要求对象最少有两个指针的大小, 那么只有一个指针的大小的对象呢?
197 // 只有一个指针的大小的对象可以分为两种情况
198 // 对象就是指针, 因为大小刚好是1个指针所以并不需要看bitmap区域, 这时第一个slot就是checkmark
199 // 对象不是指针, 因为有tiny alloc的机制, 不是指针且只有一个指针大小的对象会分配在两个指针的span中
200 // 这时候也不需要看bitmap区域, 所以和上面一样第一个slot就是checkmark
201 heapBitsSetType(uintptr(x), size, dataSize, typ)
202 if dataSize > typ.size {
203 // Array allocation. If there are any
204 // pointers, GC has to scan to the last
205 // element.
206 if typ.ptrdata != 0 {
207 scanSize = dataSize - typ.size + typ.ptrdata
208 }
209 } else {
210 scanSize = typ.ptrdata
211 }
212 c.local_scan += scanSize
213 }
214 // 内存屏障, 因为x86和x64的store不会乱序所以这里只是个针对编译器的屏障, 汇编中是ret
215 // Ensure that the stores above that initialize x to
216 // type-safe memory and set the heap bits occur before
217 // the caller can make x observable to the garbage
218 // collector. Otherwise, on weakly ordered machines,
219 // the garbage collector could follow a pointer to x,
220 // but see uninitialized memory or stale heap bits.
221 publicationBarrier()
222 // 如果当前在GC中, 需要立刻标记分配后的对象为"黑色", 防止它被回收
223 // Allocate black during GC.
224 // All slots hold nil so no scanning is needed.
225 // This may be racing with GC so do it atomically if there can be
226 // a race marking the bit.
227 if gcphase != _GCoff {
228 gcmarknewobject(uintptr(x), size, scanSize)
229 }
230 // Race Detector的处理(用于检测线程冲突问题)
231 if raceenabled {
232 racemalloc(x, size)
233 }
234 // Memory Sanitizer的处理(用于检测危险指针等内存问题)
235 if msanenabled {
236 msanmalloc(x, size)
237 }
238 // 重新允许当前的G被抢占
239 mp.mallocing = 0
240 releasem(mp)
241 // 除错记录
242 if debug.allocfreetrace != 0 {
243 tracealloc(x, size, typ)
244 }
245 // Profiler记录
246 if rate := MemProfileRate; rate > 0 {
247 if size < uintptr(rate) && int32(size) < c.next_sample {
248 c.next_sample -= int32(size)
249 } else {
250 mp := acquirem()
251 profilealloc(mp, x, size)
252 releasem(mp)
253 }
254 }
255 // gcAssistBytes减去"实际分配大小 - 要求分配大小", 调整到准确值
256 if assistG != nil {
257 // Account for internal fragmentation in the assist
258 // debt now that we know it.
259 assistG.gcAssistBytes -= int64(size - dataSize)
260 }
261 // 如果之前获取了新的span, 则判断是否需要后台启动GC
262 // 这里的判断逻辑(gcTrigger)会在下面详细说明
263 if shouldhelpgc {
264 if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
265 gcStart(gcBackgroundMode, t)
266 }
267 }
268 return x
269}
接下来看看如何从span里面分配对象, 首先会调用nextFreeFast尝试快速分配:
1// nextFreeFast returns the next free object if one is quickly available.
2// Otherwise it returns 0.
3func nextFreeFast(s *mspan) gclinkptr {
4 // 获取第一个非0的bit是第几个bit, 也就是哪个元素是未分配的
5 theBit := sys.Ctz64(s.allocCache) // Is there a free object in the allocCache?
6 // 找到未分配的元素
7 if theBit < 64 {
8 result := s.freeindex + uintptr(theBit)
9 // 要求索引值小于元素数量
10 if result < s.nelems {
11 // 下一个freeindex
12 freeidx := result + 1
13 // 可以被64整除时需要特殊处理(参考nextFree)
14 if freeidx%64 == 0 && freeidx != s.nelems {
15 return 0
16 }
17 // 更新freeindex和allocCache(高位都是0, 用尽以后会更新)
18 s.allocCache >>= uint(theBit + 1)
19 s.freeindex = freeidx
20 // 返回元素所在的地址
21 v := gclinkptr(result*s.elemsize + s.base())
22 // 添加已分配的元素计数
23 s.allocCount++
24 return v
25 }
26 }
27 return 0
28}
如果在freeindex后无法快速找到未分配的元素, 就需要调用nextFree做出更复杂的处理:
1// nextFree returns the next free object from the cached span if one is available.
2// Otherwise it refills the cache with a span with an available object and
3// returns that object along with a flag indicating that this was a heavy
4// weight allocation. If it is a heavy weight allocation the caller must
5// determine whether a new GC cycle needs to be started or if the GC is active
6// whether this goroutine needs to assist the GC.
7func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, shouldhelpgc bool) {
8 // 找到下一个freeindex和更新allocCache
9 s = c.alloc[spc]
10 shouldhelpgc = false
11 freeIndex := s.nextFreeIndex()
12 // 如果span里面所有元素都已分配, 则需要获取新的span
13 if freeIndex == s.nelems {
14 // The span is full.
15 if uintptr(s.allocCount) != s.nelems {
16 println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
17 throw("s.allocCount != s.nelems && freeIndex == s.nelems")
18 }
19 // 申请新的span
20 systemstack(func() {
21 c.refill(spc)
22 })
23 // 获取申请后的新的span, 并设置需要检查是否执行GC
24 shouldhelpgc = true
25 s = c.alloc[spc]
26 freeIndex = s.nextFreeIndex()
27 }
28 if freeIndex >= s.nelems {
29 throw("freeIndex is not valid")
30 }
31 // 返回元素所在的地址
32 v = gclinkptr(freeIndex*s.elemsize + s.base())
33 // 添加已分配的元素计数
34 s.allocCount++
35 if uintptr(s.allocCount) > s.nelems {
36 println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
37 throw("s.allocCount > s.nelems")
38 }
39 return
40}
如果mcache中指定类型的span已满, 就需要调用refill函数申请新的span:
1// Gets a span that has a free object in it and assigns it
2// to be the cached span for the given sizeclass. Returns this span.
3func (c *mcache) refill(spc spanClass) *mspan {
4 _g_ := getg()
5 // 防止G被抢占
6 _g_.m.locks++
7 // Return the current cached span to the central lists.
8 s := c.alloc[spc]
9 // 确保当前的span所有元素都已分配
10 if uintptr(s.allocCount) != s.nelems {
11 throw("refill of span with free space remaining")
12 }
13 // 设置span的incache属性, 除非是全局使用的空span(也就是mcache里面span指针的默认值)
14 if s != &emptymspan {
15 s.incache = false
16 }
17 // 向mcentral申请一个新的span
18 // Get a new cached span from the central lists.
19 s = mheap_.central[spc].mcentral.cacheSpan()
20 if s == nil {
21 throw("out of memory")
22 }
23 if uintptr(s.allocCount) == s.nelems {
24 throw("span has no free space")
25 }
26 // 设置新的span到mcache中
27 c.alloc[spc] = s
28 // 允许G被抢占
29 _g_.m.locks--
30 return s
31}
向mcentral申请一个新的span会通过cacheSpan函数:
mcentral首先尝试从内部的链表复用原有的span, 如果复用失败则向mheap申请.
1// Allocate a span to use in an MCache.
2func (c *mcentral) cacheSpan() *mspan {
3 // 让当前G协助一部分的sweep工作
4 // Deduct credit for this span allocation and sweep if necessary.
5 spanBytes := uintptr(class_to_allocnpages[c.spanclass.sizeclass()]) * _PageSize
6 deductSweepCredit(spanBytes, 0)
7 // 对mcentral上锁, 因为可能会有多个M(P)同时访问
8 lock(&c.lock)
9 traceDone := false
10 if trace.enabled {
11 traceGCSweepStart()
12 }
13 sg := mheap_.sweepgen
14retry:
15 // mcentral里面有两个span的链表
16 // - nonempty表示确定该span最少有一个未分配的元素
17 // - empty表示不确定该span最少有一个未分配的元素
18 // 这里优先查找nonempty的链表
19 // sweepgen每次GC都会增加2
20 // - sweepgen == 全局sweepgen, 表示span已经sweep过
21 // - sweepgen == 全局sweepgen-1, 表示span正在sweep
22 // - sweepgen == 全局sweepgen-2, 表示span等待sweep
23 var s *mspan
24 for s = c.nonempty.first; s != nil; s = s.next {
25 // 如果span等待sweep, 尝试原子修改sweepgen为全局sweepgen-1
26 if s.sweepgen == sg-2 && atomic.Cas(&s.sweepgen, sg-2, sg-1) {
27 // 修改成功则把span移到empty链表, sweep它然后跳到havespan
28 c.nonempty.remove(s)
29 c.empty.insertBack(s)
30 unlock(&c.lock)
31 s.sweep(true)
32 goto havespan
33 }
34 // 如果这个span正在被其他线程sweep, 就跳过
35 if s.sweepgen == sg-1 {
36 // the span is being swept by background sweeper, skip
37 continue
38 }
39 // span已经sweep过
40 // 因为nonempty链表中的span确定最少有一个未分配的元素, 这里可以直接使用它
41 // we have a nonempty span that does not require sweeping, allocate from it
42 c.nonempty.remove(s)
43 c.empty.insertBack(s)
44 unlock(&c.lock)
45 goto havespan
46 }
47 // 查找empty的链表
48 for s = c.empty.first; s != nil; s = s.next {
49 // 如果span等待sweep, 尝试原子修改sweepgen为全局sweepgen-1
50 if s.sweepgen == sg-2 && atomic.Cas(&s.sweepgen, sg-2, sg-1) {
51 // 把span放到empty链表的最后
52 // we have an empty span that requires sweeping,
53 // sweep it and see if we can free some space in it
54 c.empty.remove(s)
55 // swept spans are at the end of the list
56 c.empty.insertBack(s)
57 unlock(&c.lock)
58 // 尝试sweep
59 s.sweep(true)
60 // sweep以后还需要检测是否有未分配的对象, 如果有则可以使用它
61 freeIndex := s.nextFreeIndex()
62 if freeIndex != s.nelems {
63 s.freeindex = freeIndex
64 goto havespan
65 }
66 lock(&c.lock)
67 // the span is still empty after sweep
68 // it is already in the empty list, so just retry
69 goto retry
70 }
71 // 如果这个span正在被其他线程sweep, 就跳过
72 if s.sweepgen == sg-1 {
73 // the span is being swept by background sweeper, skip
74 continue
75 }
76 // 找不到有未分配对象的span
77 // already swept empty span,
78 // all subsequent ones must also be either swept or in process of sweeping
79 break
80 }
81 if trace.enabled {
82 traceGCSweepDone()
83 traceDone = true
84 }
85 unlock(&c.lock)
86 // 找不到有未分配对象的span, 需要从mheap分配
87 // 分配完成后加到empty链表中
88 // Replenish central list if empty.
89 s = c.grow()
90 if s == nil {
91 return nil
92 }
93 lock(&c.lock)
94 c.empty.insertBack(s)
95 unlock(&c.lock)
96 // At this point s is a non-empty span, queued at the end of the empty list,
97 // c is unlocked.
98havespan:
99 if trace.enabled && !traceDone {
100 traceGCSweepDone()
101 }
102 // 统计span中未分配的元素数量, 加到mcentral.nmalloc中
103 // 统计span中未分配的元素总大小, 加到memstats.heap_live中
104 cap := int32((s.npages << _PageShift) / s.elemsize)
105 n := cap - int32(s.allocCount)
106 if n == 0 || s.freeindex == s.nelems || uintptr(s.allocCount) == s.nelems {
107 throw("span has no free objects")
108 }
109 // Assume all objects from this span will be allocated in the
110 // mcache. If it gets uncached, we'll adjust this.
111 atomic.Xadd64(&c.nmalloc, int64(n))
112 usedBytes := uintptr(s.allocCount) * s.elemsize
113 atomic.Xadd64(&memstats.heap_live, int64(spanBytes)-int64(usedBytes))
114 // 跟踪处理
115 if trace.enabled {
116 // heap_live changed.
117 traceHeapAlloc()
118 }
119 // 如果当前在GC中, 因为heap_live改变了, 重新调整G辅助标记工作的值
120 // 详细请参考下面对revise函数的解析
121 if gcBlackenEnabled != 0 {
122 // heap_live changed.
123 gcController.revise()
124 }
125 // 设置span的incache属性, 表示span正在mcache中
126 s.incache = true
127 // 根据freeindex更新allocCache
128 freeByteBase := s.freeindex &^ (64 - 1)
129 whichByte := freeByteBase / 8
130 // Init alloc bits cache.
131 s.refillAllocCache(whichByte)
132 // Adjust the allocCache so that s.freeindex corresponds to the low bit in
133 // s.allocCache.
134 s.allocCache >>= s.freeindex % 64
135 return s
136}
版权申明:内容来源网络,版权归原创者所有。除非无法确认,我们都会标明作者及出处,如有侵权烦请告知,我们会立即删除并表示歉意。谢谢。
Golang语言社区
ID:GolangWeb
www.ByteEdu.Com
游戏服务器架构丨分布式技术丨大数据丨游戏算法学习