Debian Codegraph @

slotstate.go

raw
1 // slotstate.go - combined per-node lock + visited counter in a single []uint64
2 //
3 // Each slot (one uint64 per node index) holds:
4 //
5 // Bit 63: exclusive spinlock
6 // Bits [vbits-1 : 0]: visited counter (saturates at maxVisit)
7 //
8 // For k=1 (classic SIEVE): 1 bit for visited, lock in bit 63.
9 // For k=3: 2 bits for counter (saturates at 3), lock in bit 63.
10 //
11 // This replaces the separate spinlock + visitor arrays with a single
12 // allocation, saving one cache miss per Get() on the read path.
13 //
14 // Memory: 8 bytes per node. At 1M entries: 8 MB.
15 // - vs prior design ([]uint64 spinlock + []uint32 visitor): 12 MB.
16 //
17 // Lock uses atomic.OrUint64 as test-and-set (returns old value).
18 // Unlock uses atomic.AndUint64 to clear the lock bit.
19 // Both are single instructions on ARM64 with LSE (LDSETAL / LDCLRAL).
20 //
21 // Hot path (Get, k=1):
22 //
23 // LockAndMark: 1 Or (sets lock + visited bits, returns old to check)
24 // read val
25 // Unlock: 1 And (clears lock bit, visitor bit untouched)
26 //
27 // Two atomic ops total, down from three (CAS + Store + Or/Store).
28
29 package sieve
30
31 import (
32 "math/bits"
33 "sync/atomic"
34 )
35
36 const _LockBit = uint64(1) << 63
37
38 // slotState manages per-node lock + visited counter in a single []uint64.
39 type slotState struct {
40 words []uint64
41 maxVisit uint64 // k (saturation value)
42 vmask uint64 // (1 << vbits) - 1
43 vbits uint // ceil(log2(k+1)) — number of bits per visitor counter
44 }
45
46 // newSlotState creates a slotState for the given capacity and visit level k.
47 // k=1 uses a single visited bit. k>1 uses ceil(log2(k+1)) bits for a
48 // saturating counter.
49 func newSlotState(capacity int, k int) slotState {
50 if k < 1 {
51 k = 1
52 }
53 vb := uint(bits.Len(uint(k))) // #nosec G115 — k is a small positive int (clamped ≥1 above); k=1→1, k=2..3→2, k=4..7→3
54 return slotState{
55 words: make([]uint64, capacity),
56 maxVisit: uint64(k),
57 vmask: (1 << vb) - 1,
58 vbits: vb,
59 }
60 }
61
62 // LockAndMark acquires the exclusive lock and marks the node as visited.
63 //
64 // For k=1: single atomic.OrUint64 sets both lock bit and visited bit.
65 // Or is idempotent on the visited bit and returns the old value to test
66 // whether we acquired the lock. No CAS, no spurious retries from
67 // concurrent visitor bit changes.
68 //
69 // For k>1: acquires lock via Or, then saturating-increments the counter
70 // via CAS (only the CAS can fail spuriously, and only from concurrent
71 // Clear on the same word — probability 1/N).
72 //
73 // Spurious marks: every Or attempt sets the visited bit, including
74 // failed lock acquisitions (k=1) and callers whose stale-index key
75 // check later fails. An unrelated live node can therefore gain an
76 // undeserved visited mark, delaying its eviction by at most one hand
77 // pass. Reused slots are wiped by LockAndReset, so marks never leak
78 // across reallocation.
79 func (ss *slotState) LockAndMark(idx int32) {
80 word := &ss.words[idx]
81
82 if ss.vbits == 1 {
83 // k=1 fast path: Or sets both lock and visited bits.
84 // One atomic instruction on ARM64 with LSE (LDSETAL).
85 for i := 0; ; i++ {
86 old := atomic.OrUint64(word, _LockBit|1)
87 if old&_LockBit == 0 {
88 return // we set the lock bit 0→1
89 }
90 pause(i)
91 }
92 }
93
94 // k>1: two-step — lock via Or, then saturating increment via CAS.
95 for i := 0; ; i++ {
96 old := atomic.OrUint64(word, _LockBit)
97 if old&_LockBit == 0 {
98 break // lock acquired
99 }
100 pause(i)
101 }
102 // We hold the lock. Increment visitor counter (saturating).
103 for i := 0; ; i++ {
104 old := atomic.LoadUint64(word)
105 if old&ss.vmask >= ss.maxVisit {
106 return // saturated
107 }
108 if atomic.CompareAndSwapUint64(word, old, old+1) {
109 return
110 }
111 pause(i)
112 }
113 }
114
115 // Lock acquires the exclusive lock without marking visited.
116 // Used by remove() to serialize field zeroing with fast-path reads.
117 func (ss *slotState) Lock(idx int32) {
118 word := &ss.words[idx]
119 for i := 0; ; i++ {
120 old := atomic.OrUint64(word, _LockBit)
121 if old&_LockBit == 0 {
122 return
123 }
124 pause(i)
125 }
126 }
127
128 // LockAndReset acquires the exclusive lock and clears the visited counter.
129 // Used by newNode() when initializing a freshly allocated slot. Unlike
130 // Reset()+Lock(), this is safe against concurrent holders: it spins until
131 // the lock is acquired, then zeroes the visited bits while holding it.
132 func (ss *slotState) LockAndReset(idx int32) {
133 word := &ss.words[idx]
134 for i := 0; ; i++ {
135 old := atomic.OrUint64(word, _LockBit)
136 if old&_LockBit == 0 {
137 // Lock acquired. Clear visited bits, keep lock.
138 atomic.StoreUint64(word, _LockBit)
139 return
140 }
141 pause(i)
142 }
143 }
144
145 // Unlock releases the exclusive lock, leaving visitor bits intact.
146 // Single atomic instruction on ARM64 with LSE (LDCLRAL).
147 func (ss *slotState) Unlock(idx int32) {
148 atomic.AndUint64(&ss.words[idx], ^_LockBit)
149 }
150
151 // IsVisited returns true if the visited counter is > 0.
152 // Single atomic load — no contention.
153 func (ss *slotState) IsVisited(idx int32) bool {
154 return atomic.LoadUint64(&ss.words[idx])&ss.vmask != 0
155 }
156
157 // Clear decrements the visited counter, saturating at 0.
158 // Called during eviction under s.mu. A concurrent Get() may hold the
159 // lock on the same word, so we use CAS.
160 func (ss *slotState) Clear(idx int32) {
161 word := &ss.words[idx]
162 for i := 0; ; i++ {
163 old := atomic.LoadUint64(word)
164 if old&ss.vmask == 0 {
165 return // already zero
166 }
167 if atomic.CompareAndSwapUint64(word, old, old-1) {
168 return
169 }
170 pause(i)
171 }
172 }
173
174 // Reset zeroes the entire slot (lock + visitor). Called from newNode()
175 // under s.mu when a node is freshly allocated — no concurrent access.
176 func (ss *slotState) Reset(idx int32) {
177 atomic.StoreUint64(&ss.words[idx], 0)
178 }
179
180 // ResetAll zeroes all slots. Called from Purge() under s.mu.
181 // Uses atomic stores to avoid data races with concurrent Get() calls
182 // that may be in LockAndMark on the same word.
183 func (ss *slotState) ResetAll() {
184 for i := range ss.words {
185 atomic.StoreUint64(&ss.words[i], 0)
186 }
187 }