summaryrefslogtreecommitdiff
path: root/lib/containers/arcache.go
blob: 1dc3b7e140365eea713d7d249d90297b50f85f9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// Copyright (C) 2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package containers

import (
	"sync"
)

// ARCache is a thread-safe Adaptive Replacement Cache.
//
// The Adaptive Replacement Cache is patented by IBM (patent
// US-6,996,676-B2 is set to expire 2024-02-22).
//
// This implementation does NOT make use of the enhancements in ZFS'
// enhanced ARC, which are patented by Sun (now Oracle) (patent
// US-7,469,320-B2 is set to expire 2027-02-13).
//
// It is invalid to adjust any public members after first use.
type ARCache[K comparable, V any] struct {
	MaxLen   int        // must be >= 2
	New      func(K) V  // may be nil (.Load)
	OnHit    func(K, V) // may be nil (.Load)
	OnMiss   func(K)    // may be nil (.Load)
	OnEvict  func(K, V) // may be nil (.Load, .Store)
	OnRemove func(K, V) // may be nil (.Load, .Store, .Delete)

	mu sync.RWMutex
	// Some of the ARC literature calls these "MRU" and "MFU" for
	// "most {recently,frequently} used", but that's wrong.  The
	// `frequent` list is still ordered by most-recent-use.  The
	// distinction is that the `recent` list is entries that have
	// been used "only once recently", while the `frequent` list
	// is entries that have been used "at least twice recently"
	// (to quote the definitions from the original ARC paper); the
	// affect being that the `recent` list is for
	// recently-but-not-frequently used entries, while the
	// `frequent` list is there to ensure that frequently-used
	// entries don't get evicted.  They're both still MRU lists.
	recentLive    lruCache[K, V]
	recentGhost   lruCache[K, struct{}]
	frequentLive  lruCache[K, V]
	frequentGhost lruCache[K, struct{}]
	// recentLiveTarget is the "target" len of recentLive.  We
	// allow the actual len to deviate from this if the ARCache as
	// a whole isn't over-len.  That is: recentLiveTarget is used
	// to decide *which* list to evict from, not *whether* we need
	// to evict.
	recentLiveTarget int

	// Add a no-op .check() method that the tests can override.
	noopChecker //nolint:unused // False positive; it is used.
}

var _ Map[int, string] = (*ARCache[int, string])(nil)

//nolint:unused // False positive; it is used.
type noopChecker struct{}

//nolint:unused // False positive; it is used.
func (noopChecker) check() {}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func bound(low, val, high int) int {
	if val < low {
		return low
	}
	if val > high {
		return high
	}
	return val
}

func (c *ARCache[K, V]) onLRUEvictRecent(k K, v V) {
	if c.recentLive.Len() < c.MaxLen {
		for c.recentLen() >= c.MaxLen {
			c.recentGhost.EvictOldest()
		}
		for c.ghostLen() >= c.MaxLen {
			if c.recentGhost.Len() > 0 {
				c.recentGhost.EvictOldest()
			} else {
				c.frequentGhost.EvictOldest()
			}
		}
		c.recentGhost.Store(k, struct{}{})
	}
	if c.OnRemove != nil {
		c.OnRemove(k, v)
	}
	if c.OnEvict != nil {
		c.OnEvict(k, v)
	}
}

func (c *ARCache[K, V]) onLRUEvictFrequent(k K, v V) {
	if c.frequentLive.Len() < c.MaxLen {
		for c.frequentLen() >= c.MaxLen {
			c.frequentGhost.EvictOldest()
		}
		for c.ghostLen() >= c.MaxLen {
			if c.frequentGhost.Len() > 0 {
				c.frequentGhost.EvictOldest()
			} else {
				c.recentGhost.EvictOldest()
			}
		}
		c.frequentGhost.Store(k, struct{}{})
	}
	if c.OnRemove != nil {
		c.OnRemove(k, v)
	}
	if c.OnEvict != nil {
		c.OnEvict(k, v)
	}
}

func (c *ARCache[K, V]) init() {
	c.check()
	if c.recentLive.OnEvict == nil {
		c.recentLive.OnEvict = c.onLRUEvictRecent
		c.frequentLive.OnEvict = c.onLRUEvictFrequent
	}
	c.check()
}

func (c *ARCache[K, V]) liveLen() int     { return c.recentLive.Len() + c.frequentLive.Len() }
func (c *ARCache[K, V]) ghostLen() int    { return c.recentGhost.Len() + c.frequentGhost.Len() }
func (c *ARCache[K, V]) recentLen() int   { return c.recentLive.Len() + c.recentGhost.Len() }
func (c *ARCache[K, V]) frequentLen() int { return c.frequentLive.Len() + c.frequentGhost.Len() }
func (c *ARCache[K, V]) fullLen() int {
	return c.recentLive.Len() + c.recentGhost.Len() + c.frequentLive.Len() + c.frequentGhost.Len()
}

// Store a key/value pair in to the cache.
func (c *ARCache[K, V]) Store(k K, v V) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.init()

	c.unlockedStore(k, v)
}

func (c *ARCache[K, V]) unlockedStore(k K, v V) {
	// The "Case" comments here reflect Fig. 4. in the original paper "ARC: A
	// Self-Tuning, Low Overhead Replacement Cache" by N. Megiddo & D. Modha, FAST
	// 2003.
	switch {
	case c.recentLive.Has(k): // Case I(a): cache hit
		// Make room
		for c.frequentLen() >= c.MaxLen {
			if c.frequentGhost.Len() > 0 {
				c.frequentGhost.EvictOldest()
			} else {
				c.frequentLive.EvictOldest()
			}
		}
		c.check()
		// Move
		oldV, _ := c.recentLive.Peek(k)
		c.recentLive.Delete(k)
		c.frequentLive.Store(k, v)
		if c.OnRemove != nil {
			c.OnRemove(k, oldV)
		}
		c.check()
	case c.frequentLive.Has(k): // Case I(b): cache hit
		oldV, _ := c.frequentLive.Peek(k)
		c.frequentLive.Store(k, v)
		if c.OnRemove != nil {
			c.OnRemove(k, oldV)
		}
		c.check()
	case c.recentGhost.Has(k): // Case II: cache miss (that "should" have been a hit)
		// Adapt
		c.recentLiveTarget = bound(
			0,
			c.recentLiveTarget+max(1, c.frequentGhost.Len()/c.recentGhost.Len()),
			c.MaxLen)
		// Make room
		for c.liveLen() >= c.MaxLen {
			if c.recentLive.Len() > c.recentLiveTarget {
				c.recentLive.EvictOldest()
			} else {
				c.frequentLive.EvictOldest()
			}
		}
		for c.frequentLen() >= c.MaxLen {
			if c.frequentGhost.Len() > 0 {
				c.frequentGhost.EvictOldest()
			} else {
				c.frequentLive.EvictOldest()
			}
		}
		c.check()
		// Store
		c.recentGhost.Delete(k)
		c.frequentLive.Store(k, v)
		c.check()
	case c.frequentGhost.Has(k): // Case III: cache miss (that "should" have been a hit)
		// Adapt
		c.recentLiveTarget = bound(
			0,
			c.recentLiveTarget-max(1, c.recentGhost.Len()/c.frequentGhost.Len()),
			c.MaxLen)
		// Make room
		for c.liveLen() >= c.MaxLen {
			// TODO(lukeshu): I don't understand why this .recentLiveTarget
			// check needs to be `>=` instead of `>` like all of the others.
			if c.recentLive.Len() >= c.recentLiveTarget && c.recentLive.Len() > 0 {
				c.recentLive.EvictOldest()
			} else {
				c.frequentLive.EvictOldest()
			}
		}
		c.check()
		// Store
		c.frequentGhost.Delete(k)
		c.frequentLive.Store(k, v)
		c.check()
	default: // Case IV: cache miss
		// Make room
		if c.recentLen() < c.MaxLen {
			for c.liveLen() >= c.MaxLen {
				if c.recentLive.Len() > c.recentLiveTarget {
					c.recentLive.EvictOldest()
				} else {
					c.frequentLive.EvictOldest()
				}
			}
		} else {
			c.recentLive.EvictOldest()
			c.recentGhost.EvictOldest()
		}
		c.check()
		// Store
		c.recentLive.Store(k, v)
		c.check()
	}
}

// Load an entry from the cache, recording a "use" for the purposes of
// "least-recently-used" eviction.
//
// Calls .OnHit or .OnMiss depending on whether it's a cache-hit or
// cache-miss.
//
// If .New is non-nil, then .Load will never return (zero, false).
func (c *ARCache[K, V]) Load(k K) (v V, ok bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.init()
	defer c.check()

	if v, ok := c.recentLive.Peek(k); ok {
		// Make room
		for c.frequentLen() >= c.MaxLen {
			if c.frequentGhost.Len() > 0 {
				c.frequentGhost.EvictOldest()
			} else {
				c.frequentLive.EvictOldest()
			}
		}
		// Store
		c.recentLive.Delete(k)
		c.frequentLive.Store(k, v)
		if c.OnHit != nil {
			c.OnHit(k, v)
		}
		return v, true
	}
	if v, ok := c.frequentLive.Load(k); ok {
		if c.OnHit != nil {
			c.OnHit(k, v)
		}
		return v, true
	}

	if c.OnMiss != nil {
		c.OnMiss(k)
	}
	if c.New != nil {
		v := c.New(k)
		c.unlockedStore(k, v)
		return v, true
	}
	var zero V
	return zero, false
}

// Delete an entry from the cache.
func (c *ARCache[K, V]) Delete(k K) {
	c.mu.Lock()
	defer c.mu.Unlock()

	v, ok := c.unlockedPeek(k)

	c.recentLive.Delete(k)
	c.recentGhost.Delete(k)
	c.frequentLive.Delete(k)
	c.frequentGhost.Delete(k)

	if ok && c.OnRemove != nil {
		c.OnRemove(k, v)
	}
}

// Peek is like Load, but doesn't count as a "use" for
// "least-recently-used".
func (c *ARCache[K, V]) Peek(k K) (v V, ok bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()

	return c.unlockedPeek(k)
}

func (c *ARCache[K, V]) unlockedPeek(k K) (v V, ok bool) {
	if v, ok := c.recentLive.Peek(k); ok {
		return v, true
	}

	return c.frequentLive.Peek(k)
}

// Has returns whether an entry is present in the cache.  Calling Has
// does not count as a "use" for "least-recently-used".
func (c *ARCache[K, V]) Has(k K) bool {
	c.mu.RLock()
	defer c.mu.RUnlock()

	return c.recentLive.Has(k) || c.frequentLive.Has(k)
}

// Len returns the number of entries in the cache.
func (c *ARCache[K, V]) Len() int {
	c.mu.RLock()
	defer c.mu.RUnlock()

	return c.liveLen()
}