diff --git a/1.14/defer.md b/1.14/defer.md new file mode 100644 index 0000000..21be46d --- /dev/null +++ b/1.14/defer.md @@ -0,0 +1,458 @@ +# 1.14 defer + +## 正常处理流程 + +在 Go 1.14 中,增加了一种新的 defer 实现:open coded defer。当函数内 defer 不超过 8 个时,则会使用这种实现。 + +形如下面这样的代码: + +```go +defer f1(a) +if cond { + defer f2(b) +} +body... +``` + +会被翻译为: + +```go +deferBits |= 1<<0 // 因为函数主 block 有 defer 语句,所以这里要设置第 0 位为 1 +tmpF1 = f1 // 将函数地址搬运到预留的栈上空间 +tmpA = a // 将函数参数复制到预留的栈上空间 +if cond { + deferBits |= 1<<1 // 因为进入了 if block,所以这里要设置第 1 位为 1 + tmpF2 = f2 // 将函数地址搬运到预留的栈上空间 + tmpB = b // 将函数参数复制到预留的栈上空间 +} +body... +exit: // 退出函数 body +if deferBits & 1<<1 != 0 { // 检查第 1 个 bit,如果是 1,执行保存好的函数 + deferBits &^= 1<<1 + tmpF2(tmpB) +} +if deferBits & 1<<0 != 0 { // 检查第 0 个 bit,如果是 1,执行保存好的函数 + deferBits &^= 1<<0 + tmpF1(tmpA) +} +``` + +这样看我们不一定知道他具体是怎么实现的,可以写个 block 更多的例子来看看实际生成的代码是什么样的: + +```go + 1 package main + 2 + 3 import "fmt" + 4 + 5 var i = 100 + 6 + 7 func main() { + 8 if i == 0 { + 9 defer fmt.Println("1") + 10 } + 11 + 12 if i == 1 { + 13 defer fmt.Println("2") + 14 } + 15 + 16 if i == 2 { + 17 defer fmt.Println("3") + 18 } + 19 + 20 if i == 3 { + 21 defer fmt.Println("4") + 22 } + 23 + 24 if i == 4 { + 25 defer fmt.Println("5") + 26 } + 27 + 28 if i == 5 { + 29 defer fmt.Println("6") + 30 } + 31 } +``` + +下面是 go tool compile -S 生成的汇编代码,简单划分一下 block 来理解一下: + +``` +"".main STEXT size=1125 args=0x0 locals=0x160 +if i == 0: + 0x0055 00085 (open-coded-defer.go:8) CMPQ "".i(SB), $0 + 0x005d 00093 (open-coded-defer.go:8) JNE 1075 // 1075 是条废指令,其实本质是跳过这条 if 的 DEFER PREPARE BLOCK,去地址 188 + +DEFER PREPARE BLOCK 1,主要工作是将 fmt.Println 的参数和函数地址搬运到栈上该 defer 对应的区域: + 0x0063 00099 (open-coded-defer.go:9) XORPS X0, X0 + 0x0066 00102 (open-coded-defer.go:9) MOVUPS X0, ""..autotmp_3+72(SP) + 0x006b 00107 (open-coded-defer.go:9) LEAQ type.string(SB), AX + 0x0072 00114 (open-coded-defer.go:9) MOVQ AX, ""..autotmp_3+72(SP) + 0x0077 00119 (open-coded-defer.go:9) LEAQ ""..stmp_0(SB), CX + 0x007e 00126 (open-coded-defer.go:9) MOVQ CX, ""..autotmp_3+80(SP) + 0x0083 00131 (open-coded-defer.go:9) LEAQ fmt.Println·f(SB), CX + 0x008a 00138 (open-coded-defer.go:9) MOVQ CX, ""..autotmp_25+192(SP) + 0x0092 00146 (open-coded-defer.go:9) LEAQ ""..autotmp_3+72(SP), DX + 0x0097 00151 (open-coded-defer.go:9) MOVQ DX, ""..autotmp_26+320(SP) + 0x009f 00159 (open-coded-defer.go:9) MOVQ $1, ""..autotmp_26+328(SP) + 0x00ab 00171 (open-coded-defer.go:9) MOVQ $1, ""..autotmp_26+336(SP) + 0x00b7 00183 (open-coded-defer.go:9) MOVB $1, ""..autotmp_24+55(SP) + + // 根据 zero flag 设置值,如果 zero flag = 1,那么 DI = 1,如果 zero flag = 0,那么 DI = 0 + // 详情参见 intel 手册的 sete/setz 指令 + // 也就是说,只要走了上面的 DEFER PREPARE BLOCK,那么这里就 DI = 1,否则 DI = 0 + 0x00bc 00188 (open-coded-defer.go:8) SETEQ DL + +if i == 1: + 0x00bf 00191 (open-coded-defer.go:12) CMPQ "".i(SB), $1 + 0x00c7 00199 (open-coded-defer.go:12) JNE 278 + +DEFER PREPARE BLOCK 2, 和 BLOCK 1 工作差不多,是把第二个 defer 的参数和函数地址保存在栈上: + 0x00c9 00201 (open-coded-defer.go:13) XORPS X0, X0 + 0x00cc 00204 (open-coded-defer.go:13) MOVUPS X0, ""..autotmp_7+56(SP) + 0x00d1 00209 (open-coded-defer.go:13) MOVQ AX, ""..autotmp_7+56(SP) + 0x00d6 00214 (open-coded-defer.go:13) LEAQ ""..stmp_1(SB), BX + 0x00dd 00221 (open-coded-defer.go:13) MOVQ BX, ""..autotmp_7+64(SP) + 0x00e2 00226 (open-coded-defer.go:13) MOVQ CX, ""..autotmp_27+184(SP) + 0x00ea 00234 (open-coded-defer.go:13) LEAQ ""..autotmp_7+56(SP), BX + 0x00ef 00239 (open-coded-defer.go:13) MOVQ BX, ""..autotmp_28+296(SP) + 0x00f7 00247 (open-coded-defer.go:13) MOVQ $1, ""..autotmp_28+304(SP) + 0x0103 00259 (open-coded-defer.go:13) MOVQ $1, ""..autotmp_28+312(SP) + + 0x010f 00271 (open-coded-defer.go:13) ORL $2, DX // 设置 DX 的第二个标记位为 1 + 0x0112 00274 (open-coded-defer.go:13) MOVB DL, ""..autotmp_24+55(SP) // TODO + +if i == 2: + 0x0116 00278 (open-coded-defer.go:16) CMPQ "".i(SB), $2 + 0x011e 00286 (open-coded-defer.go:16) JNE 377 + +DEFER PREPARE BLOCK 3,和上面类似,就不解释了: + 0x0120 00288 (open-coded-defer.go:17) XORPS X0, X0 + 0x0123 00291 (open-coded-defer.go:17) MOVUPS X0, ""..autotmp_11+136(SP) + 0x012b 00299 (open-coded-defer.go:17) MOVQ AX, ""..autotmp_11+136(SP) + 0x0133 00307 (open-coded-defer.go:17) LEAQ ""..stmp_2(SB), BX + 0x013a 00314 (open-coded-defer.go:17) MOVQ BX, ""..autotmp_11+144(SP) + 0x0142 00322 (open-coded-defer.go:17) MOVQ CX, ""..autotmp_29+176(SP) + 0x014a 00330 (open-coded-defer.go:17) LEAQ ""..autotmp_11+136(SP), BX + 0x0152 00338 (open-coded-defer.go:17) MOVQ BX, ""..autotmp_30+272(SP) + 0x015a 00346 (open-coded-defer.go:17) MOVQ $1, ""..autotmp_30+280(SP) + 0x0166 00358 (open-coded-defer.go:17) MOVQ $1, ""..autotmp_30+288(SP) + + 0x0172 00370 (open-coded-defer.go:17) ORL $4, DX // 设置 DX 的第三个标记位为 1 + 0x0175 00373 (open-coded-defer.go:17) MOVB DL, ""..autotmp_24+55(SP) + +if i == 3 + 0x0179 00377 (open-coded-defer.go:20) CMPQ "".i(SB), $3 + 0x0181 00385 (open-coded-defer.go:20) JNE 467 + +DEFER PREPARE BLOCK 4: + 0x0183 00387 (open-coded-defer.go:21) XORPS X0, X0 + 0x0186 00390 (open-coded-defer.go:21) MOVUPS X0, ""..autotmp_15+120(SP) + 0x018b 00395 (open-coded-defer.go:21) MOVQ AX, ""..autotmp_15+120(SP) + 0x0190 00400 (open-coded-defer.go:21) LEAQ ""..stmp_3(SB), BX + 0x0197 00407 (open-coded-defer.go:21) MOVQ BX, ""..autotmp_15+128(SP) + 0x019f 00415 (open-coded-defer.go:21) MOVQ CX, ""..autotmp_31+168(SP) + 0x01a7 00423 (open-coded-defer.go:21) LEAQ ""..autotmp_15+120(SP), BX + 0x01ac 00428 (open-coded-defer.go:21) MOVQ BX, ""..autotmp_32+248(SP) + 0x01b4 00436 (open-coded-defer.go:21) MOVQ $1, ""..autotmp_32+256(SP) + 0x01c0 00448 (open-coded-defer.go:21) MOVQ $1, ""..autotmp_32+264(SP) + + 0x01cc 00460 (open-coded-defer.go:21) ORL $8, DX // 设置 DX 的第四个标记位为 1 + 0x01cf 00463 (open-coded-defer.go:21) MOVB DL, ""..autotmp_24+55(SP) + +if i == 4: + 0x01d3 00467 (open-coded-defer.go:24) CMPQ "".i(SB), $4 + 0x01db 00475 (open-coded-defer.go:24) JNE 554 + +DEFER PREPARE BLOCK 5: + 0x01dd 00477 (open-coded-defer.go:25) XORPS X0, X0 + 0x01e0 00480 (open-coded-defer.go:25) MOVUPS X0, ""..autotmp_19+104(SP) + 0x01e5 00485 (open-coded-defer.go:25) MOVQ AX, ""..autotmp_19+104(SP) + 0x01ea 00490 (open-coded-defer.go:25) LEAQ ""..stmp_4(SB), BX + 0x01f1 00497 (open-coded-defer.go:25) MOVQ BX, ""..autotmp_19+112(SP) + 0x01f6 00502 (open-coded-defer.go:25) MOVQ CX, ""..autotmp_33+160(SP) + 0x01fe 00510 (open-coded-defer.go:25) LEAQ ""..autotmp_19+104(SP), BX + 0x0203 00515 (open-coded-defer.go:25) MOVQ BX, ""..autotmp_34+224(SP) + 0x020b 00523 (open-coded-defer.go:25) MOVQ $1, ""..autotmp_34+232(SP) + 0x0217 00535 (open-coded-defer.go:25) MOVQ $1, ""..autotmp_34+240(SP) + + 0x0223 00547 (open-coded-defer.go:25) ORL $16, DX // 设置 DX 的第五个标记位为 1 + 0x0226 00550 (open-coded-defer.go:25) MOVB DL, ""..autotmp_24+55(SP) + +if i == 5: + 0x022a 00554 (open-coded-defer.go:28) CMPQ "".i(SB), $5 + 0x0232 00562 (open-coded-defer.go:28) JNE 641 + +DEFER PREPARE BLOCK 6: + 0x0234 00564 (open-coded-defer.go:29) XORPS X0, X0 + 0x0237 00567 (open-coded-defer.go:29) MOVUPS X0, ""..autotmp_23+88(SP) + 0x023c 00572 (open-coded-defer.go:29) MOVQ AX, ""..autotmp_23+88(SP) + 0x0241 00577 (open-coded-defer.go:29) LEAQ ""..stmp_5(SB), AX + 0x0248 00584 (open-coded-defer.go:29) MOVQ AX, ""..autotmp_23+96(SP) + 0x024d 00589 (open-coded-defer.go:29) MOVQ CX, ""..autotmp_35+152(SP) + 0x0255 00597 (open-coded-defer.go:29) LEAQ ""..autotmp_23+88(SP), AX + 0x025a 00602 (open-coded-defer.go:29) MOVQ AX, ""..autotmp_36+200(SP) + 0x0262 00610 (open-coded-defer.go:29) MOVQ $1, ""..autotmp_36+208(SP) + 0x026e 00622 (open-coded-defer.go:29) MOVQ $1, ""..autotmp_36+216(SP) + + 0x027a 00634 (open-coded-defer.go:29) ORL $32, DX // 设置 DX 的第六个标志位为 1 + 0x027d 00637 (open-coded-defer.go:29) MOVB DL, ""..autotmp_24+55(SP) + +FUNCTION END, FLAG CHECKS, 这里要检查上面设置的所有的 open coded defer bits 了,可以看到与 flag 的设置顺序是相反的: + 0x0281 00641 (open-coded-defer.go:31) TESTB $32, DL + 0x0284 00644 (open-coded-defer.go:31) JNE 1011 + 0x028a 00650 (open-coded-defer.go:31) TESTB $16, DL + 0x028d 00653 (open-coded-defer.go:31) JNE 947 + 0x0293 00659 (open-coded-defer.go:31) TESTB $8, DL + 0x0296 00662 (open-coded-defer.go:31) JNE 883 + 0x029c 00668 (open-coded-defer.go:31) TESTB $4, DL + 0x029f 00671 (open-coded-defer.go:31) JNE 819 + 0x02a5 00677 (open-coded-defer.go:31) TESTB $2, DL + 0x02a8 00680 (open-coded-defer.go:31) JNE 755 + 0x02aa 00682 (open-coded-defer.go:31) TESTB $1, DL + 0x02ad 00685 (open-coded-defer.go:31) JNE 703 + 0x02af 00687 (open-coded-defer.go:31) MOVQ 344(SP), BP + 0x02b7 00695 (open-coded-defer.go:31) ADDQ $352, SP + 0x02be 00702 (open-coded-defer.go:31) RET + +DEFER 逻辑执行部分 + // defer fmt.Println("6"): + 0x02bf 00703 (open-coded-defer.go:31) ANDL $-2, DX + 0x02c2 00706 (open-coded-defer.go:31) MOVB DL, ""..autotmp_24+55(SP) + 0x02c6 00710 (open-coded-defer.go:31) MOVQ ""..autotmp_26+320(SP), AX + 0x02ce 00718 (open-coded-defer.go:31) MOVQ ""..autotmp_26+328(SP), CX + 0x02d6 00726 (open-coded-defer.go:31) MOVQ ""..autotmp_26+336(SP), DX + 0x02de 00734 (open-coded-defer.go:31) MOVQ AX, (SP) + 0x02e2 00738 (open-coded-defer.go:31) MOVQ CX, 8(SP) + 0x02e7 00743 (open-coded-defer.go:31) MOVQ DX, 16(SP) + 0x02ec 00748 (open-coded-defer.go:31) CALL fmt.Println(SB) + 0x02f1 00753 (open-coded-defer.go:31) JMP 687 + + // defer fmt.Println("5"): + 0x02f3 00755 (open-coded-defer.go:31) ANDL $-3, DX + 0x02f6 00758 (open-coded-defer.go:31) MOVB DL, ""..autotmp_37+54(SP) + 0x02fa 00762 (open-coded-defer.go:31) MOVB DL, ""..autotmp_24+55(SP) + 0x02fe 00766 (open-coded-defer.go:31) MOVQ ""..autotmp_28+312(SP), AX + 0x0306 00774 (open-coded-defer.go:31) MOVQ ""..autotmp_28+304(SP), CX + 0x030e 00782 (open-coded-defer.go:31) MOVQ ""..autotmp_28+296(SP), BX + 0x0316 00790 (open-coded-defer.go:31) MOVQ BX, (SP) + 0x031a 00794 (open-coded-defer.go:31) MOVQ CX, 8(SP) + 0x031f 00799 (open-coded-defer.go:31) MOVQ AX, 16(SP) + 0x0324 00804 (open-coded-defer.go:31) CALL fmt.Println(SB) + 0x0329 00809 (open-coded-defer.go:31) MOVBLZX ""..autotmp_37+54(SP), DX + 0x032e 00814 (open-coded-defer.go:31) JMP 682 + + // defer fmt.Println("4"): + 0x0333 00819 (open-coded-defer.go:31) ANDL $-5, DX + 0x0336 00822 (open-coded-defer.go:31) MOVB DL, ""..autotmp_37+54(SP) + 0x033a 00826 (open-coded-defer.go:31) MOVB DL, ""..autotmp_24+55(SP) + 0x033e 00830 (open-coded-defer.go:31) MOVQ ""..autotmp_30+288(SP), AX + 0x0346 00838 (open-coded-defer.go:31) MOVQ ""..autotmp_30+280(SP), CX + 0x034e 00846 (open-coded-defer.go:31) MOVQ ""..autotmp_30+272(SP), BX + 0x0356 00854 (open-coded-defer.go:31) MOVQ BX, (SP) + 0x035a 00858 (open-coded-defer.go:31) MOVQ CX, 8(SP) + 0x035f 00863 (open-coded-defer.go:31) MOVQ AX, 16(SP) + 0x0364 00868 (open-coded-defer.go:31) CALL fmt.Println(SB) + 0x0369 00873 (open-coded-defer.go:31) MOVBLZX ""..autotmp_37+54(SP), DX + 0x036e 00878 (open-coded-defer.go:31) JMP 677 + + // defer fmt.Println("3"): + 0x0373 00883 (open-coded-defer.go:31) ANDL $-9, DX + 0x0376 00886 (open-coded-defer.go:31) MOVB DL, ""..autotmp_37+54(SP) + 0x037a 00890 (open-coded-defer.go:31) MOVB DL, ""..autotmp_24+55(SP) + 0x037e 00894 (open-coded-defer.go:31) MOVQ ""..autotmp_32+264(SP), AX + 0x0386 00902 (open-coded-defer.go:31) MOVQ ""..autotmp_32+256(SP), CX + 0x038e 00910 (open-coded-defer.go:31) MOVQ ""..autotmp_32+248(SP), BX + 0x0396 00918 (open-coded-defer.go:31) MOVQ BX, (SP) + 0x039a 00922 (open-coded-defer.go:31) MOVQ CX, 8(SP) + 0x039f 00927 (open-coded-defer.go:31) MOVQ AX, 16(SP) + 0x03a4 00932 (open-coded-defer.go:31) CALL fmt.Println(SB) + 0x03a9 00937 (open-coded-defer.go:31) MOVBLZX ""..autotmp_37+54(SP), DX + 0x03ae 00942 (open-coded-defer.go:31) JMP 668 + + // defer fmt.Println("2"): + 0x03b3 00947 (open-coded-defer.go:31) ANDL $-17, DX + 0x03b6 00950 (open-coded-defer.go:31) MOVB DL, ""..autotmp_37+54(SP) + 0x03ba 00954 (open-coded-defer.go:31) MOVB DL, ""..autotmp_24+55(SP) + 0x03be 00958 (open-coded-defer.go:31) MOVQ ""..autotmp_34+224(SP), AX + 0x03c6 00966 (open-coded-defer.go:31) MOVQ ""..autotmp_34+240(SP), CX + 0x03ce 00974 (open-coded-defer.go:31) MOVQ ""..autotmp_34+232(SP), BX + 0x03d6 00982 (open-coded-defer.go:31) MOVQ AX, (SP) + 0x03da 00986 (open-coded-defer.go:31) MOVQ BX, 8(SP) + 0x03df 00991 (open-coded-defer.go:31) MOVQ CX, 16(SP) + 0x03e4 00996 (open-coded-defer.go:31) CALL fmt.Println(SB) + 0x03e9 01001 (open-coded-defer.go:31) MOVBLZX ""..autotmp_37+54(SP), DX + 0x03ee 01006 (open-coded-defer.go:31) JMP 659 + + // defer fmt.Println("1"): + 0x03f3 01011 (open-coded-defer.go:31) ANDL $-33, DX + 0x03f6 01014 (open-coded-defer.go:31) MOVB DL, ""..autotmp_37+54(SP) + 0x03fa 01018 (open-coded-defer.go:31) MOVB DL, ""..autotmp_24+55(SP) + 0x03fe 01022 (open-coded-defer.go:31) MOVQ ""..autotmp_36+216(SP), AX + 0x0406 01030 (open-coded-defer.go:31) MOVQ ""..autotmp_36+200(SP), CX + 0x040e 01038 (open-coded-defer.go:31) MOVQ ""..autotmp_36+208(SP), BX + 0x0416 01046 (open-coded-defer.go:31) MOVQ CX, (SP) + 0x041a 01050 (open-coded-defer.go:31) MOVQ BX, 8(SP) + 0x041f 01055 (open-coded-defer.go:31) MOVQ AX, 16(SP) + 0x0424 01060 (open-coded-defer.go:31) CALL fmt.Println(SB) + 0x0429 01065 (open-coded-defer.go:31) MOVBLZX ""..autotmp_37+54(SP), DX + 0x042e 01070 (open-coded-defer.go:31) JMP 650 + +如果第一个 if 不满足,会跳到这里: + 0x0433 01075 (open-coded-defer.go:31) LEAQ type.string(SB), AX + 0x043a 01082 (open-coded-defer.go:31) LEAQ fmt.Println·f(SB), CX + 0x0441 01089 (open-coded-defer.go:8) JMP 188 + +这段代码没什么用,只有在 panic 时,才可能跳到这里,但本例中无 panic + 0x0446 01094 (open-coded-defer.go:8) CALL runtime.deferreturn(SB) + 0x044b 01099 (open-coded-defer.go:8) MOVQ 344(SP), BP + 0x0453 01107 (open-coded-defer.go:8) ADDQ $352, SP + 0x045a 01114 (open-coded-defer.go:8) RET + +函数 prologue 栈检查的时候可能会跳到这里 + 0x045b 01115 (open-coded-defer.go:8) NOP + 0x045b 01115 (open-coded-defer.go:7) CALL runtime.morestack_noctxt(SB) + 0x0460 01120 (open-coded-defer.go:7) JMP 0 +``` + +整体流程还好,不过比起以前堆上分配一个 `_defer` 链表,函数执行完之后直接遍历链表还是复杂太多了。 + +超过 8 个 defer 时会退化回以前的 defer 链,也可以观察一下: + +```go +package main + +func main() { + defer println(1) + defer println(1) + defer println(1) + defer println(1) + defer println(1) + defer println(1) + defer println(1) + defer println(1) + defer println(1) + defer println(1) +} +``` + +编译出的汇编就不贴了,和以前的没什么区别。 + +结合代码分析过程和 proposal 中的描述,总结: + +* open coded defer 在函数内部总 defer 数量少于 8 时才会使用,大于 8 时会退化回老的 defer 链,这个权衡是考虑到程序文件的体积(个人觉得应该也有栈膨胀的考虑在) +* 使用 open coded defer 时,在进入函数内的每个 block 时,都会设置这个 block 相应的 bit(ORL 指令),在执行到相应的 defer 语句时,把 defer 语句的参数和调用函数地址推到栈的相应位置 +* 在栈上需要为这些 defer 调用的参数、函数地址,以及这个用来记录 defer bits 的 byte 预留空间,所以毫无疑问,函数的 framesize 会变大 + +## panic 处理部分 + +proposal 有两部分,一部分是讲 open coded defer 的实现,另一部分是说 panic 的处理,现在在函数中发生 panic 时,我们没有办法获得原来的 `_defer` 结构体了,所以必须在编译期,给每个函数准备一项 FUNCDATA,存储每一个 defer block 的地址。这样 runtime 就可以通过 FUNCDATA 和偏移找到需要执行的 defer block 在什么地方。 + +``` + 0x004a 00074 (defer.go:8) FUNCDATA $2, gclocals·951c056c1b0a4d6097d387fbe928bbbf(SB) + 0x004a 00074 (defer.go:8) FUNCDATA $3, "".main.stkobj(SB) + 0x004a 00074 (defer.go:8) FUNCDATA $5, "".main.opendefer(SB) + + .... + + "".main.opendefer SRODATA dupok size=29 + 0x0000 30 c1 01 04 30 80 01 01 60 18 00 30 78 01 48 18 0...0...`..0x.H. + 0x0010 00 30 70 01 30 18 00 30 68 01 18 18 00 .0p.0..0h.... +``` + +这里的 main.opendefer 在编译为二进制之后,可能会被优化掉。不过我们理解基本的执行流程就可以了。 + +跟踪 runtime.gopanic 的流程,可以看到现在的 defer 上有 openDefer 的 bool 值: + +``` +(dlv) p d +*runtime._defer { + siz: 48, + started: true, + heap: false, + openDefer: false, + sp: 824634391712, + pc: 17590156, + fn: *runtime.funcval {fn: 17565744}, + _panic: *runtime._panic nil, + link: *runtime._defer { + siz: 8, + started: false, + heap: true, + openDefer: true, + sp: 824634392456, + pc: 17001293, + fn: *runtime.funcval nil, + _panic: *runtime._panic nil, + link: *runtime._defer nil, + fd: unsafe.Pointer(0x10fea48), + varp: 824634392528, + framepc: 17000984,}, + fd: unsafe.Pointer(0x0), + varp: 0, + framepc: 0,} +(dlv) n +``` + +执行具体的 defer 逻辑在 runtime.runOpenDeferFrame,也没啥神奇的: + +```go +func runOpenDeferFrame(gp *g, d *_defer) bool { + done := true + fd := d.fd + + // Skip the maxargsize + _, fd = readvarintUnsafe(fd) + deferBitsOffset, fd := readvarintUnsafe(fd) + nDefers, fd := readvarintUnsafe(fd) + deferBits := *(*uint8)(unsafe.Pointer(d.varp - uintptr(deferBitsOffset))) + + for i := int(nDefers) - 1; i >= 0; i-- { + // read the funcdata info for this defer + var argWidth, closureOffset, nArgs uint32 + argWidth, fd = readvarintUnsafe(fd) + closureOffset, fd = readvarintUnsafe(fd) + nArgs, fd = readvarintUnsafe(fd) + if deferBits&(1< tgkill() sends the signal sig to the thread with the thread ID tid in the thread group tgid. (By contrast, kill(2) can be used to send a signal only to a process (i.e., thread group) as a whole, and the signal will be delivered to an arbitrary thread within that process.) + +> tkill() is an obsolete predecessor to tgkill(). It allows only the target thread ID to be specified, which may result in the wrong thread being signaled if a thread terminates and its thread ID is recycled. Avoid using this system call. + +tgkill 是 thread group kill 的缩写,可以给某个进程的某个线程发信号,在 tgkill 之前有一个不带进程 id 的 tkill,不过这个 syscall 可能会杀掉错误的进程,比如正好在发送之前,老进程被销毁,而新进程使用了同样的线程 id。也就是说现在使用的话,都是 tgkill 这个 syscall 了。 + +与 tgkill 相比,kill 则只能给进程整体发信号,信号可能被进程内的任意线程处理。平常使用比较多的 kill -9 就是使用的 kill 这个 syscall,可以用 strace 来确认: + +sudo strace kill -9 pid + +``` +... +kill(444444, SIGKILL) = -1 ESRCH (No such process) +... +``` + +### signal + +最简单的修改信号行为的 syscall 就是 signal,因为在 Go 里写裸的 signal handler 不太容易,这里用 c 来演示: + +```cpp +// https://www.geeksforgeeks.org/signals-c-language/ +#include +#include + +void handle_sigint(int sig) +{ + printf("Caught signal %d\n", sig); +} + +int main() +{ + signal(SIGINT, handle_sigint); + while (1) ; + return 0; +} +``` + +在命令行中执行该程序,每次按下 ctrl+c 都会看到有 `^CCaught signal 2` 的输出。但是 signal 这个 syscall 实在是太简单了,信号到来的时候如果有更多的可配置项和程序上下文,就可以让我们做更复杂的操作。所以才会有 sigaction 这样的稍微复杂一些的信号处理 syscall。 + +### sigaction + +用 sigaction 可以写出和用 signal 完全一致的效果: + +```cpp +#include +#include + +void handle_sigint(int sig) +{ + printf("Caught signal %d\n", sig); +} + +int main() +{ + struct sigaction act; + act.sa_handler = handle_sigint; + sigemptyset(&act.sa_mask); + act.sa_flags = 0; + sigaction(SIGINT, &act, NULL); + while (1) ; + return 0; +} +``` + +这段代码和上面的效果是一样的,每次按 ctrl+c 都会输出 `^CCaught signal 2`。 + +sigaction 的 sa_handler 和 sa_sigaction 共同组成一个 C 语言的 union 结构(在 Mac OS 上是这样,暂时没 linux 环境,凑和看吧): + +```cpp +/* union for signal handlers */ +union __sigaction_u { + void (*__sa_handler)(int); + void (*__sa_sigaction)(int, struct __siginfo *, + void *); +}; +``` + +也就是说我们想简单处理,就用 sa_handler,想做复杂些的功能就用 sa_sigaction。 + +sigaction 的三个参数: + +* int 就是 signal number +* siginfo 中包含一些信号的上下文信息,比如发送信号的进程 id,出现信号的指令地址等等。 +* void * 是一个很特殊的参数 + +### sigaltstack + +修改信号执行时所用的函数栈。 + +## 简单的信号处理函数 + +简单起见,这里我们使用 C 来做演示: + +## 执行 non-local goto + +### goto 的限制 + +goto 虽然看起来无所不能,但实际上高级语言的 goto 是跳不出函数作用域的,比如下面这样的代码就没法通过编译: + +```go +package main + +func xx() { +xx: +} + +func main() { + goto yy + goto xx +yy: +} +``` + +goto yy,没有问题,但是 goto xx 是不行的。 + +在其它语言里也一样: + +```c +#include + +void xx() { +XX: + printf("hello world"); +} + +int main() { + goto XX; + return 0; +} +``` + +### non-local goto + +``` +#include +#define __USE_GNU +#include +#include + +void myhandle(int mysignal, siginfo_t *si, void* arg) +{ + ucontext_t *context = (ucontext_t *)arg; + printf("Address from where crash happen is %x \n",context->uc_mcontext.gregs[REG_RIP]); + context->uc_mcontext.gregs[REG_RIP] = context->uc_mcontext.gregs[REG_RIP] + 0x04 ; + +} + +int main(int argc, char *argv[]) +{ + struct sigaction action; + action.sa_sigaction = &myhandle; + action.sa_flags = SA_SIGINFO; + sigaction(11,&action,NULL); + + printf("Before segfault\n"); + + int *a=NULL; + int b; + b =*a; // Here crash will hapen + + printf("I am still alive\n"); + + return 0; +} +``` + +## Go 语言中的信号式抢占 + +有了上述的储备知识,我们在看 Go 的信号式抢占前,至少知道了以下几个知识点: + +* 信号可以在任意位置打断用户代码 +* 信号的处理函数可以自定义 +* 信号的执行栈可以自定义 +* 信号执行完毕之后默认返回用户代码的下一条汇编指令继续执行 +* 可以通过修改 pc 寄存器的值,使信号处理完之后执行非本地的 goto,其实就是跳到任意的代码位置去 + +### SIGURG + +为什么选用了 SIGURG。 + +## gsignal + +gsignal 是一个特殊的 goroutine,类似 g0,每一个线程都有一个,创建的 m 的时候,就会创建好这个 gsignal,在 linux 中为 gsignal 分配 32KB 的内存: + +newm -> allocm -> mcommoninit -> mpreinit -> malg(32 * 1024) + +在线程处理信号时,会短暂地将栈从用户栈切换到 gsignal 的栈,执行 sighandler,执行完成之后,会重新切换回用户的栈继续执行用户逻辑。 + +## 流程概述 + +抢占流程主要有两个入口,GC 和 sysmon。 + +TODO,control flow pic show + +### GC 抢占流程 + +markroot -> fetch g from allgs -> suspendG -> scan g stack -> resumeG + +除了 running 以外,任何状态(如 dead,runnable,waiting)的 g 实际上都不是正在运行的 g,对于这些 g 来说,只要将其相应的字段打包返回就可以了。 + +running 状态的 g 正在系统线程上执行代码,是需要真正发送信号来抢占的。 + +### sysmon 抢占流程 + +preemptone -> asyncPreempt -> globalrunqput + +### sighandler + +```go +func sighandler(...) + if sig == sigPreempt { + doSigPreempt(gp, c) + } +} + +func doSigPreempt(gp *g, ctxt *sigctxt) { + if wantAsyncPreempt(gp) && isAsyncSafePoint(gp, ctxt.sigpc(), ctxt.sigsp(), ctxt.siglr()) { + ctxt.pushCall(funcPC(asyncPreempt)) + } +} +``` + +```go +func (c *sigctxt) pushCall(targetPC uintptr) { + // Make it look like the signaled instruction called target. + pc := uintptr(c.rip()) + sp := uintptr(c.rsp()) + sp -= sys.PtrSize + *(*uintptr)(unsafe.Pointer(sp)) = pc + c.set_rsp(uint64(sp)) + c.set_rip(uint64(targetPC)) +} +``` + +pushCall 其实就是把用户代码中即将执行的下一条指令的地址(即 pc 寄存器的值),保存在栈顶,然后 sp 寄存器下移(就是扩栈,栈从高地址向低地址增长)。 + +TODO,这里需要图 + +### 现场保存和恢复 + +在 sighandler 修改了信号返回时的 pc 寄存器,所以从 sighandler 返回之后,之前在 running 的 g 不是执行下一条指令,而是执行 pc 寄存器中保存的函数去了,这里就是 asyncPreempt。 + +asyncPreempt 是汇编实现的,分为三个部分: + +1. 将当前 g 的所有寄存器均保存在 g 的栈上 +2. 执行 asyncPreempt2 +3. 恢复 g 的所有寄存器,继续执行用户代码 + +``` +┌────────────────┐ ┌────────────────┐ +│ stack change │ │ code │ +├────────────────┴────────────────────────────────────────────────────┐ ├────────────────┴─────────────────────────────────────────────────┐ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ ┌────────────────────────┬────────────────────────┐ │ +│ │ │ │ 0x21345 │ 0x21350 │ │ +│ ┌──────────────┐ │ │ ├────────────────────────┼────────────────────────┤ │ +│ │ stack │ │ │ │ var i = 1 │ i++ │ │ +│ ├──────────────┴───────────┐ │ │ └────────────────────────┴────────────────────────┘ │ +│ │ local var 1 │ │ │ │ +│ ├──────────────────────────┤ │ │ ┌──────────────────────────┐ │ +│ │ local var 2 │ │ │ │ │ signal handler │ │ +│ ├──────────────────────────┤ │ │ │ │ │ │ +│ ┌─────┐ │ ... │ │ │ │ │ push 0x21350 to stk top │ │ +│ │ RSP │ ─────────────▶ └──────────────────────────┘ │ │ │ │ │ │ +│ └─────┘ │ │ │ │ set pc to asyncPreempt │ │ +│ │ │ │ │ │ │ +│ │ │ │ │ return │ │ +│ │ │ │ └──────────────────────────┘ │ +│ │ │ ▼ │ +│ ┌──────────────┐ │ │ │ +│ │ stack │ │ │ │ +│ ├──────────────┴───────────┐ │ │ │ +│ │ local var 1 │ │ │ ┌────────────────────────┬───────────────────────┐ │ +│ ├──────────────────────────┤ │ │ │ 0x21345 │ 0x234234234234 │ │ +│ │ local var 2 │ │ │ ├────────────────────────┼───────────────────────┤ │ +│ ├──────────────────────────┤ │ │ │ var i = 1 │ asyncPreempt() │ │ +│ │ ... │ │ │ └────────────────────────┴───────────────────────┘ │ +│ ├──────────────────────────┤ │ │ │ +│ ┌─────┐ │ 0x21350 │ │ │ │ │ +│ │ RSP │ ─────────────▶ └──────────────────────────┘ │ │ │ │ +│ └─────┘ │ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ ┌──────────────┐ │ │ │ │ +│ │ stack │ │ │ │ │ +│ ├──────────────┴───────────┐ │ │ │ │ +│ │ local var 1 │ │ │ │ │ +│ ├──────────────────────────┤ │ │ │ │ +│ │ local var 2 │ │ │ ▼ │ +│ ├──────────────────────────┤ │ │ │ +│ │ ... │ │ │ ┌────────────────────────────────┐ │ +│ ├──────────────────────────┤ │ │ │ store registers to stack │ │ +│ │ 0x21350 │ │ │ └────────────────────────────────┘ │ +│ ├──────────────────────────┤ │ │ │ +│ │ rax │ │ │ │ │ +│ ├──────────────────────────┤ │ │ │ │ +│ │ rbx │ │ │ │ │ +│ ├──────────────────────────┤ │ │ │ │ +│ ┌─────┐ │ .... │ │ │ │ │ +│ │ RSP │ ─────────────▶ └──────────────────────────┘ │ │ │ │ +│ └─────┘ │ │ ▼ │ +│ │ │ ┌───────────────────────┐ │ +│ │ │ │ asyncPreempt2() │ │ +│ │ │ └───────────────────────┘ │ +│ │ │ │ +│ ┌──────────────┐ │ │ │ │ +│ │ stack │ │ │ │ │ +│ ├──────────────┴───────────┐ │ │ │ │ +│ │ local var 1 │ │ │ │ │ +│ ├──────────────────────────┤ │ │ │ │ +│ │ local var 2 │ │ │ │ │ +│ ├──────────────────────────┤ │ │ ▼ │ +│ │ ... │ │ │ │ +│ ├──────────────────────────┤ │ │ ┌────────────────────────────────┐ │ +│ ┌─────┐ │ 0x21350 │ │ │ │ restore registers │ │ +│ │ RSP │────────────────▶ └──────────────────────────┘ │ │ └────────────────────────────────┘ │ +│ └─────┘ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ │ │ │ │ +│ ┌──────────────┐ │ │ │ │ +│ │ stack │ │ │ │ │ +│ ├──────────────┴───────────┐ │ │ │ │ +│ │ local var 1 │ │ │ │ │ +│ ├──────────────────────────┤ │ │ ▼ │ +│ │ local var 2 │ │ │ ┌────────────────────────────────┐ │ +│ ├──────────────────────────┤ │ │ │ asyncPreempt return │ │ +│ ┌─────┐ │ ... │ │ │ └────────────────────────────────┘ │ +│ │ RSP │──────────────────▶ └──────────────────────────┘ │ │ │ +│ └─────┘ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +└─────────────────────────────────────────────────────────────────────┘ └──────────────────────────────────────────────────────────────────┘ +``` + +#### 你所想的上下文切换, 不一定等于你想要的上下文切换 + +这边需要注意的是, 抢占式调度中, 是`asyncPremmpt`这个操作保存了所有寄存器的值, 而`go`内部的诸如`systemstack`、`mcall`以及包括`runtime.Gosched()`的使用等, 是不会进行所有寄存器值的保留的, 所以在一些面对一些不常见的使用场景的时候需要注意, 避免寄存器发生非预期的篡改 + +例: +```go +// test.go +package main + +import ( + "fmt" + "os" + "os/signal" + "runtime" + "syscall" + "time" +) + +//go:noescape +func setget(v int64) int64 + +//go:noescape +func set(v int64) + +func gosched() { + runtime.Gosched() +} +func main() { + _ = gosched // avoid warning + c := make(chan os.Signal, 1) + signal.Notify(c, syscall.SIGURG) + go func() { + // for debug + for { + <-c + fmt.Println("SIGURG") + } + }() + go func() { + for { + if v := setget(1); v != 1 { + fmt.Println("not equal:", v) + os.Exit(1) + } else { + fmt.Println("equal") + } + } + }() + go func() { + for { + set(2) + } + }() + time.Sleep(time.Hour) +} +``` +```assembly +//test.s +#include "textflag.h" + +TEXT ·setget(SB),NOSPLIT,$0-16 + MOVQ v+0(FP), R13 + //CALL ·gosched(SB) // runtime.Gosched() 没有进行所有寄存器现场的保留 + MOVQ R13, ret+8(FP) + RET +TEXT ·set(SB),NOSPLIT,$0-8 + MOVQ v+0(FP), R13 + RET + +``` +以上这个简短的程序实现的是内部正常调度(非抢占式)下, 调度前后寄存器异常的问题。如果想要在应用内很好控制自身协程调度的, 那么就要小心这类问题。 +## asyncPreempt2 +接下去进行的就是常规内部上下文切换`mcall` + +```go +func asyncPreempt2() { + gp := getg() + gp.asyncSafePoint = true + if gp.preemptStop { + mcall(preemptPark) + } else { + mcall(gopreempt_m) + } + gp.asyncSafePoint = false +} +``` + +## 总结 + +TODO,总览图 + +## 参考资料 + +1. The Linux Programming Interface +2. [non-cooperative goroutine preemption](https://github.com/golang/proposal/blob/master/design/24543-non-cooperative-preemption.md) +3. https://stackoverflow.com/questions/34989829/linux-signal-handling-how-to-get-address-of-interrupted-instruction diff --git a/1.14/timer.md b/1.14/timer.md new file mode 100644 index 0000000..26cd956 --- /dev/null +++ b/1.14/timer.md @@ -0,0 +1,968 @@ +# timer + +```go +type timer struct { + pp puintptr // ** 新增字段 + + when int64 + period int64 + f func(interface{}, uintptr) + arg interface{} + seq uintptr + + nextwhen int64 // ** 新增字段,表示当 timer 的状态为 timerModifiedXX 时,下一次 when 应该设置为什么值,这里的 timerModifiedXX 包含 timerModifiedEarlier 和 timerModifiedLater + + status uint32 // ** 新增字段,代表 timer 的状态,值为下面的枚举值 +} +``` + +这里原文的注释写着: + +``` +// 本文件外的代码,在使用 timer 值时应该小心 +// +// pp,status 和 nextwhen 这几个新增加的字段只能在本文件内使用 +// +// 创建 new timer 值时,只应该设置 when,period,f,arg 和 seq 这些字段 +``` + +可以看出 Go 在字段权限控制上的一些弱势,只有较粗粒度的 pub 和 private,而没有办法做文件内的权限保护(因为当前目录(pkg)下的所有文件理论上可访问该 struct 的任意字段)。 + +创建 new timer 值之后,应该将该 timer 值传给 addtimer(实际是在 time.startTimer)中调用的。 + +一个活跃的 timer (即被传给 addtimer) 可能会被传给 deltimer (time.stopTimer),这之后该 timer 便不是一个活跃的 timer。 + +在非活跃 timer 中,period,f,arg 和 seq 字段均会被修改,when 字段则不会发生修改。 + +删除一个非活跃的 timer 并让 GC 回收,这是没什么问题的。但把一个非活跃的 timer 传给 addtimer 就不 OK 了。 + +只有新创建的 timer 值才能允许传给 addtimer。 + +一个活跃的 timer 可能会传给 modtimer。其字段不会发生任何变动。该 timer 依然能够保持活跃。 + +一个非活跃的 timer 可能会被传给 resettimer 函数,被转换为一个活跃的 timer,并且会将其 when 字段进行更新。 + +新创建的 timer 也可以传给 resettimer。 + +timer 共有 addtimer,deltimer,modtimer,resettimer,cleantimers,adjusttimers 和 runtime 这些操作。 + +不允许同时调用 addtimer/deltimer/modtimer/resettimer。 + +但 adjusttimers 和 runtimer 可以同时与上述的任何操作同时调用。 + +活跃的 timer 在和 P 相关联的堆中,即 p 结构体的 timers 字段上。 + +非活跃的 timer 在被移除之前,也临时性地在 timers 堆中。 + +下面是 timer 进行各种操作时的可能状态迁移: + +// TODO, draw status migration picture +// TODO, draw status migration picture + +```go +// +// addtimer: +// timerNoStatus -> timerWaiting +// anything else -> panic: invalid value +// deltimer: +// timerWaiting -> timerDeleted +// timerModifiedXX -> timerDeleted +// timerNoStatus -> do nothing +// timerDeleted -> do nothing +// timerRemoving -> do nothing +// timerRemoved -> do nothing +// timerRunning -> wait until status changes +// timerMoving -> wait until status changes +// timerModifying -> panic: concurrent deltimer/modtimer calls +// modtimer: +// timerWaiting -> timerModifying -> timerModifiedXX +// timerModifiedXX -> timerModifying -> timerModifiedYY +// timerNoStatus -> timerWaiting +// timerRemoved -> timerWaiting +// timerRunning -> wait until status changes +// timerMoving -> wait until status changes +// timerRemoving -> wait until status changes +// timerDeleted -> panic: concurrent modtimer/deltimer calls +// timerModifying -> panic: concurrent modtimer calls +// resettimer: +// timerNoStatus -> timerWaiting +// timerRemoved -> timerWaiting +// timerDeleted -> timerModifying -> timerModifiedXX +// timerRemoving -> wait until status changes +// timerRunning -> wait until status changes +// timerWaiting -> panic: resettimer called on active timer +// timerMoving -> panic: resettimer called on active timer +// timerModifiedXX -> panic: resettimer called on active timer +// timerModifying -> panic: resettimer called on active timer +// cleantimers (looks in P's timer heap): +// timerDeleted -> timerRemoving -> timerRemoved +// timerModifiedXX -> timerMoving -> timerWaiting +// adjusttimers (looks in P's timer heap): +// timerDeleted -> timerRemoving -> timerRemoved +// timerModifiedXX -> timerMoving -> timerWaiting +// runtimer (looks in P's timer heap): +// timerNoStatus -> panic: uninitialized timer +// timerWaiting -> timerWaiting or +// timerWaiting -> timerRunning -> timerNoStatus or +// timerWaiting -> timerRunning -> timerWaiting +// timerModifying -> wait until status changes +// timerModifiedXX -> timerMoving -> timerWaiting +// timerDeleted -> timerRemoving -> timerRemoved +// timerRunning -> panic: concurrent runtimer calls +// timerRemoved -> panic: inconsistent timer heap +// timerRemoving -> panic: inconsistent timer heap +// timerMoving -> panic: inconsistent timer heap +``` + +timer 的 status 字段可能有下面这些取值: + +``` +const ( + // timer 还没有设置任何状态 + // 刚 new 出来 + timerNoStatus = iota + + // 正在等待 timer 被触发 + // 该 timer 在某个 P 的 heap 中 + timerWaiting + + // 正在运行 timer 的执行函数 + // 一个 timer 只会有很短的时间是这个状态 + timerRunning + + // timer 已被 deleted,需要进行 remove + // 不应该执行该 timer 了,不过它还在某个 P 的 heap 里 + timerDeleted + + // timer 正在被移除 + // timer 在这个状态也只会持续很短一段时间 + timerRemoving + + // timer 已被停止: + // 不在任何一个 P 的 heap 中 + timerRemoved + + // timer 正在被修改 + // 该状态也只持续很短的时间 + timerModifying + + // timer 被修改为了较早的时间 + // 新的 when 值存在 nextwhen 字段中 + // timer 在某个 P 的 heap 中,可能是错误的位置 + timerModifiedEarlier + + // timer 被修改为了相同或者较晚的时间 + // 新的 when 值存储在 nextwhen 字段中 + // timer 在某个 P 的 heap 中,可能是在错误的位置 + timerModifiedLater + + // timer 已被修改,并且正在被移动 + // timer 在这个状态也只持续很短的时间 + timerMoving +) +``` + +## time.Sleep 的实现: + +```go +//go:linkname timeSleep time.Sleep +func timeSleep(ns int64) { + if ns <= 0 { + return + } + + gp := getg() + t := gp.timer + if t == nil { + t = new(timer) + gp.timer = t + } + t.f = goroutineReady + t.arg = gp + t.nextwhen = nanotime() + ns + gopark(resetForSleep, unsafe.Pointer(t), waitReasonSleep, traceEvGoSleep, 1) +} + +// resetForSleep 在 timeSleep 流程中,goroutine 被 parked 之后,便会调用 +// 不能在 timeSleep 内直接调用 resettimer,因为如果 sleep 的参数是一个很小的时间值 +// 且有很多 goroutine 的情况下,P 可能最终会在执行 gopark 之前就直接调用 timer 对象的 f,即 goroutineReady +func resetForSleep(gp *g, ut unsafe.Pointer) bool { + t := (*timer)(ut) + resettimer(t, t.nextwhen) + return true +} +``` + +在 goroutine 被 parked 之后,会调用传入的 resetForSleep -> resettimer。 + +```go +func resettimer(t *timer, when int64) { + for { + switch s := atomic.Load(&t.status); s { + case timerNoStatus, timerRemoved: + if atomic.Cas(&t.status, s, timerWaiting) { + t.when = when + addInitializedTimer(t) + return + } + } + } + ... +} +``` + +所以流程是 time.Sleep -> gopark -> resetForSleep -> resettimer -> addInitializedTimer -> (cleantimers && doaddtimer -> wakeNetPoller)。 + +## 添加 timer 流程 + +```go +// 把 t 放进 timer heap +//go:linkname startTimer time.startTimer +func startTimer(t *timer) { + addtimer(t) +} + +// 停止一个 timer +// 返回值表示 t 是否在被 run 之前就 stop 了 +//go:linkname stopTimer time.stopTimer +func stopTimer(t *timer) bool { + return deltimer(t) +} + +// reset 一个非活跃的 timer,并把它塞进堆里 +//go:linkname resetTimer time.resetTimer +func resetTimer(t *timer, when int64) { + resettimer(t, when) +} + +// addtimer 给当前的 P 增加一个新的 timer +// 只有新创建的 timer 才应该使用该操作 +// 这样可以避免修改某个 P 的堆上的 timer 的 when 字段,以避免导致 heap 从有序变为无序 +func addtimer(t *timer) { + // when 不能是负数,否则在计算 delta 的时候可能溢出,导致其它 timer 永远不过期 + if t.when < 0 { + t.when = maxWhen + } + if t.status != timerNoStatus { + badTimer() + } + t.status = timerWaiting + + addInitializedTimer(t) +} + +// 给当前 P 增加一个已初始化的 timer +func addInitializedTimer(t *timer) { + when := t.when + + pp := getg().m.p.ptr() + lock(&pp.timersLock) + ok := cleantimers(pp) && doaddtimer(pp, t) + unlock(&pp.timersLock) + if !ok { + badTimer() + } + + wakeNetPoller(when) +} + +// 给当前的 p 添加 timer +// 调整小顶堆至合法 +func doaddtimer(pp *p, t *timer) bool { + // 新的 timer 依赖于 network poller,所以需要确保 poller 已经被启动了 + if netpollInited == 0 { + netpollGenericInit() + } + + if t.pp != 0 { + throw("doaddtimer: P already set in timer") + } + t.pp.set(pp) + i := len(pp.timers) + pp.timers = append(pp.timers, t) + return siftupTimer(pp.timers, i) +} +``` + +## 删除 timer 流程 + +```go +// 删除 timer t,这个 t 可能在别的 P 上,所以我们不能直接从 timer 堆中移除它。只能将其置为 deleted 状态。 +// 在合适的时间,该 timer 会被其所在的 P 的的堆上被删除 +// 本函数的返回值表示该 timer 是否在被运行之前移除了 +func deltimer(t *timer) bool { + for { + switch s := atomic.Load(&t.status); s { + case timerWaiting, timerModifiedLater: + if atomic.Cas(&t.status, s, timerDeleted) { + // Timer was not yet run. + return true + } + case timerModifiedEarlier: + tpp := t.pp.ptr() + if atomic.Cas(&t.status, s, timerModifying) { + atomic.Xadd(&tpp.adjustTimers, -1) + if !atomic.Cas(&t.status, timerModifying, timerDeleted) { + badTimer() + } + // Timer was not yet run. + return true + } + case timerDeleted, timerRemoving, timerRemoved: + // Timer was already run. + return false + case timerRunning, timerMoving: + // The timer is being run or moved, by a different P. + // Wait for it to complete. + osyield() + case timerNoStatus: + // Removing timer that was never added or + // has already been run. Also see issue 21874. + return false + case timerModifying: + // Simultaneous calls to deltimer and modtimer. + badTimer() + default: + badTimer() + } + } +} + +// 从其所在的 P 的堆上,删除第 i 个 timer。 +// 本函数调用之前会被锁定在 P 上 +// 函数返回值表示是否有因为 race 导致的问题 +// 本函数需要由 caller 确保 pp 对 timers 的锁已经加好了 +func dodeltimer(pp *p, i int) bool { + if t := pp.timers[i]; t.pp.ptr() != pp { + throw("dodeltimer: wrong P") + } else { + t.pp = 0 + } + last := len(pp.timers) - 1 + if i != last { + pp.timers[i] = pp.timers[last] + } + pp.timers[last] = nil + pp.timers = pp.timers[:last] + ok := true + if i != last { + // Moving to i may have moved the last timer to a new parent, + // so sift up to preserve the heap guarantee. + if !siftupTimer(pp.timers, i) { + ok = false + } + if !siftdownTimer(pp.timers, i) { + ok = false + } + } + return ok +} + +// 删除 P 的 timer 堆上的第 0 个 timer +// 调用该函数时,需要锁定至 P +// 返回值表示是否有 race 问题 +// caller 必须确保 pp 已对 timers 上了锁 +func dodeltimer0(pp *p) bool { + if t := pp.timers[0]; t.pp.ptr() != pp { + throw("dodeltimer0: wrong P") + } else { + t.pp = 0 + } + last := len(pp.timers) - 1 + if last > 0 { + pp.timers[0] = pp.timers[last] + } + pp.timers[last] = nil + pp.timers = pp.timers[:last] + ok := true + if last > 0 { + ok = siftdownTimer(pp.timers, 0) + } + return ok +} +``` + +```go +// 修改已经存在的 timer +// 该函数被 netpoll 代码所调用 +func modtimer(t *timer, when, period int64, f func(interface{}, uintptr), arg interface{}, seq uintptr) { + if when < 0 { + when = maxWhen + } + + status := uint32(timerNoStatus) + wasRemoved := false +loop: + for { + switch status = atomic.Load(&t.status); status { + case timerWaiting, timerModifiedEarlier, timerModifiedLater: + if atomic.Cas(&t.status, status, timerModifying) { + break loop + } + case timerNoStatus, timerRemoved: + // Timer was already run and t is no longer in a heap. + // Act like addtimer. + if atomic.Cas(&t.status, status, timerWaiting) { + wasRemoved = true + break loop + } + case timerRunning, timerRemoving, timerMoving: + // The timer is being run or moved, by a different P. + // Wait for it to complete. + osyield() + case timerDeleted: + // Simultaneous calls to modtimer and deltimer. + badTimer() + case timerModifying: + // Multiple simultaneous calls to modtimer. + badTimer() + default: + badTimer() + } + } + + t.period = period + t.f = f + t.arg = arg + t.seq = seq + + if wasRemoved { + t.when = when + addInitializedTimer(t) + } else { + // The timer is in some other P's heap, so we can't change + // the when field. If we did, the other P's heap would + // be out of order. So we put the new when value in the + // nextwhen field, and let the other P set the when field + // when it is prepared to resort the heap. + t.nextwhen = when + + newStatus := uint32(timerModifiedLater) + if when < t.when { + newStatus = timerModifiedEarlier + } + + // Update the adjustTimers field. Subtract one if we + // are removing a timerModifiedEarlier, add one if we + // are adding a timerModifiedEarlier. + tpp := t.pp.ptr() + adjust := int32(0) + if status == timerModifiedEarlier { + adjust-- + } + if newStatus == timerModifiedEarlier { + adjust++ + } + if adjust != 0 { + atomic.Xadd(&tpp.adjustTimers, adjust) + } + + // Set the new status of the timer. + if !atomic.Cas(&t.status, timerModifying, newStatus) { + badTimer() + } + + // If the new status is earlier, wake up the poller. + if newStatus == timerModifiedEarlier { + wakeNetPoller(when) + } + } +} +``` + +```go +// 该函数将已存在的非活跃 timer 进行重置,并将其变为一个活跃的 timer +// 同时给该 timer 设置新的触发时间 +// 如果某个 timer 已经或者可能已经被使用过了,就不要使用 addtimer,而应该使用这个函数 +func resettimer(t *timer, when int64) { + if when < 0 { + when = maxWhen + } + + for { + switch s := atomic.Load(&t.status); s { + case timerNoStatus, timerRemoved: + if atomic.Cas(&t.status, s, timerWaiting) { + t.when = when + addInitializedTimer(t) + return + } + case timerDeleted: + if atomic.Cas(&t.status, s, timerModifying) { + t.nextwhen = when + newStatus := uint32(timerModifiedLater) + if when < t.when { + newStatus = timerModifiedEarlier + atomic.Xadd(&t.pp.ptr().adjustTimers, 1) + } + if !atomic.Cas(&t.status, timerModifying, newStatus) { + badTimer() + } + if newStatus == timerModifiedEarlier { + wakeNetPoller(when) + } + return + } + case timerRemoving: + // 等待移除完毕就行了 + osyield() + case timerRunning: + // 即使 timer 不应该活跃,也可能因为 timer function + // 允许其它 goroutine 调用 resettimer 而导致看到 timerRunning 这个状态 + // 这时候应该等待 timer function 运行完毕 + osyield() + case timerWaiting, timerModifying, timerModifiedEarlier, timerModifiedLater, timerMoving: + // Called resettimer on active timer. + badTimer() + default: + badTimer() + } + } +} + +``` + +```go +// cleantimers 会删除 timer 队列头部的那些 timer。这样会加快程序创建和删除 timer 的速度;如果将 timer 保留在堆上的话会使 addtimer 变慢。 +// 函数返回值表示是否碰到了 timer 问题(错误 +// 调用该函数前 caller 需要保证 pp 已经对 timers 上了锁 +func cleantimers(pp *p) bool { + for { + if len(pp.timers) == 0 { + return true + } + t := pp.timers[0] + if t.pp.ptr() != pp { + throw("cleantimers: bad p") + } + switch s := atomic.Load(&t.status); s { + case timerDeleted: + if !atomic.Cas(&t.status, s, timerRemoving) { + continue + } + if !dodeltimer0(pp) { + return false + } + if !atomic.Cas(&t.status, timerRemoving, timerRemoved) { + return false + } + case timerModifiedEarlier, timerModifiedLater: + if !atomic.Cas(&t.status, s, timerMoving) { + continue + } + // Now we can change the when field. + t.when = t.nextwhen + // Move t to the right position. + if !dodeltimer0(pp) { + return false + } + if !doaddtimer(pp, t) { + return false + } + if s == timerModifiedEarlier { + atomic.Xadd(&pp.adjustTimers, -1) + } + if !atomic.Cas(&t.status, timerMoving, timerWaiting) { + return false + } + default: + // timer 堆的头部不需要进行调整 + return true + } + } +} +``` + +```go +// 移动一个 timer 切片到 pp。该切片中的 timers 是从另外的 P 中获取到的 +// 当前该函数在 STW 期间调用,不过 caller 还是应该锁住 pp 中的 timers lock +func moveTimers(pp *p, timers []*timer) { + for _, t := range timers { + loop: + for { + switch s := atomic.Load(&t.status); s { + case timerWaiting: + t.pp = 0 + if !doaddtimer(pp, t) { + badTimer() + } + break loop + case timerModifiedEarlier, timerModifiedLater: + if !atomic.Cas(&t.status, s, timerMoving) { + continue + } + t.when = t.nextwhen + t.pp = 0 + if !doaddtimer(pp, t) { + badTimer() + } + if !atomic.Cas(&t.status, timerMoving, timerWaiting) { + badTimer() + } + break loop + case timerDeleted: + if !atomic.Cas(&t.status, s, timerRemoved) { + continue + } + t.pp = 0 + // We no longer need this timer in the heap. + break loop + case timerModifying: + // 循环一直到完成修改操作 + osyield() + case timerNoStatus, timerRemoved: + // 理论上不应该在时间堆上看到这两个状态 + // nostatus 是初始化的时候的默认状态,是入堆前的状态 + // removed 是移除之后的状态,在堆之外 + badTimer() + case timerRunning, timerRemoving, timerMoving: + // 有其它 P 认为他们持有该 timer + // 从原理上讲不应该 + badTimer() + default: + badTimer() + } + } + } +} +``` + +```go +// adjusttimers looks through the timers in the current P's heap for +// any timers that have been modified to run earlier, and puts them in +// the correct place in the heap. While looking for those timers, +// it also moves timers that have been modified to run later, +// and removes deleted timers. The caller must have locked the timers for pp. +func adjusttimers(pp *p) { + if len(pp.timers) == 0 { + return + } + if atomic.Load(&pp.adjustTimers) == 0 { + return + } + var moved []*timer + for i := 0; i < len(pp.timers); i++ { + t := pp.timers[i] + if t.pp.ptr() != pp { + throw("adjusttimers: bad p") + } + switch s := atomic.Load(&t.status); s { + case timerDeleted: + if atomic.Cas(&t.status, s, timerRemoving) { + if !dodeltimer(pp, i) { + badTimer() + } + if !atomic.Cas(&t.status, timerRemoving, timerRemoved) { + badTimer() + } + // Look at this heap position again. + i-- + } + case timerModifiedEarlier, timerModifiedLater: + if atomic.Cas(&t.status, s, timerMoving) { + // Now we can change the when field. + t.when = t.nextwhen + // Take t off the heap, and hold onto it. + // We don't add it back yet because the + // heap manipulation could cause our + // loop to skip some other timer. + if !dodeltimer(pp, i) { + badTimer() + } + moved = append(moved, t) + if s == timerModifiedEarlier { + if n := atomic.Xadd(&pp.adjustTimers, -1); int32(n) <= 0 { + addAdjustedTimers(pp, moved) + return + } + } + } + case timerNoStatus, timerRunning, timerRemoving, timerRemoved, timerMoving: + badTimer() + case timerWaiting: + // OK, nothing to do. + case timerModifying: + // Check again after modification is complete. + osyield() + i-- + default: + badTimer() + } + } + + if len(moved) > 0 { + addAdjustedTimers(pp, moved) + } +} + +// addAdjustedTimers adds any timers we adjusted in adjusttimers +// back to the timer heap. +func addAdjustedTimers(pp *p, moved []*timer) { + for _, t := range moved { + if !doaddtimer(pp, t) { + badTimer() + } + if !atomic.Cas(&t.status, timerMoving, timerWaiting) { + badTimer() + } + } +} + +``` + +```go +// nobarrierWakeTime looks at P's timers and returns the time when we +// should wake up the netpoller. It returns 0 if there are no timers. +// This function is invoked when dropping a P, and must run without +// any write barriers. Therefore, if there are any timers that needs +// to be moved earlier, it conservatively returns the current time. +// The netpoller M will wake up and adjust timers before sleeping again. +//go:nowritebarrierrec +func nobarrierWakeTime(pp *p) int64 { + lock(&pp.timersLock) + ret := int64(0) + if len(pp.timers) > 0 { + if atomic.Load(&pp.adjustTimers) > 0 { + ret = nanotime() + } else { + ret = pp.timers[0].when + } + } + unlock(&pp.timersLock) + return ret +} +``` + +```go +// runtimer examines the first timer in timers. If it is ready based on now, +// it runs the timer and removes or updates it. +// Returns 0 if it ran a timer, -1 if there are no more timers, or the time +// when the first timer should run. +// The caller must have locked the timers for pp. +// If a timer is run, this will temporarily unlock the timers. +//go:systemstack +func runtimer(pp *p, now int64) int64 { + for { + t := pp.timers[0] + if t.pp.ptr() != pp { + throw("runtimer: bad p") + } + switch s := atomic.Load(&t.status); s { + case timerWaiting: + if t.when > now { + // Not ready to run. + return t.when + } + + if !atomic.Cas(&t.status, s, timerRunning) { + continue + } + // Note that runOneTimer may temporarily unlock + // pp.timersLock. + runOneTimer(pp, t, now) + return 0 + + case timerDeleted: + if !atomic.Cas(&t.status, s, timerRemoving) { + continue + } + if !dodeltimer0(pp) { + badTimer() + } + if !atomic.Cas(&t.status, timerRemoving, timerRemoved) { + badTimer() + } + if len(pp.timers) == 0 { + return -1 + } + + case timerModifiedEarlier, timerModifiedLater: + if !atomic.Cas(&t.status, s, timerMoving) { + continue + } + t.when = t.nextwhen + if !dodeltimer0(pp) { + badTimer() + } + if !doaddtimer(pp, t) { + badTimer() + } + if s == timerModifiedEarlier { + atomic.Xadd(&pp.adjustTimers, -1) + } + if !atomic.Cas(&t.status, timerMoving, timerWaiting) { + badTimer() + } + + case timerModifying: + // Wait for modification to complete. + osyield() + + case timerNoStatus, timerRemoved: + // Should not see a new or inactive timer on the heap. + badTimer() + case timerRunning, timerRemoving, timerMoving: + // These should only be set when timers are locked, + // and we didn't do it. + badTimer() + default: + badTimer() + } + } +} +``` + +```go +// 运行一个独立的 timer +// caller 必须让 pp 对 timers 上锁 +// 在运行 timer 函数时会临时将 timers 的锁 unlock 掉 +//go:systemstack +func runOneTimer(pp *p, t *timer, now int64) { + f := t.f + arg := t.arg + seq := t.seq + + if t.period > 0 { + // Leave in heap but adjust next time to fire. + delta := t.when - now + t.when += t.period * (1 + -delta/t.period) + if !siftdownTimer(pp.timers, 0) { + badTimer() + } + if !atomic.Cas(&t.status, timerRunning, timerWaiting) { + badTimer() + } + } else { + // Remove from heap. + if !dodeltimer0(pp) { + badTimer() + } + if !atomic.Cas(&t.status, timerRunning, timerNoStatus) { + badTimer() + } + } + + unlock(&pp.timersLock) + + f(arg, seq) + + lock(&pp.timersLock) + +} +``` + +```go +func timejump() *p { + if faketime == 0 { + return nil + } + + // Nothing is running, so we can look at all the P's. + // Determine a timer bucket with minimum when. + var ( + minT *timer + minWhen int64 + minP *p + ) + for _, pp := range allp { + if pp.status != _Pidle && pp.status != _Pdead { + throw("non-idle P in timejump") + } + if len(pp.timers) == 0 { + continue + } + c := pp.adjustTimers + for _, t := range pp.timers { + switch s := atomic.Load(&t.status); s { + case timerWaiting: + if minT == nil || t.when < minWhen { + minT = t + minWhen = t.when + minP = pp + } + case timerModifiedEarlier, timerModifiedLater: + if minT == nil || t.nextwhen < minWhen { + minT = t + minWhen = t.nextwhen + minP = pp + } + if s == timerModifiedEarlier { + c-- + } + case timerRunning, timerModifying, timerMoving: + badTimer() + } + // The timers are sorted, so we only have to check + // the first timer for each P, unless there are + // some timerModifiedEarlier timers. The number + // of timerModifiedEarlier timers is in the adjustTimers + // field, used to initialize c, above. + if c == 0 { + break + } + } + } + + if minT == nil || minWhen <= faketime { + return nil + } + + faketime = minWhen + return minP +} + +// timeSleepUntil returns the time when the next timer should fire. +// This is only called by sysmon. +func timeSleepUntil() int64 { + next := int64(maxWhen) + + // Prevent allp slice changes. This is like retake. + lock(&allpLock) + for _, pp := range allp { + if pp == nil { + // This can happen if procresize has grown + // allp but not yet created new Ps. + continue + } + + lock(&pp.timersLock) + c := atomic.Load(&pp.adjustTimers) + for _, t := range pp.timers { + switch s := atomic.Load(&t.status); s { + case timerWaiting: + if t.when < next { + next = t.when + } + case timerModifiedEarlier, timerModifiedLater: + if t.nextwhen < next { + next = t.nextwhen + } + if s == timerModifiedEarlier { + c-- + } + } + // The timers are sorted, so we only have to check + // the first timer for each P, unless there are + // some timerModifiedEarlier timers. The number + // of timerModifiedEarlier timers is in the adjustTimers + // field, used to initialize c, above. + // + // We don't worry about cases like timerModifying. + // New timers can show up at any time, + // so this function is necessarily imprecise. + // Do a signed check here since we aren't + // synchronizing the read of pp.adjustTimers + // with the check of a timer status. + if int32(c) <= 0 { + break + } + } + unlock(&pp.timersLock) + } + unlock(&allpLock) + + return next +} +``` + +siftUpTimer 和 siftDownTimer 这两个函数的实现和以前没什么不同,只是去除了冗余的 index 赋值操作。 diff --git a/assembly.md b/assembly.md index 73232b7..474251c 100644 --- a/assembly.md +++ b/assembly.md @@ -10,7 +10,7 @@ ### 栈调整 -intel 或 AT&T 汇编提供了 push 和 pop 指令族,plan9 中没有 push 和 pop,栈的调整是通过对硬件 SP 寄存器进行运算来实现的,例如: +intel 或 AT&T 汇编提供了 push 和 pop 指令族,~~plan9 中没有 push 和 pop~~,plan9 中虽然有 push 和 pop 指令,但一般生成的代码中是没有的,我们看到的栈的调整大多是通过对硬件 SP 寄存器进行运算来实现的,例如: ```go SUBQ $0x18, SP // 对 SP 做减法,为函数分配函数栈帧 @@ -135,7 +135,7 @@ Go 的汇编还引入了 4 个伪寄存器,援引官方文档的描述: >- `FP`: Frame pointer: arguments and locals. >- `PC`: Program counter: jumps and branches. >- `SB`: Static base pointer: global symbols. ->- `SP`: Stack pointer: top of stack. +>- `SP`: Stack pointer: the highest address within the local stack frame. 官方的描述稍微有一些问题,我们对这些说明进行一点扩充: @@ -152,7 +152,7 @@ Go 的汇编还引入了 4 个伪寄存器,援引官方文档的描述: 4. 在 go tool objdump/go tool compile -S 输出的代码中,是没有伪 SP 和 FP 寄存器的,我们上面说的区分伪 SP 和硬件 SP 寄存器的方法,对于上述两个命令的输出结果是没法使用的。在编译和反汇编的结果中,只有真实的 SP 寄存器。 5. FP 和 Go 的官方源代码里的 framepointer 不是一回事,源代码里的 framepointer 指的是 caller BP 寄存器的值,在这里和 caller 的伪 SP 是值是相等的。 -以上说明看不懂也没关系,在熟悉了函数的栈结构之后再反复回来查看应该就可以明白了。个人意见,这些是 Go 官方挖的坑。。 +以上说明看不懂也没关系,在熟悉了函数的栈结构之后再反复回来查看应该就可以明白了。 ## 变量声明 @@ -258,7 +258,7 @@ TEXT ·get(SB), NOSPLIT, $0-8 // => 只有函数头,没有实现 TEXT pkgname·add(SB), NOSPLIT, $0-8 MOVQ a+0(FP), AX - MOVQ a+8(FP), BX + MOVQ b+8(FP), BX ADDQ AX, BX MOVQ BX, ret+16(FP) RET @@ -607,7 +607,7 @@ output.s: #include "textflag.h" // func output(a,b int) int -TEXT ·output(SB), NOSPLIT, $24-8 +TEXT ·output(SB), NOSPLIT, $24-24 MOVQ a+0(FP), DX // arg a MOVQ DX, 0(SP) // arg x MOVQ b+8(FP), CX // arg b @@ -999,11 +999,5 @@ go compile -S: 参考资料[4]需要特别注意,在该 slide 中给出的 callee stack frame 中把 caller 的 return address 也包含进去了,个人认为不是很合适。 + - - diff --git a/atomic.md b/atomic.md new file mode 100644 index 0000000..ed3e9c4 --- /dev/null +++ b/atomic.md @@ -0,0 +1,364 @@ +# atomic 详解 +> golang 中 atomic 类操作最终是使用 assembly 进行 cpu 指令调用实现的。本章将会对相应 api 及对应 assembly 进行分析 +> 本章所有函数分析均以 amd64 架构为例 + +sync/atomic/doc.go +```go +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// Package atomic provides low-level atomic memory primitives +// useful for implementing synchronization algorithms. +// +// These functions require great care to be used correctly. +// Except for special, low-level applications, synchronization is better +// done with channels or the facilities of the sync package. +// Share memory by communicating; +// don't communicate by sharing memory. +// +// The swap operation, implemented by the SwapT functions, is the atomic +// equivalent of: +// +// old = *addr +// *addr = new +// return old +// +// The compare-and-swap operation, implemented by the CompareAndSwapT +// functions, is the atomic equivalent of: +// +// if *addr == old { +// *addr = new +// return true +// } +// return false +// +// The add operation, implemented by the AddT functions, is the atomic +// equivalent of: +// +// *addr += delta +// return *addr +// +// The load and store operations, implemented by the LoadT and StoreT +// functions, are the atomic equivalents of "return *addr" and +// "*addr = val". +// +package atomic + +import ( + "unsafe" +) + +// BUG(rsc): On x86-32, the 64-bit functions use instructions unavailable before the Pentium MMX. +// +// On non-Linux ARM, the 64-bit functions use instructions unavailable before the ARMv6k core. +// +// On ARM, x86-32, and 32-bit MIPS, +// it is the caller's responsibility to arrange for 64-bit +// alignment of 64-bit words accessed atomically. The first word in a +// variable or in an allocated struct, array, or slice can be relied upon to be +// 64-bit aligned. + +// SwapInt32 atomically stores new into *addr and returns the previous *addr value. +func SwapInt32(addr *int32, new int32) (old int32) + +// SwapInt64 atomically stores new into *addr and returns the previous *addr value. +func SwapInt64(addr *int64, new int64) (old int64) + +// SwapUint32 atomically stores new into *addr and returns the previous *addr value. +func SwapUint32(addr *uint32, new uint32) (old uint32) + +// SwapUint64 atomically stores new into *addr and returns the previous *addr value. +func SwapUint64(addr *uint64, new uint64) (old uint64) + +// SwapUintptr atomically stores new into *addr and returns the previous *addr value. +func SwapUintptr(addr *uintptr, new uintptr) (old uintptr) + +// SwapPointer atomically stores new into *addr and returns the previous *addr value. +func SwapPointer(addr *unsafe.Pointer, new unsafe.Pointer) (old unsafe.Pointer) + +// CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value. +func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool) + +// CompareAndSwapInt64 executes the compare-and-swap operation for an int64 value. +func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool) + +// CompareAndSwapUint32 executes the compare-and-swap operation for a uint32 value. +func CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool) + +// CompareAndSwapUint64 executes the compare-and-swap operation for a uint64 value. +func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool) + +// CompareAndSwapUintptr executes the compare-and-swap operation for a uintptr value. +func CompareAndSwapUintptr(addr *uintptr, old, new uintptr) (swapped bool) + +// CompareAndSwapPointer executes the compare-and-swap operation for a unsafe.Pointer value. +func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool) + +// AddInt32 atomically adds delta to *addr and returns the new value. +func AddInt32(addr *int32, delta int32) (new int32) + +// AddUint32 atomically adds delta to *addr and returns the new value. +// To subtract a signed positive constant value c from x, do AddUint32(&x, ^uint32(c-1)). +// In particular, to decrement x, do AddUint32(&x, ^uint32(0)). +func AddUint32(addr *uint32, delta uint32) (new uint32) + +// AddInt64 atomically adds delta to *addr and returns the new value. +func AddInt64(addr *int64, delta int64) (new int64) + +// AddUint64 atomically adds delta to *addr and returns the new value. +// To subtract a signed positive constant value c from x, do AddUint64(&x, ^uint64(c-1)). +// In particular, to decrement x, do AddUint64(&x, ^uint64(0)). +func AddUint64(addr *uint64, delta uint64) (new uint64) + +// AddUintptr atomically adds delta to *addr and returns the new value. +func AddUintptr(addr *uintptr, delta uintptr) (new uintptr) + +// LoadInt32 atomically loads *addr. +func LoadInt32(addr *int32) (val int32) + +// LoadInt64 atomically loads *addr. +func LoadInt64(addr *int64) (val int64) + +// LoadUint32 atomically loads *addr. +func LoadUint32(addr *uint32) (val uint32) + +// LoadUint64 atomically loads *addr. +func LoadUint64(addr *uint64) (val uint64) + +// LoadUintptr atomically loads *addr. +func LoadUintptr(addr *uintptr) (val uintptr) + +// LoadPointer atomically loads *addr. +func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer) + +// StoreInt32 atomically stores val into *addr. +func StoreInt32(addr *int32, val int32) + +// StoreInt64 atomically stores val into *addr. +func StoreInt64(addr *int64, val int64) + +// StoreUint32 atomically stores val into *addr. +func StoreUint32(addr *uint32, val uint32) + +// StoreUint64 atomically stores val into *addr. +func StoreUint64(addr *uint64, val uint64) + +// StoreUintptr atomically stores val into *addr. +func StoreUintptr(addr *uintptr, val uintptr) + +// StorePointer atomically stores val into *addr. +func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer) + +// Helper for ARM. Linker will discard on other systems +func panic64() { + panic("sync/atomic: broken 64-bit atomic operations (buggy QEMU)") +} + +``` +> go 文件内只进行了函数的定义,具体实现为在 asm 文件中 + +sync/atomic/asm.s +```assembly +// Copyright 2011 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !race + +#include "textflag.h" + +TEXT ·SwapInt32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xchg(SB) + +TEXT ·SwapUint32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xchg(SB) + +TEXT ·SwapInt64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xchg64(SB) + +TEXT ·SwapUint64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xchg64(SB) + +TEXT ·SwapUintptr(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xchguintptr(SB) + +TEXT ·CompareAndSwapInt32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Cas(SB) + +TEXT ·CompareAndSwapUint32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Cas(SB) + +TEXT ·CompareAndSwapUintptr(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Casuintptr(SB) + +TEXT ·CompareAndSwapInt64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Cas64(SB) + +TEXT ·CompareAndSwapUint64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Cas64(SB) + +TEXT ·AddInt32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xadd(SB) + +TEXT ·AddUint32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xadd(SB) + +TEXT ·AddUintptr(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xadduintptr(SB) + +TEXT ·AddInt64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xadd64(SB) + +TEXT ·AddUint64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Xadd64(SB) + +TEXT ·LoadInt32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Load(SB) + +TEXT ·LoadUint32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Load(SB) + +TEXT ·LoadInt64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Load64(SB) + +TEXT ·LoadUint64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Load64(SB) + +TEXT ·LoadUintptr(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Loaduintptr(SB) + +TEXT ·LoadPointer(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Loadp(SB) + +TEXT ·StoreInt32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Store(SB) + +TEXT ·StoreUint32(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Store(SB) + +TEXT ·StoreInt64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Store64(SB) + +TEXT ·StoreUint64(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Store64(SB) + +TEXT ·StoreUintptr(SB),NOSPLIT,$0 + JMP runtime∕internal∕atomic·Storeuintptr(SB) + +``` +可以看到这边函数的实现仅为 JMP 跳转指令,统一跳转到 runtime/internal/atomic 下的各个函数进行 + + +runtime/internal/atomic/stubs.go +```go +// Copyright 2015 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// +build !wasm + +package atomic + +import "unsafe" + +//go:noescape +func Cas(ptr *uint32, old, new uint32) bool + +// NO go:noescape annotation; see atomic_pointer.go. +func Casp1(ptr *unsafe.Pointer, old, new unsafe.Pointer) bool + +//go:noescape +func Casuintptr(ptr *uintptr, old, new uintptr) bool + +//go:noescape +func Storeuintptr(ptr *uintptr, new uintptr) + +//go:noescape +func Loaduintptr(ptr *uintptr) uintptr + +//go:noescape +func Loaduint(ptr *uint) uint + +// TODO(matloob): Should these functions have the go:noescape annotation? + +//go:noescape +func Loadint64(ptr *int64) int64 + +//go:noescape +func Xaddint64(ptr *int64, delta int64) int64 + +``` +#### func Cas(ptr *uint32, old, new uint32) bool +- 入参为 uint32 指针,旧值,新值 +- 返回值为是否 cas 成功 + +go 文件内同样只进行了函数的定义,具体实现为在各平台的 asm 文件中: + +runtime/internal/atomic/asm_amd64.s +```assembly +TEXT runtime∕internal∕atomic·Cas(SB),NOSPLIT,$0-17 // 17 = sizeof(*uint32 + sizeof(uint32) + sizeof(uint32) + sizeof(uint8/bool)) + MOVQ ptr+0(FP), BX // 入参 1 ,8 字节 uint32 指针 + MOVL old+8(FP), AX // 入参 2 ,4 字节 uint32 + MOVL new+12(FP), CX // 入参 3 ,4 字节 uint32 + LOCK // lock 指令前缀 + /* + * CMPXCHGL r, [m] + * if AX == [m] { + * ZF = 1; + * [m] = r; + * } else { + * ZF = 0; + * AX = [m]; + * } + */ + CMPXCHGL CX, 0(BX) // 比较并交换指令, ZF set to 1 if success + SETEQ ret+16(FP) // 1 if ZF set to 1 + RET +``` +> ZF: 标志寄存器的一种,零标志:用于判断结果是否为0。运算结果0,ZF置1,否则置0。 + +#### func SwapInt32(addr *int32, new int32) (old int32) +> cmd/compile/internal/gc/ssa.go +> alias("sync/atomic", "SwapInt32", "runtime/internal/atomic", "Xchg", all...) +> 以上可知 SwapInt32 函数为 runtime/internal/atomic·Xchg 函数的一个别名。 + +runtime/internal/atomic/asm_amd64.s +```assembly +TEXT runtime∕internal∕atomic·Xchg(SB), NOSPLIT, $0-20 + MOVQ ptr+0(FP), BX + MOVL new+8(FP), AX + XCHGL AX, 0(BX) // 交换指令 + MOVL AX, ret+16(FP) // 交换后的 AX(old value) 写入 FP 返回值位 + RET +``` + +#### func AddInt32(addr *int32, new int32) (old int32) +> alias("sync/atomic", "AddInt32", "runtime/internal/atomic", "Xadd", all...) + +runtime/internal/atomic/asm_amd64.s +```assembly +TEXT runtime∕internal∕atomic·Xadd(SB), NOSPLIT, $0-20 + MOVQ ptr+0(FP), BX + MOVL delta+8(FP), AX + MOVL AX, CX + LOCK + XADDL AX, 0(BX) // Exchange and Add + ADDL CX, AX // AX += CX + MOVL AX, ret+16(FP) + RET +``` +#### func StoreInt32(addr *int32, val int32) +> alias("sync/atomic", "StoreInt32", "runtime/internal/atomic", "Store", all...) + +runtime/internal/atomic/asm_amd64.s + +```assembly +TEXT runtime∕internal∕atomic·Store(SB), NOSPLIT, $0-12 + MOVQ ptr+0(FP), BX + MOVL val+8(FP), AX + XCHGL AX, 0(BX) // 交换指令 + RET +``` + + diff --git a/bootstrap.md b/bootstrap.md index f058f98..20337a6 100644 --- a/bootstrap.md +++ b/bootstrap.md @@ -518,4 +518,6 @@ func main() { \ No newline at end of file +--> + + diff --git a/channel.md b/channel.md index 5178613..a31d9e3 100644 --- a/channel.md +++ b/channel.md @@ -305,7 +305,7 @@ func chansend(c *hchan, ep unsafe.Pointer, block bool, callerpc uintptr) bool { } // qcount 是 buffer 中已塞进的元素数量 - // dataqsize 是 buffer 的总大小 + // dataqsiz 是 buffer 的总大小 // 说明还有余量 if c.qcount < c.dataqsiz { // Space is available in the channel buffer. Enqueue the element to send. @@ -704,4 +704,7 @@ func closechan(c *hchan) { Q: 如果有多个channel同时唤醒同一个goroutine,这个并发控制是怎么做的? -A: TODO +Q: 为什么向 channel 发数据的时候,会直接把数据从一个 goroutine 的栈拷贝到另一个 goroutine 的栈? + + + diff --git a/code/empty.go b/code/empty.go new file mode 100644 index 0000000..38dd16d --- /dev/null +++ b/code/empty.go @@ -0,0 +1,3 @@ +package main + +func main() {} diff --git a/compilers.md b/compilers.md new file mode 100644 index 0000000..f9ab2f0 --- /dev/null +++ b/compilers.md @@ -0,0 +1,1247 @@ +# 编译原理 +> 本文主要介绍编译的几个主要过程及周边工具的使用, 对于工具内部具体实现的算法不做分析, 感兴趣的可自行搜索 + +## 词法分析 + +```mermaid +sequenceDiagram + Source code->>Token stream: Lexical analysis + Note left of Source code: 1 + (2 - 3) * 4 / 5 + Note left of Source code: SELECT * FROM TABLE1 LIMIT 1; + Note left of Source code: {"key1": 1, "key2": "val", "key3": {}} + #------ + Note right of Token stream: 1
+
(
2
-
3
)
*
4
/
5 + Note right of Token stream: SELECT
*
FROM
TABLE1
LIMIT
1
; + Note right of Token stream: {
"key1"
:
1
,
"key2"
:
"val"
,
"key3"
:
{
,
}
,
}
+``` + +第一步将源代码处理成为`token stream`, 这边的源代码可以是一段简单的`go`代码, `DML`, `DSL`, 甚至是`JSON`格式的文件或者其他文本内容等等, `Lexical analysis`的目的就是按照某个定义规则将文本处理成为一连串的`token stream` +> 标记 / Token: 指处理好后的一个字串, 是构成源代码的最小单位, 比如我们可以归类 golang 中的关键字, 例如 var、const、import 等等, 或者一个字符串变量 "str" 或者操作符 :=、>=、== 等等,只要是符合我们定义的语法规则处理后出现的字串, 都可以称为一个 token + +如上图, 左边框内的三条源代码案例, 经过词法分析后, 可能会(具体看自己对`token`的定义处理规则)输出右边的三块`token stream`(每一行代表一个`token`) + +### lex / flex +lex / flex 是常用的词法分析器,支持正则表示某类 token + +flex 文件完整格式: +```c +%{ +Declarations +%} +Definitions +%% +Rules +%% +User subroutines +``` + +例: +test.l +```c + +/* Declarations */ +%{ +void yyerror(const char *msg); +%} + + +/* Definitions */ +WHITESPACE ([ \t\r\a]+) +OPERATOR ([+*-/%=,;!<>(){}]) +INTEGER ([0-9]+) + + +/* Rules */ +%% + +{WHITESPACE} { /* void */ } + +{OPERATOR} { printf("%s\n", yytext); } + +{INTEGER} { printf("%d\n", atoi(yytext)); } + +\n { /* void */ } + +. { printf("analysis error: unknow [%s]\n", yytext); exit(1); } + +%% + +/* User subroutines */ +int main(int argc, char* argv[]) { + FILE *fp = NULL; + if (argc == 2) { + fp = fopen(argv[1], "r"); + if (fp) { + yyin = fp; + } + } + yylex(); + if (fp) { + fclose(fp); + } + return 0; +} + +int yywrap(void) { + return 1; +} + +void yyerror(const char *msg) { + fprintf(stderr, "Error :\n\t%s\n", msg); + exit(-1); +} +``` + + +以上小段词法分析代码定义了三种`token`:`WHITESPACE`, `OPERATOR`, `INTEGER`, 分别用正则定义了他们的规则, 而后在 `Rules` 规则阶段分别对这三种 `token` 进行了各自的处理 +```shell +# 编译 +flex -o test.c test.l +gcc -std=c89 -o flextest test.c +./test.c test.txt +``` +而后用根据我们定义的规则生成的词法分析器`flextest`来处理一个简单的案例 + +```shell +cat test.txt +1 + (2 - 3) * 4 / 5 sss + +./flextest ./test.txt +1 ++ +( +2 +- +3 +) +* +4 +/ +5 +analysis error: unknow [s] +``` +根据输出的`token stream`可以看到, 能通过`token`规则处理的字串会完成输出一个成功处理的`token`, 规则之外的则处理失败 + +经过以上的小案例, 那么如果让我们自己来做一个`golang`的词法分析 `token` 的定义, 难度就不会特别大了 + +这边可以来简单看下`golang`编译器源码内的`token`定义 + +```go +// src/go/token/token.go +var tokens = [...]string{ + ILLEGAL: "ILLEGAL", + + EOF: "EOF", + COMMENT: "COMMENT", + + IDENT: "IDENT", + INT: "INT", + FLOAT: "FLOAT", + IMAG: "IMAG", + CHAR: "CHAR", + STRING: "STRING", + + ADD: "+", + SUB: "-", + MUL: "*", + QUO: "/", + REM: "%", + + AND: "&", + OR: "|", + XOR: "^", + SHL: "<<", + SHR: ">>", + AND_NOT: "&^", + + ADD_ASSIGN: "+=", + SUB_ASSIGN: "-=", + MUL_ASSIGN: "*=", + QUO_ASSIGN: "/=", + REM_ASSIGN: "%=", + + AND_ASSIGN: "&=", + OR_ASSIGN: "|=", + XOR_ASSIGN: "^=", + SHL_ASSIGN: "<<=", + SHR_ASSIGN: ">>=", + AND_NOT_ASSIGN: "&^=", + + LAND: "&&", + LOR: "||", + ARROW: "<-", + INC: "++", + DEC: "--", + + EQL: "==", + LSS: "<", + GTR: ">", + ASSIGN: "=", + NOT: "!", + + NEQ: "!=", + LEQ: "<=", + GEQ: ">=", + DEFINE: ":=", + ELLIPSIS: "...", + + LPAREN: "(", + LBRACK: "[", + LBRACE: "{", + COMMA: ",", + PERIOD: ".", + + RPAREN: ")", + RBRACK: "]", + RBRACE: "}", + SEMICOLON: ";", + COLON: ":", + + BREAK: "break", + CASE: "case", + CHAN: "chan", + CONST: "const", + CONTINUE: "continue", + + DEFAULT: "default", + DEFER: "defer", + ELSE: "else", + FALLTHROUGH: "fallthrough", + FOR: "for", + + FUNC: "func", + GO: "go", + GOTO: "goto", + IF: "if", + IMPORT: "import", + + INTERFACE: "interface", + MAP: "map", + PACKAGE: "package", + RANGE: "range", + RETURN: "return", + + SELECT: "select", + STRUCT: "struct", + SWITCH: "switch", + TYPE: "type", + VAR: "var", +} +``` +附上一段 `go` 内置实现的词法分析 +```go +package main + +import ( + "fmt" + "go/scanner" + "go/token" +) + +func main() { + // src is the input that we want to tokenize. + src := ` + package main + + func main() { + var num1, num2 int + num1 += num2 + _ = num1 + num1 += "str" + return + } + ` + + // Initialize the scanner. + var s scanner.Scanner + fset := token.NewFileSet() // positions are relative to fset + file := fset.AddFile("", fset.Base(), len(src)) // register input "file" + s.Init(file, []byte(src), nil /* no error handler */, scanner.ScanComments) + + // Repeated calls to Scan yield the token sequence found in the input. + fmt.Printf("%s\t%s\t%s\n", "pos", "token", "literal") + for { + pos, tok, lit := s.Scan() + if tok == token.EOF { + break + } + fmt.Printf("%s\t%s\t%q\n", fset.Position(pos), tok, lit) + } +} + +``` +```shell +#output +pos token literal +2:2 package "package" +2:10 IDENT "main" +2:14 ; "\n" +4:2 func "func" +4:7 IDENT "main" +4:11 ( "" +4:12 ) "" +4:14 { "" +5:3 var "var" +5:7 IDENT "num1" +5:11 , "" +5:13 IDENT "num2" +5:18 IDENT "int" +5:21 ; "\n" +6:3 IDENT "num1" +6:8 += "" +6:11 IDENT "num2" +6:15 ; "\n" +7:3 IDENT "_" +7:5 = "" +7:7 IDENT "num1" +7:11 ; "\n" +8:3 IDENT "num1" +8:8 += "" +8:11 STRING "\"str\"" +8:16 ; "\n" +9:3 return "return" +9:9 ; "\n" +10:2 } "" +10:3 ; "\n" +``` +注意, 这边示例代码有意使用了错误的语法, 目的是为了让大家知道`token`提取的词法分析过程中, 是没有必要同步进行语义的分析的, 输出的结果也可以和之前的`token`列表自行对照一下 +## 语法分析 +根据第一步[词法分析](#词法分析)我们目前已经获取到了自源代码处理好之后的一个`token stream`, 在语法分析阶段主要负责的就是把这一串「看似毫无规则」的标记流进行语法结构上的处理 + +例如 +1. 判断某个赋值操作是否可以执行, 赋值号两边的变量及数据类型是否匹配 +2. 运算规则是否符合语法规则 +3. 语句优先级 +4. …… + +在这个阶段可以直接翻译成目标代码, 或者生成诸如语法树之类的数据结构以便后续语义分析,优化等阶段利用。 + +> 上下文无关文法: 文法中所有的产生式左边只有一个非终结符 +> https://www.zhihu.com/question/21833944 + +### token stream 处理过程第一步 +对于`token stream`首先我们得处理的是初步生成语法树而后交由下面的步骤进行处理, 然而这里并不是随意生成一颗语法树的, 它得以某种规则进行初步的约束, 可以试想, 如果生成的语法树有多种可能, 每次生成的结果都不一致, 那么对于这类的语法树进行后续的分析则没有任何意义 + +本案例中我们要实现的是一个简单的`SQL`解析器, 那么接下来看看如何通过`token stream`初步生成我们所需要的语法树 + +回头看下上下文无关语法的简单介绍, 所有的`产生式`右边都是由左侧唯一的`非终结符`产生的, 就例如我们常见的一条 `SQL` +`SELECT * FROM TABLE1;` +用上下文表达式可简单表达为 +```shell +QUERY = [SELECT TOKEN] KEY [FROM TOKEN] TABLE; +KEY = [* TOKEN] | TOKEN | TOKEN , +TABLE = TOKEN +``` +> 这个案例中 `KEY` 定义为三种形式, 对应的 `SQL` 分别为 `SELECT * FROM TABLE;` `SELECT ID FROM TABLE;` `SELECT ID, COLUMN1, COLUMN2 FROPM TABLE;` 用竖线 | 来表示推到的多种可能 + +可以清晰地看到, 最开始看似杂乱无序的一条语句最终就可以通过分治的思想化解为一个个小问题, 以此类推最终对应到我们制定的 `TOKEN` 规则, 如果`TOKEN STREAM`最终匹配不上我们所制定的所有规则, 那么则解析失败 + + +有了此类分析规则的简单概念后, 接下来我们就利用几个简单的工具实现这个解析器的功能 +### bison +[bison](https://www.gnu.org/software/bison/) GNU bison是一个自由软件,用于自动生成语法分析器程序,实际上可用于所有常见的操作系统. 可以结合上文`flex`分析后生成的`token stream`继续进行语法部分的分析 + +> 继上文`flex`工具编辑一个简单的`SQL`解析器, 本案例非完全支持完整语法, 仅支持`SELECT A, B, C FROM TABLE;` `SELECT A, B, C, *;` 形式用作展示 + +test.l +```c +/* Declarations */ +%{ +#define YYSTYPE char * +#include "y.tab.h" +void yyerror(const char *msg); +#define _DUPTEXT { yylval = strdup(yytext); } +%} + + +/* Definitions */ +IDENTIFIER [_a-zA-Z][_a-zA-Z0-9]* +OPERATOR [,;*] +WHITESPACE ([ \t\r\a]+) +/* Rules */ +%% +\n { /* void */ } +SELECT { _DUPTEXT; return T_SELECT; } +FROM { _DUPTEXT; return T_FROM; } +{WHITESPACE} { /* ignore every whitespace */ } +{OPERATOR} { _DUPTEXT; return yytext[0]; } +{IDENTIFIER} { _DUPTEXT; return T_IDENTIFIER; } +. { return 0; } + +%% + +int yywrap(void) { + return 1; +} + +void yyerror(const char *s) { + extern int yylineno; + extern char *yytext; + int len = strlen(yytext); + int i = 0; + char buf[512] = {0}; + for (; i < len; i++) + { + sprintf(buf, "%s%d:%c ", buf, yytext[i], yytext[i]); + } + fprintf(stderr, "ERROR: %s at symbol '%s' on line %d\n", s, buf, yylineno); +} +``` +test.y +```c +%{ +#include +#include +#include +#include "tree.h" +int columns = 0; +%} +/* 定义产生式所产生的数据类型 */ +%union{ + struct ast *_ast; + char** strs; + char* str; +} +/* 定义各个产生式返回的数据类型 */ +%type <_ast> Q +%type K +%type '*' ';' +%token T_SELECT T_FROM T_IDENTIFIER + +%start S +/* + SELECT A, B, C FROM TABLE; + SELECT A, B, C, *; +*/ +%% + +S : { /* void */ } + | Q { ast_print($1); ast_free($1); exit(0); } + ; +/* SQL 产生式定义 */ +Q : T_SELECT K T_FROM T_IDENTIFIER ';' { + struct ast *_ast = new_ast(); + _ast->command = T_SELECT; + ast_add_table(_ast, $4); + ast_add_fields(_ast, $2); + free($4); + int i = 0; + for (; i < _ast->filed_size; i++) { + free($2[i]); + } + free($2); + $$ = _ast; /* 将生产的 struct ast* 作为返回值返返回上一级产生式, 每个产生式的返回值有数据类型的限制, 具体看用户定义 */ + } + + | T_SELECT K ';' { + struct ast *_ast = new_ast(); + _ast->command = T_SELECT; + ast_add_fields(_ast, $2); + int i = 0; + for (; i < _ast->filed_size; i++) { + free($2[i]); + } + free($2); + $$ = _ast; + } + ; + +/* columns 产生式定义 */ +K : '*' { + columns++; + char** filed = malloc(sizeof(char*)); + filed[0] = strdup($1); + $$ = filed; + } + | K ',' T_IDENTIFIER { + columns++; + int len = columns; + char** result = malloc(sizeof(char*) * len); + int i = 0; + for (; i < len-1; i++) { + result[i] = strdup($1[i]); + free($1[i]); + } + free($1); + result[i] = strdup($3); + $$ = result; + } + | T_IDENTIFIER { + columns++; + char** filed = malloc(sizeof(char*)); + filed[0] = strdup($1); + $$ = filed; + } + ; + +%% + +int main() { + return yyparse(); +} +``` +tree.h +```c +struct ast +{ + int command; + char **fileds; + int filed_size; + char *table; +}; +void ast_add_table(struct ast *, char *); + +void ast_add_fields(struct ast *, char **); + +void ast_print(struct ast *); + +void ast_free(struct ast *); + +struct ast *new_ast(); + +extern int columns; +``` +tree.h +```c +#include "tree.h" +#include +#include +#include +#include "y.tab.h" +struct ast *new_ast() +{ + struct ast *_ast = malloc(sizeof(struct ast)); + _ast->table = NULL; + _ast->filed_size = 0; + _ast->fileds = NULL; + return _ast; +} + +void ast_print(struct ast *_ast) +{ + if (!_ast) + return; + printf("command: %d\n", _ast->command); + int i = 0; + for (; i < _ast->filed_size; i++) + { + printf("column%i:%s\n", i, _ast->fileds[i]); + } + printf("tablename: %s\n", _ast->table); + return; +} + +void ast_add_table(struct ast *_ast, char *table) +{ + if (!_ast || _ast->table) + return; + _ast->table = strdup(table); + return; +} + +void ast_add_fields(struct ast *_ast, char **fileds) +{ + if (!_ast || _ast->fileds) + return; + int len = columns; + _ast->filed_size = len; + char **_fileds = malloc(sizeof(char *) * len); + int i = 0; + for (; i < len; i++) + { + _fileds[i] = strdup(fileds[i]); + } + _ast->fileds = _fileds; +} + +void ast_free(struct ast *_ast) +{ + if (_ast->table) + free(_ast->table); + int i = 0; + for (; i < _ast->filed_size; i++) + free(_ast->fileds[i]); + free(_ast->fileds); + free(_ast); +} +``` +output +```shell +flex test.l && bison -vdty test.y && gcc -std=c89 -o test y.tab.c lex.yy.c tree.c +./test +SELECT A FROM B; +command: 258 +column0:A +tablename: B +``` +成功解析这条小`SQL`的各个部分, 当然这边的过程生成的是一个非常简单的数据结构, 仅作对应信息的统计, 通过设计更成熟的语法树而后结合`token stream`及以上的概念就可以初步生成一棵后续步骤所需要的语法树 + +再回过头来看看第一步中那段`go`代码生成的语法树(依旧是用错误代码来生成,提示此处的语法树生成仅仅是初步的阶段, 后续还要进行诸多步骤的处理) +```go +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "log" +) + +func main() { + src := ` + package main + + func main() { + var num1, num2 int + num1 += num2 + _ = num1 + num1 += "str" + return + } + ` + + // Initialize the parser. + fset := token.NewFileSet() // positions are relative to fset + f, err := parser.ParseFile(fset, "", src, 0) + if err != nil { + log.Fatalln(err) + } + ast.Print(fset, f) +} +``` +#### AST_output: +```shell + 0 *ast.File { + 1 . Package: 2:2 + 2 . Name: *ast.Ident { + 3 . . NamePos: 2:10 + 4 . . Name: "main" + 5 . } + 6 . Decls: []ast.Decl (len = 1) { + 7 . . 0: *ast.FuncDecl { + 8 . . . Name: *ast.Ident { + 9 . . . . NamePos: 4:7 + 10 . . . . Name: "main" + 11 . . . . Obj: *ast.Object { + 12 . . . . . Kind: func + 13 . . . . . Name: "main" + 14 . . . . . Decl: *(obj @ 7) + 15 . . . . } + 16 . . . } + 17 . . . Type: *ast.FuncType { + 18 . . . . Func: 4:2 + 19 . . . . Params: *ast.FieldList { + 20 . . . . . Opening: 4:11 + 21 . . . . . Closing: 4:12 + 22 . . . . } + 23 . . . } + 24 . . . Body: *ast.BlockStmt { + 25 . . . . Lbrace: 4:14 + 26 . . . . List: []ast.Stmt (len = 5) { + 27 . . . . . 0: *ast.DeclStmt { + 28 . . . . . . Decl: *ast.GenDecl { + 29 . . . . . . . TokPos: 5:3 + 30 . . . . . . . Tok: var + 31 . . . . . . . Lparen: - + 32 . . . . . . . Specs: []ast.Spec (len = 1) { + 33 . . . . . . . . 0: *ast.ValueSpec { + 34 . . . . . . . . . Names: []*ast.Ident (len = 2) { + 35 . . . . . . . . . . 0: *ast.Ident { + 36 . . . . . . . . . . . NamePos: 5:7 + 37 . . . . . . . . . . . Name: "num1" + 38 . . . . . . . . . . . Obj: *ast.Object { + 39 . . . . . . . . . . . . Kind: var + 40 . . . . . . . . . . . . Name: "num1" + 41 . . . . . . . . . . . . Decl: *(obj @ 33) + 42 . . . . . . . . . . . . Data: 0 + 43 . . . . . . . . . . . } + 44 . . . . . . . . . . } + 45 . . . . . . . . . . 1: *ast.Ident { + 46 . . . . . . . . . . . NamePos: 5:13 + 47 . . . . . . . . . . . Name: "num2" + 48 . . . . . . . . . . . Obj: *ast.Object { + 49 . . . . . . . . . . . . Kind: var + 50 . . . . . . . . . . . . Name: "num2" + 51 . . . . . . . . . . . . Decl: *(obj @ 33) + 52 . . . . . . . . . . . . Data: 0 + 53 . . . . . . . . . . . } + 54 . . . . . . . . . . } + 55 . . . . . . . . . } + 56 . . . . . . . . . Type: *ast.Ident { + 57 . . . . . . . . . . NamePos: 5:18 + 58 . . . . . . . . . . Name: "int" + 59 . . . . . . . . . } + 60 . . . . . . . . } + 61 . . . . . . . } + 62 . . . . . . . Rparen: - + 63 . . . . . . } + 64 . . . . . } + 65 . . . . . 1: *ast.AssignStmt { + 66 . . . . . . Lhs: []ast.Expr (len = 1) { + 67 . . . . . . . 0: *ast.Ident { + 68 . . . . . . . . NamePos: 6:3 + 69 . . . . . . . . Name: "num1" + 70 . . . . . . . . Obj: *(obj @ 38) + 71 . . . . . . . } + 72 . . . . . . } + 73 . . . . . . TokPos: 6:8 + 74 . . . . . . Tok: += + 75 . . . . . . Rhs: []ast.Expr (len = 1) { + 76 . . . . . . . 0: *ast.Ident { + 77 . . . . . . . . NamePos: 6:11 + 78 . . . . . . . . Name: "num2" + 79 . . . . . . . . Obj: *(obj @ 48) + 80 . . . . . . . } + 81 . . . . . . } + 82 . . . . . } + 83 . . . . . 2: *ast.AssignStmt { + 84 . . . . . . Lhs: []ast.Expr (len = 1) { + 85 . . . . . . . 0: *ast.Ident { + 86 . . . . . . . . NamePos: 7:3 + 87 . . . . . . . . Name: "_" + 88 . . . . . . . } + 89 . . . . . . } + 90 . . . . . . TokPos: 7:5 + 91 . . . . . . Tok: = + 92 . . . . . . Rhs: []ast.Expr (len = 1) { + 93 . . . . . . . 0: *ast.Ident { + 94 . . . . . . . . NamePos: 7:7 + 95 . . . . . . . . Name: "num1" + 96 . . . . . . . . Obj: *(obj @ 38) + 97 . . . . . . . } + 98 . . . . . . } + 99 . . . . . } + 100 . . . . . 3: *ast.AssignStmt { + 101 . . . . . . Lhs: []ast.Expr (len = 1) { + 102 . . . . . . . 0: *ast.Ident { + 103 . . . . . . . . NamePos: 8:3 + 104 . . . . . . . . Name: "num1" + 105 . . . . . . . . Obj: *(obj @ 38) + 106 . . . . . . . } + 107 . . . . . . } + 108 . . . . . . TokPos: 8:8 + 109 . . . . . . Tok: += + 110 . . . . . . Rhs: []ast.Expr (len = 1) { + 111 . . . . . . . 0: *ast.BasicLit { + 112 . . . . . . . . ValuePos: 8:11 + 113 . . . . . . . . Kind: STRING + 114 . . . . . . . . Value: "\"str\"" + 115 . . . . . . . } + 116 . . . . . . } + 117 . . . . . } + 118 . . . . . 4: *ast.ReturnStmt { + 119 . . . . . . Return: 9:3 + 120 . . . . . } + 121 . . . . } + 122 . . . . Rbrace: 10:2 + 123 . . . } + 124 . . } + 125 . } + 126 . Scope: *ast.Scope { + 127 . . Objects: map[string]*ast.Object (len = 1) { + 128 . . . "main": *(obj @ 11) + 129 . . } + 130 . } + 131 . Unresolved: []*ast.Ident (len = 1) { + 132 . . 0: *(obj @ 56) + 133 . } + 134 } +``` +### goyacc +`goyacc` 是一个 `golang` 版的 `yacc` 工具(作用和上文介绍的`flex & bison`)类似, 不同的是没有对应的`lex`工具, 这部分逻辑需要自己实现 +接下来用`goyacc`将上述的`SQL`小解析器实现一遍 + +parser.y +```c +%{ +package sql + +var columns int; + +func setResult(l yyLexer, v *ast) { + l.(*lex).result = v +} + +%} +/* 定义产生式所产生的数据类型 */ +%union{ + _ast * ast + strs []string + str string +} +/* 定义各个产生式返回的数据类型 */ +%type <_ast> Q +%type K +%type '*' ';' +%token T_SELECT T_FROM T_IDENTIFIER + +%start S +/* + SELECT A, B, C FROM TABLE; + SELECT A, B, C, *; +*/ +%% + +S : { /* void */ } + | Q { setResult(yylex, $1) } + ; +/* SQL 产生式定义 */ +Q : T_SELECT K T_FROM T_IDENTIFIER ';' { + _ast := new_ast(); + _ast.command = T_SELECT; + ast_add_table(_ast, $4); + ast_add_fields(_ast, $2); + $$ = _ast; /* 将生产的 struct ast* 作为返回值返返回上一级产生式, 每个产生式的返回值有数据类型的限制, 具体看用户定义 */ + } + + | T_SELECT K ';' { + _ast := new_ast(); + _ast.command = T_SELECT; + ast_add_fields(_ast, $2); + $$ = _ast; + } + ; + +/* columns 产生式定义 */ +K : '*' { + columns++; + $$ = []string{$1}; + } + | K ',' T_IDENTIFIER { + columns++; + $$ = append($1, $3); + } + | T_IDENTIFIER { + columns++; + $$ = []string{$1}; + } + ; + +%% +``` +tree.go +```go +package sql + +import ( + "errors" + "fmt" + "os" + "strings" +) + +//go:generate go run golang.org/x/tools/cmd/goyacc -l -o parser.go parser.y + +type ast struct { + command int + fileds []string + filed_size int + table string +} +type lex struct { + input []byte + pos int + result *ast + err error +} + +func Parse(sql string) (*ast, error) { + l := &lex{ + input: []byte(sql), + } + _ = yyParse(l) // yyParse 入参需要实现 goyacc lex 接口 + return l.result, l.err +} + +func (l *lex) Lex(lval *yySymType) int { // token 解析入口 + str := l.nextString() + switch strings.ToLower(str) { + case "": + return 0 + case "*", ";", ",": + lval.str = str // 对应 flex 中 yylval = strdup(yytext); 赋值操作, 需要和返回的类型相对于, goyacc 会根据返回的类型去对应的字段获取 + return int(byte(str[0])) // 对应 flex 中 return 返回 token 类型 + case "select": + lval.str = str + return T_SELECT + case "from": + lval.str = str + return T_FROM + default: + lval.str = str + return T_IDENTIFIER + } +} +func (l *lex) nextString() string { + /* trim left */ + for { + if l.pos >= len(l.input) { + return "" + } + switch l.input[l.pos] { + case ' ', '\r', '\n', '\t', '\a': + l.pos++ + default: + goto next + } + } +next: + /* get next string */ + var index int = l.pos + for ; index < len(l.input); index++ { + switch l.input[index] { + case ' ', '\r', '\n', '\t', '\a': + goto next_2 + case '*', ';', ',': + if index == l.pos { + index++ + } + goto next_2 + default: + } + } +next_2: + result := l.input[l.pos:index] + l.pos = index + return string(result) +} + +// Error satisfies yyLexer. +func (l *lex) Error(s string) { + l.err = errors.New(s) +} + +func new_ast() *ast { + return &ast{} +} + +func ast_print(_ast *ast) { + if _ast == nil { + return + } + fmt.Printf("command:%s\n", func() string { + switch _ast.command { + case T_SELECT: + return "select" + default: + return "unknow" + } + }()) + for i := range _ast.fileds { + fmt.Printf("column%d:%s\n", i, _ast.fileds[i]) + } + fmt.Printf("tablename:%s\n", _ast.table) +} + +func ast_add_table(_ast *ast, table string) { + if _ast == nil || _ast.table != "" { + return + } + _ast.table = table +} + +func ast_add_fields(_ast *ast, fileds []string) { + if _ast == nil { + return + } + _ast.fileds = fileds + _ast.filed_size = len(fileds) +} + +func ast_free(_ast *ast) { + /* void */ + return +} + +func exit(i int) { + os.Exit(i) +} + +``` +lex_test.go +```go +package sql + +import ( + "fmt" + "log" + "testing" +) + +func TestLex(t *testing.T) { + sqls := []string{ + `SELECT * FROM TABLE1;`, + `SelecT A,B,C FROM TB;`, + `SELECT A,B,C;`, + } + for _, sql := range sqls { + _ast, err := Parse(sql) + if err != nil { + log.Fatalln(err) + } + ast_print(_ast) + fmt.Println() + } +} + +``` +output: +```shell +go run golang.org/x/tools/cmd/goyacc -l -o parser.go parser.y +go test -v . +=== RUN TestLex +command:select +column0:* +tablename:TABLE1 + +command:select +column0:A +column1:B +column2:C +tablename:TB + +command:select +column0:A +column1:B +column2:C +tablename: + +--- PASS: TestLex (0.00s) +PASS +ok json1/sql 0.006s +``` + +## 类型检查 +在进行类型检查这一步的时候, 整个文件可以粗略分为`变量声明及作用域`以及`表达式`两块内容, 在检查 AST 的过程中遇到一些定义的变量会在当前作用域中查找是否有对应的声明, 如果没找到则顺着作用域向上去父级作用域寻找 + +### 声明及作用域 +作用域可大致分为几类 +1. 全局 +2. 对应函数体内 +3. 块级表达式内 {...} // 单独一对花括号包裹范围内 +```go +// 作用域结构体定义 +type Scope struct { + parent *Scope + children []*Scope + elems map[string]Object // lazily allocated + pos, end token.Pos // scope extent; may be invalid + comment string // for debugging only + isFunc bool // set if this is a function scope (internal use only) +} +func (s *Scope) LookupParent(name string, pos token.Pos) (*Scope, Object) { + for ; s != nil; s = s.parent { + if obj := s.elems[name]; obj != nil && (!pos.IsValid() || obj.scopePos() <= pos) { + return s, obj + } + } + return nil, nil +} +``` +回顾下 `AST file` 的数据结构 +```go +type File struct { + Doc *CommentGroup // associated documentation; or nil + Package token.Pos // position of "package" keyword + Name *Ident // package name + Decls []Decl // top-level declarations; or nil + Scope *Scope // package scope (this file only) + Imports []*ImportSpec // imports in this file + Unresolved []*Ident // unresolved identifiers in this file + Comments []*CommentGroup // list of all comments in the source file +} +``` +再结合之前输出的 [`AST`](#ast_output), 我们可以看到在生成的过程中, 大部分的 `identifiers token` 是能够确认对应类型的, 例如函数声明之类的, 那么对应函数名的 `token` 就可以被成功解析为对应类型的语法树中的一个节点 + +但是依旧存在一些在`AST`初步生成阶段无法被成功解析的, 那么会被存放在`Unresolved`字段中, 就比如上面输出的`int`, 那么这时候就通过向上从父级中依次查找, 如果最终能够找到对应定义, 那么检查成功, 否则则抛出未定义异常 + +例: +```go +package main + +import ( + "go/ast" + "go/parser" + "go/token" + "go/types" + "log" +) + +func main() { + src := ` + + package main + + func main() { + var num1, num2 int + num1 += num2 + _ = num1 + testval++ + return + } + ` + + // Initialize the parser. + fset := token.NewFileSet() // positions are relative to fset + f, err := parser.ParseFile(fset, "", src, parser.AllErrors|parser.ParseComments) + if err != nil { + log.Fatalln(err) + } + pkg, err := new(types.Config).Check("test.go", fset, []*ast.File{f}, nil) + if err != nil { + log.Fatal(err) + } + + _ = pkg +} + +``` +output: +```shell +2021/09/20 15:19:01 9:3: undeclared name: testval +``` +### 表达式检查 +截取之前生成的`AST`中的一小段 +`num1 += num2` +```shell +65 . . . . . 1: *ast.AssignStmt { +66 . . . . . . Lhs: []ast.Expr (len = 1) { +67 . . . . . . . 0: *ast.Ident { +68 . . . . . . . . NamePos: 6:3 +69 . . . . . . . . Name: "num1" +70 . . . . . . . . Obj: *(obj @ 38) +71 . . . . . . . } +72 . . . . . . } +73 . . . . . . TokPos: 6:8 +74 . . . . . . Tok: += +75 . . . . . . Rhs: []ast.Expr (len = 1) { +76 . . . . . . . 0: *ast.Ident { +77 . . . . . . . . NamePos: 6:11 +78 . . . . . . . . Name: "num2" +79 . . . . . . . . Obj: *(obj @ 48) +80 . . . . . . . } +81 . . . . . . } +82 . . . . . } +``` +先看下这个简单的赋值表达式生成的树形结构 +```mermaid +graph TB + +A((op: +=)) +B((exprL: num1)) +C((exprR: num2)) +A-->B +A-->C +``` +对于当前这部分表达式检查, 需要进行的步骤为 +1. 确认当前操作符(+=) +2. 左子树表达式递归, 并确认表达式最终类型 +3. 右子树表达式递归, 并确认表达式最终类型 +4. 左右 expr 类型校验, 如符合当前操作符规则, 成功, 反之失败 + +```go +// The binary expression e may be nil. It's passed in for better error messages only. +func (check *Checker) binary(x *operand, e *ast.BinaryExpr, lhs, rhs ast.Expr, op token.Token) { + var y operand + + check.expr(x, lhs) // 左子树表达式递归 + check.expr(&y, rhs) // 右子树表达式递归 + /* 先判断下特殊的操作类型 */ + if x.mode == invalid { + return + } + if y.mode == invalid { + x.mode = invalid + x.expr = y.expr + return + } + + if isShift(op) { + check.shift(x, &y, e, op) + return + } + + check.convertUntyped(x, y.typ) + if x.mode == invalid { + return + } + check.convertUntyped(&y, x.typ) + if y.mode == invalid { + x.mode = invalid + return + } + + if isComparison(op) { + check.comparison(x, &y, op) + return + } + /* 默认要求 x y 类型一致 */ + if !check.identical(x.typ, y.typ) { // 类型校验 + // only report an error if we have valid types + // (otherwise we had an error reported elsewhere already) + if x.typ != Typ[Invalid] && y.typ != Typ[Invalid] { + check.invalidOp(x.pos(), "mismatched types %s and %s", x.typ, y.typ) + } + x.mode = invalid + return + } + + if !check.op(binaryOpPredicates, x, op) { + x.mode = invalid + return + } + + if op == token.QUO || op == token.REM { + // check for zero divisor + if (x.mode == constant_ || isInteger(x.typ)) && y.mode == constant_ && constant.Sign(y.val) == 0 { + check.invalidOp(y.pos(), "division by zero") + x.mode = invalid + return + } + + // check for divisor underflow in complex division (see issue 20227) + if x.mode == constant_ && y.mode == constant_ && isComplex(x.typ) { + re, im := constant.Real(y.val), constant.Imag(y.val) + re2, im2 := constant.BinaryOp(re, token.MUL, re), constant.BinaryOp(im, token.MUL, im) + if constant.Sign(re2) == 0 && constant.Sign(im2) == 0 { + check.invalidOp(y.pos(), "division by zero") + x.mode = invalid + return + } + } + } + + if x.mode == constant_ && y.mode == constant_ { + xval := x.val + yval := y.val + typ := x.typ.Underlying().(*Basic) + // force integer division of integer operands + if op == token.QUO && isInteger(typ) { + op = token.QUO_ASSIGN + } + x.val = constant.BinaryOp(xval, op, yval) + // Typed constants must be representable in + // their type after each constant operation. + if isTyped(typ) { + if e != nil { + x.expr = e // for better error message + } + check.representable(x, typ) + } + return + } + + x.mode = value + // x.typ is unchanged +} +``` +> 这边以 `go/types` 标准库的类型检查作为案例, 编译器整体流程大同小异 + +以上, 通过`TOKEN`声明以及对应作用域的维护及查找, 再结合各操作符下表达式的递归分析过程, 对于一棵语法树的类型检查就可以进行了 + +## 中间代码生成 +## 机器码生成 +## 参考资料 +[flex & bison](https://pandolia.net/tinyc/index.html) + +[goyacc 入门案例](https://github.com/sougou/parser_tutorial) \ No newline at end of file diff --git a/context.md b/context.md new file mode 100644 index 0000000..e767fd9 --- /dev/null +++ b/context.md @@ -0,0 +1,570 @@ +# context + +先简单的了解一下几种 ctx: + +- emptyCtx,所有 ctx 类型的根,用 context.TODO(),或 context.Background() 来生成。 +- valueCtx,主要就是为了在 ctx 中嵌入上下文数据,一个简单的 k 和 v 结构,同一个 ctx 内只支持一对 kv,需要更多的 kv 的话,会形成一棵树形结构。 +- cancelCtx,用来取消程序的执行树,一般用 WithCancel,WithTimeout,WithDeadline 返回的取消函数本质上都是对应了 cancelCtx。 +- timerCtx,在 cancelCtx 上包了一层,支持基于时间的 cancel。 + +# basic usage + +## 使用 emptyCtx 初始化 context + +用来实现 context.TODO() 和 context.Background(),一般是所有 context 树的根。 + +```go +// An emptyCtx is never canceled, has no values, and has no deadline. It is not +// struct{}, since vars of this type must have distinct addresses. +type emptyCtx int + +var ( + background = new(emptyCtx) + todo = new(emptyCtx) +) +``` + +todo 和 background 两者本质上只有名字区别,在按 string 输出的时候会有区别。 + +```go +func (e *emptyCtx) String() string { + switch e { + case background: + return "context.Background" + case todo: + return "context.TODO" + } + return "unknown empty Context" +} +``` + +## 使用 valueCtx 嵌入数据 + +### valueCtx 使用 + +```go +package main + +import ( + "context" + "fmt" +) + +type orderID int + +func main() { + var x = context.TODO() + x = context.WithValue(x, orderID(1), "1234") + x = context.WithValue(x, orderID(2), "2345") + x = context.WithValue(x, orderID(3), "3456") + fmt.Println(x.Value(orderID(2))) +} +``` + +这样的代码会生成下面这样的树: + +``` + ┌────────────┐ + │ emptyCtx │ + └────────────┘ + ▲ + │ + │ + │ parent + │ + │ +┌───────────────────────────────────┐ +│ valueCtx{k: 1, v: 1234} │ +└───────────────────────────────────┘ + ▲ + │ + │ + │ parent + │ + │ + │ +┌───────────────────────────────────┐ +│ valueCtx{k: 2, v: 2345} │ +└───────────────────────────────────┘ + ▲ + │ + │ parent + │ + │ +┌───────────────────────────────────┐ +│ valueCtx{k: 3, v: 3456} │ +└───────────────────────────────────┘ +``` + +简单改一下代码,让结果更像一棵树: + +```go +package main + +import ( + "context" + "fmt" +) + +type orderID int + +func main() { + var x = context.TODO() + x = context.WithValue(x, orderID(1), "1234") + x = context.WithValue(x, orderID(2), "2345") + + y := context.WithValue(x, orderID(3), "4567") + x = context.WithValue(x, orderID(3), "3456") + + fmt.Println(x.Value(orderID(3))) + fmt.Println(y.Value(orderID(3))) +} +``` + +就是像下面这样的图了: + +``` + ┌────────────┐ + │ emptyCtx │ + └────────────┘ + ▲ + │ + │ + │ parent + │ + │ + ┌───────────────────────────────────┐ + │ valueCtx{k: 1, v: 1234} │ + └───────────────────────────────────┘ + ▲ + │ + │ + │ parent + │ + │ + │ + ┌───────────────────────────────────┐ + │ valueCtx{k: 2, v: 2345} │ + └───────────────────────────────────┘ + ▲ + │ + ┌──────────────┴──────────────────────────┐ + │ │ + │ │ +┌───────────────────────────────────┐ ┌───────────────────────────────────┐ +│ valueCtx{k: 3, v: 3456} │ │ valueCtx{k: 3, v: 4567} │ +└───────────────────────────────────┘ └───────────────────────────────────┘ + ┌───────┐ ┌───────┐ + │ x │ │ y │ + └───────┘ └───────┘ +``` + +### valueCtx 分析 + +valueCtx 主要就是用来携带贯穿整个逻辑流程的数据的,在分布式系统中最常见的就是 trace_id,在一些业务系统中,一些业务数据项也需要贯穿整个请求的生命周期,如 order_id,payment_id 等。 + +WithValue 时即会生成 valueCtx: + +```go +func WithValue(parent Context, key, val interface{}) Context { + if key == nil { + panic("nil key") + } + if !reflectlite.TypeOf(key).Comparable() { + panic("key is not comparable") + } + return &valueCtx{parent, key, val} +} +``` + +key 必须为非空,且可比较。 + +在查找值,即执行 Value 操作时,会先判断当前节点的 k 是不是等于用户的输入 k,如果相等,返回结果,如果不等,会依次向上从子节点向父节点,一直查找到整个 ctx 的根。没有找到返回 nil。是一个递归流程: + +```go +func (c *valueCtx) Value(key interface{}) interface{} { + if c.key == key { + return c.val + } + return c.Context.Value(key) // 这里发生了递归,c.Context 就是 c.parent +} +``` + +通过分析,ctx 这么设计是为了能让代码每执行到一个点都可以根据当前情况嵌入新的上下文信息,但我们也可以看到,如果我们每次加一个新值都执行 WithValue 会导致 ctx 的树的层数过高,查找成本比较高 O(H)。 + +很多业务场景中,我们希望在请求入口存入值,在请求过程中随时取用。这时候我们可以将 value 作为一个 map 整体存入。 + +```go +context.WithValue(context.Background(), info, + map[string]string{"order_id" : "111", "payment_id" : "222"} +) +``` + +## 使用 cancelCtx 取消流程 + +### cancelCtx 使用 + +在没有 ctx 的时代,我们想要取消一个 go 出去的协程是很难的,因为 go func() 这个操作没有任何返回,所以我们也没有办法去跟踪这么一个新创建的 goroutine。 + +有了 cancelCtx 之后,我们想要取消就比较简单了: + +```go +package main + +import ( + "context" + "fmt" + "time" +) + +func main() { + jobChan := make(chan struct{}) + ctx, cancelFn := context.WithCancel(context.TODO()) + worker := func() { + jobLoop: + for { + select { + case <-jobChan: + fmt.Println("do my job") + case <-ctx.Done(): + fmt.Println("parent call me to quit") + break jobLoop + } + } + } + + // start worker + go worker() + + // stop all worker + cancelFn() + time.Sleep(time.Second) +} +``` + +不过取消操作一定是需要 fork 出的 goroutine 本身要做一些配合动作的: + +```go +select { + case <-jobChan: + // do my job + fmt.Println("do my job") + case <-ctx.Done(): + // parent want me to quit + fmt.Println("parent call me to quit") + break jobLoop +} +``` + +这里我们一边消费自己的 job channel,一边还需要监听 ctx.Done(),如果不监听 ctx.Done(),那显然也就不知道什么时候需要退出了。 + +### cancelCtx 分析 + +```go +// A cancelCtx can be canceled. When canceled, it also cancels any children +// that implement canceler. +type cancelCtx struct { + Context + + mu sync.Mutex // protects following fields + done chan struct{} // created lazily, closed by first cancel call + children map[canceler]struct{} // set to nil by the first cancel call + err error // set to non-nil by the first cancel call +} +``` + +使用 WithCancel 可以得到一个 cancelCtx: + +```go +// WithCancel returns a copy of parent with a new Done channel. The returned +// context's Done channel is closed when the returned cancel function is called +// or when the parent context's Done channel is closed, whichever happens first. +// +// Canceling this context releases resources associated with it, so code should +// call cancel as soon as the operations running in this Context complete. +func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { + c := newCancelCtx(parent) + propagateCancel(parent, &c) + return &c, func() { c.cancel(true, Canceled) } +} +``` + +```go +// propagateCancel arranges for child to be canceled when parent is. +func propagateCancel(parent Context, child canceler) { + if parent.Done() == nil { + return // 说明父节点一定是 emptyCtx,或者用户自己实现的 context.Context + } + if p, ok := parentCancelCtx(parent); ok { + p.mu.Lock() + if p.err != nil { + // cancel 发生的时候,err 字段一定会被赋值,这里说明父节点已经被赋值了 + child.cancel(false, p.err) + } else { + if p.children == nil { + p.children = make(map[canceler]struct{}) + } + p.children[child] = struct{}{} // 把当前 cancelCtx 追加到父节点去 + } + p.mu.Unlock() + } else { // 如果用户把 context 包在了自己的 struct 内就会到这个分支。 + go func() { + select { + case <-parent.Done(): // 父节点取消,需要将这个取消指令同步给子节点 + child.cancel(false, parent.Err()) + case <-child.Done(): // 子节点取消的话,就不用等父节点了 + } + }() + } +} +``` + +parentCancelCtx 只识别 context 包内的三种类型,如果用户自己的类实现了 context.Context 接口,或者把 ctx 包在了自己的类型内,或者是 emptyCtx,那这里始终返回的是 nil,false。 + +```go +func parentCancelCtx(parent Context) (*cancelCtx, bool) { + for { + switch c := parent.(type) { + case *cancelCtx: + return c, true + case *timerCtx: + return &c.cancelCtx, true + case *valueCtx: + parent = c.Context + default: + return nil, false + } + } +} +``` + +## 使用 timerCtx 超时取消 + +### timerCtx 使用 + +用 WithDeadline 和 WithTimeout 都可以生成一个 timerCtx: + +```go +package main + +import ( + "context" + "fmt" + "time" +) + +func main() { + // Pass a context with a timeout to tell a blocking function that it + // should abandon its work after the timeout elapses. + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + + select { + case <-time.After(1 * time.Second): + fmt.Println("overslept") + case <-ctx.Done(): + fmt.Println(ctx.Err()) // prints "context deadline exceeded" + } + +} +``` + +这是从官方的 example 里摘出来的例子,WithTimeout 其实底层是用 WithDeadline 实现的。 + +### timerCtx 分析 + +```go +// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to +// implement Done and Err. It implements cancel by stopping its timer then +// delegating to cancelCtx.cancel. +type timerCtx struct { + cancelCtx + timer *time.Timer // Under cancelCtx.mu. + + deadline time.Time +} +``` + +用 WithTimeout 和 WithDeadline 都会生成一个 timerCtx。 + +```go +func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) { + if cur, ok := parent.Deadline(); ok && cur.Before(d) { + // 如果父节点的 dealine 更靠前,那当然以父节点的为准,当前节点的 deadline 可以抛弃 + return WithCancel(parent) + } + c := &timerCtx{ + cancelCtx: newCancelCtx(parent), + deadline: d, + } + + // 向上冒泡,把当前节点的 cancel 函数关联到父 cancelCtx 节点上 + propagateCancel(parent, c) + dur := time.Until(d) + if dur <= 0 { + c.cancel(true, DeadlineExceeded) // 已经超时了,退出吧 + return c, func() { c.cancel(false, Canceled) } + } + c.mu.Lock() + defer c.mu.Unlock() + if c.err == nil { // 说明父节点到现在还没有取消呢 + c.timer = time.AfterFunc(dur, func() { + c.cancel(true, DeadlineExceeded) // 这个方法到时间了之后会自动执行,当前的 goroutine 不会被阻塞 + }) + } + return c, func() { c.cancel(true, Canceled) } +} +``` + +- 每次执行都会创建新的 timer +- 子节点的 deadline 一定不会超过父节点 +- 创建过程中发现已经过期了,立刻返回 + +## 树形结构 + +为什么设计成树形结构呢。因为对于 fork-join 的模型(Go 的原地 go func 就是这种模型)来说,程序代码的执行本来就是树形的。在进入、退出某个子节点的时候,既要加新的数据,又不能影响父节点的数据,所以这种链式树形结构可以完美地匹配。 + +```go + ┌───────────────────────────────┐ + │ ┌─┐ │ +┌────────────────────────┐ │ ╔═════════════════▶└─┘ │ +│ │ │ ║ ▲ │ +│ │ │ ║ ┃ │ +│ │ │ ║ ┏━━━━━━━━━━━━━┫ │ +│ │ │ ║ ┃ ┃ │ +│func() { ════════════╬═══╬═╝ ┃ ┗━━━━━┓ │ +│ │ │ ┃ ┃ │ +│ │ │ ┌─┐ ┃ │ +│ go func1(){}() ═════╬═══╬═════▶└─┘ ┃ │ +│ │ │ ┃ │ +│ │ │ ┃ │ +│ │ │ ┌─┐ │ +│ go func2(){═════════╬═══╬═════════════════════════▶└─┘ │ +│ │ │ ▲ │ +│ │ │ ┃ │ +│ │ │ ┃ │ +│ go func3(){}()══╬═══╬═════════╗ ┃ │ +│ │ │ ║ ┃ │ +│ │ │ ║ ┃ │ +│ │ │ ║ ┌─┐ │ +│ }() │ │ ╚═══════════════▶└─┘ │ +│} │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +│ │ │ │ +└────────────────────────┘ └───────────────────────────────┘ +``` + +取消某个父节点,又能够用树的遍历算法将该取消指令传导到整棵树去。 + +```go + ┌──────────┐ + │ emptyCtx │ + ├──────────┤ + │cancelCtx │ + └──────────┘ + ▲ + │ + │ + │ + │ + │ + ┌──────────┐ + │cancelCtx │ cancel here + └──────────┘ + ▲ ┃ + │ ┃ + │ ┃ + ┌────────────┴─────────────┐ ┃ + │ │ ┃ + │ ▢▢▢▢▢▢▢▢▢▢▢▢▢ ┃ + │ ▢▢▢▢▢ │ ▢▢▢▢▢ ┃ + │ ▢▢▢▢ │ ▢▢▢▢ ┃ +┌──────────┐ ▢▢▢▢ ┌──────────┐ ▢▢▢ ┃ +│cancelCtx │ ▢▢ │cancelCtx │◀━━━━━━━━━━━━━━━━━━┛ +└──────────┘ ▢▢ └──────────┘ ▢▢ + ▢▢ ▲ ▢▢ + ▢ ┌────────┴────┬────────────┐ ▢▢ + ▢ │ │ │ ▢ + ▢▢ ┌──────────┐ ┌──────────┐ ┌──────────┐ ▢ + ▢ │cancelCtx │ │cancelCtx │ │cancelCtx │ ▢ + ▢ └──────────┘ └──────────┘ └─────────▢▢▢ + ▢ ▢▢▢▢ + ▢▢ ▢▢▢▢▢ + ▢ ▢▢▢▢▢ + ▢▢▢ ▢▢▢▢ + ▢▢▢▢▢▢ ▢▢▢▢▢▢ + ▢▢▢▢▢▢▢▢▢▢▢▢ +``` + +如图,树上某个节点 cancel 之后,会顺便调用其 children 数组中所有子节点的取消函数,该取消操作一直传导到叶子节点。 + +## traps + +### cancelCtx 的性能问题 + +如果不通过 WithCancel 来复制通知 channel,大家都使用同一个 ctx.Done,那么实际上是在争一把大锁。 + +```go +package main + +import "context" +import "time" + +func main() { + ctx, _ := context.WithCancel(context.TODO()) + for i := 0; i < 100; i++ { + go func() { + select { + case <-ctx.Done(): + } + }() + } + time.Sleep(time.Hour) +} + +``` + +在一些场景可能会有性能问题。 + +### ctx 的打印 panic + +http 中的 ctx 还塞了 map,打印会造成 fatal。 + +```go +package main + +import ( + "fmt" + "net/http" + "reflect" +) + +func panic(w http.ResponseWriter, r *http.Request) { + server := r.Context().Value(http.ServerContextKey).(*http.Server) + v := reflect.ValueOf(*server) + + for i := 0; i < v.NumField(); i++ { + if name := v.Type().Field(i).Name; name != "activeConn" { + continue + } + fmt.Println(v.Field(i)) + } +} + +func main() { + http.HandleFunc("/", panic) + err := http.ListenAndServe(":9090", nil) + if err != nil { + fmt.Println(err) + } +} +``` + +# 总结 + +ctx 的结构显然是根据代码的执行模型来设计的,虽然设计得比较巧妙,但因为将取消和上下文携带功能混合在一起,在一些情况下还是会给我们埋些比较隐蔽的坑。使用时需要多多注意。 + + diff --git a/defer.md b/defer.md index e69de29..ada7c2b 100644 --- a/defer.md +++ b/defer.md @@ -0,0 +1,165 @@ +# defer + +defer 可以被拆分为两个步骤 `runtime.deferproc` 和 `runtime.deferreturn`。在用户函数中调用: + +```go +func f() int { + defer println(1) +} +``` + +`defer println(1)` 被翻译两个过程,先执行 `runtime.deferproc` 生成 println 函数及其相关参数的描述结构体,然后将其挂载到当前 g 的 `_defer` 指针上。先来看看 deferproc 的过程: + +## deferproc + +```go +func deferproc(siz int32, fn *funcval) { // arguments of fn follow fn + sp := getcallersp(unsafe.Pointer(&siz)) + argp := uintptr(unsafe.Pointer(&fn)) + unsafe.Sizeof(fn) + callerpc := getcallerpc() // 存储的是 caller 中,call deferproc 的下一条指令的地址 + + d := newdefer(siz) + if d._panic != nil { + throw("deferproc: d.panic != nil after newdefer") + } + d.fn = fn + d.pc = callerpc + d.sp = sp + switch siz { + case 0: + // Do nothing. + case sys.PtrSize: + *(*uintptr)(deferArgs(d)) = *(*uintptr)(unsafe.Pointer(argp)) + default: + memmove(deferArgs(d), unsafe.Pointer(argp), uintptr(siz)) + } + + return0() + // No code can go here - the C return register has + // been set and must not be clobbered. +} +``` + +比较关键的就是 newdefer: + +```go +func newdefer(siz int32) *_defer { + var d *_defer + sc := deferclass(uintptr(siz)) + gp := getg() + if sc < uintptr(len(p{}.deferpool)) { + // 从 p 结构体的 deferpool 中获取可用的 defer struct + // 代码比较简单,省略 + } + if d == nil { + // 上面没有成功获取到可用的 defer struct + // 因此需要切换到 g0 生成新的 defer struct + systemstack(func() { + total := roundupsize(totaldefersize(uintptr(siz))) + d = (*_defer)(mallocgc(total, deferType, true)) + }) + } + // defer func 的参数大小 + d.siz = siz + // 链表链接 + // 后 defer 的在前,类似一个栈结构 + d.link = gp._defer + // 修改当前 g 的 defer 结构体,指向新的 defer struct + gp._defer = d + return d +} + +``` + +`newdefer` 函数返回的结构体为 `_defer`,简单看看其结构: + +```go +type _defer struct { + siz int32 // 函数的参数总大小 + started bool // defer 是否已开始执行 + sp uintptr // 存储调用 defer 函数的函数的 sp 寄存器值 + pc uintptr // 存储 call deferproc 的下一条汇编指令的指令地址 + fn *funcval // 描述函数的变长结构体,包括函数地址及参数 + _panic *_panic // 正在执行 defer 的 panic 结构体 + link *_defer // 链表指针 +} +``` + +## deferreturn + +```go +// 编译器会在调用过 defer 的函数的末尾插入对 deferreturn 的调用 +// 如果有被 defer 的函数的话,这里会调用 runtime·jmpdefer 跳到对应的位置 +// 实际效果是会一遍遍地调用 deferreturn 直到 _defer 链表被清空 +// 这里不能进行栈分裂,因为我们要该函数的栈来调用 defer 函数 + +//go:nosplit +func deferreturn(arg0 uintptr) { + gp := getg() + d := gp._defer + if d == nil { + return + } + sp := getcallersp(unsafe.Pointer(&arg0)) + if d.sp != sp { + return + } + + switch d.siz { + case 0: + // Do nothing. + case sys.PtrSize: + *(*uintptr)(unsafe.Pointer(&arg0)) = *(*uintptr)(deferArgs(d)) + default: + memmove(unsafe.Pointer(&arg0), deferArgs(d), uintptr(d.siz)) + } + + // 把 defer 中的函数信息提取出来,清空链表上的该 _defer 节点 + fn := d.fn + d.fn = nil + // 指向 defer 链表下一个节点 + gp._defer = d.link + // 清空 defer 结构体信息,并将该结构体存储到 p 的 deferpool 中 + freedefer(d) + // 跳转 + jmpdefer(fn, uintptr(unsafe.Pointer(&arg0))) +} +``` + +对链表的持续遍历是用 jmpdefer 实现的,看看 jmpdefer 的代码: + +```go +TEXT runtime·jmpdefer(SB), NOSPLIT, $0-16 + MOVQ fv+0(FP), DX // defer 的函数的地址 + MOVQ argp+8(FP), BX // caller sp + LEAQ -8(BX), SP // caller sp after CALL + MOVQ -8(SP), BP // 在 framepointer enable 的时候,不影响函数栈的结构 + SUBQ $5, (SP) // call 指令长度为 5,因此通过将 ret addr 减 5,能够使 deferreturn 自动被反复调用 + MOVQ 0(DX), BX + JMP BX // 调用被 defer 的函数 +``` + +在 jmpdefer 所调用的函数返回时,会回到调用 deferreturn 的函数,并重新执行 deferreturn,每次执行都会使 g 的 defer 链表表头被消耗掉,直到进入 deferreturn 时 `d == nil` 并返回。至此便完成了整个 defer 的流程。 + +这里比较粗暴的是直接把栈上存储的 pc 寄存器的值减了 5,注释中说是因为 call deferreturn 这条指令长度为 5,这是怎么算出来的呢: + +```go + defertest.go:8 0x104aca4 e82754fdff CALL runtime.deferreturn(SB) + defertest.go:8 0x104aca9 488b6c2418 MOVQ 0x18(SP), BP +``` + +0x104aca9 - 0x104aca4 = 5。所以这里理论上就是一个用汇编实现的非常 trick 的 for 循环。。。 + +Q && A: + +Q: deferreturn + jmpdefer 就可以使 _defer 链表被消耗完毕,为什么还需要编译出多次 deferreturn 调用? + +A: deferproc 和 deferreturn 是成对出现的,对于编译器的实现来说,这样做应该稍微简单一些。 + +参考资料: + +https://ieevee.com/tech/2017/11/23/go-panic.html + + + + diff --git a/fasthttp/index.md b/fasthttp/index.md new file mode 100644 index 0000000..19360ee --- /dev/null +++ b/fasthttp/index.md @@ -0,0 +1,127 @@ +# fasthttp + +坊间传言 fasthttp 在某些场景下比 nginx 还要快,说明 fasthttp 中应该是做足了优化。我们来做一些相关的验证工作。 + +先是简单的 hello server 压测。下面的结果是在 mac 上得到的,linux 下可能会有差异。 + +fasthttp: +``` +~ ❯❯❯ wrk -c36 -t12 -d 5s http://127.0.0.1:8080 +Running 5s test @ http://127.0.0.1:8080 + 12 threads and 36 connections + Thread Stats Avg Stdev Max +/- Stdev + Latency 267.58us 42.44us 0.90ms 79.18% + Req/Sec 11.05k 391.97 11.79k 87.42% + 672745 requests in 5.10s, 89.18MB read +Requests/sec: 131930.78 +Transfer/sec: 17.49MB +``` + +标准库: +``` +~ ❯❯❯ wrk -c36 -t12 -d 5s http://127.0.0.1:8080 +Running 5s test @ http://127.0.0.1:10002 + 12 threads and 36 connections + Thread Stats Avg Stdev Max +/- Stdev + Latency 310.94us 163.45us 14.41ms 93.42% + Req/Sec 9.74k 1.01k 12.80k 75.82% + 593327 requests in 5.10s, 63.37MB read +Requests/sec: 116348.87 +Transfer/sec: 12.43MB +``` + +rust 的 actix,编译选项带 --release: +``` +~ ❯❯❯ wrk -c36 -t12 -d 5s http://127.0.0.1:9999 +Running 5s test @ http://127.0.0.1:9999 + 12 threads and 36 connections + Thread Stats Avg Stdev Max +/- Stdev + Latency 267.31us 20.52us 622.00us 86.07% + Req/Sec 11.11k 364.03 11.64k 82.68% + 676329 requests in 5.10s, 68.37MB read +Requests/sec: 132629.68 +Transfer/sec: 13.41MB +``` + +好家伙,虽然是 hello 服务,但是 fasthttp 在性能上竟然赶上 rust 编写的服务了,确实有点夸张。这也间接证明了,“某些场景”至少可能真的和不带 GC 的语言性能差不多。 + +说明 fasthttp 里所做的优化是值得我们做点研究的。不过 fasthttp 搞的这些优化点也并不是很神奇,首先是很常见的 goroutine workerpool,对创建的 goroutine 进行了重用,其本身的 workerpool 结构: + +```go +type workerPool struct { + // Function for serving server connections. + // It must leave c unclosed. + WorkerFunc ServeHandler + ..... + ready []*workerChan +} +``` + +核心就是 ready 数组,该数组的元素是已经创建出来的 goroutine 的 job channel。 + +```go +type workerChan struct { + lastUseTime time.Time + ch chan net.Conn +} +``` + +这么多年过去了,基本的 workerpool 的模型还是没什么变化。最早大概是在 [handling 1 million requests with go](https://medium.com/smsjunk/handling-1-million-requests-per-minute-with-golang-f70ac505fcaa) 提到,fasthttp 中的也只是稍有区别。 + +具体的请求处理流程也比较简单: + +> tcp accept -> workerpool.Serve -> 从 workerpool 的 ready 数组中获取一个 channel -> 将当前已 accept 的连接发送到 channel 中 -> 对端消费者调用 workerFunc + +这里这个 workerFunc 其实就是 serveConn,之所以不写死成 serveConn 主要还是为了在测试的时候能替换掉做 mock,不新鲜。 + +主要的 serve 流程: + +```go +func (s *Server) serveConn(c net.Conn) (err error) { + for { + ctx := s.acquireCtx(c) + br = acquireReader(ctx) // or br, err = acquireByteReader(&ctx) + // read request header && body + + bw = acquireWriter(ctx) + + s.Handler(ctx) // 这里就是 listenAndServe 传入的那个 handler + + if br != nil { + releaseReader(s, br) + } + + if bw != nil { + releaseWriter(s, bw) + } + + if ctx != nil { + s.releaseCtx(ctx) + } + } +} +``` + +在整个 serve 流程中,几乎所有对象全部都进行了重用,ctx(其中有 Request 和 Response 结构),reader,writer,body read buffer。可见作者对于内存重用到达了偏执的程度。 + +同时,对于 header 的处理,rawHeaders 是个大 byte 数组。解析后的 header 的 value 如果是字符串类型,其实都是指向这个大 byte 数组的,不会重复生成很多小对象: + +![fasthttp-1](/content/images/2020/06/fasthttp-1.png) + + +如果是我们自己写这种 kv 结构的 header,大概率就直接 map[string][]string 上了。 + +通过阅读 serveConn 的流程我们也可以发现比较明显的问题,在执行完用户的 Handler 之后,fasthttp 会将所有相关的对象全部释放并重新推进对象池中,在某些场景下,这样做显然是不合适的,举个例子: + +![fasthttp-Page-2](/content/images/2020/06/fasthttp-Page-2.png) + +当用户流程中异步启动了 goroutine,并且在 goroutine 中使用 ctx.Request 之类对象时就会遇到并发问题,因为在 fasthttp 的主流程中认为 ctx 的生命周期已经结束,将该 ctx 放回了 sync.Pool,然而用户依然在使用。想要避免这种问题,用户需要将各种 fasthttp 返回的对象人肉拷贝一遍。 + +从这点上来看,基于 sync.Pool 的性能优化往往也是有代价的,无论在什么场景下使用 sync.Pool,都需要对应用程序中的对象生命周期进行一定的假设,这种假设并不见得适用于 100% 的场景,否则这些手段早就进标准库,而非开源库了。 + +对于库的用户来说,这样的优化手段轻则带来更高的心智负担,重则是线上 bug。在使用开源库之前,还是要多多注意。非性能敏感的业务场景,还是用标准库比较踏实。 + +## 参考资料 + +[1] https://github.com/valyala/fasthttp +[2] https://medium.com/smsjunk/handling-1-million-requests-per-minute-with-golang-f70ac505fca diff --git a/futex.md b/futex.md index 812d091..9d51161 100644 --- a/futex.md +++ b/futex.md @@ -235,3 +235,6 @@ http://blog.sina.com.cn/s/blog_e59371cc0102v29b.html https://www.jianshu.com/p/570a61f08e27 https://eli.thegreenplace.net/2018/basics-of-futexes/ + + + diff --git a/gc.md b/gc.md index 75322af..b7973ed 100644 --- a/gc.md +++ b/gc.md @@ -1,5 +1,261 @@ # Garbage Collection +## 大致流程 + +GC 和用户线程并发运行,在 GC 的概念中常见的 mutator 这个词是 Dijkstra 发明的,mutator 本意是改变者,变异子,在 GC 中将用户程序称为 mutator,是因为用户代码会不断地改变对象之间的引用关系。所以我们也看到有人说 mutator 是 fancy word for the 'real program') +``` +// +// The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple +// GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier. It is +// non-generational and non-compacting. Allocation is done using size segregated per P allocation +// areas to minimize fragmentation while eliminating locks in the common case. +// +// The algorithm decomposes into several steps. +// This is a high level description of the algorithm being used. For an overview of GC a good +// place to start is Richard Jones' gchandbook.org. +// +// The algorithm's intellectual heritage includes Dijkstra's on-the-fly algorithm, see +// Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, and E. F. M. Steffens. 1978. +// On-the-fly garbage collection: an exercise in cooperation. Commun. ACM 21, 11 (November 1978), +// 966-975. +// For journal quality proofs that these steps are complete, correct, and terminate see +// Hudson, R., and Moss, J.E.B. Copying Garbage Collection without stopping the world. +// Concurrency and Computation: Practice and Experience 15(3-5), 2003. +// +// 1. GC performs sweep termination. +// +// a. Stop the world. This causes all Ps to reach a GC safe-point. +// +// b. Sweep any unswept spans. There will only be unswept spans if +// this GC cycle was forced before the expected time. +// +// 2. GC performs the mark phase. +// +// a. Prepare for the mark phase by setting gcphase to _GCmark +// (from _GCoff), enabling the write barrier, enabling mutator +// assists, and enqueueing root mark jobs. No objects may be +// scanned until all Ps have enabled the write barrier, which is +// accomplished using STW. +// +// b. Start the world. From this point, GC work is done by mark +// workers started by the scheduler and by assists performed as +// part of allocation. The write barrier shades both the +// overwritten pointer and the new pointer value for any pointer +// writes (see mbarrier.go for details). Newly allocated objects +// are immediately marked black. +// +// c. GC performs root marking jobs. This includes scanning all +// stacks, shading all globals, and shading any heap pointers in +// off-heap runtime data structures. Scanning a stack stops a +// goroutine, shades any pointers found on its stack, and then +// resumes the goroutine. +// +// d. GC drains the work queue of grey objects, scanning each grey +// object to black and shading all pointers found in the object +// (which in turn may add those pointers to the work queue). +// +// e. Because GC work is spread across local caches, GC uses a +// distributed termination algorithm to detect when there are no +// more root marking jobs or grey objects (see gcMarkDone). At this +// point, GC transitions to mark termination. +// +// 3. GC performs mark termination. +// +// a. Stop the world. +// +// b. Set gcphase to _GCmarktermination, and disable workers and +// assists. +// +// c. Perform housekeeping like flushing mcaches. +// +// 4. GC performs the sweep phase. +// +// a. Prepare for the sweep phase by setting gcphase to _GCoff, +// setting up sweep state and disabling the write barrier. +// +// b. Start the world. From this point on, newly allocated objects +// are white, and allocating sweeps spans before use if necessary. +// +// c. GC does concurrent sweeping in the background and in response +// to allocation. See description below. +// +// 5. When sufficient allocation has taken place, replay the sequence +// starting with 1 above. See discussion of GC rate below. + +// Concurrent sweep. +// +// The sweep phase proceeds concurrently with normal program execution. +// The heap is swept span-by-span both lazily (when a goroutine needs another span) +// and concurrently in a background goroutine (this helps programs that are not CPU bound). +// At the end of STW mark termination all spans are marked as "needs sweeping". +// +// The background sweeper goroutine simply sweeps spans one-by-one. +// +// To avoid requesting more OS memory while there are unswept spans, when a +// goroutine needs another span, it first attempts to reclaim that much memory +// by sweeping. When a goroutine needs to allocate a new small-object span, it +// sweeps small-object spans for the same object size until it frees at least +// one object. When a goroutine needs to allocate large-object span from heap, +// it sweeps spans until it frees at least that many pages into heap. There is +// one case where this may not suffice: if a goroutine sweeps and frees two +// nonadjacent one-page spans to the heap, it will allocate a new two-page +// span, but there can still be other one-page unswept spans which could be +// combined into a two-page span. +// +// It's critical to ensure that no operations proceed on unswept spans (that would corrupt +// mark bits in GC bitmap). During GC all mcaches are flushed into the central cache, +// so they are empty. When a goroutine grabs a new span into mcache, it sweeps it. +// When a goroutine explicitly frees an object or sets a finalizer, it ensures that +// the span is swept (either by sweeping it, or by waiting for the concurrent sweep to finish). +// The finalizer goroutine is kicked off only when all spans are swept. +// When the next GC starts, it sweeps all not-yet-swept spans (if any). + +// GC rate. +// Next GC is after we've allocated an extra amount of memory proportional to +// the amount already in use. The proportion is controlled by GOGC environment variable +// (100 by default). If GOGC=100 and we're using 4M, we'll GC again when we get to 8M +// (this mark is tracked in next_gc variable). This keeps the GC cost in linear +// proportion to the allocation cost. Adjusting GOGC just changes the linear constant +// (and also the amount of extra memory used). + +// Oblets +// +// In order to prevent long pauses while scanning large objects and to +// improve parallelism, the garbage collector breaks up scan jobs for +// objects larger than maxObletBytes into "oblets" of at most +// maxObletBytes. When scanning encounters the beginning of a large +// object, it scans only the first oblet and enqueues the remaining +// oblets as new scan jobs. + + +``` + +``` + ┌─────────────────┐ + ┌───────────────────────────────────────────────────────│ forcegchelper │ + │ ├─────────────────┤ + ├───────────────────────────────────────────────────────│ GC │ + │ ├─────────────────┤ + ├───────────────────────────────────────────────────────│ mallocgc │ + │ └─────────────────┘ + ▼ + ┌──────────────────┐ + ┌─────────────────────────────────────┐ │ gcStart │ + │ │ ├───┬──────────────┴────────────────────┐ + ▼ │ │ 1 │ semacquire(&work.startSema) │ + ┌───────────────┐ │ ├───┼───────────────────────────────────┤ ┌────────────────┐ + │ startCycle │ │ │ 2 │ semacquire(&worldsema) │ │ schedule() │ + ├───┬───────────┴───────────────────────┐ │ ├───┼───────────────────────────────────┤ ┌─────────────────────────┐ ├────────────────┴──────────────────────┐ + │ 1 │ init gcControllerState │ │ │ 3 │ gcBgMarkStartWorkers() │───────────▶│ gcBgMarkStartWorkers() │ │ ..... │ + ├───┼───────────────────────────────────┤ │ ├───┼───────────────────────────────────┤ ├───┬─────────────────────┴─────────────┐ ├───┬───────────────────────────────────┤ + │ 2 │ calc nextgc │ │ │ 4 │ systemstack(gcResetMarkState) │ │ 1 │ loop until allp │ │ 1 │ gcBlackenEnabled != 0 │ + ├───┼───────────────────────────────────┤ │ ├───┼───────────────────────────────────┤ ├───┼───────────────────────────────────┤ ├───┼───────────────────────────────────┤ + │ 3 │ calc c.dedicatedMarkWorkersNeeded │ │ │ 5 │ systemstack(stopTheWorldWithSema) │ │ 2 │ go gcBgMarkWorker(p) │ │ 2 │ findRunnableGCWorker() │ + ├───┼───────────────────────────────────┤ │ ├───┼───────────────────────────────────┤ └───┴───────────────────────────────────┘ └───┴───────────────────────────────────┘ + │ 4 │ clear per-P state │ │ │ 6 │ systemstack(finishsweep_m()) │ │ ▲ + ├───┼───────────────────────────────────┤ │ ├───┼───────────────────────────────────┤ │ │ + │ 5 │ c.revise() │ │ │ 7 │ clearpools() │ │ │ + └───┴───────────────────────────────────┘ │ ├───┼───────────────────────────────────┤ │ │ + └────────────────────────────│ 8 │ gcController.startCycle() │ │ │ + ├───┼───────────────────────────────────┤ │ │ + │10 │ work.heapGoal = memstats.next_gc │ ▼ │ + ├───┼───────────────────────────────────┴───────────────┐┌───────────────────────────────────┐ │ + │11 │if mode != gcBackgroundMode{schedEnableUser(false)}││ go gcBgMarkWorker(p) │ │ + ├───┼───────────────────────────────────┬───────────────┘├───┬───────────────────────────────┴──────────┐ ┌───────────┴──────┐ + │11 │ setGCPhase(_GCmark) │ │ 1 │ gopark() │◀─────────────────────────────┤ wakeup │ + ├───┼───────────────────────────────────┤ ├───┼──────────────────────────────────────────┤ └──────────────────┘ + │12 │ gcBgMarkPrepare() │ │ 2 │ casgstatus(gp, _Grunning, _Gwaiting) │ + ├───┼───────────────────────────────────┤ ├───┼──────────────────────────────────────────┤ + ┌────────────────────────────────────────────────────────────────────│13 │ gcMarkRootPrepare() │ │ 3 │ gcDrain() │───────────────────────┐ + │ ├───┼───────────────────────────────────┤ ├───┼──────────────────────────────────────────┤ │ ┌──────────────────┐ + │ │14 │ gcMarkTinyAllocs() │ │ 4 │ casgstatus(gp, _Gwaiting, _Grunning) │ └───────────────────────▶│ gcDrain() │ + │ ├───┼───────────────────────────────────┤ ├───┼──────────────────────────────────────────┤ ├──────────┬───────┴────────────────────┐ + │ │15 │atomic.Store(&gcBlackenEnabled, 1) │ │ 5 │ if all worker done │ │ loop │ markroot(gcw, job) │ + │ ├───┼───────────────────────────────────┤ ├───┼──────────────────────────────────────────┤ ├──────────┼────────────────────────────┤ + │ │16 │systemstack(startTheWorldWithSema()│ │ 6 │ _p_.gcBgMarkWorker.set(nil) │ │ loop2 │ gcw.balance() │ + │ ├───┼───────────────────────────────────┤ ├───┼──────────────────────────────────────────┤ ├──────────┼────────────────────────────┤ + │ │17 │ semrelease(&work.startSema) │ │ 7 │ releasem(park.m.ptr()) │ │ loop2 │ gcw.tryGetFast() │ + │ └───┴───────────────────────────────────┘ ├───┼──────────────────────────────────────────┤ ├──────────┼────────────────────────────┤ + │ │ 8 │ gcMarkDone() │ │ loop2 │ gcw.tryGet() │ + │ └───┴──────────────────────────────────────────┘ ├──────────┼────────────────────────────┤ + │ │ │ loop2 │ scanobject(b, gcw) │ + │ │ ├──────────┼────────────────────────────┤ + │ │ │ loop2 │ flush credit to global │ + │ │ ├──────────┼────────────────────────────┤ + │ │ │ done │ gcFlushBgCredit │ + │ │ └──────────┴────────────────────────────┘ + │ │ + │ │ + │ ▼ + │ ┌────────────────┐ + │ │ gcMarkDone() │ + │ ├───┬────────────┴──────────────────────────────────┐ + ▼ │ 1 │ semacquire(&work.markDoneSema) │ +┌──────────────────────┐ ├───┼───────────────────────────────────────────────┤ +│ gcMarkRootPrepare() │ │ 2 │ gcMarkDoneFlushed = 0 │ +├──────────────────────┴────────────┐ ├───┼───────────────────────────────────────────────┤ +│ set work.nDataRoots │ │ 3 │ casgstatus(gp, _Grunning, _Gwaiting) │ +├───────────────────────────────────┤ ├───┼──────────┬──────────────────┬─────────────────┴┬──────────────────┬────────────────────────────────────┐ +│ set work.nBSSRoots │ │ 4 │ forEachP │ wbBufFlush1(_p_) │_p_.gcw.dispose() │_p_.gcw.dispose() │ atomic.Xadd(&gcMarkDoneFlushed, 1) │ +├───────────────────────────────────┤ ├───┼──────────┴──────────────────┴─────────────────┬┴──────────────────┴────────────────────────────────────┘ +│ set work.nSpanRoots │ │ 5 │ casgstatus(gp, _Gwaiting, _Grunning) │ +├───────────────────────────────────┤ ├───┼───────────────────────────────────────────────┤ +│ set work.nStackRoots │ │ 6 │ getg().m.preemptoff = "gcing" │ +├───────────────────────────────────┤ ├───┼───────────────────────────────────────────────┤ +│ set work.markrootJobs │ │ 7 │ systemstack(stopTheWorldWithSema) │ +└───────────────────────────────────┘ ┌───────────────────────────────────┐ ├───┼───────────────────────────────────────────────┤ + │ │ │ 8 │ atomic.Store(&gcBlackenEnabled, 0) │ + ▼ │ ├───┼───────────────────────────────────────────────┤ + ┌───────────────────┐ │ │ 9 │ gcWakeAllAssists() │ + │ gcMarkTermination │ │ ├───┼───────────────────────────────────────────────┤ + ├───┬───────────────┴───────────────────┐ │ │10 │ semrelease(&work.markDoneSema) │ + │ 1 │ gcBlackenEnabled -> 0 │ │ ├───┼───────────────────────────────────────────────┤ + ├───┼───────────────────────────────────┤ │ │11 │ nextTriggerRatio := gcController.endCycle() │ ┌───────────────────┐ + │ 2 │ gcphase -> _GCmarktermination │ │ ├───┼───────────────────────────────────────────────┤ │ runtime.main │ + ├───┼───────────────────────────────────┤ └─────────────────────────│12 │ gcMarkTermination(nextTriggerRatio) │ ├───────────────────┴──────┐ + │ 3 │ mp.preemptoff = "gcing" │ └───┴───────────────────────────────────────────────┘ │ ...... │ + ├───┼───────────────────────────────────┤ ├──────────────────────────┤ + │ 4 │ g : running -> waiting │ │ gcenable() │ + ├───┼───────────────────────────────────┤ └──────────────────────────┘ + │ 5 │ systemstack(gcMark) │ │ + ├───┼───────────────────────────────────┤ │ + │ 6 │ gcMark() │ │ + ┌─────────────┐ ├───┼───────────────────────────────────┤ │ + │ gcMark() │◀──────────────────────────────────────────────────────────│ 7 │ gcphase -> _GCoff │ │ + ├─────────────┴──────────────────────────────┐ ├───┼───────────────────────────────────┤ ▼ + │ loop for allp │ │ 8 │ gcSweep() │──────┐ ┌─────────────────────────┐ + ┌────┼────────────────────────────────────────────┤ ├───┼───────────────────────────────────┤ │ │ go bgsweep() │ + │for │ p.wbBuf.reset() │ │ 9 │ g : waiting -> running │ │ ├───┬─────────────────────┴─────────────────────────┐ + ├────┼────────────────────────────────────────────┤ ├───┼───────────────────────────────────┤ │ │ 1 │ sweep.g = getg() │ + │for │ gcw.dispose() │ │10 │ mp.preemptoff = "" │ │ ├───┼───────────────────────────────────────────────┤ + └────┼────────────────────────────────────────────┤ ├───┼───────────────────────────────────┤ │ │ 2 │ sweep.parked = true │ + │ cachestats() │ │11 │gcSetTriggerRatio(nextTriggerRatio)│ │ ├───┼───────────────────────────────────────────────┤ + ├────────────────────────────────────────────┤ ├───┼───────────────────────────────────┤ │ ┌─────────────────┐ │ 3 │ goparkunlock(&sweep.lock, "GC sweep wait", 1) │ + │ work.markrootDone = true │ │12 │ acc stats .... │ └─────▶│ gcSweep │ ├───┼───────────────────────────────────────────────┤ + ├────────────────────────────────────────────┤ ├───┼───────────────────────────────────┤ ├───┬─────────────┴─────────────────────┐ ┌───────────▶│for│ sweep work │ + │ cache memory stats │ │13 │ lock(&work.sweepWaiters.lock) │ │ 1 │ mheap_.sweepdone -> 0 │ │ ├───┼───────────────────────────────────────────────┤ + └────────────────────────────────────────────┘ ├───┼───────────────────────────────────┤ ├───┼───────────────────────────────────┤ │ │for│ sweep.parked = true │ + │14 │injectglist(&work.sweepWaiters.list│ │ 2 │ mheap_.pagesSwept -> 0 │ │ ├───┼───────────────────────────────────────────────┤ + ├───┼───────────────────────────────────┤ ├───┼───────────────────────────────────┤ ┌──────┴─────┐ │for│ goparkunlock(&sweep.lock, "GC sweep wait", 1) │ + │15 │ unlock(&work.sweepWaiters.lock) │ │ 3 │ sweep.parked -> false │ │ wakeup │ └───┴───────────────────────────────────────────────┘ + ├───┼───────────────────────────────────┤ ├───┼───────────────────────────────────┤ ┌──────────────────┐ └──────┬─────┘ + │16 │ systemstack startTheWorldWithSema │ │ 4 │ ready(sweep.g) │───────────────▶│ ready(sweep.g) │ │ + ├───┼───────────────────────────────────┤ └───┴───────────────────────────────────┘ ├───┬──────────────┴────────────────────┐ │ + │17 │ prepareFreeWorkbufs() │ │ 1 │ sweep.g : Gwaiting -> Grunnable │ │ + ├───┼───────────────────────────────────┤ ├───┼───────────────────────────────────┤ │ + │18 │ systemstack(freeStackSpans) │ │ 2 │ runqput(sweep.g) │ │ + ├───┼───────────────────────────────────┴┐ ├───┼───────────────────────────────────┤ │ + │ │systemstack(func() { │ │ 3 │ wakep() │◀───────────┘ + │ │ forEachP(func(_p_ *p) { │ └───┴───────────────────────────────────┘ + │...│ _p_.mcache.prepareForSweep()│ + │ │ }) │ + │ │}) │ + ├───┼───────────────────────────────────┬┘ + │19 │ semrelease(&worldsema) │ + └───┴───────────────────────────────────┘ +``` + + ## 初始化 ```go @@ -121,19 +377,15 @@ type gcTrigger struct { type gcTriggerKind int const ( - // gcTriggerAlways indicates that a cycle should be started - // unconditionally, even if GOGC is off or we're in a cycle - // right now. This cannot be consolidated with other cycles. + // 表示应该无条件地开始 GC,不管外部任何参数 + // 即使 GOGC 设置为 off,或者当前已经在进行 GC 进行中 gcTriggerAlways gcTriggerKind = iota - // gcTriggerHeap indicates that a cycle should be started when - // the heap size reaches the trigger heap size computed by the - // controller. + // 该枚举值表示 GC 会在 heap 大小达到 controller 计算出的阈值之后开始 gcTriggerHeap - // gcTriggerTime indicates that a cycle should be started when - // it's been more than forcegcperiod nanoseconds since the - // previous GC cycle. + // 表示从上一次 GC 之后,经过了 forcegcperiod 纳秒 + // 基于时间触发本次 GC gcTriggerTime // gcTriggerCycle indicates that a cycle should be started if @@ -146,7 +398,6 @@ const ( ### mallocgc 中的 trigger 类型是 gcTriggerHeap; ```go - if shouldhelpgc { if t := (gcTrigger{kind: gcTriggerHeap}); t.test() { gcStart(gcBackgroundMode, t) @@ -154,6 +405,8 @@ const ( } ``` +在 mallocgc 中进行 gc 可以防止内存分配过快,导致 GC 回收不过来。 + ### runtime.GC 中使用的是 gcTriggerCycle; ```go @@ -225,12 +478,12 @@ func (t gcTrigger) test() bool { ## gcStart ```go -// gcStart transitions the GC from _GCoff to _GCmark (if -// !mode.stwMark) or _GCmarktermination (if mode.stwMark) by -// performing sweep termination and GC initialization. +// 该函数会将 GC 状态从 _GCoff 切换到 _GCmark(if !mode.stwMark) +// 或者 _GCmarktermination(if mode.stwMark) +// 开始执行 sweep termination 或者 GC 初始化 // -// This may return without performing this transition in some cases, -// such as when called on a system stack or with locks held. +// 函数可能会在一些情况下未进行状态变更就返回 +// 比如在 system stack 中被调用,或者 locks 被别人持有 func gcStart(mode gcMode, trigger gcTrigger) { // Since this is called from malloc and malloc is called in // the guts of a number of libraries that might be holding @@ -258,10 +511,9 @@ func gcStart(mode gcMode, trigger gcTrigger) { sweep.nbgsweep++ } - // Perform GC initialization and the sweep termination - // transition. + // 进行 GC 初始化和 sweep termination semacquire(&work.startSema) - // Re-check transition condition under transition lock. + // 在 transition lock 下再检查一次 transition 条件 if !trigger.test() { semrelease(&work.startSema) return @@ -282,13 +534,11 @@ func gcStart(mode gcMode, trigger gcTrigger) { } } - // Ok, we're doing it! Stop everybody else + // 获取全局锁,让别人都停下 stw semacquire(&worldsema) - if trace.enabled { - traceGCStart() - } - + // 在 background 模式下 + // 启动所有标记 worker if mode == gcBackgroundMode { gcBgMarkStartWorkers() } @@ -308,25 +558,25 @@ func gcStart(mode gcMode, trigger gcTrigger) { now := nanotime() work.tSweepTerm = now work.pauseStart = now - if trace.enabled { - traceGCSTWStart(1) - } + systemstack(stopTheWorldWithSema) // Finish sweep before we start concurrent scan. systemstack(func() { finishsweep_m() }) - // clearpools before we start the GC. If we wait they memory will not be - // reclaimed until the next GC cycle. + + // 清除全局的 : + // 1. sudogcache(sudog 数据结构的链表) + // 2. deferpool(defer struct 的链表的数组) + // 3. sync.Pool clearpools() work.cycles++ - if mode == gcBackgroundMode { // Do as much work concurrently as possible + if mode == gcBackgroundMode { // 尽量多地提高并发度 gcController.startCycle() work.heapGoal = memstats.next_gc - // Enter concurrent mark phase and enable - // write barriers. + // 进入并发标记阶段,并让 write barriers 开始生效 // // Because the world is stopped, all Ps will // observe that write barriers are enabled by @@ -358,27 +608,21 @@ func gcStart(mode gcMode, trigger gcTrigger) { // mutators. atomic.Store(&gcBlackenEnabled, 1) - // Assists and workers can start the moment we start - // the world. + // 协助标记的 g 和 worker 在 start the world 之后就可以开始工作了 gcController.markStartTime = now - // Concurrent mark. + // 并发标记 systemstack(func() { now = startTheWorldWithSema(trace.enabled) }) work.pauseNS += now - work.pauseStart work.tMark = now } else { - if trace.enabled { - // Switch to mark termination STW. - traceGCSTWDone() - traceGCSTWStart(0) - } t := nanotime() work.tMark, work.tMarkTerm = t, t work.heapGoal = work.heap0 - // Perform mark termination. This will restart the world. + // 进行 mark termination 阶段的工作,会 restart the world gcMarkTermination(memstats.triggerRatio) } @@ -487,3 +731,16 @@ func GC() { ## FAQ 为什么需要 debug.FreeOsMemory 才能释放堆空间。 + +concurrent sweep 和普通后台sweep有什么区别,分别在什么时间触发 + +stw的时候在干什么 + +优化gc主要是在优化什么 + +gc时间,stw时间和响应延迟之间是什么关系 + +宏观来看gc划分为多少个阶段 + + + diff --git a/gc_write_barrier.md b/gc_write_barrier.md new file mode 100644 index 0000000..d606aff --- /dev/null +++ b/gc_write_barrier.md @@ -0,0 +1,37 @@ +# GC write barrier 详解 + +在垃圾回收领域所讲的 barrier 包括 read barrier 与 write barrier,无论是哪一种,都与并发编程领域的 memory barrier 不是一回事。 + +在 GC 中的 barrier 其本质是 : snippet of code insert before pointer modify。 + +所以在阅读相关材料时,请注意不要将两者混淆。 + +在当前 Go 语言的实现中,GC 只有 write barrier,没有 read barrier。 + +在应用进入 GC 标记阶段前的 stw 阶段,会将全局变量 runtime.writeBarrier.enabled 修改为 true,当应用从 STW 中恢复,重新开始执行,垃圾回收的标记阶段便与应用逻辑开始并发执行,这时所有的堆上指针修改操作在修改之前会额外调用 runtime.gcWriteBarrier: + +![](./images/garbage_collection/barrier_asm.png) + +我们随便找找这些反汇编结果在代码中对应的行: + +![](./images/garbage_collection/barrier_code.png) + +Go 语言当前使用了混合 barrier 来实现 gc 标记期间的被修改对象动态跟踪,早期只使用了 Dijistra 插入 barrier,但 Dijistra barrier 需要在标记完成之后进行栈重扫,因此在 1.8 时修改为混合 barrier。 + +Dijistra 插入屏障伪代码如下: + +![](http://xargin.com/content/images/2021/12/image-42.png) + +堆上指针修改时,新指向的对象要标灰。 + +但是因为 Go 的栈上对象不加 barrier,所以会存在对象丢失的问题: + +![](http://xargin.com/content/images/2021/12/djb.gif) + +还有一种非常有名的 barrier,Yuasa 删除屏障,与 Dijistra 屏障相反,它是在堆指针指向的对象发生变化时,将之前指向的对象标灰: + +![](http://xargin.com/content/images/2021/12/image-43.png) + +和 Dijistra 类似,也存在对象漏标问题: + +![](http://xargin.com/content/images/2021/12/yb.gif) diff --git a/generics.md b/generics.md new file mode 100644 index 0000000..4a36142 --- /dev/null +++ b/generics.md @@ -0,0 +1,44 @@ +# Generics + +在泛型出现之前,社区里也有一些伪泛型方案,例如 [genny](https://github.com/cheekybits/genny)。 + +genny 本质是基于文本替换的,比如 example 里的例子: + +```go +package queue + +import "github.com/cheekybits/genny/generic" + +// NOTE: this is how easy it is to define a generic type +type Something generic.Type + +// SomethingQueue is a queue of Somethings. +type SomethingQueue struct { + items []Something +} + +func NewSomethingQueue() *SomethingQueue { + return &SomethingQueue{items: make([]Something, 0)} +} +func (q *SomethingQueue) Push(item Something) { + q.items = append(q.items, item) +} +func (q *SomethingQueue) Pop() Something { + item := q.items[0] + q.items = q.items[1:] + return item +} +``` + +执行替换命令: + +```shell +cat source.go | genny gen "Something=string" +``` + +然后 genny 会将代码中所有 Something 替换成 string,同时确保大小写与原来一致,不影响字段/类型的导出特征。 + +没有官方的泛型支持,社区怎么搞都是邪道。2021 年 1 月,官方的方案已经基本上成型,并释出了 [draft design](https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md)。 + + + diff --git a/goroutine.md b/goroutine.md index 0de6ace..38b020b 100644 --- a/goroutine.md +++ b/goroutine.md @@ -7,4 +7,6 @@ > Written with [StackEdit](https://stackedit.io/). \ No newline at end of file +--> + + diff --git a/images/garbage_collection/barrier_asm.png b/images/garbage_collection/barrier_asm.png new file mode 100644 index 0000000..5012031 Binary files /dev/null and b/images/garbage_collection/barrier_asm.png differ diff --git a/images/garbage_collection/barrier_code.png b/images/garbage_collection/barrier_code.png new file mode 100644 index 0000000..5f971b0 Binary files /dev/null and b/images/garbage_collection/barrier_code.png differ diff --git a/images/garbage_collection/tricolor.png b/images/garbage_collection/tricolor.png new file mode 100644 index 0000000..b711acf Binary files /dev/null and b/images/garbage_collection/tricolor.png differ diff --git a/images/gzh.png b/images/gzh.png new file mode 100644 index 0000000..58046bb Binary files /dev/null and b/images/gzh.png differ diff --git a/images/mesi_1.jpg b/images/mesi_1.jpg new file mode 100644 index 0000000..47673f4 Binary files /dev/null and b/images/mesi_1.jpg differ diff --git a/images/signal.png b/images/signal.png new file mode 100644 index 0000000..6ba194a Binary files /dev/null and b/images/signal.png differ diff --git a/interface.md b/interface.md index 2d830dc..a365ff4 100644 --- a/interface.md +++ b/interface.md @@ -1,8 +1,547 @@ -# interface -## iface 和 eface +#### 从类型定义说起 +首先来看一段代码 +```go +package main -> Written with [StackEdit](https://stackedit.io/). - \ No newline at end of file +type eface_struct struct { + f float32 + i int +} + +func main() { + var test_interface interface{} + test_interface = eface_struct{} + _ = test_interface +} +``` +在这段简单的代码中我们声明了 `test_interface` 是一个不含任何函数的基础 `interface` 结构,并把 `eface_struct` 类型结构体赋予了它 + +那么我们来看看编译器是如何处理`声明`这一过程的 +> go tool compile -l -S -N ./test.go +> 注意这边将编译器优化关闭`-N`,以便我们更好的看看编译器的工作流程 + + +```assembly +(... 以下已去除多余代码) +"".main STEXT nosplit size=91 args=0x0 locals=0x38 + 0x0000 00000 (./test.go:8) TEXT "".main(SB), NOSPLIT|ABIInternal, $56-0 + 0x0000 00000 (./test.go:8) SUBQ $56, SP + 0x0004 00004 (./test.go:8) MOVQ BP, 48(SP) + 0x0009 00009 (./test.go:8) LEAQ 48(SP), BP + 0x000e 00014 (./test.go:8) PCDATA $0, $-2 + 0x000e 00014 (./test.go:8) PCDATA $1, $-2 + 0x000e 00014 (./test.go:8) FUNCDATA $0, gclocals·33cdeccccebe80329f1fdbee7f5874cb(SB) + 0x000e 00014 (./test.go:8) FUNCDATA $1, gclocals·f207267fbf96a0178e8758c6e3e0ce28(SB) + 0x000e 00014 (./test.go:8) FUNCDATA $2, gclocals·9fb7f0986f647f17cb53dda1484e0f7a(SB) + 0x000e 00014 (./test.go:9) PCDATA $0, $0 + 0x000e 00014 (./test.go:9) PCDATA $1, $0 + 0x000e 00014 (./test.go:9) XORPS X0, X0 + 0x0011 00017 (./test.go:9) MOVUPS X0, "".test_interface+32(SP) + 0x0016 00022 (./test.go:10) XORPS X0, X0 + 0x0019 00025 (./test.go:10) MOVSS X0, ""..autotmp_1+16(SP) + 0x001f 00031 (./test.go:10) MOVQ $0, ""..autotmp_1+24(SP) + 0x0028 00040 (./test.go:10) MOVSS ""..autotmp_1+16(SP), X0 + 0x002e 00046 (./test.go:10) MOVSS X0, ""..autotmp_2(SP) + 0x0033 00051 (./test.go:10) MOVQ $0, ""..autotmp_2+8(SP) + 0x003c 00060 (./test.go:10) PCDATA $0, $1 + 0x003c 00060 (./test.go:10) LEAQ type."".eface_struct(SB), AX + 0x0043 00067 (./test.go:10) PCDATA $0, $0 + 0x0043 00067 (./test.go:10) MOVQ AX, "".test_interface+32(SP) + 0x0048 00072 (./test.go:10) PCDATA $0, $1 + 0x0048 00072 (./test.go:10) LEAQ ""..autotmp_2(SP), AX + 0x004c 00076 (./test.go:10) PCDATA $0, $0 + 0x004c 00076 (./test.go:10) MOVQ AX, "".test_interface+40(SP) + 0x0051 00081 (./test.go:12) MOVQ 48(SP), BP + 0x0056 00086 (./test.go:12) ADDQ $56, SP + 0x005a 00090 (./test.go:12) RET + 0x0000 48 83 ec 38 48 89 6c 24 30 48 8d 6c 24 30 0f 57 H..8H.l$0H.l$0.W + 0x0010 c0 0f 11 44 24 20 0f 57 c0 f3 0f 11 44 24 10 48 ...D$ .W....D$.H + 0x0020 c7 44 24 18 00 00 00 00 f3 0f 10 44 24 10 f3 0f .D$........D$... + 0x0030 11 04 24 48 c7 44 24 08 00 00 00 00 48 8d 05 00 ..$H.D$.....H... + 0x0040 00 00 00 48 89 44 24 20 48 8d 04 24 48 89 44 24 ...H.D$ H..$H.D$ + 0x0050 28 48 8b 6c 24 30 48 83 c4 38 c3 (H.l$0H..8. + rel 63+4 t=16 type."".eface_struct+0 ...i +type."".eface_struct SRODATA size=144 + 0x0000 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0010 ca b4 29 a7 07 08 08 19 00 00 00 00 00 00 00 00 ..)............. + 0x0020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0040 02 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 ................ + 0x0050 00 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 ........@....... + 0x0060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0080 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 ................ + rel 24+8 t=1 type..eqfunc."".eface_struct+0 + rel 32+8 t=1 runtime.gcbits.+0 + rel 40+4 t=5 type..namedata.*main.eface_struct-+0 + rel 44+4 t=5 type.*"".eface_struct+0 + rel 48+8 t=1 type..importpath."".+0 + rel 56+8 t=1 type."".eface_struct+96 + rel 80+4 t=5 type..importpath."".+0 + rel 96+8 t=1 type..namedata.f-+0 + rel 104+8 t=1 type.float32+0 + rel 120+8 t=1 type..namedata.i-+0 + rel 128+8 t=1 type.int+0 +``` +那么其中的 +```assembly + 0x003c 00060 (./test.go:10) LEAQ type."".eface_struct(SB), AX + 0x0043 00067 (./test.go:10) PCDATA $0, $0 + 0x0043 00067 (./test.go:10) MOVQ AX, "".test_interface+32(SP) + 0x0048 00072 (./test.go:10) PCDATA $0, $1 + 0x0048 00072 (./test.go:10) LEAQ ""..autotmp_2(SP), AX + 0x004c 00076 (./test.go:10) PCDATA $0, $0 + 0x004c 00076 (./test.go:10) MOVQ AX, "".test_interface+40(SP) +``` +就是对 `test_interface` 变量的赋值过程了,可以看到首先将`type."".eface_struct`放到了该变量的首字节地址上 + +##### type."".eface_struct 是什么? +在声明一个结构体的同时, 编译器会在只读内存段定义对应的 `*face` 结构,在平时正常使用 `struct` 的时候,编译器会通过用户定义的结构进行内存布局的计算来满足结构体的实现,这是属于普通情况的使用,而一旦涉及到`interface`,那么这个`*face`结构就开始发挥它的作用了 +##### interface 的声明和赋值过程到底干了些什么? + +> var test_interface interface{} +> test_interface = eface_struct{} + +让我们来看看对 `test_interface` 这个 `interface` 类型变量赋值的过程 +对应 assembly: +```assembly + # 将 type."".eface_struct 这个 *face 结构插入 test_interface 首地址 + x003c 00060 (./test.go:10) LEAQ type."".eface_struct(SB), AX + 0x0043 00067 (./test.go:10) PCDATA $0, $0 + 0x0043 00067 (./test.go:10) MOVQ AX, "".test_interface+32(SP) # 不用纠结这边的 32 偏移量,与局部变量有关,可认为 test_interface 起始地址为 32(SP) + 0x0048 00072 (./test.go:10) PCDATA $0, $1 + 0x0048 00072 (./test.go:10) LEAQ ""..autotmp_2(SP), AX + 0x004c 00076 (./test.go:10) PCDATA $0, $0 + # test_interface 数据部分值插入,偏移量为 40-32 = 8 + 0x004c 00076 (./test.go:10) MOVQ AX, "".test_interface+40(SP) +``` +这边的案例首先分析的是不包含 `func` 的 `interface`,对应的 `*face` 结构为 `eface` +```go +// src/runtime/runtime2.go +type eface struct { + _type *_type // size 8 正好对应上述 assembly 部分 *face 结构插入 + data unsafe.Pointer // 数据部分 +} +// src/runtime/type.go +type _type struct { + size uintptr + ptrdata uintptr // size of memory prefix holding all pointers + hash uint32 + tflag tflag + align uint8 + fieldAlign uint8 + kind uint8 + // function for comparing objects of this type + // (ptr to object A, ptr to object B) -> ==? + equal func(unsafe.Pointer, unsafe.Pointer) bool + // gcdata stores the GC type data for the garbage collector. + // If the KindGCProg bit is set in kind, gcdata is a GC program. + // Otherwise it is a ptrmask bitmap. See mbitmap.go for details. + gcdata *byte + str nameOff + ptrToThis typeOff +} +``` +再看 `_type` 结构,那么有了到目前为止的分析,我们可以试着来将该结构与编译器自动生成的`type."".eface_struct`对应着拆解看看 +```assembly +type."".eface_struct SRODATA size=144 + 0x0000 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0010 ca b4 29 a7 07 08 08 19 00 00 00 00 00 00 00 00 ..)............. + 0x0020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0040 02 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 ................ + 0x0050 00 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 ........@....... + 0x0060 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0080 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 ................ + #------------------------ 24 字节 ---------------- + rel 24+8 t=1 type..eqfunc."".eface_struct+0 # 对应 _type.equal + rel 32+8 t=1 runtime.gcbits.+0 + rel 40+4 t=5 type..namedata.*main.eface_struct-+0 + rel 44+4 t=5 type.*"".eface_struct+0 + rel 48+8 t=1 type..importpath."".+0 + rel 56+8 t=1 type."".eface_struct+96 + rel 80+4 t=5 type..importpath."".+0 + rel 96+8 t=1 type..namedata.f-+0 + rel 104+8 t=1 type.float32+0 + rel 120+8 t=1 type..namedata.i-+0 + rel 128+8 t=1 type.int+0 +``` + +```go +fmt.Println(reflect.TypeOf(test_interface)) +/* + * reflect.rtype + * |- size: 16 + * |- ptrdata:0 + * |- hash 2804528330 + const ( + // tflagUncommon means that there is a pointer, *uncommonType, + // just beyond the outer type structure. + // + // For example, if t.Kind() == Struct and t.tflag&tflagUncommon != 0, + // then t has uncommonType data and it can be accessed as: + // + // type tUncommon struct { + // structType + // u uncommonType + // } + // u := &(*tUncommon)(unsafe.Pointer(t)).u + tflagUncommon tflag = 1 << 0 + + // tflagExtraStar means the name in the str field has an + // extraneous '*' prefix. This is because for most types T in + // a program, the type *T also exists and reusing the str data + // saves binary size. + tflagExtraStar tflag = 1 << 1 + + // tflagNamed means the type has a name. + tflagNamed tflag = 1 << 2 + + // tflagRegularMemory means that equal and hash functions can treat + // this type as a single region of t.size bytes. + tflagRegularMemory tflag = 1 << 3 +) + * |- tflag:tflagUncommon|tflagExtraStar|tflagNamed (7) + * |- align:8 + * |- fieldAlign:8 + * |- kind:25 + * |- equal:type..eq.main.eface_struct + * |- gcdata:<*uint8>(0x11004e6) + * |- str:23831 nameOff,通过该字段及 base pointer 计算偏移量来获取 struct name 相关信息 + * |_ ptrToThis:38080 + */ +``` +- size:16 + - 0x 00 00 00 00 00 00 00 10 +- ptrdata:0 + - 0x 00 00 00 00 00 00 00 00 +- hash:2804528330 + - 0x a7 29 b4 ca + +大小端的关系,和上述`assembly`中的前 20 个字节顺序相反,分析到这儿就可以知道`interface`结构整体的情况,以及起核心作用的为`*face`字段,此处分析了`eface`,而另一种带有函数实现的`interface`的`iface`结构也可以通过相同的过程拆解,值得一提的是`iface`结构首字段的`itab`结构内部也内置了 `_type`结构,所以编译器可以通过相同的赋值过程处理这两种类型的`interface` +# iface 和 eface + +Go 使用 iface 和 eface 来表达 interface。iface 其实就是 interface,这种接口内部是有函数的。 + +eface 表示 empty interface。 + +非空接口: +```go +// runtime2.go +type iface struct { + tab *itab + data unsafe.Pointer +} + +type itab struct { + inter *interfacetype + _type *_type + hash uint32 // copy of _type.hash. Used for type switches. + _ [4]byte + fun [1]uintptr // variable sized. fun[0]==0 means _type does not implement inter. +} +``` + +空接口: + +```go +type eface struct { + _type *_type + data unsafe.Pointer +} +``` + +所以我们可以比较容易地推断出来下面两种 interface 在 Go 内部是怎么表示的: + +iface: + +```go +type Reader interface { + Read([]byte) (int, error) +} +``` + +eface: + +```go +var x interface{} +``` + +## iface + +### iface 适用场景 + +在 Go 语言中,我们可以借助 iface,实现传统 OOP 编程中的 DIP(dependency inversion principle),即依赖反转。 + +```go + ┌─────────────────┐ + │ business logic │ + └─────────────────┘ + │ + │ + │ + ┌───────────────────────────────┼───────────────────────────────┐ + │ │ │ + │ │ │ + │ │ │ + ▼ ▼ ▼ +┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ +│ RPC │ │ DATABASE │ │ CONFIG_SERVICE │ +└─────────────────┘ └─────────────────┘ └─────────────────┘ +``` + +上面这样的控制流关系在企业软件中很常见,但如果我们让软件的依赖方向与实际控制流方向一致,很容易导致 RPC、CONFIG_SERVER,DATABASE 的抽象被泄露到上层。例如在业务逻辑中有形如下面的结构体定义: + +```go +type Person struct { + Age int `db:"age"` + Name string `db:"name"` +} +``` + +或者在业务逻辑中有类似下面的字眼: + +```go +func CreateOrder(order OrderStruct) { + config := GetConfigFromETCD() // abstraction leak + CalcOrderMinusByConfig(config, order) + SaveOrder() +} +``` + +业务逻辑不应该知道底层的实现,不应该有形如 db 的 tag,不应该知道配置是从 ETCD 中取出的。 + +``` +┌──────────────────────────────────────────────────────────────┐ +│ │ +│ │ +│ business logic │ +├────────────────────┬────────────────────┬────────────────────┤ +│ configInterface │ storeInterface │ getInterface │ +└────────────────────┴────────────────────┴────────────────────┘ + ▲ ▲ ▲ + │ │ │ + │ │ │ + │ │ │ + │ │ │ + │ │ │ + │ │ │ + │ │ │ + ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ + │ etcd Impl │ │ DATABASE │ │ RPC │ + └─────────────────┘ └─────────────────┘ └─────────────────┘ +``` + +## eface + +从定义来看,eface 其实是 iface 的一个子集: + +``` +┌─────────┐ ┌─────────┐ +│ iface │ ┌─────▶│ itab │ +├─────────┴───────────────────┐ │ ├─────────┴───────────────────┐ +│ tab *itab │──────┘ │ inter *interfacetype │ +┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ ├─────────────────────────────┤ +┃ data unsafe.Pointer ┃ ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ +┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ ┃ _type *_type ┃ + ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫ + ├─────────────────────────────┤ + │ hash uint32 │ + ├─────────────────────────────┤ + │ fun [1]uintptr │ + └─────────────────────────────┘ +┌─────────┐ +│ eface │ +├─────────┴───────────────────┐ +│ _type *_type │ +├─────────────────────────────┤ +│ data unsafe.Pointer │ +└─────────────────────────────┘ +``` + +既然是个子集,那已经有了 iface 为什么还需要 eface?显然是为了优化。 + +### eface 适用场景 + +举个标准库里的例子: + +```go +func Slice(slice interface{}, less func(i, j int) bool) +``` + +标准库的 container package,因为不知道用户会在 container 中存储什么类型,所以大部分 API 也是用 interface{} 的。 + +除了标准库,我们在 fmt.Print 系列和 json.Unmarshal 中也会见到 interface{}。 + +```go +func Println(a ...interface{}) (n int, err error) +``` + +```go +func Unmarshal(data []byte, v interface{}) error +``` + +总结一下,使用 interface 主要是我们在不知道用户的输入类型信息的前提下,希望能够实现一些通用数据结构或函数。这时候便会将空 interface{} 作为函数的输入/输出参数。在其它语言里,解决这种问题一般使用泛型。 + +## 类型转换 + +### 普通类型转换为 eface + +```go + 1 package main + 2 + 3 var i interface{} + 4 + 5 func main() { + 6 var y = 999 + 7 i = y + 8 var x = i.(int) + 9 println(x) +10 } +``` + +老规矩,看汇编知一切,主要是第 7 行: + +```go +0x0021 00033 (interface.go:7) MOVQ $999, (SP) // 把 999 作为参数挪到栈底 +0x0029 00041 (interface.go:7) CALL runtime.convT64(SB) // 以 999 作为参数调用 runtime.convT64,内部会为该变量在堆上分配额外空间,并返回其地址 +0x002e 00046 (interface.go:7) MOVQ 8(SP), AX // 返回值移动到 AX 寄存器 +0x0033 00051 (interface.go:7) LEAQ type.int(SB), CX // 将 type.int 值赋值给 CX 寄存器 +0x003a 00058 (interface.go:7) MOVQ CX, "".i(SB) // 将 type.int 赋值给 eface._type +0x004a 00074 (interface.go:7) MOVQ AX, "".i+8(SB) // 将数据 999 的地址赋值给 eface.data +``` + +还是比较简单的。 + +### eface 转换为普通类型 + +空接口转成普通类型,其实就是断言。我们继续使用上面的 demo: + +```go + 1 package main + 2 + 3 var i interface{} + 4 + 5 func main() { + 6 var y = 999 + 7 i = y + 8 var x = i.(int) // 这次关注断言的实现 + 9 println(x) +10 } +``` + +看看第 8 行的输出: + +```go +0x0033 00051 (interface.go:7) LEAQ type.int(SB), CX // 在第 7 行把 type.int 搬到 CX 寄存器了,注意下面要用到 +..... +0x0051 00081 (interface.go:8) MOVQ "".i+8(SB), AX // AX = eface.data +0x0058 00088 (interface.go:8) MOVQ "".i(SB), DX // DX = eface._type +0x005f 00095 (interface.go:8) CMPQ DX, CX // 比较 _type 和 type.int 是否相等 +0x0062 00098 (interface.go:8) JNE 161 // 如果不等,说明断言失败,跳到 161 位置,开始执行 panic 流程 +0x0064 00100 (interface.go:8) MOVQ (AX), AX // 把 AX 地址里的内容搬到 AX 寄存器,现在 AX 里存的是 999 了 +0x0067 00103 (interface.go:8) MOVQ AX, "".x+24(SP) // 将 999 赋值给变量 x + +// 下面这部分是实现 panic 的,不是我们的重点 +0x00a1 00161 (interface.go:8) MOVQ DX, (SP) +0x00a5 00165 (interface.go:8) MOVQ CX, 8(SP) +0x00aa 00170 (interface.go:8) LEAQ type.interface {}(SB), AX +0x00b1 00177 (interface.go:8) MOVQ AX, 16(SP) +0x00b6 00182 (interface.go:8) CALL runtime.panicdottypeE(SB) +0x00bb 00187 (interface.go:8) XCHGL AX, AX +0x00bc 00188 (interface.go:8) NOP +``` + +也挺简单的,这里我们用的是 int 来进行实验,对于稍微复杂一些的复合类型,也只是多出了一些步骤,本质上没有什么区别,感兴趣的读者可以自行研究。 + +### 普通类型转换为 iface + +```go + 1 package main + 2 + 3 import ( + 4 "io" + 5 "os" + 6 ) + 7 + 8 var j io.Reader + 9 +10 func main() { +11 var i, _ = os.Open("ab.go") +12 j = i +13 var k = j.(*os.File) +14 println(k) +15 } +``` + +看看第 12 行的汇编: + +```go +0x0050 00080 (interface2.go:12) LEAQ go.itab.*os.File,io.Reader(SB), CX +0x0057 00087 (interface2.go:12) MOVQ CX, "".j(SB) +0x0067 00103 (interface2.go:12) MOVQ AX, "".j+8(SB) +``` + +和 eface 的赋值其实差不多,稍微有区别的是这里的 go.itab.*os.File,io.Reader(SB),这个符号(理解成一个全局变量,类型是 runtime._type 就行)是编译器帮我们生成的: + +```go +go.itab.*os.File,io.Reader SRODATA dupok size=32 + 0x0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0010 44 b5 f3 33 00 00 00 00 00 00 00 00 00 00 00 00 D..3............ + rel 0+8 t=1 type.io.Reader+0 + rel 8+8 t=1 type.*os.File+0 + rel 24+8 t=1 os.(*File).Read+0 +``` + +并且是按需生成的,如果你把 `*os.File` 赋值给 io.Writer,在编译结果中也能找到类似的符号: + +```go +go.itab.*os.File,io.Writer SRODATA dupok size=32 + 0x0000 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ + 0x0010 44 b5 f3 33 00 00 00 00 00 00 00 00 00 00 00 00 D..3............ + rel 0+8 t=1 type.io.Writer+0 + rel 8+8 t=1 type.*os.File+0 + rel 24+8 t=1 os.(*File).Write+0 +``` + +看起来就容易理解了。 + +### iface 转换为普通类型 + +```go + 1 package main + 2 + 3 import ( + 4 "io" + 5 "os" + 6 ) + 7 + 8 var j io.Reader + 9 +10 func main() { +11 var i, _ = os.Open("ab.go") +12 j = i +13 var k = j.(*os.File) +14 println(k) +15 } +``` + +主要关心第 13 行的汇编结果: + +```go +// 数据准备在这里,AX 和 CX 寄存器 13 行会用到 +0x0050 00080 (interface2.go:12) LEAQ go.itab.*os.File,io.Reader(SB), CX +0x0057 00087 (interface2.go:12) MOVQ CX, "".j(SB) +0x0067 00103 (interface2.go:12) MOVQ AX, "".j+8(SB) + +0x006e 00110 (interface2.go:13) MOVQ "".j+8(SB), AX // AX = j.data +0x0075 00117 (interface2.go:13) MOVQ "".j(SB), DX // DX = j.itab +0x007c 00124 (interface2.go:13) CMPQ DX, CX // 比较 iface.itab 和 go.itab.*os.File,io.Reader(SB) 是否一致 +0x007f 00127 (interface2.go:13) JNE 187 // 不一致,说明断言失败,跳到 panic 流程 + +// 下面就是正常流程了 +``` + + diff --git a/io.md b/io.md new file mode 100644 index 0000000..c15b884 --- /dev/null +++ b/io.md @@ -0,0 +1,726 @@ +# directio +## page cache +页面缓存(Page Cache)是 Linux 内核中针对文件I/O的一项优化, 众所周知磁盘 I/O 的成本远比内存访问来得高, 如果每次进行文件读写都需要直接进行磁盘操作, 那成本会是非常高的, 因此, kernel 针对于文件 I/O 设计了 page cache, 简单来说就是将目标读写的文件页缓存在内存中, 而后操作这块缓存进行读写 (而且例如针对机械磁盘来说, 为了降低磁头寻道的耗时, page cache 通常会采用预读的机制), 写入新数据后该页变为脏页, 等待刷盘, 刷脏的操作可由用户主动请求 (fsync) 或者由内核在合适的时机进行操作 + +### 总结下 page cache 的好处: +- 缓存最近被访问的数据, 提高文件 I/O 的效率 +- 预读功能减少磁头寻道损耗 + +## 那么 page cache 的设计一定是能提高服务效率的么? + +来考虑下一个场景: +> 某服务正在正常工作, 存放了许许多多的静态资源等待访问, 大小为小到几十 kb, 大到几百 GB (大到无法全都加载到内存, 只能存放在本地磁盘)的大文件不等。小文件为热点文件, 大文件为冷门资源, 某天, 突然有用户进行了大文件的访问。 + +这时候会发生什么? + +正常工作的情况下假设内存足够缓存所有小文件, 服务无需进行磁盘 I/O, 而这时候突然来了个大文件的缓存, 直接跑满了大部分的 page cache, 造成内核不得不通过淘汰策略将 page cache 置换了出来(先暂不考虑各种内存拷贝的损耗), 那么接下去再去访问那一堆热点小文件就不得不去进行磁盘 I/O, 然后写入 page cache, 两者之间的矛盾无法调和不断重复, 尤其是大量的小文件基本都为随机读写。从而服务的压力增加, 效率降低。 + +### 如何优化这种场景? +> 各架构机器支持程度不一, 此处仅讨论 linux x86 + +```shell +dd if=/dev/zero of=test bs=1M count=1000 # 生成 1000MB 文件以供测试 +``` +先来测试下正常情况下文件读写的情况: +```go +package main + +import ( + "log" + "os" + "syscall" + "time" + "unsafe" +) + +const ( + // Size to align the buffer to + AlignSize = 4096 + + // Minimum block size + BlockSize = 4096 +) + +func alignment(block []byte, AlignSize int) int { + return int(uintptr(unsafe.Pointer(&block[0])) & uintptr(AlignSize-1)) +} + +func AlignedBlock(BlockSize int) []byte { + block := make([]byte, BlockSize+AlignSize) + if AlignSize == 0 { + return block + } + a := alignment(block, AlignSize) + offset := 0 + if a != 0 { + offset = AlignSize - a + } + block = block[offset : offset+BlockSize] + // Can't check alignment of a zero sized block + if BlockSize != 0 { + a = alignment(block, AlignSize) + if a != 0 { + log.Fatal("Failed to align block") + } + } + return block +} +func main() { + fd, err := os.OpenFile("/disk/data/tmp/test", os.O_RDWR|syscall.O_DIRECT, 0666) + block := AlignedBlock(BlockSize) + if err != nil { + panic(err) + } + defer fd.Close() + for i := range block { + block[i] = 1 + } + for { + n, err := fd.Write(block) + _ = n + if err != nil { + panic(err) + } + fd.Seek(0, 0) + time.Sleep(time.Nanosecond * 10) + } +} +``` +```shell +iotop +Total DISK READ : 0.00 B/s +Actual DISK READ: 0.00 B/s +``` +可以观察到除了初次 I/O 的时候产生磁盘读写, 待测试代码稳定下后是没有产生磁盘读写的, 再看看文件 page cache 的情况 +```shell +vmtouch /disk/data/tmp/test + Files: 1 + Directories: 0 + Resident Pages: 4/256000 16K/1000M 0.00156% + Elapsed: 0.007374 seconds +``` +与预期中的一样缓存了前 16K 文件页 +```shell +# 强刷 page cache +echo 3 > /proc/sys/vm/drop_caches +``` +再来测试下绕过 page cache 进行文件读写的方法 +```go +package main + +import ( + "log" + "os" + "syscall" + "time" + "unsafe" +) + +const ( + // Size to align the buffer to + AlignSize = 4096 + + // Minimum block size + BlockSize = 4096 +) + +func alignment(block []byte, AlignSize int) int { + return int(uintptr(unsafe.Pointer(&block[0])) & uintptr(AlignSize-1)) +} + +func AlignedBlock(BlockSize int) []byte { + block := make([]byte, BlockSize+AlignSize) + if AlignSize == 0 { + return block + } + a := alignment(block, AlignSize) + offset := 0 + if a != 0 { + offset = AlignSize - a + } + block = block[offset : offset+BlockSize] + // Can't check alignment of a zero sized block + if BlockSize != 0 { + a = alignment(block, AlignSize) + if a != 0 { + log.Fatal("Failed to align block") + } + } + return block +} +func main() { + // syscall.O_DIRECT fsfd 直接 I/O 选项 + fd, err := os.OpenFile("/disk/data/tmp/test", os.O_RDWR|syscall.O_DIRECT, 0666) + block := AlignedBlock(BlockSize) + if err != nil { + panic(err) + } + defer fd.Close() + for i := range block { + block[i] = 1 + } + for { + n, err := fd.Read(block) + _ = n + if err != nil { + panic(err) + } + fd.Seek(0, 0) + time.Sleep(time.Nanosecond * 10) + } +} +``` +> 注: 要使用 O_DIRECT 的方式进行文件 I/O 的话, 文件每次操作的大小得进行文件 lock size 以及 memory address 的对齐 + +```shell +iotop +Total DISK READ : 17.45 M/s +Actual DISK READ: 17.42 M/s +``` +再来看看 page cache 的情况: +```shell +vmtouch /disk/data/tmp/test + Files: 1 + Directories: 0 + Resident Pages: 0/256000 0/1000M 0% + Elapsed: 0.006608 seconds +``` + +## 回到 golang +当前标准库如 http.ServeFile, os.Open 等默认采用的访问静态资源的方式均为非直接 I/O, 因此如果有特定场景需要用户自己进行这方面的考量及优化 +## 参考资料 +- http://nginx.org/en/docs/http/ngx_http_core_module.html#directio +- https://tech.meituan.com/2017/05/19/about-desk-io.html +- https://github.com/ncw/directio +# DMA +# Zero-Copy + +## splice +在介绍 splice 及其在 golang 中的应用之前, 先从一段简单的网络代理代码开始入手 +#### read & write +```go +var ( + p sync.Pool +) + +func init() { + p.New = func() interface{} { + return make([]byte, DEFAULTSIZE) + } +} +// src 客户端 tcp 链接 +// dst mock server tcp 链接 +func normal(src, dst net.Conn) { + var bts []byte = p.Get().([]byte) + var bts2 []byte = p.Get().([]byte) + defer p.Put(bts) + defer p.Put(bts2) + // mock server to client + go func() { + for { + num, err := dst.Read(bts2[:]) + if err != nil { + break + } + var num_write int + for num > 0 { + num_write, err = src.Write(bts2[num_write:num]) + if err != nil { + return + } + num -= num_write + } + } + }() + // client to mock server + for { + num, err := src.Read(bts[:]) + if err != nil { + break + } + var num_write int + for num > 0 { + num_write, err = dst.Write(bts[num_write:num]) + if err != nil { + return + } + num -= num_write + } + } +} +``` +以上片段实现了一个简单的功能: 将客户端请求的 tcp 数据通过`read`系统调用读出放入本地用户空间 缓存, 而后再调用`write`发送给目标服务器,反之亦然 + +整个过程如下图所示(暂不考虑 IO 模型调度以及 DMA 等细节部分) + +```shell +[ user space ] + + -------------------------------------------- + | application | + -------------------------------------------- + ····················|·································|·················· + | read() | write() +[ kernel space ] | | + ----------------- ----------------- + | socket buffer | | socket buffer | + ----------------- ----------------- + | copy | + ····················|·································|·················· +[ hardware sapce ] | | + ------------------------------------------------------ + | network interface | + ------------------------------------------------------ + +``` +对于透传或者部分透传(例如七层头部解析后透明代理请求体)之类的需求场景来说, 这种流程的成本无疑是很高的, 可以总结下涉及的几个浪费点 + +- 数据需要从内核态拷贝到用户态 +- 应用层在 read 及 write 的过程中对这部分 byte 的操作开销(申请、释放、对象池维护等) + +#### splice 介绍 +```c +/* + splice() moves data between two file descriptors without copying + between kernel address space and user address space. It + transfers up to len bytes of data from the file descriptor fd_in + to the file descriptor fd_out, where one of the file descriptors + must refer to a pipe. +*/ +ssize_t splice(int fd_in, off64_t *off_in, int fd_out, + off64_t *off_out, size_t len, unsigned int flags); +``` +一句话概括就是, `splice` 不需要从内核空间复制这部分数据到用户空间就可以支持将数据从两个文件描述符之间进行转移, 不过两个描述符至少得有一个是 `pipe`, 以下列举如何利用`splice`完成 `socket->socket` 的数据代理 + +example: +```go +func example(src, dst net.Conn) { + // 由于 src 及 dst 都是 socket, 没法直接使用 splice, 因此先创建临时 pipe + const flags = syscall.O_CLOEXEC | syscall.O_NONBLOCK + var fds [2]int // readfd, writefd + if err := syscall.Pipe2(fds[:], flags); err != nil { + panic(err) + } + // 使用完后关闭 pipe + defer syscall.Close(fds[0]) + defer syscall.Close(fds[1]) + // 获取 src fd + srcfile, err := src.(*net.TCPConn).File() + if err != nil { + panic(err) + } + srcfd := int(srcfile.Fd()) + syscall.SetNonblock(srcfd, true) + ... + // 从 srcfd 读出, 写入 fds[1] (pipe write fd) + num, err := syscall.Splice(srcfd, nil, fds[1], nil, DEFAULTSIZE/* size to splice */, SPLICE_F_NONBLOCK) + ... +} +``` +此时的调用过程变为: + +```shell +[ user space ] + + ----------------------------------------------------------------------------------------------- + | application | + ----------------------------------------------------------------------------------------------- + ········································|····················|·····················|·································· + | splice() | pipe() | splice() +[ kernel space ] | | | + ----------------- ”copy“ ----------------------- ”copy“ ----------------- + | socket buffer |· · · · · · · · · >| pipe writefd & readfd |· · · · · · · · >| socket buffer | + ----------------- ----------------------- ----------------- + | copy | + ····················|··············································································| +[ hardware sapce ] | | + ----------------------------------------------------------------------------------------------- + | network interface | + ----------------------------------------------------------------------------------------------- +``` +此时产生的系统调用为 +- 首先 `pipe()` 调用, 创建临时管道 +- 调用 `splice()` 将 `srcfd` 数据 ”拷贝“ 到 `pipe` +- 调用 `splice()` 将 `pipe` 中的数据 ”拷贝“ 到 `dstfd` + +可以注意到图中以及总结部分的”拷贝“给加了引号, 具体了解过`pipe`底层实现的小伙伴应该理解, 在这边简单表述下, `splice` 是基于 `pipe buffer` 实现的, 本质上在数据传输的时候并没有进行数据的拷贝, 而是仅仅将数据的内存地址等信息塞进了`pipe_buffer`中对应的字段 + +至此, 完成了 kernel-user space 的拷贝优化, 不过可能细心的人会发现, 这种方式虽然减少了数据的拷贝, 但是同样额外增加了系统调用(create pipe & close pipe), 接下来就关于这部分的取舍与具体场景进行具体讨论 + +#### splice 还是 read & write? +如何取舍使用哪种方式? + +两种方法各有各的好处, 往往选择层面的考虑在于应用层的具体策略, 如是否进行透传(/部分), 饥饿问题, 对象池策略等等 + +下面提供几种场景下的测试以供参考 +benchmark 代码: +```go +/* + * 测试环境: go 1.14.3 centos7 + */ +package main + +import ( + "bytes" + "io" + "net" + "net/http" + "sync" + "sync/atomic" + "testing" + "time" +) + +var ( + p sync.Pool +) + +func init() { + p.New = func() interface{} { + return make([]byte, DEFAULTSIZE) + } +} + +const ( + // mock http 请求体大小 + REQUESTBYTESIZE = 0 + // 应用层对象池 byte 大小 + DEFAULTSIZE = 1 << 10 + + SPLICE_F_MOVE = 0x1 + SPLICE_F_NONBLOCK = 0x2 + SPLICE_F_MORE = 0x4 + SPLICE_F_GIFT = 0x8 +) +// io.Copy 该场景下内部调用 splice syscall, 感兴趣的自行查看源码 +func gosplice(src, dst net.Conn) { + defer src.Close() + defer dst.Close() + go func() { + io.Copy(src, dst) + }() + io.Copy(dst, src) +} + +func normal(src, dst net.Conn) { + defer src.Close() + defer dst.Close() + var bts []byte = p.Get().([]byte) + var bts2 []byte = p.Get().([]byte) + defer p.Put(bts) + defer p.Put(bts2) + go func() { + for { + num, err := dst.Read(bts2[:]) + if err != nil { + break + } + var num_write int + for num > 0 { + num_write, err = src.Write(bts2[num_write:num]) + num -= num_write + if err != nil { + return + } + } + } + }() + // local to mock serve + for { + num, err := src.Read(bts[:]) + if err != nil { + break + } + var num_write int + for num > 0 { + num_write, err = dst.Write(bts[num_write:num]) + num -= num_write + if err != nil { + return + } + } + } +} + +// Server http server +var Server *http.Server + +type s struct{} + +func (ss s) ServeHTTP(res http.ResponseWriter, req *http.Request) { + res.WriteHeader(200) + return +} +func TestMain(m *testing.M) { + // mock tcp server + var ss s + go func() { + Server = &http.Server{ + Addr: "0.0.0.0:9610", + Handler: ss, + WriteTimeout: 60 * time.Second, + ReadTimeout: 60 * time.Second, + } + err := Server.ListenAndServe() + if err != nil { + panic(err) + } + }() + go func() { // normal 9611 + l, err := net.ListenTCP("tcp4", &net.TCPAddr{ + IP: net.ParseIP("0.0.0.0"), + Port: 9611, + }) + if err != nil { + panic(err) + } + for { + n, err := l.Accept() + if err != nil { + continue + } + remote, err := net.DialTCP("tcp4", &net.TCPAddr{ + IP: net.ParseIP("0.0.0.0"), Port: 0, + }, &net.TCPAddr{ + IP: net.ParseIP("0.0.0.0"), Port: 9610, + }) + if err != nil { + continue + } + go normal(n, remote) + } + }() + go func() { // gosplice 9612 + l, err := net.ListenTCP("tcp4", &net.TCPAddr{ + IP: net.ParseIP("0.0.0.0"), + Port: 9612, + }) + if err != nil { + panic(err) + } + for { + n, err := l.Accept() + if err != nil { + continue + } + remote, err := net.DialTCP("tcp4", &net.TCPAddr{ + IP: net.ParseIP("0.0.0.0"), Port: 0, + }, &net.TCPAddr{ + IP: net.ParseIP("0.0.0.0"), Port: 9610, + }) + if err != nil { + continue + } + go gosplice(n, remote) + } + }() + m.Run() +} +func BenchmarkNormalReadWrite(b *testing.B) { + // normal 9611 + c := http.Client{ + Timeout: time.Minute, + } + var total, success uint32 + b.ResetTimer() + for i := 0; i < b.N; i++ { + atomic.AddUint32(&total, 1) + req, err := http.NewRequest("POST", "http://0.0.0.0:9611", bytes.NewReader(make([]byte, REQUESTBYTESIZE))) + if err != nil { + b.Fatalf("%s", err.Error()) + } + res, err := c.Do(req) + if err == nil && res.StatusCode == 200 { + atomic.AddUint32(&success, 1) + } + c.CloseIdleConnections() + } + b.Logf("test:%s,total: %d,rate: %.2f%%\n", b.Name(), total, float64(success*100/total)) +} + +func BenchmarkGoSplice(b *testing.B) { + // normal 9612 + c := http.Client{ + Timeout: time.Minute, + } + var total, success uint32 + b.ResetTimer() + for i := 0; i < b.N; i++ { + atomic.AddUint32(&total, 1) + req, err := http.NewRequest("POST", "http://0.0.0.0:9612", bytes.NewReader(make([]byte, REQUESTBYTESIZE))) + if err != nil { + b.Fatalf("%s", err.Error()) + } + res, err := c.Do(req) + if err == nil && res.StatusCode == 200 { + atomic.AddUint32(&success, 1) + } + c.CloseIdleConnections() + } + b.Logf("test:%s, total: %d, success rate: %.2f%%\n", b.Name(), total, float64(success*100/total)) +} +``` +- 场景一: 单次请求数据量较少, 应用维护单个 buffer 较小 +```go +REQUESTBYTESIZE = 0 // http request body +DEFAULTSIZE = 1 << 10 // buffer size 1kb +``` +```shell +RRunning tool: /usr/local/bin/go test -benchmem -run=^$ -bench ^(BenchmarkNormalReadWrite|BenchmarkGoSplice)$ barrier/t + +goos: linux +goarch: amd64 +pkg: barrier/t +BenchmarkNormalReadWrite-4 6348 179699 ns/op 4847 B/op 62 allocs/op +--- BENCH: BenchmarkNormalReadWrite-4 + test_test.go:173: test:BenchmarkNormalReadWrite,total: 1,rate: 100.00% + test_test.go:173: test:BenchmarkNormalReadWrite,total: 100,rate: 100.00% + test_test.go:173: test:BenchmarkNormalReadWrite,total: 6348,rate: 100.00% +BenchmarkGoSplice-4 6652 179622 ns/op 4852 B/op 62 allocs/op +--- BENCH: BenchmarkGoSplice-4 + test_test.go:194: test:BenchmarkGoSplice, total: 1, success rate: 100.00% + test_test.go:194: test:BenchmarkGoSplice, total: 100, success rate: 100.00% + test_test.go:194: test:BenchmarkGoSplice, total: 6652, success rate: 100.00% +PASS +ok barrier/t 2.391s +``` +两种方式无明显性能差异 +- 场景二: 单次请求数据量多, 应用维护单个 buffer 较小 +```go +REQUESTBYTESIZE = 1 << 20 // 1 MB +DEFAULTSIZE = 1 << 10 // buffer size 1kb +``` +```shell +Running tool: /usr/local/bin/go test -benchmem -run=^$ -bench ^(BenchmarkNormalReadWrite|BenchmarkGoSplice)$ barrier/t + +goos: linux +goarch: amd64 +pkg: barrier/t +BenchmarkNormalReadWrite-4 465 2329209 ns/op 1073956 B/op 163 allocs/op +--- BENCH: BenchmarkNormalReadWrite-4 + test_test.go:173: test:BenchmarkNormalReadWrite,total: 1,rate: 100.00% + test_test.go:173: test:BenchmarkNormalReadWrite,total: 100,rate: 100.00% + test_test.go:173: test:BenchmarkNormalReadWrite,total: 376,rate: 100.00% + test_test.go:173: test:BenchmarkNormalReadWrite,total: 465,rate: 100.00% +BenchmarkGoSplice-4 963 1555386 ns/op 1070506 B/op 157 allocs/op +--- BENCH: BenchmarkGoSplice-4 + test_test.go:194: test:BenchmarkGoSplice, total: 1, success rate: 100.00% + test_test.go:194: test:BenchmarkGoSplice, total: 100, success rate: 100.00% + test_test.go:194: test:BenchmarkGoSplice, total: 963, success rate: 100.00% +PASS +ok barrier/t 4.056s +``` +当链接需要处理的数据量较多而应用层每次处理的 buffer 相比起来较小, 以至于需要 read & write 的次数更多的时候, 差异就会比较明显 + +#### go 中的 splice +在上面的介绍过程中简单说了下 `io.Copy` 在 `socket` 之间操作的时候, 当机器架构支持的时候会采取 `splice`, 接下来就此进行详细分析来介绍下 `runtime` 在 `splice` 上的一些决策以及当前`runtime`在 `splice` 上的一些不足 +```go +/* + * src/net/spice_linux.go + */ +// splice transfers data from r to c using the splice system call to minimize +// copies from and to userspace. c must be a TCP connection. Currently, splice +// is only enabled if r is a TCP or a stream-oriented Unix connection. +// +// If splice returns handled == false, it has performed no work. +func splice(c *netFD, r io.Reader) (written int64, err error, handled bool) { + /* + * 因为前面介绍过 splice 是通过 pipe buffer 实现的 + * 在调用的时候 kernel无需进行数据拷贝, 仅操作数据原信息(基础字段的指针等) + * 所以这边默认 splice 的 len 开得比较大, 读到 EOF 为止 + */ + var remain int64 = 1 << 62 // by default, copy until EOF + lr, ok := r.(*io.LimitedReader) + if ok { + remain, r = lr.N, lr.R + if remain <= 0 { + return 0, nil, true + } + } + + var s *netFD + if tc, ok := r.(*TCPConn); ok { + s = tc.fd + } else if uc, ok := r.(*UnixConn); ok { + if uc.fd.net != "unix" { + return 0, nil, false + } + s = uc.fd + } else { + return 0, nil, false + } + + written, handled, sc, err := poll.Splice(&c.pfd, &s.pfd, remain) + if lr != nil { + lr.N -= written + } + return written, wrapSyscallError(sc, err), handled +} +``` +```go +/* + * go 1.14.3 + * src/internal/poll/splice_linux.go + */ +// Splice transfers at most remain bytes of data from src to dst, using the +// splice system call to minimize copies of data from and to userspace. +// +// Splice creates a temporary pipe, to serve as a buffer for the data transfer. +// src and dst must both be stream-oriented sockets. +// +// If err != nil, sc is the system call which caused the error. +func Splice(dst, src *FD, remain int64) (written int64, handled bool, sc string, err error) { + // dst 以及 src 均为 socket.fd, 因此若想使用 splice 则需要借助 pipe + // 创建临时 pipe + prfd, pwfd, sc, err := newTempPipe() + if err != nil { + return 0, false, sc, err + } + defer destroyTempPipe(prfd, pwfd) + var inPipe, n int + for err == nil && remain > 0 { + max := maxSpliceSize + if int64(max) > remain { + max = int(remain) + } + // spliceDrain 调用 splice syscall + inPipe, err = spliceDrain(pwfd, src, max) + // The operation is considered handled if splice returns no + // error, or an error other than EINVAL. An EINVAL means the + // kernel does not support splice for the socket type of src. + // The failed syscall does not consume any data so it is safe + // to fall back to a generic copy. + // + // spliceDrain should never return EAGAIN, so if err != nil, + // Splice cannot continue. + // + // If inPipe == 0 && err == nil, src is at EOF, and the + // transfer is complete. + handled = handled || (err != syscall.EINVAL) + if err != nil || (inPipe == 0 && err == nil) { + break + } + // splicePump 调用 splice syscall + n, err = splicePump(dst, prfd, inPipe) + if n > 0 { + written += int64(n) + remain -= int64(n) + } + } + if err != nil { + return written, handled, "splice", err + } + return written, true, "", nil +} +``` + +相信上面简短的分析大家也可以看到, 每次在进行 `splice` 的时候都会利用临时 `pipe`, 频繁的创建、销毁, 用户态-内核态的切换会带来非常多不必要的开销, 当前社区内也有关于 `splice temp-pipe` 生命周期的[讨论](https://go-review.googlesource.com/c/go/+/271537/)。 + +再者, 因为当前关联到 `socket` 的 `splice` 实现在 `runtime` 层面和内置 `io 模型(epoll 等)`高度耦合, 基本无法解耦单独应用, 而如果想自己来实现 `splice(syscall.Splice)` 的话则不得不顺带在用户层面实现自己的`io 模型`再来使用, 会比较繁琐(上面测试用例使用内置 `splice api` 也是因为这个原因) + +## 参考资料 + +- https://go-review.googlesource.com/c/go/+/271537/ +- https://zhuanlan.zhihu.com/p/308054212 + + diff --git a/lockfree.md b/lockfree.md new file mode 100644 index 0000000..261e9cb --- /dev/null +++ b/lockfree.md @@ -0,0 +1,6 @@ +# lock free programming in Go + +# 参考资料 +https://docs.google.com/presentation/d/1wuNNW-g6v8qizIc_IxAGZTj-49TODKF0TYddTA1VDUo/mobilepresent?slide=id.p + + diff --git a/map.md b/map.md index 9800e13..351146d 100644 --- a/map.md +++ b/map.md @@ -163,10 +163,10 @@ type bmap struct { make(map[k]v, hint) ``` -的代码,在 hint <= 7 时,会调用 makemap_small 来进行初始化,如果 hint > 7,则调用 makemap。 +的代码,在 hint <= 8(bucketSize) 时,会调用 makemap_small 来进行初始化,如果 hint > 8,则调用 makemap。 ```go -make(map[k]v) +make(map[k]v) // 测试时,把这个作为一个全局变量 var a = make(map[int]int) ``` 不提供 hint 的代码,编译器始终会调用 makemap_small 来初始化。 @@ -217,6 +217,28 @@ func makemap(t *maptype, hint int, h *hmap) *hmap { } ``` +当然,实际选用哪个函数不只要看 hint,还要看逃逸分析结果,比如下面这段代码,在生成的汇编中,你是找不到 makemap 的踪影的: + +```go +package main + +func main() { + var m = make(map[int]int, 4) + m[1] = 1 +} +``` + +编译器确定 make map 函数的位置在:cmd/compile/internal/gc/walk.go:1192: + +```go + case OMAKEMAP: + t := n.Type + hmapType := hmap(t) + hint := n.Left +``` + +有兴趣的同学可以自行查看~ + ## 元素访问 主要是对 key 进行 hash 计算,计算后用 low bits 和高 8 位 hash 找到对应的位置: @@ -645,6 +667,12 @@ search: } ``` +## 缩容 + +Go 的 map 是不会缩容的,除非你把整个 map 删掉: + +https://github.com/golang/go/issues/20135 + ## 扩容 扩容触发在 mapassign 中,我们之前注释过了,主要是两点: @@ -848,7 +876,7 @@ func evacuate(t *maptype, h *hmap, oldbucket uintptr) { // 1111 // 所以实际上这个就是 // xxx1xxx & 1000 > 0 - // 说明这个元素在扩容后一定会去上半区 + // 说明这个元素在扩容后一定会去下半区,即Y部分 // 所以就是 useY 了 if hash&newbit != 0 { useY = 1 @@ -1239,3 +1267,5 @@ func (h *hmap) incrnoverflow() { } } ``` + + diff --git a/memory.md b/memory.md index d71141a..b937fcf 100644 --- a/memory.md +++ b/memory.md @@ -1396,3 +1396,6 @@ func (p *notInHeap) add(bytes uintptr) *notInHeap { ### 堆外内存用法 嗯,堆外内存只是 runtime 自己玩的东西,用户态是使用不了的,属于 runtime 专用的 directive。 + + + diff --git a/memory_barrier.md b/memory_barrier.md index e69de29..cc1a7ce 100644 --- a/memory_barrier.md +++ b/memory_barrier.md @@ -0,0 +1,573 @@ +# memory barrier + +> There are only two hard things in Computer Science: cache invalidation and naming things. + +> -- Phil Karlton + +https://martinfowler.com/bliki/TwoHardThings.html + +memory barrier 也称为 memory fence。 + +## CPU 架构 + +``` + ┌─────────────┐ ┌─────────────┐ + │ CPU 0 │ │ CPU 1 │ + └───────────┬─┘ └───────────┬─┘ + ▲ │ ▲ │ + │ │ │ │ + │ │ │ │ + │ │ │ │ + │ ▼ │ ▼ + │ ┌────────┐ │ ┌────────┐ + │◀───┤ Store │ │◀───┤ Store │ + ├───▶│ Buffer │ ├───▶│ Buffer │ + │ └────┬───┘ │ └───┬────┘ + │ │ │ │ + │ │ │ │ + │ │ │ │ + │ │ │ │ + │ ▼ │ ▼ +┌──┴────────────┐ ┌──┴────────────┐ +│ │ │ │ +│ Cache │ │ Cache │ +│ │ │ │ +└───────┬───────┘ └───────┬───────┘ + │ │ + │ │ + │ │ + ┌──────┴──────┐ ┌──────┴──────┐ + │ Invalidate │ │ Invalidate │ + │ Queue │ │ Queue │ + └──────┬──────┘ └──────┬──────┘ + │ │ + │ Interconnect │ + └───────────────┬───────────────┘ + │ + │ + │ + │ + ┌───────┴───────┐ + │ │ + │ Memory │ + │ │ + └───────────────┘ +``` + +CPU 和内存间是个多层的架构,有些资料上会把 L1/L2/L3 都叫作内存,并把这个整体称为内存分层: memory hierachy。 + +CPU 的 cache 层需要保证其本身能保证一定的一致性,一般叫 cache coherence,这是通过 MESI 协议来保证的。 + +但是 MESI 协议中,如果要写入,需要把其它 cache 中的数据 invalidate 掉。这会导致 CPU 需要等待本地的 cacheline 变为 E(Exclusive)状态才能写入,也就是会带来等待,为了优化这种等待,最好是攒一波写,统一进行触发,所以积攒这些写入操作的地方就是 store buffer。 + +如果 CPU 收到了其它核心发来的 invalidate 消息(BusRdX),这时候 CPU 需要将本地的 cache invalidate 掉,又涉及了 cacheline 的修改和 store buffer 的处理,需要等待。为了消除这个等待,CPU 会把这些 invalidate 消息放在 invalidate queue 中,只要保证该消息之后一定会被处理后才对相应的 cache line 进行处理,那么就可以立即对其它核心发来的 invalidate 消息进行响应,以避免阻塞其它核心的流程处理。 + +这样的多层结构在我们编写程序的时候,也给我们带来了一些困扰。 + +不过我们先来看看 cache 层怎么保证多核心间数据的一致性,即 mesi 协议。 + +## mesi 协议 + +| | p0 | p1 | p2 | p3 | +|---|:----:|:----:|:--:| :--: | +| initial state | I | I | I | I | +| p0 reads X | E | I | I | I | +| p1 reads X | S | S | I | I | +| p2 reads X | S | S | S | I | +| p3 writes X | I | I | I | M | +| p0 readx X | S | I | I | S | + +![](images/mesi_1.jpg) + +下面是不同类型的处理器请求和总线侧的请求: + +处理器向 Cache 发请求包括下面这些操作: + +PrRd: 处理器请求读取一个 Cache block +PrWr: 处理器请求写入一个 Cache block + +总线侧的请求包含: + +BusRd: 监听到请求,表示当前有其它处理器正在发起对某个 Cache block 的读请求 + +BusRdX: 监听到请求,表示当前有其它处理器正在发起对某个其未拥有的 Cache block 的写请求 + +BusUpgr: 监听到请求,表示有另一个处理器正在发起对某 Cache block 的写请求,该处理器已经持有此 Cache block 块 + +Flush: 监听到请求,表示整个 cache 块已被另一个处理器写入到主存中 + +FlushOpt: 监听到请求,表示一个完整的 cache 块已经被发送到总线,以提供给另一个处理器使用(Cache 到 Cache 传数) + +Cache 到 Cache 的传送可以降低 read miss 导致的延迟,如果不这样做,需要先将该 block 写回到主存,再读取,延迟会大大增加,在基于总线的系统中,这个结论是正确的。但在多核架构中,coherence 是在 L2 caches 这一级保证的,从 L3 中取可能要比从另一个 L2 中取还要快。 + +mesi 协议解决了多核环境下,内存多层级带来的问题。使得 cache 层对于 CPU 来说可以认为是透明的,不存在的。单一地址的变量的写入,可以以线性的逻辑进行理解。 + +但 mesi 协议有两个问题没有解决,一种是 RMW 操作,或者叫 CAS;一种是 ADD 操作。因为这两种操作都需要先读到原始值,进行修改,然后再写回到内存中。 + +同时,在 CPU 架构中我们看到 CPU 除了 cache 这一层之外,还存在 store buffer,而 store buffer 导致的内存乱序问题,mesi 协议是解决不了的,这是 memory consistency 范畴讨论的问题。 + +下面一节是 wikipedia 上对于 store buffer 和 invalidate queue 的描述,可能比我开头写的要权威一些。 + +## store buffer 和 invalidate queue + +>Store Buffer: + +>当写入到一行 invalidate 状态的 cache line 时便会使用到 store buffer。写如果要继续执行,CPU 需要先发出一条 read-invalid 消息(因为需要确保所有其它缓存了当前内存地址的 CPU 的 cache line 都被 invalidate 掉),然后将写推入到 store buffer 中,当最终 cache line 达到当前 CPU 时再执行这个写操作。 + +>CPU 存在 store buffer 的直接影响是,当 CPU 提交一个写操作时,这个写操作不会立即写入到 cache 中。因而,无论什么时候 CPU 需要从 cache line 中读取,都需要先扫描它自己的 store buffer 来确认是否存在相同的 line,因为有可能当前 CPU 在这次操作之前曾经写入过 cache,但该数据还没有被刷入过 cache(之前的写操作还在 store buffer 中等待)。需要注意的是,虽然 CPU 可以读取其之前写入到 store buffer 中的值,但其它 CPU 并不能在该 CPU 将 store buffer 中的内容 flush 到 cache 之前看到这些值。即 store buffer 是不能跨核心访问的,CPU 核心看不到其它核心的 store buffer。 + +>Invalidate Queues: + +>为了处理 invalidation 消息,CPU 实现了 invalidate queue,借以处理新达到的 invalidate 请求,在这些请求到达时,可以马上进行响应,但可以不马上处理。取而代之的,invalidation 消息只是会被推进一个 invalidation 队列,并在之后尽快处理(但不是马上)。因此,CPU 可能并不知道在它 cache 里的某个 cache line 是 invalid 状态的,因为 invalidation 队列包含有收到但还没有处理的 invalidation 消息,这是因为 CPU 和 invalidation 队列从物理上来讲是位于 cache 的两侧的。 + +>从结果上来讲,memory barrier 是必须的。一个 store barrier 会把 store buffer flush 掉,确保所有的写操作都被应用到 CPU 的 cache。一个 read barrier 会把 invalidation queue flush 掉,也就确保了其它 CPU 的写入对执行 flush 操作的当前这个 CPU 可见。再进一步,MMU 没有办法扫描 store buffer,会导致类似的问题。这种效果对于单线程处理器来说已经是会发生的了。 + +因为前面提到的 store buffer 的存在,会导致多核心运行用户代码时,读和写以非程序顺序的顺序完成。下面我们用工具来对这种乱序进行一些观察。 + +## CPU 导致乱序 + +使用 litmus 进行验证: + +``` +cat sb.litmus + +X86 SB +{ x=0; y=0; } + P0 | P1 ; + MOV [x],$1 | MOV [y],$1 ; + MOV EAX,[y] | MOV EAX,[x] ; +locations [x;y;] +exists (0:EAX=0 /\ 1:EAX=0) +``` + +```shell +~ ❯❯❯ bin/litmus7 ./sb.litmus +%%%%%%%%%%%%%%%%%%%%%%%%%%% +% Results for ./sb.litmus % +%%%%%%%%%%%%%%%%%%%%%%%%%%% +X86 SB + +{x=0; y=0;} + + P0 | P1 ; + MOV [x],$1 | MOV [y],$1 ; + MOV EAX,[y] | MOV EAX,[x] ; + +locations [x; y;] +exists (0:EAX=0 /\ 1:EAX=0) +Generated assembler + ##START _litmus_P0 + movl $1, -4(%rbx,%rcx,4) + movl -4(%rsi,%rcx,4), %eax + ##START _litmus_P1 + movl $1, -4(%rsi,%rcx,4) + movl -4(%rbx,%rcx,4), %eax + +Test SB Allowed +Histogram (4 states) +96 *>0:EAX=0; 1:EAX=0; x=1; y=1; +499878:>0:EAX=1; 1:EAX=0; x=1; y=1; +499862:>0:EAX=0; 1:EAX=1; x=1; y=1; +164 :>0:EAX=1; 1:EAX=1; x=1; y=1; +Ok + +Witnesses +Positive: 96, Negative: 999904 +Condition exists (0:EAX=0 /\ 1:EAX=0) is validated +Hash=2d53e83cd627ba17ab11c875525e078b +Observation SB Sometimes 96 999904 +Time SB 0.11 +``` + +在两个核心上运行汇编指令,意料之外的情况 100w 次中出现了 96 次。虽然很少,但确实是客观存在的情况。 + +有文档提到,x86 体系的内存序本身比较严格,除了 store-load 以外不存在其它类型的重排,也可以用下列脚本验证: + +``` +X86 RW +{ x=0; y=0; } + P0 | P1 ; + MOV EAX,[y] | MOV EAX,[x] ; + MOV [x],$1 | MOV [y],$1 ; +locations [x;y;] +exists (0:EAX=1 /\ 1:EAX=1) +``` + +``` +%%%%%%%%%%%%%%%%%%%%%%%%% +% Results for sb.litmus % +%%%%%%%%%%%%%%%%%%%%%%%%% +X86 OOO + +{x=0; y=0;} + + P0 | P1 ; + MOV EAX,[y] | MOV EAX,[x] ; + MOV [x],$1 | MOV [y],$1 ; + +locations [x; y;] +exists (0:EAX=1 /\ 1:EAX=1) +Generated assembler + ##START _litmus_P0 + movl -4(%rsi,%rcx,4), %eax + movl $1, -4(%rbx,%rcx,4) + ##START _litmus_P1 + movl -4(%rbx,%rcx,4), %eax + movl $1, -4(%rsi,%rcx,4) + +Test OOO Allowed +Histogram (2 states) +500000:>0:EAX=1; 1:EAX=0; x=1; y=1; +500000:>0:EAX=0; 1:EAX=1; x=1; y=1; +No + +Witnesses +Positive: 0, Negative: 1000000 +Condition exists (0:EAX=1 /\ 1:EAX=1) is NOT validated +Hash=7cdd62e8647b817c1615cf8eb9d2117b +Observation OOO Never 0 1000000 +Time OOO 0.14 +``` + +无论运行多少次,Positive 应该都是 0。 + +## barrier + +从功能上来讲,barrier 有四种: + +|#LoadLoad|#LoadStore| +|-|-| +|#StoreLoad|#StoreStore| + +具体说明: + +|barrier name|desc| +|-|-| +|#LoadLoad|阻止不相关的 Load 操作发生重排| +|#LoadStore|阻止 Store 被重排到 Load 之前| +|#StoreLoad|阻止 Load 被重排到 Store 之前| +|#StoreStore|阻止 Store 被重排到 Store 之前| + +需要注意的是,这里所说的重排都是内存一致性范畴,即全局视角的不同变量操作。如果是同一个变量的读写的话,显然是不会发生重排的,因为不按照 program order 来执行程序的话,相当于对用户的程序发生了破坏行为。 + +## lfence, sfence, mfence + +Intel x86/x64 平台,total store ordering(但未来不一定还是 TSO): + +mm_lfence("load fence": wait for all loads to complete) + +不保证在 lfence 之前的写全局可见(globally visible)。并不是把读操作都序列化。只是保证这些读操作和 lfence 之间的先后关系。 + +mm_sfence("store fence": wait for all stores to complete) + +>The Semantics of a Store Fence +>On all Intel and AMD processors, a store fence has two effects: + +>Serializes all memory stores. All stores that precede the store fence in program order will become globally observable before any stores that succeed the store fence in program order become globally observable. Note that a store fence is ordered, by definition, with other store fences. +>In the cycle that follows the cycle when the store fence instruction retires, all stores that precede the store fence in program order are guaranteed to be globally observable. Any store that succeeds the store fence in program order may or may not be globally observable immediately after retiring the store fence. See Section 7.4 of the Intel optimization manual and Section 7.5 of the Intel developer manual Volume 2. Global observability will be discussed in the next section. +>However, that “SFENCE operation” is not actually a fully store serializing operation even though there is the word SFENCE in its name. This is clarified by the emphasized part. I think there is a typo here; it should read “store fence” not “store, fence.” The manual specifies that while clearing IA32_RTIT_CTL.TraceEn serializes all previous stores with respect to all later stores, it does not by itself ensure global observability of previous stores. It is exactly for this reason why the Linux kernel uses a full store fence (called wmb, which is basically SFENCE) after clearing TraceEn. + +mm_mfence("mem fence": wait for all memory operations to complete) + +mfence 会等待当前核心中的 store buffer 排空之后再执行后续指令。 + +https://stackoverflow.com/questions/27595595/when-are-x86-lfence-sfence-and-mfence-instructions-required + +直接考虑硬件的 fence 指令太复杂了,因为硬件提供的 fence 指令和我们前面说的 RW RR WW WR barrier 逻辑并不是严格对应的。 + +我们在写程序的时候的思考过程应该是,先从程序逻辑出发,然后考虑需要使用哪种 barrier/fence(LL LS SS SL),然后再找对应硬件平台上对应的 fence 指令。 + +## acquire/release 语义 + +![barriers](https://preshing.com/images/acq-rel-barriers.png) + +https://preshing.com/20130922/acquire-and-release-fences/ + +在 x86/64 平台上,只有 StoreLoad 乱序,所以你使用 acquire release 时,实际上生成的 fence 是 NOP。 + +在 Go 语言中也不需要操心这个问题,Go 语言的 atomic 默认是最强的内存序保证,即 sequential consistency。该一致性保证由 Go 保证,在所有运行 Go 的硬件平台上都是一致的。当然,这里说的只是 sync/atomic 暴露出来的接口。Go 在 runtime 层有较弱内存序的相关接口,位置在: runtime/internal/atomic。 + +## memory order 参数 + +硬件会提供其 memory order,而语言本身可能也会有自己的 memory order,在 C/C++ 语言中会根据传给 atomic 的参数来决定其使用的 memory order,从而进行一些重排,这里的重排不但有硬件重排,还有编译器级别的重排。 + +下面是 C++ 中对 memory_order 参数的描述: +> std::memory_order specifies how memory accesses, including regular, non-atomic memory accesses, are to be ordered around an atomic operation. Absent any constraints on a multi-core system, when multiple threads simultaneously read and write to several variables, one thread can observe the values change in an order different from the order another thread wrote them. Indeed, the apparent order of changes can even differ among multiple reader threads. Some similar effects can occur even on uniprocessor systems due to compiler transformations allowed by the memory model. + +> The default behavior of all atomic operations in the library provides for sequentially consistent ordering (see discussion below). That default can hurt performance, but the library's atomic operations can be given an additional std::memory_order argument to specify the exact constraints, beyond atomicity, that the compiler and processor must enforce for that operation. + +这也是一个 Go 不需要操心的问题。 + +## sequential consistency + +> Sequential consistency is a strong safety property for concurrent systems. Informally, sequential consistency implies that operations appear to take place in some total order, and that that order is consistent with the order of operations on each individual process. + +可以理解为,同一块内存每次一定只有一个核心能执行。是最符合人的直觉的多线程执行顺序,可以用顺序的逻辑来理解程序执行结果。可以理解为完全没有读写重排。 + +其执行流程类似下图: + +``` +┌──────────────┐ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ +│ Processor 1 │ │ Processor 2 │ │ Processor 3 │ │ Processor 4 │ +└──────────────┘ └──────────────┘ └──────────────┘ └──────────────┘ + ▲ + │ + │ + │ + │ + │ + │ + └──────────────────────────┐ + │ + │ + │ + │ + │ + │ + │ + ┌──────────────────┐ + │ │ + │ Memory │ + │ │ + └──────────────────┘ +``` + +内存上有一个开关,可以拨到任意一个 Processor 上,拨动到位后 Processor 即开始访问和修改内存。 + +保证 Sequential Consistency 的话,性能会非常差。体现不了多核心的优势。Intel 的 TSO 虽然是较强的 Memory Model,但也会有 WR 的重排。 + +## cache coherency vs memory consistency + +MESI 协议使 cache 层对 CPU 透明。多线程程序不需要担心某个核心读到过期数据,或者多个核心同时写入到一行 cache line 的不同部分,而导致 half write 的 cache line 被同步到主存中。 + +然而这种一致性机制没有办法解决 read-modify-write 操作的问题,比如 increment 操作,compare and swap 等操作。MESI 协议并不会阻止两个核心读到相同的内存内容,然后每个核心分别对其加一,再将新的相同的值写回到内存中,相当于将两次加一操作合并成了一次。 + +在现代 CPU 上,Lock 前缀会将 cache line 上锁,从而使 read-modify-write 操作在逻辑上具备原子性。下面的说明进行了简化,不过应该可以说明问题。 + +Unlocked increment: + +1. Acquire cache line, shareable is fine. Read the value. +2. Add one to the read value. +3. Acquire cache line exclusive (if not already E or M) and lock it. +4. Write the new value to the cache line. +5. Change the cache line to modified and unlock it. + +Locked increment: + +1. Acquire cache line exclusive (if not already E or M) and lock it. +2. Read value. +3. Add one to it. +4. Write the new value to the cache line. +5. Change the cache line to modified and unlock it. + +在 unlocked increment 操作中,cache line 只在写内存操作时被锁住,和所有类型的写一样。在 locked increment 中,cache line 在整个指令阶段都被持有,从读一直到最后的写操作。 + +某些 CPU 除了 cache 之外,还有其它的组件会影响内存的可见性。比如一些 CPU 有一个 read prefetcher(预取器)或者 write buffer,会导致内存操作执行乱序。不管有什么组件,LOCK 前缀(或其它 CPU 上的等价方式)可以避免一些内存操作上的顺序问题。 + +https://stackoverflow.com/questions/29880015/lock-prefix-vs-mesi-protocol + +总结一下,cache coherence 解决的是单一地址的写问题,可以使多核心对同一地址的写入序列化。而 memory consistency 说的是不同地址的读写的顺序问题。即全局视角对读写的观测顺序问题。解决 cache coherence 的协议(MESI)并不能解决 CAS 类的问题。同时也解决不了 memory consistency,即不同内存地址读写的可见性问题,要解决 memory consistency 的问题,需要使用 memory barrier 之类的工具。 + +## 编译器导致乱序 + +snippet 1 +```python +X = 0 +for i in range(100): + X = 1 + print X +``` + +snippet 2 +```python +X = 1 +for i in range(100): + print X + +``` + +snippet 1 和 snippet 2 从逻辑上等价的。 + +如果这时候,假设有 Processor 2 同时在执行一条指令: + +```python +X = 0 +``` + +P2 中的指令和 snippet 1 交错执行时,可能产生的结果是:111101111.. + +P2 中的指令和 snippet 2 交错执行时,可能产生的结果是:11100000…​ + +多核心下,编译器对代码的优化也可能导致内存读写的重排。 + +有人说这个例子不够有说服力,我们看看参考资料中的另一个例子: + +```c +int a, b; +int foo() +{ + a = b + 1; + b = 0; + return 1; +} +``` + +输出汇编: +``` +mov eax, DWORD PTR b[rip] +add eax, 1 +mov DWORD PTR a[rip], eax // --> store to a +mov DWORD PTR b[rip], 0 // --> store to b +``` + +开启 O2 优化后,输出汇编: +``` +mov eax, DWORD PTR b[rip] +mov DWORD PTR b[rip], 0 // --> store to b +add eax, 1 +mov DWORD PTR a[rip], eax // --> store to a +``` + +可见 compiler 也是可能会修改赋值的顺序的。 + +## atomic/lock 操作成本 in Go + +```go +package main + +import ( + "sync/atomic" + "testing" +) + +var a int64 + +func BenchmarkAtomic(b *testing.B) { + for i := 0; i < b.N; i++ { + atomic.StoreInt64(&a, int64(i)) + } +} + +func BenchmarkNormal(b *testing.B) { + for i := 0; i < b.N; i++ { + a = 1 + } +} + +func BenchmarkAtomicParallel(b *testing.B) { + b.SetParallelism(100) + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + atomic.StoreInt64(&a, int64(0)) + } + }) +} + +``` + +结果: + +```shell +goos: darwin +goarch: amd64 +BenchmarkAtomic-4 200000000 7.01 ns/op +BenchmarkNormal-4 2000000000 0.63 ns/op +BenchmarkAtomicParallel-4 100000000 15.8 ns/op +PASS +ok _/Users/didi/test/go/atomic_bench 5.051s +``` + +可见,atomic 耗时比普通赋值操作要高一个数量级,在有竞争的情况下会更加慢。 + +## false sharing / true sharing + +true sharing 的概念比较好理解,在对全局变量或局部变量进行多线程修改时,就是一种形式的共享,而且非常字面意思,就是 true sharing。true sharing 带来的明显的问题,例如 RWMutex scales poorly 的官方 issue,即 RWMutex 的 RLock 会对 RWMutex 这个对象的 readerCount 原子加一。本质上就是一种 true sharing。 + +false sharing 指的是那些意料之外的共享。我们知道 CPU 是以 cacheline 为单位进行内存加载的,L1 的 cache line 大小一般是 64 bytes,如果两个变量,或者两个结构体在内存上相邻,那么在 CPU 加载并修改前一个变量的时候,会把第二个变量也加载到 cache line 中,这时候如果恰好另一个核心在使用第二个变量,那么在 P1 修改掉第一个变量的时候,会把整个 cache line invalidate 掉,这时候 P2 要修改第二个变量的话,就需要再重新加载该 cache line。导致了无谓的加载。 + +在 Go 的 runtime 中有不少例子,特别是那些 per-P 的结构,大多都有针对 false sharing 的优化: + +runtime/time.go + +```go +var timers [timersLen]struct { + timersBucket + + // The padding should eliminate false sharing + // between timersBucket values. + pad [cpu.CacheLinePadSize - unsafe.Sizeof(timersBucket{})%cpu.CacheLinePadSize]byte +} +``` + +runtime/sema.go + +```go +var semtable [semTabSize]struct { + root semaRoot + pad [cpu.CacheLinePadSize - unsafe.Sizeof(semaRoot{})]byte +} +``` + +用户态的代码对 false sharing 其实关注的比较少。 + +例: +sync/pool.go + +```go +type poolLocal struct { + poolLocalInternal + + // Prevents false sharing on widespread platforms with + // 128 mod (cache line size) = 0 . + pad [128 - unsafe.Sizeof(poolLocalInternal{})%128]byte +} +``` + + +## runtime 中的 publicationBarrier + +TODO + +https://github.com/golang/go/issues/35541 + +参考资料: + +https://homes.cs.washington.edu/~bornholt/post/memory-models.html + +https://people.eecs.berkeley.edu/~rcs/research/interactive_latency.html + +https://monkeysayhi.github.io/2017/12/28/%E4%B8%80%E6%96%87%E8%A7%A3%E5%86%B3%E5%86%85%E5%AD%98%E5%B1%8F%E9%9A%9C/ + +https://blog.csdn.net/zhangxiao93/article/details/42966279 + +http://kaiyuan.me/2017/09/22/memory-barrier/ + +https://blog.csdn.net/dd864140130/article/details/56494925 + +https://preshing.com/20120515/memory-reordering-caught-in-the-act/ + +https://preshing.com/20120710/memory-barriers-are-like-source-control-operations/ + +https://preshing.com/20120625/memory-ordering-at-compile-time/ + +https://preshing.com/20120612/an-introduction-to-lock-free-programming/ + +https://preshing.com/20130922/acquire-and-release-fences/ + +https://webcourse.cs.technion.ac.il/234267/Spring2016/ho/WCFiles/tirgul%205%20mesi.pdf + +https://www.scss.tcd.ie/Jeremy.Jones/VivioJS/caches/MESIHelp.htm + +http://15418.courses.cs.cmu.edu/spring2017/lectures + +https://software.intel.com/en-us/articles/how-memory-is-accessed + +https://software.intel.com/en-us/articles/detect-and-avoid-memory-bottlenecks#_Move_Instructions_into + +https://stackoverflow.com/questions/29880015/lock-prefix-vs-mesi-protocol + +https://github.com/torvalds/linux/blob/master/Documentation/memory-barriers.txt + +http://www.overbyte.com.au/misc/Lesson3/CacheFun.html + + diff --git a/monodraw/asyncPreempt.monopic b/monodraw/asyncPreempt.monopic new file mode 100644 index 0000000..ba2c4e9 Binary files /dev/null and b/monodraw/asyncPreempt.monopic differ diff --git a/monodraw/cancelTree.monopic b/monodraw/cancelTree.monopic new file mode 100644 index 0000000..9bce250 Binary files /dev/null and b/monodraw/cancelTree.monopic differ diff --git a/monodraw/context.monopic b/monodraw/context.monopic new file mode 100644 index 0000000..0df6ad1 Binary files /dev/null and b/monodraw/context.monopic differ diff --git a/monodraw/cpu_arch.monopic b/monodraw/cpu_arch.monopic new file mode 100644 index 0000000..d0643dd Binary files /dev/null and b/monodraw/cpu_arch.monopic differ diff --git a/monodraw/ctx_tree.monopic b/monodraw/ctx_tree.monopic new file mode 100644 index 0000000..81616fa Binary files /dev/null and b/monodraw/ctx_tree.monopic differ diff --git a/monodraw/gc_process.monopic b/monodraw/gc_process.monopic new file mode 100644 index 0000000..e754216 Binary files /dev/null and b/monodraw/gc_process.monopic differ diff --git a/monodraw/gc_process1.13.monopic b/monodraw/gc_process1.13.monopic new file mode 100644 index 0000000..7c829b0 Binary files /dev/null and b/monodraw/gc_process1.13.monopic differ diff --git a/monodraw/gpm.monopic b/monodraw/gpm.monopic new file mode 100644 index 0000000..1c2bc85 Binary files /dev/null and b/monodraw/gpm.monopic differ diff --git a/monodraw/hash_select.monopic b/monodraw/hash_select.monopic new file mode 100644 index 0000000..e7db6da Binary files /dev/null and b/monodraw/hash_select.monopic differ diff --git a/monodraw/hashgrow2.monopic b/monodraw/hashgrow2.monopic new file mode 100644 index 0000000..c804498 Binary files /dev/null and b/monodraw/hashgrow2.monopic differ diff --git a/monodraw/hashmap.monopic b/monodraw/hashmap.monopic new file mode 100644 index 0000000..eaf3a46 Binary files /dev/null and b/monodraw/hashmap.monopic differ diff --git a/monodraw/mesi_protocol.monopic b/monodraw/mesi_protocol.monopic new file mode 100644 index 0000000..9764dc8 Binary files /dev/null and b/monodraw/mesi_protocol.monopic differ diff --git a/monodraw/min_heap.monopic b/monodraw/min_heap.monopic new file mode 100644 index 0000000..a736f01 Binary files /dev/null and b/monodraw/min_heap.monopic differ diff --git a/monodraw/sequential_consistency.monopic b/monodraw/sequential_consistency.monopic new file mode 100644 index 0000000..16d6c11 Binary files /dev/null and b/monodraw/sequential_consistency.monopic differ diff --git a/monodraw/timer2.monopic b/monodraw/timer2.monopic new file mode 100644 index 0000000..d540795 Binary files /dev/null and b/monodraw/timer2.monopic differ diff --git a/monodraw/timer3.monopic b/monodraw/timer3.monopic new file mode 100644 index 0000000..9355ad9 Binary files /dev/null and b/monodraw/timer3.monopic differ diff --git a/monodraw/timer4.monopic b/monodraw/timer4.monopic new file mode 100644 index 0000000..7c27a50 Binary files /dev/null and b/monodraw/timer4.monopic differ diff --git a/monotonic.md b/monotonic.md new file mode 100644 index 0000000..78af96e --- /dev/null +++ b/monotonic.md @@ -0,0 +1,8 @@ +# monotonic time + +https://go.googlesource.com/proposal/+/master/design/12914-monotonic.md + + +time.Since + +time.Now diff --git a/netpoll.md b/netpoll.md index 04288c2..7ab59f9 100644 --- a/netpoll.md +++ b/netpoll.md @@ -397,6 +397,10 @@ func poll_runtime_pollOpen(fd uintptr) (*pollDesc, int) { ```go func netpollopen(fd uintptr, pd *pollDesc) int32 { var ev epollevent + // linux 下 epoll 采用了 ET 模式 + // epoll 下用户可以 watch 的 descriptors 是有上限的 + // 具体上限的查看及配置可以通过 /proc/sys/fs/epoll/max_user_watches 系统虚拟文件进行操作 + // https://github.com/torvalds/linux/blob/v4.9/fs/eventpoll.c#L259-L263 ev.events = _EPOLLIN | _EPOLLOUT | _EPOLLRDHUP | _EPOLLET *(**pollDesc)(unsafe.Pointer(&ev.data)) = pd return -epollctl(epfd, _EPOLL_CTL_ADD, int32(fd), &ev) @@ -1351,3 +1355,5 @@ func poll_runtime_pollUnblock(pd *pollDesc) { } } ``` + + diff --git a/panic.md b/panic.md index 653c14d..e34b3ad 100644 --- a/panic.md +++ b/panic.md @@ -1,54 +1,23 @@ -# panic 和 error 处理 +# panic ## panic 的本质 +panic 的本质其实就是 gopanic,用户代码和 runtime 中都会有对 panic() 的调用,最终会转为这个 runtime.gopanic 函数。 + ```go -// The implementation of the predeclared function panic. func gopanic(e interface{}) { + // 获取当前 g gp := getg() - if gp.m.curg != gp { - print("panic: ") - printany(e) - print("\n") - throw("panic on system stack") - } - - // m.softfloat is set during software floating point. - // It increments m.locks to avoid preemption. - // We moved the memory loads out, so there shouldn't be - // any reason for it to panic anymore. - if gp.m.softfloat != 0 { - gp.m.locks-- - gp.m.softfloat = 0 - throw("panic during softfloat") - } - if gp.m.mallocing != 0 { - print("panic: ") - printany(e) - print("\n") - throw("panic during malloc") - } - if gp.m.preemptoff != "" { - print("panic: ") - printany(e) - print("\n") - print("preempt off reason: ") - print(gp.m.preemptoff) - print("\n") - throw("panic during preemptoff") - } - if gp.m.locks != 0 { - print("panic: ") - printany(e) - print("\n") - throw("panic holding locks") - } + // 生成一个新的 panic 结构体 var p _panic p.arg = e + // 链上之前的 panic 结构 p.link = gp._panic + // 新节点做整个链表的表头 gp._panic = (*_panic)(noescape(unsafe.Pointer(&p))) + // 统计 atomic.Xadd(&runningPanicDefers, 1) for { @@ -57,34 +26,21 @@ func gopanic(e interface{}) { break } - // If defer was started by earlier panic or Goexit (and, since we're back here, that triggered a new panic), - // take defer off list. The earlier panic or Goexit will not continue running. - if d.started { - if d._panic != nil { - d._panic.aborted = true - } - d._panic = nil - d.fn = nil - gp._defer = d.link - freedefer(d) - continue - } - - // Mark defer as started, but keep on list, so that traceback - // can find and update the defer's argument frame if stack growth - // or a garbage collection happens before reflectcall starts executing d.fn. + // 标记 defer 为已启动,暂时保持在链表上 + // 这样 traceback 在栈增长或者 GC 的时候,能够找到并更新 defer 的参数栈帧 + // 并用 reflectcall 执行 d.fn d.started = true - // Record the panic that is running the defer. - // If there is a new panic during the deferred call, that panic - // will find d in the list and will mark d._panic (this panic) aborted. + // 记录在 defer 中发生的 panic + // 如果在 defer 的函数调用过程中又发生了新的 panic,那个 panic 会在链表中找到 d + // 然后标记 d._panic(指向当前的 panic) 为 aborted 状态。 d._panic = (*_panic)(noescape(unsafe.Pointer(&p))) p.argp = unsafe.Pointer(getargp(0)) reflectcall(nil, unsafe.Pointer(d.fn), deferArgs(d), uint32(d.siz), uint32(d.siz)) p.argp = nil - // reflectcall did not panic. Remove d. + // reflectcall 没有 panic,移除 d if gp._defer != d { throw("bad defer entry in panic") } @@ -92,12 +48,10 @@ func gopanic(e interface{}) { d.fn = nil gp._defer = d.link - // trigger shrinkage to test stack copy. See stack_test.go:TestStackPanic - //GC() - pc := d.pc sp := unsafe.Pointer(d.sp) // must be pointer so it gets adjusted during stack copy freedefer(d) + // p.recovered 字段在 gorecover 函数中已经修改为 true 了 if p.recovered { atomic.Xadd(&runningPanicDefers, -1) @@ -107,33 +61,240 @@ func gopanic(e interface{}) { for gp._panic != nil && gp._panic.aborted { gp._panic = gp._panic.link } - if gp._panic == nil { // must be done with signal + if gp._panic == nil { // 必须已处理完 signal gp.sig = 0 } - // Pass information about recovering frame to recovery. + // 把需要恢复的栈帧信息传给 recovery 函数 gp.sigcode0 = uintptr(sp) gp.sigcode1 = pc mcall(recovery) - throw("recovery failed") // mcall should not return + throw("recovery failed") // mcall 永远不会返回 } } +} + +``` + +gopanic 会把当前函数的 defer 一直执行完,其中碰到 recover 的话就会调用 gorecover 函数: + +```go +func gorecover(argp uintptr) interface{} { + gp := getg() + p := gp._panic + if p != nil && !p.recovered && argp == uintptr(p.argp) { + p.recovered = true + return p.arg + } + return nil +} +``` + +很简单,就是改改 recovered 字段。 + +gopanic 里生成的 panic 对象是带指针的结构体,串成一个链表,用 link 指针相连接,并挂在 g 结构体上: + +```go +// panics +type _panic struct { + argp unsafe.Pointer // pointer to arguments of deferred call run during panic; cannot move - known to liblink + arg interface{} // argument to panic + link *_panic // link to earlier panic + recovered bool // whether this panic is over + aborted bool // the panic was aborted +} +``` + +下面这种写法应该会形成一个 _panic 的链表: + +```go +package main + +func fxfx() { + defer func() { + if err := recover(); err != nil { + println("recover here") + } + }() + + defer func() { + panic(1) + }() + + defer func() { + panic(2) + }() +} + +func main() { + fxfx() +} +``` + +非 defer 中的 panic 的话,函数的后续代码就没办法运行了,写代码的时候要注意这个特性。 + +## recovery + +上面的 panic 恢复过程,最终走到了 recovery: + +```go +// 把需要恢复的栈帧信息传给 recovery 函数 +gp.sigcode0 = uintptr(sp) +gp.sigcode1 = pc +mcall(recovery) +``` + +```go +// 在被 defer 的函数中调用的 recover 从 panic 中已恢复,展开栈继续运行。 +// 现场恢复为发生 panic 的函数正常返回时的情况 +func recovery(gp *g) { + // 之前之前传入的 sp 和 pc 恢复 + sp := gp.sigcode0 + pc := gp.sigcode1 + + // d 的参数需要放在栈上 + if sp != 0 && (sp < gp.stack.lo || gp.stack.hi < sp) { + print("recover: ", hex(sp), " not in [", hex(gp.stack.lo), ", ", hex(gp.stack.hi), "]\n") + throw("bad recovery") + } + + // 让这个 defer 结构体的 deferproc 位置的调用重新返回 + // 这次将返回值修改为 1 + gp.sched.sp = sp + gp.sched.pc = pc + gp.sched.lr = 0 + gp.sched.ret = 1 // ------> 没有调用 deferproc,但直接修改了返回值,所以跳转到 deferproc 的下一条指令位置,且设置了 1,假装作为 deferproc 的返回值 + gogo(&gp.sched) +} +``` + +这里比较 trick,实际上 recovery 中传入的 pc 寄存器的值是 call deferproc 的下一条汇编指令的地址: + +```go + 0x0034 00052 (x.go:4) CALL runtime.deferproc(SB) + 0x0039 00057 (x.go:4) TESTL AX, AX -----> 传入到 deferproc 中的 pc 寄存器指向的位置 + 0x003b 00059 (x.go:4) JNE 135 +``` - // ran out of deferred calls - old-school panic now - // Because it is unsafe to call arbitrary user code after freezing - // the world, we call preprintpanics to invoke all necessary Error - // and String methods to prepare the panic strings before startpanic. - preprintpanics(gp._panic) - startpanic() +和刚注册 defer 结构体链表时的情况不同,panic 时,我们没有调用 deferproc,而是直接跳到了 deferproc 的下一条指令的地址上,并且检查 AX 的值,这里已经被改成 1 了。 - // startpanic set panicking, which will block main from exiting, - // so now OK to decrement runningPanicDefers. - atomic.Xadd(&runningPanicDefers, -1) +所以会直接跳转到函数最后对应该 deferproc 的 deferreturn 位置去。 - printpanics(gp._panic) - dopanic(0) // should not return - *(*int)(nil) = 0 // not reached +最后确认一次,runtime.gogo 会把 sched.ret 搬到 AX 寄存器: + +```go +TEXT runtime·gogo(SB), NOSPLIT, $16-8 + MOVQ buf+0(FP), BX // gobuf + MOVQ gobuf_g(BX), DX + MOVQ 0(DX), CX // make sure g != nil + get_tls(CX) + MOVQ DX, g(CX) + MOVQ gobuf_sp(BX), SP // restore SP + MOVQ gobuf_ret(BX), AX // ----------> 重点在这里 + MOVQ gobuf_ctxt(BX), DX +``` + +这样所有流程就都打通了。 + +--- + +同样需要注意的是, 如多次`panic(defer)`后再利用`recover`恢复后获取到的`panic`信息仅仅为最近一次的信息, 是获取不了`_panic`整个链表中记录的所有信息的, 如果坚持想这样做, 那只能从 TLS 中获取当前的上下文, 通过基址加变址寻址的方式从当前的`g`中来获取`_panic`信息 + +go 1.14.3 为例: +```assembly +#include "textflag.h" +// main.s +// func GetPanicPtr() uintptr +TEXT ·GetPanicPtr(SB), NOSPLIT, $0-8 + MOVQ TLS, CX + MOVQ 0(CX)(TLS*1), AX + MOVQ $32, BX // 32 根据不同版本 type g struct 中 _panic 字段计算偏移量即可 + LEAQ 0(AX)(BX*1), DX + MOVQ (DX), AX + MOVQ AX, ret+0(FP) + RET +``` +```go +// main.go +package main + +import ( + "fmt" + "unsafe" +) + +func GetPanicPtr() uintptr + +type gobuf struct { + // The offsets of sp, pc, and g are known to (hard-coded in) libmach. + // + // ctxt is unusual with respect to GC: it may be a + // heap-allocated funcval, so GC needs to track it, but it + // needs to be set and cleared from assembly, where it's + // difficult to have write barriers. However, ctxt is really a + // saved, live register, and we only ever exchange it between + // the real register and the gobuf. Hence, we treat it as a + // root during stack scanning, which means assembly that saves + // and restores it doesn't need write barriers. It's still + // typed as a pointer so that any other writes from Go get + // write barriers. + sp uintptr + pc uintptr + g uintptr + ctxt unsafe.Pointer + ret uint64 + lr uintptr + bp uintptr // for GOEXPERIMENT=framepointer +} +type stack struct { + lo uintptr + hi uintptr } +type g struct { + // Stack parameters. + // stack describes the actual stack memory: [stack.lo, stack.hi). + // stackguard0 is the stack pointer compared in the Go stack growth prologue. + // It is stack.lo+StackGuard normally, but can be StackPreempt to trigger a preemption. + // stackguard1 is the stack pointer compared in the C stack growth prologue. + // It is stack.lo+StackGuard on g0 and gsignal stacks. + // It is ~0 on other goroutine stacks, to trigger a call to morestackc (and crash). + stack stack // offset known to runtime/cgo + stackguard0 uintptr // offset known to liblink + stackguard1 uintptr // offset known to liblink + _panic uintptr // innermost panic - offset known to liblink + _defer uintptr // innermost defer + m uintptr // current m; offset known to arm liblink + sched gobuf + syscallsp uintptr // if status==Gsyscall, syscallsp = sched.sp to use during gc + syscallpc uintptr // if status==Gsyscall, syscallpc = sched.pc to use during gc + stktopsp uintptr // expected sp at top of stack, to check in traceback + param unsafe.Pointer // passed parameter on wakeup + atomicstatus uint32 + stackLock uint32 // sigprof/scang lock; TODO: fold in to atomicstatus + goid int64 +} +type _panic struct { + argp unsafe.Pointer // pointer to arguments of deferred call run during panic; cannot move - known to liblink + arg interface{} // argument to panic + link *_panic // link to earlier panic + pc uintptr // where to return to in runtime if this panic is bypassed + sp unsafe.Pointer // where to return to in runtime if this panic is bypassed + recovered bool // whether this panic is over + aborted bool // the panic was aborted + goexit bool +} + +func main() { + defer func() { + var __panic *_panic + var _panic_ptr uintptr = GetPanicPtr() + __panic = (*_panic)(unsafe.Pointer(_panic_ptr)) + fmt.Println(__panic) + }() + defer panic(3) + defer panic(2) + panic(1) +} ``` -## error 处理 + diff --git a/paper/arch/10_cachecoherence1_slides.pdf b/paper/arch/10_cachecoherence1_slides.pdf new file mode 100644 index 0000000..afdefca Binary files /dev/null and b/paper/arch/10_cachecoherence1_slides.pdf differ diff --git a/paper/arch/mesi.pdf b/paper/arch/mesi.pdf new file mode 100644 index 0000000..6387a23 Binary files /dev/null and b/paper/arch/mesi.pdf differ diff --git a/pprof.md b/pprof.md new file mode 100644 index 0000000..f825a1a --- /dev/null +++ b/pprof.md @@ -0,0 +1,778 @@ +# pprof +> 本章节没有介绍具体 pprof 以及周边工具的使用, 而是进行了 runtime pprof 实现原理的分析, 旨在提供给读者一个使用方面的参考 +在进行深入本章节之前, 让我们来看三个问题, 相信下面这几个问题也是大部分人在使用 pprof 的时候对它最大的困惑, 那么可以带着这三个问题来进行接下去的分析 +- 开启 pprof 会对 runtime 产生多大的压力? +- 能否选择性在合适阶段对生产环境的应用进行 pprof 的开启 / 关闭操作? +- pprof 的原理是什么? + +go 内置的 `pprof API` 在 `runtime/pprof` 包内, 它提供给了用户与 `runtime` 交互的能力, 让我们能够在应用运行的过程中分析当前应用的各项指标来辅助进行性能优化以及问题排查, 当然也可以直接加载 `_ "net/http/pprof"` 包使用内置的 `http 接口` 来进行使用, `net` 模块内的 pprof 即为 go 替我们封装好的一系列调用 `runtime/pprof` 的方法, 当然也可以自己直接使用 +```go +// src/runtime/pprof/pprof.go +// 可观察类目 +profiles.m = map[string]*Profile{ + "goroutine": goroutineProfile, + "threadcreate": threadcreateProfile, + "heap": heapProfile, + "allocs": allocsProfile, + "block": blockProfile, + "mutex": mutexProfile, + } +``` + +## allocs +```go + +var allocsProfile = &Profile{ + name: "allocs", + count: countHeap, // identical to heap profile + write: writeAlloc, +} +``` +- writeAlloc (主要涉及以下几个 api) + - ReadMemStats(m *MemStats) + - MemProfile(p []MemProfileRecord, inuseZero bool) + +```go +// ReadMemStats populates m with memory allocator statistics. +// +// The returned memory allocator statistics are up to date as of the +// call to ReadMemStats. This is in contrast with a heap profile, +// which is a snapshot as of the most recently completed garbage +// collection cycle. +func ReadMemStats(m *MemStats) { + // STW 操作 + stopTheWorld("read mem stats") + // systemstack 切换 + systemstack(func() { + // 将 memstats 通过 copy 操作复制给 m + readmemstats_m(m) + }) + + startTheWorld() +} +``` + +```go +// MemProfile returns a profile of memory allocated and freed per allocation +// site. +// +// MemProfile returns n, the number of records in the current memory profile. +// If len(p) >= n, MemProfile copies the profile into p and returns n, true. +// If len(p) < n, MemProfile does not change p and returns n, false. +// +// If inuseZero is true, the profile includes allocation records +// where r.AllocBytes > 0 but r.AllocBytes == r.FreeBytes. +// These are sites where memory was allocated, but it has all +// been released back to the runtime. +// +// The returned profile may be up to two garbage collection cycles old. +// This is to avoid skewing the profile toward allocations; because +// allocations happen in real time but frees are delayed until the garbage +// collector performs sweeping, the profile only accounts for allocations +// that have had a chance to be freed by the garbage collector. +// +// Most clients should use the runtime/pprof package or +// the testing package's -test.memprofile flag instead +// of calling MemProfile directly. +func MemProfile(p []MemProfileRecord, inuseZero bool) (n int, ok bool) { + lock(&proflock) + // If we're between mProf_NextCycle and mProf_Flush, take care + // of flushing to the active profile so we only have to look + // at the active profile below. + mProf_FlushLocked() + clear := true + /* + * 记住这个 mbuckets -- memory profile buckets + * allocs 的采样都是记录在这个全局变量内, 下面会进行详细分析 + * ------------------------------------------------- + * (gdb) info variables mbuckets + * All variables matching regular expression "mbuckets": + + * File runtime: + * runtime.bucket *runtime.mbuckets; + * (gdb) + */ + for b := mbuckets; b != nil; b = b.allnext { + mp := b.mp() + if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes { + n++ + } + if mp.active.allocs != 0 || mp.active.frees != 0 { + clear = false + } + } + if clear { + // Absolutely no data, suggesting that a garbage collection + // has not yet happened. In order to allow profiling when + // garbage collection is disabled from the beginning of execution, + // accumulate all of the cycles, and recount buckets. + n = 0 + for b := mbuckets; b != nil; b = b.allnext { + mp := b.mp() + for c := range mp.future { + mp.active.add(&mp.future[c]) + mp.future[c] = memRecordCycle{} + } + if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes { + n++ + } + } + } + if n <= len(p) { + ok = true + idx := 0 + for b := mbuckets; b != nil; b = b.allnext { + mp := b.mp() + if inuseZero || mp.active.alloc_bytes != mp.active.free_bytes { + // mbuckets 数据拷贝 + record(&p[idx], b) + idx++ + } + } + } + unlock(&proflock) + return +} +``` + +总结一下 `pprof/allocs` 所涉及的操作 +- 短暂的 `STW` 以及 `systemstack` 切换来获取 `runtime` 相关信息 +- 拷贝全局对象 `mbuckets` 值返回给用户 + +### mbuckets +上文提到, `pprof/allocs` 的核心在于对 `mbuckets` 的操作, 下面用一张图来简单描述下 `mbuckets` 的相关操作 +```go +var mbuckets *bucket // memory profile buckets +type bucket struct { + next *bucket + allnext *bucket + typ bucketType // memBucket or blockBucket (includes mutexProfile) + hash uintptr + size uintptr + nstk uintptr +} +``` + + +```shell + --------------- + | user access | + --------------- + | + ------------------ | +| mbuckets list | copy | +| (global) | ------------------------------------- + ------------------ + | + | + | create_or_get && insert_or_update bucket into mbuckets + | + | + -------------------------------------- +| func stkbucket & typ == memProfile | + -------------------------------------- + | + ---------------- + | mProf_Malloc | // 堆栈等信息记录 + ---------------- + | + ---------------- + | profilealloc | // next_sample 计算 + ---------------- + | + | /* + | * if rate := MemProfileRate; rate > 0 { + | * if rate != 1 && size < c.next_sample { + | * c.next_sample -= size + | 采样 * } else { + | 记录 * mp := acquirem() + | * profilealloc(mp, x, size) + | * releasem(mp) + | * } + | * } + | */ + | + ------------ 不采样 + | mallocgc |-----------... + ------------ +``` + +由上图我们可以清晰的看见, `runtime` 在内存分配的时候会根据一定策略进行采样, 记录到 `mbuckets` 中让用户得以进行分析, 而采样算法有个重要的依赖 `MemProfileRate` + +```go +// MemProfileRate controls the fraction of memory allocations +// that are recorded and reported in the memory profile. +// The profiler aims to sample an average of +// one allocation per MemProfileRate bytes allocated. +// +// To include every allocated block in the profile, set MemProfileRate to 1. +// To turn off profiling entirely, set MemProfileRate to 0. +// +// The tools that process the memory profiles assume that the +// profile rate is constant across the lifetime of the program +// and equal to the current value. Programs that change the +// memory profiling rate should do so just once, as early as +// possible in the execution of the program (for example, +// at the beginning of main). +var MemProfileRate int = 512 * 1024 +``` +默认大小是 512 KB, 可以由用户自行配置. + +值的注意的是, 由于开启了 pprof 会产生一些采样的额外压力及开销, go 团队已经在较新的编译器中有选择地进行了这个变量的配置以[改变](https://go-review.googlesource.com/c/go/+/299671/8/src/runtime/mprof.go)默认开启的现状 + +具体方式为代码未进行相关引用则编译器将初始值配置为 0, 否则则为默认(512 KB) + +(本文讨论的基于 1.14.3 版本, 如有差异请进行版本确认) + +#### pprof/allocs 总结 +- 开启后会对 runtime 产生额外压力, 采样时会在 `runtime malloc` 时记录额外信息以供后续分析 +- 可以人为选择是否开启, 以及采样频率, 通过设置 `runtime.MemProfileRate` 参数, 不同 go 版本存在差异(是否默认开启), 与用户代码内是否引用(linker)相关模块/变量有关, 默认大小为 512 KB + +`allocs` 部分还包含了 `heap` 情况的近似计算, 放在下一节分析 +## heap +>allocs: A sampling of all past memory allocations + +>heap: A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample. + +对比下 `allocs` 和 `heap` 官方说明上的区别, 一个是分析所有内存分配的情况, 一个是当前 `heap` 上的分配情况. `heap` 还能使用额外参数运行一次 `GC` 后再进行分析 + +看起来两者差别很大。。。不过实质上在代码层面两者除了一次 `GC` 可以人为调用以及生成的文件类型不同之外 (debug == 0 的时候) 之外没啥区别. + +### heap 采样(伪) +```go +// p 为上文提到过的 MemProfileRecord 采样记录 +for _, r := range p { + hideRuntime := true + for tries := 0; tries < 2; tries++ { + stk := r.Stack() + // For heap profiles, all stack + // addresses are return PCs, which is + // what appendLocsForStack expects. + if hideRuntime { + for i, addr := range stk { + if f := runtime.FuncForPC(addr); f != nil && strings.HasPrefix(f.Name(), "runtime.") { + continue + } + // Found non-runtime. Show any runtime uses above it. + stk = stk[i:] + break + } + } + locs = b.appendLocsForStack(locs[:0], stk) + if len(locs) > 0 { + break + } + hideRuntime = false // try again, and show all frames next time. + } + // rate 即为 runtime.MemProfileRate + values[0], values[1] = scaleHeapSample(r.AllocObjects, r.AllocBytes, rate) + values[2], values[3] = scaleHeapSample(r.InUseObjects(), r.InUseBytes(), rate) + var blockSize int64 + if r.AllocObjects > 0 { + blockSize = r.AllocBytes / r.AllocObjects + } + b.pbSample(values, locs, func() { + if blockSize != 0 { + b.pbLabel(tagSample_Label, "bytes", "", blockSize) + } + }) + } +``` +```go +// scaleHeapSample adjusts the data from a heap Sample to +// account for its probability of appearing in the collected +// data. heap profiles are a sampling of the memory allocations +// requests in a program. We estimate the unsampled value by dividing +// each collected sample by its probability of appearing in the +// profile. heap profiles rely on a poisson process to determine +// which samples to collect, based on the desired average collection +// rate R. The probability of a sample of size S to appear in that +// profile is 1-exp(-S/R). +func scaleHeapSample(count, size, rate int64) (int64, int64) { + if count == 0 || size == 0 { + return 0, 0 + } + + if rate <= 1 { + // if rate==1 all samples were collected so no adjustment is needed. + // if rate<1 treat as unknown and skip scaling. + return count, size + } + + avgSize := float64(size) / float64(count) + scale := 1 / (1 - math.Exp(-avgSize/float64(rate))) + + return int64(float64(count) * scale), int64(float64(size) * scale) +} +``` + +为什么要在标题里加个伪? 看上面代码片段也可以注意到, 实质上在 `pprof` 分析的时候并没有扫描所有堆上内存进行分析 (想想也不现实) , 而是通过之前采样出的数据, 进行计算 (现有对象数量, 大小, 采样率等) 来估算出 `heap` 上的情况, 当然给我们参考一般来说是足够了 + +## goroutine +- debug >= 2 的情况, 直接进行堆栈输出, 详情可以查看 [stack](runtime_stack.md) 章节 + +```go +// fetch == runtime.GoroutineProfile +func writeRuntimeProfile(w io.Writer, debug int, name string, fetch func([]runtime.StackRecord) (int, bool)) error { + // Find out how many records there are (fetch(nil)), + // allocate that many records, and get the data. + // There's a race—more records might be added between + // the two calls—so allocate a few extra records for safety + // and also try again if we're very unlucky. + // The loop should only execute one iteration in the common case. + var p []runtime.StackRecord + n, ok := fetch(nil) + for { + // Allocate room for a slightly bigger profile, + // in case a few more entries have been added + // since the call to ThreadProfile. + p = make([]runtime.StackRecord, n+10) + n, ok = fetch(p) + if ok { + p = p[0:n] + break + } + // Profile grew; try again. + } + + return printCountProfile(w, debug, name, runtimeProfile(p)) +} +``` + +```go +// GoroutineProfile returns n, the number of records in the active goroutine stack profile. +// If len(p) >= n, GoroutineProfile copies the profile into p and returns n, true. +// If len(p) < n, GoroutineProfile does not change p and returns n, false. +// +// Most clients should use the runtime/pprof package instead +// of calling GoroutineProfile directly. +func GoroutineProfile(p []StackRecord) (n int, ok bool) { + gp := getg() + + isOK := func(gp1 *g) bool { + // Checking isSystemGoroutine here makes GoroutineProfile + // consistent with both NumGoroutine and Stack. + return gp1 != gp && readgstatus(gp1) != _Gdead && !isSystemGoroutine(gp1, false) + } + // 熟悉的味道, STW 又来了 + stopTheWorld("profile") + // 统计有多少 goroutine + n = 1 + for _, gp1 := range allgs { + if isOK(gp1) { + n++ + } + } + // 当传入的 p 非空的时候, 开始获取各个 goroutine 信息, 整体姿势和 stack api 几乎一模一样 + if n <= len(p) { + ok = true + r := p + + // Save current goroutine. + sp := getcallersp() + pc := getcallerpc() + systemstack(func() { + saveg(pc, sp, gp, &r[0]) + }) + r = r[1:] + + // Save other goroutines. + for _, gp1 := range allgs { + if isOK(gp1) { + if len(r) == 0 { + // Should be impossible, but better to return a + // truncated profile than to crash the entire process. + break + } + saveg(^uintptr(0), ^uintptr(0), gp1, &r[0]) + r = r[1:] + } + } + } + + startTheWorld() + + return n, ok +} +``` +总结下 `pprof/goroutine` +- STW 操作, 如果需要观察详情的需要注意这个 API 带来的风险 +- 整体流程基本就是 stackdump 所有协程信息的流程, 差别不大没什么好讲的, 不熟悉的可以去看下 stack 对应章节 + +## pprof/threadcreate +可能会有人想问, 我们通常只关注 `goroutine` 就够了, 为什么还需要对线程的一些情况进行追踪? 例如无法被抢占的阻塞性[系统调用](syscall.md), `cgo` 相关的线程等等, 都可以利用它来进行一个简单的分析, 当然大多数情况考虑的线程问题(诸如泄露等), 一般都是上层的使用问题所导致的(线程泄露等) +```go +// 还是用之前用过的无法被抢占的阻塞性系统调用来进行一个简单的实验 +package main + +import ( + "fmt" + "net/http" + _ "net/http/pprof" + "os" + "syscall" + "unsafe" +) + +const ( + SYS_futex = 202 + _FUTEX_PRIVATE_FLAG = 128 + _FUTEX_WAIT = 0 + _FUTEX_WAKE = 1 + _FUTEX_WAIT_PRIVATE = _FUTEX_WAIT | _FUTEX_PRIVATE_FLAG + _FUTEX_WAKE_PRIVATE = _FUTEX_WAKE | _FUTEX_PRIVATE_FLAG +) + +func main() { + fmt.Println(os.Getpid()) + go func() { + b := make([]byte, 1<<20) + _ = b + }() + for i := 1; i < 13; i++ { + go func() { + var futexVar int = 0 + for { + // Syscall && RawSyscall, 具体差别分析可自行查看 syscall 章节 + fmt.Println(syscall.Syscall6( + SYS_futex, // trap AX 202 + uintptr(unsafe.Pointer(&futexVar)), // a1 DI 1 + uintptr(_FUTEX_WAIT), // a2 SI 0 + 0, // a3 DX + 0, //uintptr(unsafe.Pointer(&ts)), // a4 R10 + 0, // a5 R8 + 0)) + } + }() + } + http.ListenAndServe("0.0.0.0:8899", nil) +} +``` +```shell +# GET /debug/pprof/threadcreate?debug=1 +threadcreate profile: total 18 +17 @ +# 0x0 + +1 @ 0x43b818 0x43bfa3 0x43c272 0x43857d 0x467fb1 +# 0x43b817 runtime.allocm+0x157 /usr/local/go/src/runtime/proc.go:1414 +# 0x43bfa2 runtime.newm+0x42 /usr/local/go/src/runtime/proc.go:1736 +# 0x43c271 runtime.startTemplateThread+0xb1 /usr/local/go/src/runtime/proc.go:1805 +# 0x43857c runtime.main+0x18c /usr/local/go/src/runtime/proc.go:186 +``` +```shell +# 再结合诸如 pstack 的工具 +ps -efT | grep 22298 # pid = 22298 +root 22298 22298 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22299 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22300 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22301 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22302 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22303 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22304 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22305 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22306 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22307 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22308 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22309 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22310 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22311 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22312 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22316 13767 0 16:59 pts/4 00:00:00 ./mstest +root 22298 22317 13767 0 16:59 pts/4 00:00:00 ./mstest + +pstack 22299 +Thread 1 (process 22299): +#0 runtime.futex () at /usr/local/go/src/runtime/sys_linux_amd64.s:568 +#1 0x00000000004326f4 in runtime.futexsleep (addr=0xb2fd78 , val=0, ns=60000000000) at /usr/local/go/src/runtime/os_linux.go:51 +#2 0x000000000040cb3e in runtime.notetsleep_internal (n=0xb2fd78 , ns=60000000000, ~r2=) at /usr/local/go/src/runtime/lock_futex.go:193 +#3 0x000000000040cc11 in runtime.notetsleep (n=0xb2fd78 , ns=60000000000, ~r2=) at /usr/local/go/src/runtime/lock_futex.go:216 +#4 0x00000000004433b2 in runtime.sysmon () at /usr/local/go/src/runtime/proc.go:4558 +#5 0x000000000043af33 in runtime.mstart1 () at /usr/local/go/src/runtime/proc.go:1112 +#6 0x000000000043ae4e in runtime.mstart () at /usr/local/go/src/runtime/proc.go:1077 +#7 0x0000000000401893 in runtime/cgo(.text) () +#8 0x00007fb1e2d53700 in ?? () +#9 0x0000000000000000 in ?? () +``` +其他的线程如果感兴趣也可以仔细查看 + +`pprof/threadcreate` 具体实现和 `pprof/goroutine` 类似, 无非前者遍历的对象是全局 `allm`, 而后者为 `allgs`, 区别在于 `pprof/threadcreate => ThreadCreateProfile` 时不会进行进行 `STW` + +## pprof/mutex +mutex 默认是关闭采样的, 通过 `runtime.SetMutexProfileFraction(int)` 来进行 `rate` 的配置进行开启或关闭 + +和上文分析过的 `mbuckets` 类似, 这边用以记录采样数据的是 `xbuckets`, `bucket` 记录了锁持有的堆栈, 次数(采样)等信息以供用户查看 +```go +//go:linkname mutexevent sync.event +func mutexevent(cycles int64, skip int) { + if cycles < 0 { + cycles = 0 + } + rate := int64(atomic.Load64(&mutexprofilerate)) + // TODO(pjw): measure impact of always calling fastrand vs using something + // like malloc.go:nextSample() + // 同样根据 rate 来进行采样, 这边用以记录 rate 的是 mutexprofilerate 变量 + if rate > 0 && int64(fastrand())%rate == 0 { + saveblockevent(cycles, skip+1, mutexProfile) + } +} +``` +```shell + --------------- + | user access | + --------------- + | + ------------------ | +| xbuckets list | copy | +| (global) | ------------------------------------- + ------------------ + | + | + | create_or_get && insert_or_update bucket into xbuckets + | + | + -------------------------------------- +| func stkbucket & typ == mutexProfile | + -------------------------------------- + | + ------------------ + | saveblockevent | // 堆栈等信息记录 + ------------------ + | + | + | /* + | * //go:linkname mutexevent sync.event + | * func mutexevent(cycles int64, skip int) { + | * if cycles < 0 { + | * cycles = 0 + | * } + | 采样 * rate := int64(atomic.Load64(&mutexprofilerate)) + | 记录 * // TODO(pjw): measure impact of always calling fastrand vs using something + | * // like malloc.go:nextSample() + | * if rate > 0 && int64(fastrand())%rate == 0 { + | * saveblockevent(cycles, skip+1, mutexProfile) + | * } + | * + | */ + | + ------------ 不采样 + | mutexevent | ----------.... + ------------ + | + | + ------------ + | semrelease1 | + ------------ + | + | + ------------------------ + | runtime_Semrelease | + ------------------------ + | + | + ------------ + | unlockSlow | + ------------ + | + | + ------------ + | Unlock | + ------------ +``` + +## pprof/block +同上, 主要来分析下 `bbuckets` +```shell + --------------- + | user access | + --------------- + | + ------------------ | +| bbuckets list | copy | +| (global) | ------------------------------------- + ------------------ + | + | + | create_or_get && insert_or_update bucket into bbuckets + | + | + -------------------------------------- +| func stkbucket & typ == blockProfile | + -------------------------------------- + | + ------------------ + | saveblockevent | // 堆栈等信息记录 + ------------------ + | + | + | /* + | * func blocksampled(cycles int64) bool { + | * rate := int64(atomic.Load64(&blockprofilerate)) + | * if rate <= 0 || (rate > cycles && int64(fastrand())%rate > cycles) { + | * return false + | 采样 * } + | 记录 * return true + | * } + | */ + | + ------------ 不采样 + | blockevent | ----------.... + ------------ + |---------------------------------------------------------------------------- + | | | + ------------ ----------------------------------------------- ------------ + | semrelease1 | | chansend / chanrecv && mysg.releasetime > 0 | | selectgo | + ------------ ----------------------------------------------- ------------ +``` +相比较 `mutex` 的采样, `block` 的埋点会额外存在于 `chan` 中, 每次 `block` 记录的是前后两个 `cpu 周期` 的差值 (cycles) +需要注意的是 `cputicks` 可能在不同系统上存在一些[问题](https://github.com/golang/go/issues/8976). 暂不放在这边讨论 + +## pprof/profile +上面分析的都属于 `runtime` 在运行的过程中自动采用保存数据后用户进行观察的, `profile` 则是用户选择指定周期内的 `CPU Profiling` + +#总结 +- `pprof` 的确会给 `runtime` 带来额外的压力, 压力的多少取决于用户使用的各个 `*_rate` 配置, 在获取 `pprof` 信息的时候需要按照实际情况酌情使用各个接口, 每个接口产生的额外压力是不一样的. +- 不同版本在是否默认开启上有不同策略, 需要自行根据各自的环境进行确认 +- `pprof` 获取到的数据仅能作为参考, 和设置的采样频率有关, 在计算例如 `heap` 情况时会进行相关的近似预估, 非实质上对 `heap` 进行扫描 + +```shell + ------------------------- +| pprof.StartCPUProfile | + ------------------------- + | + | + | + ------------------------- +| sleep(time.Duration) | + ------------------------- + | + | + | + ------------------------- +| pprof.StopCPUProfile | + ------------------------- +``` +`pprof.StartCPUProfile` 与 `pprof.StopCPUProfile` 核心为 `runtime.SetCPUProfileRate(hz int)` 控制 `cpu profile` 频率, 但是这边的频率设置和前面几个有差异, 不仅仅是设计 rate 的设置, 还涉及全局对象 `cpuprof` log buffer 的分配 +```go +var cpuprof cpuProfile +type cpuProfile struct { + lock mutex + on bool // profiling is on + log *profBuf // profile events written here + + // extra holds extra stacks accumulated in addNonGo + // corresponding to profiling signals arriving on + // non-Go-created threads. Those stacks are written + // to log the next time a normal Go thread gets the + // signal handler. + // Assuming the stacks are 2 words each (we don't get + // a full traceback from those threads), plus one word + // size for framing, 100 Hz profiling would generate + // 300 words per second. + // Hopefully a normal Go thread will get the profiling + // signal at least once every few seconds. + extra [1000]uintptr + numExtra int + lostExtra uint64 // count of frames lost because extra is full + lostAtomic uint64 // count of frames lost because of being in atomic64 on mips/arm; updated racily +} +``` +`log buffer` 的大小每次分配是固定的, 无法进行调节 + +### cpuprof.add +将 `stack trace` 信息写入 `cpuprof` 的 `log buffer` +```go +// add adds the stack trace to the profile. +// It is called from signal handlers and other limited environments +// and cannot allocate memory or acquire locks that might be +// held at the time of the signal, nor can it use substantial amounts +// of stack. +//go:nowritebarrierrec +func (p *cpuProfile) add(gp *g, stk []uintptr) { + // Simple cas-lock to coordinate with setcpuprofilerate. + for !atomic.Cas(&prof.signalLock, 0, 1) { + osyield() + } + + if prof.hz != 0 { // implies cpuprof.log != nil + if p.numExtra > 0 || p.lostExtra > 0 || p.lostAtomic > 0 { + p.addExtra() + } + hdr := [1]uint64{1} + // Note: write "knows" that the argument is &gp.labels, + // because otherwise its write barrier behavior may not + // be correct. See the long comment there before + // changing the argument here. + cpuprof.log.write(&gp.labels, nanotime(), hdr[:], stk) + } + + atomic.Store(&prof.signalLock, 0) +} +``` + +来看下调用 `cpuprof.add` 的流程 +```shell + ------------------------ +| cpu profile start | + ------------------------ + | + | + | start timer (setitimer syscall / ITIMER_PROF) + | 每个一段时间(rate)在向当前 P 所在线程发送一个 SIGPROF 信号量 -- + | | + | | + ------------------------ loop | +| sighandler |---------------------------------------------- + ------------------------ | + | | + | /* | + | * if sig == _SIGPROF { | + | * sigprof(c.sigpc(), c.sigsp(), c.siglr(), gp, _g_.m) + | * return | + | */ } | + | | + ---------------------------- | stop + | sigprof(stack strace) | | + ---------------------------- | + | | + | | + | | + ---------------------- | + | cpuprof.add | | + ---------------------- ---------------------- + | | cpu profile stop | + | ---------------------- + | + ---------------------- + | cpuprof.log buffer | + ---------------------- + | --------------------- --------------- + ----------------------------------------| cpuprof.read |----------------| user access | + --------------------- --------------- +``` +由于 `GMP` 的模型设计, 在绝大多数情况下通过这种 `timer` + `sig` + `current thread` 以及当前支持的抢占式调度, 这种记录方式是能够很好进行整个 `runtime cpu profile` 采样分析的, 但也不能排除一些极端情况是无法被覆盖的, 毕竟也只是基于当前 M 而已. + +# 总结 +#### 可用性: +runtime 自带的 pprof 已经在数据采集的准确性, 覆盖率, 压力等各方面替我们做好了一个比较均衡及全面的考虑 + +在绝大多数场景下使用起来需要考虑的性能点无非就是几个 rate 的设置 + +不同版本的默认开启是有差别的, 几个参数默认值可自行确认, 有时候你觉得没有开启 pprof 但是实际上已经开启了 + +当选择的参数合适的时候, pprof 远远没有想象中那般“重” +#### 局限性: +得到的数据只是采样(根据 rate 决定) 或预估值 + +无法 cover 所有场景, 对于一些特殊的或者极端的情况, 需要各自进行优化来选择合适的手段完善 +#### 安全性: +生产环境可用 pprof, 注意接口不能直接暴露, 毕竟存在诸如 STW 等操作, 存在潜在风险点 + +#开源项目 pprof 参考 +[nsq](https://github.com/nsqio/nsq/blob/v1.2.0/nsqd/http.go#L78-L88) +[etcd](https://github.com/etcd-io/etcd/blob/release-3.4/pkg/debugutil/pprof.go#L23) 采用的是[配置式](https://github.com/etcd-io/etcd/blob/release-3.4/etcd.conf.yml.sample#L76)选择是否开启 + +# 参考资料 +https://go-review.googlesource.com/c/go/+/299671 + + diff --git a/readme.md b/readme.md index ad224e6..d0c7ab2 100644 --- a/readme.md +++ b/readme.md @@ -6,15 +6,15 @@ 1. [x] [Bootstrap](bootstrap.md) 2. [x] [Channel](channel.md) -3. [ ] [Interface](interface.md) +3. [x] [Interface](interface.md) 4. [x] [Select](select.md) 5. [x] [Slice](slice.md) 6. [x] [Timer](timer.md) -7. [ ] [Defer](defer.md) +7. [x] [Defer](defer.md) 8. [x] [Sync](sync.md) 9. [x] [Netpoll](netpoll.md) 10. [ ] [Reflect](reflect.md) -11. [ ] [Panic](panic.md) +11. [x] [Panic](panic.md) 12. [ ] [Goroutine](goroutine.md) 13. [x] [Scheduler](scheduler.md) 14. [ ] [GC](gc.md) @@ -23,3 +23,21 @@ 17. [x] [Syscall](syscall.md) 18. [x] [Memory](memory.md) 19. [x] [Semaphore](semaphore.md) +20. [x] [Memory Barrier](memory_barrier.md) +21. [ ] [Lock Free](lockfree.md) +22. [x] [context](context.md) +23. [x] [stack dump](runtime_stack.md) +24. [x] [Atomic](atomic.md) +25. [ ] [Generics](generics.md) +26. [x] [IO](io.md) +26. [x] [pprof](pprof.md) + +# Authors + +[cch123](https://github.com/cch123) + +[wziww](https://github.com/wziww) + +# 公众号 + + diff --git a/runtime_stack.md b/runtime_stack.md new file mode 100644 index 0000000..a92b9b1 --- /dev/null +++ b/runtime_stack.md @@ -0,0 +1,282 @@ +# Stack Dump + +> 引言:在工程中经常需要在异常发生的时候打印相应的日志,或利用成熟的第三方日志库,或自己进行简单的实现,在相应日志输出的时候,常常会有不同的级别,当遇到 error 或者 panic 之类的情况的时候,通常需要输出相应堆栈信息来辅助我们进行问题的定位以及解决,那么,关于堆栈这块的信息我们该怎么获取,获取的时候需要注意什么,以及堆栈的获取会对程序造成什么影响,会带来多大的性能损耗?日志库的使用或者进行相关配置我们该怎么选择?本章的目的就是深入一下 golang 中 stack dump 的细节 + +## STACK APIs +- debug.Stack + - debug.PrintStack +- runtime.Stack +- runtime.Callers + - runtime.Caller + +## debug.Stack & debug.PrintStack +```go +package main + +import ( + "fmt" + "runtime/debug" +) + +func main() { + fmt.Println(debug.Stack()) +} +``` +runtime/debug/stack.go +```go +func Stack() []byte { + buf := make([]byte, 1024) + for { + /* + * 可以看到实质上 debug.Stack 调用的就是 runtime.Stack 方法 + * 并且会不断扩大 buf 大小直到读取完所有 stack 信息 + */ + n := runtime.Stack(buf, false) + if n < len(buf) { + return buf[:n] + } + buf = make([]byte, 2*len(buf)) + } +} +``` +而 runtime.Stack 方法入参为 `buf []byte` 以及 `all bool` 两个参数 +- `buf []byte` 是用来接收 stack dump 信息的 +- `all bool` 参数则是用来决定是否获取所有协程的堆栈 + +`buf` 参数比较好理解,而 `all` 参数如果设置为获取所有协程信息,则会触发 `STW` 操作,这是一个代价十分巨大的操作,整个 runtime 会被暂停以获取所有协程的堆栈信息而后再进行恢复, + +runtime/mprof.go +```go +func Stack(buf []byte, all bool) int { + if all { + stopTheWorld("stack trace") + } + + n := 0 + if len(buf) > 0 { + gp := getg() + sp := getcallersp() + pc := getcallerpc() + systemstack(func() { + g0 := getg() + // Force traceback=1 to override GOTRACEBACK setting, + // so that Stack's results are consistent. + // GOTRACEBACK is only about crash dumps. + g0.m.traceback = 1 + g0.writebuf = buf[0:0:len(buf)] + goroutineheader(gp) + traceback(pc, sp, 0, gp) + if all { + tracebackothers(gp) + } + g0.m.traceback = 0 + n = len(g0.writebuf) + g0.writebuf = nil + }) + } + + if all { + startTheWorld() + } + return n +} +``` +分析下具体调用过程,首先判断是否进行 `STW`,而后通过`getg()` 获取当前 goroutine +- `getcallersp()`: 汇编实现,获取当前调用 stack pointer (SP) +- `getcallerpc()`: 汇编实现,获取当前调用方的程序计数器 program counter (PC) +- `systemstack`: 切换到系统栈执行传入函数(如果当前就在系统栈则直接执行),可以看到在传入的函数中再次调用 getg() 获取到了 g0 (主协程)。并且将传入的 buf 放置在了 g0 的 writebuf 上(slice 底层 data 地址不变) +- `goroutineheader` 获取 gp 协程头部信息 + +runtime/traceback.go +```go +func goroutineheader(gp *g) { + gpstatus := readgstatus(gp) + + isScan := gpstatus&_Gscan != 0 + gpstatus &^= _Gscan // drop the scan bit + + // Basic string status + var status string + if 0 <= gpstatus && gpstatus < uint32(len(gStatusStrings)) { + status = gStatusStrings[gpstatus] + } else { + status = "???" + } + + // Override. + if gpstatus == _Gwaiting && gp.waitreason != waitReasonZero { + status = gp.waitreason.String() + } + + // approx time the G is blocked, in minutes + var waitfor int64 + if (gpstatus == _Gwaiting || gpstatus == _Gsyscall) && gp.waitsince != 0 { + waitfor = (nanotime() - gp.waitsince) / 60e9 + } + print("goroutine ", gp.goid, " [", status) + if isScan { + print(" (scan)") + } + if waitfor >= 1 { + print(", ", waitfor, " minutes") + } + if gp.lockedm != 0 { + print(", locked to thread") + } + print("]:\n") +} +``` +函数内部直接调用内置函数 `print` 将信息输入到刚才设置的 `writebuf` 中,`print` 内置函数具体实现可以查看 `runtime/print.go`,内部是将 `print` 的值通过 copy 复制到当前协程的 `writebuf` 上 + +runtime/print.go +```go +func gwrite(b []byte) { + if len(b) == 0 { + return + } + recordForPanic(b) + gp := getg() + // Don't use the writebuf if gp.m is dying. We want anything + // written through gwrite to appear in the terminal rather + // than be written to in some buffer, if we're in a panicking state. + // Note that we can't just clear writebuf in the gp.m.dying case + // because a panic isn't allowed to have any write barriers. + if gp == nil || gp.writebuf == nil || gp.m.dying > 0 { + writeErr(b) + return + } + + n := copy(gp.writebuf[len(gp.writebuf):cap(gp.writebuf)], b) + gp.writebuf = gp.writebuf[:len(gp.writebuf)+n] +} +``` +继续回到之前的分析 +- `traceback` + +```go +func traceback1(pc, sp, lr uintptr, gp *g, flags uint) { + // If the goroutine is in cgo, and we have a cgo traceback, print that. + if iscgo && gp.m != nil && gp.m.ncgo > 0 && gp.syscallsp != 0 && gp.m.cgoCallers != nil && gp.m.cgoCallers[0] != 0 { + // Lock cgoCallers so that a signal handler won't + // change it, copy the array, reset it, unlock it. + // We are locked to the thread and are not running + // concurrently with a signal handler. + // We just have to stop a signal handler from interrupting + // in the middle of our copy. + atomic.Store(&gp.m.cgoCallersUse, 1) + cgoCallers := *gp.m.cgoCallers + gp.m.cgoCallers[0] = 0 + atomic.Store(&gp.m.cgoCallersUse, 0) + + printCgoTraceback(&cgoCallers) + } + + var n int + if readgstatus(gp)&^_Gscan == _Gsyscall { + // Override registers if blocked in system call. + pc = gp.syscallpc + sp = gp.syscallsp + flags &^= _TraceTrap + } + // Print traceback. By default, omits runtime frames. + // If that means we print nothing at all, repeat forcing all frames printed. + n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags) + if n == 0 && (flags&_TraceRuntimeFrames) == 0 { + n = gentraceback(pc, sp, lr, gp, 0, nil, _TracebackMaxFrames, nil, nil, flags|_TraceRuntimeFrames) + } + if n == _TracebackMaxFrames { + print("...additional frames elided...\n") + } + printcreatedby(gp) + + if gp.ancestors == nil { + return + } + for _, ancestor := range *gp.ancestors { + printAncestorTraceback(ancestor) + } +} +``` +函数首先判断了 `cgo` 相关信息,如果是处于 `cgo` 的模式中,那么输出一下 `cgo` 的堆栈信息(如果有的话) + +而后调用关键的 `gentraceback` 函数 +```go +func gentraceback(pc0, sp0, lr0 uintptr, gp *g, skip int, pcbuf *uintptr, max int, callback func(*stkframe, unsafe.Pointer) bool, v unsafe.Pointer, flags uint) int +``` +可以看到,通过 `debug.Stack` 函数调用时,max 参数传入的值为 `_TracebackMaxFrames` +```go +// The maximum number of frames we print for a traceback +const _TracebackMaxFrames = 100 +``` +最大帧数为固定值 100,意味着在 stack dump 时需要追溯至多 100 个栈帧的信息,O(N) 复杂度。 + +## runtime.Caller & runtime.Callers +runtime/extern.go +```go +// Caller reports file and line number information about function invocations on +// the calling goroutine's stack. The argument skip is the number of stack frames +// to ascend, with 0 identifying the caller of Caller. (For historical reasons the +// meaning of skip differs between Caller and Callers.) The return values report the +// program counter, file name, and line number within the file of the corresponding +// call. The boolean ok is false if it was not possible to recover the information. +func Caller(skip int) (pc uintptr, file string, line int, ok bool) { + rpc := make([]uintptr, 1) + n := callers(skip+1, rpc[:]) + if n < 1 { + return + } + frame, _ := CallersFrames(rpc).Next() + return frame.PC, frame.File, frame.Line, frame.PC != 0 +} + +// Callers fills the slice pc with the return program counters of function invocations +// on the calling goroutine's stack. The argument skip is the number of stack frames +// to skip before recording in pc, with 0 identifying the frame for Callers itself and +// 1 identifying the caller of Callers. +// It returns the number of entries written to pc. +// +// To translate these PCs into symbolic information such as function +// names and line numbers, use CallersFrames. CallersFrames accounts +// for inlined functions and adjusts the return program counters into +// call program counters. Iterating over the returned slice of PCs +// directly is discouraged, as is using FuncForPC on any of the +// returned PCs, since these cannot account for inlining or return +// program counter adjustment. +func Callers(skip int, pc []uintptr) int { + // runtime.callers uses pc.array==nil as a signal + // to print a stack trace. Pick off 0-length pc here + // so that we don't let a nil pc slice get to it. + if len(pc) == 0 { + return 0 + } + return callers(skip, pc) +} +``` +以上两个函数最终调用的都是 `callers` 函数 +```go +func callers(skip int, pcbuf []uintptr) int { + sp := getcallersp() + pc := getcallerpc() + gp := getg() + var n int + systemstack(func() { + n = gentraceback(pc, sp, 0, gp, skip, &pcbuf[0], len(pcbuf), nil, nil, 0) + }) + return n +} +``` +`callers` 函数大部分逻辑和之前的 `runtime.Stack`函数中 `traceback` 大同小异,唯一不同的就是 +`gentraceback` 调用的入参 `max` 参数是人为设置的,并且仅针对当前 `goroutine` 进行 +## 总结 +- stack dump 操作是否会有性能损耗(是),损耗在哪儿 + - 与调用方式有关,如果是通过类似 `runtime.Stack` 方法打印所有堆栈信息的, 会触发 `STW` 操作,是一个代价比较大的操作 + - 与需要追溯的栈帧数量有关 + - 会触发协程的切换 + - 更细致化一些例如 `stack dump` 出的信息会进行 `copy` 操作等等 + +- 如何更优雅地获取 `stack dump` 信息? + - 以 `runtime.Callers` 与 `runtime.CallersFrames` 相结合代替 `runtime.Stack` 、`debug.Stack`,避免使用默认的 `stack dump` 配置,根据自己的业务情况选择合适的栈帧数量(如不同级别的日志打印不同数量的栈帧信息),知名的开源日志库 `github.com/uber-go/zap` 正是使用这种思路 + +---- +### 参考: +[zap stacktrace 实现](https://github.com/uber-go/zap/blob/v1.16.0/stacktrace.go) \ No newline at end of file diff --git a/scheduler.md b/scheduler.md index 5f7afdc..7d4557b 100644 --- a/scheduler.md +++ b/scheduler.md @@ -1,3 +1,4 @@ +> 注: 在抢占式调度的 go 版本下如果需要对 runtime 进行调试,诸如使用 gdb, lldb, [delve](https://github.com/go-delve/delve) 等工具时,需要注意 GODEBUG=asyncpreemptoff=1 环境变量,该变量会决定 runtime 是否开启抢占式调度,由于 https://github.com/golang/go/issues/36494 ,导致部分系统下该变量会被一些(如 delve)工具配置开启,从而导致超出预期的调试情况,需要读者自行关注 # 调度 ## 基本数据结构 @@ -751,6 +752,8 @@ runtime.gcenable --> main.init main.init --> main.main ``` +**主线程也是需要和 p 绑定来运行的**,绑定过程在 procresize -> acquirep 中。 + ### sysmon 线程 sysmon 是在 `runtime.main` 中启动的,不过需要注意的是 sysmon 并不是在 m0 上执行的。因为: @@ -1618,7 +1621,7 @@ findrunnable 比较复杂,流程图先把 gc 相关的省略掉了: ```mermaid graph TD -runqget --> A[gp == nil] +localrunqget --> A[gp == nil] A --> |no|return A --> |yes|globrunqget globrunqget --> B[gp == nil] @@ -1641,7 +1644,7 @@ H --> |yes|I[netpoll] I --> J[gp == nil] J --> |no| return J --> |yes| stopm -stopm --> runqget +stopm --> localrunqget ``` ```go @@ -2344,3 +2347,5 @@ gcMarkDone --> forEachP 可见只有 gc 和 retake 才会去真正地抢占 g,并没有其它的入口,其它的地方就只是恢复一下可能在 newstack 中被清除掉的抢占标记。 当然,这里 entersyscall 和 entersyscallblock 比较特殊,虽然这俩函数的实现中有设置抢占标记,但实际上这两段逻辑是不会被走到的。因为 syscall 执行时是在 m 的 g0 栈上,如果在执行时被抢占,那么会直接 throw,而无法恢复。 + + diff --git a/select.md b/select.md index e5a81bc..ed93053 100644 --- a/select.md +++ b/select.md @@ -563,7 +563,15 @@ loop: switch cas.kind { case caseNil: - // 这个 case 要怎么触发? + /* + * var nil_chan chan int + * var non_nil_chan chan int = make(chan int) + * select { + * case <-nil_chan: + * // here + * case <-non_nil_chan: + * } + */ continue case caseRecv: @@ -817,4 +825,6 @@ sclose: Q: 如果select多个channel,有一个channel触发了,其他channel的waitlist需要不要主动去除?还是一直在那等着? -A: TODO +A: waitlist 的出列是由 `func (q *waitq) dequeue() *sudog` 函数控制的,每个 sudog 携带了一个 `selectDone` 标志位,通过 `cas` 操作在每次 `dequeue` 的时候「惰性」去除队列中无效的元素 + + diff --git a/semaphore.md b/semaphore.md index 4fbeddd..51d4640 100644 --- a/semaphore.md +++ b/semaphore.md @@ -236,7 +236,7 @@ func semacquire1(addr *uint32, lifo bool, profile semaProfileFlags) { // 高成本的情况: // 增加 waiter count 的值 - // 再尝试调用一次 cansemacquire,成本了就直接返回 + // 再尝试调用一次 cansemacquire,成功了就直接返回 // 没成功就把自己作为一个 waiter 入队 // sleep // (之后 waiter 的 descriptor 被 signaler 用 dequeue 踢出) @@ -735,4 +735,6 @@ func notifyListCheck(sz uintptr) { func sync_nanotime() int64 { return nanotime() } -``` \ No newline at end of file +``` + + diff --git a/signal.md b/signal.md deleted file mode 100644 index 09c2668..0000000 --- a/signal.md +++ /dev/null @@ -1,3 +0,0 @@ -# Signal - -Go 1.12 的抢占使用 signal 来实现,所以我们来分析一下 Go runtime 中是怎么处理这些 signal 的。 diff --git a/site/README.md b/site/README.md new file mode 100644 index 0000000..f6a4c5e --- /dev/null +++ b/site/README.md @@ -0,0 +1,3 @@ +# golang + +source of go.xargin.com diff --git a/site/archetypes/default.md b/site/archetypes/default.md new file mode 100644 index 0000000..00e77bd --- /dev/null +++ b/site/archetypes/default.md @@ -0,0 +1,6 @@ +--- +title: "{{ replace .Name "-" " " | title }}" +date: {{ .Date }} +draft: true +--- + diff --git a/site/config.toml b/site/config.toml new file mode 100644 index 0000000..80f33af --- /dev/null +++ b/site/config.toml @@ -0,0 +1,6 @@ +baseURL = "http://go.xargin.com/" +languageCode = "en-us" +title = "Go 语言笔记" +theme = "book" +googleAnalytics = "G-KLR638LKEQ" + diff --git a/site/content/_index.md b/site/content/_index.md new file mode 100644 index 0000000..e5fb159 --- /dev/null +++ b/site/content/_index.md @@ -0,0 +1,13 @@ +--- +title: Go 语言笔记 +type: docs +--- + +# Go 语言笔记 + +## 为什么会有这本书 + +之前关于 Go 的输出主要散落在 blog 和 github 的 golang-notes 以及公众号中,内容比较分散。不方便阅读,到了这个时间点,本人已经使用 Go 已有超过 6 个年头,可以将之前的输出集合起来,进行系统化的输出了。 + +![nobody knows more about Go than me](/images/index/banner.jpg) + diff --git a/site/content/docs/_index.md b/site/content/docs/_index.md new file mode 100644 index 0000000..e69de29 diff --git a/site/content/docs/api_programming/_index.md b/site/content/docs/api_programming/_index.md new file mode 100644 index 0000000..7718841 --- /dev/null +++ b/site/content/docs/api_programming/_index.md @@ -0,0 +1,6 @@ +--- +title: API 开发 +weight: 5 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/api_programming/fasthttp.md b/site/content/docs/api_programming/fasthttp.md new file mode 100644 index 0000000..a886942 --- /dev/null +++ b/site/content/docs/api_programming/fasthttp.md @@ -0,0 +1,2 @@ +# FastHTTP + diff --git a/site/content/docs/api_programming/httprouter.md b/site/content/docs/api_programming/httprouter.md new file mode 100644 index 0000000..bc5ea15 --- /dev/null +++ b/site/content/docs/api_programming/httprouter.md @@ -0,0 +1 @@ +# http router 的实现 diff --git a/site/content/docs/api_programming/mysql.md b/site/content/docs/api_programming/mysql.md new file mode 100644 index 0000000..c64321e --- /dev/null +++ b/site/content/docs/api_programming/mysql.md @@ -0,0 +1 @@ +# mysql diff --git a/site/content/docs/api_programming/orm.md b/site/content/docs/api_programming/orm.md new file mode 100644 index 0000000..c69e1ca --- /dev/null +++ b/site/content/docs/api_programming/orm.md @@ -0,0 +1 @@ +# orm && sql builder diff --git a/site/content/docs/api_programming/validator.md b/site/content/docs/api_programming/validator.md new file mode 100644 index 0000000..76a423c --- /dev/null +++ b/site/content/docs/api_programming/validator.md @@ -0,0 +1 @@ +# validator diff --git a/site/content/docs/api_programming/viper.md b/site/content/docs/api_programming/viper.md new file mode 100644 index 0000000..63d973f --- /dev/null +++ b/site/content/docs/api_programming/viper.md @@ -0,0 +1 @@ +# viper diff --git a/site/content/docs/assembly/_index.md b/site/content/docs/assembly/_index.md new file mode 100644 index 0000000..18a2318 --- /dev/null +++ b/site/content/docs/assembly/_index.md @@ -0,0 +1,6 @@ +--- +title: 汇编基础 +weight: 1 +bookCollapseSection: true +--- + diff --git a/site/content/docs/assembly/assembly.md b/site/content/docs/assembly/assembly.md new file mode 100644 index 0000000..22fef9c --- /dev/null +++ b/site/content/docs/assembly/assembly.md @@ -0,0 +1,1006 @@ +--- +title: Plan9 汇编解析 +weight: 10 +--- + +# plan9 assembly 完全解析 + +众所周知,Go 使用了 Unix 老古董(误 们发明的 plan9 汇编。就算你对 x86 汇编有所了解,在 plan9 里还是有些许区别。说不定你在看代码的时候,偶然发现代码里的 SP 看起来是 SP,但它实际上不是 SP 的时候就抓狂了哈哈哈。 + +本文将对 plan9 汇编进行全面的介绍,同时解答你在接触 plan9 汇编时可能遇到的大部分问题。 + +本文所使用的平台是 linux amd64,因为不同的平台指令集和寄存器都不一样,所以没有办法共同探讨。这也是由汇编本身的性质决定的。 + +## 基本指令 + +### 栈调整 + +intel 或 AT&T 汇编提供了 push 和 pop 指令族,~~plan9 中没有 push 和 pop~~,plan9 中虽然有 push 和 pop 指令,但一般生成的代码中是没有的,我们看到的栈的调整大多是通过对硬件 SP 寄存器进行运算来实现的,例如: + +```go +SUBQ $0x18, SP // 对 SP 做减法,为函数分配函数栈帧 +... // 省略无用代码 +ADDQ $0x18, SP // 对 SP 做加法,清除函数栈帧 +``` + +通用的指令和 X64 平台差不多,下面分节详述。 + +### 数据搬运 + +常数在 plan9 汇编用 $num 表示,可以为负数,默认情况下为十进制。可以用 $0x123 的形式来表示十六进制数。 + +```go +MOVB $1, DI // 1 byte +MOVW $0x10, BX // 2 bytes +MOVD $1, DX // 4 bytes +MOVQ $-10, AX // 8 bytes +``` + +可以看到,搬运的长度是由 MOV 的后缀决定的,这一点与 intel 汇编稍有不同,看看类似的 X64 汇编: + +```asm +mov rax, 0x1 // 8 bytes +mov eax, 0x100 // 4 bytes +mov ax, 0x22 // 2 bytes +mov ah, 0x33 // 1 byte +mov al, 0x44 // 1 byte +``` + +plan9 的汇编的操作数的方向是和 intel 汇编相反的,与 AT&T 类似。 + +```go +MOVQ $0x10, AX ===== mov rax, 0x10 + | |------------| | + |------------------------| +``` + +不过凡事总有例外,如果想了解这种意外,可以参见参考资料中的 [1]。 + +### 常见计算指令 + +```go +ADDQ AX, BX // BX += AX +SUBQ AX, BX // BX -= AX +IMULQ AX, BX // BX *= AX +``` + +类似数据搬运指令,同样可以通过修改指令的后缀来对应不同长度的操作数。例如 ADDQ/ADDW/ADDL/ADDB。 + +### 条件跳转/无条件跳转 + +```go +// 无条件跳转 +JMP addr // 跳转到地址,地址可为代码中的地址,不过实际上手写不会出现这种东西 +JMP label // 跳转到标签,可以跳转到同一函数内的标签位置 +JMP 2(PC) // 以当前指令为基础,向前/后跳转 x 行 +JMP -2(PC) // 同上 + +// 有条件跳转 +JZ target // 如果 zero flag 被 set 过,则跳转 + +``` + + +### 指令集 + +可以参考源代码的 [arch](https://github.com/golang/arch/blob/master/x86/x86.csv) 部分。 + +额外提一句,Go 1.10 添加了大量的 SIMD 指令支持,所以在该版本以上的话,不像之前写那样痛苦了,也就是不用人肉填 byte 了。 + +## 寄存器 + +### 通用寄存器 + +amd64 的通用寄存器: + +```gdb +(lldb) reg read +General Purpose Registers: + rax = 0x0000000000000005 + rbx = 0x000000c420088000 + rcx = 0x0000000000000000 + rdx = 0x0000000000000000 + rdi = 0x000000c420088008 + rsi = 0x0000000000000000 + rbp = 0x000000c420047f78 + rsp = 0x000000c420047ed8 + r8 = 0x0000000000000004 + r9 = 0x0000000000000000 + r10 = 0x000000c420020001 + r11 = 0x0000000000000202 + r12 = 0x0000000000000000 + r13 = 0x00000000000000f1 + r14 = 0x0000000000000011 + r15 = 0x0000000000000001 + rip = 0x000000000108ef85 int`main.main + 213 at int.go:19 + rflags = 0x0000000000000212 + cs = 0x000000000000002b + fs = 0x0000000000000000 + gs = 0x0000000000000000 +``` + +在 plan9 汇编里都是可以使用的,应用代码层面会用到的通用寄存器主要是: rax, rbx, rcx, rdx, rdi, rsi, r8~r15 这 14 个寄存器,虽然 rbp 和 rsp 也可以用,不过 bp 和 sp 会被用来管理栈顶和栈底,最好不要拿来进行运算。 + +plan9 中使用寄存器不需要带 r 或 e 的前缀,例如 rax,只要写 AX 即可: + +```go +MOVQ $101, AX = mov rax, 101 +``` + +下面是通用通用寄存器的名字在 X64 和 plan9 中的对应关系: + +| X64 | rax | rbx| rcx | rdx | rdi | rsi | rbp | rsp | r8 | r9 | r10 | r11 | r12 | r13 | r14 | rip| +|--|--|--|--| --| --|--| --|--|--|--|--|--|--|--|--|--| +| Plan9 | AX | BX | CX | DX | DI | SI | BP | SP | R8 | R9 | R10 | R11 | R12 | R13 | R14 | PC | + +### 伪寄存器 + +Go 的汇编还引入了 4 个伪寄存器,援引官方文档的描述: + +>- `FP`: Frame pointer: arguments and locals. +>- `PC`: Program counter: jumps and branches. +>- `SB`: Static base pointer: global symbols. +>- `SP`: Stack pointer: the highest address within the local stack frame. + +官方的描述稍微有一些问题,我们对这些说明进行一点扩充: + +- FP: 使用形如 `symbol+offset(FP)` 的方式,引用函数的输入参数。例如 `arg0+0(FP)`,`arg1+8(FP)`,使用 FP 不加 symbol 时,无法通过编译,在汇编层面来讲,symbol 并没有什么用,加 symbol 主要是为了提升代码可读性。另外,官方文档虽然将伪寄存器 FP 称之为 frame pointer,实际上它根本不是 frame pointer,按照传统的 x86 的习惯来讲,frame pointer 是指向整个 stack frame 底部的 BP 寄存器。假如当前的 callee 函数是 add,在 add 的代码中引用 FP,该 FP 指向的位置不在 callee 的 stack frame 之内,而是在 caller 的 stack frame 上。具体可参见之后的 **栈结构** 一章。 +- PC: 实际上就是在体系结构的知识中常见的 pc 寄存器,在 x86 平台下对应 ip 寄存器,amd64 上则是 rip。除了个别跳转之外,手写 plan9 代码与 PC 寄存器打交道的情况较少。 +- SB: 全局静态基指针,一般用来声明函数或全局变量,在之后的函数知识和示例部分会看到具体用法。 +- SP: plan9 的这个 SP 寄存器指向当前栈帧的局部变量的开始位置,使用形如 `symbol+offset(SP)` 的方式,引用函数的局部变量。offset 的合法取值是 [-framesize, 0),注意是个左闭右开的区间。假如局部变量都是 8 字节,那么第一个局部变量就可以用 `localvar0-8(SP)` 来表示。这也是一个词不表意的寄存器。与硬件寄存器 SP 是两个不同的东西,在栈帧 size 为 0 的情况下,伪寄存器 SP 和硬件寄存器 SP 指向同一位置。手写汇编代码时,如果是 `symbol+offset(SP)` 形式,则表示伪寄存器 SP。如果是 `offset(SP)` 则表示硬件寄存器 SP。务必注意。对于编译输出(go tool compile -S / go tool objdump)的代码来讲,目前所有的 SP 都是硬件寄存器 SP,无论是否带 symbol。 + +我们这里对容易混淆的几点简单进行说明: + +1. 伪 SP 和硬件 SP 不是一回事,在手写代码时,伪 SP 和硬件 SP 的区分方法是看该 SP 前是否有 symbol。如果有 symbol,那么即为伪寄存器,如果没有,那么说明是硬件 SP 寄存器。 +2. SP 和 FP 的相对位置是会变的,所以不应该尝试用伪 SP 寄存器去找那些用 FP + offset 来引用的值,例如函数的入参和返回值。 +3. 官方文档中说的伪 SP 指向 stack 的 top,是有问题的。其指向的局部变量位置实际上是整个栈的栈底(除 caller BP 之外),所以说 bottom 更合适一些。 +4. 在 go tool objdump/go tool compile -S 输出的代码中,是没有伪 SP 和 FP 寄存器的,我们上面说的区分伪 SP 和硬件 SP 寄存器的方法,对于上述两个命令的输出结果是没法使用的。在编译和反汇编的结果中,只有真实的 SP 寄存器。 +5. FP 和 Go 的官方源代码里的 framepointer 不是一回事,源代码里的 framepointer 指的是 caller BP 寄存器的值,在这里和 caller 的伪 SP 是值是相等的。 + +以上说明看不懂也没关系,在熟悉了函数的栈结构之后再反复回来查看应该就可以明白了。 + +## 变量声明 + +在汇编里所谓的变量,一般是存储在 .rodata 或者 .data 段中的只读值。对应到应用层的话,就是已初始化过的全局的 const、var、static 变量/常量。 + +使用 DATA 结合 GLOBL 来定义一个变量。DATA 的用法为: + +```go +DATA symbol+offset(SB)/width, value +``` + +大多数参数都是字面意思,不过这个 offset 需要稍微注意。其含义是该值相对于符号 symbol 的偏移,而不是相对于全局某个地址的偏移。 + +使用 GLOBL 指令将变量声明为 global,额外接收两个参数,一个是 flag,另一个是变量的总大小。 + +```go +GLOBL divtab(SB), RODATA, $64 +``` + +GLOBL 必须跟在 DATA 指令之后,下面是一个定义了多个 readonly 的全局变量的完整例子: + +```go +DATA age+0x00(SB)/4, $18 // forever 18 +GLOBL age(SB), RODATA, $4 + +DATA pi+0(SB)/8, $3.1415926 +GLOBL pi(SB), RODATA, $8 + +DATA birthYear+0(SB)/4, $1988 +GLOBL birthYear(SB), RODATA, $4 +``` + +正如之前所说,所有符号在声明时,其 offset 一般都是 0。 + +有时也可能会想在全局变量中定义数组,或字符串,这时候就需要用上非 0 的 offset 了,例如: + +```go +DATA bio<>+0(SB)/8, $"oh yes i" +DATA bio<>+8(SB)/8, $"am here " +GLOBL bio<>(SB), RODATA, $16 +``` + +大部分都比较好理解,不过这里我们又引入了新的标记 `<>`,这个跟在符号名之后,表示该全局变量只在当前文件中生效,类似于 C 语言中的 static。如果在另外文件中引用该变量的话,会报 `relocation target not found` 的错误。 + +本小节中提到的 flag,还可以有其它的取值: +>- `NOPROF` = 1 + (For `TEXT` items.) Don't profile the marked function. This flag is deprecated. +>- `DUPOK` = 2 + It is legal to have multiple instances of this symbol in a single binary. The linker will choose one of the duplicates to use. +>- `NOSPLIT` = 4 + (For `TEXT` items.) Don't insert the preamble to check if the stack must be split. The frame for the routine, plus anything it calls, must fit in the spare space at the top of the stack segment. Used to protect routines such as the stack splitting code itself. +>- `RODATA` = 8 + (For `DATA` and `GLOBL` items.) Put this data in a read-only section. +>- `NOPTR` = 16 + (For `DATA` and `GLOBL` items.) This data contains no pointers and therefore does not need to be scanned by the garbage collector. +>- `WRAPPER` = 32 + (For `TEXT` items.) This is a wrapper function and should not count as disabling `recover`. +>- `NEEDCTXT` = 64 + (For `TEXT` items.) This function is a closure so it uses its incoming context register. + +当使用这些 flag 的字面量时,需要在汇编文件中 `#include "textflag.h"`。 + +## .s 和 .go 文件的全局变量互通 + +在 `.s` 文件中是可以直接使用 `.go` 中定义的全局变量的,看看下面这个简单的例子: + +refer.go: + +```go +package main + +var a = 999 +func get() int + +func main() { + println(get()) +} + +``` + +refer.s: + +```go +#include "textflag.h" + +TEXT ·get(SB), NOSPLIT, $0-8 + MOVQ ·a(SB), AX + MOVQ AX, ret+0(FP) + RET +``` + +·a(SB),表示该符号需要链接器来帮我们进行重定向(relocation),如果找不到该符号,会输出 `relocation target not found` 的错误。 + +例子比较简单,大家可以自行尝试。 + +## 函数声明 + +我们来看看一个典型的 plan9 的汇编函数的定义: + +```go +// func add(a, b int) int +// => 该声明定义在同一个 package 下的任意 .go 文件中 +// => 只有函数头,没有实现 +TEXT pkgname·add(SB), NOSPLIT, $0-8 + MOVQ a+0(FP), AX + MOVQ a+8(FP), BX + ADDQ AX, BX + MOVQ BX, ret+16(FP) + RET +``` + +为什么要叫 TEXT ?如果对程序数据在文件中和内存中的分段稍有了解的同学应该知道,我们的代码在二进制文件中,是存储在 .text 段中的,这里也就是一种约定俗成的起名方式。实际上在 plan9 中 TEXT 是一个指令,用来定义一个函数。除了 TEXT 之外还有前面变量声明说到的 DATA/GLOBL。 + +定义中的 pkgname 部分是可以省略的,非想写也可以写上。不过写上 pkgname 的话,在重命名 package 之后还需要改代码,所以推荐最好还是不要写。 + +中点 `·` 比较特殊,是一个 unicode 的中点,该点在 mac 下的输入方法是 `option+shift+9`。在程序被链接之后,所有的中点`·` 都会被替换为句号`.`,比如你的方法是 `runtime·main`,在编译之后的程序里的符号则是 `runtime.main`。嗯,看起来很变态。简单总结一下: + +```go + + 参数及返回值大小 + | + TEXT pkgname·add(SB),NOSPLIT,$32-32 + | | | + 包名 函数名 栈帧大小(局部变量+可能需要的额外调用函数的参数空间的总大小,但不包括调用其它函数时的 ret address 的大小) + +``` + +## 栈结构 + +下面是一个典型的函数的栈结构图: + +``` + + ----------------- + current func arg0 + ----------------- <----------- FP(pseudo FP) + caller ret addr + +---------------+ + | caller BP(*) | + ----------------- <----------- SP(pseudo SP,实际上是当前栈帧的 BP 位置) + | Local Var0 | + ----------------- + | Local Var1 | + ----------------- + | Local Var2 | + ----------------- - + | ........ | + ----------------- + | Local VarN | + ----------------- + | | + | | + | temporarily | + | unused space | + | | + | | + ----------------- + | call retn | + ----------------- + | call ret(n-1)| + ----------------- + | .......... | + ----------------- + | call ret1 | + ----------------- + | call argn | + ----------------- + | ..... | + ----------------- + | call arg3 | + ----------------- + | call arg2 | + |---------------| + | call arg1 | + ----------------- <------------ hardware SP 位置 + return addr + +---------------+ + + +``` + +从原理上来讲,如果当前函数调用了其它函数,那么 return addr 也是在 caller 的栈上的,不过往栈上插 return addr 的过程是由 CALL 指令完成的,在 RET 时,SP 又会恢复到图上位置。我们在计算 SP 和参数相对位置时,可以认为硬件 SP 指向的就是图上的位置。 + +图上的 caller BP,指的是 caller 的 BP 寄存器值,有些人把 caller BP 叫作 caller 的 frame pointer,实际上这个习惯是从 x86 架构沿袭来的。Go 的 asm 文档中把伪寄存器 FP 也称为 frame pointer,但是这两个 frame pointer 根本不是一回事。 + +此外需要注意的是,caller BP 是在编译期由编译器插入的,用户手写代码时,计算 frame size 时是不包括这个 caller BP 部分的。是否插入 caller BP 的主要判断依据是: + +1. 函数的栈帧大小大于 0 +2. 下述函数返回 true + +```go +func Framepointer_enabled(goos, goarch string) bool { + return framepointer_enabled != 0 && goarch == "amd64" && goos != "nacl" +} +``` + +如果编译器在最终的汇编结果中没有插入 caller BP(源代码中所称的 frame pointer)的情况下,伪 SP 和伪 FP 之间只有 8 个字节的 caller 的 return address,而插入了 BP 的话,就会多出额外的 8 字节。也就说伪 SP 和伪 FP 的相对位置是不固定的,有可能是间隔 8 个字节,也有可能间隔 16 个字节。并且判断依据会根据平台和 Go 的版本有所不同。 + +图上可以看到,FP 伪寄存器指向函数的传入参数的开始位置,因为栈是朝低地址方向增长,为了通过寄存器引用参数时方便,所以参数的摆放方向和栈的增长方向是相反的,即: + +```shell + FP +high ----------------------> low +argN, ... arg3, arg2, arg1, arg0 +``` + +假设所有参数均为 8 字节,这样我们就可以用 symname+0(FP) 访问第一个 参数,symname+8(FP) 访问第二个参数,以此类推。用伪 SP 来引用局部变量,原理上来讲差不多,不过因为伪 SP 指向的是局部变量的底部,所以 symname-8(SP) 表示的是第一个局部变量,symname-16(SP)表示第二个,以此类推。当然,这里假设局部变量都占用 8 个字节。 + +图的最上部的 caller return address 和 current func arg0 都是由 caller 来分配空间的。不算在当前的栈帧内。 + +因为官方文档本身较模糊,我们来一个函数调用的全景图,来看一下这些真假 SP/FP/BP 到底是个什么关系: + +``` + + caller + +------------------+ + | | + +----------------------> -------------------- + | | | + | | caller parent BP | + | BP(pseudo SP) -------------------- + | | | + | | Local Var0 | + | -------------------- + | | | + | | ....... | + | -------------------- + | | | + | | Local VarN | + -------------------- + caller stack frame | | + | callee arg2 | + | |------------------| + | | | + | | callee arg1 | + | |------------------| + | | | + | | callee arg0 | + | ----------------------------------------------+ FP(virtual register) + | | | | + | | return addr | parent return address | + +----------------------> +------------------+--------------------------- <-------------------------------+ + | caller BP | | + | (caller frame pointer) | | + BP(pseudo SP) ---------------------------- | + | | | + | Local Var0 | | + ---------------------------- | + | | + | Local Var1 | + ---------------------------- callee stack frame + | | + | ..... | + ---------------------------- | + | | | + | Local VarN | | + SP(Real Register) ---------------------------- | + | | | + | | | + | | | + | | | + | | | + +--------------------------+ <-------------------------------+ + + callee +``` + +## argsize 和 framesize 计算规则 + +### argsize + +在函数声明中: + +```go + TEXT pkgname·add(SB),NOSPLIT,$16-32 +``` + +前面已经说过 $16-32 表示 $framesize-argsize。Go 在函数调用时,参数和返回值都需要由 caller 在其栈帧上备好空间。callee 在声明时仍然需要知道这个 argsize。argsize 的计算方法是,参数大小求和+返回值大小求和,例如入参是 3 个 int64 类型,返回值是 1 个 int64 类型,那么这里的 argsize = sizeof(int64) * 4。 + +不过真实世界永远没有我们假设的这么美好,函数参数往往混合了多种类型,还需要考虑内存对齐问题。 + +如果不确定自己的函数签名需要多大的 argsize,可以通过简单实现一个相同签名的空函数,然后 go tool objdump 来逆向查找应该分配多少空间。 + +### framesize + +函数的 framesize 就稍微复杂一些了,手写代码的 framesize 不需要考虑由编译器插入的 caller BP,要考虑: + +1. 局部变量,及其每个变量的 size。 +2. 在函数中是否有对其它函数调用时,如果有的话,调用时需要将 callee 的参数、返回值考虑在内。虽然 return address(rip)的值也是存储在 caller 的 stack frame 上的,但是这个过程是由 CALL 指令和 RET 指令完成 PC 寄存器的保存和恢复的,在手写汇编时,同样也是不需要考虑这个 PC 寄存器在栈上所需占用的 8 个字节的。 +3. 原则上来说,调用函数时只要不把局部变量覆盖掉就可以了。稍微多分配几个字节的 framesize 也不会死。 +4. 在确保逻辑没有问题的前提下,你愿意覆盖局部变量也没有问题。只要保证进入和退出汇编函数时的 caller 和 callee 能正确拿到返回值就可以。 + +## 地址运算 + +地址运算也是用 lea 指令,英文原意为 `Load Effective Address`,amd64 平台地址都是 8 个字节,所以直接就用 LEAQ 就好: + +```go +LEAQ (BX)(AX*8), CX +// 上面代码中的 8 代表 scale +// scale 只能是 0、2、4、8 +// 如果写成其它值: +// LEAQ (BX)(AX*3), CX +// ./a.s:6: bad scale: 3 + +// 用 LEAQ 的话,即使是两个寄存器值直接相加,也必须提供 scale +// 下面这样是不行的 +// LEAQ (BX)(AX), CX +// asm: asmidx: bad address 0/2064/2067 +// 正确的写法是 +LEAQ (BX)(AX*1), CX + + +// 在寄存器运算的基础上,可以加上额外的 offset +LEAQ 16(BX)(AX*1), CX + +// 三个寄存器做运算,还是别想了 +// LEAQ DX(BX)(AX*8), CX +// ./a.s:13: expected end of operand, found ( +``` + +使用 LEAQ 的好处也比较明显,可以节省指令数。如果用基本算术指令来实现 LEAQ 的功能,需要两~三条以上的计算指令才能实现 LEAQ 的完整功能。 + +## 示例 + +### add/sub/mul + +math.go: + +```go +package main + +import "fmt" + +func add(a, b int) int // 汇编函数声明 + +func sub(a, b int) int // 汇编函数声明 + +func mul(a, b int) int // 汇编函数声明 + +func main() { + fmt.Println(add(10, 11)) + fmt.Println(sub(99, 15)) + fmt.Println(mul(11, 12)) +} +``` + +math.s: + +```go +#include "textflag.h" // 因为我们声明函数用到了 NOSPLIT 这样的 flag,所以需要将 textflag.h 包含进来 + +// func add(a, b int) int +TEXT ·add(SB), NOSPLIT, $0-24 + MOVQ a+0(FP), AX // 参数 a + MOVQ b+8(FP), BX // 参数 b + ADDQ BX, AX // AX += BX + MOVQ AX, ret+16(FP) // 返回 + RET + +// func sub(a, b int) int +TEXT ·sub(SB), NOSPLIT, $0-24 + MOVQ a+0(FP), AX + MOVQ b+8(FP), BX + SUBQ BX, AX // AX -= BX + MOVQ AX, ret+16(FP) + RET + +// func mul(a, b int) int +TEXT ·mul(SB), NOSPLIT, $0-24 + MOVQ a+0(FP), AX + MOVQ b+8(FP), BX + IMULQ BX, AX // AX *= BX + MOVQ AX, ret+16(FP) + RET + // 最后一行的空行是必须的,否则可能报 unexpected EOF +``` + +把这两个文件放在任意目录下,执行 `go build` 并运行就可以看到效果了。 + +### 伪寄存器 SP 、伪寄存器 FP 和硬件寄存器 SP + +来写一段简单的代码证明伪 SP、伪 FP 和硬件 SP 的位置关系。 +spspfp.s: + +```go +#include "textflag.h" + +// func output(int) (int, int, int) +TEXT ·output(SB), $8-48 + MOVQ 24(SP), DX // 不带 symbol,这里的 SP 是硬件寄存器 SP + MOVQ DX, ret3+24(FP) // 第三个返回值 + MOVQ perhapsArg1+16(SP), BX // 当前函数栈大小 > 0,所以 FP 在 SP 的上方 16 字节处 + MOVQ BX, ret2+16(FP) // 第二个返回值 + MOVQ arg1+0(FP), AX + MOVQ AX, ret1+8(FP) // 第一个返回值 + RET + +``` + +spspfp.go: + +```go +package main + +import ( + "fmt" +) + +func output(int) (int, int, int) // 汇编函数声明 + +func main() { + a, b, c := output(987654321) + fmt.Println(a, b, c) +} +``` + +执行上面的代码,可以得到输出: + +```shell +987654321 987654321 987654321 +``` + +和代码结合思考,可以知道我们当前的栈结构是这样的: + +```shell +------ +ret2 (8 bytes) +------ +ret1 (8 bytes) +------ +ret0 (8 bytes) +------ +arg0 (8 bytes) +------ FP +ret addr (8 bytes) +------ +caller BP (8 bytes) +------ pseudo SP +frame content (8 bytes) +------ hardware SP +``` + +本小节例子的 framesize 是大于 0 的,读者可以尝试修改 framesize 为 0,然后调整代码中引用伪 SP 和硬件 SP 时的 offset,来研究 framesize 为 0 时,伪 FP,伪 SP 和硬件 SP 三者之间的相对位置。 + +本小节的例子是为了告诉大家,伪 SP 和伪 FP 的相对位置是会变化的,手写时不应该用伪 SP 和 >0 的 offset 来引用数据,否则结果可能会出乎你的预料。 + +### 汇编调用非汇编函数 + +output.s: + +```go +#include "textflag.h" + +// func output(a,b int) int +TEXT ·output(SB), NOSPLIT, $24-24 + MOVQ a+0(FP), DX // arg a + MOVQ DX, 0(SP) // arg x + MOVQ b+8(FP), CX // arg b + MOVQ CX, 8(SP) // arg y + CALL ·add(SB) // 在调用 add 之前,已经把参数都通过物理寄存器 SP 搬到了函数的栈顶 + MOVQ 16(SP), AX // add 函数会把返回值放在这个位置 + MOVQ AX, ret+16(FP) // return result + RET + +``` + +output.go: + +```go +package main + +import "fmt" + +func add(x, y int) int { + return x + y +} + +func output(a, b int) int + +func main() { + s := output(10, 13) + fmt.Println(s) +} + +``` + +### 汇编中的循环 + +通过 DECQ 和 JZ 结合,可以实现高级语言里的循环逻辑: + +sum.s: + +```go +#include "textflag.h" + +// func sum(sl []int64) int64 +TEXT ·sum(SB), NOSPLIT, $0-32 + MOVQ $0, SI + MOVQ sl+0(FP), BX // &sl[0], addr of the first elem + MOVQ sl+8(FP), CX // len(sl) + INCQ CX // CX++, 因为要循环 len 次 + +start: + DECQ CX // CX-- + JZ done + ADDQ (BX), SI // SI += *BX + ADDQ $8, BX // 指针移动 + JMP start + +done: + // 返回地址是 24 是怎么得来的呢? + // 可以通过 go tool compile -S math.go 得知 + // 在调用 sum 函数时,会传入三个值,分别为: + // slice 的首地址、slice 的 len, slice 的 cap + // 不过我们这里的求和只需要 len,但 cap 依然会占用参数的空间 + // 就是 16(FP) + MOVQ SI, ret+24(FP) + RET +``` + +sum.go: + +```go +package main + +func sum([]int64) int64 + +func main() { + println(sum([]int64{1, 2, 3, 4, 5})) +} +``` + +## 扩展话题 + +### 标准库中的一些数据结构 + +#### 数值类型 + +标准库中的数值类型很多: + +1. int/int8/int16/int32/int64 +2. uint/uint8/uint16/uint32/uint64 +3. float32/float64 +4. byte/rune +5. uintptr + +这些类型在汇编中就是一段存储着数据的连续内存,只是内存长度不一样,操作的时候看好数据长度就行。 + +#### slice + +前面的例子已经说过了,slice 在传递给函数的时候,实际上会展开成三个参数: + +1. 首元素地址 +2. slice 的 len +3. slice 的 cap + +在汇编中处理时,只要知道这个原则那就很好办了,按顺序还是按索引操作随你开心。 + +#### string + +```go +package main + +//go:noinline +func stringParam(s string) {} + +func main() { + var x = "abcc" + stringParam(x) +} +``` + +用 `go tool compile -S` 输出其汇编: + +```go +0x001d 00029 (stringParam.go:11) LEAQ go.string."abcc"(SB), AX // 获取 RODATA 段中的字符串地址 +0x0024 00036 (stringParam.go:11) MOVQ AX, (SP) // 将获取到的地址放在栈顶,作为第一个参数 +0x0028 00040 (stringParam.go:11) MOVQ $4, 8(SP) // 字符串长度作为第二个参数 +0x0031 00049 (stringParam.go:11) PCDATA $0, $0 // gc 相关 +0x0031 00049 (stringParam.go:11) CALL "".stringParam(SB) // 调用 stringParam 函数 +``` + +在汇编层面 string 就是地址 + 字符串长度。 + +#### struct + +struct 在汇编层面实际上就是一段连续内存,在作为参数传给函数时,会将其展开在 caller 的栈上传给对应的 callee: + +struct.go + +```go +package main + +type address struct { + lng int + lat int +} + +type person struct { + age int + height int + addr address +} + +func readStruct(p person) (int, int, int, int) + +func main() { + var p = person{ + age: 99, + height: 88, + addr: address{ + lng: 77, + lat: 66, + }, + } + a, b, c, d := readStruct(p) + println(a, b, c, d) +} +``` + +struct.s + +```go +#include "textflag.h" + +TEXT ·readStruct(SB), NOSPLIT, $0-64 + MOVQ arg0+0(FP), AX + MOVQ AX, ret0+32(FP) + MOVQ arg1+8(FP), AX + MOVQ AX, ret1+40(FP) + MOVQ arg2+16(FP), AX + MOVQ AX, ret2+48(FP) + MOVQ arg3+24(FP), AX + MOVQ AX, ret3+56(FP) + RET +``` + +上述的程序会输出 99, 88, 77, 66,这表明即使是内嵌结构体,在内存分布上依然是连续的。 + +#### map + +通过对下述文件进行汇编(go tool compile -S),我们可以得到一个 map 在对某个 key 赋值时所需要做的操作: + +m.go: + +```go +package main + +func main() { + var m = map[int]int{} + m[43] = 1 + var n = map[string]int{} + n["abc"] = 1 + println(m, n) +} +``` + +看一看第七行的输出: + +```go +0x0085 00133 (m.go:7) LEAQ type.map[int]int(SB), AX +0x008c 00140 (m.go:7) MOVQ AX, (SP) +0x0090 00144 (m.go:7) LEAQ ""..autotmp_2+232(SP), AX +0x0098 00152 (m.go:7) MOVQ AX, 8(SP) +0x009d 00157 (m.go:7) MOVQ $43, 16(SP) +0x00a6 00166 (m.go:7) PCDATA $0, $1 +0x00a6 00166 (m.go:7) CALL runtime.mapassign_fast64(SB) +0x00ab 00171 (m.go:7) MOVQ 24(SP), AX +0x00b0 00176 (m.go:7) MOVQ $1, (AX) +``` + +前面我们已经分析过调用函数的过程,这里前几行都是在准备 runtime.mapassign_fast64(SB) 的参数。去 runtime 里看看这个函数的签名: + +```go +func mapassign_fast64(t *maptype, h *hmap, key uint64) unsafe.Pointer { +``` + +不用看函数的实现我们也大概能推测出函数输入参数和输出参数的关系了,把入参和汇编指令对应的话: + +```go +t *maptype +=> +LEAQ type.map[int]int(SB), AX +MOVQ AX, (SP) + +h *hmap +=> +LEAQ ""..autotmp_2+232(SP), AX +MOVQ AX, 8(SP) + +key uint64 +=> +MOVQ $43, 16(SP) +``` + +返回参数就是 key 对应的可以写值的内存地址,拿到该地址后我们把想要写的值写进去就可以了: + +```go +MOVQ 24(SP), AX +MOVQ $1, (AX) +``` + +整个过程还挺复杂的,我们手抄一遍倒也可以实现。不过还要考虑,不同类型的 map,实际上需要执行的 runtime 中的 assign 函数是不同的,感兴趣的同学可以汇编本节的示例自行尝试。 + +整体来讲,用汇编来操作 map 并不是一个明智的选择。 + +#### channel + +channel 在 runtime 也是比较复杂的数据结构,如果在汇编层面操作,实际上也是调用 runtime 中 chan.go 中的函数,和 map 比较类似,这里就不展开说了。 + +### 获取 goroutine id + +Go 的 goroutine 是一个叫 g 的结构体,内部有自己的唯一 id,不过 runtime 没有把这个 id 暴露出来,但不知道为什么有很多人就是想把这个 id 得到。于是就有了各种或其 goroutine id 的库。 + +在 struct 一小节我们已经提到,结构体本身就是一段连续的内存,我们知道起始地址和字段的偏移量的话,很容易就可以把这段数据搬运出来: + +go_tls.h: + +```go +#ifdef GOARCH_arm +#define LR R14 +#endif + +#ifdef GOARCH_amd64 +#define get_tls(r) MOVQ TLS, r +#define g(r) 0(r)(TLS*1) +#endif + +#ifdef GOARCH_amd64p32 +#define get_tls(r) MOVL TLS, r +#define g(r) 0(r)(TLS*1) +#endif + +#ifdef GOARCH_386 +#define get_tls(r) MOVL TLS, r +#define g(r) 0(r)(TLS*1) +#endif +``` + +goid.go: + +```go +package goroutineid +import "runtime" +var offsetDict = map[string]int64{ + // ... 省略一些行 + "go1.7": 192, + "go1.7.1": 192, + "go1.7.2": 192, + "go1.7.3": 192, + "go1.7.4": 192, + "go1.7.5": 192, + "go1.7.6": 192, + // ... 省略一些行 +} + +var offset = offsetDict[runtime.Version()] + +// GetGoID returns the goroutine id +func GetGoID() int64 { + return getGoID(offset) +} + +func getGoID(off int64) int64 +``` + +goid.s: + +```go +#include "textflag.h" +#include "go_tls.h" + +// func getGoID() int64 +TEXT ·getGoID(SB), NOSPLIT, $0-16 + get_tls(CX) + MOVQ g(CX), AX + MOVQ offset(FP), BX + LEAQ 0(AX)(BX*1), DX + MOVQ (DX), AX + MOVQ AX, ret+8(FP) + RET +``` + +这样就实现了一个简单的获取 struct g 中的 goid 字段的小 library,作为玩具放在这里: +>https://github.com/cch123/goroutineid + +### SIMD + +[SIMD](https://cch123.gitbooks.io/duplicate/content/part3/performance/simd-instruction-class.html) 是 Single Instruction, Multiple Data 的缩写,在 Intel 平台上的 SIMD 指令集先后为 SSE,AVX,AVX2,AVX512,这些指令集引入了标准以外的指令,和宽度更大的寄存器,例如: + +- 128 位的 XMM0~XMM31 寄存器。 +- 256 位的 YMM0~YMM31 寄存器。 +- 512 位的 ZMM0~ZMM31 寄存器。 + +这些寄存器的关系,类似 RAX,EAX,AX 之间的关系。指令方面可以同时对多组数据进行移动或者计算,例如: + +- movups : 把4个不对准的单精度值传送到xmm寄存器或者内存 +- movaps : 把4个对准的单精度值传送到xmm寄存器或者内存 + +上述指令,当我们将数组作为函数的入参时有很大概率会看到,例如: + +arr_par.go: + +```go +package main + +import "fmt" + +func pr(input [3]int) { + fmt.Println(input) +} + +func main() { + pr([3]int{1, 2, 3}) +} +``` + +go compile -S: + +```go +0x001d 00029 (arr_par.go:10) MOVQ "".statictmp_0(SB), AX +0x0024 00036 (arr_par.go:10) MOVQ AX, (SP) +0x0028 00040 (arr_par.go:10) MOVUPS "".statictmp_0+8(SB), X0 +0x002f 00047 (arr_par.go:10) MOVUPS X0, 8(SP) +0x0034 00052 (arr_par.go:10) CALL "".pr(SB) +``` + +可见,编译器在某些情况下已经考虑到了性能问题,帮助我们使用 SIMD 指令集来对数据搬运进行了优化。 + +因为 SIMD 这个话题本身比较广,这里就不展开细说了。 + +## 特别感谢 + +研究过程基本碰到不太明白的都去骚扰卓巨巨了,就是这位 https://mzh.io/ 大大。特别感谢他,给了不少线索和提示。 + +## 参考资料 + +1. https://quasilyte.github.io/blog/post/go-asm-complementary-reference/#external-resources +2. http://davidwong.fr/goasm +3. https://www.doxsey.net/blog/go-and-assembly +4. https://github.com/golang/go/files/447163/GoFunctionsInAssembly.pdf +5. https://golang.org/doc/asm + +参考资料[4]需要特别注意,在该 slide 中给出的 callee stack frame 中把 caller 的 return address 也包含进去了,个人认为不是很合适。 + + diff --git a/site/content/docs/assembly/exercises.md b/site/content/docs/assembly/exercises.md new file mode 100644 index 0000000..3c16b05 --- /dev/null +++ b/site/content/docs/assembly/exercises.md @@ -0,0 +1,7 @@ +--- +title: 习题 +weight: 2 +draft: true +--- + +# 习题 diff --git a/site/content/docs/bootstrap/_index.md b/site/content/docs/bootstrap/_index.md new file mode 100644 index 0000000..3832726 --- /dev/null +++ b/site/content/docs/bootstrap/_index.md @@ -0,0 +1,7 @@ +--- +title: Go 进程的启动流程 +weight: 2 +bookCollapseSection: true +draft: true +--- + diff --git a/site/content/docs/bootstrap/boot.md b/site/content/docs/bootstrap/boot.md new file mode 100644 index 0000000..a8fe587 --- /dev/null +++ b/site/content/docs/bootstrap/boot.md @@ -0,0 +1,7 @@ +--- +title: 启动流程 +weight: 2 +--- +# 启动流程 + + diff --git a/site/content/docs/bootstrap/elf.md b/site/content/docs/bootstrap/elf.md new file mode 100644 index 0000000..15a78a7 --- /dev/null +++ b/site/content/docs/bootstrap/elf.md @@ -0,0 +1 @@ +# elf 文件简介 diff --git a/site/content/docs/bootstrap/exercises.md b/site/content/docs/bootstrap/exercises.md new file mode 100644 index 0000000..a49ba48 --- /dev/null +++ b/site/content/docs/bootstrap/exercises.md @@ -0,0 +1,2 @@ +--- +--- \ No newline at end of file diff --git a/site/content/docs/compiler_and_linker/_index.md b/site/content/docs/compiler_and_linker/_index.md new file mode 100644 index 0000000..ce63fe2 --- /dev/null +++ b/site/content/docs/compiler_and_linker/_index.md @@ -0,0 +1,6 @@ +--- +title: 编译器与链接器 +weight: 3 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/compiler_and_linker/calling_convention.md b/site/content/docs/compiler_and_linker/calling_convention.md new file mode 100644 index 0000000..e0609f0 --- /dev/null +++ b/site/content/docs/compiler_and_linker/calling_convention.md @@ -0,0 +1,25 @@ +--- +title: 调用规约 +weight: 3 +draft: true +--- + +# 调用规约 + +早期版本的 Go 在向函数传递参数时,是使用栈的。 + +从 1.17 开始,调用函数时会尽量使用寄存器传参。 + +"".add STEXT size=121 args=0x10 locals=0x18 funcid=0x0 + 0x0000 00000 (add.go:8) TEXT "".add(SB), ABIInternal, $24-16 + 0x0000 00000 (add.go:8) CMPQ SP, 16(R14) + 0x0004 00004 (add.go:8) JLS 94 + 0x0006 00006 (add.go:8) SUBQ $24, SP + 0x005d 00093 (add.go:11) RET + 0x005e 00094 (add.go:11) NOP + 0x005e 00094 (add.go:8) MOVQ AX, 8(SP) + 0x0063 00099 (add.go:8) MOVQ BX, 16(SP) + 0x0068 00104 (add.go:8) CALL runtime.morestack_noctxt(SB) + 0x006d 00109 (add.go:8) MOVQ 8(SP), AX + 0x0072 00114 (add.go:8) MOVQ 16(SP), BX + 0x0077 00119 (add.go:8) JMP 0 diff --git a/site/content/docs/compiler_and_linker/compiler.md b/site/content/docs/compiler_and_linker/compiler.md new file mode 100644 index 0000000..6592c8e --- /dev/null +++ b/site/content/docs/compiler_and_linker/compiler.md @@ -0,0 +1,6 @@ +--- +title: 编译器 +weight: 3 +draft: true +--- +# 编译器 diff --git a/site/content/docs/compiler_and_linker/linker.md b/site/content/docs/compiler_and_linker/linker.md new file mode 100644 index 0000000..ea2d801 --- /dev/null +++ b/site/content/docs/compiler_and_linker/linker.md @@ -0,0 +1,6 @@ +--- +title: 链接器 +weight: 3 +draft: true +--- +# linker diff --git a/site/content/docs/data_structure/_index.md b/site/content/docs/data_structure/_index.md new file mode 100644 index 0000000..08b7aa5 --- /dev/null +++ b/site/content/docs/data_structure/_index.md @@ -0,0 +1,5 @@ +--- +title: 内置数据结构 +weight: 10 +bookCollapseSection: true +--- diff --git a/site/content/docs/data_structure/channel.md b/site/content/docs/data_structure/channel.md new file mode 100644 index 0000000..da9c943 --- /dev/null +++ b/site/content/docs/data_structure/channel.md @@ -0,0 +1,10 @@ +--- +title: channel +weight: 10 +bookCollapseSection: false +--- +# channel 实现 + +{{}} + +{{}} diff --git a/site/content/docs/data_structure/context.md b/site/content/docs/data_structure/context.md new file mode 100644 index 0000000..ed1e832 --- /dev/null +++ b/site/content/docs/data_structure/context.md @@ -0,0 +1,7 @@ +--- +title: 内置数据结构 +weight: 10 +bookCollapseSection: true +draft: true +--- +# context 的实现 diff --git a/site/content/docs/data_structure/interface.md b/site/content/docs/data_structure/interface.md new file mode 100644 index 0000000..be9c333 --- /dev/null +++ b/site/content/docs/data_structure/interface.md @@ -0,0 +1,7 @@ +--- +title: 内置数据结构 +weight: 10 +bookCollapseSection: true +draft: true +--- +# interface 实现 diff --git a/site/content/docs/data_structure/map.md b/site/content/docs/data_structure/map.md new file mode 100644 index 0000000..61f68ea --- /dev/null +++ b/site/content/docs/data_structure/map.md @@ -0,0 +1,27 @@ +--- +title: map +weight: 10 +bookCollapseSection: false +--- + +# map 实现 + +![map struct](/images/runtime/data_struct/map.png) + +## map 元素定位过程 + +![top hash](/images/runtime/data_struct/map_tophash.png) + +## 特权函数 + +![func translate](/images/runtime/data_struct/map_function_translate.png) + +## 函数翻译 + +![func translate](/images/runtime/data_struct/map_func_translate2.png) + +## map 遍历过程 + +{{}} + +{{}} diff --git a/site/content/docs/data_structure/semaphore.md b/site/content/docs/data_structure/semaphore.md new file mode 100644 index 0000000..73af24b --- /dev/null +++ b/site/content/docs/data_structure/semaphore.md @@ -0,0 +1,9 @@ +--- +title: 内置数据结构 +weight: 10 +bookCollapseSection: true +draft: true +--- + +# 信号量的实现 + diff --git a/site/content/docs/data_structure/string.md b/site/content/docs/data_structure/string.md new file mode 100644 index 0000000..49eee42 --- /dev/null +++ b/site/content/docs/data_structure/string.md @@ -0,0 +1,7 @@ +--- +title: 内置数据结构 +weight: 10 +bookCollapseSection: true +draft: true +--- +# string 不可变字符串 diff --git a/site/content/docs/data_structure/timer.md b/site/content/docs/data_structure/timer.md new file mode 100644 index 0000000..907fa4e --- /dev/null +++ b/site/content/docs/data_structure/timer.md @@ -0,0 +1,6 @@ +--- +title: 内置数据结构 +weight: 10 +bookCollapseSection: true +draft: true +--- \ No newline at end of file diff --git a/site/content/docs/ddd/_index.md b/site/content/docs/ddd/_index.md new file mode 100644 index 0000000..e28e493 --- /dev/null +++ b/site/content/docs/ddd/_index.md @@ -0,0 +1,6 @@ +--- +title: 领域驱动设计 +weight: 2 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/debug/_index.md b/site/content/docs/debug/_index.md new file mode 100644 index 0000000..a3feaba --- /dev/null +++ b/site/content/docs/debug/_index.md @@ -0,0 +1,6 @@ +--- +title: 调试工具 +weight: 5 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/debug/dlv_tutorial.md b/site/content/docs/debug/dlv_tutorial.md new file mode 100644 index 0000000..ae66d9d --- /dev/null +++ b/site/content/docs/debug/dlv_tutorial.md @@ -0,0 +1 @@ +# dlv tutorial diff --git a/site/content/docs/debug/ssa_debug.md b/site/content/docs/debug/ssa_debug.md new file mode 100644 index 0000000..3e5bba3 --- /dev/null +++ b/site/content/docs/debug/ssa_debug.md @@ -0,0 +1 @@ +# debug ssa func diff --git a/site/content/docs/design_patterns/_index.md b/site/content/docs/design_patterns/_index.md new file mode 100644 index 0000000..b45eae5 --- /dev/null +++ b/site/content/docs/design_patterns/_index.md @@ -0,0 +1,6 @@ +--- +title: 设计模式 +weight: 6 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/design_patterns/decorator.md b/site/content/docs/design_patterns/decorator.md new file mode 100644 index 0000000..7fad81a --- /dev/null +++ b/site/content/docs/design_patterns/decorator.md @@ -0,0 +1 @@ +# 装饰器模式 diff --git a/site/content/docs/optimization/_index.md b/site/content/docs/optimization/_index.md new file mode 100644 index 0000000..ff520c9 --- /dev/null +++ b/site/content/docs/optimization/_index.md @@ -0,0 +1,6 @@ +--- +title: 性能优化 +weight: 8 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/optimization/benchmark.md b/site/content/docs/optimization/benchmark.md new file mode 100644 index 0000000..58abd58 --- /dev/null +++ b/site/content/docs/optimization/benchmark.md @@ -0,0 +1 @@ +# benchmark 入门 diff --git a/site/content/docs/optimization/continuous_profiling.md b/site/content/docs/optimization/continuous_profiling.md new file mode 100644 index 0000000..ef9e56f --- /dev/null +++ b/site/content/docs/optimization/continuous_profiling.md @@ -0,0 +1 @@ +# continuous profiling diff --git a/site/content/docs/optimization/optimizations.md b/site/content/docs/optimization/optimizations.md new file mode 100644 index 0000000..c6ae860 --- /dev/null +++ b/site/content/docs/optimization/optimizations.md @@ -0,0 +1 @@ +# 性能优化 diff --git a/site/content/docs/optimization/pprof_tutorial.md b/site/content/docs/optimization/pprof_tutorial.md new file mode 100644 index 0000000..43a898b --- /dev/null +++ b/site/content/docs/optimization/pprof_tutorial.md @@ -0,0 +1 @@ +# pprof 指南 diff --git a/site/content/docs/quality/_index.md b/site/content/docs/quality/_index.md new file mode 100644 index 0000000..d6f49c9 --- /dev/null +++ b/site/content/docs/quality/_index.md @@ -0,0 +1,5 @@ +--- +title: 工程质量管控 +weight: 20 +bookCollapseSection: true +--- diff --git a/site/content/docs/quality/auto_review.md b/site/content/docs/quality/auto_review.md new file mode 100644 index 0000000..83193f6 --- /dev/null +++ b/site/content/docs/quality/auto_review.md @@ -0,0 +1,9 @@ +--- +title: 自动化 Code Review +weight: 1 +draft: true +--- + +# 自动化 Code Review + +## reviewdog diff --git a/site/content/docs/quality/custom_linter.md b/site/content/docs/quality/custom_linter.md new file mode 100644 index 0000000..7bd48f9 --- /dev/null +++ b/site/content/docs/quality/custom_linter.md @@ -0,0 +1,5 @@ +--- +title: 定制 linter +weight: 1 +draft: true +--- \ No newline at end of file diff --git a/site/content/docs/quality/performance.md b/site/content/docs/quality/performance.md new file mode 100644 index 0000000..7d7e022 --- /dev/null +++ b/site/content/docs/quality/performance.md @@ -0,0 +1,360 @@ +## 为什么要做优化 + +这是一个速度决定一切的年代,只要我们的生活还在继续数字化,线下的流程与系统就在持续向线上转移,在这个转移过程中,我们会碰到持续的性能问题。 + +互联网公司本质是将用户共通的行为流程进行了集中化管理,通过中心化的信息交换达到效率提升的目的,同时用规模效应降低了数据交换的成本。 + +用人话来讲,公司希望的是用尽量少的机器成本来赚取尽量多的利润。利润的提升与业务逻辑本身相关,与技术关系不大。而降低成本则是与业务无关,纯粹的技术话题。这里面最重要的主题就是“性能优化”。 + +如果业务的后端服务规模足够大,那么一个程序员通过优化帮公司节省的成本,或许就可以负担他十年的工资了。 + +## 优化的前置知识 + +从资源视角出发来对一台服务器进行审视的话,CPU、内存、磁盘与网络是后端服务最需要关注的四种资源类型。 + +对于计算密集型的程序来说,优化的主要精力会放在 CPU 上,要知道 CPU 基本的流水线概念,知道怎么样在使用少的 CPU 资源的情况下,达到相同的计算目标。 + +对于 IO 密集型的程序(后端服务一般都是 IO 密集型)来说,优化可以是降低程序的服务延迟,也可以是提升系统整体的吞吐量。 + +IO 密集型应用主要与磁盘、内存、网络打交道。因此我们需要知道一些基本的与磁盘、内存、网络相关的基本数据与常见概念: + +- 要了解内存的多级存储结构:L1,L2,L3,主存。还要知道这些不同层级的存储操作时的大致延迟:[latency numbers every programmer should know](https://colin-scott.github.io/personal_website/research/interactive_latency.html)。 +- 要知道基本的文件系统读写 syscall,批量 syscall,数据同步 syscall。 +- 要熟悉项目中使用的网络协议,至少要对 TCP, HTTP 有所了解。 + +## 优化越靠近应用层效果越好 + +> Performance tuning is most effective when done closest to where the work is performed. For workloads driven by applications, this means within the application itself. + +我们在应用层的逻辑优化能够帮助应用提升几十倍的性能,而最底层的优化可能也就只能提升几个百分点了。 + +这个很好理解,我们可以看到一个 GTA Online 的新闻:[rockstar thanks gta online player who fixed poor load times](https://www.pcgamer.com/rockstar-thanks-gta-online-player-who-fixed-poor-load-times-official-update-coming/)。 + +简单来说,GTA online 的游戏启动过程让玩家等待时间过于漫长,经过各种工具分析,发现一个 10M 的文件加载就需要几十秒,用户 diy 进行优化之后,将加载时间减少 70%,并分享出来:[how I cut GTA Online loading times by 70%](https://nee.lv/2021/02/28/How-I-cut-GTA-Online-loading-times-by-70/)。 + +这就是一个非常典型的案例,GTA 在商业上取得了巨大的成功,但不妨碍它局部的代码是一坨屎。我们只要把这里的重复逻辑干掉,就可以完成三倍的优化效果。同样的案例,如果我们去优化磁盘的读写速度,则可能收效甚微。 + +## 优化是与业务场景相关的 + +不同的业务场景优化的侧重也是不同的。 + +对于大多数无状态业务模块来说,内存一般不是瓶颈,所以业务 API 的优化主要聚焦于延迟和吞吐。对于网关类的应用,因为有海量的连接,除了延迟和吞吐,内存占用可能就会成为一个关注的重点。对于存储类应用,内存是个逃不掉的瓶颈点。 + +在关注一些性能优化文章时,我们也应特别留意作者的业务场景。场景的侧重可能会让某些人去选择使用更为 hack 的手段进行优化,而 hack 往往也就意味着 bug。如果你选择了少有人走过的路,那你未来要面临的也是少有人会碰到的 bug。解决起来令人头疼。 + +## 优化的工作流程 + +对于一个典型的 API 应用来说,优化工作基本遵从下面的工作流: + +1. 建立评估指标,例如固定 QPS 压力下的延迟或内存占用,或模块在满足 SLA 前提下的极限 QPS +2. 通过自研、开源压测工具进行压测,直到模块无法满足预设性能要求:如大量超时,QPS 不达预期,OOM +3. 通过内置 profile 工具寻找性能瓶颈 +4. 本地 benchmark 证明优化效果 +5. 集成 patch 到业务模块,回到 2 + +## 可以使用的工具 + +### pprof + +#### memory profiler + +Go 内置的内存 profiler 可以让我们对线上系统进行内存使用采样,有四个相应的指标: + +- inuse\_objects:当我们认为内存中的驻留对象过多时,就会关注该指标 +- inuse\_space:当我们认为应用程序占据的 RSS 过大时,会关注该指标 +- alloc\_objects:当应用曾经发生过历史上的大量内存分配行为导致 CPU 或内存使用大幅上升时,可能关注该指标 +- alloc\_space:当应用历史上发生过内存使用大量上升时,会关注该指标 + +网关类应用因为海量连接的关系,会导致进程消耗大量内存,所以我们经常看到相关的优化文章,主要就是降低应用的 inuse\_space。 + +而两个对象数指标主要是为 GC 优化提供依据,当我们进行 GC 调优时,会同时关注应用分配的对象数、正在使用的对象数,以及 GC 的 CPU 占用的指标。 + +GC 的 CPU 占用情况可以由内置的 CPU profiler 得到。 + +#### cpu profiler + +> The builtin Go CPU profiler uses the setitimer(2) system call to ask the operating system to be sent a SIGPROF signal 100 times a second. Each signal stops the Go process and gets delivered to a random thread’s sigtrampgo() function. This function then proceeds to call sigprof() or sigprofNonGo() to record the thread’s current stack. + +Go 语言内置的 CPU profiler 使用 setitimer 系统调用,操作系统会每秒 100 次向程序发送 SIGPROF 信号。在 Go 进程中会选择随机的信号执行 sigtrampgo 函数。该函数使用 sigprof 或 sigprofNonGo 来记录线程当前的栈。 + +> Since Go uses non-blocking I/O, Goroutines that wait on I/O are parked and not running on any threads. Therefore they end up being largely invisible to Go’s builtin CPU profiler. + +Go 语言内置的 cpu profiler 是在性能领域比较常见的 On-CPU profiler,对于瓶颈主要在 CPU 消耗的应用,我们使用内置的 profiler 也就足够了。 + +如果我们碰到的问题是应用的 CPU 使用不高,但接口的延迟却很大,那么就需要用上 Off-CPU profiler,遗憾的是官方的 profiler 并未提供该功能,我们需要借助社区的 fgprof。 + +### fgprof + +> fgprof is implemented as a background goroutine that wakes up 99 times per second and calls runtime.GoroutineProfile. This returns a list of all goroutines regardless of their current On/Off CPU scheduling status and their call stacks. + +fgprof 是启动了一个后台的 goroutine,每秒启动 99 次,调用 runtime.GoroutineProfile 来采集所有 gorooutine 的栈。 + +虽然看起来很美好: + +``` +func GoroutineProfile(p []StackRecord) (n int, ok bool) { + ..... +stopTheWorld("profile") + +for _, gp1 := range allgs { +...... +} + +if n <= len(p) { +// Save current goroutine. +........ +systemstack(func() { +saveg(pc, sp, gp, &r[0]) +}) + +// Save other goroutines. +for _, gp1 := range allgs { +if isOK(gp1) { +....... +saveg(^uintptr(0), ^uintptr(0), gp1, &r[0]) + ....... +} +} +} + +startTheWorld() + +return n, ok +} +``` + +但调用 GoroutineProfile 函数的开销并不低,如果线上系统的 goroutine 上万,每次采集 profile 都遍历上万个 goroutine 的成本实在是太高了。所以 fgprof 只适合在测试环境中使用。 + +### trace + +一般情况下我们是不需要使用 trace 来定位性能问题的,通过压测 + profile 就可以解决大部分问题,除非我们的问题与 runtime 本身的问题相关。 + +比如 STW 时间比预想中长,超过百毫秒,向官方反馈问题时,才需要出具相关的 trace 文件。比如类似 [long stw](https://github.com/golang/go/issues/19378) 这样的 issue。 + +采集 trace 对系统的性能影响还是比较大的,即使我们只是开启 gctrace,把 gctrace 日志重定向到文件,对系统延迟也会有一定影响,因为 gctrace 的 print 是在 stw 期间来做的:[gc trace 阻塞调度](http://xiaorui.cc/archives/6232)。 + +### perf + +如果应用没有开启 pprof,在线上应急时,我们也可以临时使用 perf: + +![perf demo](https://cch123.github.io/perf_opt/perf.png) + +## 微观性能优化 + +在编写 library 时,我们会关注关键的函数性能,这时可以脱离系统去探讨性能优化,Go 语言的 test 子命令集成了相关的功能,只要我们按照约定来写 Benchmark 前缀的测试函数,就可以实现函数级的基准测试。我们以常见的二维数组遍历为例: + +``` +package main + +import "testing" + +var x = make([][]int, 100) + +func init() { + for i := 0; i < 100; i++ { + x[i] = make([]int, 100) + } +} + +func traverseVertical() { + for i := 0; i < 100; i++ { + for j := 0; j < 100; j++ { + x[j][i] = 1 + } + } +} + +func traverseHorizontal() { + for i := 0; i < 100; i++ { + for j := 0; j < 100; j++ { + x[i][j] = 1 + } + } +} + +func BenchmarkHorizontal(b *testing.B) { + for i := 0; i < b.N; i++ { + traverseHorizontal() + } +} + +func BenchmarkVertical(b *testing.B) { + for i := 0; i < b.N; i++ { + traverseVertical() + } +} + +``` + +执行 `go test -bench=.` + +``` +BenchmarkHorizontal-12 102368 10916 ns/op +BenchmarkVertical-12 66612 18197 ns/op +``` + +可见横向遍历数组要快得多,这提醒我们在写代码时要考虑 CPU 的 cache 设计及局部性原理,以使程序能够在相同的逻辑下获得更好的性能。 + +除了 CPU 优化,我们还经常会碰到要优化内存分配的场景。只要带上 -benchmem 的 flag 就可以实现了。 + +举个例子,形如下面这样的代码: + +``` +logStr := "userid :" + userID + "; orderid:" + orderID +``` + +你觉得代码写的很难看,想要优化一下可读性,就改成了下列代码: + +``` +logStr := fmt.Sprintf("userid: %v; orderid: %v", userID, orderID) +``` + +这样的修改方式在某公司的系统中曾经导致了 p2 事故,上线后接口的超时俱增至 SLA 承诺以上。 + +我们简单验证就可以发现: + +``` +BenchmarkPrint-12 7168467 157 ns/op 64 B/op 3 allocs/op +BenchmarkPlus-12 43278558 26.7 ns/op 0 B/op 0 allocs/op +``` + +使用 + 进行字符串拼接,不会在堆上产生额外对象。而使用 fmt 系列函数,则会造成局部对象逃逸到堆上,这里是高频路径上有大量逃逸,所以导致线上服务的 GC 压力加重,大量接口超时。 + +出于谨慎考虑,修改高并发接口时,拿不准的尽量都应进行简单的线下 benchmark 测试。 + +当然,我们不能指望靠写一大堆 benchmark 帮我们发现系统的瓶颈。 + +实际工作中还是要使用前文提到的优化工作流来进行系统性能优化。也就是尽量从接口整体而非函数局部考虑去发现与解决瓶颈。 + +## 宏观性能优化 + +接口类的服务,我们可以使用两种方式对其进行压测: + +- 固定 QPS 压测:在每次系统有大的特性发布时,都应进行固定 QPS 压测,与历史版本进行对比,需要关注的指标包括,相同 QPS 下的系统的 CPU 使用情况,内存占用情况(监控中的 RSS 值),goroutine 数,GC 触发频率和相关指标(是否有较长的 stw,mark 阶段是否时间较长等),平均延迟,p99 延迟。 +- 极限 QPS 压测:极限 QPS 压测一般只是为了 benchmark show,没有太大意义。系统满负荷时,基本 p99 已经超出正常用户的忍受范围了。 + +压测过程中需要采集不同 QPS 下的 CPU profile,内存 profile,记录 goroutine 数。与历史情况进行 AB 对比。 + +Go 的 pprof 还提供了 --base 的 flag,能够很直观地帮我们发现不同版本之间的指标差异:[用 pprof 比较内存使用差异](https://colobu.com/2019/08/20/use-pprof-to-compare-go-memory-usage/)。 + +总之记住一点,接口的性能一定是通过压测来进行优化的,而不是通过硬啃代码找瓶颈点。关键路径的简单修改往往可以带来巨大收益。如果只是啃代码,很有可能将 1% 优化到 0%,优化了 100% 的局部性能,对接口整体影响微乎其微。 + +## 寻找性能瓶颈 + +在压测时,我们通过以下步骤来逐渐提升接口的整体性能: + +1. 使用固定 QPS 压测,以阶梯形式逐渐增加压测 QPS,如 1000 -> 每分钟增加 1000 QPS +2. 压测过程中观察系统的延迟是否异常 +3. 观察系统的 CPU 使用情况 +4. 如果 CPU 使用率在达到一定值之后不再上升,反而引起了延迟的剧烈波动,这时大概率是发生了阻塞,进入 pprof 的 web 页面,点击 goroutine,查看 top 的 goroutine 数,这时应该有大量的 goroutine 阻塞在某处,比如 Semacquire +5. 如果 CPU 上升较快,未达到预期吞吐就已经过了高水位,则可以重点考察 CPU 使用是否合理,在 CPU 高水位进行 profile 采样,重点关注火焰图中较宽的“平顶山” + +## 一些优化案例 + +### gc mark 占用过多 CPU + +在 Go 语言中 gc mark 占用的 CPU 主要和运行时的对象数相关,也就是我们需要看 inuse\_objects。 + +定时任务,或访问流量不规律的应用,需要关注 alloc\_objects。 + +优化主要是下面几方面: + +#### 减少变量逃逸 + +尽量在栈上分配对象,关于逃逸的规则,可以查看 Go 编译器代码中的逃逸测试部分: + +![Pasted-Graphic](http://xargin.com/content/images/2021/03/Pasted-Graphic.png) + +查看某个 package 内的逃逸情况,可以使用 build + 全路径的方式,如: + +`go build -gcflags="-m -m" github.com/cch123/elasticsql` + +需要注意的是,逃逸分析的结果是会**随着版本变化**的,所以去背诵网上逃逸相关的文章结论是没有什么意义的。 + +#### 使用 sync.Pool 复用堆上对象 + +sync.Pool 用出花儿的就是 fasthttp 了,可以看看我之前写的这一篇:[fasthttp 为什么快](http://xargin.com/why-fasthttp-is-fast-and-the-cost-of-it/)。 + +最简单的复用就是复用各种 struct,slice,在复用时 put 时,需要 size 是否已经扩容过头,小心因为 sync.Pool 中存了大量的巨型对象导致进程占用了大量内存。 + +#### 修改 GOGC + +当前有 memory ballast 和动态 GOGC 两种方案: +1. [memory ballast](https://blog.twitch.tv/en/2019/04/10/go-memory-ballast-how-i-learnt-to-stop-worrying-and-love-the-heap/) +2. [GOGCTuner](https://github.com/cch123/gogctuner) + +后者可以根据 gc cycle 动态调整 GOGC,使应用占用的内存水位始终保持在 70%,既不 OOM,又能合理利用内存空间来降低 GC 触发频率。 + +### 调度占用过多 CPU + +goroutine 频繁创建与销毁会给调度造成较大的负担,如果我们发现 CPU 火焰图中 schedule,findrunnable 占用了大量 CPU,那么可以考虑使用开源的 workerpool 来进行改进,比较典型的 [fasthttp worker pool](https://github.com/valyala/fasthttp/blob/master/workerpool.go#L19)。 + +如果客户端与服务端之间使用的是短连接,那么我们可以使用长连接。 + +### 进程占用大量内存 + +当前大多数的业务后端服务是不太需要关注进程消耗的内存的。 + +我们经常看到做 Go 内存占用优化的是在网关(包括 mesh)、存储系统这两个场景。 + +对于网关类系统来说,Go 的内存占用主要是因为 Go 独特的抽象模型造成的,这个很好理解: + +![Pasted-Graphic-1](http://xargin.com/content/images/2021/03/Pasted-Graphic-1.png) + +海量的连接加上海量的 goroutine,使网关和 mesh 成为 Go OOM 的重灾区。所以网关侧的优化一般就是优化: + +- goroutine 占用的栈内存 +- read buffer 和 write buffer 占用的内存 + +很多项目都有相关的分享,这里就不再赘述了。 + +对于存储类系统来说,内存占用方面的努力也是在优化 buffer,比如 dgraph 使用 cgo + jemalloc 来优化他们的产品[内存占用](https://dgraph.io/blog/post/manual-memory-management-golang-jemalloc/)。 + +堆外内存不会在 Go 的 GC 系统里进行管辖,所以也不会影响到 Go 的 GC Heap Goal,所以也不会像 Go 这样内存占用难以控制。 + +### 锁冲突严重,导致吞吐量瓶颈 + +我在 [几个 Go 系统可能遇到的锁问题](http://xargin.com/lock-contention-in-go/) 中分享过实际的线上 case。 + +进行锁优化的思路无非就一个“拆”和一个“缩”字: + +- 拆:将锁粒度进行拆分,比如全局锁,我能不能把锁粒度拆分为连接粒度的锁;如果是连接粒度的锁,那我能不能拆分为请求粒度的锁;在 logger fd 或 net fd 上加的锁不太好拆,那么我们增加一些客户端,比如从 1-> 100,降低锁的冲突是不是就可以了。 +- 缩:缩小锁的临界区,比如业务允许的前提下,可以把 syscall 移到锁外面;比如我们只是想要锁 map,但是却不小心锁了连接读写的逻辑,或许简单地用 sync.Map 来代替 map Lock,defer Unlock 就能简单地缩小临界区了。 + +### timer 相关函数占用大量 CPU + +同样是在某些网关应用中较常见,优化方法手段: + +- 使用时间轮/粗粒度的时间管理,精确到 ms 级一般就足够了 +- 升级到 Go 1.14+,享受官方的升级红利 + +## 模拟真实工作负载 + +在前面的论述中,我们对问题进行了简化。真实世界中的后端系统往往不只一个接口,压测工具、平台往往只支持单接口压测。 + +公司的业务希望知道的是某个后端系统最终能支持多少业务量,例如系统整体能承载多少发单量而不会在重点环节出现崩溃。 + +虽然大家都在讲微服务,但单一服务往往也不只有单一功能,如果一个系统有 10 个接口(已经算是很小的服务了),那么这个服务的真实负载是很难靠人肉去模拟的。 + +这也就是为什么互联网公司普遍都需要做全链路压测。像样点的公司都会定期进行全链路压测演练,以便知晓随着系统快速迭代变化,系统整体是否出现了严重的性能衰退。 + +通过真实的工作负载,我们才能发现真实的线上性能问题。讲全链路压测的文章也很多,本文就不再赘述了。 + +## 当前性能问题定位工具的局限性 + +本文中几乎所有优化手段都是通过 Benchmark 和压测来进行的,但真实世界的软件会有下列场景: + +- 做 ToB 生意,我们的应用是部署在客户侧(比如一些数据库产品),客户说我们的应用会 OOM,但是我们很难拿到 OOM 的现场,不知道到底是哪些对象分配导致了 OOM +- 做大型平台,平台上有各种不同类型的用户编写代码,升级用户代码后,线上出现各种 CPU 毛刺和 OOM 问题 + +这些问题在压测中是发现不了的,需要有更为灵活的工具和更为强大的平台,关于这些问题,我将在 4 月 10 日的武汉 Gopher Meetup 上进行分享,欢迎关注。 + +参考资料: + +[cache contention](https://web.eecs.umich.edu/~zmao/Papers/xu10mar.pdf) + +[every-programmer-should-know](https://github.com/mtdvio/every-programmer-should-know) + +[go-perfbook](https://github.com/dgryski/go-perfbook) + +[Systems Performance](https://www.amazon.com/Systems-Performance-Brendan-Gregg/dp/0136820158/ref=sr_1_1?dchild=1&keywords=systems+performance&qid=1617092159&sr=8-1) diff --git a/site/content/docs/quality/refactoring.md b/site/content/docs/quality/refactoring.md new file mode 100644 index 0000000..d556488 --- /dev/null +++ b/site/content/docs/quality/refactoring.md @@ -0,0 +1,5 @@ +--- +title: 整洁代码 +weight: 1 +draft: true +--- diff --git a/site/content/docs/quality/static_analysis.md b/site/content/docs/quality/static_analysis.md new file mode 100644 index 0000000..21c2184 --- /dev/null +++ b/site/content/docs/quality/static_analysis.md @@ -0,0 +1,277 @@ +--- +title: 静态分析 +weight: 1 +--- + +# 静态分析 + +静态分析是通过扫描并解析用户代码,寻找代码中的潜在 bug 的一种手段。 + +静态分析一般会集成在项目上线的 CI 流程中,如果分析过程找到了 bug,会直接阻断上线,避免有问题的代码被部署到线上系统。从而在部署早期发现并修正潜在的问题。 + +## 社区常见 linter + +时至今日,社区已经有了丰富的 linter 资源供我们使用,本文会挑出一些常见 linter 进行说明。 + +### go lint + +go lint 是官方出的 linter,是 Go 语言最早期的 linter 了,其可以检查: + +* 导出函数是否有注释 +* 变量、函数、包命名不符合 Go 规范,有下划线 +* receiver 命名是否不符合规范 + +但这几年社区的 linter 蓬勃发展,所以这个项目也被官方 deprecated 掉了。其主要功能被另外一个 linter:revive[^1] 完全继承了。 + +### go vet + +go vet 也是官方提供的静态分析工具,其内置了锁拷贝检查、循环变量捕获问题、printf 参数不匹配等工具。 + +比如新手老手都很容易犯的 loop capture 错误: + +```go +package main + +func main() { + var a = map[int]int {1 : 1, 2: 3} + var b = map[int]*int{} + for k, r := range a { + go func() { + b[k] = &r + }() + } +} +``` + +go vet 会直接把你骂醒: + +```shell +~/test git:master ❯❯❯ go vet ./clo.go +# command-line-arguments +./clo.go:8:6: loop variable k captured by func literal +./clo.go:8:12: loop variable r captured by func literal +``` + +执行 go tool vet help 可以看到 go vet 已经内置的一些 linter。 + +```shell +~ ❯❯❯ go tool vet help +vet is a tool for static analysis of Go programs. + +vet examines Go source code and reports suspicious constructs, +such as Printf calls whose arguments do not align with the format +string. It uses heuristics that do not guarantee all reports are +genuine problems, but it can find errors not caught by the compilers. + +Registered analyzers: + + asmdecl report mismatches between assembly files and Go declarations + assign check for useless assignments + atomic check for common mistakes using the sync/atomic package + bools check for common mistakes involving boolean operators + buildtag check that +build tags are well-formed and correctly located + cgocall detect some violations of the cgo pointer passing rules + composites check for unkeyed composite literals + copylocks check for locks erroneously passed by value + errorsas report passing non-pointer or non-error values to errors.As + httpresponse check for mistakes using HTTP responses + loopclosure check references to loop variables from within nested functions + lostcancel check cancel func returned by context.WithCancel is called + nilfunc check for useless comparisons between functions and nil + printf check consistency of Printf format strings and arguments + shift check for shifts that equal or exceed the width of the integer + stdmethods check signature of methods of well-known interfaces + structtag check that struct field tags conform to reflect.StructTag.Get + tests check for common mistaken usages of tests and examples + unmarshal report passing non-pointer or non-interface values to unmarshal + unreachable check for unreachable code + unsafeptr check for invalid conversions of uintptr to unsafe.Pointer + unusedresult check for unused results of calls to some functions +``` + +默认情况下这些 linter 都是会跑的,当前很多 IDE 在代码修改时会自动执行 go vet,所以我们在写代码的时候一般就能发现这些错了。 + +但 `go vet` 还是应该集成到线上流程中,因为有些程序员的下限实在太低。 + +### errcheck + +Go 语言中的大多数函数返回字段中都是有 error 的: + +```go +func sayhello(wr http.ResponseWriter, r *http.Request) { + io.WriteString(wr, "hello") +} + +func main() { + http.HandleFunc("/", sayhello) + http.ListenAndServe(":1314", nil) // 这里返回的 err 没有处理 +} +``` + +这个例子中,我们没有处理 `http.ListenAndServe` 函数返回的 error 信息,这会导致我们的程序在启动时发生静默失败。 + +程序员往往会基于过往经验,对当前的场景产生过度自信,从而忽略掉一些常见函数的返回错误,这样的编程习惯经常为我们带来意外的线上事故。例如,规矩的写法是下面这样的: + +```go +data, err := getDataFromRPC() +if err != nil { + return nil, err +} + +// do business logic +age := data.age +``` + +而自信的程序员可能会写成这样: + +```go +data, _ := getDataFromRPC() + +// do business logic +age := data.age +``` + +如果底层 RPC 逻辑出错,上层的 data 是个空指针也是很正常的,如果底层函数返回的 err 非空时,我们不应该对其它字段做任何的假设。这里 data 完全有可能是个空指针,造成用户程序 panic。 + +errcheck 会强制我们在代码中检查并处理 err。 + +### gocyclo + +gocyclo 主要用来检查函数的圈复杂度。圈复杂度可以参考下面的定义: + +> 圈复杂度(Cyclomatic complexity)是一种代码复杂度的衡量标准,在 1976 年由 Thomas J. McCabe, Sr. 提出。在软件测试的概念里,圈复杂度用来衡量一个模块判定结构的复杂程度,数量上表现为线性无关的路径条数,即合理的预防错误所需测试的最少路径条数。圈复杂度大说明程序代码可能质量低且难于测试和维护,根据经验,程序的可能错误和高的圈复杂度有着很大关系。 + +看定义较为复杂但计算还是比较简单的,我们可以认为: + +* 一个 if,那么函数的圈复杂度要 + 1 +* 一个 switch 的 case,函数的圈复杂度要 + 1 +* 一个 for 循环,圈复杂度 + 1 +* 一个 && 或 ||,圈复杂度 + 1 + +在大多数语言中,若函数的圈复杂度超过了 10,那么我们就认为该函数较为复杂,需要做拆解或重构。部分场景可以使用表驱动的方式进行重构。 + +由于在 Go 语言中,我们使用 `if err != nil` 来处理错误,所以在一个函数中出现多个 `if err != nil` 是比较正常的,因此 Go 中函数复杂度的阈值可以稍微调高一些,15 是较为合适的值。 + +下面是在个人项目 elasticsql 中执行 gocyclo 的结果,输出 top 10 复杂的函数: + +```shell +~/g/s/g/c/elasticsql git:master ❯❯❯ gocyclo -top 10 ./ +23 elasticsql handleSelectWhere select_handler.go:289:1 +16 elasticsql handleSelectWhereComparisonExpr select_handler.go:220:1 +16 elasticsql handleSelect select_handler.go:11:1 +9 elasticsql handleGroupByFuncExprDateHisto select_agg_handler.go:82:1 +9 elasticsql handleGroupByFuncExprDateRange select_agg_handler.go:154:1 +8 elasticsql buildComparisonExprRightStr select_handler.go:188:1 +7 elasticsql TestSupported select_test.go:80:1 +7 elasticsql Convert main.go:28:1 +7 elasticsql handleGroupByFuncExpr select_agg_handler.go:215:1 +6 elasticsql handleSelectWhereOrExpr select_handler.go:157:1 +``` + +### bodyclose + +使用 bodyclose[^2] 可以帮我们检查在使用 HTTP 标准库时忘记关闭 http body 导致连接一直被占用的问题。 + +```go +resp, err := http.Get("http://example.com/") // Wrong case +if err != nil { + // handle error +} +body, err := ioutil.ReadAll(resp.Body) +``` + +像上面这样的例子是不对的,使用标准库很容易犯这样的错。bodyclose 可以直接检查出这个问题: + +```shell +# command-line-arguments +./httpclient.go:10:23: response body must be closed +``` + +所以必须要把 Body 关闭: + +```go +resp, err := http.Get("http://example.com/") +if err != nil { + // handle error +} +defer resp.Body.Close() // OK +body, err := ioutil.ReadAll(resp.Body) +``` + +HTTP 标准库的 API 设计的不太好,这个问题更好的避免方法是公司内部将 HTTP client 封装为 SDK,防止用户写出这样不 Close HTTP body 的代码。 + +### sqlrows + +与 HTTP 库设计类似,我们在面向数据库编程时,也会碰到 sql.Rows 忘记关闭的问题,导致连接大量被占用。sqlrows[^3] 这个 linter 能帮我们避免这个问题,先来看看错误的写法: + +```go +rows, err := db.QueryContext(ctx, "SELECT * FROM users") +if err != nil { + return nil, err +} + +for rows.Next() { + err = rows.Scan(...) + if err != nil { + return nil, err // NG: this return will not release a connection. + } +} +``` + +正确的写法需要在使用完后关闭 sql.Rows: + +```go +rows, err := db.QueryContext(ctx, "SELECT * FROM users") +if err != nil { + return nil, err +} +defer rows.Close() +``` + +与 HTTP 同理,公司内也应该将 DB 查询封装为合理的 SDK,不要让业务使用标准库中的 API,避免上述错误发生。 + +### funlen + +funlen[^4] 和 gocyclo 类似,但是这两个 linter 对代码复杂度的视角不太相同,gocyclo 更多关注函数中的逻辑分支,而 funlen 则重点关注函数的长度。默认函数超过 60 行和 40 条语句时,该 linter 即会报警。 + +## linter 集成工具 + +一个一个去社区里找 linter 来拼搭效率太低,当前社区里已经有了较好的集成工具,早期是 gometalinter,后来性能更好,功能更全的 golangci-lint 逐渐取而代之。目前 golangci-lint 是 Go 社区的绝对主流 linter。 + +### golangci-lint + +golangci-lint[^5] 能够通过配置来 enable 很多 linter,基本主流的都包含在内了。 + +在本节开头讲到的所有 linter 都可以在 golangci-lint 中进行配置, + +使用也较为简单,只要在项目目录执行 golangci-lint run . 即可。 + +```shell +~/g/s/g/c/elasticsql git:master ❯❯❯ golangci-lint run . +main.go:36:9: S1034: assigning the result of this type assertion to a variable (switch stmt := stmt.(type)) could eliminate type assertions in switch cases (gosimple) + switch stmt.(type) { + ^ +main.go:38:34: S1034(related information): could eliminate this type assertion (gosimple) + dsl, table, err = handleSelect(stmt.(*sqlparser.Select)) + ^ +main.go:40:23: S1034(related information): could eliminate this type assertion (gosimple) + return handleUpdate(stmt.(*sqlparser.Update)) + ^ +main.go:42:23: S1034(related information): could eliminate this type assertion (gosimple) + return handleInsert(stmt.(*sqlparser.Insert)) + ^ +select_handler.go:192:9: S1034: assigning the result of this type assertion to a variable (switch expr := expr.(type)) could eliminate type assertions in switch cases (gosimple) + switch expr.(type) { +``` + +## 参考资料 + +[^1]:https://revive.run/ + +[^2]:https://github.com/timakin/bodyclose + +[^3]:https://github.com/gostaticanalysis/sqlrows + +[^4]:https://github.com/ultraware/funlen + +[^5]:https://github.com/golangci/golangci-lint diff --git a/site/content/docs/runtime/_index.md b/site/content/docs/runtime/_index.md new file mode 100644 index 0000000..308963f --- /dev/null +++ b/site/content/docs/runtime/_index.md @@ -0,0 +1,5 @@ +--- +title: 运行时 +weight: 2 +bookCollapseSection: true +--- diff --git a/site/content/docs/runtime/memory_management/_index.md b/site/content/docs/runtime/memory_management/_index.md new file mode 100644 index 0000000..0b705e3 --- /dev/null +++ b/site/content/docs/runtime/memory_management/_index.md @@ -0,0 +1,4 @@ +--- +title: 内存管理 +weight: 10 +--- diff --git a/site/content/docs/runtime/memory_management/escape_analysis.md b/site/content/docs/runtime/memory_management/escape_analysis.md new file mode 100644 index 0000000..009a738 --- /dev/null +++ b/site/content/docs/runtime/memory_management/escape_analysis.md @@ -0,0 +1,7 @@ +--- +title: 逃逸分析 +weight: 10 +draft: true +--- + +# 逃逸分析 diff --git a/site/content/docs/runtime/memory_management/finalizer.md b/site/content/docs/runtime/memory_management/finalizer.md new file mode 100644 index 0000000..42b6c5e --- /dev/null +++ b/site/content/docs/runtime/memory_management/finalizer.md @@ -0,0 +1,7 @@ +--- +title: finalizer +weight: 10 +draft: true +--- + +# finalizer diff --git a/site/content/docs/runtime/memory_management/garbage_collection.md b/site/content/docs/runtime/memory_management/garbage_collection.md new file mode 100644 index 0000000..dbf5dfb --- /dev/null +++ b/site/content/docs/runtime/memory_management/garbage_collection.md @@ -0,0 +1,171 @@ +--- +title: 垃圾回收 +weight: 10 +--- + +# 垃圾回收(WIP) + +基于 Go 1.17。 + +![GC 的多个阶段](/images/runtime/memory/gcphases.jpg) + +## 三色抽象 + +在 Go 的代码中并无直接提示对象颜色的代码,对象的颜色主要由: + +* 对象对应的 gcmarkbit 位是否为 1 +* 对象的子对象是否已入队完成,若已完成,对象本身应该已经在队列外了 + +这两个状态来决定,三种颜色分别为: + +* 黑色:对象的 gcmarkbit 为 1,且对象已从队列中弹出 +* 灰色:对象的 gcmarkbit 为 1,其子对象未被处理完成,对象本身还在队列中 +* 白色:对象的 gcmarkbit 为 0,还未被标记流程所处理 + +## GC 触发 + +当前 GC 有三个触发点: + +* runtime.GC +* forcegchelper +* heap trigger + +## 并发标记流程 + + +{{}} + +{{}} + +### 关键组件及启动流程 + +worker 的三种模式 + +* 全职模式:gcMarkWorkerDedicatedMode +* 比例模式:gcMarkWorkerFractionalMode +* 兼职模式:gcMarkWorkerIdleMode + + +### gc roots + +垃圾回收的标记流程是将存活对象对应的 bit 位置为 1,堆上存活对象在内存中会形成森林结构,标记开始之前需要先将所有的根确定下来。 + +根对象包括四个来源: + +* bss 段 +* data 段 +* goroutine 栈 +* finalizer 关联的 special 类对象 + +### gcDrain + +gcDrain 是标记的核心流程 + +#### markroot + +根标记的流程很简单,就是根据 gcMarkrootPrepare 中计算出的索引值,遍历使用的根,执行 scanblock。 + +这些全局变量、goroutine 栈变量被扫描后,会被推到 gcw 队列中,成为灰色对象。 + +#### 标记过程中的队列 gcw && wbBuf && work.full + +{{}} + +{{}} + +#### 排空本地 gcw 和全局 work.full + +#### 标记终止流程 + +## mutator 与 marker 并发执行时的问题 + +### 对象丢失问题 + +GC 标记过程与 mutator 是并发执行的,所以在标记过程中,堆上对象的引用关系也会被动态修改,这时候可能有下面这种情况: + +{{}} + +{{}} + +丢失的对象会被认为是垃圾而被回收掉,这样在 mutator 后续访问该对象时便会发生内存错误。为了解决这个问题,mutator 在 GC 标记阶段需要打开 write barrier。所谓的 write barrier,就是在堆上指针发生修改前,插入一小段代码: + +![write barrier demo](/images/runtime/memory/write_barrier_demo.jpg) + +每次修改堆上指针都会判断 runtime.writeBarrier.enabled 是否为 true,如果为 true,那么在修改指针前需要调用 runtime.gcWriteBarrier。 + +Go 语言使用的 gc write barrier 是插入和删除的混合屏障,我们先来看看插入和删除屏障是什么。 + +#### dijistra 插入屏障 + +{{}} + +{{}} + +#### yuasa 删除屏障 + +{{}} + +{{}} + +#### Go 语言使用的混合屏障 + +runtime.gcWriteBarrier 是汇编函数,可以看到会将指针在修改前指向的值,和修改后指向的值都 push 到 wbBuf 中。 + +如果 wbBuf 满,那么就会将其 push 到 gcw 中,gcw 满了会 push 到全局的 work.full 中。 + +```go +TEXT runtime·gcWriteBarrier(SB),NOSPLIT,$112 + ...... + MOVQ (p_wbBuf+wbBuf_next)(R13), R12 + // Increment wbBuf.next position. + LEAQ 16(R12), R12 + MOVQ R12, (p_wbBuf+wbBuf_next)(R13) + CMPQ R12, (p_wbBuf+wbBuf_end)(R13) + // Record the write. + MOVQ AX, -16(R12) // Record value + MOVQ (DI), R13 + MOVQ R13, -8(R12) // Record *slot + // Is the buffer full? (flags set in CMPQ above) + JEQ flush +ret: + MOVQ 96(SP), R12 + MOVQ 104(SP), R13 + // Do the write. + MOVQ AX, (DI) + RET + +flush: + ...... + CALL runtime·wbBufFlush(SB) + ...... + JMP ret + ...... +``` + +## 清扫流程 sweep + +标记完成后,在 gcMarkTermination 中调用 gcSweep 会唤醒后台清扫 goroutine。该 goroutine 循环遍历所有 mspan,sweepone -> sweep 的主要操作为: + +* mspan.allocBits = mspan.gcMarkBits +* mspan.gcMarkBits clear + +清扫完成后会有三种情况: +* 该 mspan 全空了,那么调用 freeSpan 释放该 mspan 使其回归 arena,等待 scavenge 最终将这些 page 归还给操作系统 +* 尽管清扫了,但该 mspan 还是满的,那么将该 mspan 从 full 的 Unswept 链表移动到 full 的 Swept 部分 +* 清扫后 mspan 中出现了空槽,那么将该 mspan 从 full/partial 的 Unswept 链表移动到 partial 的 Swept 部分 + +### 协助清扫 + +TODO + +## 归还内存流程 scavenge + +bgscavenge -> pageAlloc.scavenge -> pageAlloc.scavengeOne -> pageAlloc.scavengeRangeLocked -> sysUnused -> madvise + + +### GOGC 及 GC 调步算法 + + +## debug.FreeOsMemory + +TODO \ No newline at end of file diff --git a/site/content/docs/runtime/memory_management/memory_alloctor.md b/site/content/docs/runtime/memory_management/memory_alloctor.md new file mode 100644 index 0000000..f149226 --- /dev/null +++ b/site/content/docs/runtime/memory_management/memory_alloctor.md @@ -0,0 +1,32 @@ +--- +title: 内存分配 +weight: 10 +--- + +# 内存分配 + +## bump/sequential allocator + +{{}} + + +{{}} + +## freelist allocator + +{{}} + +{{}} + +## dangling pointer + +{{}} + +{{}} + + +## tiny alloc + +{{}} + +{{}} \ No newline at end of file diff --git a/site/content/docs/runtime/netpoll/_index.md b/site/content/docs/runtime/netpoll/_index.md new file mode 100644 index 0000000..515c93b --- /dev/null +++ b/site/content/docs/runtime/netpoll/_index.md @@ -0,0 +1,5 @@ +--- +title: netpoll +weight: 10 +draft: true +--- diff --git a/site/content/docs/runtime/netpoll/basics.md b/site/content/docs/runtime/netpoll/basics.md new file mode 100644 index 0000000..8ec08a2 --- /dev/null +++ b/site/content/docs/runtime/netpoll/basics.md @@ -0,0 +1,127 @@ +--- +title: 网络编程基础 +weight: 1 +draft: true +--- + +# 网络编程基础 + +## 阻塞与非阻塞 + +在 linux 中,一切外部资源都被抽象为文件。网络连接也不例外,当我们在执行网络读、写操作时,可以使用 [fcntl](https://man7.org/linux/man-pages/man2/fcntl.2.html) 这个 syscall 来调整网络 fd 的阻塞模式: + +```c +int flag = fcntl(fd, F_GETFL, 0); +fcntl(fd, F_SETFL, flag|O_NONBLOCK); +``` + +fd 默认都是阻塞模式的,使用 fcntl 调整之后即为非阻塞模式。非阻塞与阻塞的区别可以用这张图来理解: + + + +## C 语言 epoll 示例 + +```c +#include +#include +#include +#include +#include +#include +#include + +#define BUF_SIZE 1024 +#define EPOLL_SIZE 50 + +void error_handling( char * msg ); + + +int main( int argc, char * argv[] ) +{ + int sock_fd, conn_fd; + struct sockaddr_in serv_addr, client_addr; + socklen_t addr_size; + int str_len, i; + char buf[BUF_SIZE]; + struct epoll_event * ep_events; + struct epoll_event event; + + int epfd, event_cnt; + + if ( argc != 2 ) + { + printf( "Usage : %s \n", argv[0] ); + exit( 1 ); + } + + sock_fd = socket( PF_INET, SOCK_STREAM, 0 ); + memset( &serv_addr, 0, sizeof(serv_addr) ); + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = htonl( INADDR_ANY ); + serv_addr.sin_port = htons( atoi( argv[1] ) ); + + if ( bind( sock_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr) ) == -1 ) + { + error_handling( "bind error" ); + } + + if ( listen( sock_fd, 5 ) == -1 ) + { + error_handling( "listen error" ); + } + + epfd = epoll_create( EPOLL_SIZE ); + ep_events = malloc( sizeof(struct epoll_event) * EPOLL_SIZE ); + + event.events = EPOLLIN; + event.data.fd = sock_fd; + epoll_ctl( epfd, EPOLL_CTL_ADD, sock_fd, &event ); + + while ( 1 ) + { + event_cnt = epoll_wait( epfd, ep_events, EPOLL_SIZE, -1 ); + if ( event_cnt == -1 ) + { + puts( "epoll_wait error" ); + break; + } + + for ( i = 0; i < event_cnt; i++ ) + { + if ( ep_events[i].data.fd == sock_fd ) + { + addr_size = sizeof(client_addr); + conn_fd = accept( sock_fd, (struct sockaddr *) &client_addr, &addr_size ); + event.events = EPOLLIN; + event.data.fd = conn_fd; + epoll_ctl( epfd, EPOLL_CTL_ADD, conn_fd, &event ); + printf( "connected client : %d\n", conn_fd ); + } else { + str_len = read( ep_events[i].data.fd, buf, BUF_SIZE ); + if ( str_len == 0 ) /* close request EOF? */ + { + epoll_ctl( epfd, EPOLL_CTL_DEL, ep_events[i].data.fd, NULL ); + close( ep_events[i].data.fd ); /* close(conn_fd); */ + printf( "closed client: %d\n", ep_events[i].data.fd ); + } else { + write( ep_events[i].data.fd, buf, str_len ); /* echo result! */ + } + } + } + } + close( sock_fd ); + close( epfd ); + return(0); +} + + +void error_handling( char * msg ) +{ + fputs( msg, stderr ); + fputc( '\n', stderr ); +} +``` + +## 参考资料 + +https://chromium.googlesource.com/chromiumos/docs/+/master/constants/syscalls.md diff --git a/site/content/docs/runtime/netpoll/netpoll.md b/site/content/docs/runtime/netpoll/netpoll.md new file mode 100644 index 0000000..6996b89 --- /dev/null +++ b/site/content/docs/runtime/netpoll/netpoll.md @@ -0,0 +1,20 @@ +--- +title: Go 语言的网络抽象 +weight: 2 +--- + +# netpoller + +从网络编程基础篇我们知道,网络编程中涉及到的主要系统调用是下面这些: + +* socket +* bind +* listen +* accept +* epoll_create +* epoll_wait +* epoll_ctl +* read +* write + +因此在学习 Go 对网络层的抽象时,我们也是重点关注 Go 的 netpoller 中,这些 syscall 被封装进了哪个具体的流程里。 diff --git a/site/content/docs/runtime/scheduler/_index.md b/site/content/docs/runtime/scheduler/_index.md new file mode 100644 index 0000000..178e6d8 --- /dev/null +++ b/site/content/docs/runtime/scheduler/_index.md @@ -0,0 +1,5 @@ +--- +title: 调度器 +weight: 10 +--- + diff --git a/site/content/docs/runtime/scheduler/gmp.md b/site/content/docs/runtime/scheduler/gmp.md new file mode 100644 index 0000000..b3329eb --- /dev/null +++ b/site/content/docs/runtime/scheduler/gmp.md @@ -0,0 +1,7 @@ +--- +title: G、M、P 抽象 +weight: 10 +draft: true +--- + +# G、M、P 抽象 diff --git a/site/content/docs/runtime/scheduler/handling_blocking.md b/site/content/docs/runtime/scheduler/handling_blocking.md new file mode 100644 index 0000000..62174d5 --- /dev/null +++ b/site/content/docs/runtime/scheduler/handling_blocking.md @@ -0,0 +1,28 @@ +--- +title: 处理阻塞 +weight: 10 +draft: true +--- + +# 处理阻塞 + +在 Go 语言中,我们可能写出很多会阻塞执行的代码。 + +## channel 发送阻塞 + +![block on channel send](/images/runtime/block_on_channel_send.jpg) + + +## channel 接收阻塞 + +## net.Conn 读阻塞 + +## net.Conn 写阻塞 + +## time.Sleep 阻塞 + +## select 阻塞 + +## lock 阻塞 + + diff --git a/site/content/docs/runtime/scheduler/preemption.md b/site/content/docs/runtime/scheduler/preemption.md new file mode 100644 index 0000000..399a016 --- /dev/null +++ b/site/content/docs/runtime/scheduler/preemption.md @@ -0,0 +1,622 @@ +--- +title: 抢占 +weight: 2 +--- + +# 抢占 + +从 Go 1.14 开始,通过使用信号,Go 语言实现了调度和 GC 过程中的真“抢占“。 + +抢占流程由抢占的发起方向被抢占线程发送 SIGURG 信号。 + +当被抢占线程收到信号后,进入 SIGURG 的处理流程,将 asyncPreempt 的调用强制插入到用户当前执行的代码位置。 + +本节会对该过程进行详尽分析。 + +## 抢占发起的时机 + +抢占会在下列时机发生: + +* STW 期间 +* 在 P 上执行 safe point 函数期间 +* sysmon 后台监控期间 +* gc pacer 分配新的 dedicated worker 期间 +* panic 崩溃期间 + +{{< rawhtml >}} + +{{< /rawhtml >}} + +除了栈扫描,所有触发抢占最终都会去执行 preemptone 函数。栈扫描流程比较特殊: + +{{< rawhtml >}} + +{{< /rawhtml >}} + +从这些流程里,我们挑出三个来一探究竟。 + +### STW 抢占 + +![GC 的多个阶段](/images/runtime/memory/gcphases.jpg) + +上图是现在 Go 语言的 GC 流程图,在两个 STW 阶段都需要将正在执行的线程上的 running 状态的 goroutine 停下来。 + +```go +func stopTheWorldWithSema() { + ..... + preemptall() + ..... + // 等待剩余的 P 主动停下 + if wait { + for { + // wait for 100us, then try to re-preempt in case of any races + // 等待 100us,然后重新尝试抢占 + if notetsleep(&sched.stopnote, 100*1000) { + noteclear(&sched.stopnote) + break + } + preemptall() + } + } + +``` + + +### GC 栈扫描 + +goroutine 的栈是 GC 扫描期间的根,所有 markroot 中需要将用户的 goroutine 停下来,主要是 running 状态: + +```go +func markroot(gcw *gcWork, i uint32) { + // Note: if you add a case here, please also update heapdump.go:dumproots. + switch { + ...... + default: + // the rest is scanning goroutine stacks + var gp *g + ...... + + // scanstack must be done on the system stack in case + // we're trying to scan our own stack. + systemstack(func() { + stopped := suspendG(gp) + scanstack(gp, gcw) + resumeG(stopped) + }) + } +} +``` + +suspendG 中会调用 preemptM -> signalM 对正在执行的 goroutine 所在的线程发送抢占信号。 + +### sysmon 后台监控 + +```go +func sysmon() { + idle := 0 // how many cycles in succession we had not wokeup somebody + for { + ...... + // retake P's blocked in syscalls + // and preempt long running G's + if retake(now) != 0 { + idle = 0 + } else { + idle++ + } + } +} +``` + +执行 syscall 太久的,需要将 P 从 M 上剥离;运行用户代码太久的,需要抢占停止该 goroutine 执行。这里我们只看抢占 goroutine 的部分: + +```go +const forcePreemptNS = 10 * 1000 * 1000 // 10ms + +func retake(now int64) uint32 { + ...... + for i := 0; i < len(allp); i++ { + _p_ := allp[i] + s := _p_.status + if s == _Prunning || s == _Psyscall { + // Preempt G if it's running for too long. + t := int64(_p_.schedtick) + if int64(pd.schedtick) != t { + pd.schedtick = uint32(t) + pd.schedwhen = now + } else if pd.schedwhen+forcePreemptNS <= now { + preemptone(_p_) + } + } + ...... + } + ...... +} +``` + +## 协作式抢占原理 + +cooperative preemption 关键在于 cooperative,抢占的时机在各个版本实现差异不大,我们重点来看看这个协作过程。 + +### 函数头、函数尾插入的栈扩容检查 + +在 Go 语言中发生函数调用时,如果函数的 framesize > 0,说明在调用该函数时可能会发生 goroutine 的栈扩张,这时会在函数头、函数尾分别插入一段汇编码: + +```go +package main + +func main() { + add(1, 2) +} + +//go:noinline +func add(x, y int) (int, bool) { + var z = x + y + println(z) + return x + y, true +} +``` + +add 函数在使用 go tool compile -S 后会生成下面的结果: + +```go +// 这里的汇编代码使用 go1.14 生成 +// 在 go1.17 之后,函数的调用规约发生变化 +// 1.17 与以往版本头部的汇编代码也会有所不同,但逻辑保持一致 +"".add STEXT size=103 args=0x20 locals=0x18 + 0x0000 00000 (add.go:8) TEXT "".add(SB), ABIInternal, $24-32 + 0x0000 00000 (add.go:8) MOVQ (TLS), CX + 0x0009 00009 (add.go:8) CMPQ SP, 16(CX) + 0x000d 00013 (add.go:8) JLS 96 + ...... func body + 0x005f 00095 (add.go:11) RET + 0x0060 00096 (add.go:11) NOP + 0x0060 00096 (add.go:8) CALL runtime.morestack_noctxt(SB) + 0x0065 00101 (add.go:8) JMP 0 +``` + +TLS 中存储的是 G 的指针,偏移 16 字节即是 G 的结构体中的 stackguard0。由于 goroutine 的栈也是从高地址向低地址增长,因此这里检查当前 SP < stackguard0 的话,说明需要对栈进行扩容了。 + +### morestack 中的调度逻辑 + +```go +// morestack_noctxt 是个简单的汇编方法 +// 直接跳转到 morestack +TEXT runtime·morestack_noctxt(SB),NOSPLIT|NOFRAME,$0-0 + MOV ZERO, CTXT + JMP runtime·morestack(SB) + +TEXT runtime·morestack(SB),NOSPLIT,$0-0 + ...... + // 前面会切换将执行现场保存到 goroutine 的 gobuf 中 + // 并将执行栈切换到 g0 + // Call newstack on m->g0's stack. + MOVQ m_g0(BX), BX + MOVQ BX, g(CX) + MOVQ (g_sched+gobuf_sp)(BX), SP + CALL runtime·newstack(SB) + ...... + RET +``` + +morestack 会将 goroutine 的现场保存在当前 goroutine 的 gobuf 中,并将执行栈切换到 g0,然后在 g0 上执行 runtime.newstack。 + +在未实现信号抢占之前,用户的 g 到底啥时候能停下来,负责 GC 栈扫描的 goroutine 也不知道,所以 scanstack 也就只能设置一下 preemptscan 的标志位,最终栈扫描要 [newstack](https://github.com/golang/go/blob/2bc8d90fa21e9547aeb0f0ae775107dc8e05dc0a/src/runtime/stack.go#L917) 来配合,下面的 newstack 是 Go 1.13 版本的实现: + +```go +func newstack() { + thisg := getg() + gp := thisg.m.curg + preempt := atomic.Loaduintptr(&gp.stackguard0) == stackPreempt + if preempt { + if thisg.m.locks != 0 || thisg.m.mallocing != 0 || thisg.m.preemptoff != "" || thisg.m.p.ptr().status != _Prunning { + gp.stackguard0 = gp.stack.lo + _StackGuard + gogo(&gp.sched) // never return + } + } + + if preempt { + // 要和 scang 过程配合 + // 老版本的 newstack 和 gc scan 过程是有较重的耦合的 + casgstatus(gp, _Grunning, _Gwaiting) + if gp.preemptscan { + for !castogscanstatus(gp, _Gwaiting, _Gscanwaiting) { + } + if !gp.gcscandone { + gcw := &gp.m.p.ptr().gcw + // 注意这里,偶合了 GC 的 scanstack 逻辑代码 + scanstack(gp, gcw) + gp.gcscandone = true + } + gp.preemptscan = false + gp.preempt = false + casfrom_Gscanstatus(gp, _Gscanwaiting, _Gwaiting) + casgstatus(gp, _Gwaiting, _Grunning) + gp.stackguard0 = gp.stack.lo + _StackGuard + gogo(&gp.sched) // never return + } + + casgstatus(gp, _Gwaiting, _Grunning) + gopreempt_m(gp) // never return + } + ...... +} + +``` + +抢占成功后,当前的 goroutine 会被放在全局队列中: + +```go +func gopreempt_m(gp *g) { + goschedImpl(gp) +} + +func goschedImpl(gp *g) { + status := readgstatus(gp) + ...... + + casgstatus(gp, _Grunning, _Grunnable) + dropg() + lock(&sched.lock) + globrunqput(gp) // 将当前 goroutine 放进全局队列 + unlock(&sched.lock) + + schedule() // 当前线程重新进入调度循环 +} +``` + +### 信号式抢占实现后的 newstack + +在实现了信号式抢占之后,对于用户的 goroutine 何时中止有了一些预期,所以 newstack 就不需要耦合 scanstack 的逻辑了,新版的 [newstack](https://github.com/golang/go/blob/c3b47cb598e1ecdbbec110325d9d1979553351fc/src/runtime/stack.go#L948) 实现如下: + +```go +func newstack() { + thisg := getg() + gp := thisg.m.curg + preempt := atomic.Loaduintptr(&gp.stackguard0) == stackPreempt + + if preempt { + if !canPreemptM(thisg.m) { + // 让 goroutine 继续执行 + // 下次再抢占它 + gp.stackguard0 = gp.stack.lo + _StackGuard + gogo(&gp.sched) // never return + } + } + + if preempt { + // 当 GC 需要发起 goroutine 的栈扫描时 + // 会设置这个 preemptStop 为 true + // 这时候需要 goroutine 自己去 gopark + if gp.preemptStop { + preemptPark(gp) // never returns + } + + // 除了 GC 栈扫描以外的其它抢占场景走这个分支 + // 看起来就像 goroutine 自己调用了 runtime.Gosched 一样 + gopreempt_m(gp) // never return + } + ...... 后面就是正常的栈扩展逻辑了 +} +``` + +newstack 中会使用 [canPreemptM](https://github.com/golang/go/blob/287c5e8066396e953254d7980a80ec082edf11bd/src/runtime/preempt.go#L287)判断哪些场景适合抢占,哪些不适合。如果当前 goroutine 正在执行(即 status == running),并且满足下列任意其一: + +* 持有锁(主要是写锁,读锁其实判断不出来); +* 正在进行内存分配 +* preemptoff 非空 + +便不应该进行抢占,会在下一次进入到 newstack 时再进行判断。 + +## 非协作式抢占 + +非协作式抢占,就是通过信号处理来实现的。所以我们只要关注 SIGURG 的处理流程即可。 + +### 信号处理初始化 + +当 m0(即程序启动时的第一个线程)初始化时,会进行信号处理的初始化工作: + +```go +// mstartm0 implements part of mstart1 that only runs on the m0. +func mstartm0() { + initsig(false) +} + +// Initialize signals. +func initsig(preinit bool) { + for i := uint32(0); i < _NSIG; i++ { + setsig(i, funcPC(sighandler)) + } +} + +var sigtable = [...]sigTabT{ + ...... + /* 23 */ {_SigNotify + _SigIgn, "SIGURG: urgent condition on socket"}, + ...... +} + +``` + +最后都是执行 sigaction: + +```go +TEXT runtime·rt_sigaction(SB),NOSPLIT,$0-36 + MOVQ sig+0(FP), DI + MOVQ new+8(FP), SI + MOVQ old+16(FP), DX + MOVQ size+24(FP), R10 + MOVL $SYS_rt_sigaction, AX + SYSCALL + MOVL AX, ret+32(FP) + RET +``` + +与一般的 syscall 区别不大。 + +信号处理初始化的流程比较简单,就是给所有已知的需要处理的信号绑上 sighandler。 + +### 发送信号 + +```go +func preemptone(_p_ *p) bool { + mp := _p_.m.ptr() + gp := mp.curg + gp.preempt = true + gp.stackguard0 = stackPreempt + + // 向该线程发送 SIGURG 信号 + if preemptMSupported && debug.asyncpreemptoff == 0 { + _p_.preempt = true + preemptM(mp) + } + + return true +} +``` + +preemptM 的流程较为线性: + +```go +func preemptM(mp *m) { + if atomic.Cas(&mp.signalPending, 0, 1) { + signalM(mp, sigPreempt) + } +} + +func signalM(mp *m, sig int) { + tgkill(getpid(), int(mp.procid), sig) +} +``` + +最后使用 tgkill 这个 syscall 将信号发送给指定 id 的线程: + +```go +TEXT ·tgkill(SB),NOSPLIT,$0 + MOVQ tgid+0(FP), DI + MOVQ tid+8(FP), SI + MOVQ sig+16(FP), DX + MOVL $SYS_tgkill, AX + SYSCALL + RET +``` + +### 接收信号后的处理 + +当线程 m 接收到信号后,会从用户栈 g 切换到 gsignal 执行信号处理逻辑,即 sighandler 流程: + +```go +func sighandler(sig uint32, info *siginfo, ctxt unsafe.Pointer, gp *g) { + _g_ := getg() + c := &sigctxt{info, ctxt} + + ...... + if sig == sigPreempt && debug.asyncpreemptoff == 0 { + doSigPreempt(gp, c) + } + ...... +} +``` + +如果收到的是抢占信号,那么执行 doSigPreempt 逻辑: + +```go +func doSigPreempt(gp *g, ctxt *sigctxt) { + // 检查当前 G 被抢占是否安全 + if wantAsyncPreempt(gp) { + if ok, newpc := isAsyncSafePoint(gp, ctxt.sigpc(), ctxt.sigsp(), ctxt.siglr()); ok { + // Adjust the PC and inject a call to asyncPreempt. + ctxt.pushCall(funcPC(asyncPreempt), newpc) + } + } + ...... +} +``` + +isAsyncSafePoint 中会把一些不应该抢占的场景过滤掉,具体包括: + +* 当前代码在汇编编写的函数中执行 +* 代码在 runtime,runtime/internal 或者 reflect 包中执行 + +doSigPreempt 代码中的 pushCall 是关键步骤: + +```go +func (c *sigctxt) pushCall(targetPC, resumePC uintptr) { + // Make it look like we called target at resumePC. + sp := uintptr(c.rsp()) + sp -= sys.PtrSize + *(*uintptr)(unsafe.Pointer(sp)) = resumePC + c.set_rsp(uint64(sp)) + c.set_rip(uint64(targetPC)) +} +``` + +pushCall 相当于将用户将要执行的下一条代码的地址直接 push 到栈上,并 jmp 到指定的 target 地址去执行代码: + +{{< columns >}} + +before + +```shell +----- PC = 0x123 +local var 1 +----- +local var 2 +----- <---- SP +``` + +<---> + +after + +```shell +----- PC = targetPC +local var 1 +----- +local var 2 +----- +prev PC = 0x123 +----- <---- SP +``` + +{{}} + +{{< columns>}} +{{< /columns >}} + +这里的 target 就是 asyncPreempt。 + +### asyncPreempt 执行流程分析 + +asyncPreempt 分为上半部分和下半部分,中间被 asyncPreempt2 隔开。上半部分负责将 goroutine 当前执行现场的所有寄存器都保存到当前的运行栈上。 + +下半部分负责在 asyncPreempt2 返回后将这些现场恢复出来。 + +```go +TEXT ·asyncPreempt(SB),NOSPLIT|NOFRAME,$0-0 + PUSHQ BP + MOVQ SP, BP + ...... 保存现场 1 + MOVQ AX, 0(SP) + MOVQ CX, 8(SP) + MOVQ DX, 16(SP) + MOVQ BX, 24(SP) + MOVQ SI, 32(SP) + ...... 保存现场 2 + MOVQ R15, 104(SP) + MOVUPS X0, 112(SP) + MOVUPS X1, 128(SP) + ...... + MOVUPS X15, 352(SP) + + CALL ·asyncPreempt2(SB) + + MOVUPS 352(SP), X15 + ...... 恢复现场 2 + MOVUPS 112(SP), X0 + MOVQ 104(SP), R15 + ...... 恢复现场 1 + MOVQ 8(SP), CX + MOVQ 0(SP), AX + ...... + RET + +``` + +asyncPreempt2 中有两个分支: + +```go +func asyncPreempt2() { + gp := getg() + gp.asyncSafePoint = true + if gp.preemptStop { // 这个 preemptStop 是在 GC 的栈扫描中才会设置为 true + mcall(preemptPark) + } else { // 除了栈扫描,其它抢占全部走这条分支 + mcall(gopreempt_m) + } + gp.asyncSafePoint = false +} +``` + +GC 栈扫描走 if 分支,除栈扫描以外所有情况均走 else 分支。 + +**栈扫描抢占流程** + +suspendG -> preemptM -> signalM 发信号。 + +sighandler -> asyncPreempt -> 保存执行现场 -> asyncPreempt2 -> **preemptPark** + +preemptPark 和 gopark 类似,挂起当前正在执行的 goroutine,该 goroutine 之前绑定的线程就可以继续执行调度循环了。 + +scanstack 执行完之后: + +resumeG -> ready -> runqput 会让之前被停下来的 goroutine 进当前 P 的队列或全局队列。 + +**其它流程** + +preemptone -> preemptM - signalM 发信号。 + +sighandler -> asyncPreempt -> 保存执行现场 -> asyncPreempt2 -> **gopreempt_m** + +gopreempt_m 会直接将被抢占的 goroutine 放进全局队列。 + +无论是栈扫描流程还是其它流程,当 goroutine 程序被调度到时,都是从汇编中的 `CALL ·asyncPreempt2(SB)` 的下一条指令开始执行的,即 asyncPreempt 汇编函数的下半部分。 + +这部分会将之前 goroutine 的现场完全恢复,就和抢占从来没有发生过一样。 + +## 动画演示 + +下面的动画是可以点的哦~ + +**sighandler 收到抢占信号,保存 PC,并将 PC 指向 asyncPreempt 的过程动画:** + +{{}} + +{{}} + + +**GC 栈扫描时的抢占和恢复过程:** + +{{}} + +{{}} + + +**除了栈扫描之外的抢占和恢复过程:** + +{{}} + +{{}} diff --git a/site/content/docs/runtime/scheduler/sched_loop.md b/site/content/docs/runtime/scheduler/sched_loop.md new file mode 100644 index 0000000..2ea1f2c --- /dev/null +++ b/site/content/docs/runtime/scheduler/sched_loop.md @@ -0,0 +1,34 @@ +--- +title: 调度流程(WIP) +weight: 1 +--- + +## 组件大图 + +![](/images/runtime/schedule/sche_big.png) + +## Go 的调度流程 + +我们可以认为 goroutine 的创建与调度循环是一个生产-消费流程。整个 go 程序的运行就是在不断地执行 goroutine 的生产与消费流程。 + +创建 goroutine 即是在创建任务,这些生产出来的 goroutine 可能会有三个去处,分别是: + +* p.runnext +* p.localrunq +* schedt.global runq + +按照执行权来讲,优先级是逐渐降低的。 + +调度循环会不断地从上面讲的三个目标中消费 goroutine,并执行。 + +## goroutine 生产 + +{{}} + +{{}} + +## goroutine 消费 + +{{}} + +{{}} diff --git a/site/content/docs/std_library/_index.md b/site/content/docs/std_library/_index.md new file mode 100644 index 0000000..e7e0be6 --- /dev/null +++ b/site/content/docs/std_library/_index.md @@ -0,0 +1,6 @@ +--- +title: 标准库 +weight: 5 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/sync/_index.md b/site/content/docs/sync/_index.md new file mode 100644 index 0000000..3e93950 --- /dev/null +++ b/site/content/docs/sync/_index.md @@ -0,0 +1,5 @@ +--- +title: 同步编程 +weight: 5 +bookCollapseSection: true +--- diff --git a/site/content/docs/sync/lock_free.md b/site/content/docs/sync/lock_free.md new file mode 100644 index 0000000..290f271 --- /dev/null +++ b/site/content/docs/sync/lock_free.md @@ -0,0 +1,8 @@ +--- +title: 同步编程 +weight: 5 +bookCollapseSection: true +draft: true +--- + +# lock free programming diff --git a/site/content/docs/sync/memory_barrier.md b/site/content/docs/sync/memory_barrier.md new file mode 100644 index 0000000..1da714b --- /dev/null +++ b/site/content/docs/sync/memory_barrier.md @@ -0,0 +1,7 @@ +--- +title: 同步编程 +weight: 5 +bookCollapseSection: true +draft: true +--- +# Memory Barrier diff --git a/site/content/docs/sync/patterns.md b/site/content/docs/sync/patterns.md new file mode 100644 index 0000000..e565ddc --- /dev/null +++ b/site/content/docs/sync/patterns.md @@ -0,0 +1,8 @@ +--- +title: 同步编程 +weight: 5 +bookCollapseSection: true +draft: true +--- + +# 并发编程模式 diff --git a/site/content/docs/sync/theory.md b/site/content/docs/sync/theory.md new file mode 100644 index 0000000..bdc60be --- /dev/null +++ b/site/content/docs/sync/theory.md @@ -0,0 +1,8 @@ +--- +title: 同步编程 +weight: 5 +bookCollapseSection: true +draft: true +--- + +# 并发编程理论 diff --git a/site/content/docs/sync/tools.md b/site/content/docs/sync/tools.md new file mode 100644 index 0000000..2662af1 --- /dev/null +++ b/site/content/docs/sync/tools.md @@ -0,0 +1,8 @@ +--- +title: 同步编程 +weight: 5 +bookCollapseSection: true +draft: true +--- + +# 并发工具 diff --git a/site/content/docs/sync/tools/_index.md b/site/content/docs/sync/tools/_index.md new file mode 100644 index 0000000..715279b --- /dev/null +++ b/site/content/docs/sync/tools/_index.md @@ -0,0 +1,6 @@ +--- +title: 同步工具 +weight: 5 +bookCollapseSection: true +--- + diff --git a/site/content/docs/sync/tools/syncPool.md b/site/content/docs/sync/tools/syncPool.md new file mode 100644 index 0000000..29e31da --- /dev/null +++ b/site/content/docs/sync/tools/syncPool.md @@ -0,0 +1,7 @@ +--- +title: sync.Pool[WIP] +weight: 5 +bookCollapseSection: true +--- + +![map struct](/images/sync/syncPool.png) diff --git a/site/content/docs/syntax_sugar/_index.md b/site/content/docs/syntax_sugar/_index.md new file mode 100644 index 0000000..11ae5e4 --- /dev/null +++ b/site/content/docs/syntax_sugar/_index.md @@ -0,0 +1,6 @@ +--- +title: 语法糖 +weight: 5 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/syntax_sugar/defer.md b/site/content/docs/syntax_sugar/defer.md new file mode 100644 index 0000000..45a4cc1 --- /dev/null +++ b/site/content/docs/syntax_sugar/defer.md @@ -0,0 +1 @@ +# defer 的实现 diff --git a/site/content/docs/system_programming/_index.md b/site/content/docs/system_programming/_index.md new file mode 100644 index 0000000..feb46d7 --- /dev/null +++ b/site/content/docs/system_programming/_index.md @@ -0,0 +1,6 @@ +--- +title: 系统编程 +weight: 5 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/system_programming/syscall.md b/site/content/docs/system_programming/syscall.md new file mode 100644 index 0000000..7bf6a30 --- /dev/null +++ b/site/content/docs/system_programming/syscall.md @@ -0,0 +1 @@ +# syscall 理论 diff --git a/site/content/docs/system_programming/vdso.md b/site/content/docs/system_programming/vdso.md new file mode 100644 index 0000000..63b9d7f --- /dev/null +++ b/site/content/docs/system_programming/vdso.md @@ -0,0 +1 @@ +# vdso syscall diff --git a/site/content/docs/third_party/_index.md b/site/content/docs/third_party/_index.md new file mode 100644 index 0000000..21f7d69 --- /dev/null +++ b/site/content/docs/third_party/_index.md @@ -0,0 +1,6 @@ +--- +title: 第三方库 +weight: 5 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/third_party/parser.md b/site/content/docs/third_party/parser.md new file mode 100644 index 0000000..a3c71f6 --- /dev/null +++ b/site/content/docs/third_party/parser.md @@ -0,0 +1,3 @@ +# parser + +## 使用 antlr 实现 parser diff --git a/site/content/docs/time/_index.md b/site/content/docs/time/_index.md new file mode 100644 index 0000000..3402c64 --- /dev/null +++ b/site/content/docs/time/_index.md @@ -0,0 +1,6 @@ +--- +title: 时间处理 +weight: 5 +bookCollapseSection: true +draft: true +--- diff --git a/site/content/docs/time/monotonic.md b/site/content/docs/time/monotonic.md new file mode 100644 index 0000000..7bf57e7 --- /dev/null +++ b/site/content/docs/time/monotonic.md @@ -0,0 +1 @@ +# monotonic diff --git a/site/layouts/shortcodes/rawhtml.html b/site/layouts/shortcodes/rawhtml.html new file mode 100644 index 0000000..b90bea2 --- /dev/null +++ b/site/layouts/shortcodes/rawhtml.html @@ -0,0 +1,2 @@ + +{{.Inner}} diff --git a/site/resources/_gen/assets/scss/book.scss_50fc8c04e12a2f59027287995557ceff.content b/site/resources/_gen/assets/scss/book.scss_50fc8c04e12a2f59027287995557ceff.content new file mode 100644 index 0000000..b200717 --- /dev/null +++ b/site/resources/_gen/assets/scss/book.scss_50fc8c04e12a2f59027287995557ceff.content @@ -0,0 +1 @@ +@charset "UTF-8";:root{--gray-100:#f8f9fa;--gray-200:#e9ecef;--gray-500:#adb5bd;--color-link:#0055bb;--color-visited-link:#8440f1;--body-background:white;--body-font-color:black;--icon-filter:none;--hint-color-info:#6bf;--hint-color-warning:#fd6;--hint-color-danger:#f66}/*!normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css*/html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button::-moz-focus-inner,[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}.flex{display:flex}.flex-auto{flex:auto}.flex-even{flex:1 1}.flex-wrap{flex-wrap:wrap}.justify-start{justify-content:flex-start}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.align-center{align-items:center}.mx-auto{margin:0 auto}.text-center{text-align:center}.text-left{text-align:left}.text-right{text-align:right}.hidden{display:none}input.toggle{height:0;width:0;overflow:hidden;opacity:0;position:absolute}.clearfix::after{content:"";display:table;clear:both}html{font-size:16px;scroll-behavior:smooth;touch-action:manipulation}body{min-width:20rem;color:var(--body-font-color);background:var(--body-background);letter-spacing:.33px;font-weight:400;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;box-sizing:border-box}body *{box-sizing:inherit}h1,h2,h3,h4,h5{font-weight:400}a{text-decoration:none;color:var(--color-link)}img{vertical-align:baseline}:focus{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}aside nav ul{padding:0;margin:0;list-style:none}aside nav ul li{margin:1em 0;position:relative}aside nav ul a{display:block}aside nav ul a:hover{opacity:.5}aside nav ul ul{padding-inline-start:1rem}ul.pagination{display:flex;justify-content:center;list-style-type:none}ul.pagination .page-item a{padding:1rem}.container{max-width:80rem;margin:0 auto}.book-icon{filter:var(--icon-filter)}.book-brand{margin-top:0}.book-brand img{height:1.5em;width:auto;vertical-align:middle;margin-inline-end:.5rem}.book-menu{flex:0 0 16rem;font-size:.875rem}.book-menu .book-menu-content{width:16rem;padding:1rem;background:var(--body-background);position:fixed;top:0;bottom:0;overflow-x:hidden;overflow-y:auto}.book-menu a,.book-menu label{color:inherit;cursor:pointer;word-wrap:break-word}.book-menu a.active{color:var(--color-link)}.book-menu input.toggle+label+ul{display:none}.book-menu input.toggle:checked+label+ul{display:block}.book-menu input.toggle+label::after{content:"▸"}.book-menu input.toggle:checked+label::after{content:"▾"}body[dir=rtl] .book-menu input.toggle+label::after{content:"◂"}body[dir=rtl] .book-menu input.toggle:checked+label::after{content:"▾"}.book-section-flat{margin-bottom:2rem}.book-section-flat:not(:first-child){margin-top:2rem}.book-section-flat>a,.book-section-flat>span,.book-section-flat>label{font-weight:bolder}.book-section-flat>ul{padding-inline-start:0}.book-page{min-width:20rem;flex-grow:1;padding:1rem}.book-post{margin-bottom:3rem}.book-header{display:none;margin-bottom:1rem}.book-header label{line-height:0}.book-header img.book-icon{height:1.5em;width:1.5em}.book-search{position:relative;margin:1rem 0;border-bottom:1px solid transparent}.book-search input{width:100%;padding:.5rem;border:0;border-radius:.25rem;background:var(--gray-100);color:var(--body-font-color)}.book-search input:required+.book-search-spinner{display:block}.book-search .book-search-spinner{position:absolute;top:0;margin:.5rem;margin-inline-start:calc(100% - 1.5rem);width:1rem;height:1rem;border:1px solid transparent;border-top-color:var(--body-font-color);border-radius:50%;animation:spin 1s ease infinite}@keyframes spin{100%{transform:rotate(360deg)}}.book-search small{opacity:.5}.book-toc{flex:0 0 16rem;font-size:.75rem}.book-toc .book-toc-content{width:16rem;padding:1rem;position:fixed;top:0;bottom:0;overflow-x:hidden;overflow-y:auto}.book-toc img{height:1em;width:1em}.book-toc nav>ul>li:first-child{margin-top:0}.book-footer{padding-top:1rem;font-size:.875rem}.book-footer img{height:1em;width:1em;margin-inline-end:.5rem}.book-comments{margin-top:1rem}.book-languages{position:relative;overflow:visible;padding:1rem;margin:-1rem}.book-languages ul{margin:0;padding:0;list-style:none}.book-languages ul li{white-space:nowrap;cursor:pointer}.book-languages:hover .book-languages-list,.book-languages:focus .book-languages-list,.book-languages:focus-within .book-languages-list{display:block}.book-languages .book-languages-list{display:none;position:absolute;bottom:100%;left:0;padding:.5rem 0;background:var(--body-background);box-shadow:0 0 .25rem rgba(0,0,0,.1)}.book-languages .book-languages-list li img{opacity:.25}.book-languages .book-languages-list li.active img,.book-languages .book-languages-list li:hover img{opacity:initial}.book-languages .book-languages-list a{color:inherit;padding:.5rem 1rem}.book-home{padding:1rem}.book-menu-content,.book-toc-content,.book-page,.book-header aside,.markdown{transition:.2s ease-in-out;transition-property:transform,margin,opacity,visibility;will-change:transform,margin,opacity}@media screen and (max-width:56rem){#menu-control,#toc-control{display:inline}.book-menu{visibility:hidden;margin-inline-start:-16rem;font-size:16px;z-index:1}.book-toc{display:none}.book-header{display:block}#menu-control:focus~main label[for=menu-control]{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}#menu-control:checked~main .book-menu{visibility:initial}#menu-control:checked~main .book-menu .book-menu-content{transform:translateX(16rem);box-shadow:0 0 .5rem rgba(0,0,0,.1)}#menu-control:checked~main .book-page{opacity:.25}#menu-control:checked~main .book-menu-overlay{display:block;position:absolute;top:0;bottom:0;left:0;right:0}#toc-control:focus~main label[for=toc-control]{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}#toc-control:checked~main .book-header aside{display:block}body[dir=rtl] #menu-control:checked~main .book-menu .book-menu-content{transform:translateX(-16rem)}}@media screen and (min-width:80rem){.book-page,.book-menu .book-menu-content,.book-toc .book-toc-content{padding:2rem 1rem}}@font-face{font-family:roboto;font-style:normal;font-weight:400;font-display:swap;src:local(""),url(fonts/roboto-v27-latin-regular.woff2)format("woff2"),url(fonts/roboto-v27-latin-regular.woff)format("woff")}@font-face{font-family:roboto;font-style:normal;font-weight:700;font-display:swap;src:local(""),url(fonts/roboto-v27-latin-700.woff2)format("woff2"),url(fonts/roboto-v27-latin-700.woff)format("woff")}@font-face{font-family:roboto mono;font-style:normal;font-weight:400;font-display:swap;src:local(""),url(fonts/roboto-mono-v13-latin-regular.woff2)format("woff2"),url(fonts/roboto-mono-v13-latin-regular.woff)format("woff")}body{font-family:roboto,sans-serif}code{font-family:roboto mono,monospace}@media print{.book-menu,.book-footer,.book-toc{display:none}.book-header,.book-header aside{display:block}main{display:block!important}}.markdown{line-height:1.6}.markdown>:first-child{margin-top:0}.markdown h1,.markdown h2,.markdown h3,.markdown h4,.markdown h5,.markdown h6{font-weight:400;line-height:1;margin-top:1.5em;margin-bottom:1rem}.markdown h1 a.anchor,.markdown h2 a.anchor,.markdown h3 a.anchor,.markdown h4 a.anchor,.markdown h5 a.anchor,.markdown h6 a.anchor{opacity:0;font-size:.75em;vertical-align:middle;text-decoration:none}.markdown h1:hover a.anchor,.markdown h1 a.anchor:focus,.markdown h2:hover a.anchor,.markdown h2 a.anchor:focus,.markdown h3:hover a.anchor,.markdown h3 a.anchor:focus,.markdown h4:hover a.anchor,.markdown h4 a.anchor:focus,.markdown h5:hover a.anchor,.markdown h5 a.anchor:focus,.markdown h6:hover a.anchor,.markdown h6 a.anchor:focus{opacity:initial}.markdown h4,.markdown h5,.markdown h6{font-weight:bolder}.markdown h5{font-size:.875em}.markdown h6{font-size:.75em}.markdown b,.markdown optgroup,.markdown strong{font-weight:bolder}.markdown a{text-decoration:none}.markdown a:hover{text-decoration:underline}.markdown a:visited{color:var(--color-visited-link)}.markdown img{max-width:100%}.markdown code{padding:0 .25rem;background:var(--gray-200);border-radius:.25rem;font-size:.875em}.markdown pre{padding:1rem;background:var(--gray-100);border-radius:.25rem;overflow-x:auto}.markdown pre code{padding:0;background:0 0}.markdown blockquote{margin:1rem 0;padding:.5rem 1rem .5rem .75rem;border-inline-start:.25rem solid var(--gray-200);border-radius:.25rem}.markdown blockquote :first-child{margin-top:0}.markdown blockquote :last-child{margin-bottom:0}.markdown table{overflow:auto;display:block;border-spacing:0;border-collapse:collapse;margin-top:1rem;margin-bottom:1rem}.markdown table tr th,.markdown table tr td{padding:.5rem 1rem;border:1px solid var(--gray-200)}.markdown table tr:nth-child(2n){background:var(--gray-100)}.markdown hr{height:1px;border:none;background:var(--gray-200)}.markdown ul,.markdown ol{padding-inline-start:2rem}.markdown dl dt{font-weight:bolder;margin-top:1rem}.markdown dl dd{margin-inline-start:0;margin-bottom:1rem}.markdown .highlight table tr td:nth-child(1) pre{margin:0;padding-inline-end:0}.markdown .highlight table tr td:nth-child(2) pre{margin:0;padding-inline-start:0}.markdown details{padding:1rem;border:1px solid var(--gray-200);border-radius:.25rem}.markdown details summary{line-height:1;padding:1rem;margin:-1rem;cursor:pointer}.markdown details[open] summary{margin-bottom:0}.markdown figure{margin:1rem 0}.markdown figure figcaption p{margin-top:0}.markdown-inner>:first-child{margin-top:0}.markdown-inner>:last-child{margin-bottom:0}.markdown .book-expand{margin-top:1rem;margin-bottom:1rem;border:1px solid var(--gray-200);border-radius:.25rem;overflow:hidden}.markdown .book-expand .book-expand-head{background:var(--gray-100);padding:.5rem 1rem;cursor:pointer}.markdown .book-expand .book-expand-content{display:none;padding:1rem}.markdown .book-expand input[type=checkbox]:checked+.book-expand-content{display:block}.markdown .book-tabs{margin-top:1rem;margin-bottom:1rem;border:1px solid var(--gray-200);border-radius:.25rem;overflow:hidden;display:flex;flex-wrap:wrap}.markdown .book-tabs label{display:inline-block;padding:.5rem 1rem;border-bottom:1px transparent;cursor:pointer}.markdown .book-tabs .book-tabs-content{order:999;width:100%;border-top:1px solid var(--gray-100);padding:1rem;display:none}.markdown .book-tabs input[type=radio]:checked+label{border-bottom:1px solid var(--color-link)}.markdown .book-tabs input[type=radio]:checked+label+.book-tabs-content{display:block}.markdown .book-tabs input[type=radio]:focus+label{outline-style:auto;outline-color:currentColor;outline-color:-webkit-focus-ring-color}.markdown .book-columns{margin-left:-1rem;margin-right:-1rem}.markdown .book-columns>div{margin:1rem 0;min-width:10rem;padding:0 1rem}.markdown a.book-btn{display:inline-block;font-size:.875rem;color:var(--color-link);line-height:2rem;padding:0 1rem;border:1px solid var(--color-link);border-radius:.25rem;cursor:pointer}.markdown a.book-btn:hover{text-decoration:none}.markdown .book-hint.info{border-color:#6bf;background-color:rgba(102,187,255,.1)}.markdown .book-hint.warning{border-color:#fd6;background-color:rgba(255,221,102,.1)}.markdown .book-hint.danger{border-color:#f66;background-color:rgba(255,102,102,.1)} \ No newline at end of file diff --git a/site/resources/_gen/assets/scss/book.scss_50fc8c04e12a2f59027287995557ceff.json b/site/resources/_gen/assets/scss/book.scss_50fc8c04e12a2f59027287995557ceff.json new file mode 100644 index 0000000..112aa6d --- /dev/null +++ b/site/resources/_gen/assets/scss/book.scss_50fc8c04e12a2f59027287995557ceff.json @@ -0,0 +1 @@ +{"Target":"book.min.958cea7827621d6fbcb3acf091344c3e44e3d2a9428f9c3c38bb9eb37bf8c45d.css","MediaType":"text/css","Data":{"Integrity":"sha256-lYzqeCdiHW+8s6zwkTRMPkTj0qlCj5w8OLues3v4xF0="}} \ No newline at end of file diff --git a/site/static/images/index/banner.jpg b/site/static/images/index/banner.jpg new file mode 100644 index 0000000..8e14478 Binary files /dev/null and b/site/static/images/index/banner.jpg differ diff --git a/site/static/images/runtime/block_on_channel_send.jpg b/site/static/images/runtime/block_on_channel_send.jpg new file mode 100644 index 0000000..2462fa1 Binary files /dev/null and b/site/static/images/runtime/block_on_channel_send.jpg differ diff --git a/site/static/images/runtime/data_struct/map.png b/site/static/images/runtime/data_struct/map.png new file mode 100644 index 0000000..b2d2bfe Binary files /dev/null and b/site/static/images/runtime/data_struct/map.png differ diff --git a/site/static/images/runtime/data_struct/map_func_translate2.png b/site/static/images/runtime/data_struct/map_func_translate2.png new file mode 100644 index 0000000..761edec Binary files /dev/null and b/site/static/images/runtime/data_struct/map_func_translate2.png differ diff --git a/site/static/images/runtime/data_struct/map_function_translate.png b/site/static/images/runtime/data_struct/map_function_translate.png new file mode 100644 index 0000000..8ec419f Binary files /dev/null and b/site/static/images/runtime/data_struct/map_function_translate.png differ diff --git a/site/static/images/runtime/data_struct/map_tophash.png b/site/static/images/runtime/data_struct/map_tophash.png new file mode 100644 index 0000000..39e85b8 Binary files /dev/null and b/site/static/images/runtime/data_struct/map_tophash.png differ diff --git a/site/static/images/runtime/memory/gcphases.jpg b/site/static/images/runtime/memory/gcphases.jpg new file mode 100644 index 0000000..ecfd519 Binary files /dev/null and b/site/static/images/runtime/memory/gcphases.jpg differ diff --git a/site/static/images/runtime/memory/write_barrier_demo.jpg b/site/static/images/runtime/memory/write_barrier_demo.jpg new file mode 100644 index 0000000..9245d11 Binary files /dev/null and b/site/static/images/runtime/memory/write_barrier_demo.jpg differ diff --git a/site/static/images/runtime/schedule/sche_big.png b/site/static/images/runtime/schedule/sche_big.png new file mode 100644 index 0000000..0183c4f Binary files /dev/null and b/site/static/images/runtime/schedule/sche_big.png differ diff --git a/site/static/images/sync/syncPool.png b/site/static/images/sync/syncPool.png new file mode 100644 index 0000000..63c87a8 Binary files /dev/null and b/site/static/images/sync/syncPool.png differ diff --git a/site/themes/book/.github/workflows/main.yml b/site/themes/book/.github/workflows/main.yml new file mode 100644 index 0000000..67f73e1 --- /dev/null +++ b/site/themes/book/.github/workflows/main.yml @@ -0,0 +1,24 @@ +name: Build with Hugo + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + hugo-version: + - 'latest' + - '0.68.0' + steps: + - uses: actions/checkout@v2 + + - name: Setup Hugo + uses: peaceiris/actions-hugo@v2 + with: + hugo-version: ${{ matrix.hugo-version }} + extended: true + + - name: Run Hugo + working-directory: exampleSite + run: hugo --themesDir ../.. diff --git a/site/themes/book/.gitignore b/site/themes/book/.gitignore new file mode 100644 index 0000000..e52eb52 --- /dev/null +++ b/site/themes/book/.gitignore @@ -0,0 +1,3 @@ +public/ +exampleSite/public/ +.DS_Store diff --git a/site/themes/book/LICENSE b/site/themes/book/LICENSE new file mode 100644 index 0000000..e7a669a --- /dev/null +++ b/site/themes/book/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2018 Alex Shpak + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/site/themes/book/README.md b/site/themes/book/README.md new file mode 100644 index 0000000..c879150 --- /dev/null +++ b/site/themes/book/README.md @@ -0,0 +1,327 @@ +# Hugo Book Theme + +[![Hugo](https://img.shields.io/badge/hugo-0.68-blue.svg)](https://gohugo.io) +[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE) +![Build with Hugo](https://github.com/alex-shpak/hugo-book/workflows/Build%20with%20Hugo/badge.svg) + +### [Hugo](https://gohugo.io) documentation theme as simple as plain book + +![Screenshot](https://github.com/alex-shpak/hugo-book/blob/master/images/screenshot.png) + +- [Features](#features) +- [Requirements](#requirements) +- [Installation](#installation) +- [Menu](#menu) +- [Blog](#blog) +- [Configuration](#configuration) +- [Shortcodes](#shortcodes) +- [Versioning](#versioning) +- [Contributing](#contributing) + +## Features + +- Clean simple design +- Light and Mobile-Friendly +- Multi-language support +- Customisable +- Zero initial configuration +- Handy shortcodes +- Comments support +- Simple blog and taxonomy +- Primary features work without JavaScript +- Dark Mode + +## Requirements + +- Hugo 0.68 or higher +- Hugo extended version, read more [here](https://gohugo.io/news/0.48-relnotes/) + +## Installation + +Navigate to your hugo project root and run: + +``` +git submodule add https://github.com/alex-shpak/hugo-book themes/book +``` + +Then run hugo (or set `theme = "book"`/`theme: book` in configuration file) + +``` +hugo server --minify --theme book +``` + +### Creating site from scratch + +Below is an example on how to create a new site from scratch: + +```sh +hugo new site mydocs; cd mydocs +git init +git submodule add https://github.com/alex-shpak/hugo-book themes/book +cp -R themes/book/exampleSite/content . +``` + +```sh +hugo server --minify --theme book +``` + +## Menu + +### File tree menu (default) + +By default, the theme will render pages from the `content/docs` section as a menu in a tree structure. +You can set `title` and `weight` in the front matter of pages to adjust the order and titles in the menu. + +### Leaf bundle menu + +You can also use leaf bundle and the content of its `index.md` file as menu. +Given you have the following file structure: + +``` +├── content +│ ├── docs +│ │ ├── page-one.md +│ │ └── page-two.md +│ └── posts +│ ├── post-one.md +│ └── post-two.md +``` + +Create a file `content/menu/index.md` with the content: + +```md ++++ +headless = true ++++ + +- [Book Example]({{< relref "/docs/" >}}) + - [Page One]({{< relref "/docs/page-one" >}}) + - [Page Two]({{< relref "/docs/page-two" >}}) +- [Blog]({{< relref "/posts" >}}) +``` + +And Enable it by setting `BookMenuBundle: /menu` in Site configuration. + +- [Example menu](https://github.com/alex-shpak/hugo-book/blob/master/exampleSite/content/menu/index.md) +- [Example config file](https://github.com/alex-shpak/hugo-book/blob/master/exampleSite/config.yaml) +- [Leaf bundles](https://gohugo.io/content-management/page-bundles/) + +## Blog + +A simple blog is supported in the section `posts`. +A blog is not the primary usecase of this theme, so it has only minimal features. + +## Configuration + +### Site Configuration + +There are a few configuration options that you can add to your `config.toml` file. +You can also see the `yaml` example [here](https://github.com/alex-shpak/hugo-book/blob/master/exampleSite/config.yaml). + +```toml +# (Optional) Set Google Analytics if you use it to track your website. +# Always put it on the top of the configuration file, otherwise it won't work +googleAnalytics = "UA-XXXXXXXXX-X" + +# (Optional) If you provide a Disqus shortname, comments will be enabled on +# all pages. +disqusShortname = "my-site" + +# (Optional) Set this to true if you use capital letters in file names +disablePathToLower = true + +# (Optional) Set this to true to enable 'Last Modified by' date and git author +# information on 'doc' type pages. +enableGitInfo = true + +# (Optional) Theme is intended for documentation use, therefore it doesn't render taxonomy. +# You can remove related files with config below +disableKinds = ['taxonomy', 'taxonomyTerm'] + +[params] + # (Optional, default light) Sets color theme: light, dark or auto. + # Theme 'auto' switches between dark and light modes based on browser/os preferences + BookTheme = 'light' + + # (Optional, default true) Controls table of contents visibility on right side of pages. + # Start and end levels can be controlled with markup.tableOfContents setting. + # You can also specify this parameter per page in front matter. + BookToC = true + + # (Optional, default none) Set the path to a logo for the book. If the logo is + # /static/logo.png then the path would be 'logo.png' + BookLogo = 'logo.png' + + # (Optional, default none) Set leaf bundle to render as side menu + # When not specified file structure and weights will be used + BookMenuBundle = '/menu' + + # (Optional, default docs) Specify section of content to render as menu + # You can also set value to "*" to render all sections to menu + BookSection = 'docs' + + # Set source repository location. + # Used for 'Last Modified' and 'Edit this page' links. + BookRepo = 'https://github.com/alex-shpak/hugo-book' + + # Specifies commit portion of the link to the page's last modified commit hash for 'doc' page + # type. + # Required if 'BookRepo' param is set. + # Value used to construct a URL consisting of BookRepo/BookCommitPath/ + # Github uses 'commit', Bitbucket uses 'commits' + BookCommitPath = 'commit' + + # Enable 'Edit this page' links for 'doc' page type. + # Disabled by default. Uncomment to enable. Requires 'BookRepo' param. + # Path must point to the site directory. + BookEditPath = 'edit/master/exampleSite' + + # (Optional, default January 2, 2006) Configure the date format used on the pages + # - In git information + # - In blog posts + BookDateFormat = 'Jan 2, 2006' + + # (Optional, default true) Enables search function with flexsearch, + # Index is built on fly, therefore it might slowdown your website. + # Configuration for indexing can be adjusted in i18n folder per language. + BookSearch = true + + # (Optional, default true) Enables comments template on pages + # By default partials/docs/comments.html includes Disqus template + # See https://gohugo.io/content-management/comments/#configure-disqus + # Can be overwritten by same param in page frontmatter + BookComments = true + + # /!\ This is an experimental feature, might be removed or changed at any time + # (Optional, experimental, default false) Enables portable links and link checks in markdown pages. + # Portable links meant to work with text editors and let you write markdown without {{< relref >}} shortcode + # Theme will print warning if page referenced in markdown does not exists. + BookPortableLinks = true + + # /!\ This is an experimental feature, might be removed or changed at any time + # (Optional, experimental, default false) Enables service worker that caches visited pages and resources for offline use. + BookServiceWorker = true +``` + +### Multi-Language Support + +Theme supports Hugo's [multilingual mode](https://gohugo.io/content-management/multilingual/), just follow configuration guide there. You can also tweak search indexing configuration per language in `i18n` folder. + +### Page Configuration + +You can specify additional params in the front matter of individual pages: + +```toml +# Set type to 'docs' if you want to render page outside of configured section or if you render section other than 'docs' +type = 'docs' + +# Set page weight to re-arrange items in file-tree menu (if BookMenuBundle not set) +weight = 10 + +# (Optional) Set to 'true' to mark page as flat section in file-tree menu (if BookMenuBundle not set) +bookFlatSection = false + +# (Optional) Set to hide nested sections or pages at that level. Works only with file-tree menu mode +bookCollapseSection = true + +# (Optional) Set true to hide page or section from side menu (if BookMenuBundle not set) +bookHidden = false + +# (Optional) Set 'false' to hide ToC from page +bookToC = true + +# (Optional) If you have enabled BookComments for the site, you can disable it for specific pages. +bookComments = true + +# (Optional) Set to 'false' to exclude page from search index. +bookSearchExclude = true +``` + +### Partials + +There are few empty partials you can override in `layouts/partials/` + +| Partial | Placement | +| -------------------------------------------------- | ------------------------------------------- | +| `layouts/partials/docs/inject/head.html` | Before closing `` tag | +| `layouts/partials/docs/inject/body.html` | Before closing `` tag | +| `layouts/partials/docs/inject/footer.html` | After page footer content | +| `layouts/partials/docs/inject/menu-before.html` | At the beginning of `