2 * DEBUG: section 47 Store Directory Routines
7 #include "CollapsedForwarding.h"
8 #include "ConfigOption.h"
9 #include "DiskIO/DiskIOModule.h"
10 #include "DiskIO/DiskIOStrategy.h"
11 #include "DiskIO/ReadRequest.h"
12 #include "DiskIO/WriteRequest.h"
13 #include "fs/rock/RockIoRequests.h"
14 #include "fs/rock/RockIoState.h"
15 #include "fs/rock/RockRebuild.h"
16 #include "fs/rock/RockSwapDir.h"
18 #include "ipc/mem/Pages.h"
19 #include "MemObject.h"
21 #include "SquidConfig.h"
22 #include "SquidMath.h"
32 const int64_t Rock::SwapDir::HeaderSize
= 16*1024;
34 Rock::SwapDir::SwapDir(): ::SwapDir("rock"),
35 slotSize(HeaderSize
), filePath(NULL
), map(NULL
), io(NULL
),
40 Rock::SwapDir::~SwapDir()
48 Rock::SwapDir::search(String
const url
, HttpRequest
*)
51 return NULL
; // XXX: implement
55 Rock::SwapDir::get(String
const key
, STOREGETCLIENT cb
, void *data
)
57 ::SwapDir::get(key
, cb
, data
);
60 // called when Squid core needs a StoreEntry with a given key
62 Rock::SwapDir::get(const cache_key
*key
)
64 if (!map
|| !theFile
|| !theFile
->canRead())
68 const Ipc::StoreMapAnchor
*const slot
= map
->openForReading(key
, filen
);
72 // create a brand new store entry and initialize it with stored basics
73 StoreEntry
*e
= new StoreEntry();
74 anchorEntry(*e
, filen
, *slot
);
80 // the disk entry remains open for reading, protected from modifications
84 Rock::SwapDir::anchorCollapsed(StoreEntry
&collapsed
, bool &inSync
)
86 if (!map
|| !theFile
|| !theFile
->canRead())
90 const Ipc::StoreMapAnchor
*const slot
= map
->openForReading(
91 reinterpret_cast<cache_key
*>(collapsed
.key
), filen
);
95 anchorEntry(collapsed
, filen
, *slot
);
96 inSync
= updateCollapsedWith(collapsed
, *slot
);
97 return true; // even if inSync is false
101 Rock::SwapDir::updateCollapsed(StoreEntry
&collapsed
)
103 if (!map
|| !theFile
|| !theFile
->canRead())
106 if (collapsed
.swap_filen
< 0) // no longer using a disk cache
108 assert(collapsed
.swap_dirn
== index
);
110 const Ipc::StoreMapAnchor
&s
= map
->readableEntry(collapsed
.swap_filen
);
111 return updateCollapsedWith(collapsed
, s
);
115 Rock::SwapDir::updateCollapsedWith(StoreEntry
&collapsed
, const Ipc::StoreMapAnchor
&anchor
)
117 collapsed
.swap_file_sz
= anchor
.basics
.swap_file_sz
;
122 Rock::SwapDir::anchorEntry(StoreEntry
&e
, const sfileno filen
, const Ipc::StoreMapAnchor
&anchor
)
124 const Ipc::StoreMapAnchor::Basics
&basics
= anchor
.basics
;
126 e
.swap_file_sz
= basics
.swap_file_sz
;
127 e
.lastref
= basics
.lastref
;
128 e
.timestamp
= basics
.timestamp
;
129 e
.expires
= basics
.expires
;
130 e
.lastmod
= basics
.lastmod
;
131 e
.refcount
= basics
.refcount
;
132 e
.flags
= basics
.flags
;
134 if (anchor
.complete()) {
135 e
.store_status
= STORE_OK
;
136 e
.swap_status
= SWAPOUT_DONE
;
138 e
.store_status
= STORE_PENDING
;
139 e
.swap_status
= SWAPOUT_WRITING
; // even though another worker writes?
142 e
.ping_status
= PING_NONE
;
144 EBIT_CLR(e
.flags
, RELEASE_REQUEST
);
145 EBIT_CLR(e
.flags
, KEY_PRIVATE
);
146 EBIT_SET(e
.flags
, ENTRY_VALIDATED
);
149 e
.swap_filen
= filen
;
152 void Rock::SwapDir::disconnect(StoreEntry
&e
)
154 assert(e
.swap_dirn
== index
);
155 assert(e
.swap_filen
>= 0);
156 // cannot have SWAPOUT_NONE entry with swap_filen >= 0
157 assert(e
.swap_status
!= SWAPOUT_NONE
);
159 // do not rely on e.swap_status here because there is an async delay
160 // before it switches from SWAPOUT_WRITING to SWAPOUT_DONE.
162 // since e has swap_filen, its slot is locked for reading and/or writing
163 // but it is difficult to know whether THIS worker is reading or writing e,
164 // especially since we may switch from writing to reading. This code relies
165 // on Rock::IoState::writeableAnchor_ being set when we locked for writing.
166 if (e
.mem_obj
&& e
.mem_obj
->swapout
.sio
!= NULL
&&
167 dynamic_cast<IoState
&>(*e
.mem_obj
->swapout
.sio
).writeableAnchor_
) {
168 map
->abortWriting(e
.swap_filen
);
171 e
.swap_status
= SWAPOUT_NONE
;
172 dynamic_cast<IoState
&>(*e
.mem_obj
->swapout
.sio
).writeableAnchor_
= NULL
;
173 Store::Root().transientsAbandon(e
); // broadcasts after the change
175 map
->closeForReading(e
.swap_filen
);
178 e
.swap_status
= SWAPOUT_NONE
;
183 Rock::SwapDir::currentSize() const
185 const uint64_t spaceSize
= !freeSlots
?
186 maxSize() : (slotSize
* freeSlots
->size());
187 // everything that is not free is in use
188 return maxSize() - spaceSize
;
192 Rock::SwapDir::currentCount() const
194 return map
? map
->entryCount() : 0;
197 /// In SMP mode only the disker process reports stats to avoid
198 /// counting the same stats by multiple processes.
200 Rock::SwapDir::doReportStat() const
202 return ::SwapDir::doReportStat() && (!UsingSmp() || IamDiskProcess());
206 Rock::SwapDir::swappedOut(const StoreEntry
&)
208 // stats are not stored but computed when needed
212 Rock::SwapDir::entryLimitAllowed() const
214 const int64_t eLimitLo
= map
? map
->entryLimit() : 0; // dynamic shrinking unsupported
215 const int64_t eWanted
= (maxSize() - HeaderSize
)/slotSize
;
216 return min(max(eLimitLo
, eWanted
), entryLimitHigh());
219 // TODO: encapsulate as a tool
221 Rock::SwapDir::create()
226 if (UsingSmp() && !IamDiskProcess()) {
227 debugs (47,3, HERE
<< "disker will create in " << path
);
231 debugs (47,3, HERE
<< "creating in " << path
);
234 if (::stat(path
, &dir_sb
) == 0) {
236 if (::stat(filePath
, &file_sb
) == 0) {
237 debugs (47, DBG_IMPORTANT
, "Skipping existing Rock db: " << filePath
);
240 // else the db file is not there or is not accessible, and we will try
241 // to create it later below, generating a detailed error on failures.
242 } else { // path does not exist or is inaccessible
243 // If path exists but is not accessible, mkdir() below will fail, and
244 // the admin should see the error and act accordingly, so there is
245 // no need to distinguish ENOENT from other possible stat() errors.
246 debugs (47, DBG_IMPORTANT
, "Creating Rock db directory: " << path
);
247 const int res
= mkdir(path
, 0700);
249 createError("mkdir");
252 debugs (47, DBG_IMPORTANT
, "Creating Rock db: " << filePath
);
253 const int swap
= open(filePath
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_BINARY
, 0600);
255 createError("create");
257 #if SLOWLY_FILL_WITH_ZEROS
259 Must(maxSize() % sizeof(block
) == 0);
260 memset(block
, '\0', sizeof(block
));
262 for (off_t offset
= 0; offset
< maxSize(); offset
+= sizeof(block
)) {
263 if (write(swap
, block
, sizeof(block
)) != sizeof(block
))
264 createError("write");
267 if (ftruncate(swap
, maxSize()) != 0)
268 createError("truncate");
270 char header
[HeaderSize
];
271 memset(header
, '\0', sizeof(header
));
272 if (write(swap
, header
, sizeof(header
)) != sizeof(header
))
273 createError("write");
279 // report Rock DB creation error and exit
281 Rock::SwapDir::createError(const char *const msg
)
283 debugs(47, DBG_CRITICAL
, "ERROR: Failed to initialize Rock Store db in " <<
284 filePath
<< "; " << msg
<< " error: " << xstrerror());
285 fatal("Rock Store db creation error");
289 Rock::SwapDir::init()
293 // XXX: SwapDirs aren't refcounted. We make IORequestor calls, which
294 // are refcounted. We up our count once to avoid implicit delete's.
297 freeSlots
= shm_old(Ipc::Mem::PageStack
)(freeSlotsPath());
300 map
= new DirMap(inodeMapPath());
303 const char *ioModule
= needsDiskStrand() ? "IpcIo" : "Blocking";
304 if (DiskIOModule
*m
= DiskIOModule::Find(ioModule
)) {
305 debugs(47,2, HERE
<< "Using DiskIO module: " << ioModule
);
306 io
= m
->createStrategy();
309 debugs(47, DBG_CRITICAL
, "FATAL: Rock store is missing DiskIO module: " <<
311 fatal("Rock Store missing a required DiskIO module");
314 theFile
= io
->newFile(filePath
);
315 theFile
->configure(fileConfig
);
316 theFile
->open(O_RDWR
, 0644, this);
318 // Increment early. Otherwise, if one SwapDir finishes rebuild before
319 // others start, storeRebuildComplete() will think the rebuild is over!
320 // TODO: move store_dirs_rebuilding hack to store modules that need it.
321 ++StoreController::store_dirs_rebuilding
;
325 Rock::SwapDir::needsDiskStrand() const
327 const bool wontEvenWorkWithoutDisker
= Config
.workers
> 1;
328 const bool wouldWorkBetterWithDisker
= DiskIOModule::Find("IpcIo");
329 return InDaemonMode() && (wontEvenWorkWithoutDisker
||
330 wouldWorkBetterWithDisker
);
334 Rock::SwapDir::parse(int anIndex
, char *aPath
)
338 path
= xstrdup(aPath
);
340 // cache store is located at path/db
342 fname
.append("/rock");
343 filePath
= xstrdup(fname
.termedBuf());
348 // Current openForWriting() code overwrites the old slot if needed
349 // and possible, so proactively removing old slots is probably useless.
350 assert(!repl
); // repl = createRemovalPolicy(Config.replPolicy);
356 Rock::SwapDir::reconfigure()
360 // TODO: can we reconfigure the replacement policy (repl)?
364 /// parse maximum db disk size
366 Rock::SwapDir::parseSize(const bool reconfig
)
368 const int i
= GetInteger();
370 fatal("negative Rock cache_dir size value");
371 const uint64_t new_max_size
=
372 static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
374 max_size
= new_max_size
;
375 else if (new_max_size
!= max_size
) {
376 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir '" << path
<< "' size "
377 "cannot be changed dynamically, value left unchanged (" <<
378 (max_size
>> 20) << " MB)");
383 Rock::SwapDir::getOptionTree() const
385 ConfigOptionVector
*vector
= dynamic_cast<ConfigOptionVector
*>(::SwapDir::getOptionTree());
387 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseSizeOption
, &SwapDir::dumpSizeOption
));
388 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseTimeOption
, &SwapDir::dumpTimeOption
));
389 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseRateOption
, &SwapDir::dumpRateOption
));
394 Rock::SwapDir::allowOptionReconfigure(const char *const option
) const
396 return strcmp(option
, "slot-size") != 0 &&
397 ::SwapDir::allowOptionReconfigure(option
);
400 /// parses time-specific options; mimics ::SwapDir::optionObjectSizeParse()
402 Rock::SwapDir::parseTimeOption(char const *option
, const char *value
, int reconfig
)
404 // TODO: ::SwapDir or, better, Config should provide time-parsing routines,
405 // including time unit handling. Same for size and rate.
407 time_msec_t
*storedTime
;
408 if (strcmp(option
, "swap-timeout") == 0)
409 storedTime
= &fileConfig
.ioTimeout
;
416 // TODO: handle time units and detect parsing errors better
417 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
418 if (parsedValue
< 0) {
419 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
423 const time_msec_t newTime
= static_cast<time_msec_t
>(parsedValue
);
426 *storedTime
= newTime
;
427 else if (*storedTime
!= newTime
) {
428 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
429 << " cannot be changed dynamically, value left unchanged: " <<
436 /// reports time-specific options; mimics ::SwapDir::optionObjectSizeDump()
438 Rock::SwapDir::dumpTimeOption(StoreEntry
* e
) const
440 if (fileConfig
.ioTimeout
)
441 storeAppendPrintf(e
, " swap-timeout=%" PRId64
,
442 static_cast<int64_t>(fileConfig
.ioTimeout
));
445 /// parses rate-specific options; mimics ::SwapDir::optionObjectSizeParse()
447 Rock::SwapDir::parseRateOption(char const *option
, const char *value
, int isaReconfig
)
450 if (strcmp(option
, "max-swap-rate") == 0)
451 storedRate
= &fileConfig
.ioRate
;
458 // TODO: handle time units and detect parsing errors better
459 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
460 if (parsedValue
< 0) {
461 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
465 const int newRate
= static_cast<int>(parsedValue
);
468 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << newRate
);
473 *storedRate
= newRate
;
474 else if (*storedRate
!= newRate
) {
475 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
476 << " cannot be changed dynamically, value left unchanged: " <<
483 /// reports rate-specific options; mimics ::SwapDir::optionObjectSizeDump()
485 Rock::SwapDir::dumpRateOption(StoreEntry
* e
) const
487 if (fileConfig
.ioRate
>= 0)
488 storeAppendPrintf(e
, " max-swap-rate=%d", fileConfig
.ioRate
);
491 /// parses size-specific options; mimics ::SwapDir::optionObjectSizeParse()
493 Rock::SwapDir::parseSizeOption(char const *option
, const char *value
, int reconfig
)
495 uint64_t *storedSize
;
496 if (strcmp(option
, "slot-size") == 0)
497 storedSize
= &slotSize
;
504 // TODO: handle size units and detect parsing errors better
505 const uint64_t newSize
= strtoll(value
, NULL
, 10);
507 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must be positive; got: " << newSize
);
511 if (newSize
<= sizeof(DbCellHeader
)) {
512 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must exceed " << sizeof(DbCellHeader
) << "; got: " << newSize
);
517 *storedSize
= newSize
;
518 else if (*storedSize
!= newSize
) {
519 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
520 << " cannot be changed dynamically, value left unchanged: " <<
527 /// reports size-specific options; mimics ::SwapDir::optionObjectSizeDump()
529 Rock::SwapDir::dumpSizeOption(StoreEntry
* e
) const
531 storeAppendPrintf(e
, " slot-size=%" PRId64
, slotSize
);
534 /// check the results of the configuration; only level-0 debugging works here
536 Rock::SwapDir::validateOptions()
539 fatal("Rock store requires a positive slot-size");
541 const int64_t maxSizeRoundingWaste
= 1024 * 1024; // size is configured in MB
542 const int64_t slotSizeRoundingWaste
= slotSize
;
543 const int64_t maxRoundingWaste
=
544 max(maxSizeRoundingWaste
, slotSizeRoundingWaste
);
545 const int64_t usableDiskSize
= diskOffset(entryLimitAllowed());
546 const int64_t diskWasteSize
= maxSize() - usableDiskSize
;
547 Must(diskWasteSize
>= 0);
549 // warn if maximum db size is not reachable due to sfileno limit
550 if (entryLimitAllowed() == entryLimitHigh() &&
551 diskWasteSize
>= maxRoundingWaste
) {
552 debugs(47, DBG_CRITICAL
, "Rock store cache_dir[" << index
<< "] '" << path
<< "':");
553 debugs(47, DBG_CRITICAL
, "\tmaximum number of entries: " << entryLimitAllowed());
554 debugs(47, DBG_CRITICAL
, "\tdb slot size: " << slotSize
<< " Bytes");
555 debugs(47, DBG_CRITICAL
, "\tmaximum db size: " << maxSize() << " Bytes");
556 debugs(47, DBG_CRITICAL
, "\tusable db size: " << usableDiskSize
<< " Bytes");
557 debugs(47, DBG_CRITICAL
, "\tdisk space waste: " << diskWasteSize
<< " Bytes");
558 debugs(47, DBG_CRITICAL
, "WARNING: Rock store config wastes space.");
563 Rock::SwapDir::rebuild()
565 //++StoreController::store_dirs_rebuilding; // see Rock::SwapDir::init()
566 AsyncJob::Start(new Rebuild(this));
570 Rock::SwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
572 if (!::SwapDir::canStore(e
, sizeof(DbCellHeader
)+diskSpaceNeeded
, load
))
575 if (!theFile
|| !theFile
->canWrite())
581 // Do not start I/O transaction if there are less than 10% free pages left.
582 // TODO: reserve page instead
583 if (needsDiskStrand() &&
584 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
585 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
596 StoreIOState::Pointer
597 Rock::SwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
599 if (!theFile
|| theFile
->error()) {
600 debugs(47,4, HERE
<< theFile
);
605 Ipc::StoreMapAnchor
*const slot
=
606 map
->openForWriting(reinterpret_cast<const cache_key
*>(e
.key
), filen
);
608 debugs(47, 5, HERE
<< "map->add failed");
615 // XXX: We rely on our caller, storeSwapOutStart(), to set e.fileno.
616 // If that does not happen, the entry will not decrement the read level!
618 Rock::SwapDir::Pointer
self(this);
619 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
621 sio
->swap_dirn
= index
;
622 sio
->swap_filen
= filen
;
623 sio
->writeableAnchor_
= slot
;
625 debugs(47,5, HERE
<< "dir " << index
<< " created new filen " <<
626 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
627 sio
->swap_filen
<< std::dec
<< " starting at " <<
628 diskOffset(sio
->swap_filen
));
637 Rock::SwapDir::diskOffset(int filen
) const
640 return HeaderSize
+ slotSize
*filen
;
644 Rock::SwapDir::diskOffset(Ipc::Mem::PageId
&pageId
) const
647 return diskOffset(pageId
.number
- 1);
651 Rock::SwapDir::diskOffsetLimit() const
654 return diskOffset(map
->entryLimit());
658 Rock::SwapDir::entryMaxPayloadSize() const
660 return slotSize
- sizeof(DbCellHeader
);
664 Rock::SwapDir::entriesNeeded(const int64_t objSize
) const
666 return (objSize
+ entryMaxPayloadSize() - 1) / entryMaxPayloadSize();
670 Rock::SwapDir::useFreeSlot(Ipc::Mem::PageId
&pageId
)
672 if (freeSlots
->pop(pageId
)) {
673 debugs(47, 5, "got a previously free slot: " << pageId
);
677 // catch free slots delivered to noteFreeMapSlice()
678 assert(!waitingForPage
);
679 waitingForPage
= &pageId
;
680 if (map
->purgeOne()) {
681 assert(!waitingForPage
); // noteFreeMapSlice() should have cleared it
682 assert(pageId
.set());
683 debugs(47, 5, "got a previously busy slot: " << pageId
);
686 assert(waitingForPage
== &pageId
);
687 waitingForPage
= NULL
;
689 debugs(47, 3, "cannot get a slot; entries: " << map
->entryCount());
694 Rock::SwapDir::validSlotId(const SlotId slotId
) const
696 return 0 <= slotId
&& slotId
< entryLimitAllowed();
700 Rock::SwapDir::noteFreeMapSlice(const sfileno sliceId
)
702 Ipc::Mem::PageId pageId
;
703 pageId
.pool
= index
+1;
704 pageId
.number
= sliceId
+1;
705 if (waitingForPage
) {
706 *waitingForPage
= pageId
;
707 waitingForPage
= NULL
;
709 freeSlots
->push(pageId
);
713 // tries to open an old entry with swap_filen for reading
714 StoreIOState::Pointer
715 Rock::SwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
717 if (!theFile
|| theFile
->error()) {
718 debugs(47,4, HERE
<< theFile
);
722 if (e
.swap_filen
< 0) {
723 debugs(47,4, HERE
<< e
);
727 // Do not start I/O transaction if there are less than 10% free pages left.
728 // TODO: reserve page instead
729 if (needsDiskStrand() &&
730 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
731 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
735 // The are two ways an entry can get swap_filen: our get() locked it for
736 // reading or our storeSwapOutStart() locked it for writing. Peeking at our
737 // locked entry is safe, but no support for reading the entry we swap out.
738 const Ipc::StoreMapAnchor
*slot
= map
->peekAtReader(e
.swap_filen
);
740 return NULL
; // we were writing afterall
742 Rock::SwapDir::Pointer
self(this);
743 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
745 sio
->swap_dirn
= index
;
746 sio
->swap_filen
= e
.swap_filen
;
747 sio
->readableAnchor_
= slot
;
750 debugs(47,5, HERE
<< "dir " << index
<< " has old filen: " <<
751 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
754 assert(slot
->sameKey(static_cast<const cache_key
*>(e
.key
)));
755 // For collapsed disk hits: e.swap_file_sz and slot->basics.swap_file_sz
756 // may still be zero and basics.swap_file_sz may grow.
757 assert(slot
->basics
.swap_file_sz
>= e
.swap_file_sz
);
763 Rock::SwapDir::ioCompletedNotification()
766 fatalf("Rock cache_dir failed to initialize db file: %s", filePath
);
768 if (theFile
->error())
769 fatalf("Rock cache_dir at %s failed to open db file: %s", filePath
,
772 debugs(47, 2, "Rock cache_dir[" << index
<< "] limits: " <<
773 std::setw(12) << maxSize() << " disk bytes and " <<
774 std::setw(7) << map
->entryLimit() << " entries");
780 Rock::SwapDir::closeCompleted()
786 Rock::SwapDir::readCompleted(const char *buf
, int rlen
, int errflag
, RefCount
< ::ReadRequest
> r
)
788 ReadRequest
*request
= dynamic_cast<Rock::ReadRequest
*>(r
.getRaw());
790 IoState::Pointer sio
= request
->sio
;
792 if (errflag
== DISK_OK
&& rlen
> 0)
793 sio
->offset_
+= rlen
;
795 sio
->callReaderBack(r
->buf
, rlen
);
799 Rock::SwapDir::writeCompleted(int errflag
, size_t rlen
, RefCount
< ::WriteRequest
> r
)
801 Rock::WriteRequest
*request
= dynamic_cast<Rock::WriteRequest
*>(r
.getRaw());
803 assert(request
->sio
!= NULL
);
804 IoState
&sio
= *request
->sio
;
806 // quit if somebody called IoState::close() while we were waiting
807 if (!sio
.stillWaiting()) {
808 debugs(79, 3, "ignoring closed entry " << sio
.swap_filen
);
809 noteFreeMapSlice(request
->sidNext
);
813 // TODO: Fail if disk dropped one of the previous write requests.
815 if (errflag
== DISK_OK
) {
816 // do not increment sio.offset_ because we do it in sio->write()
818 // finalize the shared slice info after writing slice contents to disk
819 Ipc::StoreMap::Slice
&slice
=
820 map
->writeableSlice(sio
.swap_filen
, request
->sidCurrent
);
821 slice
.size
= request
->len
- sizeof(DbCellHeader
);
822 slice
.next
= request
->sidNext
;
826 assert(sio
.writeableAnchor_
);
827 sio
.e
->swap_file_sz
= sio
.writeableAnchor_
->basics
.swap_file_sz
=
830 // close, the entry gets the read lock
831 map
->closeForWriting(sio
.swap_filen
, true);
832 sio
.writeableAnchor_
= NULL
;
833 sio
.finishedWriting(errflag
);
836 noteFreeMapSlice(request
->sidNext
);
839 sio
.finishedWriting(errflag
);
840 // and hope that Core will call disconnect() to close the map entry
843 CollapsedForwarding::Broadcast(*sio
.e
);
847 Rock::SwapDir::writeError(StoreEntry
&e
)
849 // Do not abortWriting here. The entry should keep the write lock
850 // instead of losing association with the store and confusing core.
851 map
->freeEntry(e
.swap_filen
); // will mark as unusable, just in case
853 Store::Root().transientsAbandon(e
);
855 // All callers must also call IoState callback, to propagate the error.
859 Rock::SwapDir::full() const
861 return freeSlots
!= NULL
&& !freeSlots
->size();
864 // storeSwapOutFileClosed calls this nethod on DISK_NO_SPACE_LEFT,
865 // but it should not happen for us
867 Rock::SwapDir::diskFull()
869 debugs(20, DBG_IMPORTANT
, "BUG: No space left with rock cache_dir: " <<
873 /// purge while full(); it should be sufficient to purge just one
875 Rock::SwapDir::maintain()
877 // The Store calls this to free some db space, but there is nothing wrong
878 // with a full() db, except when db has to shrink after reconfigure, and
879 // we do not support shrinking yet (it would have to purge specific slots).
880 // TODO: Disable maintain() requests when they are pointless.
884 Rock::SwapDir::reference(StoreEntry
&e
)
886 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
887 if (repl
&& repl
->Referenced
)
888 repl
->Referenced(repl
, &e
, &e
.repl
);
892 Rock::SwapDir::dereference(StoreEntry
&e
, bool)
894 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
895 if (repl
&& repl
->Dereferenced
)
896 repl
->Dereferenced(repl
, &e
, &e
.repl
);
898 // no need to keep e in the global store_table for us; we have our own map
903 Rock::SwapDir::unlinkdUseful() const
905 // no entry-specific files to unlink
910 Rock::SwapDir::unlink(StoreEntry
&e
)
912 debugs(47, 5, HERE
<< e
);
914 map
->freeEntry(e
.swap_filen
);
919 Rock::SwapDir::markForUnlink(StoreEntry
&e
)
922 map
->freeEntry(e
.swap_filen
);
926 Rock::SwapDir::trackReferences(StoreEntry
&e
)
928 debugs(47, 5, HERE
<< e
);
930 repl
->Add(repl
, &e
, &e
.repl
);
934 Rock::SwapDir::ignoreReferences(StoreEntry
&e
)
936 debugs(47, 5, HERE
<< e
);
938 repl
->Remove(repl
, &e
, &e
.repl
);
942 Rock::SwapDir::statfs(StoreEntry
&e
) const
944 storeAppendPrintf(&e
, "\n");
945 storeAppendPrintf(&e
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
946 storeAppendPrintf(&e
, "Current Size: %.2f KB %.2f%%\n",
947 currentSize() / 1024.0,
948 Math::doublePercent(currentSize(), maxSize()));
951 const int limit
= map
->entryLimit();
952 storeAppendPrintf(&e
, "Maximum entries: %9d\n", limit
);
954 const int entryCount
= map
->entryCount();
955 storeAppendPrintf(&e
, "Current entries: %9d %.2f%%\n",
956 entryCount
, (100.0 * entryCount
/ limit
));
958 const unsigned int slotsFree
= !freeSlots
? 0 : freeSlots
->size();
959 if (slotsFree
<= static_cast<const unsigned int>(limit
)) {
960 const int usedSlots
= limit
- static_cast<const int>(slotsFree
);
961 storeAppendPrintf(&e
, "Used slots: %9d %.2f%%\n",
962 usedSlots
, (100.0 * usedSlots
/ limit
));
964 if (limit
< 100) { // XXX: otherwise too expensive to count
965 Ipc::ReadWriteLockStats stats
;
966 map
->updateStats(stats
);
972 storeAppendPrintf(&e
, "Pending operations: %d out of %d\n",
973 store_open_disk_fd
, Config
.max_open_disk_fds
);
975 storeAppendPrintf(&e
, "Flags:");
978 storeAppendPrintf(&e
, " SELECTED");
981 storeAppendPrintf(&e
, " READ-ONLY");
983 storeAppendPrintf(&e
, "\n");
988 Rock::SwapDir::inodeMapPath() const
990 static String inodesPath
;
992 inodesPath
.append("_inodes");
993 return inodesPath
.termedBuf();
997 Rock::SwapDir::freeSlotsPath() const
999 static String spacesPath
;
1001 spacesPath
.append("_spaces");
1002 return spacesPath
.termedBuf();
1007 RunnerRegistrationEntry(rrAfterConfig
, SwapDirRr
);
1010 void Rock::SwapDirRr::create(const RunnerRegistry
&)
1012 Must(mapOwners
.empty() && freeSlotsOwners
.empty());
1013 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1014 if (const Rock::SwapDir
*const sd
= dynamic_cast<Rock::SwapDir
*>(INDEXSD(i
))) {
1015 const int64_t capacity
= sd
->entryLimitAllowed();
1017 SwapDir::DirMap::Owner
*const mapOwner
=
1018 SwapDir::DirMap::Init(sd
->inodeMapPath(), capacity
);
1019 mapOwners
.push_back(mapOwner
);
1021 // TODO: somehow remove pool id and counters from PageStack?
1022 Ipc::Mem::Owner
<Ipc::Mem::PageStack
> *const freeSlotsOwner
=
1023 shm_new(Ipc::Mem::PageStack
)(sd
->freeSlotsPath(),
1025 sizeof(DbCellHeader
));
1026 freeSlotsOwners
.push_back(freeSlotsOwner
);
1028 // TODO: add method to initialize PageStack with no free pages
1030 Ipc::Mem::PageId pageId
;
1031 if (!freeSlotsOwner
->object()->pop(pageId
))
1038 Rock::SwapDirRr::~SwapDirRr()
1040 for (size_t i
= 0; i
< mapOwners
.size(); ++i
) {
1041 delete mapOwners
[i
];
1042 delete freeSlotsOwners
[i
];