Source file
src/runtime/vgetrandom_linux.go
1
2
3
4
5
6
7 package runtime
8
9 import (
10 "internal/cpu"
11 "unsafe"
12 )
13
14
15 func vgetrandom1(buf *byte, length uintptr, flags uint32, state uintptr, stateSize uintptr) int
16
17 var vgetrandomAlloc struct {
18 states []uintptr
19 statesLock mutex
20 stateSize uintptr
21 mmapProt int32
22 mmapFlags int32
23 }
24
25 func vgetrandomInit() {
26 if vdsoGetrandomSym == 0 {
27 return
28 }
29
30 var params struct {
31 SizeOfOpaqueState uint32
32 MmapProt uint32
33 MmapFlags uint32
34 reserved [13]uint32
35 }
36 if vgetrandom1(nil, 0, 0, uintptr(unsafe.Pointer(¶ms)), ^uintptr(0)) != 0 {
37 return
38 }
39 vgetrandomAlloc.stateSize = uintptr(params.SizeOfOpaqueState)
40 vgetrandomAlloc.mmapProt = int32(params.MmapProt)
41 vgetrandomAlloc.mmapFlags = int32(params.MmapFlags)
42
43 lockInit(&vgetrandomAlloc.statesLock, lockRankLeafRank)
44 }
45
46 func vgetrandomGetState() uintptr {
47 lock(&vgetrandomAlloc.statesLock)
48 if len(vgetrandomAlloc.states) == 0 {
49 num := uintptr(ncpu)
50 stateSizeCacheAligned := (vgetrandomAlloc.stateSize + cpu.CacheLineSize - 1) &^ (cpu.CacheLineSize - 1)
51 allocSize := (num*stateSizeCacheAligned + physPageSize - 1) &^ (physPageSize - 1)
52 num = (physPageSize / stateSizeCacheAligned) * (allocSize / physPageSize)
53 p, err := mmap(nil, allocSize, vgetrandomAlloc.mmapProt, vgetrandomAlloc.mmapFlags, -1, 0)
54 if err != 0 {
55 unlock(&vgetrandomAlloc.statesLock)
56 return 0
57 }
58 setVMAName(p, allocSize, "getrandom states")
59 newBlock := uintptr(p)
60 if vgetrandomAlloc.states == nil {
61 vgetrandomAlloc.states = make([]uintptr, 0, num)
62 }
63 for i := uintptr(0); i < num; i++ {
64 if (newBlock&(physPageSize-1))+vgetrandomAlloc.stateSize > physPageSize {
65 newBlock = (newBlock + physPageSize - 1) &^ (physPageSize - 1)
66 }
67 vgetrandomAlloc.states = append(vgetrandomAlloc.states, newBlock)
68 newBlock += stateSizeCacheAligned
69 }
70 }
71 state := vgetrandomAlloc.states[len(vgetrandomAlloc.states)-1]
72 vgetrandomAlloc.states = vgetrandomAlloc.states[:len(vgetrandomAlloc.states)-1]
73 unlock(&vgetrandomAlloc.statesLock)
74 return state
75 }
76
77
78
79
80 func vgetrandomDestroy(mp *m) {
81 if mp.vgetrandomState == 0 {
82 return
83 }
84
85 lock(&vgetrandomAlloc.statesLock)
86 vgetrandomAlloc.states = append(vgetrandomAlloc.states, mp.vgetrandomState)
87 unlock(&vgetrandomAlloc.statesLock)
88 }
89
90
91
92
93 func vgetrandom(p []byte, flags uint32) (ret int, supported bool) {
94 if vgetrandomAlloc.stateSize == 0 {
95 return -1, false
96 }
97
98
99
100
101
102
103
104
105
106
107
108 mp := getg().m
109
110 if mp.vgetrandomState == 0 {
111 mp.locks++
112 state := vgetrandomGetState()
113 mp.locks--
114 if state == 0 {
115 return -1, false
116 }
117 mp.vgetrandomState = state
118 }
119 return vgetrandom1(unsafe.SliceData(p), uintptr(len(p)), flags, mp.vgetrandomState, vgetrandomAlloc.stateSize), true
120 }
121
View as plain text