]> git.ipfire.org Git - thirdparty/squid.git/blob - src/fs/rock/RockSwapDir.cc
Bug 7: Update cached entries on 304 responses.
[thirdparty/squid.git] / src / fs / rock / RockSwapDir.cc
1 /*
2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
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
9 /* DEBUG: section 47 Store Directory Routines */
10
11 #include "squid.h"
12 #include "cache_cf.h"
13 #include "CollapsedForwarding.h"
14 #include "ConfigOption.h"
15 #include "DiskIO/DiskIOModule.h"
16 #include "DiskIO/DiskIOStrategy.h"
17 #include "DiskIO/ReadRequest.h"
18 #include "DiskIO/WriteRequest.h"
19 #include "fs/rock/RockHeaderUpdater.h"
20 #include "fs/rock/RockIoRequests.h"
21 #include "fs/rock/RockIoState.h"
22 #include "fs/rock/RockRebuild.h"
23 #include "fs/rock/RockSwapDir.h"
24 #include "globals.h"
25 #include "ipc/mem/Pages.h"
26 #include "MemObject.h"
27 #include "Parsing.h"
28 #include "SquidConfig.h"
29 #include "SquidMath.h"
30 #include "tools.h"
31
32 #include <cstdlib>
33 #include <iomanip>
34 #include <limits>
35
36 #if HAVE_SYS_STAT_H
37 #include <sys/stat.h>
38 #endif
39
40 const int64_t Rock::SwapDir::HeaderSize = 16*1024;
41
42 Rock::SwapDir::SwapDir(): ::SwapDir("rock"),
43 slotSize(HeaderSize), filePath(NULL), map(NULL), io(NULL),
44 waitingForPage(NULL)
45 {
46 }
47
48 Rock::SwapDir::~SwapDir()
49 {
50 delete io;
51 delete map;
52 safe_free(filePath);
53 }
54
55 // called when Squid core needs a StoreEntry with a given key
56 StoreEntry *
57 Rock::SwapDir::get(const cache_key *key)
58 {
59 if (!map || !theFile || !theFile->canRead())
60 return NULL;
61
62 sfileno filen;
63 const Ipc::StoreMapAnchor *const slot = map->openForReading(key, filen);
64 if (!slot)
65 return NULL;
66
67 // create a brand new store entry and initialize it with stored basics
68 StoreEntry *e = new StoreEntry();
69 anchorEntry(*e, filen, *slot);
70
71 e->hashInsert(key);
72 trackReferences(*e);
73
74 return e;
75 // the disk entry remains open for reading, protected from modifications
76 }
77
78 bool
79 Rock::SwapDir::anchorCollapsed(StoreEntry &collapsed, bool &inSync)
80 {
81 if (!map || !theFile || !theFile->canRead())
82 return false;
83
84 sfileno filen;
85 const Ipc::StoreMapAnchor *const slot = map->openForReading(
86 reinterpret_cast<cache_key*>(collapsed.key), filen);
87 if (!slot)
88 return false;
89
90 anchorEntry(collapsed, filen, *slot);
91 inSync = updateCollapsedWith(collapsed, *slot);
92 return true; // even if inSync is false
93 }
94
95 bool
96 Rock::SwapDir::updateCollapsed(StoreEntry &collapsed)
97 {
98 if (!map || !theFile || !theFile->canRead())
99 return false;
100
101 if (collapsed.swap_filen < 0) // no longer using a disk cache
102 return true;
103 assert(collapsed.swap_dirn == index);
104
105 const Ipc::StoreMapAnchor &s = map->readableEntry(collapsed.swap_filen);
106 return updateCollapsedWith(collapsed, s);
107 }
108
109 bool
110 Rock::SwapDir::updateCollapsedWith(StoreEntry &collapsed, const Ipc::StoreMapAnchor &anchor)
111 {
112 collapsed.swap_file_sz = anchor.basics.swap_file_sz;
113 return true;
114 }
115
116 void
117 Rock::SwapDir::anchorEntry(StoreEntry &e, const sfileno filen, const Ipc::StoreMapAnchor &anchor)
118 {
119 const Ipc::StoreMapAnchor::Basics &basics = anchor.basics;
120
121 e.swap_file_sz = basics.swap_file_sz;
122 e.lastref = basics.lastref;
123 e.timestamp = basics.timestamp;
124 e.expires = basics.expires;
125 e.lastmod = basics.lastmod;
126 e.refcount = basics.refcount;
127 e.flags = basics.flags;
128
129 if (anchor.complete()) {
130 e.store_status = STORE_OK;
131 e.swap_status = SWAPOUT_DONE;
132 } else {
133 e.store_status = STORE_PENDING;
134 e.swap_status = SWAPOUT_WRITING; // even though another worker writes?
135 }
136
137 e.ping_status = PING_NONE;
138
139 EBIT_CLR(e.flags, RELEASE_REQUEST);
140 EBIT_CLR(e.flags, KEY_PRIVATE);
141 EBIT_SET(e.flags, ENTRY_VALIDATED);
142
143 e.swap_dirn = index;
144 e.swap_filen = filen;
145 }
146
147 void Rock::SwapDir::disconnect(StoreEntry &e)
148 {
149 assert(e.swap_dirn == index);
150 assert(e.swap_filen >= 0);
151 // cannot have SWAPOUT_NONE entry with swap_filen >= 0
152 assert(e.swap_status != SWAPOUT_NONE);
153
154 // do not rely on e.swap_status here because there is an async delay
155 // before it switches from SWAPOUT_WRITING to SWAPOUT_DONE.
156
157 // since e has swap_filen, its slot is locked for reading and/or writing
158 // but it is difficult to know whether THIS worker is reading or writing e,
159 // especially since we may switch from writing to reading. This code relies
160 // on Rock::IoState::writeableAnchor_ being set when we locked for writing.
161 if (e.mem_obj && e.mem_obj->swapout.sio != NULL &&
162 dynamic_cast<IoState&>(*e.mem_obj->swapout.sio).writeableAnchor_) {
163 map->abortWriting(e.swap_filen);
164 e.swap_dirn = -1;
165 e.swap_filen = -1;
166 e.swap_status = SWAPOUT_NONE;
167 dynamic_cast<IoState&>(*e.mem_obj->swapout.sio).writeableAnchor_ = NULL;
168 Store::Root().transientsAbandon(e); // broadcasts after the change
169 } else {
170 map->closeForReading(e.swap_filen);
171 e.swap_dirn = -1;
172 e.swap_filen = -1;
173 e.swap_status = SWAPOUT_NONE;
174 }
175 }
176
177 uint64_t
178 Rock::SwapDir::currentSize() const
179 {
180 const uint64_t spaceSize = !freeSlots ?
181 maxSize() : (slotSize * freeSlots->size());
182 // everything that is not free is in use
183 return maxSize() - spaceSize;
184 }
185
186 uint64_t
187 Rock::SwapDir::currentCount() const
188 {
189 return map ? map->entryCount() : 0;
190 }
191
192 /// In SMP mode only the disker process reports stats to avoid
193 /// counting the same stats by multiple processes.
194 bool
195 Rock::SwapDir::doReportStat() const
196 {
197 return ::SwapDir::doReportStat() && (!UsingSmp() || IamDiskProcess());
198 }
199
200 void
201 Rock::SwapDir::swappedOut(const StoreEntry &)
202 {
203 // stats are not stored but computed when needed
204 }
205
206 int64_t
207 Rock::SwapDir::slotLimitAbsolute() const
208 {
209 // the max value is an invalid one; all values must be below the limit
210 assert(std::numeric_limits<Ipc::StoreMapSliceId>::max() ==
211 std::numeric_limits<SlotId>::max());
212 return std::numeric_limits<SlotId>::max();
213 }
214
215 int64_t
216 Rock::SwapDir::slotLimitActual() const
217 {
218 const int64_t sWanted = (maxSize() - HeaderSize)/slotSize;
219 const int64_t sLimitLo = map ? map->sliceLimit() : 0; // dynamic shrinking unsupported
220 const int64_t sLimitHi = slotLimitAbsolute();
221 return min(max(sLimitLo, sWanted), sLimitHi);
222 }
223
224 int64_t
225 Rock::SwapDir::entryLimitActual() const
226 {
227 return min(slotLimitActual(), entryLimitAbsolute());
228 }
229
230 // TODO: encapsulate as a tool
231 void
232 Rock::SwapDir::create()
233 {
234 assert(path);
235 assert(filePath);
236
237 if (UsingSmp() && !IamDiskProcess()) {
238 debugs (47,3, HERE << "disker will create in " << path);
239 return;
240 }
241
242 debugs (47,3, HERE << "creating in " << path);
243
244 struct stat dir_sb;
245 if (::stat(path, &dir_sb) == 0) {
246 struct stat file_sb;
247 if (::stat(filePath, &file_sb) == 0) {
248 debugs (47, DBG_IMPORTANT, "Skipping existing Rock db: " << filePath);
249 return;
250 }
251 // else the db file is not there or is not accessible, and we will try
252 // to create it later below, generating a detailed error on failures.
253 } else { // path does not exist or is inaccessible
254 // If path exists but is not accessible, mkdir() below will fail, and
255 // the admin should see the error and act accordingly, so there is
256 // no need to distinguish ENOENT from other possible stat() errors.
257 debugs (47, DBG_IMPORTANT, "Creating Rock db directory: " << path);
258 const int res = mkdir(path, 0700);
259 if (res != 0)
260 createError("mkdir");
261 }
262
263 debugs (47, DBG_IMPORTANT, "Creating Rock db: " << filePath);
264 const int swap = open(filePath, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0600);
265 if (swap < 0)
266 createError("create");
267
268 #if SLOWLY_FILL_WITH_ZEROS
269 char block[1024];
270 Must(maxSize() % sizeof(block) == 0);
271 memset(block, '\0', sizeof(block));
272
273 for (off_t offset = 0; offset < maxSize(); offset += sizeof(block)) {
274 if (write(swap, block, sizeof(block)) != sizeof(block))
275 createError("write");
276 }
277 #else
278 if (ftruncate(swap, maxSize()) != 0)
279 createError("truncate");
280
281 char header[HeaderSize];
282 memset(header, '\0', sizeof(header));
283 if (write(swap, header, sizeof(header)) != sizeof(header))
284 createError("write");
285 #endif
286
287 close(swap);
288 }
289
290 // report Rock DB creation error and exit
291 void
292 Rock::SwapDir::createError(const char *const msg)
293 {
294 debugs(47, DBG_CRITICAL, "ERROR: Failed to initialize Rock Store db in " <<
295 filePath << "; " << msg << " error: " << xstrerror());
296 fatal("Rock Store db creation error");
297 }
298
299 void
300 Rock::SwapDir::init()
301 {
302 debugs(47,2, HERE);
303
304 // XXX: SwapDirs aren't refcounted. We make IORequestor calls, which
305 // are refcounted. We up our count once to avoid implicit delete's.
306 lock();
307
308 freeSlots = shm_old(Ipc::Mem::PageStack)(freeSlotsPath());
309
310 Must(!map);
311 map = new DirMap(inodeMapPath());
312 map->cleaner = this;
313
314 const char *ioModule = needsDiskStrand() ? "IpcIo" : "Blocking";
315 if (DiskIOModule *m = DiskIOModule::Find(ioModule)) {
316 debugs(47,2, HERE << "Using DiskIO module: " << ioModule);
317 io = m->createStrategy();
318 io->init();
319 } else {
320 debugs(47, DBG_CRITICAL, "FATAL: Rock store is missing DiskIO module: " <<
321 ioModule);
322 fatal("Rock Store missing a required DiskIO module");
323 }
324
325 theFile = io->newFile(filePath);
326 theFile->configure(fileConfig);
327 theFile->open(O_RDWR, 0644, this);
328
329 // Increment early. Otherwise, if one SwapDir finishes rebuild before
330 // others start, storeRebuildComplete() will think the rebuild is over!
331 // TODO: move store_dirs_rebuilding hack to store modules that need it.
332 ++StoreController::store_dirs_rebuilding;
333 }
334
335 bool
336 Rock::SwapDir::needsDiskStrand() const
337 {
338 const bool wontEvenWorkWithoutDisker = Config.workers > 1;
339 const bool wouldWorkBetterWithDisker = DiskIOModule::Find("IpcIo");
340 return InDaemonMode() && (wontEvenWorkWithoutDisker ||
341 wouldWorkBetterWithDisker);
342 }
343
344 void
345 Rock::SwapDir::parse(int anIndex, char *aPath)
346 {
347 index = anIndex;
348
349 path = xstrdup(aPath);
350
351 // cache store is located at path/db
352 String fname(path);
353 fname.append("/rock");
354 filePath = xstrdup(fname.termedBuf());
355
356 parseSize(false);
357 parseOptions(0);
358
359 // Current openForWriting() code overwrites the old slot if needed
360 // and possible, so proactively removing old slots is probably useless.
361 assert(!repl); // repl = createRemovalPolicy(Config.replPolicy);
362
363 validateOptions();
364 }
365
366 void
367 Rock::SwapDir::reconfigure()
368 {
369 parseSize(true);
370 parseOptions(1);
371 // TODO: can we reconfigure the replacement policy (repl)?
372 validateOptions();
373 }
374
375 /// parse maximum db disk size
376 void
377 Rock::SwapDir::parseSize(const bool reconfig)
378 {
379 const int i = GetInteger();
380 if (i < 0)
381 fatal("negative Rock cache_dir size value");
382 const uint64_t new_max_size =
383 static_cast<uint64_t>(i) << 20; // MBytes to Bytes
384 if (!reconfig)
385 max_size = new_max_size;
386 else if (new_max_size != max_size) {
387 debugs(3, DBG_IMPORTANT, "WARNING: cache_dir '" << path << "' size "
388 "cannot be changed dynamically, value left unchanged (" <<
389 (max_size >> 20) << " MB)");
390 }
391 }
392
393 ConfigOption *
394 Rock::SwapDir::getOptionTree() const
395 {
396 ConfigOption *copt = ::SwapDir::getOptionTree();
397 ConfigOptionVector *vector = dynamic_cast<ConfigOptionVector*>(copt);
398 if (vector) {
399 // if copt is actually a ConfigOptionVector
400 vector->options.push_back(new ConfigOptionAdapter<SwapDir>(*const_cast<SwapDir *>(this), &SwapDir::parseSizeOption, &SwapDir::dumpSizeOption));
401 vector->options.push_back(new ConfigOptionAdapter<SwapDir>(*const_cast<SwapDir *>(this), &SwapDir::parseTimeOption, &SwapDir::dumpTimeOption));
402 vector->options.push_back(new ConfigOptionAdapter<SwapDir>(*const_cast<SwapDir *>(this), &SwapDir::parseRateOption, &SwapDir::dumpRateOption));
403 } else {
404 // we don't know how to handle copt, as it's not a ConfigOptionVector.
405 // free it (and return nullptr)
406 delete copt;
407 copt = nullptr;
408 }
409 return copt;
410 }
411
412 bool
413 Rock::SwapDir::allowOptionReconfigure(const char *const option) const
414 {
415 return strcmp(option, "slot-size") != 0 &&
416 ::SwapDir::allowOptionReconfigure(option);
417 }
418
419 /// parses time-specific options; mimics ::SwapDir::optionObjectSizeParse()
420 bool
421 Rock::SwapDir::parseTimeOption(char const *option, const char *value, int reconfig)
422 {
423 // TODO: ::SwapDir or, better, Config should provide time-parsing routines,
424 // including time unit handling. Same for size and rate.
425
426 time_msec_t *storedTime;
427 if (strcmp(option, "swap-timeout") == 0)
428 storedTime = &fileConfig.ioTimeout;
429 else
430 return false;
431
432 if (!value)
433 self_destruct();
434
435 // TODO: handle time units and detect parsing errors better
436 const int64_t parsedValue = strtoll(value, NULL, 10);
437 if (parsedValue < 0) {
438 debugs(3, DBG_CRITICAL, "FATAL: cache_dir " << path << ' ' << option << " must not be negative but is: " << parsedValue);
439 self_destruct();
440 }
441
442 const time_msec_t newTime = static_cast<time_msec_t>(parsedValue);
443
444 if (!reconfig)
445 *storedTime = newTime;
446 else if (*storedTime != newTime) {
447 debugs(3, DBG_IMPORTANT, "WARNING: cache_dir " << path << ' ' << option
448 << " cannot be changed dynamically, value left unchanged: " <<
449 *storedTime);
450 }
451
452 return true;
453 }
454
455 /// reports time-specific options; mimics ::SwapDir::optionObjectSizeDump()
456 void
457 Rock::SwapDir::dumpTimeOption(StoreEntry * e) const
458 {
459 if (fileConfig.ioTimeout)
460 storeAppendPrintf(e, " swap-timeout=%" PRId64,
461 static_cast<int64_t>(fileConfig.ioTimeout));
462 }
463
464 /// parses rate-specific options; mimics ::SwapDir::optionObjectSizeParse()
465 bool
466 Rock::SwapDir::parseRateOption(char const *option, const char *value, int isaReconfig)
467 {
468 int *storedRate;
469 if (strcmp(option, "max-swap-rate") == 0)
470 storedRate = &fileConfig.ioRate;
471 else
472 return false;
473
474 if (!value)
475 self_destruct();
476
477 // TODO: handle time units and detect parsing errors better
478 const int64_t parsedValue = strtoll(value, NULL, 10);
479 if (parsedValue < 0) {
480 debugs(3, DBG_CRITICAL, "FATAL: cache_dir " << path << ' ' << option << " must not be negative but is: " << parsedValue);
481 self_destruct();
482 }
483
484 const int newRate = static_cast<int>(parsedValue);
485
486 if (newRate < 0) {
487 debugs(3, DBG_CRITICAL, "FATAL: cache_dir " << path << ' ' << option << " must not be negative but is: " << newRate);
488 self_destruct();
489 }
490
491 if (!isaReconfig)
492 *storedRate = newRate;
493 else if (*storedRate != newRate) {
494 debugs(3, DBG_IMPORTANT, "WARNING: cache_dir " << path << ' ' << option
495 << " cannot be changed dynamically, value left unchanged: " <<
496 *storedRate);
497 }
498
499 return true;
500 }
501
502 /// reports rate-specific options; mimics ::SwapDir::optionObjectSizeDump()
503 void
504 Rock::SwapDir::dumpRateOption(StoreEntry * e) const
505 {
506 if (fileConfig.ioRate >= 0)
507 storeAppendPrintf(e, " max-swap-rate=%d", fileConfig.ioRate);
508 }
509
510 /// parses size-specific options; mimics ::SwapDir::optionObjectSizeParse()
511 bool
512 Rock::SwapDir::parseSizeOption(char const *option, const char *value, int reconfig)
513 {
514 uint64_t *storedSize;
515 if (strcmp(option, "slot-size") == 0)
516 storedSize = &slotSize;
517 else
518 return false;
519
520 if (!value)
521 self_destruct();
522
523 // TODO: handle size units and detect parsing errors better
524 const uint64_t newSize = strtoll(value, NULL, 10);
525 if (newSize <= 0) {
526 debugs(3, DBG_CRITICAL, "FATAL: cache_dir " << path << ' ' << option << " must be positive; got: " << newSize);
527 self_destruct();
528 }
529
530 if (newSize <= sizeof(DbCellHeader)) {
531 debugs(3, DBG_CRITICAL, "FATAL: cache_dir " << path << ' ' << option << " must exceed " << sizeof(DbCellHeader) << "; got: " << newSize);
532 self_destruct();
533 }
534
535 if (!reconfig)
536 *storedSize = newSize;
537 else if (*storedSize != newSize) {
538 debugs(3, DBG_IMPORTANT, "WARNING: cache_dir " << path << ' ' << option
539 << " cannot be changed dynamically, value left unchanged: " <<
540 *storedSize);
541 }
542
543 return true;
544 }
545
546 /// reports size-specific options; mimics ::SwapDir::optionObjectSizeDump()
547 void
548 Rock::SwapDir::dumpSizeOption(StoreEntry * e) const
549 {
550 storeAppendPrintf(e, " slot-size=%" PRId64, slotSize);
551 }
552
553 /// check the results of the configuration; only level-0 debugging works here
554 void
555 Rock::SwapDir::validateOptions()
556 {
557 if (slotSize <= 0)
558 fatal("Rock store requires a positive slot-size");
559
560 const int64_t maxSizeRoundingWaste = 1024 * 1024; // size is configured in MB
561 const int64_t slotSizeRoundingWaste = slotSize;
562 const int64_t maxRoundingWaste =
563 max(maxSizeRoundingWaste, slotSizeRoundingWaste);
564
565 // an entry consumes at least one slot; round up to reduce false warnings
566 const int64_t blockSize = static_cast<int64_t>(slotSize);
567 const int64_t maxObjSize = max(blockSize,
568 ((maxObjectSize()+blockSize-1)/blockSize)*blockSize);
569
570 // Does the "sfileno*max-size" limit match configured db capacity?
571 const double entriesMayOccupy = entryLimitAbsolute()*static_cast<double>(maxObjSize);
572 if (entriesMayOccupy + maxRoundingWaste < maxSize()) {
573 const int64_t diskWasteSize = maxSize() - static_cast<int64_t>(entriesMayOccupy);
574 debugs(47, DBG_CRITICAL, "WARNING: Rock cache_dir " << path << " wastes disk space due to entry limits:" <<
575 "\n\tconfigured db capacity: " << maxSize() << " bytes" <<
576 "\n\tconfigured db slot size: " << slotSize << " bytes" <<
577 "\n\tconfigured maximum entry size: " << maxObjectSize() << " bytes" <<
578 "\n\tmaximum number of cache_dir entries supported by Squid: " << entryLimitAbsolute() <<
579 "\n\tdisk space all entries may use: " << entriesMayOccupy << " bytes" <<
580 "\n\tdisk space wasted: " << diskWasteSize << " bytes");
581 }
582
583 // Does the "absolute slot count" limit match configured db capacity?
584 const double slotsMayOccupy = slotLimitAbsolute()*static_cast<double>(slotSize);
585 if (slotsMayOccupy + maxRoundingWaste < maxSize()) {
586 const int64_t diskWasteSize = maxSize() - static_cast<int64_t>(entriesMayOccupy);
587 debugs(47, DBG_CRITICAL, "WARNING: Rock cache_dir " << path << " wastes disk space due to slot limits:" <<
588 "\n\tconfigured db capacity: " << maxSize() << " bytes" <<
589 "\n\tconfigured db slot size: " << slotSize << " bytes" <<
590 "\n\tmaximum number of rock cache_dir slots supported by Squid: " << slotLimitAbsolute() <<
591 "\n\tdisk space all slots may use: " << slotsMayOccupy << " bytes" <<
592 "\n\tdisk space wasted: " << diskWasteSize << " bytes");
593 }
594 }
595
596 void
597 Rock::SwapDir::rebuild()
598 {
599 //++StoreController::store_dirs_rebuilding; // see Rock::SwapDir::init()
600 AsyncJob::Start(new Rebuild(this));
601 }
602
603 bool
604 Rock::SwapDir::canStore(const StoreEntry &e, int64_t diskSpaceNeeded, int &load) const
605 {
606 if (!::SwapDir::canStore(e, sizeof(DbCellHeader)+diskSpaceNeeded, load))
607 return false;
608
609 if (!theFile || !theFile->canWrite())
610 return false;
611
612 if (!map)
613 return false;
614
615 // Do not start I/O transaction if there are less than 10% free pages left.
616 // TODO: reserve page instead
617 if (needsDiskStrand() &&
618 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage)) {
619 debugs(47, 5, HERE << "too few shared pages for IPC I/O left");
620 return false;
621 }
622
623 if (io->shedLoad())
624 return false;
625
626 load = io->load();
627 return true;
628 }
629
630 StoreIOState::Pointer
631 Rock::SwapDir::createStoreIO(StoreEntry &e, StoreIOState::STFNCB *cbFile, StoreIOState::STIOCB *cbIo, void *data)
632 {
633 if (!theFile || theFile->error()) {
634 debugs(47,4, HERE << theFile);
635 return NULL;
636 }
637
638 sfileno filen;
639 Ipc::StoreMapAnchor *const slot =
640 map->openForWriting(reinterpret_cast<const cache_key *>(e.key), filen);
641 if (!slot) {
642 debugs(47, 5, HERE << "map->add failed");
643 return NULL;
644 }
645
646 assert(filen >= 0);
647 slot->set(e);
648
649 // XXX: We rely on our caller, storeSwapOutStart(), to set e.fileno.
650 // If that does not happen, the entry will not decrement the read level!
651
652 Rock::SwapDir::Pointer self(this);
653 IoState *sio = new IoState(self, &e, cbFile, cbIo, data);
654
655 sio->swap_dirn = index;
656 sio->swap_filen = filen;
657 sio->writeableAnchor_ = slot;
658
659 debugs(47,5, HERE << "dir " << index << " created new filen " <<
660 std::setfill('0') << std::hex << std::uppercase << std::setw(8) <<
661 sio->swap_filen << std::dec << " starting at " <<
662 diskOffset(sio->swap_filen));
663
664 sio->file(theFile);
665
666 trackReferences(e);
667 return sio;
668 }
669
670 StoreIOState::Pointer
671 Rock::SwapDir::createUpdateIO(const Ipc::StoreMapUpdate &update, StoreIOState::STFNCB *cbFile, StoreIOState::STIOCB *cbIo, void *data)
672 {
673 if (!theFile || theFile->error()) {
674 debugs(47,4, theFile);
675 return nullptr;
676 }
677
678 Must(update.fresh);
679 Must(update.fresh.fileNo >= 0);
680
681 Rock::SwapDir::Pointer self(this);
682 IoState *sio = new IoState(self, update.entry, cbFile, cbIo, data);
683
684 sio->swap_dirn = index;
685 sio->swap_filen = update.fresh.fileNo;
686 sio->writeableAnchor_ = update.fresh.anchor;
687
688 debugs(47,5, "dir " << index << " updating filen " <<
689 std::setfill('0') << std::hex << std::uppercase << std::setw(8) <<
690 sio->swap_filen << std::dec << " starting at " <<
691 diskOffset(sio->swap_filen));
692
693 sio->file(theFile);
694 return sio;
695 }
696
697 int64_t
698 Rock::SwapDir::diskOffset(const SlotId sid) const
699 {
700 assert(sid >= 0);
701 return HeaderSize + slotSize*sid;
702 }
703
704 int64_t
705 Rock::SwapDir::diskOffset(Ipc::Mem::PageId &pageId) const
706 {
707 assert(pageId);
708 return diskOffset(pageId.number - 1);
709 }
710
711 int64_t
712 Rock::SwapDir::diskOffsetLimit() const
713 {
714 assert(map);
715 return diskOffset(map->sliceLimit());
716 }
717
718 bool
719 Rock::SwapDir::useFreeSlot(Ipc::Mem::PageId &pageId)
720 {
721 if (freeSlots->pop(pageId)) {
722 debugs(47, 5, "got a previously free slot: " << pageId);
723 return true;
724 }
725
726 // catch free slots delivered to noteFreeMapSlice()
727 assert(!waitingForPage);
728 waitingForPage = &pageId;
729 if (map->purgeOne()) {
730 assert(!waitingForPage); // noteFreeMapSlice() should have cleared it
731 assert(pageId.set());
732 debugs(47, 5, "got a previously busy slot: " << pageId);
733 return true;
734 }
735 assert(waitingForPage == &pageId);
736 waitingForPage = NULL;
737
738 debugs(47, 3, "cannot get a slot; entries: " << map->entryCount());
739 return false;
740 }
741
742 bool
743 Rock::SwapDir::validSlotId(const SlotId slotId) const
744 {
745 return 0 <= slotId && slotId < slotLimitActual();
746 }
747
748 void
749 Rock::SwapDir::noteFreeMapSlice(const Ipc::StoreMapSliceId sliceId)
750 {
751 Ipc::Mem::PageId pageId;
752 pageId.pool = index+1;
753 pageId.number = sliceId+1;
754 if (waitingForPage) {
755 *waitingForPage = pageId;
756 waitingForPage = NULL;
757 } else {
758 freeSlots->push(pageId);
759 }
760 }
761
762 // tries to open an old entry with swap_filen for reading
763 StoreIOState::Pointer
764 Rock::SwapDir::openStoreIO(StoreEntry &e, StoreIOState::STFNCB *cbFile, StoreIOState::STIOCB *cbIo, void *data)
765 {
766 if (!theFile || theFile->error()) {
767 debugs(47,4, HERE << theFile);
768 return NULL;
769 }
770
771 if (e.swap_filen < 0) {
772 debugs(47,4, HERE << e);
773 return NULL;
774 }
775
776 // Do not start I/O transaction if there are less than 10% free pages left.
777 // TODO: reserve page instead
778 if (needsDiskStrand() &&
779 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage)) {
780 debugs(47, 5, HERE << "too few shared pages for IPC I/O left");
781 return NULL;
782 }
783
784 // The are two ways an entry can get swap_filen: our get() locked it for
785 // reading or our storeSwapOutStart() locked it for writing. Peeking at our
786 // locked entry is safe, but no support for reading the entry we swap out.
787 const Ipc::StoreMapAnchor *slot = map->peekAtReader(e.swap_filen);
788 if (!slot)
789 return NULL; // we were writing afterall
790
791 Rock::SwapDir::Pointer self(this);
792 IoState *sio = new IoState(self, &e, cbFile, cbIo, data);
793
794 sio->swap_dirn = index;
795 sio->swap_filen = e.swap_filen;
796 sio->readableAnchor_ = slot;
797 sio->file(theFile);
798
799 debugs(47,5, HERE << "dir " << index << " has old filen: " <<
800 std::setfill('0') << std::hex << std::uppercase << std::setw(8) <<
801 sio->swap_filen);
802
803 assert(slot->sameKey(static_cast<const cache_key*>(e.key)));
804 // For collapsed disk hits: e.swap_file_sz and slot->basics.swap_file_sz
805 // may still be zero and basics.swap_file_sz may grow.
806 assert(slot->basics.swap_file_sz >= e.swap_file_sz);
807
808 return sio;
809 }
810
811 void
812 Rock::SwapDir::ioCompletedNotification()
813 {
814 if (!theFile)
815 fatalf("Rock cache_dir failed to initialize db file: %s", filePath);
816
817 if (theFile->error())
818 fatalf("Rock cache_dir at %s failed to open db file: %s", filePath,
819 xstrerror());
820
821 debugs(47, 2, "Rock cache_dir[" << index << "] limits: " <<
822 std::setw(12) << maxSize() << " disk bytes, " <<
823 std::setw(7) << map->entryLimit() << " entries, and " <<
824 std::setw(7) << map->sliceLimit() << " slots");
825
826 rebuild();
827 }
828
829 void
830 Rock::SwapDir::closeCompleted()
831 {
832 theFile = NULL;
833 }
834
835 void
836 Rock::SwapDir::readCompleted(const char *, int rlen, int errflag, RefCount< ::ReadRequest> r)
837 {
838 ReadRequest *request = dynamic_cast<Rock::ReadRequest*>(r.getRaw());
839 assert(request);
840 IoState::Pointer sio = request->sio;
841
842 if (errflag == DISK_OK && rlen > 0)
843 sio->offset_ += rlen;
844
845 sio->callReaderBack(r->buf, rlen);
846 }
847
848 void
849 Rock::SwapDir::writeCompleted(int errflag, size_t, RefCount< ::WriteRequest> r)
850 {
851 Rock::WriteRequest *request = dynamic_cast<Rock::WriteRequest*>(r.getRaw());
852 assert(request);
853 assert(request->sio != NULL);
854 IoState &sio = *request->sio;
855
856 // quit if somebody called IoState::close() while we were waiting
857 if (!sio.stillWaiting()) {
858 debugs(79, 3, "ignoring closed entry " << sio.swap_filen);
859 noteFreeMapSlice(request->sidNext);
860 return;
861 }
862
863 debugs(79, 7, "errflag=" << errflag << " rlen=" << request->len << " eof=" << request->eof);
864
865 // TODO: Fail if disk dropped one of the previous write requests.
866
867 if (errflag == DISK_OK) {
868 // do not increment sio.offset_ because we do it in sio->write()
869
870 // finalize the shared slice info after writing slice contents to disk
871 Ipc::StoreMap::Slice &slice =
872 map->writeableSlice(sio.swap_filen, request->sidCurrent);
873 slice.size = request->len - sizeof(DbCellHeader);
874 slice.next = request->sidNext;
875
876 if (request->eof) {
877 assert(sio.e);
878 assert(sio.writeableAnchor_);
879 if (sio.touchingStoreEntry()) {
880 sio.e->swap_file_sz = sio.writeableAnchor_->basics.swap_file_sz =
881 sio.offset_;
882
883 // close, the entry gets the read lock
884 map->closeForWriting(sio.swap_filen, true);
885 }
886 sio.writeableAnchor_ = NULL;
887 sio.splicingPoint = request->sidCurrent;
888 sio.finishedWriting(errflag);
889 }
890 } else {
891 noteFreeMapSlice(request->sidNext);
892
893 writeError(sio);
894 sio.finishedWriting(errflag);
895 // and hope that Core will call disconnect() to close the map entry
896 }
897
898 if (sio.touchingStoreEntry())
899 CollapsedForwarding::Broadcast(*sio.e);
900 }
901
902 void
903 Rock::SwapDir::writeError(StoreIOState &sio)
904 {
905 // Do not abortWriting here. The entry should keep the write lock
906 // instead of losing association with the store and confusing core.
907 map->freeEntry(sio.swap_filen); // will mark as unusable, just in case
908
909 if (sio.touchingStoreEntry())
910 Store::Root().transientsAbandon(*sio.e);
911 // else noop: a fresh entry update error does not affect stale entry readers
912
913 // All callers must also call IoState callback, to propagate the error.
914 }
915
916 void
917 Rock::SwapDir::updateHeaders(StoreEntry *updatedE)
918 {
919 if (!map)
920 return;
921
922 Ipc::StoreMapUpdate update(updatedE);
923 if (!map->openForUpdating(update, updatedE->swap_filen))
924 return;
925
926 try {
927 AsyncJob::Start(new HeaderUpdater(this, update));
928 } catch (const std::exception &ex) {
929 debugs(20, 2, "error starting to update entry " << *updatedE << ": " << ex.what());
930 map->abortUpdating(update);
931 }
932 }
933
934 bool
935 Rock::SwapDir::full() const
936 {
937 return freeSlots != NULL && !freeSlots->size();
938 }
939
940 // storeSwapOutFileClosed calls this nethod on DISK_NO_SPACE_LEFT,
941 // but it should not happen for us
942 void
943 Rock::SwapDir::diskFull()
944 {
945 debugs(20, DBG_IMPORTANT, "BUG: No space left with rock cache_dir: " <<
946 filePath);
947 }
948
949 /// purge while full(); it should be sufficient to purge just one
950 void
951 Rock::SwapDir::maintain()
952 {
953 // The Store calls this to free some db space, but there is nothing wrong
954 // with a full() db, except when db has to shrink after reconfigure, and
955 // we do not support shrinking yet (it would have to purge specific slots).
956 // TODO: Disable maintain() requests when they are pointless.
957 }
958
959 void
960 Rock::SwapDir::reference(StoreEntry &e)
961 {
962 debugs(47, 5, HERE << &e << ' ' << e.swap_dirn << ' ' << e.swap_filen);
963 if (repl && repl->Referenced)
964 repl->Referenced(repl, &e, &e.repl);
965 }
966
967 bool
968 Rock::SwapDir::dereference(StoreEntry &e)
969 {
970 debugs(47, 5, HERE << &e << ' ' << e.swap_dirn << ' ' << e.swap_filen);
971 if (repl && repl->Dereferenced)
972 repl->Dereferenced(repl, &e, &e.repl);
973
974 // no need to keep e in the global store_table for us; we have our own map
975 return false;
976 }
977
978 bool
979 Rock::SwapDir::unlinkdUseful() const
980 {
981 // no entry-specific files to unlink
982 return false;
983 }
984
985 void
986 Rock::SwapDir::unlink(StoreEntry &e)
987 {
988 debugs(47, 5, HERE << e);
989 ignoreReferences(e);
990 map->freeEntry(e.swap_filen);
991 disconnect(e);
992 }
993
994 void
995 Rock::SwapDir::markForUnlink(StoreEntry &e)
996 {
997 debugs(47, 5, e);
998 map->freeEntry(e.swap_filen);
999 }
1000
1001 void
1002 Rock::SwapDir::trackReferences(StoreEntry &e)
1003 {
1004 debugs(47, 5, HERE << e);
1005 if (repl)
1006 repl->Add(repl, &e, &e.repl);
1007 }
1008
1009 void
1010 Rock::SwapDir::ignoreReferences(StoreEntry &e)
1011 {
1012 debugs(47, 5, HERE << e);
1013 if (repl)
1014 repl->Remove(repl, &e, &e.repl);
1015 }
1016
1017 void
1018 Rock::SwapDir::statfs(StoreEntry &e) const
1019 {
1020 storeAppendPrintf(&e, "\n");
1021 storeAppendPrintf(&e, "Maximum Size: %" PRIu64 " KB\n", maxSize() >> 10);
1022 storeAppendPrintf(&e, "Current Size: %.2f KB %.2f%%\n",
1023 currentSize() / 1024.0,
1024 Math::doublePercent(currentSize(), maxSize()));
1025
1026 const int entryLimit = entryLimitActual();
1027 const int slotLimit = slotLimitActual();
1028 storeAppendPrintf(&e, "Maximum entries: %9d\n", entryLimit);
1029 if (map && entryLimit > 0) {
1030 const int entryCount = map->entryCount();
1031 storeAppendPrintf(&e, "Current entries: %9d %.2f%%\n",
1032 entryCount, (100.0 * entryCount / entryLimit));
1033 }
1034
1035 storeAppendPrintf(&e, "Maximum slots: %9d\n", slotLimit);
1036 if (map && slotLimit > 0) {
1037 const unsigned int slotsFree = !freeSlots ? 0 : freeSlots->size();
1038 if (slotsFree <= static_cast<const unsigned int>(slotLimit)) {
1039 const int usedSlots = slotLimit - static_cast<const int>(slotsFree);
1040 storeAppendPrintf(&e, "Used slots: %9d %.2f%%\n",
1041 usedSlots, (100.0 * usedSlots / slotLimit));
1042 }
1043 if (slotLimit < 100) { // XXX: otherwise too expensive to count
1044 Ipc::ReadWriteLockStats stats;
1045 map->updateStats(stats);
1046 stats.dump(e);
1047 }
1048 }
1049
1050 storeAppendPrintf(&e, "Pending operations: %d out of %d\n",
1051 store_open_disk_fd, Config.max_open_disk_fds);
1052
1053 storeAppendPrintf(&e, "Flags:");
1054
1055 if (flags.selected)
1056 storeAppendPrintf(&e, " SELECTED");
1057
1058 if (flags.read_only)
1059 storeAppendPrintf(&e, " READ-ONLY");
1060
1061 storeAppendPrintf(&e, "\n");
1062
1063 }
1064
1065 SBuf
1066 Rock::SwapDir::inodeMapPath() const
1067 {
1068 return Ipc::Mem::Segment::Name(SBuf(path), "map");
1069 }
1070
1071 const char *
1072 Rock::SwapDir::freeSlotsPath() const
1073 {
1074 static String spacesPath;
1075 spacesPath = path;
1076 spacesPath.append("_spaces");
1077 return spacesPath.termedBuf();
1078 }
1079
1080 namespace Rock
1081 {
1082 RunnerRegistrationEntry(SwapDirRr);
1083 }
1084
1085 void Rock::SwapDirRr::create()
1086 {
1087 Must(mapOwners.empty() && freeSlotsOwners.empty());
1088 for (int i = 0; i < Config.cacheSwap.n_configured; ++i) {
1089 if (const Rock::SwapDir *const sd = dynamic_cast<Rock::SwapDir *>(INDEXSD(i))) {
1090 const int64_t capacity = sd->slotLimitActual();
1091
1092 SwapDir::DirMap::Owner *const mapOwner =
1093 SwapDir::DirMap::Init(sd->inodeMapPath(), capacity);
1094 mapOwners.push_back(mapOwner);
1095
1096 // TODO: somehow remove pool id and counters from PageStack?
1097 Ipc::Mem::Owner<Ipc::Mem::PageStack> *const freeSlotsOwner =
1098 shm_new(Ipc::Mem::PageStack)(sd->freeSlotsPath(),
1099 i+1, capacity, 0);
1100 freeSlotsOwners.push_back(freeSlotsOwner);
1101
1102 // TODO: add method to initialize PageStack with no free pages
1103 while (true) {
1104 Ipc::Mem::PageId pageId;
1105 if (!freeSlotsOwner->object()->pop(pageId))
1106 break;
1107 }
1108 }
1109 }
1110 }
1111
1112 Rock::SwapDirRr::~SwapDirRr()
1113 {
1114 for (size_t i = 0; i < mapOwners.size(); ++i) {
1115 delete mapOwners[i];
1116 delete freeSlotsOwners[i];
1117 }
1118 }
1119