Golang 从 1.5 开始引入了三色 GC, 经过多次改进, 当前的 1.9 版本的 GC 停顿时间已经可以做到极短.
停顿时间的减少意味着 “最大响应时间” 的缩短, 这也让 go 更适合编写网络服务程序.
这篇文章将通过分析 golang 的源代码来讲解 go 中的三色 GC 的实现原理.

这个系列分析的 golang 源代码是 Google 官方的实现的 1.9.2 版本, 不适用于其他版本和 gccgo 等其他实现,
运行环境是 Ubuntu 16.04 LTS 64bit.
首先会讲解基础概念, 然后讲解分配器, 再讲解收集器的实现.

内存结构

go 在程序启动时会分配一块虚拟内存地址是连续的内存, 结构如下:

【golang】GC详解 - SegmentFault 思否 - 图1

这一块内存分为了 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 分别表示是否应该继续扫描和是否包含指针:

【golang】GC详解 - SegmentFault 思否 - 图2

bitmap 中的 byte 和 arena 的对应关系从末尾开始, 也就是随着内存分配会向两边扩展:

【golang】GC详解 - SegmentFault 思否 - 图3

spans

spans 区域用于表示 arena 区中的某一页 (Page) 属于哪个 span, 什么是 span 将在下面介绍.
spans 区域中一个指针 (8 byte) 对应了 arena 区域中的一页(在 go 中一页 = 8KB).
所以 spans 的大小是 512GB / 页大小 (8KB) * 指针大小 (8 byte) = 512MB.

spans 区域的一个指针对应 arena 区域的一页的结构如下, 和 bitmap 不一样的是对应关系会从开头开始:

【golang】GC详解 - SegmentFault 思否 - 图4

什么时候从 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 的内部结构:

【golang】GC详解 - SegmentFault 思否 - 图5

通常一个 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 个类型, 如下:

  1. // class bytes/obj bytes/span objects tail waste max waste
  2. // 1 8 8192 1024 0 87.50%
  3. // 2 16 8192 512 0 43.75%
  4. // 3 32 8192 256 0 46.88%
  5. // 4 48 8192 170 32 31.52%
  6. // 5 64 8192 128 0 23.44%
  7. // 6 80 8192 102 32 19.07%
  8. // 7 96 8192 85 32 15.95%
  9. // 8 112 8192 73 16 13.56%
  10. // 9 128 8192 64 0 11.72%
  11. // 10 144 8192 56 128 11.82%
  12. // 11 160 8192 51 32 9.73%
  13. // 12 176 8192 46 96 9.59%
  14. // 13 192 8192 42 128 9.25%
  15. // 14 208 8192 39 80 8.12%
  16. // 15 224 8192 36 128 8.15%
  17. // 16 240 8192 34 32 6.62%
  18. // 17 256 8192 32 0 5.86%
  19. // 18 288 8192 28 128 12.16%
  20. // 19 320 8192 25 192 11.80%
  21. // 20 352 8192 23 96 9.88%
  22. // 21 384 8192 21 128 9.51%
  23. // 22 416 8192 19 288 10.71%
  24. // 23 448 8192 18 128 8.37%
  25. // 24 480 8192 17 32 6.82%
  26. // 25 512 8192 16 0 6.05%
  27. // 26 576 8192 14 128 12.33%
  28. // 27 640 8192 12 512 15.48%
  29. // 28 704 8192 11 448 13.93%
  30. // 29 768 8192 10 512 13.94%
  31. // 30 896 8192 9 128 15.52%
  32. // 31 1024 8192 8 0 12.40%
  33. // 32 1152 8192 7 128 12.41%
  34. // 33 1280 8192 6 512 15.55%
  35. // 34 1408 16384 11 896 14.00%
  36. // 35 1536 8192 5 512 14.00%
  37. // 36 1792 16384 9 256 15.57%
  38. // 37 2048 8192 4 0 12.45%
  39. // 38 2304 16384 7 256 12.46%
  40. // 39 2688 8192 3 128 15.59%
  41. // 40 3072 24576 8 0 12.47%
  42. // 41 3200 16384 5 384 6.22%
  43. // 42 3456 24576 7 384 8.83%
  44. // 43 4096 8192 2 0 15.60%
  45. // 44 4864 24576 5 256 16.65%
  46. // 45 5376 16384 3 256 10.92%
  47. // 46 6144 24576 4 0 12.48%
  48. // 47 6528 32768 5 128 6.23%
  49. // 48 6784 40960 6 256 4.36%
  50. // 49 6912 49152 7 768 3.37%
  51. // 50 8192 8192 1 0 15.61%
  52. // 51 9472 57344 6 512 14.28%
  53. // 52 9728 49152 5 512 3.64%
  54. // 53 10240 40960 4 0 4.99%
  55. // 54 10880 32768 3 128 6.24%
  56. // 55 12288 24576 2 0 11.45%
  57. // 56 13568 40960 3 256 9.99%
  58. // 57 14336 57344 4 0 5.35%
  59. // 58 16384 16384 1 0 12.49%
  60. // 59 18432 73728 4 0 11.11%
  61. // 60 19072 57344 3 128 3.57%
  62. // 61 20480 40960 2 0 6.87%
  63. // 62 21760 65536 3 256 6.25%
  64. // 63 24576 24576 1 0 11.45%
  65. // 64 27264 81920 3 128 10.00%
  66. // 65 28672 57344 2 0 4.91%
  67. // 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), 缓存的结构如下:

【golang】GC详解 - SegmentFault 思否 - 图6

各个 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 函数, 这个函数的流程大致如下:

【golang】GC详解 - SegmentFault 思否 - 图7

首先会检查 GC 是否在工作中, 如果 GC 在工作中并且当前的 G 分配了一定大小的内存则需要协助 GC 做一定的工作,
这个机制叫 GC Assist, 用于防止分配内存太快导致 GC 回收跟不上的情况发生.

之后会判断是小对象还是大对象, 如果是大对象则直接调用 largeAlloc 从堆中分配,
如果是小对象分 3 个阶段获取可用的 span, 然后从 span 中分配对象:

  • 首先从 P 的缓存 (mcache) 获取
  • 然后从全局缓存 (mcentral) 获取, 全局缓存中有可用的 span 的列表
  • 最后从 mheap 获取, mheap 中也有 span 的自由列表, 如果都获取失败则从 arena 区域分配

这三个阶段的详细结构如下图:

【golang】GC详解 - SegmentFault 思否 - 图8

数据类型的定义

分配对象涉及的数据类型包含:

p: 前一篇提到过, P 是协程中的用于运行 go 代码的虚拟资源
m: 前一篇提到过, M 目前代表系统线程
g: 前一篇提到过, G 就是 goroutine
mspan: 用于分配对象的区块
mcentral: 全局的 mspan 缓存, 一共有 67*2=134 个
mheap: 用于管理 heap 的对象, 全局只有一个

源代码分析

go 从堆分配对象时会调用newobject函数, 先从这个函数看起:

  1. func newobject(typ *_type) unsafe.Pointer {
  2. return mallocgc(typ.size, typ, true)
  3. }

newobject调用了mallocgc函数:

  1. // Allocate an object of size bytes.
  2. // Small objects are allocated from the per-P cache's free lists.
  3. // Large objects (> 32 kB) are allocated straight from the heap.
  4. func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
  5. if gcphase == _GCmarktermination {
  6. throw("mallocgc called with gcphase == _GCmarktermination")
  7. }
  8. if size == 0 {
  9. return unsafe.Pointer(&zerobase)
  10. }
  11. if debug.sbrk != 0 {
  12. align := uintptr(16)
  13. if typ != nil {
  14. align = uintptr(typ.align)
  15. }
  16. return persistentalloc(size, align, &memstats.other_sys)
  17. }
  18. // 判断是否要辅助GC工作
  19. // gcBlackenEnabled在GC的标记阶段会开启
  20. // assistG is the G to charge for this allocation, or nil if
  21. // GC is not currently active.
  22. var assistG *g
  23. if gcBlackenEnabled != 0 {
  24. // Charge the current user G for this allocation.
  25. assistG = getg()
  26. if assistG.m.curg != nil {
  27. assistG = assistG.m.curg
  28. }
  29. // Charge the allocation against the G. We'll account
  30. // for internal fragmentation at the end of mallocgc.
  31. assistG.gcAssistBytes -= int64(size)
  32. // 会按分配的大小判断需要协助GC完成多少工作
  33. // 具体的算法将在下面讲解收集器时说明
  34. if assistG.gcAssistBytes < 0 {
  35. // This G is in debt. Assist the GC to correct
  36. // this before allocating. This must happen
  37. // before disabling preemption.
  38. gcAssistAlloc(assistG)
  39. }
  40. }
  41. // 增加当前G对应的M的lock计数, 防止这个G被抢占
  42. // Set mp.mallocing to keep from being preempted by GC.
  43. mp := acquirem()
  44. if mp.mallocing != 0 {
  45. throw("malloc deadlock")
  46. }
  47. if mp.gsignal == getg() {
  48. throw("malloc during signal")
  49. }
  50. mp.mallocing = 1
  51. shouldhelpgc := false
  52. dataSize := size
  53. // 获取当前G对应的M对应的P的本地span缓存(mcache)
  54. // 因为M在拥有P后会把P的mcache设到M中, 这里返回的是getg().m.mcache
  55. c := gomcache()
  56. var x unsafe.Pointer
  57. noscan := typ == nil || typ.kind&kindNoPointers != 0
  58. // 判断是否小对象, maxSmallSize当前的值是32K
  59. if size <= maxSmallSize {
  60. // 如果对象不包含指针, 并且对象的大小小于16 bytes, 可以做特殊处理
  61. // 这里是针对非常小的对象的优化, 因为span的元素最小只能是8 byte, 如果对象更小那么很多空间都会被浪费掉
  62. // 非常小的对象可以整合在"class 2 noscan"的元素(大小为16 byte)中
  63. if noscan && size < maxTinySize {
  64. // Tiny allocator.
  65. //
  66. // Tiny allocator combines several tiny allocation requests
  67. // into a single memory block. The resulting memory block
  68. // is freed when all subobjects are unreachable. The subobjects
  69. // must be noscan (don't have pointers), this ensures that
  70. // the amount of potentially wasted memory is bounded.
  71. //
  72. // Size of the memory block used for combining (maxTinySize) is tunable.
  73. // Current setting is 16 bytes, which relates to 2x worst case memory
  74. // wastage (when all but one subobjects are unreachable).
  75. // 8 bytes would result in no wastage at all, but provides less
  76. // opportunities for combining.
  77. // 32 bytes provides more opportunities for combining,
  78. // but can lead to 4x worst case wastage.
  79. // The best case winning is 8x regardless of block size.
  80. //
  81. // Objects obtained from tiny allocator must not be freed explicitly.
  82. // So when an object will be freed explicitly, we ensure that
  83. // its size >= maxTinySize.
  84. //
  85. // SetFinalizer has a special case for objects potentially coming
  86. // from tiny allocator, it such case it allows to set finalizers
  87. // for an inner byte of a memory block.
  88. //
  89. // The main targets of tiny allocator are small strings and
  90. // standalone escaping variables. On a json benchmark
  91. // the allocator reduces number of allocations by ~12% and
  92. // reduces heap size by ~20%.
  93. off := c.tinyoffset
  94. // Align tiny pointer for required (conservative) alignment.
  95. if size&7 == 0 {
  96. off = round(off, 8)
  97. } else if size&3 == 0 {
  98. off = round(off, 4)
  99. } else if size&1 == 0 {
  100. off = round(off, 2)
  101. }
  102. if off+size <= maxTinySize && c.tiny != 0 {
  103. // The object fits into existing tiny block.
  104. x = unsafe.Pointer(c.tiny + off)
  105. c.tinyoffset = off + size
  106. c.local_tinyallocs++
  107. mp.mallocing = 0
  108. releasem(mp)
  109. return x
  110. }
  111. // Allocate a new maxTinySize block.
  112. span := c.alloc[tinySpanClass]
  113. v := nextFreeFast(span)
  114. if v == 0 {
  115. v, _, shouldhelpgc = c.nextFree(tinySpanClass)
  116. }
  117. x = unsafe.Pointer(v)
  118. (*[2]uint64)(x)[0] = 0
  119. (*[2]uint64)(x)[1] = 0
  120. // See if we need to replace the existing tiny block with the new one
  121. // based on amount of remaining free space.
  122. if size < c.tinyoffset || c.tiny == 0 {
  123. c.tiny = uintptr(x)
  124. c.tinyoffset = size
  125. }
  126. size = maxTinySize
  127. } else {
  128. // 否则按普通的小对象分配
  129. // 首先获取对象的大小应该使用哪个span类型
  130. var sizeclass uint8
  131. if size <= smallSizeMax-8 {
  132. sizeclass = size_to_class8[(size+smallSizeDiv-1)/smallSizeDiv]
  133. } else {
  134. sizeclass = size_to_class128[(size-smallSizeMax+largeSizeDiv-1)/largeSizeDiv]
  135. }
  136. size = uintptr(class_to_size[sizeclass])
  137. // 等于sizeclass * 2 + (noscan ? 1 : 0)
  138. spc := makeSpanClass(sizeclass, noscan)
  139. span := c.alloc[spc]
  140. // 尝试快速的从这个span中分配
  141. v := nextFreeFast(span)
  142. if v == 0 {
  143. // 分配失败, 可能需要从mcentral或者mheap中获取
  144. // 如果从mcentral或者mheap获取了新的span, 则shouldhelpgc会等于true
  145. // shouldhelpgc会等于true时会在下面判断是否要触发GC
  146. v, span, shouldhelpgc = c.nextFree(spc)
  147. }
  148. x = unsafe.Pointer(v)
  149. if needzero && span.needzero != 0 {
  150. memclrNoHeapPointers(unsafe.Pointer(v), size)
  151. }
  152. }
  153. } else {
  154. // 大对象直接从mheap分配, 这里的s是一个特殊的span, 它的class是0
  155. var s *mspan
  156. shouldhelpgc = true
  157. systemstack(func() {
  158. s = largeAlloc(size, needzero, noscan)
  159. })
  160. s.freeindex = 1
  161. s.allocCount = 1
  162. x = unsafe.Pointer(s.base())
  163. size = s.elemsize
  164. }
  165. // 设置arena对应的bitmap, 记录哪些位置包含了指针, GC会使用bitmap扫描所有可到达的对象
  166. var scanSize uintptr
  167. if !noscan {
  168. // If allocating a defer+arg block, now that we've picked a malloc size
  169. // large enough to hold everything, cut the "asked for" size down to
  170. // just the defer header, so that the GC bitmap will record the arg block
  171. // as containing nothing at all (as if it were unused space at the end of
  172. // a malloc block caused by size rounding).
  173. // The defer arg areas are scanned as part of scanstack.
  174. if typ == deferType {
  175. dataSize = unsafe.Sizeof(_defer{})
  176. }
  177. // 这个函数非常的长, 有兴趣的可以看
  178. // https://github.com/golang/go/blob/go1.9.2/src/runtime/mbitmap.go#L855
  179. // 虽然代码很长但是设置的内容跟上面说过的bitmap区域的结构一样
  180. // 根据类型信息设置scan bit跟pointer bit, scan bit成立表示应该继续扫描, pointer bit成立表示该位置是指针
  181. // 需要注意的地方有
  182. // - 如果一个类型只有开头的地方包含指针, 例如[ptr, ptr, large non-pointer data]
  183. // 那么后面的部分的scan bit将会为0, 这样可以大幅提升标记的效率
  184. // - 第二个slot的scan bit用途比较特殊, 它并不用于标记是否继续scan, 而是标记checkmark
  185. // 什么是checkmark
  186. // - 因为go的并行GC比较复杂, 为了检查实现是否正确, go需要在有一个检查所有应该被标记的对象是否被标记的机制
  187. // 这个机制就是checkmark, 在开启checkmark时go会在标记阶段的最后停止整个世界然后重新执行一次标记
  188. // 上面的第二个slot的scan bit就是用于标记对象在checkmark标记中是否被标记的
  189. // - 有的人可能会发现第二个slot要求对象最少有两个指针的大小, 那么只有一个指针的大小的对象呢?
  190. // 只有一个指针的大小的对象可以分为两种情况
  191. // 对象就是指针, 因为大小刚好是1个指针所以并不需要看bitmap区域, 这时第一个slot就是checkmark
  192. // 对象不是指针, 因为有tiny alloc的机制, 不是指针且只有一个指针大小的对象会分配在两个指针的span中
  193. // 这时候也不需要看bitmap区域, 所以和上面一样第一个slot就是checkmark
  194. heapBitsSetType(uintptr(x), size, dataSize, typ)
  195. if dataSize > typ.size {
  196. // Array allocation. If there are any
  197. // pointers, GC has to scan to the last
  198. // element.
  199. if typ.ptrdata != 0 {
  200. scanSize = dataSize - typ.size + typ.ptrdata
  201. }
  202. } else {
  203. scanSize = typ.ptrdata
  204. }
  205. c.local_scan += scanSize
  206. }
  207. // 内存屏障, 因为x86和x64的store不会乱序所以这里只是个针对编译器的屏障, 汇编中是ret
  208. // Ensure that the stores above that initialize x to
  209. // type-safe memory and set the heap bits occur before
  210. // the caller can make x observable to the garbage
  211. // collector. Otherwise, on weakly ordered machines,
  212. // the garbage collector could follow a pointer to x,
  213. // but see uninitialized memory or stale heap bits.
  214. publicationBarrier()
  215. // 如果当前在GC中, 需要立刻标记分配后的对象为"黑色", 防止它被回收
  216. // Allocate black during GC.
  217. // All slots hold nil so no scanning is needed.
  218. // This may be racing with GC so do it atomically if there can be
  219. // a race marking the bit.
  220. if gcphase != _GCoff {
  221. gcmarknewobject(uintptr(x), size, scanSize)
  222. }
  223. // Race Detector的处理(用于检测线程冲突问题)
  224. if raceenabled {
  225. racemalloc(x, size)
  226. }
  227. // Memory Sanitizer的处理(用于检测危险指针等内存问题)
  228. if msanenabled {
  229. msanmalloc(x, size)
  230. }
  231. // 重新允许当前的G被抢占
  232. mp.mallocing = 0
  233. releasem(mp)
  234. // 除错记录
  235. if debug.allocfreetrace != 0 {
  236. tracealloc(x, size, typ)
  237. }
  238. // Profiler记录
  239. if rate := MemProfileRate; rate > 0 {
  240. if size < uintptr(rate) && int32(size) < c.next_sample {
  241. c.next_sample -= int32(size)
  242. } else {
  243. mp := acquirem()
  244. profilealloc(mp, x, size)
  245. releasem(mp)
  246. }
  247. }
  248. // gcAssistBytes减去"实际分配大小 - 要求分配大小", 调整到准确值
  249. if assistG != nil {
  250. // Account for internal fragmentation in the assist
  251. // debt now that we know it.
  252. assistG.gcAssistBytes -= int64(size - dataSize)
  253. }
  254. // 如果之前获取了新的span, 则判断是否需要后台启动GC
  255. // 这里的判断逻辑(gcTrigger)会在下面详细说明
  256. if shouldhelpgc {
  257. if t := (gcTrigger{kind: gcTriggerHeap}); t.test() {
  258. gcStart(gcBackgroundMode, t)
  259. }
  260. }
  261. return x
  262. }

接下来看看如何从 span 里面分配对象, 首先会调用nextFreeFast尝试快速分配:

  1. func nextFreeFast(s *mspan) gclinkptr {
  2. theBit := sys.Ctz64(s.allocCache)
  3. if theBit < 64 {
  4. result := s.freeindex + uintptr(theBit)
  5. if result < s.nelems {
  6. freeidx := result + 1
  7. if freeidx%64 == 0 && freeidx != s.nelems {
  8. return 0
  9. }
  10. s.allocCache >>= uint(theBit + 1)
  11. s.freeindex = freeidx
  12. v := gclinkptr(result*s.elemsize + s.base())
  13. s.allocCount++
  14. return v
  15. }
  16. }
  17. return 0
  18. }

如果在 freeindex 后无法快速找到未分配的元素, 就需要调用nextFree做出更复杂的处理:

  1. func (c *mcache) nextFree(spc spanClass) (v gclinkptr, s *mspan, shouldhelpgc bool) {
  2. s = c.alloc[spc]
  3. shouldhelpgc = false
  4. freeIndex := s.nextFreeIndex()
  5. if freeIndex == s.nelems {
  6. if uintptr(s.allocCount) != s.nelems {
  7. println("runtime: s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
  8. throw("s.allocCount != s.nelems && freeIndex == s.nelems")
  9. }
  10. systemstack(func() {
  11. c.refill(spc)
  12. })
  13. shouldhelpgc = true
  14. s = c.alloc[spc]
  15. freeIndex = s.nextFreeIndex()
  16. }
  17. if freeIndex >= s.nelems {
  18. throw("freeIndex is not valid")
  19. }
  20. v = gclinkptr(freeIndex*s.elemsize + s.base())
  21. s.allocCount++
  22. if uintptr(s.allocCount) > s.nelems {
  23. println("s.allocCount=", s.allocCount, "s.nelems=", s.nelems)
  24. throw("s.allocCount > s.nelems")
  25. }
  26. return
  27. }

如果 mcache 中指定类型的 span 已满, 就需要调用refill函数申请新的 span:

  1. func (c *mcache) refill(spc spanClass) *mspan {
  2. _g_ := getg()
  3. _g_.m.locks++
  4. s := c.alloc[spc]
  5. if uintptr(s.allocCount) != s.nelems {
  6. throw("refill of span with free space remaining")
  7. }
  8. if s != &emptymspan {
  9. s.incache = false
  10. }
  11. s = mheap_.central[spc].mcentral.cacheSpan()
  12. if s == nil {
  13. throw("out of memory")
  14. }
  15. if uintptr(s.allocCount) == s.nelems {
  16. throw("span has no free space")
  17. }
  18. c.alloc[spc] = s
  19. _g_.m.locks--
  20. return s
  21. }

向 mcentral 申请一个新的 span 会通过cacheSpan函数:
mcentral 首先尝试从内部的链表复用原有的 span, 如果复用失败则向 mheap 申请.

  1. func (c *mcentral) cacheSpan() *mspan {
  2. spanBytes := uintptr(class_to_allocnpages[c.spanclass.sizeclass()]) * _PageSize
  3. deductSweepCredit(spanBytes, 0)
  4. lock(&c.lock)
  5. traceDone := false
  6. if trace.enabled {
  7. traceGCSweepStart()
  8. }
  9. sg := mheap_.sweepgen
  10. retry:
  11. var s *mspan
  12. for s = c.nonempty.first; s != nil; s = s.next {
  13. if s.sweepgen == sg-2 && atomic.Cas(&s.sweepgen, sg-2, sg-1) {
  14. c.nonempty.remove(s)
  15. c.empty.insertBack(s)
  16. unlock(&c.lock)
  17. s.sweep(true)
  18. goto havespan
  19. }
  20. if s.sweepgen == sg-1 {
  21. continue
  22. }
  23. c.nonempty.remove(s)
  24. c.empty.insertBack(s)
  25. unlock(&c.lock)
  26. goto havespan
  27. }
  28. for s = c.empty.first; s != nil; s = s.next {
  29. if s.sweepgen == sg-2 && atomic.Cas(&s.sweepgen, sg-2, sg-1) {
  30. c.empty.remove(s)
  31. c.empty.insertBack(s)
  32. unlock(&c.lock)
  33. s.sweep(true)
  34. freeIndex := s.nextFreeIndex()
  35. if freeIndex != s.nelems {
  36. s.freeindex = freeIndex
  37. goto havespan
  38. }
  39. lock(&c.lock)
  40. goto retry
  41. }
  42. if s.sweepgen == sg-1 {
  43. continue
  44. }
  45. break
  46. }
  47. if trace.enabled {
  48. traceGCSweepDone()
  49. traceDone = true
  50. }
  51. unlock(&c.lock)
  52. s = c.grow()
  53. if s == nil {
  54. return nil
  55. }
  56. lock(&c.lock)
  57. c.empty.insertBack(s)
  58. unlock(&c.lock)
  59. havespan:
  60. if trace.enabled && !traceDone {
  61. traceGCSweepDone()
  62. }
  63. cap := int32((s.npages << _PageShift) / s.elemsize)
  64. n := cap - int32(s.allocCount)
  65. if n == 0 || s.freeindex == s.nelems || uintptr(s.allocCount) == s.nelems {
  66. throw("span has no free objects")
  67. }
  68. atomic.Xadd64(&c.nmalloc, int64(n))
  69. usedBytes := uintptr(s.allocCount) * s.elemsize
  70. atomic.Xadd64(&memstats.heap_live, int64(spanBytes)-int64(usedBytes))
  71. if trace.enabled {
  72. traceHeapAlloc()
  73. }
  74. if gcBlackenEnabled != 0 {
  75. gcController.revise()
  76. }
  77. s.incache = true
  78. freeByteBase := s.freeindex &^ (64 - 1)
  79. whichByte := freeByteBase / 8
  80. s.refillAllocCache(whichByte)
  81. s.allocCache >>= s.freeindex % 64
  82. return s
  83. }

mcentral 向 mheap 申请一个新的 span 会使用grow函数:

  1. func (c *mcentral) grow() *mspan {
  2. npages := uintptr(class_to_allocnpages[c.spanclass.sizeclass()])
  3. size := uintptr(class_to_size[c.spanclass.sizeclass()])
  4. n := (npages << _PageShift) / size
  5. s := mheap_.alloc(npages, c.spanclass, false, true)
  6. if s == nil {
  7. return nil
  8. }
  9. p := s.base()
  10. s.limit = p + size*n
  11. heapBitsForSpan(s.base()).initSpan(s)
  12. return s
  13. }

mheap 分配 span 的函数是alloc:

  1. func (h *mheap) alloc(npage uintptr, spanclass spanClass, large bool, needzero bool) *mspan {
  2. var s *mspan
  3. systemstack(func() {
  4. s = h.alloc_m(npage, spanclass, large)
  5. })
  6. if s != nil {
  7. if needzero && s.needzero != 0 {
  8. memclrNoHeapPointers(unsafe.Pointer(s.base()), s.npages<<_PageShift)
  9. }
  10. s.needzero = 0
  11. }
  12. return s
  13. }

alloc 函数会在 g0 的栈空间中调用alloc_m函数:

  1. func (h *mheap) alloc_m(npage uintptr, spanclass spanClass, large bool) *mspan {
  2. _g_ := getg()
  3. if _g_ != _g_.m.g0 {
  4. throw("_mheap_alloc not on g0 stack")
  5. }
  6. lock(&h.lock)
  7. if h.sweepdone == 0 {
  8. if trace.enabled {
  9. traceGCSweepStart()
  10. }
  11. h.reclaim(npage)
  12. if trace.enabled {
  13. traceGCSweepDone()
  14. }
  15. }
  16. memstats.heap_scan += uint64(_g_.m.mcache.local_scan)
  17. _g_.m.mcache.local_scan = 0
  18. memstats.tinyallocs += uint64(_g_.m.mcache.local_tinyallocs)
  19. _g_.m.mcache.local_tinyallocs = 0
  20. s := h.allocSpanLocked(npage, &memstats.heap_inuse)
  21. if s != nil {
  22. atomic.Store(&s.sweepgen, h.sweepgen)
  23. h.sweepSpans[h.sweepgen/2%2].push(s)
  24. s.state = _MSpanInUse
  25. s.allocCount = 0
  26. s.spanclass = spanclass
  27. if sizeclass := spanclass.sizeclass(); sizeclass == 0 {
  28. s.elemsize = s.npages << _PageShift
  29. s.divShift = 0
  30. s.divMul = 0
  31. s.divShift2 = 0
  32. s.baseMask = 0
  33. } else {
  34. s.elemsize = uintptr(class_to_size[sizeclass])
  35. m := &class_to_divmagic[sizeclass]
  36. s.divShift = m.shift
  37. s.divMul = m.mul
  38. s.divShift2 = m.shift2
  39. s.baseMask = m.baseMask
  40. }
  41. h.pagesInUse += uint64(npage)
  42. if large {
  43. memstats.heap_objects++
  44. mheap_.largealloc += uint64(s.elemsize)
  45. mheap_.nlargealloc++
  46. atomic.Xadd64(&memstats.heap_live, int64(npage<<_PageShift))
  47. if s.npages < uintptr(len(h.busy)) {
  48. h.busy[s.npages].insertBack(s)
  49. } else {
  50. h.busylarge.insertBack(s)
  51. }
  52. }
  53. }
  54. if gcBlackenEnabled != 0 {
  55. gcController.revise()
  56. }
  57. if trace.enabled {
  58. traceHeapAlloc()
  59. }
  60. unlock(&h.lock)
  61. return s
  62. }

继续查看allocSpanLocked函数:

  1. func (h *mheap) allocSpanLocked(npage uintptr, stat *uint64) *mspan {
  2. var list *mSpanList
  3. var s *mspan
  4. for i := int(npage); i < len(h.free); i++ {
  5. list = &h.free[i]
  6. if !list.isEmpty() {
  7. s = list.first
  8. list.remove(s)
  9. goto HaveSpan
  10. }
  11. }
  12. s = h.allocLarge(npage)
  13. if s == nil {
  14. if !h.grow(npage) {
  15. return nil
  16. }
  17. s = h.allocLarge(npage)
  18. if s == nil {
  19. return nil
  20. }
  21. }
  22. HaveSpan:
  23. if s.state != _MSpanFree {
  24. throw("MHeap_AllocLocked - MSpan not free")
  25. }
  26. if s.npages < npage {
  27. throw("MHeap_AllocLocked - bad npages")
  28. }
  29. if s.npreleased > 0 {
  30. sysUsed(unsafe.Pointer(s.base()), s.npages<<_PageShift)
  31. memstats.heap_released -= uint64(s.npreleased << _PageShift)
  32. s.npreleased = 0
  33. }
  34. if s.npages > npage {
  35. t := (*mspan)(h.spanalloc.alloc())
  36. t.init(s.base()+npage<<_PageShift, s.npages-npage)
  37. s.npages = npage
  38. p := (t.base() - h.arena_start) >> _PageShift
  39. if p > 0 {
  40. h.spans[p-1] = s
  41. }
  42. h.spans[p] = t
  43. h.spans[p+t.npages-1] = t
  44. t.needzero = s.needzero
  45. s.state = _MSpanManual
  46. t.state = _MSpanManual
  47. h.freeSpanLocked(t, false, false, s.unusedsince)
  48. s.state = _MSpanFree
  49. }
  50. s.unusedsince = 0
  51. p := (s.base() - h.arena_start) >> _PageShift
  52. for n := uintptr(0); n < npage; n++ {
  53. h.spans[p+n] = s
  54. }
  55. *stat += uint64(npage << _PageShift)
  56. memstats.heap_idle -= uint64(npage << _PageShift)
  57. if s.inList() {
  58. throw("still in list")
  59. }
  60. return s
  61. }

继续查看allocLarge函数:

  1. func (h *mheap) allocLarge(npage uintptr) *mspan {
  2. return h.freelarge.remove(npage)
  3. }

freelarge 的类型是 mTreap, 调用remove函数会在树里面搜索一个至少 npage 且在树中的最小的 span 返回:

  1. func (root *mTreap) remove(npages uintptr) *mspan {
  2. t := root.treap
  3. for t != nil {
  4. if t.spanKey == nil {
  5. throw("treap node with nil spanKey found")
  6. }
  7. if t.npagesKey < npages {
  8. t = t.right
  9. } else if t.left != nil && t.left.npagesKey >= npages {
  10. t = t.left
  11. } else {
  12. result := t.spanKey
  13. root.removeNode(t)
  14. return result
  15. }
  16. }
  17. return nil
  18. }

向 arena 区域申请新 span 的函数是 mheap 类的grow函数:

  1. func (h *mheap) grow(npage uintptr) bool {
  2. npage = round(npage, (64<<10)/_PageSize)
  3. ask := npage << _PageShift
  4. if ask < _HeapAllocChunk {
  5. ask = _HeapAllocChunk
  6. }
  7. v := h.sysAlloc(ask)
  8. if v == nil {
  9. if ask > npage<<_PageShift {
  10. ask = npage << _PageShift
  11. v = h.sysAlloc(ask)
  12. }
  13. if v == nil {
  14. print("runtime: out of memory: cannot allocate ", ask, "-byte block (", memstats.heap_sys, " in use)n")
  15. return false
  16. }
  17. }
  18. s := (*mspan)(h.spanalloc.alloc())
  19. s.init(uintptr(v), ask>>_PageShift)
  20. p := (s.base() - h.arena_start) >> _PageShift
  21. for i := p; i < p+s.npages; i++ {
  22. h.spans[i] = s
  23. }
  24. atomic.Store(&s.sweepgen, h.sweepgen)
  25. s.state = _MSpanInUse
  26. h.pagesInUse += uint64(s.npages)
  27. h.freeSpanLocked(s, false, true, 0)
  28. return true
  29. }

继续查看 mheap 的sysAlloc函数:

  1. func (h *mheap) sysAlloc(n uintptr) unsafe.Pointer {
  2. const strandLimit = 16 << 20
  3. if n > h.arena_end-h.arena_alloc {
  4. p_size := round(n+_PageSize, 256<<20)
  5. new_end := h.arena_end + p_size
  6. if h.arena_end <= new_end && new_end-h.arena_start-1 <= _MaxMem {
  7. var reserved bool
  8. p := uintptr(sysReserve(unsafe.Pointer(h.arena_end), p_size, &reserved))
  9. if p == 0 {
  10. goto reservationFailed
  11. }
  12. if p == h.arena_end {
  13. h.arena_end = new_end
  14. h.arena_reserved = reserved
  15. } else if h.arena_start <= p && p+p_size-h.arena_start-1 <= _MaxMem && h.arena_end-h.arena_alloc < strandLimit {
  16. h.arena_end = p + p_size
  17. p = round(p, _PageSize)
  18. h.arena_alloc = p
  19. h.arena_reserved = reserved
  20. } else {
  21. stat := uint64(p_size)
  22. sysFree(unsafe.Pointer(p), p_size, &stat)
  23. }
  24. }
  25. }
  26. if n <= h.arena_end-h.arena_alloc {
  27. p := h.arena_alloc
  28. sysMap(unsafe.Pointer(p), n, h.arena_reserved, &memstats.heap_sys)
  29. h.arena_alloc += n
  30. if h.arena_alloc > h.arena_used {
  31. h.setArenaUsed(h.arena_alloc, true)
  32. }
  33. if p&(_PageSize-1) != 0 {
  34. throw("misrounded allocation in MHeap_SysAlloc")
  35. }
  36. return unsafe.Pointer(p)
  37. }
  38. reservationFailed:
  39. if sys.PtrSize != 4 {
  40. return nil
  41. }
  42. p_size := round(n, _PageSize) + _PageSize
  43. p := uintptr(sysAlloc(p_size, &memstats.heap_sys))
  44. if p == 0 {
  45. return nil
  46. }
  47. if p < h.arena_start || p+p_size-h.arena_start > _MaxMem {
  48. top := uint64(h.arena_start) + _MaxMem
  49. print("runtime: memory allocated by OS (", hex(p), ") not in usable range [", hex(h.arena_start), ",", hex(top), ")n")
  50. sysFree(unsafe.Pointer(p), p_size, &memstats.heap_sys)
  51. return nil
  52. }
  53. p += -p & (_PageSize - 1)
  54. if p+n > h.arena_used {
  55. h.setArenaUsed(p+n, true)
  56. }
  57. if p&(_PageSize-1) != 0 {
  58. throw("misrounded allocation in MHeap_SysAlloc")
  59. }
  60. return unsafe.Pointer(p)
  61. }

以上就是分配对象的完整流程了, 接下来分析 GC 标记和回收对象的处理.

回收对象的流程

GO 的 GC 是并行 GC, 也就是 GC 的大部分处理和普通的 go 代码是同时运行的, 这让 GO 的 GC 流程比较复杂.
首先 GC 有四个阶段, 它们分别是:

  • Sweep Termination: 对未清扫的 span 进行清扫, 只有上一轮的 GC 的清扫工作完成才可以开始新一轮的 GC
  • Mark: 扫描所有根对象, 和根对象可以到达的所有对象, 标记它们不被回收
  • Mark Termination: 完成标记工作, 重新扫描部分根对象 (要求 STW)
  • Sweep: 按标记结果清扫 span

下图是比较完整的 GC 流程, 并按颜色对这四个阶段进行了分类:

【golang】GC详解 - SegmentFault 思否 - 图9

在 GC 过程中会有两种后台任务 (G), 一种是标记用的后台任务, 一种是清扫用的后台任务.
标记用的后台任务会在需要时启动, 可以同时工作的后台任务数量大约是 P 的数量的 25%, 也就是 go 所讲的让 25% 的 cpu 用在 GC 上的根据.
清扫用的后台任务在程序启动时会启动一个, 进入清扫阶段时唤醒.

目前整个 GC 流程会进行两次 STW(Stop The World), 第一次是 Mark 阶段的开始, 第二次是 Mark Termination 阶段.
第一次 STW 会准备根对象的扫描, 启动写屏障 (Write Barrier) 和辅助 GC(mutator assist).
第二次 STW 会重新扫描部分根对象, 禁用写屏障 (Write Barrier) 和辅助 GC(mutator assist).
需要注意的是, 不是所有根对象的扫描都需要 STW, 例如扫描栈上的对象只需要停止拥有该栈的 G.
从 go 1.9 开始, 写屏障的实现使用了 Hybrid Write Barrier, 大幅减少了第二次 STW 的时间.

GC 的触发条件

GC 在满足一定条件后会被触发, 触发条件有以下几种:

  • gcTriggerAlways: 强制触发 GC
  • gcTriggerHeap: 当前分配的内存达到一定值就触发 GC
  • gcTriggerTime: 当一定时间没有执行过 GC 就触发 GC
  • gcTriggerCycle: 要求启动新一轮的 GC, 已启动则跳过, 手动触发 GC 的runtime.GC()会使用这个条件

触发条件的判断在 gctrigger 的test函数.
其中 gcTriggerHeap 和 gcTriggerTime 这两个条件是自然触发的, gcTriggerHeap 的判断代码如下:

  1. return memstats.heap_live >= memstats.gc_trigger

heap_live 的增加在上面对分配器的代码分析中可以看到, 当值达到 gc_trigger 就会触发 GC, 那么 gc_trigger 是如何决定的?
gc_trigger 的计算在gcSetTriggerRatio函数中, 公式是:

  1. trigger = uint64(float64(memstats.heap_marked) * (1 + triggerRatio))

当前标记存活的大小乘以 1 + 系数 triggerRatio, 就是下次出发 GC 需要的分配量.
triggerRatio 在每次 GC 后都会调整, 计算 triggerRatio 的函数是encCycle, 公式是:

  1. const triggerGain = 0.5
  2. // 目标Heap增长率, 默认是1.0
  3. goalGrowthRatio := float64(gcpercent) / 100
  4. // 实际Heap增长率, 等于总大小/存活大小-1
  5. actualGrowthRatio := float64(memstats.heap_live)/float64(memstats.heap_marked) - 1
  6. // GC标记阶段的使用时间(因为endCycle是在Mark Termination阶段调用的)
  7. assistDuration := nanotime() - c.markStartTime
  8. // GC标记阶段的CPU占用率, 目标值是0.25
  9. utilization := gcGoalUtilization
  10. if assistDuration > 0 {
  11. // assistTime是G辅助GC标记对象所使用的时间合计
  12. // (nanosecnds spent in mutator assists during this cycle)
  13. // 额外的CPU占用率 = 辅助GC标记对象的总时间 / (GC标记使用时间 * P的数量)
  14. utilization += float64(c.assistTime) / float64(assistDuration*int64(gomaxprocs))
  15. }
  16. // 触发系数偏移值 = 目标增长率 - 原触发系数 - CPU占用率 / 目标CPU占用率 * (实际增长率 - 原触发系数)
  17. // 参数的分析:
  18. // 实际增长率越大, 触发系数偏移值越小, 小于0时下次触发GC会提早
  19. // CPU占用率越大, 触发系数偏移值越小, 小于0时下次触发GC会提早
  20. // 原触发系数越大, 触发系数偏移值越小, 小于0时下次触发GC会提早
  21. triggerError := goalGrowthRatio - memstats.triggerRatio - utilization/gcGoalUtilization*(actualGrowthRatio-memstats.triggerRatio)
  22. // 根据偏移值调整触发系数, 每次只调整偏移值的一半(渐进式调整)
  23. triggerRatio := memstats.triggerRatio + triggerGain*triggerError

公式中的 “目标 Heap 增长率” 可以通过设置环境变量 “GOGC” 调整, 默认值是 100, 增加它的值可以减少 GC 的触发.
设置 “GOGC=off” 可以彻底关掉 GC.

gcTriggerTime 的判断代码如下:

  1. lastgc := int64(atomic.Load64(&memstats.last_gc_nanotime))
  2. return lastgc != 0 && t.now-lastgc > forcegcperiod

forcegcperiod 的定义是 2 分钟, 也就是 2 分钟内没有执行过 GC 就会强制触发.

三色的定义 (黑, 灰, 白)

我看过的对三色 GC 的 “三色” 这个概念解释的最好的文章就是这一篇了, 强烈建议先看这一篇中的讲解.
“三色” 的概念可以简单的理解为:

  • 黑色: 对象在这次 GC 中已标记, 且这个对象包含的子对象也已标记
  • 灰色: 对象在这次 GC 中已标记, 但这个对象包含的子对象未标记
  • 白色: 对象在这次 GC 中未标记

在 go 内部对象并没有保存颜色的属性, 三色只是对它们的状态的描述,
白色的对象在它所在的 span 的 gcmarkBits 中对应的 bit 为 0,
灰色的对象在它所在的 span 的 gcmarkBits 中对应的 bit 为 1, 并且对象在标记队列中,
黑色的对象在它所在的 span 的 gcmarkBits 中对应的 bit 为 1, 并且对象已经从标记队列中取出并处理.
gc 完成后, gcmarkBits 会移动到 allocBits 然后重新分配一个全部为 0 的 bitmap, 这样黑色的对象就变为了白色.

写屏障 (Write Barrier)

因为 go 支持并行 GC, GC 的扫描和 go 代码可以同时运行, 这样带来的问题是 GC 扫描的过程中 go 代码有可能改变了对象的依赖树,
例如开始扫描时发现根对象 A 和 B, B 拥有 C 的指针, GC 先扫描 A, 然后 B 把 C 的指针交给 A, GC 再扫描 B, 这时 C 就不会被扫描到.
为了避免这个问题, go 在 GC 的标记阶段会启用写屏障 (Write Barrier).

启用了写屏障 (Write Barrier) 后, 当 B 把 C 的指针交给 A 时, GC 会认为在这一轮的扫描中 C 的指针是存活的,
即使 A 可能会在稍后丢掉 C, 那么 C 就在下一轮回收.
写屏障只针对指针启用, 而且只在 GC 的标记阶段启用, 平时会直接把值写入到目标地址.

go 在 1.9 开始启用了混合写屏障 (Hybrid Write Barrier), 伪代码如下:

  1. writePointer(slot, ptr):
  2. shade(*slot)
  3. if any stack is grey:
  4. shade(ptr)
  5. *slot = ptr

混合写屏障会同时标记指针写入目标的 “原指针” 和 “新指针 “.

标记原指针的原因是, 其他运行中的线程有可能会同时把这个指针的值复制到寄存器或者栈上的本地变量,
因为复制指针到寄存器或者栈上的本地变量不会经过写屏障, 所以有可能会导致指针不被标记, 试想下面的情况:

  1. [go] b = obj
  2. [go] oldx = nil
  3. [gc] scan oldx...
  4. [go] oldx = b.x
  5. [go] b.x = ptr
  6. [gc] scan b...
  7. 如果写屏障不标记原值, 那么oldx就不会被扫描到.

标记新指针的原因是, 其他运行中的线程有可能会转移指针的位置, 试想下面的情况:

  1. [go] a = ptr
  2. [go] b = obj
  3. [gc] scan b...
  4. [go] b.x = a
  5. [go] a = nil
  6. [gc] scan a...
  7. 如果写屏障不标记新值, 那么ptr就不会被扫描到.

混合写屏障可以让 GC 在并行标记结束后不需要重新扫描各个 G 的堆栈, 可以减少 Mark Termination 中的 STW 时间.
除了写屏障外, 在 GC 的过程中所有新分配的对象都会立刻变为黑色, 在上面的 mallocgc 函数中可以看到.

辅助 GC(mutator assist)

为了防止 heap 增速太快, 在 GC 执行的过程中如果同时运行的 G 分配了内存, 那么这个 G 会被要求辅助 GC 做一部分的工作.
在 GC 的过程中同时运行的 G 称为 “mutator”, “mutator assist” 机制就是 G 辅助 GC 做一部分工作的机制.

辅助 GC 做的工作有两种类型, 一种是标记 (Mark), 另一种是清扫 (Sweep).
辅助标记的触发可以查看上面的 mallocgc 函数, 触发时 G 会帮助扫描 “工作量” 个对象, 工作量的计算公式是:

  1. debtBytes * assistWorkPerByte

意思是分配的大小乘以系数 assistWorkPerByte, assistWorkPerByte 的计算在函数revise中, 公式是:

  1. scanWorkExpected := int64(memstats.heap_scan) - c.scanWork
  2. if scanWorkExpected < 1000 {
  3. scanWorkExpected = 1000
  4. }
  5. heapDistance := int64(memstats.next_gc) - int64(atomic.Load64(&memstats.heap_live))
  6. if heapDistance <= 0 {
  7. heapDistance = 1
  8. }
  9. c.assistWorkPerByte = float64(scanWorkExpected) / float64(heapDistance)
  10. c.assistBytesPerWork = float64(heapDistance) / float64(scanWorkExpected)

和辅助标记不一样的是, 辅助清扫申请新 span 时才会检查, 而辅助标记是每次分配对象时都会检查.
辅助清扫的触发可以看上面的 cacheSpan 函数, 触发时 G 会帮助回收 “工作量” 页的对象, 工作量的计算公式是:

  1. spanBytes * sweepPagesPerByte // 不完全相同, 具体看deductSweepCredit函数

意思是分配的大小乘以系数 sweepPagesPerByte, sweepPagesPerByte 的计算在函数gcSetTriggerRatio中, 公式是:

  1. heapLiveBasis := atomic.Load64(&memstats.heap_live)
  2. heapDistance := int64(trigger) - int64(heapLiveBasis)
  3. heapDistance -= 1024 * 1024
  4. if heapDistance < _PageSize {
  5. heapDistance = _PageSize
  6. }
  7. pagesSwept := atomic.Load64(&mheap_.pagesSwept)
  8. sweepDistancePages := int64(mheap_.pagesInUse) - int64(pagesSwept)
  9. if sweepDistancePages <= 0 {
  10. mheap_.sweepPagesPerByte = 0
  11. } else {
  12. mheap_.sweepPagesPerByte = float64(sweepDistancePages) / float64(heapDistance)
  13. }

根对象

在 GC 的标记阶段首先需要标记的就是 “根对象”, 从根对象开始可到达的所有对象都会被认为是存活的.
根对象包含了全局变量, 各个 G 的栈上的变量等, GC 会先扫描根对象然后再扫描根对象可到达的所有对象.
扫描根对象包含了一系列的工作, 它们定义在[https://github.com/golang/go/blob/go1.9.2/src/runtime/mgcmark.go#L54]函数:

  • Fixed Roots: 特殊的扫描工作

    • fixedRootFinalizers: 扫描析构器队列
    • fixedRootFreeGStacks: 释放已中止的 G 的栈
  • Flush Cache Roots: 释放 mcache 中的所有 span, 要求 STW

  • Data Roots: 扫描可读写的全局变量

  • BSS Roots: 扫描只读的全局变量

  • Span Roots: 扫描各个 span 中特殊对象 (析构器列表)

  • Stack Roots: 扫描各个 G 的栈

标记阶段 (Mark) 会做其中的 “Fixed Roots”, “Data Roots”, “BSS Roots”, “Span Roots”, “Stack Roots”.
完成标记阶段 (Mark Termination) 会做其中的 “Fixed Roots”, “Flush Cache Roots”.

标记队列

GC 的标记阶段会使用 “标记队列” 来确定所有可从根对象到达的对象都已标记, 上面提到的 “灰色” 的对象就是在标记队列中的对象.
举例来说, 如果当前有[A, B, C]这三个根对象, 那么扫描根对象时就会把它们放到标记队列:

  1. work queue: [A, B, C]

后台标记任务从标记队列中取出 A, 如果 A 引用了 D, 则把 D 放入标记队列:

  1. work queue: [B, C, D]

后台标记任务从标记队列取出 B, 如果 B 也引用了 D, 这时因为 D 在 gcmarkBits 中对应的 bit 已经是 1 所以会跳过:

  1. work queue: [C, D]

如果并行运行的 go 代码分配了一个对象 E, 对象 E 会被立刻标记, 但不会进入标记队列 (因为确定 E 没有引用其他对象).
然后并行运行的 go 代码把对象 F 设置给对象 E 的成员, 写屏障会标记对象 F 然后把对象 F 加到运行队列:

  1. work queue: [C, D, F]

后台标记任务从标记队列取出 C, 如果 C 没有引用其他对象, 则不需要处理:

  1. work queue: [D, F]

后台标记任务从标记队列取出 D, 如果 D 引用了 X, 则把 X 放入标记队列:

  1. work queue: [F, X]

后台标记任务从标记队列取出 F, 如果 F 没有引用其他对象, 则不需要处理.
后台标记任务从标记队列取出 X, 如果 X 没有引用其他对象, 则不需要处理.
最后标记队列为空, 标记完成, 存活的对象有[A, B, C, D, E, F, X].

实际的状况会比上面介绍的状况稍微复杂一点.
标记队列会分为全局标记队列和各个 P 的本地标记队列, 这点和协程中的运行队列相似.
并且标记队列为空以后, 还需要停止整个世界并禁止写屏障, 然后再次检查是否为空.

源代码分析

go 触发 gc 会从gcStart函数开始:

  1. func gcStart(mode gcMode, trigger gcTrigger) {
  2. mp := acquirem()
  3. if gp := getg(); gp == mp.g0 || mp.locks > 1 || mp.preemptoff != "" {
  4. releasem(mp)
  5. return
  6. }
  7. releasem(mp)
  8. mp = nil
  9. for trigger.test() && gosweepone() != ^uintptr(0) {
  10. sweep.nbgsweep++
  11. }
  12. semacquire(&work.startSema)
  13. if !trigger.test() {
  14. semrelease(&work.startSema)
  15. return
  16. }
  17. work.userForced = trigger.kind == gcTriggerAlways || trigger.kind == gcTriggerCycle
  18. if mode == gcBackgroundMode {
  19. if debug.gcstoptheworld == 1 {
  20. mode = gcForceMode
  21. } else if debug.gcstoptheworld == 2 {
  22. mode = gcForceBlockMode
  23. }
  24. }
  25. semacquire(&worldsema)
  26. if trace.enabled {
  27. traceGCStart()
  28. }
  29. if mode == gcBackgroundMode {
  30. gcBgMarkStartWorkers()
  31. }
  32. gcResetMarkState()
  33. work.stwprocs, work.maxprocs = gcprocs(), gomaxprocs
  34. work.heap0 = atomic.Load64(&memstats.heap_live)
  35. work.pauseNS = 0
  36. work.mode = mode
  37. now := nanotime()
  38. work.tSweepTerm = now
  39. work.pauseStart = now
  40. systemstack(stopTheWorldWithSema)
  41. systemstack(func() {
  42. finishsweep_m()
  43. })
  44. clearpools()
  45. work.cycles++
  46. if mode == gcBackgroundMode {
  47. gcController.startCycle()
  48. work.heapGoal = memstats.next_gc
  49. setGCPhase(_GCmark)
  50. gcBgMarkPrepare()
  51. gcMarkRootPrepare()
  52. gcMarkTinyAllocs()
  53. atomic.Store(&gcBlackenEnabled, 1)
  54. gcController.markStartTime = now
  55. systemstack(startTheWorldWithSema)
  56. now = nanotime()
  57. work.pauseNS += now - work.pauseStart
  58. work.tMark = now
  59. } else {
  60. t := nanotime()
  61. work.tMark, work.tMarkTerm = t, t
  62. work.heapGoal = work.heap0
  63. gcMarkTermination(memstats.triggerRatio)
  64. }
  65. semrelease(&work.startSema)
  66. }

接下来一个个分析 gcStart 调用的函数, 建议配合上面的 “回收对象的流程” 中的图理解.

函数gcBgMarkStartWorkers用于启动后台标记任务, 先分别对每个 P 启动一个:

  1. func gcBgMarkStartWorkers() {
  2. for _, p := range &allp {
  3. if p == nil || p.status == _Pdead {
  4. break
  5. }
  6. if p.gcBgMarkWorker == 0 {
  7. go gcBgMarkWorker(p)
  8. notetsleepg(&work.bgMarkReady, -1)
  9. noteclear(&work.bgMarkReady)
  10. }
  11. }
  12. }

这里虽然为每个 P 启动了一个后台标记任务, 但是可以同时工作的只有 25%, 这个逻辑在协程 M 获取 G 时调用的findRunnableGCWorker中:

  1. func (c *gcControllerState) findRunnableGCWorker(_p_ *p) *g {
  2. if gcBlackenEnabled == 0 {
  3. throw("gcControllerState.findRunnable: blackening not enabled")
  4. }
  5. if _p_.gcBgMarkWorker == 0 {
  6. return nil
  7. }
  8. if !gcMarkWorkAvailable(_p_) {
  9. return nil
  10. }
  11. decIfPositive := func(ptr *int64) bool {
  12. if *ptr > 0 {
  13. if atomic.Xaddint64(ptr, -1) >= 0 {
  14. return true
  15. }
  16. atomic.Xaddint64(ptr, +1)
  17. }
  18. return false
  19. }
  20. if decIfPositive(&c.dedicatedMarkWorkersNeeded) {
  21. _p_.gcMarkWorkerMode = gcMarkWorkerDedicatedMode
  22. } else {
  23. if !decIfPositive(&c.fractionalMarkWorkersNeeded) {
  24. return nil
  25. }
  26. const gcForcePreemptNS = 0
  27. now := nanotime() - gcController.markStartTime
  28. then := now + gcForcePreemptNS
  29. timeUsed := c.fractionalMarkTime + gcForcePreemptNS
  30. if then > 0 && float64(timeUsed)/float64(then) > c.fractionalUtilizationGoal {
  31. atomic.Xaddint64(&c.fractionalMarkWorkersNeeded, +1)
  32. return nil
  33. }
  34. _p_.gcMarkWorkerMode = gcMarkWorkerFractionalMode
  35. }
  36. gp := _p_.gcBgMarkWorker.ptr()
  37. casgstatus(gp, _Gwaiting, _Grunnable)
  38. if trace.enabled {
  39. traceGoUnpark(gp, 0)
  40. }
  41. return gp
  42. }

gcResetMarkState函数会重置标记相关的状态:

  1. func gcResetMarkState() {
  2. lock(&allglock)
  3. for _, gp := range allgs {
  4. gp.gcscandone = false
  5. gp.gcscanvalid = false
  6. gp.gcAssistBytes = 0
  7. }
  8. unlock(&allglock)
  9. work.bytesMarked = 0
  10. work.initialHeapLive = atomic.Load64(&memstats.heap_live)
  11. work.markrootDone = false
  12. }

stopTheWorldWithSema函数会停止整个世界, 这个函数必须在 g0 中运行:

  1. func stopTheWorldWithSema() {
  2. _g_ := getg()
  3. if _g_.m.locks > 0 {
  4. throw("stopTheWorld: holding locks")
  5. }
  6. lock(&sched.lock)
  7. sched.stopwait = gomaxprocs
  8. atomic.Store(&sched.gcwaiting, 1)
  9. preemptall()
  10. _g_.m.p.ptr().status = _Pgcstop
  11. sched.stopwait--
  12. for i := 0; i < int(gomaxprocs); i++ {
  13. p := allp[i]
  14. s := p.status
  15. if s == _Psyscall && atomic.Cas(&p.status, s, _Pgcstop) {
  16. if trace.enabled {
  17. traceGoSysBlock(p)
  18. traceProcStop(p)
  19. }
  20. p.syscalltick++
  21. sched.stopwait--
  22. }
  23. }
  24. for {
  25. p := pidleget()
  26. if p == nil {
  27. break
  28. }
  29. p.status = _Pgcstop
  30. sched.stopwait--
  31. }
  32. wait := sched.stopwait > 0
  33. unlock(&sched.lock)
  34. if wait {
  35. for {
  36. if notetsleep(&sched.stopnote, 100*1000) {
  37. noteclear(&sched.stopnote)
  38. break
  39. }
  40. preemptall()
  41. }
  42. }
  43. bad := ""
  44. if sched.stopwait != 0 {
  45. bad = "stopTheWorld: not stopped (stopwait != 0)"
  46. } else {
  47. for i := 0; i < int(gomaxprocs); i++ {
  48. p := allp[i]
  49. if p.status != _Pgcstop {
  50. bad = "stopTheWorld: not stopped (status != _Pgcstop)"
  51. }
  52. }
  53. }
  54. if atomic.Load(&freezing) != 0 {
  55. lock(&deadlock)
  56. lock(&deadlock)
  57. }
  58. if bad != "" {
  59. throw(bad)
  60. }
  61. }

finishsweep_m函数会清扫上一轮 GC 未清扫的 span, 确保上一轮 GC 已完成:

  1. func finishsweep_m() {
  2. for sweepone() != ^uintptr(0) {
  3. sweep.npausesweep++
  4. }
  5. nextMarkBitArenaEpoch()
  6. }

clearpools函数会清理 sched.sudogcache 和 sched.deferpool, 让它们的内存可以被回收:

  1. func clearpools() {
  2. if poolcleanup != nil {
  3. poolcleanup()
  4. }
  5. lock(&sched.sudoglock)
  6. var sg, sgnext *sudog
  7. for sg = sched.sudogcache; sg != nil; sg = sgnext {
  8. sgnext = sg.next
  9. sg.next = nil
  10. }
  11. sched.sudogcache = nil
  12. unlock(&sched.sudoglock)
  13. lock(&sched.deferlock)
  14. for i := range sched.deferpool {
  15. var d, dlink *_defer
  16. for d = sched.deferpool[i]; d != nil; d = dlink {
  17. dlink = d.link
  18. d.link = nil
  19. }
  20. sched.deferpool[i] = nil
  21. }
  22. unlock(&sched.deferlock)
  23. }

startCycle标记开始了新一轮的 GC:

  1. func (c *gcControllerState) startCycle() {
  2. c.scanWork = 0
  3. c.bgScanCredit = 0
  4. c.assistTime = 0
  5. c.dedicatedMarkTime = 0
  6. c.fractionalMarkTime = 0
  7. c.idleMarkTime = 0
  8. if memstats.gc_trigger <= heapminimum {
  9. memstats.heap_marked = uint64(float64(memstats.gc_trigger) / (1 + memstats.triggerRatio))
  10. }
  11. memstats.next_gc = memstats.heap_marked + memstats.heap_marked*uint64(gcpercent)/100
  12. if gcpercent < 0 {
  13. memstats.next_gc = ^uint64(0)
  14. }
  15. if memstats.next_gc < memstats.heap_live+1024*1024 {
  16. memstats.next_gc = memstats.heap_live + 1024*1024
  17. }
  18. totalUtilizationGoal := float64(gomaxprocs) * gcGoalUtilization
  19. c.dedicatedMarkWorkersNeeded = int64(totalUtilizationGoal)
  20. c.fractionalUtilizationGoal = totalUtilizationGoal - float64(c.dedicatedMarkWorkersNeeded)
  21. if c.fractionalUtilizationGoal > 0 {
  22. c.fractionalMarkWorkersNeeded = 1
  23. } else {
  24. c.fractionalMarkWorkersNeeded = 0
  25. }
  26. for _, p := range &allp {
  27. if p == nil {
  28. break
  29. }
  30. p.gcAssistTime = 0
  31. }
  32. c.revise()
  33. if debug.gcpacertrace > 0 {
  34. print("pacer: assist ratio=", c.assistWorkPerByte,
  35. " (scan ", memstats.heap_scan>>20, " MB in ",
  36. work.initialHeapLive>>20, "->",
  37. memstats.next_gc>>20, " MB)",
  38. " workers=", c.dedicatedMarkWorkersNeeded,
  39. "+", c.fractionalMarkWorkersNeeded, "n")
  40. }
  41. }

setGCPhase函数会修改表示当前 GC 阶段的全局变量和是否开启写屏障的全局变量:

  1. func setGCPhase(x uint32) {
  2. atomic.Store(&gcphase, x)
  3. writeBarrier.needed = gcphase == _GCmark || gcphase == _GCmarktermination
  4. writeBarrier.enabled = writeBarrier.needed || writeBarrier.cgo
  5. }

gcBgMarkPrepare函数会重置后台标记任务的计数:

  1. func gcBgMarkPrepare() {
  2. work.nproc = ^uint32(0)
  3. work.nwait = ^uint32(0)
  4. }

gcMarkRootPrepare函数会计算扫描根对象的任务数量:

  1. func gcMarkRootPrepare() {
  2. if gcphase == _GCmarktermination {
  3. work.nFlushCacheRoots = int(gomaxprocs)
  4. } else {
  5. work.nFlushCacheRoots = 0
  6. }
  7. nBlocks := func(bytes uintptr) int {
  8. return int((bytes + rootBlockBytes - 1) / rootBlockBytes)
  9. }
  10. work.nDataRoots = 0
  11. work.nBSSRoots = 0
  12. if !work.markrootDone {
  13. for _, datap := range activeModules() {
  14. nDataRoots := nBlocks(datap.edata - datap.data)
  15. if nDataRoots > work.nDataRoots {
  16. work.nDataRoots = nDataRoots
  17. }
  18. }
  19. for _, datap := range activeModules() {
  20. nBSSRoots := nBlocks(datap.ebss - datap.bss)
  21. if nBSSRoots > work.nBSSRoots {
  22. work.nBSSRoots = nBSSRoots
  23. }
  24. }
  25. }
  26. if !work.markrootDone {
  27. work.nSpanRoots = mheap_.sweepSpans[mheap_.sweepgen/2%2].numBlocks()
  28. work.nStackRoots = int(atomic.Loaduintptr(&allglen))
  29. } else {
  30. work.nSpanRoots = 0
  31. work.nStackRoots = 0
  32. if debug.gcrescanstacks > 0 {
  33. work.nStackRoots = int(atomic.Loaduintptr(&allglen))
  34. }
  35. }
  36. work.markrootNext = 0
  37. work.markrootJobs = uint32(fixedRootCount + work.nFlushCacheRoots + work.nDataRoots + work.nBSSRoots + work.nSpanRoots + work.nStackRoots)
  38. }

gcMarkTinyAllocs函数会标记所有 tiny alloc 等待合并的对象:

  1. func gcMarkTinyAllocs() {
  2. for _, p := range &allp {
  3. if p == nil || p.status == _Pdead {
  4. break
  5. }
  6. c := p.mcache
  7. if c == nil || c.tiny == 0 {
  8. continue
  9. }
  10. _, hbits, span, objIndex := heapBitsForObject(c.tiny, 0, 0)
  11. gcw := &p.gcw
  12. greyobject(c.tiny, 0, 0, hbits, span, gcw, objIndex)
  13. if gcBlackenPromptly {
  14. gcw.dispose()
  15. }
  16. }
  17. }

startTheWorldWithSema函数会重新启动世界:

  1. func startTheWorldWithSema() {
  2. _g_ := getg()
  3. _g_.m.locks++
  4. gp := netpoll(false)
  5. injectglist(gp)
  6. add := needaddgcproc()
  7. lock(&sched.lock)
  8. procs := gomaxprocs
  9. if newprocs != 0 {
  10. procs = newprocs
  11. newprocs = 0
  12. }
  13. p1 := procresize(procs)
  14. sched.gcwaiting = 0
  15. if sched.sysmonwait != 0 {
  16. sched.sysmonwait = 0
  17. notewakeup(&sched.sysmonnote)
  18. }
  19. unlock(&sched.lock)
  20. for p1 != nil {
  21. p := p1
  22. p1 = p1.link.ptr()
  23. if p.m != 0 {
  24. mp := p.m.ptr()
  25. p.m = 0
  26. if mp.nextp != 0 {
  27. throw("startTheWorld: inconsistent mp->nextp")
  28. }
  29. mp.nextp.set(p)
  30. notewakeup(&mp.park)
  31. } else {
  32. newm(nil, p)
  33. add = false
  34. }
  35. }
  36. if atomic.Load(&sched.npidle) != 0 && atomic.Load(&sched.nmspinning) == 0 {
  37. wakep()
  38. }
  39. if add {
  40. newm(mhelpgc, nil)
  41. }
  42. _g_.m.locks--
  43. if _g_.m.locks == 0 && _g_.preempt {
  44. _g_.stackguard0 = stackPreempt
  45. }
  46. }

重启世界后各个 M 会重新开始调度, 调度时会优先使用上面提到的 findRunnableGCWorker 函数查找任务, 之后就有大约 25% 的 P 运行后台标记任务.
后台标记任务的函数是gcBgMarkWorker:

  1. func gcBgMarkWorker(_p_ *p) {
  2. gp := getg()
  3. type parkInfo struct {
  4. m muintptr
  5. attach puintptr
  6. }
  7. gp.m.preemptoff = "GC worker init"
  8. park := new(parkInfo)
  9. gp.m.preemptoff = ""
  10. park.m.set(acquirem())
  11. park.attach.set(_p_)
  12. notewakeup(&work.bgMarkReady)
  13. for {
  14. gopark(func(g *g, parkp unsafe.Pointer) bool {
  15. park := (*parkInfo)(parkp)
  16. releasem(park.m.ptr())
  17. if park.attach != 0 {
  18. p := park.attach.ptr()
  19. park.attach.set(nil)
  20. if !p.gcBgMarkWorker.cas(0, guintptr(unsafe.Pointer(g))) {
  21. return false
  22. }
  23. }
  24. return true
  25. }, unsafe.Pointer(park), "GC worker (idle)", traceEvGoBlock, 0)
  26. if _p_.gcBgMarkWorker.ptr() != gp {
  27. break
  28. }
  29. park.m.set(acquirem())
  30. if gcBlackenEnabled == 0 {
  31. throw("gcBgMarkWorker: blackening not enabled")
  32. }
  33. startTime := nanotime()
  34. decnwait := atomic.Xadd(&work.nwait, -1)
  35. if decnwait == work.nproc {
  36. println("runtime: work.nwait=", decnwait, "work.nproc=", work.nproc)
  37. throw("work.nwait was > work.nproc")
  38. }
  39. systemstack(func() {
  40. casgstatus(gp, _Grunning, _Gwaiting)
  41. switch _p_.gcMarkWorkerMode {
  42. default:
  43. throw("gcBgMarkWorker: unexpected gcMarkWorkerMode")
  44. case gcMarkWorkerDedicatedMode:
  45. gcDrain(&_p_.gcw, gcDrainUntilPreempt|gcDrainFlushBgCredit)
  46. if gp.preempt {
  47. lock(&sched.lock)
  48. for {
  49. gp, _ := runqget(_p_)
  50. if gp == nil {
  51. break
  52. }
  53. globrunqput(gp)
  54. }
  55. unlock(&sched.lock)
  56. }
  57. gcDrain(&_p_.gcw, gcDrainNoBlock|gcDrainFlushBgCredit)
  58. case gcMarkWorkerFractionalMode:
  59. gcDrain(&_p_.gcw, gcDrainUntilPreempt|gcDrainFlushBgCredit)
  60. case gcMarkWorkerIdleMode:
  61. gcDrain(&_p_.gcw, gcDrainIdle|gcDrainUntilPreempt|gcDrainFlushBgCredit)
  62. }
  63. casgstatus(gp, _Gwaiting, _Grunning)
  64. })
  65. if gcBlackenPromptly {
  66. _p_.gcw.dispose()
  67. }
  68. duration := nanotime() - startTime
  69. switch _p_.gcMarkWorkerMode {
  70. case gcMarkWorkerDedicatedMode:
  71. atomic.Xaddint64(&gcController.dedicatedMarkTime, duration)
  72. atomic.Xaddint64(&gcController.dedicatedMarkWorkersNeeded, 1)
  73. case gcMarkWorkerFractionalMode:
  74. atomic.Xaddint64(&gcController.fractionalMarkTime, duration)
  75. atomic.Xaddint64(&gcController.fractionalMarkWorkersNeeded, 1)
  76. case gcMarkWorkerIdleMode:
  77. atomic.Xaddint64(&gcController.idleMarkTime, duration)
  78. }
  79. incnwait := atomic.Xadd(&work.nwait, +1)
  80. if incnwait > work.nproc {
  81. println("runtime: p.gcMarkWorkerMode=", _p_.gcMarkWorkerMode,
  82. "work.nwait=", incnwait, "work.nproc=", work.nproc)
  83. throw("work.nwait > work.nproc")
  84. }
  85. if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
  86. _p_.gcBgMarkWorker.set(nil)
  87. releasem(park.m.ptr())
  88. gcMarkDone()
  89. park.m.set(acquirem())
  90. park.attach.set(_p_)
  91. }
  92. }
  93. }

gcDrain函数用于执行标记:

  1. func gcDrain(gcw *gcWork, flags gcDrainFlags) {
  2. if !writeBarrier.needed {
  3. throw("gcDrain phase incorrect")
  4. }
  5. gp := getg().m.curg
  6. preemptible := flags&gcDrainUntilPreempt != 0
  7. blocking := flags&(gcDrainUntilPreempt|gcDrainIdle|gcDrainNoBlock) == 0
  8. flushBgCredit := flags&gcDrainFlushBgCredit != 0
  9. idle := flags&gcDrainIdle != 0
  10. initScanWork := gcw.scanWork
  11. idleCheck := initScanWork + idleCheckThreshold
  12. if work.markrootNext < work.markrootJobs {
  13. for !(preemptible && gp.preempt) {
  14. job := atomic.Xadd(&work.markrootNext, +1) - 1
  15. if job >= work.markrootJobs {
  16. break
  17. }
  18. markroot(gcw, job)
  19. if idle && pollWork() {
  20. goto done
  21. }
  22. }
  23. }
  24. for !(preemptible && gp.preempt) {
  25. if work.full == 0 {
  26. gcw.balance()
  27. }
  28. var b uintptr
  29. if blocking {
  30. b = gcw.get()
  31. } else {
  32. b = gcw.tryGetFast()
  33. if b == 0 {
  34. b = gcw.tryGet()
  35. }
  36. }
  37. if b == 0 {
  38. break
  39. }
  40. scanobject(b, gcw)
  41. if gcw.scanWork >= gcCreditSlack {
  42. atomic.Xaddint64(&gcController.scanWork, gcw.scanWork)
  43. if flushBgCredit {
  44. gcFlushBgCredit(gcw.scanWork - initScanWork)
  45. initScanWork = 0
  46. }
  47. idleCheck -= gcw.scanWork
  48. gcw.scanWork = 0
  49. if idle && idleCheck <= 0 {
  50. idleCheck += idleCheckThreshold
  51. if pollWork() {
  52. break
  53. }
  54. }
  55. }
  56. }
  57. done:
  58. if gcw.scanWork > 0 {
  59. atomic.Xaddint64(&gcController.scanWork, gcw.scanWork)
  60. if flushBgCredit {
  61. gcFlushBgCredit(gcw.scanWork - initScanWork)
  62. }
  63. gcw.scanWork = 0
  64. }
  65. }

markroot函数用于执行根对象扫描工作:

  1. func markroot(gcw *gcWork, i uint32) {
  2. baseFlushCache := uint32(fixedRootCount)
  3. baseData := baseFlushCache + uint32(work.nFlushCacheRoots)
  4. baseBSS := baseData + uint32(work.nDataRoots)
  5. baseSpans := baseBSS + uint32(work.nBSSRoots)
  6. baseStacks := baseSpans + uint32(work.nSpanRoots)
  7. end := baseStacks + uint32(work.nStackRoots)
  8. switch {
  9. case baseFlushCache <= i && i < baseData:
  10. flushmcache(int(i - baseFlushCache))
  11. case baseData <= i && i < baseBSS:
  12. for _, datap := range activeModules() {
  13. markrootBlock(datap.data, datap.edata-datap.data, datap.gcdatamask.bytedata, gcw, int(i-baseData))
  14. }
  15. case baseBSS <= i && i < baseSpans:
  16. for _, datap := range activeModules() {
  17. markrootBlock(datap.bss, datap.ebss-datap.bss, datap.gcbssmask.bytedata, gcw, int(i-baseBSS))
  18. }
  19. case i == fixedRootFinalizers:
  20. if work.markrootDone {
  21. break
  22. }
  23. for fb := allfin; fb != nil; fb = fb.alllink {
  24. cnt := uintptr(atomic.Load(&fb.cnt))
  25. scanblock(uintptr(unsafe.Pointer(&fb.fin[0])), cnt*unsafe.Sizeof(fb.fin[0]), &finptrmask[0], gcw)
  26. }
  27. case i == fixedRootFreeGStacks:
  28. if !work.markrootDone {
  29. systemstack(markrootFreeGStacks)
  30. }
  31. case baseSpans <= i && i < baseStacks:
  32. markrootSpans(gcw, int(i-baseSpans))
  33. default:
  34. var gp *g
  35. if baseStacks <= i && i < end {
  36. gp = allgs[i-baseStacks]
  37. } else {
  38. throw("markroot: bad index")
  39. }
  40. status := readgstatus(gp)
  41. if (status == _Gwaiting || status == _Gsyscall) && gp.waitsince == 0 {
  42. gp.waitsince = work.tstart
  43. }
  44. systemstack(func() {
  45. userG := getg().m.curg
  46. selfScan := gp == userG && readgstatus(userG) == _Grunning
  47. if selfScan {
  48. casgstatus(userG, _Grunning, _Gwaiting)
  49. userG.waitreason = "garbage collection scan"
  50. }
  51. scang(gp, gcw)
  52. if selfScan {
  53. casgstatus(userG, _Gwaiting, _Grunning)
  54. }
  55. })
  56. }
  57. }

scang函数负责扫描 G 的栈:

  1. func scang(gp *g, gcw *gcWork) {
  2. gp.gcscandone = false
  3. const yieldDelay = 10 * 1000
  4. var nextYield int64
  5. loop:
  6. for i := 0; !gp.gcscandone; i++ {
  7. switch s := readgstatus(gp); s {
  8. default:
  9. dumpgstatus(gp)
  10. throw("stopg: invalid status")
  11. case _Gdead:
  12. gp.gcscandone = true
  13. break loop
  14. case _Gcopystack:
  15. case _Grunnable, _Gsyscall, _Gwaiting:
  16. if castogscanstatus(gp, s, s|_Gscan) {
  17. if !gp.gcscandone {
  18. scanstack(gp, gcw)
  19. gp.gcscandone = true
  20. }
  21. restartg(gp)
  22. break loop
  23. }
  24. case _Gscanwaiting:
  25. case _Grunning:
  26. if gp.preemptscan && gp.preempt && gp.stackguard0 == stackPreempt {
  27. break
  28. }
  29. if castogscanstatus(gp, _Grunning, _Gscanrunning) {
  30. if !gp.gcscandone {
  31. gp.preemptscan = true
  32. gp.preempt = true
  33. gp.stackguard0 = stackPreempt
  34. }
  35. casfrom_Gscanstatus(gp, _Gscanrunning, _Grunning)
  36. }
  37. }
  38. if i == 0 {
  39. nextYield = nanotime() + yieldDelay
  40. }
  41. if nanotime() < nextYield {
  42. procyield(10)
  43. } else {
  44. osyield()
  45. nextYield = nanotime() + yieldDelay/2
  46. }
  47. }
  48. gp.preemptscan = false
  49. }

设置 preemptscan 后, 在抢占 G 成功时会调用 scanstack 扫描它自己的栈, 具体代码在这里.
扫描栈用的函数是scanstack:

  1. func scanstack(gp *g, gcw *gcWork) {
  2. if gp.gcscanvalid {
  3. return
  4. }
  5. if readgstatus(gp)&_Gscan == 0 {
  6. print("runtime:scanstack: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", hex(readgstatus(gp)), "n")
  7. throw("scanstack - bad status")
  8. }
  9. switch readgstatus(gp) &^ _Gscan {
  10. default:
  11. print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "n")
  12. throw("mark - bad status")
  13. case _Gdead:
  14. return
  15. case _Grunning:
  16. print("runtime: gp=", gp, ", goid=", gp.goid, ", gp->atomicstatus=", readgstatus(gp), "n")
  17. throw("scanstack: goroutine not stopped")
  18. case _Grunnable, _Gsyscall, _Gwaiting:
  19. }
  20. if gp == getg() {
  21. throw("can't scan our own stack")
  22. }
  23. mp := gp.m
  24. if mp != nil && mp.helpgc != 0 {
  25. throw("can't scan gchelper stack")
  26. }
  27. if !work.markrootDone {
  28. shrinkstack(gp)
  29. }
  30. var cache pcvalueCache
  31. scanframe := func(frame *stkframe, unused unsafe.Pointer) bool {
  32. scanframeworker(frame, &cache, gcw)
  33. return true
  34. }
  35. gentraceback(^uintptr(0), ^uintptr(0), 0, gp, 0, nil, 0x7fffffff, scanframe, nil, 0)
  36. tracebackdefers(gp, scanframe, nil)
  37. gp.gcscanvalid = true
  38. }

scanblock函数是一个通用的扫描函数, 扫描全局变量和栈空间都会用它, 和 scanobject 不同的是 bitmap 需要手动传入:

  1. func scanblock(b0, n0 uintptr, ptrmask *uint8, gcw *gcWork) {
  2. b := b0
  3. n := n0
  4. arena_start := mheap_.arena_start
  5. arena_used := mheap_.arena_used
  6. for i := uintptr(0); i < n; {
  7. bits := uint32(*addb(ptrmask, i/(sys.PtrSize*8)))
  8. if bits == 0 {
  9. i += sys.PtrSize * 8
  10. continue
  11. }
  12. for j := 0; j < 8 && i < n; j++ {
  13. if bits&1 != 0 {
  14. obj := *(*uintptr)(unsafe.Pointer(b + i))
  15. if obj != 0 && arena_start <= obj && obj < arena_used {
  16. if obj, hbits, span, objIndex := heapBitsForObject(obj, b, i); obj != 0 {
  17. greyobject(obj, b, i, hbits, span, gcw, objIndex)
  18. }
  19. }
  20. }
  21. bits >>= 1
  22. i += sys.PtrSize
  23. }
  24. }
  25. }

greyobject用于标记一个对象存活, 并把它加到标记队列 (该对象变为灰色):

  1. func greyobject(obj, base, off uintptr, hbits heapBits, span *mspan, gcw *gcWork, objIndex uintptr) {
  2. if obj&(sys.PtrSize-1) != 0 {
  3. throw("greyobject: obj not pointer-aligned")
  4. }
  5. mbits := span.markBitsForIndex(objIndex)
  6. if useCheckmark {
  7. if !mbits.isMarked() {
  8. printlock()
  9. print("runtime:greyobject: checkmarks finds unexpected unmarked object obj=", hex(obj), "n")
  10. print("runtime: found obj at *(", hex(base), "+", hex(off), ")n")
  11. gcDumpObject("base", base, off)
  12. gcDumpObject("obj", obj, ^uintptr(0))
  13. getg().m.traceback = 2
  14. throw("checkmark found unmarked object")
  15. }
  16. if hbits.isCheckmarked(span.elemsize) {
  17. return
  18. }
  19. hbits.setCheckmarked(span.elemsize)
  20. if !hbits.isCheckmarked(span.elemsize) {
  21. throw("setCheckmarked and isCheckmarked disagree")
  22. }
  23. } else {
  24. if debug.gccheckmark > 0 && span.isFree(objIndex) {
  25. print("runtime: marking free object ", hex(obj), " found at *(", hex(base), "+", hex(off), ")n")
  26. gcDumpObject("base", base, off)
  27. gcDumpObject("obj", obj, ^uintptr(0))
  28. getg().m.traceback = 2
  29. throw("marking free object")
  30. }
  31. if mbits.isMarked() {
  32. return
  33. }
  34. atomic.Or8(mbits.bytep, mbits.mask)
  35. if span.spanclass.noscan() {
  36. gcw.bytesMarked += uint64(span.elemsize)
  37. return
  38. }
  39. }
  40. if !gcw.putFast(obj) {
  41. gcw.put(obj)
  42. }
  43. }

gcDrain 函数扫描完根对象, 就会开始消费标记队列, 对从标记队列中取出的对象调用scanobject函数:

  1. func scanobject(b uintptr, gcw *gcWork) {
  2. arena_start := mheap_.arena_start
  3. arena_used := mheap_.arena_used
  4. hbits := heapBitsForAddr(b)
  5. s := spanOfUnchecked(b)
  6. n := s.elemsize
  7. if n == 0 {
  8. throw("scanobject n == 0")
  9. }
  10. if n > maxObletBytes {
  11. if b == s.base() {
  12. if s.spanclass.noscan() {
  13. gcw.bytesMarked += uint64(n)
  14. return
  15. }
  16. for oblet := b + maxObletBytes; oblet < s.base()+s.elemsize; oblet += maxObletBytes {
  17. if !gcw.putFast(oblet) {
  18. gcw.put(oblet)
  19. }
  20. }
  21. }
  22. n = s.base() + s.elemsize - b
  23. if n > maxObletBytes {
  24. n = maxObletBytes
  25. }
  26. }
  27. var i uintptr
  28. for i = 0; i < n; i += sys.PtrSize {
  29. if i != 0 {
  30. hbits = hbits.next()
  31. }
  32. bits := hbits.bits()
  33. if i != 1*sys.PtrSize && bits&bitScan == 0 {
  34. break
  35. }
  36. if bits&bitPointer == 0 {
  37. continue
  38. }
  39. obj := *(*uintptr)(unsafe.Pointer(b + i))
  40. if obj != 0 && arena_start <= obj && obj < arena_used && obj-b >= n {
  41. if obj, hbits, span, objIndex := heapBitsForObject(obj, b, i); obj != 0 {
  42. greyobject(obj, b, i, hbits, span, gcw, objIndex)
  43. }
  44. }
  45. }
  46. gcw.bytesMarked += uint64(n)
  47. gcw.scanWork += int64(i)
  48. }

在所有后台标记任务都把标记队列消费完毕时, 会执行gcMarkDone函数准备进入完成标记阶段 (mark termination):
在并行 GC 中 gcMarkDone 会被执行两次, 第一次会禁止本地标记队列然后重新开始后台标记任务, 第二次会进入完成标记阶段 (mark termination)。

  1. func gcMarkDone() {
  2. top:
  3. semacquire(&work.markDoneSema)
  4. if !(gcphase == _GCmark && work.nwait == work.nproc && !gcMarkWorkAvailable(nil)) {
  5. semrelease(&work.markDoneSema)
  6. return
  7. }
  8. atomic.Xaddint64(&gcController.dedicatedMarkWorkersNeeded, -0xffffffff)
  9. atomic.Xaddint64(&gcController.fractionalMarkWorkersNeeded, -0xffffffff)
  10. if !gcBlackenPromptly {
  11. gcBlackenPromptly = true
  12. atomic.Xadd(&work.nwait, -1)
  13. semrelease(&work.markDoneSema)
  14. systemstack(func() {
  15. forEachP(func(_p_ *p) {
  16. _p_.gcw.dispose()
  17. })
  18. })
  19. gcMarkRootCheck()
  20. atomic.Xaddint64(&gcController.dedicatedMarkWorkersNeeded, 0xffffffff)
  21. atomic.Xaddint64(&gcController.fractionalMarkWorkersNeeded, 0xffffffff)
  22. incnwait := atomic.Xadd(&work.nwait, +1)
  23. if incnwait == work.nproc && !gcMarkWorkAvailable(nil) {
  24. goto top
  25. }
  26. } else {
  27. now := nanotime()
  28. work.tMarkTerm = now
  29. work.pauseStart = now
  30. getg().m.preemptoff = "gcing"
  31. systemstack(stopTheWorldWithSema)
  32. work.markrootDone = true
  33. atomic.Store(&gcBlackenEnabled, 0)
  34. gcWakeAllAssists()
  35. semrelease(&work.markDoneSema)
  36. nextTriggerRatio := gcController.endCycle()
  37. gcMarkTermination(nextTriggerRatio)
  38. }
  39. }

gcMarkTermination函数会进入完成标记阶段:

  1. func gcMarkTermination(nextTriggerRatio float64) {
  2. atomic.Store(&gcBlackenEnabled, 0)
  3. gcBlackenPromptly = false
  4. setGCPhase(_GCmarktermination)
  5. work.heap1 = memstats.heap_live
  6. startTime := nanotime()
  7. mp := acquirem()
  8. mp.preemptoff = "gcing"
  9. _g_ := getg()
  10. _g_.m.traceback = 2
  11. gp := _g_.m.curg
  12. casgstatus(gp, _Grunning, _Gwaiting)
  13. gp.waitreason = "garbage collection"
  14. systemstack(func() {
  15. gcMark(startTime)
  16. })
  17. systemstack(func() {
  18. work.heap2 = work.bytesMarked
  19. if debug.gccheckmark > 0 {
  20. gcResetMarkState()
  21. initCheckmarks()
  22. gcMark(startTime)
  23. clearCheckmarks()
  24. }
  25. setGCPhase(_GCoff)
  26. gcSweep(work.mode)
  27. if debug.gctrace > 1 {
  28. startTime = nanotime()
  29. gcResetMarkState()
  30. finishsweep_m()
  31. setGCPhase(_GCmarktermination)
  32. gcMark(startTime)
  33. setGCPhase(_GCoff)
  34. gcSweep(work.mode)
  35. }
  36. })
  37. _g_.m.traceback = 0
  38. casgstatus(gp, _Gwaiting, _Grunning)
  39. if trace.enabled {
  40. traceGCDone()
  41. }
  42. mp.preemptoff = ""
  43. if gcphase != _GCoff {
  44. throw("gc done but gcphase != _GCoff")
  45. }
  46. gcSetTriggerRatio(nextTriggerRatio)
  47. now := nanotime()
  48. sec, nsec, _ := time_now()
  49. unixNow := sec*1e9 + int64(nsec)
  50. work.pauseNS += now - work.pauseStart
  51. work.tEnd = now
  52. atomic.Store64(&memstats.last_gc_unix, uint64(unixNow))
  53. atomic.Store64(&memstats.last_gc_nanotime, uint64(now))
  54. memstats.pause_ns[memstats.numgc%uint32(len(memstats.pause_ns))] = uint64(work.pauseNS)
  55. memstats.pause_end[memstats.numgc%uint32(len(memstats.pause_end))] = uint64(unixNow)
  56. memstats.pause_total_ns += uint64(work.pauseNS)
  57. sweepTermCpu := int64(work.stwprocs) * (work.tMark - work.tSweepTerm)
  58. markCpu := gcController.assistTime + gcController.dedicatedMarkTime + gcController.fractionalMarkTime
  59. markTermCpu := int64(work.stwprocs) * (work.tEnd - work.tMarkTerm)
  60. cycleCpu := sweepTermCpu + markCpu + markTermCpu
  61. work.totaltime += cycleCpu
  62. totalCpu := sched.totaltime + (now-sched.procresizetime)*int64(gomaxprocs)
  63. memstats.gc_cpu_fraction = float64(work.totaltime) / float64(totalCpu)
  64. sweep.nbgsweep = 0
  65. sweep.npausesweep = 0
  66. if work.userForced {
  67. memstats.numforcedgc++
  68. }
  69. lock(&work.sweepWaiters.lock)
  70. memstats.numgc++
  71. injectglist(work.sweepWaiters.head.ptr())
  72. work.sweepWaiters.head = 0
  73. unlock(&work.sweepWaiters.lock)
  74. mProf_NextCycle()
  75. systemstack(startTheWorldWithSema)
  76. mProf_Flush()
  77. prepareFreeWorkbufs()
  78. systemstack(freeStackSpans)
  79. if debug.gctrace > 0 {
  80. util := int(memstats.gc_cpu_fraction * 100)
  81. var sbuf [24]byte
  82. printlock()
  83. print("gc ", memstats.numgc,
  84. " @", string(itoaDiv(sbuf[:], uint64(work.tSweepTerm-runtimeInitTime)/1e6, 3)), "s ",
  85. util, "%: ")
  86. prev := work.tSweepTerm
  87. for i, ns := range []int64{work.tMark, work.tMarkTerm, work.tEnd} {
  88. if i != 0 {
  89. print("+")
  90. }
  91. print(string(fmtNSAsMS(sbuf[:], uint64(ns-prev))))
  92. prev = ns
  93. }
  94. print(" ms clock, ")
  95. for i, ns := range []int64{sweepTermCpu, gcController.assistTime, gcController.dedicatedMarkTime + gcController.fractionalMarkTime, gcController.idleMarkTime, markTermCpu} {
  96. if i == 2 || i == 3 {
  97. print("/")
  98. } else if i != 0 {
  99. print("+")
  100. }
  101. print(string(fmtNSAsMS(sbuf[:], uint64(ns))))
  102. }
  103. print(" ms cpu, ",
  104. work.heap0>>20, "->", work.heap1>>20, "->", work.heap2>>20, " MB, ",
  105. work.heapGoal>>20, " MB goal, ",
  106. work.maxprocs, " P")
  107. if work.userForced {
  108. print(" (forced)")
  109. }
  110. print("n")
  111. printunlock()
  112. }
  113. semrelease(&worldsema)
  114. releasem(mp)
  115. mp = nil
  116. if !concurrentSweep {
  117. Gosched()
  118. }
  119. }

gcSweep函数会唤醒后台清扫任务:
后台清扫任务会在程序启动时调用的gcenable函数中启动.

  1. func gcSweep(mode gcMode) {
  2. if gcphase != _GCoff {
  3. throw("gcSweep being done but phase is not GCoff")
  4. }
  5. lock(&mheap_.lock)
  6. mheap_.sweepgen += 2
  7. mheap_.sweepdone = 0
  8. if mheap_.sweepSpans[mheap_.sweepgen/2%2].index != 0 {
  9. throw("non-empty swept list")
  10. }
  11. mheap_.pagesSwept = 0
  12. unlock(&mheap_.lock)
  13. if !_ConcurrentSweep || mode == gcForceBlockMode {
  14. lock(&mheap_.lock)
  15. mheap_.sweepPagesPerByte = 0
  16. unlock(&mheap_.lock)
  17. for sweepone() != ^uintptr(0) {
  18. sweep.npausesweep++
  19. }
  20. prepareFreeWorkbufs()
  21. for freeSomeWbufs(false) {
  22. }
  23. mProf_NextCycle()
  24. mProf_Flush()
  25. return
  26. }
  27. lock(&sweep.lock)
  28. if sweep.parked {
  29. sweep.parked = false
  30. ready(sweep.g, 0, true)
  31. }
  32. unlock(&sweep.lock)
  33. }

后台清扫任务的函数是bgsweep:

  1. func bgsweep(c chan int) {
  2. sweep.g = getg()
  3. lock(&sweep.lock)
  4. sweep.parked = true
  5. c <- 1
  6. goparkunlock(&sweep.lock, "GC sweep wait", traceEvGoBlock, 1)
  7. for {
  8. for gosweepone() != ^uintptr(0) {
  9. sweep.nbgsweep++
  10. Gosched()
  11. }
  12. for freeSomeWbufs(true) {
  13. Gosched()
  14. }
  15. lock(&sweep.lock)
  16. if !gosweepdone() {
  17. unlock(&sweep.lock)
  18. continue
  19. }
  20. sweep.parked = true
  21. goparkunlock(&sweep.lock, "GC sweep wait", traceEvGoBlock, 1)
  22. }
  23. }

gosweepone函数会从 sweepSpans 中取出单个 span 清扫:

  1. func gosweepone() uintptr {
  2. var ret uintptr
  3. systemstack(func() {
  4. ret = sweepone()
  5. })
  6. return ret
  7. }

sweepone函数如下:

  1. func sweepone() uintptr {
  2. _g_ := getg()
  3. sweepRatio := mheap_.sweepPagesPerByte
  4. _g_.m.locks++
  5. if atomic.Load(&mheap_.sweepdone) != 0 {
  6. _g_.m.locks--
  7. return ^uintptr(0)
  8. }
  9. atomic.Xadd(&mheap_.sweepers, +1)
  10. npages := ^uintptr(0)
  11. sg := mheap_.sweepgen
  12. for {
  13. s := mheap_.sweepSpans[1-sg/2%2].pop()
  14. if s == nil {
  15. atomic.Store(&mheap_.sweepdone, 1)
  16. break
  17. }
  18. if s.state != mSpanInUse {
  19. if s.sweepgen != sg {
  20. print("runtime: bad span s.state=", s.state, " s.sweepgen=", s.sweepgen, " sweepgen=", sg, "n")
  21. throw("non in-use span in unswept list")
  22. }
  23. continue
  24. }
  25. if s.sweepgen != sg-2 || !atomic.Cas(&s.sweepgen, sg-2, sg-1) {
  26. continue
  27. }
  28. npages = s.npages
  29. if !s.sweep(false) {
  30. npages = 0
  31. }
  32. break
  33. }
  34. if atomic.Xadd(&mheap_.sweepers, -1) == 0 && atomic.Load(&mheap_.sweepdone) != 0 {
  35. if debug.gcpacertrace > 0 {
  36. print("pacer: sweep done at heap size ", memstats.heap_live>>20, "MB; allocated ", (memstats.heap_live-mheap_.sweepHeapLiveBasis)>>20, "MB during sweep; swept ", mheap_.pagesSwept, " pages at ", sweepRatio, " pages/byten")
  37. }
  38. }
  39. _g_.m.locks--
  40. return npages
  41. }

span 的sweep函数用于清扫单个 span:

  1. func (s *mspan) sweep(preserve bool) bool {
  2. _g_ := getg()
  3. if _g_.m.locks == 0 && _g_.m.mallocing == 0 && _g_ != _g_.m.g0 {
  4. throw("MSpan_Sweep: m is not locked")
  5. }
  6. sweepgen := mheap_.sweepgen
  7. if s.state != mSpanInUse || s.sweepgen != sweepgen-1 {
  8. print("MSpan_Sweep: state=", s.state, " sweepgen=", s.sweepgen, " mheap.sweepgen=", sweepgen, "n")
  9. throw("MSpan_Sweep: bad span state")
  10. }
  11. if trace.enabled {
  12. traceGCSweepSpan(s.npages * _PageSize)
  13. }
  14. atomic.Xadd64(&mheap_.pagesSwept, int64(s.npages))
  15. spc := s.spanclass
  16. size := s.elemsize
  17. res := false
  18. c := _g_.m.mcache
  19. freeToHeap := false
  20. specialp := &s.specials
  21. special := *specialp
  22. for special != nil {
  23. objIndex := uintptr(special.offset) / size
  24. p := s.base() + objIndex*size
  25. mbits := s.markBitsForIndex(objIndex)
  26. if !mbits.isMarked() {
  27. hasFin := false
  28. endOffset := p - s.base() + size
  29. for tmp := special; tmp != nil && uintptr(tmp.offset) < endOffset; tmp = tmp.next {
  30. if tmp.kind == _KindSpecialFinalizer {
  31. mbits.setMarkedNonAtomic()
  32. hasFin = true
  33. break
  34. }
  35. }
  36. for special != nil && uintptr(special.offset) < endOffset {
  37. p := s.base() + uintptr(special.offset)
  38. if special.kind == _KindSpecialFinalizer || !hasFin {
  39. y := special
  40. special = special.next
  41. *specialp = special
  42. freespecial(y, unsafe.Pointer(p), size)
  43. } else {
  44. specialp = &special.next
  45. special = *specialp
  46. }
  47. }
  48. } else {
  49. specialp = &special.next
  50. special = *specialp
  51. }
  52. }
  53. if debug.allocfreetrace != 0 || raceenabled || msanenabled {
  54. mbits := s.markBitsForBase()
  55. abits := s.allocBitsForIndex(0)
  56. for i := uintptr(0); i < s.nelems; i++ {
  57. if !mbits.isMarked() && (abits.index < s.freeindex || abits.isMarked()) {
  58. x := s.base() + i*s.elemsize
  59. if debug.allocfreetrace != 0 {
  60. tracefree(unsafe.Pointer(x), size)
  61. }
  62. if raceenabled {
  63. racefree(unsafe.Pointer(x), size)
  64. }
  65. if msanenabled {
  66. msanfree(unsafe.Pointer(x), size)
  67. }
  68. }
  69. mbits.advance()
  70. abits.advance()
  71. }
  72. }
  73. nalloc := uint16(s.countAlloc())
  74. if spc.sizeclass() == 0 && nalloc == 0 {
  75. s.needzero = 1
  76. freeToHeap = true
  77. }
  78. nfreed := s.allocCount - nalloc
  79. if nalloc > s.allocCount {
  80. print("runtime: nelems=", s.nelems, " nalloc=", nalloc, " previous allocCount=", s.allocCount, " nfreed=", nfreed, "n")
  81. throw("sweep increased allocation count")
  82. }
  83. s.allocCount = nalloc
  84. wasempty := s.nextFreeIndex() == s.nelems
  85. s.freeindex = 0
  86. if trace.enabled {
  87. getg().m.p.ptr().traceReclaimed += uintptr(nfreed) * s.elemsize
  88. }
  89. s.allocBits = s.gcmarkBits
  90. s.gcmarkBits = newMarkBits(s.nelems)
  91. s.refillAllocCache(0)
  92. if freeToHeap || nfreed == 0 {
  93. if s.state != mSpanInUse || s.sweepgen != sweepgen-1 {
  94. print("MSpan_Sweep: state=", s.state, " sweepgen=", s.sweepgen, " mheap.sweepgen=", sweepgen, "n")
  95. throw("MSpan_Sweep: bad span state after sweep")
  96. }
  97. atomic.Store(&s.sweepgen, sweepgen)
  98. }
  99. if nfreed > 0 && spc.sizeclass() != 0 {
  100. c.local_nsmallfree[spc.sizeclass()] += uintptr(nfreed)
  101. res = mheap_.central[spc].mcentral.freeSpan(s, preserve, wasempty)
  102. } else if freeToHeap {
  103. if debug.efence > 0 {
  104. s.limit = 0
  105. sysFault(unsafe.Pointer(s.base()), size)
  106. } else {
  107. mheap_.freeSpan(s, 1)
  108. }
  109. c.local_nlargefree++
  110. c.local_largefree += size
  111. res = true
  112. }
  113. if !res {
  114. mheap_.sweepSpans[sweepgen/2%2].push(s)
  115. }
  116. return res
  117. }

从 bgsweep 和前面的分配器可以看出扫描阶段的工作是十分懒惰 (lazy) 的,
实际可能会出现前一阶段的扫描还未完成, 就需要开始新一轮的 GC 的情况,
所以每一轮 GC 开始之前都需要完成前一轮 GC 的扫描工作 (Sweep Termination 阶段).

GC 的整个流程都分析完毕了, 最后贴上写屏障函数writebarrierptr的实现:

  1. func writebarrierptr(dst *uintptr, src uintptr) {
  2. if writeBarrier.cgo {
  3. cgoCheckWriteBarrier(dst, src)
  4. }
  5. if !writeBarrier.needed {
  6. *dst = src
  7. return
  8. }
  9. if src != 0 && src < minPhysPageSize {
  10. systemstack(func() {
  11. print("runtime: writebarrierptr *", dst, " = ", hex(src), "n")
  12. throw("bad pointer in write barrier")
  13. })
  14. }
  15. writebarrierptr_prewrite1(dst, src)
  16. *dst = src
  17. }

writebarrierptr_prewrite1函数如下:

  1. func writebarrierptr_prewrite1(dst *uintptr, src uintptr) {
  2. mp := acquirem()
  3. if mp.inwb || mp.dying > 0 {
  4. releasem(mp)
  5. return
  6. }
  7. systemstack(func() {
  8. if mp.p == 0 && memstats.enablegc && !mp.inwb && inheap(src) {
  9. throw("writebarrierptr_prewrite1 called with mp.p == nil")
  10. }
  11. mp.inwb = true
  12. gcmarkwb_m(dst, src)
  13. })
  14. mp.inwb = false
  15. releasem(mp)
  16. }

gcmarkwb_m函数如下:

  1. func gcmarkwb_m(slot *uintptr, ptr uintptr) {
  2. if writeBarrier.needed {
  3. if slot1 := uintptr(unsafe.Pointer(slot)); slot1 >= minPhysPageSize {
  4. if optr := *slot; optr != 0 {
  5. shade(optr)
  6. }
  7. }
  8. if ptr != 0 && inheap(ptr) {
  9. shade(ptr)
  10. }
  11. }
  12. }

shade函数如下:

  1. func shade(b uintptr) {
  2. if obj, hbits, span, objIndex := heapBitsForObject(b, 0, 0); obj != 0 {
  3. gcw := &getg().m.p.ptr().gcw
  4. greyobject(obj, 0, 0, hbits, span, gcw, objIndex)
  5. if gcphase == _GCmarktermination || gcBlackenPromptly {
  6. gcw.dispose()
  7. }
  8. }
  9. }

https://github.com/golang/go
https://making.pusher.com/golangs-real-time-gc-in-theory-and-practice
https://github.com/golang/proposal/blob/master/design/17503-eliminate-rescan.md
https://golang.org/s/go15gcpacing
https://golang.org/ref/mem
https://talks.golang.org/2015/go-gc.pdf
https://docs.google.com/document/d/1ETuA2IOmnaQ4j81AtTGT40Y4_Jr6_IDASEKg0t0dBR8/edit#heading=h.x4kziklnb8fr
https://go-review.googlesource.com/c/go/+/21503
http://www.cnblogs.com/diegodu/p/5803202.html
http://legendtkl.com/2017/04/28/golang-gc
https://lengzzz.com/note/gc-in-golang

因为我之前已经对 CoreCLR 的 GC 做过分析 (看这一篇这一篇), 这里我可以简单的对比一下 CoreCLR 和 GO 的 GC 实现:

  • CoreCLR 的对象带有类型信息, GO 的对象不带, 而是通过 bitmap 区域记录哪些地方包含指针

  • CoreCLR 分配对象的速度明显更快, GO 分配对象需要查找 span 和写入 bitmap 区域

  • CoreCLR 的收集器需要做的工作比 GO 多很多

    • CoreCLR 不同大小的对象都会放在一个 segment 中, 只能线性扫描
    • CoreCLR 判断对象引用要访问类型信息, 而 go 只需要访问 bitmap
    • CoreCLR 清扫时要一个个去标记为自由对象, 而 go 只需要切换 allocBits
  • CoreCLR 的停顿时间比 GO 要长

    • 虽然 CoreCLR 支持并行 GC, 但是没有 GO 彻底, GO 连扫描根对象都不需要完全停顿
  • CoreCLR 支持分代 GC

    • 虽然 Full GC 时 CoreCLR 的效率不如 GO, 但是 CoreCLR 可以在大部分时候只扫描第 0 和第 1 代的对象
    • 因为支持分代 GC, 通常 CoreCLR 花在 GC 上的 CPU 时间会比 GO 要少

CoreCLR 的分配器和收集器通常比 GO 要高效, 也就是说 CoreCLR 会有更高的吞吐量.
但 CoreCLR 的最大停顿时间不如 GO 短, 这是因为 GO 的 GC 整个设计都是为了减少停顿时间.

现在分布式计算和横向扩展越来越流行,
比起追求单机吞吐量, 追求低延迟然后让分布式解决吞吐量问题无疑是更明智的选择,
GO 的设计目标使得它比其他语言都更适合编写网络服务程序.
https://segmentfault.com/a/1190000037770285?utm_source=tag-newest