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()
54 // called when Squid core needs a StoreEntry with a given key
56 Rock::SwapDir::get(const cache_key
*key
)
58 if (!map
|| !theFile
|| !theFile
->canRead())
62 const Ipc::StoreMapAnchor
*const slot
= map
->openForReading(key
, filen
);
66 // create a brand new store entry and initialize it with stored basics
67 StoreEntry
*e
= new StoreEntry();
68 anchorEntry(*e
, filen
, *slot
);
74 // the disk entry remains open for reading, protected from modifications
78 Rock::SwapDir::anchorCollapsed(StoreEntry
&collapsed
, bool &inSync
)
80 if (!map
|| !theFile
|| !theFile
->canRead())
84 const Ipc::StoreMapAnchor
*const slot
= map
->openForReading(
85 reinterpret_cast<cache_key
*>(collapsed
.key
), filen
);
89 anchorEntry(collapsed
, filen
, *slot
);
90 inSync
= updateCollapsedWith(collapsed
, *slot
);
91 return true; // even if inSync is false
95 Rock::SwapDir::updateCollapsed(StoreEntry
&collapsed
)
97 if (!map
|| !theFile
|| !theFile
->canRead())
100 if (collapsed
.swap_filen
< 0) // no longer using a disk cache
102 assert(collapsed
.swap_dirn
== index
);
104 const Ipc::StoreMapAnchor
&s
= map
->readableEntry(collapsed
.swap_filen
);
105 return updateCollapsedWith(collapsed
, s
);
109 Rock::SwapDir::updateCollapsedWith(StoreEntry
&collapsed
, const Ipc::StoreMapAnchor
&anchor
)
111 collapsed
.swap_file_sz
= anchor
.basics
.swap_file_sz
;
116 Rock::SwapDir::anchorEntry(StoreEntry
&e
, const sfileno filen
, const Ipc::StoreMapAnchor
&anchor
)
118 const Ipc::StoreMapAnchor::Basics
&basics
= anchor
.basics
;
120 e
.swap_file_sz
= basics
.swap_file_sz
;
121 e
.lastref
= basics
.lastref
;
122 e
.timestamp
= basics
.timestamp
;
123 e
.expires
= basics
.expires
;
124 e
.lastmod
= basics
.lastmod
;
125 e
.refcount
= basics
.refcount
;
126 e
.flags
= basics
.flags
;
128 if (anchor
.complete()) {
129 e
.store_status
= STORE_OK
;
130 e
.swap_status
= SWAPOUT_DONE
;
132 e
.store_status
= STORE_PENDING
;
133 e
.swap_status
= SWAPOUT_WRITING
; // even though another worker writes?
136 e
.ping_status
= PING_NONE
;
138 EBIT_CLR(e
.flags
, RELEASE_REQUEST
);
139 EBIT_CLR(e
.flags
, KEY_PRIVATE
);
140 EBIT_SET(e
.flags
, ENTRY_VALIDATED
);
143 e
.swap_filen
= filen
;
146 void Rock::SwapDir::disconnect(StoreEntry
&e
)
148 assert(e
.swap_dirn
== index
);
149 assert(e
.swap_filen
>= 0);
150 // cannot have SWAPOUT_NONE entry with swap_filen >= 0
151 assert(e
.swap_status
!= SWAPOUT_NONE
);
153 // do not rely on e.swap_status here because there is an async delay
154 // before it switches from SWAPOUT_WRITING to SWAPOUT_DONE.
156 // since e has swap_filen, its slot is locked for reading and/or writing
157 // but it is difficult to know whether THIS worker is reading or writing e,
158 // especially since we may switch from writing to reading. This code relies
159 // on Rock::IoState::writeableAnchor_ being set when we locked for writing.
160 if (e
.mem_obj
&& e
.mem_obj
->swapout
.sio
!= NULL
&&
161 dynamic_cast<IoState
&>(*e
.mem_obj
->swapout
.sio
).writeableAnchor_
) {
162 map
->abortWriting(e
.swap_filen
);
165 e
.swap_status
= SWAPOUT_NONE
;
166 dynamic_cast<IoState
&>(*e
.mem_obj
->swapout
.sio
).writeableAnchor_
= NULL
;
167 Store::Root().transientsAbandon(e
); // broadcasts after the change
169 map
->closeForReading(e
.swap_filen
);
172 e
.swap_status
= SWAPOUT_NONE
;
177 Rock::SwapDir::currentSize() const
179 const uint64_t spaceSize
= !freeSlots
?
180 maxSize() : (slotSize
* freeSlots
->size());
181 // everything that is not free is in use
182 return maxSize() - spaceSize
;
186 Rock::SwapDir::currentCount() const
188 return map
? map
->entryCount() : 0;
191 /// In SMP mode only the disker process reports stats to avoid
192 /// counting the same stats by multiple processes.
194 Rock::SwapDir::doReportStat() const
196 return ::SwapDir::doReportStat() && (!UsingSmp() || IamDiskProcess());
200 Rock::SwapDir::swappedOut(const StoreEntry
&)
202 // stats are not stored but computed when needed
206 Rock::SwapDir::slotLimitAbsolute() const
208 // the max value is an invalid one; all values must be below the limit
209 assert(std::numeric_limits
<Ipc::StoreMapSliceId
>::max() ==
210 std::numeric_limits
<SlotId
>::max());
211 return std::numeric_limits
<SlotId
>::max();
215 Rock::SwapDir::slotLimitActual() const
217 const int64_t sWanted
= (maxSize() - HeaderSize
)/slotSize
;
218 const int64_t sLimitLo
= map
? map
->sliceLimit() : 0; // dynamic shrinking unsupported
219 const int64_t sLimitHi
= slotLimitAbsolute();
220 return min(max(sLimitLo
, sWanted
), sLimitHi
);
224 Rock::SwapDir::entryLimitActual() const
226 return min(slotLimitActual(), entryLimitAbsolute());
229 // TODO: encapsulate as a tool
231 Rock::SwapDir::create()
236 if (UsingSmp() && !IamDiskProcess()) {
237 debugs (47,3, HERE
<< "disker will create in " << path
);
241 debugs (47,3, HERE
<< "creating in " << path
);
244 if (::stat(path
, &dir_sb
) == 0) {
246 if (::stat(filePath
, &file_sb
) == 0) {
247 debugs (47, DBG_IMPORTANT
, "Skipping existing Rock db: " << filePath
);
250 // else the db file is not there or is not accessible, and we will try
251 // to create it later below, generating a detailed error on failures.
252 } else { // path does not exist or is inaccessible
253 // If path exists but is not accessible, mkdir() below will fail, and
254 // the admin should see the error and act accordingly, so there is
255 // no need to distinguish ENOENT from other possible stat() errors.
256 debugs (47, DBG_IMPORTANT
, "Creating Rock db directory: " << path
);
257 const int res
= mkdir(path
, 0700);
259 createError("mkdir");
262 debugs (47, DBG_IMPORTANT
, "Creating Rock db: " << filePath
);
263 const int swap
= open(filePath
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_BINARY
, 0600);
265 createError("create");
267 #if SLOWLY_FILL_WITH_ZEROS
269 Must(maxSize() % sizeof(block
) == 0);
270 memset(block
, '\0', sizeof(block
));
272 for (off_t offset
= 0; offset
< maxSize(); offset
+= sizeof(block
)) {
273 if (write(swap
, block
, sizeof(block
)) != sizeof(block
))
274 createError("write");
277 if (ftruncate(swap
, maxSize()) != 0)
278 createError("truncate");
280 char header
[HeaderSize
];
281 memset(header
, '\0', sizeof(header
));
282 if (write(swap
, header
, sizeof(header
)) != sizeof(header
))
283 createError("write");
289 // report Rock DB creation error and exit
291 Rock::SwapDir::createError(const char *const msg
)
293 debugs(47, DBG_CRITICAL
, "ERROR: Failed to initialize Rock Store db in " <<
294 filePath
<< "; " << msg
<< " error: " << xstrerror());
295 fatal("Rock Store db creation error");
299 Rock::SwapDir::init()
303 // XXX: SwapDirs aren't refcounted. We make IORequestor calls, which
304 // are refcounted. We up our count once to avoid implicit delete's.
307 freeSlots
= shm_old(Ipc::Mem::PageStack
)(freeSlotsPath());
310 map
= new DirMap(inodeMapPath());
313 const char *ioModule
= needsDiskStrand() ? "IpcIo" : "Blocking";
314 if (DiskIOModule
*m
= DiskIOModule::Find(ioModule
)) {
315 debugs(47,2, HERE
<< "Using DiskIO module: " << ioModule
);
316 io
= m
->createStrategy();
319 debugs(47, DBG_CRITICAL
, "FATAL: Rock store is missing DiskIO module: " <<
321 fatal("Rock Store missing a required DiskIO module");
324 theFile
= io
->newFile(filePath
);
325 theFile
->configure(fileConfig
);
326 theFile
->open(O_RDWR
, 0644, this);
328 // Increment early. Otherwise, if one SwapDir finishes rebuild before
329 // others start, storeRebuildComplete() will think the rebuild is over!
330 // TODO: move store_dirs_rebuilding hack to store modules that need it.
331 ++StoreController::store_dirs_rebuilding
;
335 Rock::SwapDir::needsDiskStrand() const
337 const bool wontEvenWorkWithoutDisker
= Config
.workers
> 1;
338 const bool wouldWorkBetterWithDisker
= DiskIOModule::Find("IpcIo");
339 return InDaemonMode() && (wontEvenWorkWithoutDisker
||
340 wouldWorkBetterWithDisker
);
344 Rock::SwapDir::parse(int anIndex
, char *aPath
)
348 path
= xstrdup(aPath
);
350 // cache store is located at path/db
352 fname
.append("/rock");
353 filePath
= xstrdup(fname
.termedBuf());
358 // Current openForWriting() code overwrites the old slot if needed
359 // and possible, so proactively removing old slots is probably useless.
360 assert(!repl
); // repl = createRemovalPolicy(Config.replPolicy);
366 Rock::SwapDir::reconfigure()
370 // TODO: can we reconfigure the replacement policy (repl)?
374 /// parse maximum db disk size
376 Rock::SwapDir::parseSize(const bool reconfig
)
378 const int i
= GetInteger();
380 fatal("negative Rock cache_dir size value");
381 const uint64_t new_max_size
=
382 static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
384 max_size
= new_max_size
;
385 else if (new_max_size
!= max_size
) {
386 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir '" << path
<< "' size "
387 "cannot be changed dynamically, value left unchanged (" <<
388 (max_size
>> 20) << " MB)");
393 Rock::SwapDir::getOptionTree() const
395 ConfigOption
*copt
= ::SwapDir::getOptionTree();
396 ConfigOptionVector
*vector
= dynamic_cast<ConfigOptionVector
*>(copt
);
398 // if copt is actually a ConfigOptionVector
399 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseSizeOption
, &SwapDir::dumpSizeOption
));
400 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseTimeOption
, &SwapDir::dumpTimeOption
));
401 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseRateOption
, &SwapDir::dumpRateOption
));
403 // we don't know how to handle copt, as it's not a ConfigOptionVector.
404 // free it (and return nullptr)
412 Rock::SwapDir::allowOptionReconfigure(const char *const option
) const
414 return strcmp(option
, "slot-size") != 0 &&
415 ::SwapDir::allowOptionReconfigure(option
);
418 /// parses time-specific options; mimics ::SwapDir::optionObjectSizeParse()
420 Rock::SwapDir::parseTimeOption(char const *option
, const char *value
, int reconfig
)
422 // TODO: ::SwapDir or, better, Config should provide time-parsing routines,
423 // including time unit handling. Same for size and rate.
425 time_msec_t
*storedTime
;
426 if (strcmp(option
, "swap-timeout") == 0)
427 storedTime
= &fileConfig
.ioTimeout
;
434 // TODO: handle time units and detect parsing errors better
435 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
436 if (parsedValue
< 0) {
437 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
441 const time_msec_t newTime
= static_cast<time_msec_t
>(parsedValue
);
444 *storedTime
= newTime
;
445 else if (*storedTime
!= newTime
) {
446 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
447 << " cannot be changed dynamically, value left unchanged: " <<
454 /// reports time-specific options; mimics ::SwapDir::optionObjectSizeDump()
456 Rock::SwapDir::dumpTimeOption(StoreEntry
* e
) const
458 if (fileConfig
.ioTimeout
)
459 storeAppendPrintf(e
, " swap-timeout=%" PRId64
,
460 static_cast<int64_t>(fileConfig
.ioTimeout
));
463 /// parses rate-specific options; mimics ::SwapDir::optionObjectSizeParse()
465 Rock::SwapDir::parseRateOption(char const *option
, const char *value
, int isaReconfig
)
468 if (strcmp(option
, "max-swap-rate") == 0)
469 storedRate
= &fileConfig
.ioRate
;
476 // TODO: handle time units and detect parsing errors better
477 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
478 if (parsedValue
< 0) {
479 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
483 const int newRate
= static_cast<int>(parsedValue
);
486 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << newRate
);
491 *storedRate
= newRate
;
492 else if (*storedRate
!= newRate
) {
493 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
494 << " cannot be changed dynamically, value left unchanged: " <<
501 /// reports rate-specific options; mimics ::SwapDir::optionObjectSizeDump()
503 Rock::SwapDir::dumpRateOption(StoreEntry
* e
) const
505 if (fileConfig
.ioRate
>= 0)
506 storeAppendPrintf(e
, " max-swap-rate=%d", fileConfig
.ioRate
);
509 /// parses size-specific options; mimics ::SwapDir::optionObjectSizeParse()
511 Rock::SwapDir::parseSizeOption(char const *option
, const char *value
, int reconfig
)
513 uint64_t *storedSize
;
514 if (strcmp(option
, "slot-size") == 0)
515 storedSize
= &slotSize
;
522 // TODO: handle size units and detect parsing errors better
523 const uint64_t newSize
= strtoll(value
, NULL
, 10);
525 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must be positive; got: " << newSize
);
529 if (newSize
<= sizeof(DbCellHeader
)) {
530 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must exceed " << sizeof(DbCellHeader
) << "; got: " << newSize
);
535 *storedSize
= newSize
;
536 else if (*storedSize
!= newSize
) {
537 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
538 << " cannot be changed dynamically, value left unchanged: " <<
545 /// reports size-specific options; mimics ::SwapDir::optionObjectSizeDump()
547 Rock::SwapDir::dumpSizeOption(StoreEntry
* e
) const
549 storeAppendPrintf(e
, " slot-size=%" PRId64
, slotSize
);
552 /// check the results of the configuration; only level-0 debugging works here
554 Rock::SwapDir::validateOptions()
557 fatal("Rock store requires a positive slot-size");
559 const int64_t maxSizeRoundingWaste
= 1024 * 1024; // size is configured in MB
560 const int64_t slotSizeRoundingWaste
= slotSize
;
561 const int64_t maxRoundingWaste
=
562 max(maxSizeRoundingWaste
, slotSizeRoundingWaste
);
564 // an entry consumes at least one slot; round up to reduce false warnings
565 const int64_t blockSize
= static_cast<int64_t>(slotSize
);
566 const int64_t maxObjSize
= max(blockSize
,
567 ((maxObjectSize()+blockSize
-1)/blockSize
)*blockSize
);
569 // Does the "sfileno*max-size" limit match configured db capacity?
570 const double entriesMayOccupy
= entryLimitAbsolute()*static_cast<double>(maxObjSize
);
571 if (entriesMayOccupy
+ maxRoundingWaste
< maxSize()) {
572 const int64_t diskWasteSize
= maxSize() - static_cast<int64_t>(entriesMayOccupy
);
573 debugs(47, DBG_CRITICAL
, "WARNING: Rock cache_dir " << path
<< " wastes disk space due to entry limits:" <<
574 "\n\tconfigured db capacity: " << maxSize() << " bytes" <<
575 "\n\tconfigured db slot size: " << slotSize
<< " bytes" <<
576 "\n\tconfigured maximum entry size: " << maxObjectSize() << " bytes" <<
577 "\n\tmaximum number of cache_dir entries supported by Squid: " << entryLimitAbsolute() <<
578 "\n\tdisk space all entries may use: " << entriesMayOccupy
<< " bytes" <<
579 "\n\tdisk space wasted: " << diskWasteSize
<< " bytes");
582 // Does the "absolute slot count" limit match configured db capacity?
583 const double slotsMayOccupy
= slotLimitAbsolute()*static_cast<double>(slotSize
);
584 if (slotsMayOccupy
+ maxRoundingWaste
< maxSize()) {
585 const int64_t diskWasteSize
= maxSize() - static_cast<int64_t>(entriesMayOccupy
);
586 debugs(47, DBG_CRITICAL
, "WARNING: Rock cache_dir " << path
<< " wastes disk space due to slot limits:" <<
587 "\n\tconfigured db capacity: " << maxSize() << " bytes" <<
588 "\n\tconfigured db slot size: " << slotSize
<< " bytes" <<
589 "\n\tmaximum number of rock cache_dir slots supported by Squid: " << slotLimitAbsolute() <<
590 "\n\tdisk space all slots may use: " << slotsMayOccupy
<< " bytes" <<
591 "\n\tdisk space wasted: " << diskWasteSize
<< " bytes");
596 Rock::SwapDir::rebuild()
598 //++StoreController::store_dirs_rebuilding; // see Rock::SwapDir::init()
599 AsyncJob::Start(new Rebuild(this));
603 Rock::SwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
605 if (!::SwapDir::canStore(e
, sizeof(DbCellHeader
)+diskSpaceNeeded
, load
))
608 if (!theFile
|| !theFile
->canWrite())
614 // Do not start I/O transaction if there are less than 10% free pages left.
615 // TODO: reserve page instead
616 if (needsDiskStrand() &&
617 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
618 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
629 StoreIOState::Pointer
630 Rock::SwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
632 if (!theFile
|| theFile
->error()) {
633 debugs(47,4, HERE
<< theFile
);
638 Ipc::StoreMapAnchor
*const slot
=
639 map
->openForWriting(reinterpret_cast<const cache_key
*>(e
.key
), filen
);
641 debugs(47, 5, HERE
<< "map->add failed");
648 // XXX: We rely on our caller, storeSwapOutStart(), to set e.fileno.
649 // If that does not happen, the entry will not decrement the read level!
651 Rock::SwapDir::Pointer
self(this);
652 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
654 sio
->swap_dirn
= index
;
655 sio
->swap_filen
= filen
;
656 sio
->writeableAnchor_
= slot
;
658 debugs(47,5, HERE
<< "dir " << index
<< " created new filen " <<
659 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
660 sio
->swap_filen
<< std::dec
<< " starting at " <<
661 diskOffset(sio
->swap_filen
));
670 Rock::SwapDir::diskOffset(const SlotId sid
) const
673 return HeaderSize
+ slotSize
*sid
;
677 Rock::SwapDir::diskOffset(Ipc::Mem::PageId
&pageId
) const
680 return diskOffset(pageId
.number
- 1);
684 Rock::SwapDir::diskOffsetLimit() const
687 return diskOffset(map
->sliceLimit());
691 Rock::SwapDir::useFreeSlot(Ipc::Mem::PageId
&pageId
)
693 if (freeSlots
->pop(pageId
)) {
694 debugs(47, 5, "got a previously free slot: " << pageId
);
698 // catch free slots delivered to noteFreeMapSlice()
699 assert(!waitingForPage
);
700 waitingForPage
= &pageId
;
701 if (map
->purgeOne()) {
702 assert(!waitingForPage
); // noteFreeMapSlice() should have cleared it
703 assert(pageId
.set());
704 debugs(47, 5, "got a previously busy slot: " << pageId
);
707 assert(waitingForPage
== &pageId
);
708 waitingForPage
= NULL
;
710 debugs(47, 3, "cannot get a slot; entries: " << map
->entryCount());
715 Rock::SwapDir::validSlotId(const SlotId slotId
) const
717 return 0 <= slotId
&& slotId
< slotLimitActual();
721 Rock::SwapDir::noteFreeMapSlice(const Ipc::StoreMapSliceId sliceId
)
723 Ipc::Mem::PageId pageId
;
724 pageId
.pool
= index
+1;
725 pageId
.number
= sliceId
+1;
726 if (waitingForPage
) {
727 *waitingForPage
= pageId
;
728 waitingForPage
= NULL
;
730 freeSlots
->push(pageId
);
734 // tries to open an old entry with swap_filen for reading
735 StoreIOState::Pointer
736 Rock::SwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
738 if (!theFile
|| theFile
->error()) {
739 debugs(47,4, HERE
<< theFile
);
743 if (e
.swap_filen
< 0) {
744 debugs(47,4, HERE
<< e
);
748 // Do not start I/O transaction if there are less than 10% free pages left.
749 // TODO: reserve page instead
750 if (needsDiskStrand() &&
751 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
752 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
756 // The are two ways an entry can get swap_filen: our get() locked it for
757 // reading or our storeSwapOutStart() locked it for writing. Peeking at our
758 // locked entry is safe, but no support for reading the entry we swap out.
759 const Ipc::StoreMapAnchor
*slot
= map
->peekAtReader(e
.swap_filen
);
761 return NULL
; // we were writing afterall
763 Rock::SwapDir::Pointer
self(this);
764 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
766 sio
->swap_dirn
= index
;
767 sio
->swap_filen
= e
.swap_filen
;
768 sio
->readableAnchor_
= slot
;
771 debugs(47,5, HERE
<< "dir " << index
<< " has old filen: " <<
772 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
775 assert(slot
->sameKey(static_cast<const cache_key
*>(e
.key
)));
776 // For collapsed disk hits: e.swap_file_sz and slot->basics.swap_file_sz
777 // may still be zero and basics.swap_file_sz may grow.
778 assert(slot
->basics
.swap_file_sz
>= e
.swap_file_sz
);
784 Rock::SwapDir::ioCompletedNotification()
787 fatalf("Rock cache_dir failed to initialize db file: %s", filePath
);
789 if (theFile
->error())
790 fatalf("Rock cache_dir at %s failed to open db file: %s", filePath
,
793 debugs(47, 2, "Rock cache_dir[" << index
<< "] limits: " <<
794 std::setw(12) << maxSize() << " disk bytes, " <<
795 std::setw(7) << map
->entryLimit() << " entries, and " <<
796 std::setw(7) << map
->sliceLimit() << " slots");
802 Rock::SwapDir::closeCompleted()
808 Rock::SwapDir::readCompleted(const char *, int rlen
, int errflag
, RefCount
< ::ReadRequest
> r
)
810 ReadRequest
*request
= dynamic_cast<Rock::ReadRequest
*>(r
.getRaw());
812 IoState::Pointer sio
= request
->sio
;
814 if (errflag
== DISK_OK
&& rlen
> 0)
815 sio
->offset_
+= rlen
;
817 sio
->callReaderBack(r
->buf
, rlen
);
821 Rock::SwapDir::writeCompleted(int errflag
, size_t, RefCount
< ::WriteRequest
> r
)
823 Rock::WriteRequest
*request
= dynamic_cast<Rock::WriteRequest
*>(r
.getRaw());
825 assert(request
->sio
!= NULL
);
826 IoState
&sio
= *request
->sio
;
828 // quit if somebody called IoState::close() while we were waiting
829 if (!sio
.stillWaiting()) {
830 debugs(79, 3, "ignoring closed entry " << sio
.swap_filen
);
831 noteFreeMapSlice(request
->sidNext
);
835 // TODO: Fail if disk dropped one of the previous write requests.
837 if (errflag
== DISK_OK
) {
838 // do not increment sio.offset_ because we do it in sio->write()
840 // finalize the shared slice info after writing slice contents to disk
841 Ipc::StoreMap::Slice
&slice
=
842 map
->writeableSlice(sio
.swap_filen
, request
->sidCurrent
);
843 slice
.size
= request
->len
- sizeof(DbCellHeader
);
844 slice
.next
= request
->sidNext
;
848 assert(sio
.writeableAnchor_
);
849 sio
.e
->swap_file_sz
= sio
.writeableAnchor_
->basics
.swap_file_sz
=
852 // close, the entry gets the read lock
853 map
->closeForWriting(sio
.swap_filen
, true);
854 sio
.writeableAnchor_
= NULL
;
855 sio
.finishedWriting(errflag
);
858 noteFreeMapSlice(request
->sidNext
);
861 sio
.finishedWriting(errflag
);
862 // and hope that Core will call disconnect() to close the map entry
865 CollapsedForwarding::Broadcast(*sio
.e
);
869 Rock::SwapDir::writeError(StoreEntry
&e
)
871 // Do not abortWriting here. The entry should keep the write lock
872 // instead of losing association with the store and confusing core.
873 map
->freeEntry(e
.swap_filen
); // will mark as unusable, just in case
875 Store::Root().transientsAbandon(e
);
877 // All callers must also call IoState callback, to propagate the error.
881 Rock::SwapDir::full() const
883 return freeSlots
!= NULL
&& !freeSlots
->size();
886 // storeSwapOutFileClosed calls this nethod on DISK_NO_SPACE_LEFT,
887 // but it should not happen for us
889 Rock::SwapDir::diskFull()
891 debugs(20, DBG_IMPORTANT
, "BUG: No space left with rock cache_dir: " <<
895 /// purge while full(); it should be sufficient to purge just one
897 Rock::SwapDir::maintain()
899 // The Store calls this to free some db space, but there is nothing wrong
900 // with a full() db, except when db has to shrink after reconfigure, and
901 // we do not support shrinking yet (it would have to purge specific slots).
902 // TODO: Disable maintain() requests when they are pointless.
906 Rock::SwapDir::reference(StoreEntry
&e
)
908 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
909 if (repl
&& repl
->Referenced
)
910 repl
->Referenced(repl
, &e
, &e
.repl
);
914 Rock::SwapDir::dereference(StoreEntry
&e
)
916 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
917 if (repl
&& repl
->Dereferenced
)
918 repl
->Dereferenced(repl
, &e
, &e
.repl
);
920 // no need to keep e in the global store_table for us; we have our own map
925 Rock::SwapDir::unlinkdUseful() const
927 // no entry-specific files to unlink
932 Rock::SwapDir::unlink(StoreEntry
&e
)
934 debugs(47, 5, HERE
<< e
);
936 map
->freeEntry(e
.swap_filen
);
941 Rock::SwapDir::markForUnlink(StoreEntry
&e
)
944 map
->freeEntry(e
.swap_filen
);
948 Rock::SwapDir::trackReferences(StoreEntry
&e
)
950 debugs(47, 5, HERE
<< e
);
952 repl
->Add(repl
, &e
, &e
.repl
);
956 Rock::SwapDir::ignoreReferences(StoreEntry
&e
)
958 debugs(47, 5, HERE
<< e
);
960 repl
->Remove(repl
, &e
, &e
.repl
);
964 Rock::SwapDir::statfs(StoreEntry
&e
) const
966 storeAppendPrintf(&e
, "\n");
967 storeAppendPrintf(&e
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
968 storeAppendPrintf(&e
, "Current Size: %.2f KB %.2f%%\n",
969 currentSize() / 1024.0,
970 Math::doublePercent(currentSize(), maxSize()));
972 const int entryLimit
= entryLimitActual();
973 const int slotLimit
= slotLimitActual();
974 storeAppendPrintf(&e
, "Maximum entries: %9d\n", entryLimit
);
975 if (map
&& entryLimit
> 0) {
976 const int entryCount
= map
->entryCount();
977 storeAppendPrintf(&e
, "Current entries: %9d %.2f%%\n",
978 entryCount
, (100.0 * entryCount
/ entryLimit
));
981 storeAppendPrintf(&e
, "Maximum slots: %9d\n", slotLimit
);
982 if (map
&& slotLimit
> 0) {
983 const unsigned int slotsFree
= !freeSlots
? 0 : freeSlots
->size();
984 if (slotsFree
<= static_cast<const unsigned int>(slotLimit
)) {
985 const int usedSlots
= slotLimit
- static_cast<const int>(slotsFree
);
986 storeAppendPrintf(&e
, "Used slots: %9d %.2f%%\n",
987 usedSlots
, (100.0 * usedSlots
/ slotLimit
));
989 if (slotLimit
< 100) { // XXX: otherwise too expensive to count
990 Ipc::ReadWriteLockStats stats
;
991 map
->updateStats(stats
);
996 storeAppendPrintf(&e
, "Pending operations: %d out of %d\n",
997 store_open_disk_fd
, Config
.max_open_disk_fds
);
999 storeAppendPrintf(&e
, "Flags:");
1002 storeAppendPrintf(&e
, " SELECTED");
1004 if (flags
.read_only
)
1005 storeAppendPrintf(&e
, " READ-ONLY");
1007 storeAppendPrintf(&e
, "\n");
1012 Rock::SwapDir::inodeMapPath() const
1014 return Ipc::Mem::Segment::Name(SBuf(path
), "map");
1018 Rock::SwapDir::freeSlotsPath() const
1020 static String spacesPath
;
1022 spacesPath
.append("_spaces");
1023 return spacesPath
.termedBuf();
1028 RunnerRegistrationEntry(SwapDirRr
);
1031 void Rock::SwapDirRr::create()
1033 Must(mapOwners
.empty() && freeSlotsOwners
.empty());
1034 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1035 if (const Rock::SwapDir
*const sd
= dynamic_cast<Rock::SwapDir
*>(INDEXSD(i
))) {
1036 const int64_t capacity
= sd
->slotLimitActual();
1038 SwapDir::DirMap::Owner
*const mapOwner
=
1039 SwapDir::DirMap::Init(sd
->inodeMapPath(), capacity
);
1040 mapOwners
.push_back(mapOwner
);
1042 // TODO: somehow remove pool id and counters from PageStack?
1043 Ipc::Mem::Owner
<Ipc::Mem::PageStack
> *const freeSlotsOwner
=
1044 shm_new(Ipc::Mem::PageStack
)(sd
->freeSlotsPath(),
1046 freeSlotsOwners
.push_back(freeSlotsOwner
);
1048 // TODO: add method to initialize PageStack with no free pages
1050 Ipc::Mem::PageId pageId
;
1051 if (!freeSlotsOwner
->object()->pop(pageId
))
1058 Rock::SwapDirRr::~SwapDirRr()
1060 for (size_t i
= 0; i
< mapOwners
.size(); ++i
) {
1061 delete mapOwners
[i
];
1062 delete freeSlotsOwners
[i
];