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 newBlock := uintptr(p)
59 if vgetrandomAlloc.states == nil {
60 vgetrandomAlloc.states = make([]uintptr, 0, num)
61 }
62 for i := uintptr(0); i < num; i++ {
63 if (newBlock&(physPageSize-1))+vgetrandomAlloc.stateSize > physPageSize {
64 newBlock = (newBlock + physPageSize - 1) &^ (physPageSize - 1)
65 }
66 vgetrandomAlloc.states = append(vgetrandomAlloc.states, newBlock)
67 newBlock += stateSizeCacheAligned
68 }
69 }
70 state := vgetrandomAlloc.states[len(vgetrandomAlloc.states)-1]
71 vgetrandomAlloc.states = vgetrandomAlloc.states[:len(vgetrandomAlloc.states)-1]
72 unlock(&vgetrandomAlloc.statesLock)
73 return state
74 }
75
76 func vgetrandomPutState(state uintptr) {
77 lock(&vgetrandomAlloc.statesLock)
78 vgetrandomAlloc.states = append(vgetrandomAlloc.states, state)
79 unlock(&vgetrandomAlloc.statesLock)
80 }
81
82
83
84
85 func vgetrandom(p []byte, flags uint32) (ret int, supported bool) {
86 if vgetrandomAlloc.stateSize == 0 {
87 return -1, false
88 }
89
90
91
92
93
94
95
96
97
98
99
100 mp := getg().m
101
102 if mp.vgetrandomState == 0 {
103 mp.locks++
104 state := vgetrandomGetState()
105 mp.locks--
106 if state == 0 {
107 return -1, false
108 }
109 mp.vgetrandomState = state
110 }
111 return vgetrandom1(unsafe.SliceData(p), uintptr(len(p)), flags, mp.vgetrandomState, vgetrandomAlloc.stateSize), true
112 }
113
View as plain text