github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/runtime/mbarrier.go (about)

     1  // Copyright 2015 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  // Garbage collector: write barriers.
     6  //
     7  // For the concurrent garbage collector, the Go compiler implements
     8  // updates to pointer-valued fields that may be in heap objects by
     9  // emitting calls to write barriers. The main write barrier for
    10  // individual pointer writes is gcWriteBarrier and is implemented in
    11  // assembly. This file contains write barrier entry points for bulk
    12  // operations. See also mwbbuf.go.
    13  
    14  package runtime
    15  
    16  import (
    17  	"internal/abi"
    18  	"internal/goarch"
    19  	"internal/goexperiment"
    20  	"unsafe"
    21  )
    22  
    23  // Go uses a hybrid barrier that combines a Yuasa-style deletion
    24  // barrier—which shades the object whose reference is being
    25  // overwritten—with Dijkstra insertion barrier—which shades the object
    26  // whose reference is being written. The insertion part of the barrier
    27  // is necessary while the calling goroutine's stack is grey. In
    28  // pseudocode, the barrier is:
    29  //
    30  //     writePointer(slot, ptr):
    31  //         shade(*slot)
    32  //         if current stack is grey:
    33  //             shade(ptr)
    34  //         *slot = ptr
    35  //
    36  // slot is the destination in Go code.
    37  // ptr is the value that goes into the slot in Go code.
    38  //
    39  // Shade indicates that it has seen a white pointer by adding the referent
    40  // to wbuf as well as marking it.
    41  //
    42  // The two shades and the condition work together to prevent a mutator
    43  // from hiding an object from the garbage collector:
    44  //
    45  // 1. shade(*slot) prevents a mutator from hiding an object by moving
    46  // the sole pointer to it from the heap to its stack. If it attempts
    47  // to unlink an object from the heap, this will shade it.
    48  //
    49  // 2. shade(ptr) prevents a mutator from hiding an object by moving
    50  // the sole pointer to it from its stack into a black object in the
    51  // heap. If it attempts to install the pointer into a black object,
    52  // this will shade it.
    53  //
    54  // 3. Once a goroutine's stack is black, the shade(ptr) becomes
    55  // unnecessary. shade(ptr) prevents hiding an object by moving it from
    56  // the stack to the heap, but this requires first having a pointer
    57  // hidden on the stack. Immediately after a stack is scanned, it only
    58  // points to shaded objects, so it's not hiding anything, and the
    59  // shade(*slot) prevents it from hiding any other pointers on its
    60  // stack.
    61  //
    62  // For a detailed description of this barrier and proof of
    63  // correctness, see https://github.com/golang/proposal/blob/master/design/17503-eliminate-rescan.md
    64  //
    65  //
    66  //
    67  // Dealing with memory ordering:
    68  //
    69  // Both the Yuasa and Dijkstra barriers can be made conditional on the
    70  // color of the object containing the slot. We chose not to make these
    71  // conditional because the cost of ensuring that the object holding
    72  // the slot doesn't concurrently change color without the mutator
    73  // noticing seems prohibitive.
    74  //
    75  // Consider the following example where the mutator writes into
    76  // a slot and then loads the slot's mark bit while the GC thread
    77  // writes to the slot's mark bit and then as part of scanning reads
    78  // the slot.
    79  //
    80  // Initially both [slot] and [slotmark] are 0 (nil)
    81  // Mutator thread          GC thread
    82  // st [slot], ptr          st [slotmark], 1
    83  //
    84  // ld r1, [slotmark]       ld r2, [slot]
    85  //
    86  // Without an expensive memory barrier between the st and the ld, the final
    87  // result on most HW (including 386/amd64) can be r1==r2==0. This is a classic
    88  // example of what can happen when loads are allowed to be reordered with older
    89  // stores (avoiding such reorderings lies at the heart of the classic
    90  // Peterson/Dekker algorithms for mutual exclusion). Rather than require memory
    91  // barriers, which will slow down both the mutator and the GC, we always grey
    92  // the ptr object regardless of the slot's color.
    93  //
    94  // Another place where we intentionally omit memory barriers is when
    95  // accessing mheap_.arena_used to check if a pointer points into the
    96  // heap. On relaxed memory machines, it's possible for a mutator to
    97  // extend the size of the heap by updating arena_used, allocate an
    98  // object from this new region, and publish a pointer to that object,
    99  // but for tracing running on another processor to observe the pointer
   100  // but use the old value of arena_used. In this case, tracing will not
   101  // mark the object, even though it's reachable. However, the mutator
   102  // is guaranteed to execute a write barrier when it publishes the
   103  // pointer, so it will take care of marking the object. A general
   104  // consequence of this is that the garbage collector may cache the
   105  // value of mheap_.arena_used. (See issue #9984.)
   106  //
   107  //
   108  // Stack writes:
   109  //
   110  // The compiler omits write barriers for writes to the current frame,
   111  // but if a stack pointer has been passed down the call stack, the
   112  // compiler will generate a write barrier for writes through that
   113  // pointer (because it doesn't know it's not a heap pointer).
   114  //
   115  // One might be tempted to ignore the write barrier if slot points
   116  // into to the stack. Don't do it! Mark termination only re-scans
   117  // frames that have potentially been active since the concurrent scan,
   118  // so it depends on write barriers to track changes to pointers in
   119  // stack frames that have not been active.
   120  //
   121  //
   122  // Global writes:
   123  //
   124  // The Go garbage collector requires write barriers when heap pointers
   125  // are stored in globals. Many garbage collectors ignore writes to
   126  // globals and instead pick up global -> heap pointers during
   127  // termination. This increases pause time, so we instead rely on write
   128  // barriers for writes to globals so that we don't have to rescan
   129  // global during mark termination.
   130  //
   131  //
   132  // Publication ordering:
   133  //
   134  // The write barrier is *pre-publication*, meaning that the write
   135  // barrier happens prior to the *slot = ptr write that may make ptr
   136  // reachable by some goroutine that currently cannot reach it.
   137  //
   138  //
   139  // Signal handler pointer writes:
   140  //
   141  // In general, the signal handler cannot safely invoke the write
   142  // barrier because it may run without a P or even during the write
   143  // barrier.
   144  //
   145  // There is exactly one exception: profbuf.go omits a barrier during
   146  // signal handler profile logging. That's safe only because of the
   147  // deletion barrier. See profbuf.go for a detailed argument. If we
   148  // remove the deletion barrier, we'll have to work out a new way to
   149  // handle the profile logging.
   150  
   151  // typedmemmove copies a value of type typ to dst from src.
   152  // Must be nosplit, see #16026.
   153  //
   154  // TODO: Perfect for go:nosplitrec since we can't have a safe point
   155  // anywhere in the bulk barrier or memmove.
   156  //
   157  //go:nosplit
   158  func typedmemmove(typ *abi.Type, dst, src unsafe.Pointer) {
   159  	if dst == src {
   160  		return
   161  	}
   162  	if writeBarrier.needed && typ.PtrBytes != 0 {
   163  		bulkBarrierPreWrite(uintptr(dst), uintptr(src), typ.PtrBytes)
   164  	}
   165  	// There's a race here: if some other goroutine can write to
   166  	// src, it may change some pointer in src after we've
   167  	// performed the write barrier but before we perform the
   168  	// memory copy. This safe because the write performed by that
   169  	// other goroutine must also be accompanied by a write
   170  	// barrier, so at worst we've unnecessarily greyed the old
   171  	// pointer that was in src.
   172  	memmove(dst, src, typ.Size_)
   173  	if goexperiment.CgoCheck2 {
   174  		cgoCheckMemmove2(typ, dst, src, 0, typ.Size_)
   175  	}
   176  }
   177  
   178  // wbZero performs the write barrier operations necessary before
   179  // zeroing a region of memory at address dst of type typ.
   180  // Does not actually do the zeroing.
   181  //
   182  //go:nowritebarrierrec
   183  //go:nosplit
   184  func wbZero(typ *_type, dst unsafe.Pointer) {
   185  	bulkBarrierPreWrite(uintptr(dst), 0, typ.PtrBytes)
   186  }
   187  
   188  // wbMove performs the write barrier operations necessary before
   189  // copying a region of memory from src to dst of type typ.
   190  // Does not actually do the copying.
   191  //
   192  //go:nowritebarrierrec
   193  //go:nosplit
   194  func wbMove(typ *_type, dst, src unsafe.Pointer) {
   195  	bulkBarrierPreWrite(uintptr(dst), uintptr(src), typ.PtrBytes)
   196  }
   197  
   198  //go:linkname reflect_typedmemmove reflect.typedmemmove
   199  func reflect_typedmemmove(typ *_type, dst, src unsafe.Pointer) {
   200  	if raceenabled {
   201  		raceWriteObjectPC(typ, dst, getcallerpc(), abi.FuncPCABIInternal(reflect_typedmemmove))
   202  		raceReadObjectPC(typ, src, getcallerpc(), abi.FuncPCABIInternal(reflect_typedmemmove))
   203  	}
   204  	if msanenabled {
   205  		msanwrite(dst, typ.Size_)
   206  		msanread(src, typ.Size_)
   207  	}
   208  	if asanenabled {
   209  		asanwrite(dst, typ.Size_)
   210  		asanread(src, typ.Size_)
   211  	}
   212  	typedmemmove(typ, dst, src)
   213  }
   214  
   215  //go:linkname reflectlite_typedmemmove internal/reflectlite.typedmemmove
   216  func reflectlite_typedmemmove(typ *_type, dst, src unsafe.Pointer) {
   217  	reflect_typedmemmove(typ, dst, src)
   218  }
   219  
   220  // reflectcallmove is invoked by reflectcall to copy the return values
   221  // out of the stack and into the heap, invoking the necessary write
   222  // barriers. dst, src, and size describe the return value area to
   223  // copy. typ describes the entire frame (not just the return values).
   224  // typ may be nil, which indicates write barriers are not needed.
   225  //
   226  // It must be nosplit and must only call nosplit functions because the
   227  // stack map of reflectcall is wrong.
   228  //
   229  //go:nosplit
   230  func reflectcallmove(typ *_type, dst, src unsafe.Pointer, size uintptr, regs *abi.RegArgs) {
   231  	if writeBarrier.needed && typ != nil && typ.PtrBytes != 0 && size >= goarch.PtrSize {
   232  		bulkBarrierPreWrite(uintptr(dst), uintptr(src), size)
   233  	}
   234  	memmove(dst, src, size)
   235  
   236  	// Move pointers returned in registers to a place where the GC can see them.
   237  	for i := range regs.Ints {
   238  		if regs.ReturnIsPtr.Get(i) {
   239  			regs.Ptrs[i] = unsafe.Pointer(regs.Ints[i])
   240  		}
   241  	}
   242  }
   243  
   244  //go:nosplit
   245  func typedslicecopy(typ *_type, dstPtr unsafe.Pointer, dstLen int, srcPtr unsafe.Pointer, srcLen int) int {
   246  	n := dstLen
   247  	if n > srcLen {
   248  		n = srcLen
   249  	}
   250  	if n == 0 {
   251  		return 0
   252  	}
   253  
   254  	// The compiler emits calls to typedslicecopy before
   255  	// instrumentation runs, so unlike the other copying and
   256  	// assignment operations, it's not instrumented in the calling
   257  	// code and needs its own instrumentation.
   258  	if raceenabled {
   259  		callerpc := getcallerpc()
   260  		pc := abi.FuncPCABIInternal(slicecopy)
   261  		racewriterangepc(dstPtr, uintptr(n)*typ.Size_, callerpc, pc)
   262  		racereadrangepc(srcPtr, uintptr(n)*typ.Size_, callerpc, pc)
   263  	}
   264  	if msanenabled {
   265  		msanwrite(dstPtr, uintptr(n)*typ.Size_)
   266  		msanread(srcPtr, uintptr(n)*typ.Size_)
   267  	}
   268  	if asanenabled {
   269  		asanwrite(dstPtr, uintptr(n)*typ.Size_)
   270  		asanread(srcPtr, uintptr(n)*typ.Size_)
   271  	}
   272  
   273  	if goexperiment.CgoCheck2 {
   274  		cgoCheckSliceCopy(typ, dstPtr, srcPtr, n)
   275  	}
   276  
   277  	if dstPtr == srcPtr {
   278  		return n
   279  	}
   280  
   281  	// Note: No point in checking typ.PtrBytes here:
   282  	// compiler only emits calls to typedslicecopy for types with pointers,
   283  	// and growslice and reflect_typedslicecopy check for pointers
   284  	// before calling typedslicecopy.
   285  	size := uintptr(n) * typ.Size_
   286  	if writeBarrier.needed {
   287  		pwsize := size - typ.Size_ + typ.PtrBytes
   288  		bulkBarrierPreWrite(uintptr(dstPtr), uintptr(srcPtr), pwsize)
   289  	}
   290  	// See typedmemmove for a discussion of the race between the
   291  	// barrier and memmove.
   292  	memmove(dstPtr, srcPtr, size)
   293  	return n
   294  }
   295  
   296  //go:linkname reflect_typedslicecopy reflect.typedslicecopy
   297  func reflect_typedslicecopy(elemType *_type, dst, src slice) int {
   298  	if elemType.PtrBytes == 0 {
   299  		return slicecopy(dst.array, dst.len, src.array, src.len, elemType.Size_)
   300  	}
   301  	return typedslicecopy(elemType, dst.array, dst.len, src.array, src.len)
   302  }
   303  
   304  // typedmemclr clears the typed memory at ptr with type typ. The
   305  // memory at ptr must already be initialized (and hence in type-safe
   306  // state). If the memory is being initialized for the first time, see
   307  // memclrNoHeapPointers.
   308  //
   309  // If the caller knows that typ has pointers, it can alternatively
   310  // call memclrHasPointers.
   311  //
   312  // TODO: A "go:nosplitrec" annotation would be perfect for this.
   313  //
   314  //go:nosplit
   315  func typedmemclr(typ *_type, ptr unsafe.Pointer) {
   316  	if writeBarrier.needed && typ.PtrBytes != 0 {
   317  		bulkBarrierPreWrite(uintptr(ptr), 0, typ.PtrBytes)
   318  	}
   319  	memclrNoHeapPointers(ptr, typ.Size_)
   320  }
   321  
   322  //go:linkname reflect_typedmemclr reflect.typedmemclr
   323  func reflect_typedmemclr(typ *_type, ptr unsafe.Pointer) {
   324  	typedmemclr(typ, ptr)
   325  }
   326  
   327  //go:linkname reflect_typedmemclrpartial reflect.typedmemclrpartial
   328  func reflect_typedmemclrpartial(typ *_type, ptr unsafe.Pointer, off, size uintptr) {
   329  	if writeBarrier.needed && typ.PtrBytes != 0 {
   330  		bulkBarrierPreWrite(uintptr(ptr), 0, size)
   331  	}
   332  	memclrNoHeapPointers(ptr, size)
   333  }
   334  
   335  //go:linkname reflect_typedarrayclear reflect.typedarrayclear
   336  func reflect_typedarrayclear(typ *_type, ptr unsafe.Pointer, len int) {
   337  	size := typ.Size_ * uintptr(len)
   338  	if writeBarrier.needed && typ.PtrBytes != 0 {
   339  		bulkBarrierPreWrite(uintptr(ptr), 0, size)
   340  	}
   341  	memclrNoHeapPointers(ptr, size)
   342  }
   343  
   344  // memclrHasPointers clears n bytes of typed memory starting at ptr.
   345  // The caller must ensure that the type of the object at ptr has
   346  // pointers, usually by checking typ.PtrBytes. However, ptr
   347  // does not have to point to the start of the allocation.
   348  //
   349  //go:nosplit
   350  func memclrHasPointers(ptr unsafe.Pointer, n uintptr) {
   351  	bulkBarrierPreWrite(uintptr(ptr), 0, n)
   352  	memclrNoHeapPointers(ptr, n)
   353  }