Source file src/sync/counter_stripe.go

     1  // Copyright 2026 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 sync
     6  
     7  import (
     8  	"runtime"
     9  	"sync/atomic"
    10  	"unsafe"
    11  )
    12  
    13  // stripeArr is the slice of pointers to uint64. Each index in the slice
    14  // corresponds to a uint64 which should only be modified by a single P. Each
    15  // uint64 is stored in a counterBlock of memory that is associated with a unique P.
    16  // The stripe block contains values for a counter that span multiple different counterBlocks.
    17  type stripeArr []*uint64
    18  
    19  // stripe handles the dynamic growth of the sharded counters.
    20  // It can only grow.
    21  //
    22  // Synchronization protocol:
    23  //   - mu serializes growth only (grow, and the check-then-grow in getSlow).
    24  //     Readers on the fast path never take mu.
    25  //   - block and stripeCap are published atomically. grow stores block before
    26  //     stripeCap; readers (get/getSlow/Value) load stripeCap before block.
    27  //     Because block only ever grows and always preserves its existing prefix,
    28  //     a reader may observe a smaller stripeCap paired with a larger block, but
    29  //     never the reverse. Slicing block to stripeCap is therefore always in
    30  //     bounds and yields stable per-index pointers.
    31  //
    32  // The zero value is a valid, empty stripe (stripeCap 0, nil block); the first
    33  // get for any pID takes the slow path and grows it.
    34  type stripe struct {
    35  	mu Mutex // serializes stripe growth
    36  
    37  	stripeCap atomic.Uint32           // current capacity (number of counters)
    38  	block     atomic.Pointer[*uint64] // stripe block
    39  }
    40  
    41  // newStripe returns a new stripe initialized with a capacity
    42  // appropriate for GOMAXPROCS length of counters.
    43  func newStripe() *stripe {
    44  	pCount := runtime.GOMAXPROCS(0)
    45  	shards := make(stripeArr, pCount)
    46  	var cnt int
    47  	for intPtr := range allocCounters(pCount) {
    48  		shards[cnt] = intPtr
    49  		cnt++
    50  	}
    51  	s := new(stripe)
    52  	s.block.Store(&shards[0])
    53  	s.stripeCap.Store(uint32(pCount))
    54  	return s
    55  }
    56  
    57  // get returns the counter associated with the current P.
    58  // The caller must have the current P pinned (runtime_procPin).
    59  // If the request pID is larger than the capacity for the stripe,
    60  // get grows the stripe to accommodate it. We assume that the number
    61  // of Ps has grown. This may temporarily unpin the P, pID may not
    62  // be valid on return.
    63  func (s *stripe) get(pID int) *uint64 {
    64  	stripeCap := s.cap()
    65  
    66  	if pID < stripeCap {
    67  		// Fast path: lock-free read
    68  		return unsafe.Slice(s.block.Load(), stripeCap)[pID]
    69  	}
    70  	return s.getSlow(pID, stripeCap)
    71  }
    72  
    73  // getSlow is the slow path to returning a counter associated
    74  // with the current P. This is called when the stripe capacity
    75  // needs to grow. The caller must have the current P pinned
    76  // (runtime_procPin). This may temporarily unpin the P, pID may not
    77  // be valid on return.
    78  func (s *stripe) getSlow(pID, stripeCap int) *uint64 {
    79  	for {
    80  		if pID < stripeCap {
    81  			// Fast path: lock-free read
    82  			return unsafe.Slice(s.block.Load(), stripeCap)[pID]
    83  		}
    84  
    85  		// Slow path: grow
    86  		// Unpin from the P to grab the lock.
    87  		runtime_procUnpin()
    88  		s.mu.Lock()
    89  
    90  		// Check again under lock
    91  		stripeCap = s.cap()
    92  		if pID < stripeCap {
    93  			// Another goroutine must have grown the stripe before
    94  			// this goroutine obtained the lock. Release the lock
    95  			// and attempt to return the counter.
    96  			s.mu.Unlock()
    97  			// Pin to a P again and update pID before retrying
    98  			// the counter retrieval. The pID may have changed.
    99  			pID = runtime_procPin()
   100  			// Retry the counter retrieval.
   101  			continue
   102  		}
   103  		// Grow the stripe, then refresh the local capacity so the retry
   104  		// below can usually take the fast path without re-locking.
   105  		s.grow()
   106  		stripeCap = s.cap()
   107  		s.mu.Unlock()
   108  
   109  		// pin to a P again and update pID before retrying
   110  		// the counter retrieval.
   111  		pID = runtime_procPin()
   112  	}
   113  }
   114  
   115  // grow grows the stripe to GOMAXPROCS if needed.
   116  // s.mu must be held. Must not be pinned to a P while growing.
   117  func (s *stripe) grow() {
   118  	origStripeCap := s.cap()
   119  	targetStripeLen := runtime.GOMAXPROCS(0)
   120  	if targetStripeLen <= origStripeCap {
   121  		return
   122  	}
   123  	block := unsafe.Slice(s.block.Load(), origStripeCap)
   124  	newStripe := make(stripeArr, targetStripeLen)
   125  	// Copy existing shards over.
   126  	for idx := range len(block) {
   127  		newStripe[idx] = block[idx]
   128  	}
   129  	var cnt int
   130  	// allocCounters allocates one slot per P. When growing, keep the existing
   131  	// pointers for Ps < origCnt so in-flight writes continue uninterrupted, and
   132  	// discard the duplicate new pointers. Wasting a few slots on growth avoids
   133  	// the complexity of tracking per-P allocation offsets.
   134  	for intPtr := range allocCounters(targetStripeLen) {
   135  		if cnt < origStripeCap {
   136  			// skip over previously allocated ptr. Do
   137  			// not set pointers allocated to the wrong pID.
   138  			cnt++
   139  			continue
   140  		}
   141  		newStripe[cnt] = intPtr
   142  		cnt++
   143  	}
   144  	// block is always stored before stripeCap, and stripeCap is always
   145  	// loaded before block. Assuming that block can only grow
   146  	// then even if the reader sees an inconsistent block/stripeCap
   147  	// combination, the access is safe since the logical size of
   148  	// block will always be greater than or equal to the observed size
   149  	// of stripeCap.
   150  	s.block.Store(&newStripe[0])
   151  	s.stripeCap.Store(uint32(targetStripeLen))
   152  }
   153  
   154  // cap returns the capacity of the stripe.
   155  func (s *stripe) cap() int {
   156  	return int(s.stripeCap.Load())
   157  }
   158  

View as plain text