]> Cypherpunks.ru repositories - gostls13.git/blob - src/runtime/pinner.go
runtime: clarify Pinner doc
[gostls13.git] / src / runtime / pinner.go
1 // Copyright 2023 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package runtime
6
7 import (
8         "runtime/internal/atomic"
9         "unsafe"
10 )
11
12 // A Pinner is a set of pinned Go objects. An object can be pinned with
13 // the Pin method and all pinned objects of a Pinner can be unpinned with the
14 // Unpin method.
15 type Pinner struct {
16         *pinner
17 }
18
19 // Pin pins a Go object, preventing it from being moved or freed by the garbage
20 // collector until the Unpin method has been called.
21 //
22 // A pointer to a pinned
23 // object can be directly stored in C memory or can be contained in Go memory
24 // passed to C functions. If the pinned object itself contains pointers to Go
25 // objects, these objects must be pinned separately if they are going to be
26 // accessed from C code.
27 //
28 // The argument must be a pointer of any type or an
29 // unsafe.Pointer. It must be the result of calling new,
30 // taking the address of a composite literal, or taking the address of a
31 // local variable. If one of these conditions is not met, Pin will panic.
32 func (p *Pinner) Pin(pointer any) {
33         if p.pinner == nil {
34                 // Check the pinner cache first.
35                 mp := acquirem()
36                 if pp := mp.p.ptr(); pp != nil {
37                         p.pinner = pp.pinnerCache
38                         pp.pinnerCache = nil
39                 }
40                 releasem(mp)
41
42                 if p.pinner == nil {
43                         // Didn't get anything from the pinner cache.
44                         p.pinner = new(pinner)
45                         p.refs = p.refStore[:0]
46
47                         // We set this finalizer once and never clear it. Thus, if the
48                         // pinner gets cached, we'll reuse it, along with its finalizer.
49                         // This lets us avoid the relatively expensive SetFinalizer call
50                         // when reusing from the cache. The finalizer however has to be
51                         // resilient to an empty pinner being finalized, which is done
52                         // by checking p.refs' length.
53                         SetFinalizer(p.pinner, func(i *pinner) {
54                                 if len(i.refs) != 0 {
55                                         i.unpin() // only required to make the test idempotent
56                                         pinnerLeakPanic()
57                                 }
58                         })
59                 }
60         }
61         ptr := pinnerGetPtr(&pointer)
62         setPinned(ptr, true)
63         p.refs = append(p.refs, ptr)
64 }
65
66 // Unpin unpins all pinned objects of the Pinner.
67 func (p *Pinner) Unpin() {
68         p.pinner.unpin()
69
70         mp := acquirem()
71         if pp := mp.p.ptr(); pp != nil && pp.pinnerCache == nil {
72                 // Put the pinner back in the cache, but only if the
73                 // cache is empty. If application code is reusing Pinners
74                 // on its own, we want to leave the backing store in place
75                 // so reuse is more efficient.
76                 pp.pinnerCache = p.pinner
77                 p.pinner = nil
78         }
79         releasem(mp)
80 }
81
82 const (
83         pinnerSize         = 64
84         pinnerRefStoreSize = (pinnerSize - unsafe.Sizeof([]unsafe.Pointer{})) / unsafe.Sizeof(unsafe.Pointer(nil))
85 )
86
87 type pinner struct {
88         refs     []unsafe.Pointer
89         refStore [pinnerRefStoreSize]unsafe.Pointer
90 }
91
92 func (p *pinner) unpin() {
93         if p == nil || p.refs == nil {
94                 return
95         }
96         for i := range p.refs {
97                 setPinned(p.refs[i], false)
98         }
99         // The following two lines make all pointers to references
100         // in p.refs unreachable, either by deleting them or dropping
101         // p.refs' backing store (if it was not backed by refStore).
102         p.refStore = [pinnerRefStoreSize]unsafe.Pointer{}
103         p.refs = p.refStore[:0]
104 }
105
106 func pinnerGetPtr(i *any) unsafe.Pointer {
107         e := efaceOf(i)
108         etyp := e._type
109         if etyp == nil {
110                 panic(errorString("runtime.Pinner: argument is nil"))
111         }
112         if kind := etyp.Kind_ & kindMask; kind != kindPtr && kind != kindUnsafePointer {
113                 panic(errorString("runtime.Pinner: argument is not a pointer: " + toRType(etyp).string()))
114         }
115         if inUserArenaChunk(uintptr(e.data)) {
116                 // Arena-allocated objects are not eligible for pinning.
117                 panic(errorString("runtime.Pinner: object was allocated into an arena"))
118         }
119         return e.data
120 }
121
122 // isPinned checks if a Go pointer is pinned.
123 // nosplit, because it's called from nosplit code in cgocheck.
124 //
125 //go:nosplit
126 func isPinned(ptr unsafe.Pointer) bool {
127         span := spanOfHeap(uintptr(ptr))
128         if span == nil {
129                 // this code is only called for Go pointer, so this must be a
130                 // linker-allocated global object.
131                 return true
132         }
133         pinnerBits := span.getPinnerBits()
134         // these pinnerBits might get unlinked by a concurrently running sweep, but
135         // that's OK because gcBits don't get cleared until the following GC cycle
136         // (nextMarkBitArenaEpoch)
137         if pinnerBits == nil {
138                 return false
139         }
140         objIndex := span.objIndex(uintptr(ptr))
141         pinState := pinnerBits.ofObject(objIndex)
142         KeepAlive(ptr) // make sure ptr is alive until we are done so the span can't be freed
143         return pinState.isPinned()
144 }
145
146 // setPinned marks or unmarks a Go pointer as pinned.
147 func setPinned(ptr unsafe.Pointer, pin bool) {
148         span := spanOfHeap(uintptr(ptr))
149         if span == nil {
150                 if isGoPointerWithoutSpan(ptr) {
151                         // this is a linker-allocated or zero size object, nothing to do.
152                         return
153                 }
154                 panic(errorString("runtime.Pinner.Pin: argument is not a Go pointer"))
155         }
156
157         // ensure that the span is swept, b/c sweeping accesses the specials list
158         // w/o locks.
159         mp := acquirem()
160         span.ensureSwept()
161         KeepAlive(ptr) // make sure ptr is still alive after span is swept
162
163         objIndex := span.objIndex(uintptr(ptr))
164
165         lock(&span.speciallock) // guard against concurrent calls of setPinned on same span
166
167         pinnerBits := span.getPinnerBits()
168         if pinnerBits == nil {
169                 pinnerBits = span.newPinnerBits()
170                 span.setPinnerBits(pinnerBits)
171         }
172         pinState := pinnerBits.ofObject(objIndex)
173         if pin {
174                 if pinState.isPinned() {
175                         // multiple pins on same object, set multipin bit
176                         pinState.setMultiPinned(true)
177                         // and increase the pin counter
178                         // TODO(mknyszek): investigate if systemstack is necessary here
179                         systemstack(func() {
180                                 offset := objIndex * span.elemsize
181                                 span.incPinCounter(offset)
182                         })
183                 } else {
184                         // set pin bit
185                         pinState.setPinned(true)
186                 }
187         } else {
188                 // unpin
189                 if pinState.isPinned() {
190                         if pinState.isMultiPinned() {
191                                 var exists bool
192                                 // TODO(mknyszek): investigate if systemstack is necessary here
193                                 systemstack(func() {
194                                         offset := objIndex * span.elemsize
195                                         exists = span.decPinCounter(offset)
196                                 })
197                                 if !exists {
198                                         // counter is 0, clear multipin bit
199                                         pinState.setMultiPinned(false)
200                                 }
201                         } else {
202                                 // no multipins recorded. unpin object.
203                                 pinState.setPinned(false)
204                         }
205                 } else {
206                         // unpinning unpinned object, bail out
207                         throw("runtime.Pinner: object already unpinned")
208                 }
209         }
210         unlock(&span.speciallock)
211         releasem(mp)
212         return
213 }
214
215 type pinState struct {
216         bytep   *uint8
217         byteVal uint8
218         mask    uint8
219 }
220
221 // nosplit, because it's called by isPinned, which is nosplit
222 //
223 //go:nosplit
224 func (v *pinState) isPinned() bool {
225         return (v.byteVal & v.mask) != 0
226 }
227
228 func (v *pinState) isMultiPinned() bool {
229         return (v.byteVal & (v.mask << 1)) != 0
230 }
231
232 func (v *pinState) setPinned(val bool) {
233         v.set(val, false)
234 }
235
236 func (v *pinState) setMultiPinned(val bool) {
237         v.set(val, true)
238 }
239
240 // set sets the pin bit of the pinState to val. If multipin is true, it
241 // sets/unsets the multipin bit instead.
242 func (v *pinState) set(val bool, multipin bool) {
243         mask := v.mask
244         if multipin {
245                 mask <<= 1
246         }
247         if val {
248                 atomic.Or8(v.bytep, mask)
249         } else {
250                 atomic.And8(v.bytep, ^mask)
251         }
252 }
253
254 // pinnerBits is the same type as gcBits but has different methods.
255 type pinnerBits gcBits
256
257 // ofObject returns the pinState of the n'th object.
258 // nosplit, because it's called by isPinned, which is nosplit
259 //
260 //go:nosplit
261 func (p *pinnerBits) ofObject(n uintptr) pinState {
262         bytep, mask := (*gcBits)(p).bitp(n * 2)
263         byteVal := atomic.Load8(bytep)
264         return pinState{bytep, byteVal, mask}
265 }
266
267 func (s *mspan) pinnerBitSize() uintptr {
268         return divRoundUp(s.nelems*2, 8)
269 }
270
271 // newPinnerBits returns a pointer to 8 byte aligned bytes to be used for this
272 // span's pinner bits. newPinneBits is used to mark objects that are pinned.
273 // They are copied when the span is swept.
274 func (s *mspan) newPinnerBits() *pinnerBits {
275         return (*pinnerBits)(newMarkBits(s.nelems * 2))
276 }
277
278 // nosplit, because it's called by isPinned, which is nosplit
279 //
280 //go:nosplit
281 func (s *mspan) getPinnerBits() *pinnerBits {
282         return (*pinnerBits)(atomic.Loadp(unsafe.Pointer(&s.pinnerBits)))
283 }
284
285 func (s *mspan) setPinnerBits(p *pinnerBits) {
286         atomicstorep(unsafe.Pointer(&s.pinnerBits), unsafe.Pointer(p))
287 }
288
289 // refreshPinnerBits replaces pinnerBits with a fresh copy in the arenas for the
290 // next GC cycle. If it does not contain any pinned objects, pinnerBits of the
291 // span is set to nil.
292 func (s *mspan) refreshPinnerBits() {
293         p := s.getPinnerBits()
294         if p == nil {
295                 return
296         }
297
298         hasPins := false
299         bytes := alignUp(s.pinnerBitSize(), 8)
300
301         // Iterate over each 8-byte chunk and check for pins. Note that
302         // newPinnerBits guarantees that pinnerBits will be 8-byte aligned, so we
303         // don't have to worry about edge cases, irrelevant bits will simply be
304         // zero.
305         for _, x := range unsafe.Slice((*uint64)(unsafe.Pointer(&p.x)), bytes/8) {
306                 if x != 0 {
307                         hasPins = true
308                         break
309                 }
310         }
311
312         if hasPins {
313                 newPinnerBits := s.newPinnerBits()
314                 memmove(unsafe.Pointer(&newPinnerBits.x), unsafe.Pointer(&p.x), bytes)
315                 s.setPinnerBits(newPinnerBits)
316         } else {
317                 s.setPinnerBits(nil)
318         }
319 }
320
321 // incPinCounter is only called for multiple pins of the same object and records
322 // the _additional_ pins.
323 func (span *mspan) incPinCounter(offset uintptr) {
324         var rec *specialPinCounter
325         ref, exists := span.specialFindSplicePoint(offset, _KindSpecialPinCounter)
326         if !exists {
327                 lock(&mheap_.speciallock)
328                 rec = (*specialPinCounter)(mheap_.specialPinCounterAlloc.alloc())
329                 unlock(&mheap_.speciallock)
330                 // splice in record, fill in offset.
331                 rec.special.offset = uint16(offset)
332                 rec.special.kind = _KindSpecialPinCounter
333                 rec.special.next = *ref
334                 *ref = (*special)(unsafe.Pointer(rec))
335                 spanHasSpecials(span)
336         } else {
337                 rec = (*specialPinCounter)(unsafe.Pointer(*ref))
338         }
339         rec.counter++
340 }
341
342 // decPinCounter decreases the counter. If the counter reaches 0, the counter
343 // special is deleted and false is returned. Otherwise true is returned.
344 func (span *mspan) decPinCounter(offset uintptr) bool {
345         ref, exists := span.specialFindSplicePoint(offset, _KindSpecialPinCounter)
346         if !exists {
347                 throw("runtime.Pinner: decreased non-existing pin counter")
348         }
349         counter := (*specialPinCounter)(unsafe.Pointer(*ref))
350         counter.counter--
351         if counter.counter == 0 {
352                 *ref = counter.special.next
353                 if span.specials == nil {
354                         spanHasNoSpecials(span)
355                 }
356                 lock(&mheap_.speciallock)
357                 mheap_.specialPinCounterAlloc.free(unsafe.Pointer(counter))
358                 unlock(&mheap_.speciallock)
359                 return false
360         }
361         return true
362 }
363
364 // only for tests
365 func pinnerGetPinCounter(addr unsafe.Pointer) *uintptr {
366         _, span, objIndex := findObject(uintptr(addr), 0, 0)
367         offset := objIndex * span.elemsize
368         t, exists := span.specialFindSplicePoint(offset, _KindSpecialPinCounter)
369         if !exists {
370                 return nil
371         }
372         counter := (*specialPinCounter)(unsafe.Pointer(*t))
373         return &counter.counter
374 }
375
376 // to be able to test that the GC panics when a pinned pointer is leaking, this
377 // panic function is a variable, that can be overwritten by a test.
378 var pinnerLeakPanic = func() {
379         panic(errorString("runtime.Pinner: found leaking pinned pointer; forgot to call Unpin()?"))
380 }