]> git.ipfire.org Git - thirdparty/squid.git/blame - src/ipc/StoreMap.h
Cleanup unit tests (#688)
[thirdparty/squid.git] / src / ipc / StoreMap.h
CommitLineData
bbc27441 1/*
77b1029d 2 * Copyright (C) 1996-2020 The Squid Software Foundation and contributors
bbc27441
AJ
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
44c95fcf
AR
9#ifndef SQUID_IPC_STORE_MAP_H
10#define SQUID_IPC_STORE_MAP_H
11
3a8c5551 12#include "ipc/mem/FlexibleArray.h"
68353d5a 13#include "ipc/mem/Pointer.h"
602d9612 14#include "ipc/ReadWriteLock.h"
65e41a45 15#include "sbuf/SBuf.h"
2745fea5 16#include "store/forward.h"
e1ba42a4 17#include "store_key_md5.h"
44c95fcf 18
abf396ec
AR
19#include <functional>
20
9199139f
AR
21namespace Ipc
22{
44c95fcf 23
f13833e9 24typedef int32_t StoreMapSliceId;
bc8b6522
AR
25
26/// a piece of Store entry, linked to other pieces, forming a chain
ce49546e 27/// slices may be appended by writers while readers read the entry
bc8b6522
AR
28class StoreMapSlice
29{
30public:
ce49546e 31 typedef uint32_t Size;
bc8b6522 32
ce49546e 33 StoreMapSlice(): size(0), next(-1) {}
d2b13bab
AJ
34 StoreMapSlice(const StoreMapSlice &o) {
35 size.exchange(o.size);
36 next.exchange(o.next);
37 }
38
39 StoreMapSlice &operator =(const StoreMapSlice &o) {
40 size.store(o.size);
41 next.store(o.next);
42 return *this;
43 }
44
c2037547
EB
45 /// restore default-constructed state
46 void clear() { size = 0; next = -1; }
47
d2b13bab
AJ
48 std::atomic<Size> size; ///< slice contents size
49 std::atomic<StoreMapSliceId> next; ///< ID of the next entry slice
bc8b6522
AR
50};
51
50dc81ec
AR
52/// Maintains shareable information about a StoreEntry as a whole.
53/// An anchor points to one or more StoreEntry slices. This is the
54/// only lockable part of shared StoreEntry information, providing
55/// protection for all StoreEntry slices.
56class StoreMapAnchor
9199139f 57{
44c95fcf 58public:
50dc81ec 59 StoreMapAnchor();
44c95fcf 60
50dc81ec 61 /// store StoreEntry key and basics for an inode slot
4310f8b0
EB
62 void set(const StoreEntry &anEntry, const cache_key *aKey = nullptr);
63 /// load StoreEntry basics that were previously stored with set()
64 void exportInto(StoreEntry &) const;
44c95fcf
AR
65
66 void setKey(const cache_key *const aKey);
67 bool sameKey(const cache_key *const aKey) const;
68
50dc81ec
AR
69 /// undo the effects of set(), setKey(), etc., but keep locks and state
70 void rewind();
71
ce49546e
AR
72 /* entry state may change immediately after calling these methods unless
73 * the caller holds an appropriate lock */
74 bool empty() const { return !key[0] && !key[1]; }
75 bool reading() const { return lock.readers; }
a3023c03 76 bool writing() const { return lock.writing; }
ce49546e
AR
77 bool complete() const { return !empty() && !writing(); }
78
44c95fcf
AR
79public:
80 mutable ReadWriteLock lock; ///< protects slot data below
d2b13bab 81 std::atomic<uint8_t> waitingToBeFreed; ///< may be accessed w/o a lock
4310f8b0
EB
82 /// whether StoreMap::abortWriting() was called for a read-locked entry
83 std::atomic<uint8_t> writerHalted;
44c95fcf 84
ce49546e 85 // fields marked with [app] can be modified when appending-while-reading
abf396ec 86 // fields marked with [update] can be modified when updating-while-reading
ce49546e 87
b56b37cf 88 uint64_t key[2] = {0, 0}; ///< StoreEntry key
44c95fcf
AR
89
90 // STORE_META_STD TLV field from StoreEntry
91 struct Basics {
b56b37cf
AJ
92 void clear() {
93 timestamp = 0;
94 lastref = 0;
95 expires = 0;
96 lastmod = 0;
97 swap_file_sz.store(0);
98 refcount = 0;
99 flags = 0;
100 }
101 time_t timestamp = 0;
102 time_t lastref = 0;
103 time_t expires = 0;
104 time_t lastmod = 0;
d2b13bab 105 std::atomic<uint64_t> swap_file_sz; // [app]
b56b37cf
AJ
106 uint16_t refcount = 0;
107 uint16_t flags = 0;
9199139f 108 } basics;
44c95fcf 109
e6d2c263 110 /// where the chain of StoreEntry slices begins [app]
d2b13bab 111 std::atomic<StoreMapSliceId> start;
abf396ec
AR
112
113 /// where the updated chain prefix containing metadata/headers ends [update]
114 /// if unset, this anchor points to a chain that was never updated
115 std::atomic<StoreMapSliceId> splicingPoint;
1860fbac
AR
116};
117
118/// an array of shareable Items
119/// must be the last data member or, if used as a parent class, the last parent
120template <class C>
121class StoreMapItems
122{
123public:
124 typedef C Item;
125 typedef Ipc::Mem::Owner< StoreMapItems<Item> > Owner;
126
127 explicit StoreMapItems(const int aCapacity): capacity(aCapacity), items(aCapacity) {}
50dc81ec 128
1860fbac
AR
129 size_t sharedMemorySize() const { return SharedMemorySize(capacity); }
130 static size_t SharedMemorySize(const int aCapacity) { return sizeof(StoreMapItems<Item>) + aCapacity*sizeof(Item); }
131
132 const int capacity; ///< total number of items
133 Ipc::Mem::FlexibleArray<Item> items; ///< storage
44c95fcf
AR
134};
135
1860fbac
AR
136/// StoreMapSlices indexed by their slice ID.
137typedef StoreMapItems<StoreMapSlice> StoreMapSlices;
138
abf396ec 139/// StoreMapAnchors (indexed by fileno) plus
1860fbac
AR
140/// sharing-safe basic housekeeping info about Store entries
141class StoreMapAnchors
9d4e9cfb 142{
50dc81ec 143public:
1860fbac
AR
144 typedef Ipc::Mem::Owner< StoreMapAnchors > Owner;
145
146 explicit StoreMapAnchors(const int aCapacity);
147
148 size_t sharedMemorySize() const;
149 static size_t SharedMemorySize(const int anAnchorLimit);
150
d2b13bab
AJ
151 std::atomic<int32_t> count; ///< current number of entries
152 std::atomic<uint32_t> victim; ///< starting point for purge search
1860fbac
AR
153 const int capacity; ///< total number of anchors
154 Ipc::Mem::FlexibleArray<StoreMapAnchor> items; ///< anchors storage
50dc81ec 155};
1860fbac 156// TODO: Find an elegant way to use StoreMapItems in StoreMapAnchors
50dc81ec 157
abf396ec
AR
158/// StoreMapAnchor positions, indexed by entry "name" (i.e., the entry key hash)
159typedef StoreMapItems< std::atomic<sfileno> > StoreMapFileNos;
160
161/// Aggregates information required for updating entry metadata and headers.
162class StoreMapUpdate
163{
164public:
165 /// During an update, the stored entry has two editions: stale and fresh.
166 class Edition
167 {
168 public:
169 Edition(): anchor(nullptr), fileNo(-1), name(-1), splicingPoint(-1) {}
170
171 /// whether this entry edition is currently used/initialized
172 explicit operator bool() const { return anchor; }
173
174 StoreMapAnchor *anchor; ///< StoreMap::anchors[fileNo], for convenience/speed
175 sfileno fileNo; ///< StoreMap::fileNos[name], for convenience/speed
176 sfileno name; ///< StoreEntry position in StoreMap::fileNos, for swapping Editions
177
178 /// the last slice in the chain still containing metadata/headers
179 StoreMapSliceId splicingPoint;
180 };
181
182 explicit StoreMapUpdate(StoreEntry *anEntry);
183 StoreMapUpdate(const StoreMapUpdate &other);
184 ~StoreMapUpdate();
185
186 StoreMapUpdate &operator =(const StoreMapUpdate &other) = delete;
187
188 StoreEntry *entry; ///< the store entry being updated
66d51f4f
AR
189 Edition stale; ///< old anchor and chain
190 Edition fresh; ///< new anchor and the updated chain prefix
abf396ec
AR
191};
192
7f6748c8
AR
193class StoreMapCleaner;
194
1860fbac 195/// Manages shared Store index (e.g., locking/unlocking/freeing entries) using
abf396ec
AR
196/// StoreMapFileNos indexed by hashed entry keys (a.k.a. entry names),
197/// StoreMapAnchors indexed by fileno, and
198/// StoreMapSlices indexed by slice ID.
44c95fcf
AR
199class StoreMap
200{
201public:
abf396ec 202 typedef StoreMapFileNos FileNos;
50dc81ec 203 typedef StoreMapAnchor Anchor;
1860fbac 204 typedef StoreMapAnchors Anchors;
50dc81ec
AR
205 typedef sfileno AnchorId;
206 typedef StoreMapSlice Slice;
1860fbac 207 typedef StoreMapSlices Slices;
50dc81ec 208 typedef StoreMapSliceId SliceId;
abf396ec 209 typedef StoreMapUpdate Update;
44c95fcf 210
1860fbac
AR
211public:
212 /// aggregates anchor and slice owners for Init() caller convenience
2da4bfe6
A
213 class Owner
214 {
f8f98441 215 public:
1860fbac
AR
216 Owner();
217 ~Owner();
abf396ec 218 FileNos::Owner *fileNos;
1860fbac
AR
219 Anchors::Owner *anchors;
220 Slices::Owner *slices;
221 private:
222 Owner(const Owner &); // not implemented
223 Owner &operator =(const Owner &); // not implemented
68353d5a
DK
224 };
225
68353d5a 226 /// initialize shared memory
1860fbac 227 static Owner *Init(const SBuf &path, const int slotLimit);
68353d5a 228
1860fbac 229 StoreMap(const SBuf &aPath);
44c95fcf 230
abf396ec
AR
231 /// computes map entry anchor position for a given entry key
232 sfileno fileNoByKey(const cache_key *const key) const;
50dc81ec
AR
233
234 /// Like strcmp(mapped, new), but for store entry versions/timestamps.
235 /// Returns +2 if the mapped entry does not exist; -1/0/+1 otherwise.
236 /// Comparison may be inaccurate unless the caller is a lock holder.
237 int compareVersions(const sfileno oldFileno, time_t newVersion) const;
238
239 /// finds, locks, and returns an anchor for an empty key position,
240 /// erasing the old entry (if any)
241 Anchor *openForWriting(const cache_key *const key, sfileno &fileno);
242 /// locks and returns an anchor for the empty fileno position; if
243 /// overwriteExisting is false and the position is not empty, returns nil
244 Anchor *openForWritingAt(sfileno fileno, bool overwriteExisting = true);
ce49546e
AR
245 /// restrict opened for writing entry to appending operations; allow reads
246 void startAppending(const sfileno fileno);
50dc81ec 247 /// successfully finish creating or updating the entry at fileno pos
8253d451
AR
248 void closeForWriting(const sfileno fileno);
249 /// stop writing (or updating) the locked entry and start reading it
250 void switchWritingToReading(const sfileno fileno);
50dc81ec
AR
251 /// unlock and "forget" openForWriting entry, making it Empty again
252 /// this call does not free entry slices so the caller has to do that
253 void forgetWritingEntry(const sfileno fileno);
254
abf396ec
AR
255 /// finds and locks the Update entry for an exclusive metadata update
256 bool openForUpdating(Update &update, sfileno fileNoHint);
257 /// makes updated info available to others, unlocks, and cleans up
258 void closeForUpdating(Update &update);
259 /// undoes partial update, unlocks, and cleans up
260 void abortUpdating(Update &update);
261
d1d3b4dc
EB
262 /// the caller must hold a lock on the entry
263 /// \returns nullptr unless the slice is readable
50dc81ec
AR
264 const Anchor *peekAtReader(const sfileno fileno) const;
265
d1d3b4dc
EB
266 /// the caller must hold a lock on the entry
267 /// \returns nullptr unless the slice is writeable
268 const Anchor *peekAtWriter(const sfileno fileno) const;
269
270 /// the caller must hold a lock on the entry
271 /// \returns the corresponding Anchor
d366a7fa
AR
272 const Anchor &peekAtEntry(const sfileno fileno) const;
273
ce49546e 274 /// free the entry if possible or mark it as waiting to be freed if not
4310f8b0
EB
275 /// \returns whether the entry was neither empty nor marked
276 bool freeEntry(const sfileno);
ce49546e
AR
277 /// free the entry if possible or mark it as waiting to be freed if not
278 /// does nothing if we cannot check that the key matches the cached entry
279 void freeEntryByKey(const cache_key *const key);
50dc81ec 280
4310f8b0
EB
281 /// whether the entry with the given key exists and was marked as
282 /// "waiting to be freed" some time ago
283 bool markedForDeletion(const cache_key *const);
284
285 /// whether the index contains a valid readable entry with the given key
286 bool hasReadableEntry(const cache_key *const);
287
50dc81ec
AR
288 /// opens entry (identified by key) for reading, increments read level
289 const Anchor *openForReading(const cache_key *const key, sfileno &fileno);
290 /// opens entry (identified by sfileno) for reading, increments read level
b2aca62a 291 const Anchor *openForReadingAt(const sfileno, const cache_key *const);
50dc81ec
AR
292 /// closes open entry after reading, decrements read level
293 void closeForReading(const sfileno fileno);
d1d3b4dc
EB
294 /// same as closeForReading() but also frees the entry if it is unlocked
295 void closeForReadingAndFreeIdle(const sfileno fileno);
44c95fcf 296
50dc81ec
AR
297 /// writeable slice within an entry chain created by openForWriting()
298 Slice &writeableSlice(const AnchorId anchorId, const SliceId sliceId);
299 /// readable slice within an entry chain opened by openForReading()
300 const Slice &readableSlice(const AnchorId anchorId, const SliceId sliceId) const;
301 /// writeable anchor for the entry created by openForWriting()
302 Anchor &writeableEntry(const AnchorId anchorId);
ce49546e
AR
303 /// readable anchor for the entry created by openForReading()
304 const Anchor &readableEntry(const AnchorId anchorId) const;
44c95fcf 305
c2037547
EB
306 /// prepare a chain-unaffiliated slice for being added to an entry chain
307 void prepFreeSlice(const SliceId sliceId);
308
abf396ec
AR
309 /// Returns the ID of the entry slice containing n-th byte or
310 /// a negative ID if the entry does not store that many bytes (yet).
311 /// Requires a read lock.
312 SliceId sliceContaining(const sfileno fileno, const uint64_t nth) const;
313
a3023c03
AR
314 /// stop writing the entry, freeing its slot for others to use if possible
315 void abortWriting(const sfileno fileno);
44c95fcf 316
5bba33c9 317 /// either finds and frees an entry with at least 1 slice or returns false
50dc81ec 318 bool purgeOne();
44c95fcf 319
b2aca62a
EB
320 /// validates locked hit metadata and calls freeEntry() for invalid entries
321 /// \returns whether hit metadata is correct
322 bool validateHit(const sfileno);
323
324 void disableHitValidation() { hitValidation = false; }
325
50dc81ec
AR
326 /// copies slice to its designated position
327 void importSlice(const SliceId sliceId, const Slice &slice);
44c95fcf 328
36c84e19
AR
329 /* SwapFilenMax limits the number of entries, but not slices or slots */
330 bool validEntry(const int n) const; ///< whether n is a valid slice coordinate
331 bool validSlice(const int n) const; ///< whether n is a valid slice coordinate
50dc81ec
AR
332 int entryCount() const; ///< number of writeable and readable entries
333 int entryLimit() const; ///< maximum entryCount() possible
36c84e19 334 int sliceLimit() const; ///< maximum number of slices possible
44c95fcf
AR
335
336 /// adds approximate current stats to the supplied ones
337 void updateStats(ReadWriteLockStats &stats) const;
338
7f6748c8
AR
339 StoreMapCleaner *cleaner; ///< notified before a readable entry is freed
340
44c95fcf 341protected:
1860fbac 342 const SBuf path; ///< cache_dir path or similar cache name; for logging
abf396ec 343 Mem::Pointer<StoreMapFileNos> fileNos; ///< entry inodes (starting blocks)
1860fbac
AR
344 Mem::Pointer<StoreMapAnchors> anchors; ///< entry inodes (starting blocks)
345 Mem::Pointer<StoreMapSlices> slices; ///< chained entry pieces positions
44c95fcf
AR
346
347private:
abf396ec
AR
348 /// computes entry name (i.e., key hash) for a given entry key
349 sfileno nameByKey(const cache_key *const key) const;
350 /// computes anchor position for a given entry name
351 sfileno fileNoByName(const sfileno name) const;
352 void relocate(const sfileno name, const sfileno fileno);
353
1860fbac
AR
354 Anchor &anchorAt(const sfileno fileno);
355 const Anchor &anchorAt(const sfileno fileno) const;
50dc81ec 356 Anchor &anchorByKey(const cache_key *const key);
44c95fcf 357
1860fbac
AR
358 Slice &sliceAt(const SliceId sliceId);
359 const Slice &sliceAt(const SliceId sliceId) const;
50dc81ec 360 Anchor *openForReading(Slice &s);
abf396ec
AR
361 bool openKeyless(Update::Edition &edition);
362 void closeForUpdateFinal(Update &update);
363
364 typedef std::function<bool (const sfileno name)> NameFilter; // a "name"-based test
365 bool visitVictims(const NameFilter filter);
50dc81ec
AR
366
367 void freeChain(const sfileno fileno, Anchor &inode, const bool keepLock);
abf396ec 368 void freeChainAt(SliceId sliceId, const SliceId splicingPoint);
b2aca62a
EB
369
370 /// whether paranoid_hit_validation should be performed
371 bool hitValidation;
68353d5a 372};
44c95fcf 373
50dc81ec 374/// API for adjusting external state when dirty map slice is being freed
7f6748c8
AR
375class StoreMapCleaner
376{
377public:
378 virtual ~StoreMapCleaner() {}
379
50dc81ec 380 /// adjust slice-linked state before a locked Readable slice is erased
36c84e19 381 virtual void noteFreeMapSlice(const StoreMapSliceId sliceId) = 0;
7f6748c8
AR
382};
383
44c95fcf
AR
384} // namespace Ipc
385
75f8f9a2 386// We do not reuse FileMap because we cannot control its size,
44c95fcf
AR
387// resulting in sfilenos that are pointing beyond the database.
388
389#endif /* SQUID_IPC_STORE_MAP_H */
f53969cc 390