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.
8 "runtime/internal/atomic"
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
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.
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.
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) {
34 // Check the pinner cache first.
36 if pp := mp.p.ptr(); pp != nil {
37 p.pinner = pp.pinnerCache
43 // Didn't get anything from the pinner cache.
44 p.pinner = new(pinner)
45 p.refs = p.refStore[:0]
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) {
55 i.unpin() // only required to make the test idempotent
61 ptr := pinnerGetPtr(&pointer)
63 p.refs = append(p.refs, ptr)
66 // Unpin unpins all pinned objects of the Pinner.
67 func (p *Pinner) Unpin() {
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
84 pinnerRefStoreSize = (pinnerSize - unsafe.Sizeof([]unsafe.Pointer{})) / unsafe.Sizeof(unsafe.Pointer(nil))
89 refStore [pinnerRefStoreSize]unsafe.Pointer
92 func (p *pinner) unpin() {
93 if p == nil || p.refs == nil {
96 for i := range p.refs {
97 setPinned(p.refs[i], false)
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]
106 func pinnerGetPtr(i *any) unsafe.Pointer {
110 panic(errorString("runtime.Pinner: argument is nil"))
112 if kind := etyp.Kind_ & kindMask; kind != kindPtr && kind != kindUnsafePointer {
113 panic(errorString("runtime.Pinner: argument is not a pointer: " + toRType(etyp).string()))
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"))
122 // isPinned checks if a Go pointer is pinned.
123 // nosplit, because it's called from nosplit code in cgocheck.
126 func isPinned(ptr unsafe.Pointer) bool {
127 span := spanOfHeap(uintptr(ptr))
129 // this code is only called for Go pointer, so this must be a
130 // linker-allocated global object.
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 {
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()
146 // setPinned marks or unmarks a Go pointer as pinned.
147 func setPinned(ptr unsafe.Pointer, pin bool) {
148 span := spanOfHeap(uintptr(ptr))
150 if isGoPointerWithoutSpan(ptr) {
151 // this is a linker-allocated or zero size object, nothing to do.
154 panic(errorString("runtime.Pinner.Pin: argument is not a Go pointer"))
157 // ensure that the span is swept, b/c sweeping accesses the specials list
161 KeepAlive(ptr) // make sure ptr is still alive after span is swept
163 objIndex := span.objIndex(uintptr(ptr))
165 lock(&span.speciallock) // guard against concurrent calls of setPinned on same span
167 pinnerBits := span.getPinnerBits()
168 if pinnerBits == nil {
169 pinnerBits = span.newPinnerBits()
170 span.setPinnerBits(pinnerBits)
172 pinState := pinnerBits.ofObject(objIndex)
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
180 offset := objIndex * span.elemsize
181 span.incPinCounter(offset)
185 pinState.setPinned(true)
189 if pinState.isPinned() {
190 if pinState.isMultiPinned() {
192 // TODO(mknyszek): investigate if systemstack is necessary here
194 offset := objIndex * span.elemsize
195 exists = span.decPinCounter(offset)
198 // counter is 0, clear multipin bit
199 pinState.setMultiPinned(false)
202 // no multipins recorded. unpin object.
203 pinState.setPinned(false)
206 // unpinning unpinned object, bail out
207 throw("runtime.Pinner: object already unpinned")
210 unlock(&span.speciallock)
215 type pinState struct {
221 // nosplit, because it's called by isPinned, which is nosplit
224 func (v *pinState) isPinned() bool {
225 return (v.byteVal & v.mask) != 0
228 func (v *pinState) isMultiPinned() bool {
229 return (v.byteVal & (v.mask << 1)) != 0
232 func (v *pinState) setPinned(val bool) {
236 func (v *pinState) setMultiPinned(val bool) {
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) {
248 atomic.Or8(v.bytep, mask)
250 atomic.And8(v.bytep, ^mask)
254 // pinnerBits is the same type as gcBits but has different methods.
255 type pinnerBits gcBits
257 // ofObject returns the pinState of the n'th object.
258 // nosplit, because it's called by isPinned, which is 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}
267 func (s *mspan) pinnerBitSize() uintptr {
268 return divRoundUp(s.nelems*2, 8)
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))
278 // nosplit, because it's called by isPinned, which is nosplit
281 func (s *mspan) getPinnerBits() *pinnerBits {
282 return (*pinnerBits)(atomic.Loadp(unsafe.Pointer(&s.pinnerBits)))
285 func (s *mspan) setPinnerBits(p *pinnerBits) {
286 atomicstorep(unsafe.Pointer(&s.pinnerBits), unsafe.Pointer(p))
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()
299 bytes := alignUp(s.pinnerBitSize(), 8)
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
305 for _, x := range unsafe.Slice((*uint64)(unsafe.Pointer(&p.x)), bytes/8) {
313 newPinnerBits := s.newPinnerBits()
314 memmove(unsafe.Pointer(&newPinnerBits.x), unsafe.Pointer(&p.x), bytes)
315 s.setPinnerBits(newPinnerBits)
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)
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)
337 rec = (*specialPinCounter)(unsafe.Pointer(*ref))
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)
347 throw("runtime.Pinner: decreased non-existing pin counter")
349 counter := (*specialPinCounter)(unsafe.Pointer(*ref))
351 if counter.counter == 0 {
352 *ref = counter.special.next
353 if span.specials == nil {
354 spanHasNoSpecials(span)
356 lock(&mheap_.speciallock)
357 mheap_.specialPinCounterAlloc.free(unsafe.Pointer(counter))
358 unlock(&mheap_.speciallock)
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)
372 counter := (*specialPinCounter)(unsafe.Pointer(*t))
373 return &counter.counter
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()?"))