...
Run Format

Source file src/runtime/mwbbuf.go

Documentation: runtime

     1  // Copyright 2017 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  // This implements the write barrier buffer. The write barrier itself
     6  // is gcWriteBarrier and is implemented in assembly.
     7  //
     8  // See mbarrier.go for algorithmic details on the write barrier. This
     9  // file deals only with the buffer.
    10  //
    11  // The write barrier has a fast path and a slow path. The fast path
    12  // simply enqueues to a per-P write barrier buffer. It's written in
    13  // assembly and doesn't clobber any general purpose registers, so it
    14  // doesn't have the usual overheads of a Go call.
    15  //
    16  // When the buffer fills up, the write barrier invokes the slow path
    17  // (wbBufFlush) to flush the buffer to the GC work queues. In this
    18  // path, since the compiler didn't spill registers, we spill *all*
    19  // registers and disallow any GC safe points that could observe the
    20  // stack frame (since we don't know the types of the spilled
    21  // registers).
    22  
    23  package runtime
    24  
    25  import (
    26  	"runtime/internal/sys"
    27  	"unsafe"
    28  )
    29  
    30  // testSmallBuf forces a small write barrier buffer to stress write
    31  // barrier flushing.
    32  const testSmallBuf = false
    33  
    34  // wbBuf is a per-P buffer of pointers queued by the write barrier.
    35  // This buffer is flushed to the GC workbufs when it fills up and on
    36  // various GC transitions.
    37  //
    38  // This is closely related to a "sequential store buffer" (SSB),
    39  // except that SSBs are usually used for maintaining remembered sets,
    40  // while this is used for marking.
    41  type wbBuf struct {
    42  	// next points to the next slot in buf. It must not be a
    43  	// pointer type because it can point past the end of buf and
    44  	// must be updated without write barriers.
    45  	//
    46  	// This is a pointer rather than an index to optimize the
    47  	// write barrier assembly.
    48  	next uintptr
    49  
    50  	// end points to just past the end of buf. It must not be a
    51  	// pointer type because it points past the end of buf and must
    52  	// be updated without write barriers.
    53  	end uintptr
    54  
    55  	// buf stores a series of pointers to execute write barriers
    56  	// on. This must be a multiple of wbBufEntryPointers because
    57  	// the write barrier only checks for overflow once per entry.
    58  	buf [wbBufEntryPointers * wbBufEntries]uintptr
    59  }
    60  
    61  const (
    62  	// wbBufEntries is the number of write barriers between
    63  	// flushes of the write barrier buffer.
    64  	//
    65  	// This trades latency for throughput amortization. Higher
    66  	// values amortize flushing overhead more, but increase the
    67  	// latency of flushing. Higher values also increase the cache
    68  	// footprint of the buffer.
    69  	//
    70  	// TODO: What is the latency cost of this? Tune this value.
    71  	wbBufEntries = 256
    72  
    73  	// wbBufEntryPointers is the number of pointers added to the
    74  	// buffer by each write barrier.
    75  	wbBufEntryPointers = 2
    76  )
    77  
    78  // reset empties b by resetting its next and end pointers.
    79  func (b *wbBuf) reset() {
    80  	start := uintptr(unsafe.Pointer(&b.buf[0]))
    81  	b.next = start
    82  	if gcBlackenPromptly || writeBarrier.cgo {
    83  		// Effectively disable the buffer by forcing a flush
    84  		// on every barrier.
    85  		b.end = uintptr(unsafe.Pointer(&b.buf[wbBufEntryPointers]))
    86  	} else if testSmallBuf {
    87  		// For testing, allow two barriers in the buffer. If
    88  		// we only did one, then barriers of non-heap pointers
    89  		// would be no-ops. This lets us combine a buffered
    90  		// barrier with a flush at a later time.
    91  		b.end = uintptr(unsafe.Pointer(&b.buf[2*wbBufEntryPointers]))
    92  	} else {
    93  		b.end = start + uintptr(len(b.buf))*unsafe.Sizeof(b.buf[0])
    94  	}
    95  
    96  	if (b.end-b.next)%(wbBufEntryPointers*unsafe.Sizeof(b.buf[0])) != 0 {
    97  		throw("bad write barrier buffer bounds")
    98  	}
    99  }
   100  
   101  // discard resets b's next pointer, but not its end pointer.
   102  //
   103  // This must be nosplit because it's called by wbBufFlush.
   104  //
   105  //go:nosplit
   106  func (b *wbBuf) discard() {
   107  	b.next = uintptr(unsafe.Pointer(&b.buf[0]))
   108  }
   109  
   110  // putFast adds old and new to the write barrier buffer and returns
   111  // false if a flush is necessary. Callers should use this as:
   112  //
   113  //     buf := &getg().m.p.ptr().wbBuf
   114  //     if !buf.putFast(old, new) {
   115  //         wbBufFlush(...)
   116  //     }
   117  //     ... actual memory write ...
   118  //
   119  // The arguments to wbBufFlush depend on whether the caller is doing
   120  // its own cgo pointer checks. If it is, then this can be
   121  // wbBufFlush(nil, 0). Otherwise, it must pass the slot address and
   122  // new.
   123  //
   124  // The caller must ensure there are no preemption points during the
   125  // above sequence. There must be no preemption points while buf is in
   126  // use because it is a per-P resource. There must be no preemption
   127  // points between the buffer put and the write to memory because this
   128  // could allow a GC phase change, which could result in missed write
   129  // barriers.
   130  //
   131  // putFast must be nowritebarrierrec to because write barriers here would
   132  // corrupt the write barrier buffer. It (and everything it calls, if
   133  // it called anything) has to be nosplit to avoid scheduling on to a
   134  // different P and a different buffer.
   135  //
   136  //go:nowritebarrierrec
   137  //go:nosplit
   138  func (b *wbBuf) putFast(old, new uintptr) bool {
   139  	p := (*[2]uintptr)(unsafe.Pointer(b.next))
   140  	p[0] = old
   141  	p[1] = new
   142  	b.next += 2 * sys.PtrSize
   143  	return b.next != b.end
   144  }
   145  
   146  // wbBufFlush flushes the current P's write barrier buffer to the GC
   147  // workbufs. It is passed the slot and value of the write barrier that
   148  // caused the flush so that it can implement cgocheck.
   149  //
   150  // This must not have write barriers because it is part of the write
   151  // barrier implementation.
   152  //
   153  // This and everything it calls must be nosplit because 1) the stack
   154  // contains untyped slots from gcWriteBarrier and 2) there must not be
   155  // a GC safe point between the write barrier test in the caller and
   156  // flushing the buffer.
   157  //
   158  // TODO: A "go:nosplitrec" annotation would be perfect for this.
   159  //
   160  //go:nowritebarrierrec
   161  //go:nosplit
   162  func wbBufFlush(dst *uintptr, src uintptr) {
   163  	// Note: Every possible return from this function must reset
   164  	// the buffer's next pointer to prevent buffer overflow.
   165  
   166  	// This *must not* modify its arguments because this
   167  	// function's argument slots do double duty in gcWriteBarrier
   168  	// as register spill slots. Currently, not modifying the
   169  	// arguments is sufficient to keep the spill slots unmodified
   170  	// (which seems unlikely to change since it costs little and
   171  	// helps with debugging).
   172  
   173  	if getg().m.dying > 0 {
   174  		// We're going down. Not much point in write barriers
   175  		// and this way we can allow write barriers in the
   176  		// panic path.
   177  		getg().m.p.ptr().wbBuf.discard()
   178  		return
   179  	}
   180  
   181  	if writeBarrier.cgo && dst != nil {
   182  		// This must be called from the stack that did the
   183  		// write. It's nosplit all the way down.
   184  		cgoCheckWriteBarrier(dst, src)
   185  		if !writeBarrier.needed {
   186  			// We were only called for cgocheck.
   187  			getg().m.p.ptr().wbBuf.discard()
   188  			return
   189  		}
   190  	}
   191  
   192  	// Switch to the system stack so we don't have to worry about
   193  	// the untyped stack slots or safe points.
   194  	systemstack(func() {
   195  		wbBufFlush1(getg().m.p.ptr())
   196  	})
   197  }
   198  
   199  // wbBufFlush1 flushes p's write barrier buffer to the GC work queue.
   200  //
   201  // This must not have write barriers because it is part of the write
   202  // barrier implementation, so this may lead to infinite loops or
   203  // buffer corruption.
   204  //
   205  // This must be non-preemptible because it uses the P's workbuf.
   206  //
   207  //go:nowritebarrierrec
   208  //go:systemstack
   209  func wbBufFlush1(_p_ *p) {
   210  	// Get the buffered pointers.
   211  	start := uintptr(unsafe.Pointer(&_p_.wbBuf.buf[0]))
   212  	n := (_p_.wbBuf.next - start) / unsafe.Sizeof(_p_.wbBuf.buf[0])
   213  	ptrs := _p_.wbBuf.buf[:n]
   214  
   215  	// Reset the buffer.
   216  	_p_.wbBuf.reset()
   217  
   218  	if useCheckmark {
   219  		// Slow path for checkmark mode.
   220  		for _, ptr := range ptrs {
   221  			shade(ptr)
   222  		}
   223  		return
   224  	}
   225  
   226  	// Mark all of the pointers in the buffer and record only the
   227  	// pointers we greyed. We use the buffer itself to temporarily
   228  	// record greyed pointers.
   229  	//
   230  	// TODO: Should scanobject/scanblock just stuff pointers into
   231  	// the wbBuf? Then this would become the sole greying path.
   232  	//
   233  	// TODO: We could avoid shading any of the "new" pointers in
   234  	// the buffer if the stack has been shaded, or even avoid
   235  	// putting them in the buffer at all (which would double its
   236  	// capacity). This is slightly complicated with the buffer; we
   237  	// could track whether any un-shaded goroutine has used the
   238  	// buffer, or just track globally whether there are any
   239  	// un-shaded stacks and flush after each stack scan.
   240  	gcw := &_p_.gcw
   241  	pos := 0
   242  	for _, ptr := range ptrs {
   243  		if ptr < minLegalPointer {
   244  			// nil pointers are very common, especially
   245  			// for the "old" values. Filter out these and
   246  			// other "obvious" non-heap pointers ASAP.
   247  			//
   248  			// TODO: Should we filter out nils in the fast
   249  			// path to reduce the rate of flushes?
   250  			continue
   251  		}
   252  		obj, span, objIndex := findObject(ptr, 0, 0)
   253  		if obj == 0 {
   254  			continue
   255  		}
   256  		// TODO: Consider making two passes where the first
   257  		// just prefetches the mark bits.
   258  		mbits := span.markBitsForIndex(objIndex)
   259  		if mbits.isMarked() {
   260  			continue
   261  		}
   262  		mbits.setMarked()
   263  		if span.spanclass.noscan() {
   264  			gcw.bytesMarked += uint64(span.elemsize)
   265  			continue
   266  		}
   267  		ptrs[pos] = obj
   268  		pos++
   269  	}
   270  
   271  	// Enqueue the greyed objects.
   272  	gcw.putBatch(ptrs[:pos])
   273  	if gcphase == _GCmarktermination || gcBlackenPromptly {
   274  		// Ps aren't allowed to cache work during mark
   275  		// termination.
   276  		gcw.dispose()
   277  	}
   278  }
   279  

View as plain text