2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section 47 Store Directory Routines */
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/RockIoRequests.h"
20 #include "fs/rock/RockIoState.h"
21 #include "fs/rock/RockRebuild.h"
22 #include "fs/rock/RockSwapDir.h"
24 #include "ipc/mem/Pages.h"
25 #include "MemObject.h"
27 #include "SquidConfig.h"
28 #include "SquidMath.h"
39 const int64_t Rock::SwapDir::HeaderSize
= 16*1024;
41 Rock::SwapDir::SwapDir(): ::SwapDir("rock"),
42 slotSize(HeaderSize
), filePath(NULL
), map(NULL
), io(NULL
),
47 Rock::SwapDir::~SwapDir()
55 Rock::SwapDir::search(String
const, HttpRequest
*)
58 return NULL
; // XXX: implement
62 Rock::SwapDir::get(String
const key
, STOREGETCLIENT cb
, void *data
)
64 ::SwapDir::get(key
, cb
, data
);
67 // called when Squid core needs a StoreEntry with a given key
69 Rock::SwapDir::get(const cache_key
*key
)
71 if (!map
|| !theFile
|| !theFile
->canRead())
75 const Ipc::StoreMapAnchor
*const slot
= map
->openForReading(key
, filen
);
79 // create a brand new store entry and initialize it with stored basics
80 StoreEntry
*e
= new StoreEntry();
81 anchorEntry(*e
, filen
, *slot
);
87 // the disk entry remains open for reading, protected from modifications
91 Rock::SwapDir::anchorCollapsed(StoreEntry
&collapsed
, bool &inSync
)
93 if (!map
|| !theFile
|| !theFile
->canRead())
97 const Ipc::StoreMapAnchor
*const slot
= map
->openForReading(
98 reinterpret_cast<cache_key
*>(collapsed
.key
), filen
);
102 anchorEntry(collapsed
, filen
, *slot
);
103 inSync
= updateCollapsedWith(collapsed
, *slot
);
104 return true; // even if inSync is false
108 Rock::SwapDir::updateCollapsed(StoreEntry
&collapsed
)
110 if (!map
|| !theFile
|| !theFile
->canRead())
113 if (collapsed
.swap_filen
< 0) // no longer using a disk cache
115 assert(collapsed
.swap_dirn
== index
);
117 const Ipc::StoreMapAnchor
&s
= map
->readableEntry(collapsed
.swap_filen
);
118 return updateCollapsedWith(collapsed
, s
);
122 Rock::SwapDir::updateCollapsedWith(StoreEntry
&collapsed
, const Ipc::StoreMapAnchor
&anchor
)
124 collapsed
.swap_file_sz
= anchor
.basics
.swap_file_sz
;
129 Rock::SwapDir::anchorEntry(StoreEntry
&e
, const sfileno filen
, const Ipc::StoreMapAnchor
&anchor
)
131 const Ipc::StoreMapAnchor::Basics
&basics
= anchor
.basics
;
133 e
.swap_file_sz
= basics
.swap_file_sz
;
134 e
.lastref
= basics
.lastref
;
135 e
.timestamp
= basics
.timestamp
;
136 e
.expires
= basics
.expires
;
137 e
.lastmod
= basics
.lastmod
;
138 e
.refcount
= basics
.refcount
;
139 e
.flags
= basics
.flags
;
141 if (anchor
.complete()) {
142 e
.store_status
= STORE_OK
;
143 e
.swap_status
= SWAPOUT_DONE
;
145 e
.store_status
= STORE_PENDING
;
146 e
.swap_status
= SWAPOUT_WRITING
; // even though another worker writes?
149 e
.ping_status
= PING_NONE
;
151 EBIT_CLR(e
.flags
, RELEASE_REQUEST
);
152 EBIT_CLR(e
.flags
, KEY_PRIVATE
);
153 EBIT_SET(e
.flags
, ENTRY_VALIDATED
);
156 e
.swap_filen
= filen
;
159 void Rock::SwapDir::disconnect(StoreEntry
&e
)
161 assert(e
.swap_dirn
== index
);
162 assert(e
.swap_filen
>= 0);
163 // cannot have SWAPOUT_NONE entry with swap_filen >= 0
164 assert(e
.swap_status
!= SWAPOUT_NONE
);
166 // do not rely on e.swap_status here because there is an async delay
167 // before it switches from SWAPOUT_WRITING to SWAPOUT_DONE.
169 // since e has swap_filen, its slot is locked for reading and/or writing
170 // but it is difficult to know whether THIS worker is reading or writing e,
171 // especially since we may switch from writing to reading. This code relies
172 // on Rock::IoState::writeableAnchor_ being set when we locked for writing.
173 if (e
.mem_obj
&& e
.mem_obj
->swapout
.sio
!= NULL
&&
174 dynamic_cast<IoState
&>(*e
.mem_obj
->swapout
.sio
).writeableAnchor_
) {
175 map
->abortWriting(e
.swap_filen
);
178 e
.swap_status
= SWAPOUT_NONE
;
179 dynamic_cast<IoState
&>(*e
.mem_obj
->swapout
.sio
).writeableAnchor_
= NULL
;
180 Store::Root().transientsAbandon(e
); // broadcasts after the change
182 map
->closeForReading(e
.swap_filen
);
185 e
.swap_status
= SWAPOUT_NONE
;
190 Rock::SwapDir::currentSize() const
192 const uint64_t spaceSize
= !freeSlots
?
193 maxSize() : (slotSize
* freeSlots
->size());
194 // everything that is not free is in use
195 return maxSize() - spaceSize
;
199 Rock::SwapDir::currentCount() const
201 return map
? map
->entryCount() : 0;
204 /// In SMP mode only the disker process reports stats to avoid
205 /// counting the same stats by multiple processes.
207 Rock::SwapDir::doReportStat() const
209 return ::SwapDir::doReportStat() && (!UsingSmp() || IamDiskProcess());
213 Rock::SwapDir::swappedOut(const StoreEntry
&)
215 // stats are not stored but computed when needed
219 Rock::SwapDir::slotLimitAbsolute() const
221 // the max value is an invalid one; all values must be below the limit
222 assert(std::numeric_limits
<Ipc::StoreMapSliceId
>::max() ==
223 std::numeric_limits
<SlotId
>::max());
224 return std::numeric_limits
<SlotId
>::max();
228 Rock::SwapDir::slotLimitActual() const
230 const int64_t sWanted
= (maxSize() - HeaderSize
)/slotSize
;
231 const int64_t sLimitLo
= map
? map
->sliceLimit() : 0; // dynamic shrinking unsupported
232 const int64_t sLimitHi
= slotLimitAbsolute();
233 return min(max(sLimitLo
, sWanted
), sLimitHi
);
237 Rock::SwapDir::entryLimitActual() const
239 return min(slotLimitActual(), entryLimitAbsolute());
242 // TODO: encapsulate as a tool
244 Rock::SwapDir::create()
249 if (UsingSmp() && !IamDiskProcess()) {
250 debugs (47,3, HERE
<< "disker will create in " << path
);
254 debugs (47,3, HERE
<< "creating in " << path
);
257 if (::stat(path
, &dir_sb
) == 0) {
259 if (::stat(filePath
, &file_sb
) == 0) {
260 debugs (47, DBG_IMPORTANT
, "Skipping existing Rock db: " << filePath
);
263 // else the db file is not there or is not accessible, and we will try
264 // to create it later below, generating a detailed error on failures.
265 } else { // path does not exist or is inaccessible
266 // If path exists but is not accessible, mkdir() below will fail, and
267 // the admin should see the error and act accordingly, so there is
268 // no need to distinguish ENOENT from other possible stat() errors.
269 debugs (47, DBG_IMPORTANT
, "Creating Rock db directory: " << path
);
270 const int res
= mkdir(path
, 0700);
272 createError("mkdir");
275 debugs (47, DBG_IMPORTANT
, "Creating Rock db: " << filePath
);
276 const int swap
= open(filePath
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_BINARY
, 0600);
278 createError("create");
280 #if SLOWLY_FILL_WITH_ZEROS
282 Must(maxSize() % sizeof(block
) == 0);
283 memset(block
, '\0', sizeof(block
));
285 for (off_t offset
= 0; offset
< maxSize(); offset
+= sizeof(block
)) {
286 if (write(swap
, block
, sizeof(block
)) != sizeof(block
))
287 createError("write");
290 if (ftruncate(swap
, maxSize()) != 0)
291 createError("truncate");
293 char header
[HeaderSize
];
294 memset(header
, '\0', sizeof(header
));
295 if (write(swap
, header
, sizeof(header
)) != sizeof(header
))
296 createError("write");
302 // report Rock DB creation error and exit
304 Rock::SwapDir::createError(const char *const msg
)
306 debugs(47, DBG_CRITICAL
, "ERROR: Failed to initialize Rock Store db in " <<
307 filePath
<< "; " << msg
<< " error: " << xstrerror());
308 fatal("Rock Store db creation error");
312 Rock::SwapDir::init()
316 // XXX: SwapDirs aren't refcounted. We make IORequestor calls, which
317 // are refcounted. We up our count once to avoid implicit delete's.
320 freeSlots
= shm_old(Ipc::Mem::PageStack
)(freeSlotsPath());
323 map
= new DirMap(inodeMapPath());
326 const char *ioModule
= needsDiskStrand() ? "IpcIo" : "Blocking";
327 if (DiskIOModule
*m
= DiskIOModule::Find(ioModule
)) {
328 debugs(47,2, HERE
<< "Using DiskIO module: " << ioModule
);
329 io
= m
->createStrategy();
332 debugs(47, DBG_CRITICAL
, "FATAL: Rock store is missing DiskIO module: " <<
334 fatal("Rock Store missing a required DiskIO module");
337 theFile
= io
->newFile(filePath
);
338 theFile
->configure(fileConfig
);
339 theFile
->open(O_RDWR
, 0644, this);
341 // Increment early. Otherwise, if one SwapDir finishes rebuild before
342 // others start, storeRebuildComplete() will think the rebuild is over!
343 // TODO: move store_dirs_rebuilding hack to store modules that need it.
344 ++StoreController::store_dirs_rebuilding
;
348 Rock::SwapDir::needsDiskStrand() const
350 const bool wontEvenWorkWithoutDisker
= Config
.workers
> 1;
351 const bool wouldWorkBetterWithDisker
= DiskIOModule::Find("IpcIo");
352 return InDaemonMode() && (wontEvenWorkWithoutDisker
||
353 wouldWorkBetterWithDisker
);
357 Rock::SwapDir::parse(int anIndex
, char *aPath
)
361 path
= xstrdup(aPath
);
363 // cache store is located at path/db
365 fname
.append("/rock");
366 filePath
= xstrdup(fname
.termedBuf());
371 // Current openForWriting() code overwrites the old slot if needed
372 // and possible, so proactively removing old slots is probably useless.
373 assert(!repl
); // repl = createRemovalPolicy(Config.replPolicy);
379 Rock::SwapDir::reconfigure()
383 // TODO: can we reconfigure the replacement policy (repl)?
387 /// parse maximum db disk size
389 Rock::SwapDir::parseSize(const bool reconfig
)
391 const int i
= GetInteger();
393 fatal("negative Rock cache_dir size value");
394 const uint64_t new_max_size
=
395 static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
397 max_size
= new_max_size
;
398 else if (new_max_size
!= max_size
) {
399 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir '" << path
<< "' size "
400 "cannot be changed dynamically, value left unchanged (" <<
401 (max_size
>> 20) << " MB)");
406 Rock::SwapDir::getOptionTree() const
408 ConfigOption
*copt
= ::SwapDir::getOptionTree();
409 ConfigOptionVector
*vector
= dynamic_cast<ConfigOptionVector
*>(copt
);
411 // if copt is actually a ConfigOptionVector
412 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseSizeOption
, &SwapDir::dumpSizeOption
));
413 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseTimeOption
, &SwapDir::dumpTimeOption
));
414 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseRateOption
, &SwapDir::dumpRateOption
));
416 // we don't know how to handle copt, as it's not a ConfigOptionVector.
417 // free it (and return nullptr)
424 Rock::SwapDir::allowOptionReconfigure(const char *const option
) const
426 return strcmp(option
, "slot-size") != 0 &&
427 ::SwapDir::allowOptionReconfigure(option
);
430 /// parses time-specific options; mimics ::SwapDir::optionObjectSizeParse()
432 Rock::SwapDir::parseTimeOption(char const *option
, const char *value
, int reconfig
)
434 // TODO: ::SwapDir or, better, Config should provide time-parsing routines,
435 // including time unit handling. Same for size and rate.
437 time_msec_t
*storedTime
;
438 if (strcmp(option
, "swap-timeout") == 0)
439 storedTime
= &fileConfig
.ioTimeout
;
446 // TODO: handle time units and detect parsing errors better
447 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
448 if (parsedValue
< 0) {
449 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
453 const time_msec_t newTime
= static_cast<time_msec_t
>(parsedValue
);
456 *storedTime
= newTime
;
457 else if (*storedTime
!= newTime
) {
458 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
459 << " cannot be changed dynamically, value left unchanged: " <<
466 /// reports time-specific options; mimics ::SwapDir::optionObjectSizeDump()
468 Rock::SwapDir::dumpTimeOption(StoreEntry
* e
) const
470 if (fileConfig
.ioTimeout
)
471 storeAppendPrintf(e
, " swap-timeout=%" PRId64
,
472 static_cast<int64_t>(fileConfig
.ioTimeout
));
475 /// parses rate-specific options; mimics ::SwapDir::optionObjectSizeParse()
477 Rock::SwapDir::parseRateOption(char const *option
, const char *value
, int isaReconfig
)
480 if (strcmp(option
, "max-swap-rate") == 0)
481 storedRate
= &fileConfig
.ioRate
;
488 // TODO: handle time units and detect parsing errors better
489 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
490 if (parsedValue
< 0) {
491 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
495 const int newRate
= static_cast<int>(parsedValue
);
498 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << newRate
);
503 *storedRate
= newRate
;
504 else if (*storedRate
!= newRate
) {
505 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
506 << " cannot be changed dynamically, value left unchanged: " <<
513 /// reports rate-specific options; mimics ::SwapDir::optionObjectSizeDump()
515 Rock::SwapDir::dumpRateOption(StoreEntry
* e
) const
517 if (fileConfig
.ioRate
>= 0)
518 storeAppendPrintf(e
, " max-swap-rate=%d", fileConfig
.ioRate
);
521 /// parses size-specific options; mimics ::SwapDir::optionObjectSizeParse()
523 Rock::SwapDir::parseSizeOption(char const *option
, const char *value
, int reconfig
)
525 uint64_t *storedSize
;
526 if (strcmp(option
, "slot-size") == 0)
527 storedSize
= &slotSize
;
534 // TODO: handle size units and detect parsing errors better
535 const uint64_t newSize
= strtoll(value
, NULL
, 10);
537 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must be positive; got: " << newSize
);
541 if (newSize
<= sizeof(DbCellHeader
)) {
542 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must exceed " << sizeof(DbCellHeader
) << "; got: " << newSize
);
547 *storedSize
= newSize
;
548 else if (*storedSize
!= newSize
) {
549 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
550 << " cannot be changed dynamically, value left unchanged: " <<
557 /// reports size-specific options; mimics ::SwapDir::optionObjectSizeDump()
559 Rock::SwapDir::dumpSizeOption(StoreEntry
* e
) const
561 storeAppendPrintf(e
, " slot-size=%" PRId64
, slotSize
);
564 /// check the results of the configuration; only level-0 debugging works here
566 Rock::SwapDir::validateOptions()
569 fatal("Rock store requires a positive slot-size");
571 const int64_t maxSizeRoundingWaste
= 1024 * 1024; // size is configured in MB
572 const int64_t slotSizeRoundingWaste
= slotSize
;
573 const int64_t maxRoundingWaste
=
574 max(maxSizeRoundingWaste
, slotSizeRoundingWaste
);
576 // an entry consumes at least one slot; round up to reduce false warnings
577 const int64_t blockSize
= static_cast<int64_t>(slotSize
);
578 const int64_t maxObjSize
= max(blockSize
,
579 ((maxObjectSize()+blockSize
-1)/blockSize
)*blockSize
);
581 // Does the "sfileno*max-size" limit match configured db capacity?
582 const double entriesMayOccupy
= entryLimitAbsolute()*static_cast<double>(maxObjSize
);
583 if (entriesMayOccupy
+ maxRoundingWaste
< maxSize()) {
584 const int64_t diskWasteSize
= maxSize() - static_cast<int64_t>(entriesMayOccupy
);
585 debugs(47, DBG_CRITICAL
, "WARNING: Rock cache_dir " << path
<< " wastes disk space due to entry limits:" <<
586 "\n\tconfigured db capacity: " << maxSize() << " bytes" <<
587 "\n\tconfigured db slot size: " << slotSize
<< " bytes" <<
588 "\n\tconfigured maximum entry size: " << maxObjectSize() << " bytes" <<
589 "\n\tmaximum number of cache_dir entries supported by Squid: " << entryLimitAbsolute() <<
590 "\n\tdisk space all entries may use: " << entriesMayOccupy
<< " bytes" <<
591 "\n\tdisk space wasted: " << diskWasteSize
<< " bytes");
594 // Does the "absolute slot count" limit match configured db capacity?
595 const double slotsMayOccupy
= slotLimitAbsolute()*static_cast<double>(slotSize
);
596 if (slotsMayOccupy
+ maxRoundingWaste
< maxSize()) {
597 const int64_t diskWasteSize
= maxSize() - static_cast<int64_t>(entriesMayOccupy
);
598 debugs(47, DBG_CRITICAL
, "WARNING: Rock cache_dir " << path
<< " wastes disk space due to slot limits:" <<
599 "\n\tconfigured db capacity: " << maxSize() << " bytes" <<
600 "\n\tconfigured db slot size: " << slotSize
<< " bytes" <<
601 "\n\tmaximum number of rock cache_dir slots supported by Squid: " << slotLimitAbsolute() <<
602 "\n\tdisk space all slots may use: " << slotsMayOccupy
<< " bytes" <<
603 "\n\tdisk space wasted: " << diskWasteSize
<< " bytes");
608 Rock::SwapDir::rebuild()
610 //++StoreController::store_dirs_rebuilding; // see Rock::SwapDir::init()
611 AsyncJob::Start(new Rebuild(this));
615 Rock::SwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
617 if (!::SwapDir::canStore(e
, sizeof(DbCellHeader
)+diskSpaceNeeded
, load
))
620 if (!theFile
|| !theFile
->canWrite())
626 // Do not start I/O transaction if there are less than 10% free pages left.
627 // TODO: reserve page instead
628 if (needsDiskStrand() &&
629 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
630 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
641 StoreIOState::Pointer
642 Rock::SwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
644 if (!theFile
|| theFile
->error()) {
645 debugs(47,4, HERE
<< theFile
);
650 Ipc::StoreMapAnchor
*const slot
=
651 map
->openForWriting(reinterpret_cast<const cache_key
*>(e
.key
), filen
);
653 debugs(47, 5, HERE
<< "map->add failed");
660 // XXX: We rely on our caller, storeSwapOutStart(), to set e.fileno.
661 // If that does not happen, the entry will not decrement the read level!
663 Rock::SwapDir::Pointer
self(this);
664 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
666 sio
->swap_dirn
= index
;
667 sio
->swap_filen
= filen
;
668 sio
->writeableAnchor_
= slot
;
670 debugs(47,5, HERE
<< "dir " << index
<< " created new filen " <<
671 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
672 sio
->swap_filen
<< std::dec
<< " starting at " <<
673 diskOffset(sio
->swap_filen
));
682 Rock::SwapDir::diskOffset(const SlotId sid
) const
685 return HeaderSize
+ slotSize
*sid
;
689 Rock::SwapDir::diskOffset(Ipc::Mem::PageId
&pageId
) const
692 return diskOffset(pageId
.number
- 1);
696 Rock::SwapDir::diskOffsetLimit() const
699 return diskOffset(map
->sliceLimit());
703 Rock::SwapDir::useFreeSlot(Ipc::Mem::PageId
&pageId
)
705 if (freeSlots
->pop(pageId
)) {
706 debugs(47, 5, "got a previously free slot: " << pageId
);
710 // catch free slots delivered to noteFreeMapSlice()
711 assert(!waitingForPage
);
712 waitingForPage
= &pageId
;
713 if (map
->purgeOne()) {
714 assert(!waitingForPage
); // noteFreeMapSlice() should have cleared it
715 assert(pageId
.set());
716 debugs(47, 5, "got a previously busy slot: " << pageId
);
719 assert(waitingForPage
== &pageId
);
720 waitingForPage
= NULL
;
722 debugs(47, 3, "cannot get a slot; entries: " << map
->entryCount());
727 Rock::SwapDir::validSlotId(const SlotId slotId
) const
729 return 0 <= slotId
&& slotId
< slotLimitActual();
733 Rock::SwapDir::noteFreeMapSlice(const Ipc::StoreMapSliceId sliceId
)
735 Ipc::Mem::PageId pageId
;
736 pageId
.pool
= index
+1;
737 pageId
.number
= sliceId
+1;
738 if (waitingForPage
) {
739 *waitingForPage
= pageId
;
740 waitingForPage
= NULL
;
742 freeSlots
->push(pageId
);
746 // tries to open an old entry with swap_filen for reading
747 StoreIOState::Pointer
748 Rock::SwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
750 if (!theFile
|| theFile
->error()) {
751 debugs(47,4, HERE
<< theFile
);
755 if (e
.swap_filen
< 0) {
756 debugs(47,4, HERE
<< e
);
760 // Do not start I/O transaction if there are less than 10% free pages left.
761 // TODO: reserve page instead
762 if (needsDiskStrand() &&
763 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
764 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
768 // The are two ways an entry can get swap_filen: our get() locked it for
769 // reading or our storeSwapOutStart() locked it for writing. Peeking at our
770 // locked entry is safe, but no support for reading the entry we swap out.
771 const Ipc::StoreMapAnchor
*slot
= map
->peekAtReader(e
.swap_filen
);
773 return NULL
; // we were writing afterall
775 Rock::SwapDir::Pointer
self(this);
776 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
778 sio
->swap_dirn
= index
;
779 sio
->swap_filen
= e
.swap_filen
;
780 sio
->readableAnchor_
= slot
;
783 debugs(47,5, HERE
<< "dir " << index
<< " has old filen: " <<
784 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
787 assert(slot
->sameKey(static_cast<const cache_key
*>(e
.key
)));
788 // For collapsed disk hits: e.swap_file_sz and slot->basics.swap_file_sz
789 // may still be zero and basics.swap_file_sz may grow.
790 assert(slot
->basics
.swap_file_sz
>= e
.swap_file_sz
);
796 Rock::SwapDir::ioCompletedNotification()
799 fatalf("Rock cache_dir failed to initialize db file: %s", filePath
);
801 if (theFile
->error())
802 fatalf("Rock cache_dir at %s failed to open db file: %s", filePath
,
805 debugs(47, 2, "Rock cache_dir[" << index
<< "] limits: " <<
806 std::setw(12) << maxSize() << " disk bytes, " <<
807 std::setw(7) << map
->entryLimit() << " entries, and " <<
808 std::setw(7) << map
->sliceLimit() << " slots");
814 Rock::SwapDir::closeCompleted()
820 Rock::SwapDir::readCompleted(const char *, int rlen
, int errflag
, RefCount
< ::ReadRequest
> r
)
822 ReadRequest
*request
= dynamic_cast<Rock::ReadRequest
*>(r
.getRaw());
824 IoState::Pointer sio
= request
->sio
;
826 if (errflag
== DISK_OK
&& rlen
> 0)
827 sio
->offset_
+= rlen
;
829 sio
->callReaderBack(r
->buf
, rlen
);
833 Rock::SwapDir::writeCompleted(int errflag
, size_t, RefCount
< ::WriteRequest
> r
)
835 Rock::WriteRequest
*request
= dynamic_cast<Rock::WriteRequest
*>(r
.getRaw());
837 assert(request
->sio
!= NULL
);
838 IoState
&sio
= *request
->sio
;
840 // quit if somebody called IoState::close() while we were waiting
841 if (!sio
.stillWaiting()) {
842 debugs(79, 3, "ignoring closed entry " << sio
.swap_filen
);
843 noteFreeMapSlice(request
->sidNext
);
847 // TODO: Fail if disk dropped one of the previous write requests.
849 if (errflag
== DISK_OK
) {
850 // do not increment sio.offset_ because we do it in sio->write()
852 // finalize the shared slice info after writing slice contents to disk
853 Ipc::StoreMap::Slice
&slice
=
854 map
->writeableSlice(sio
.swap_filen
, request
->sidCurrent
);
855 slice
.size
= request
->len
- sizeof(DbCellHeader
);
856 slice
.next
= request
->sidNext
;
860 assert(sio
.writeableAnchor_
);
861 sio
.e
->swap_file_sz
= sio
.writeableAnchor_
->basics
.swap_file_sz
=
864 // close, the entry gets the read lock
865 map
->closeForWriting(sio
.swap_filen
, true);
866 sio
.writeableAnchor_
= NULL
;
867 sio
.finishedWriting(errflag
);
870 noteFreeMapSlice(request
->sidNext
);
873 sio
.finishedWriting(errflag
);
874 // and hope that Core will call disconnect() to close the map entry
877 CollapsedForwarding::Broadcast(*sio
.e
);
881 Rock::SwapDir::writeError(StoreEntry
&e
)
883 // Do not abortWriting here. The entry should keep the write lock
884 // instead of losing association with the store and confusing core.
885 map
->freeEntry(e
.swap_filen
); // will mark as unusable, just in case
887 Store::Root().transientsAbandon(e
);
889 // All callers must also call IoState callback, to propagate the error.
893 Rock::SwapDir::full() const
895 return freeSlots
!= NULL
&& !freeSlots
->size();
898 // storeSwapOutFileClosed calls this nethod on DISK_NO_SPACE_LEFT,
899 // but it should not happen for us
901 Rock::SwapDir::diskFull()
903 debugs(20, DBG_IMPORTANT
, "BUG: No space left with rock cache_dir: " <<
907 /// purge while full(); it should be sufficient to purge just one
909 Rock::SwapDir::maintain()
911 // The Store calls this to free some db space, but there is nothing wrong
912 // with a full() db, except when db has to shrink after reconfigure, and
913 // we do not support shrinking yet (it would have to purge specific slots).
914 // TODO: Disable maintain() requests when they are pointless.
918 Rock::SwapDir::reference(StoreEntry
&e
)
920 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
921 if (repl
&& repl
->Referenced
)
922 repl
->Referenced(repl
, &e
, &e
.repl
);
926 Rock::SwapDir::dereference(StoreEntry
&e
, bool)
928 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
929 if (repl
&& repl
->Dereferenced
)
930 repl
->Dereferenced(repl
, &e
, &e
.repl
);
932 // no need to keep e in the global store_table for us; we have our own map
937 Rock::SwapDir::unlinkdUseful() const
939 // no entry-specific files to unlink
944 Rock::SwapDir::unlink(StoreEntry
&e
)
946 debugs(47, 5, HERE
<< e
);
948 map
->freeEntry(e
.swap_filen
);
953 Rock::SwapDir::markForUnlink(StoreEntry
&e
)
956 map
->freeEntry(e
.swap_filen
);
960 Rock::SwapDir::trackReferences(StoreEntry
&e
)
962 debugs(47, 5, HERE
<< e
);
964 repl
->Add(repl
, &e
, &e
.repl
);
968 Rock::SwapDir::ignoreReferences(StoreEntry
&e
)
970 debugs(47, 5, HERE
<< e
);
972 repl
->Remove(repl
, &e
, &e
.repl
);
976 Rock::SwapDir::statfs(StoreEntry
&e
) const
978 storeAppendPrintf(&e
, "\n");
979 storeAppendPrintf(&e
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
980 storeAppendPrintf(&e
, "Current Size: %.2f KB %.2f%%\n",
981 currentSize() / 1024.0,
982 Math::doublePercent(currentSize(), maxSize()));
984 const int entryLimit
= entryLimitActual();
985 const int slotLimit
= slotLimitActual();
986 storeAppendPrintf(&e
, "Maximum entries: %9d\n", entryLimit
);
987 if (map
&& entryLimit
> 0) {
988 const int entryCount
= map
->entryCount();
989 storeAppendPrintf(&e
, "Current entries: %9d %.2f%%\n",
990 entryCount
, (100.0 * entryCount
/ entryLimit
));
993 storeAppendPrintf(&e
, "Maximum slots: %9d\n", slotLimit
);
994 if (map
&& slotLimit
> 0) {
995 const unsigned int slotsFree
= !freeSlots
? 0 : freeSlots
->size();
996 if (slotsFree
<= static_cast<const unsigned int>(slotLimit
)) {
997 const int usedSlots
= slotLimit
- static_cast<const int>(slotsFree
);
998 storeAppendPrintf(&e
, "Used slots: %9d %.2f%%\n",
999 usedSlots
, (100.0 * usedSlots
/ slotLimit
));
1001 if (slotLimit
< 100) { // XXX: otherwise too expensive to count
1002 Ipc::ReadWriteLockStats stats
;
1003 map
->updateStats(stats
);
1008 storeAppendPrintf(&e
, "Pending operations: %d out of %d\n",
1009 store_open_disk_fd
, Config
.max_open_disk_fds
);
1011 storeAppendPrintf(&e
, "Flags:");
1014 storeAppendPrintf(&e
, " SELECTED");
1016 if (flags
.read_only
)
1017 storeAppendPrintf(&e
, " READ-ONLY");
1019 storeAppendPrintf(&e
, "\n");
1024 Rock::SwapDir::inodeMapPath() const
1026 return Ipc::Mem::Segment::Name(SBuf(path
), "map");
1030 Rock::SwapDir::freeSlotsPath() const
1032 static String spacesPath
;
1034 spacesPath
.append("_spaces");
1035 return spacesPath
.termedBuf();
1040 RunnerRegistrationEntry(SwapDirRr
);
1043 void Rock::SwapDirRr::create()
1045 Must(mapOwners
.empty() && freeSlotsOwners
.empty());
1046 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1047 if (const Rock::SwapDir
*const sd
= dynamic_cast<Rock::SwapDir
*>(INDEXSD(i
))) {
1048 const int64_t capacity
= sd
->slotLimitActual();
1050 SwapDir::DirMap::Owner
*const mapOwner
=
1051 SwapDir::DirMap::Init(sd
->inodeMapPath(), capacity
);
1052 mapOwners
.push_back(mapOwner
);
1054 // TODO: somehow remove pool id and counters from PageStack?
1055 Ipc::Mem::Owner
<Ipc::Mem::PageStack
> *const freeSlotsOwner
=
1056 shm_new(Ipc::Mem::PageStack
)(sd
->freeSlotsPath(),
1058 freeSlotsOwners
.push_back(freeSlotsOwner
);
1060 // TODO: add method to initialize PageStack with no free pages
1062 Ipc::Mem::PageId pageId
;
1063 if (!freeSlotsOwner
->object()->pop(pageId
))
1070 Rock::SwapDirRr::~SwapDirRr()
1072 for (size_t i
= 0; i
< mapOwners
.size(); ++i
) {
1073 delete mapOwners
[i
];
1074 delete freeSlotsOwners
[i
];