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/RockSwapDir.h"
14 #include "fs/rock/RockIoState.h"
15 #include "fs/rock/RockIoRequests.h"
16 #include "fs/rock/RockRebuild.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
;
153 void Rock::SwapDir::disconnect(StoreEntry
&e
)
155 assert(e
.swap_dirn
== index
);
156 assert(e
.swap_filen
>= 0);
157 // cannot have SWAPOUT_NONE entry with swap_filen >= 0
158 assert(e
.swap_status
!= SWAPOUT_NONE
);
160 // do not rely on e.swap_status here because there is an async delay
161 // before it switches from SWAPOUT_WRITING to SWAPOUT_DONE.
163 // since e has swap_filen, its slot is locked for reading and/or writing
164 // but it is difficult to know whether THIS worker is reading or writing e
165 if (e
.swap_status
== SWAPOUT_WRITING
||
166 (e
.mem_obj
&& e
.mem_obj
->swapout
.sio
!= NULL
)) {
167 map
->abortWriting(e
.swap_filen
);
170 e
.swap_status
= SWAPOUT_NONE
;
171 Store::Root().transientsAbandon(e
); // broadcasts after the change
173 map
->closeForReading(e
.swap_filen
);
176 e
.swap_status
= SWAPOUT_NONE
;
181 Rock::SwapDir::currentSize() const
183 const uint64_t spaceSize
= !freeSlots
?
184 maxSize() : (slotSize
* freeSlots
->size());
185 // everything that is not free is in use
186 return maxSize() - spaceSize
;
190 Rock::SwapDir::currentCount() const
192 return map
? map
->entryCount() : 0;
195 /// In SMP mode only the disker process reports stats to avoid
196 /// counting the same stats by multiple processes.
198 Rock::SwapDir::doReportStat() const
200 return ::SwapDir::doReportStat() && (!UsingSmp() || IamDiskProcess());
204 Rock::SwapDir::swappedOut(const StoreEntry
&)
206 // stats are not stored but computed when needed
210 Rock::SwapDir::entryLimitAllowed() const
212 const int64_t eLimitLo
= map
? map
->entryLimit() : 0; // dynamic shrinking unsupported
213 const int64_t eWanted
= (maxSize() - HeaderSize
)/slotSize
;
214 return min(max(eLimitLo
, eWanted
), entryLimitHigh());
217 // TODO: encapsulate as a tool; identical to CossSwapDir::create()
219 Rock::SwapDir::create()
224 if (UsingSmp() && !IamDiskProcess()) {
225 debugs (47,3, HERE
<< "disker will create in " << path
);
229 debugs (47,3, HERE
<< "creating in " << path
);
232 if (::stat(path
, &dir_sb
) == 0) {
234 if (::stat(filePath
, &file_sb
) == 0) {
235 debugs (47, DBG_IMPORTANT
, "Skipping existing Rock db: " << filePath
);
238 // else the db file is not there or is not accessible, and we will try
239 // to create it later below, generating a detailed error on failures.
240 } else { // path does not exist or is inaccessible
241 // If path exists but is not accessible, mkdir() below will fail, and
242 // the admin should see the error and act accordingly, so there is
243 // no need to distinguish ENOENT from other possible stat() errors.
244 debugs (47, DBG_IMPORTANT
, "Creating Rock db directory: " << path
);
245 const int res
= mkdir(path
, 0700);
247 createError("mkdir");
250 debugs (47, DBG_IMPORTANT
, "Creating Rock db: " << filePath
);
251 const int swap
= open(filePath
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_BINARY
, 0600);
253 createError("create");
255 #if SLOWLY_FILL_WITH_ZEROS
257 Must(maxSize() % sizeof(block
) == 0);
258 memset(block
, '\0', sizeof(block
));
260 for (off_t offset
= 0; offset
< maxSize(); offset
+= sizeof(block
)) {
261 if (write(swap
, block
, sizeof(block
)) != sizeof(block
))
262 createError("write");
265 if (ftruncate(swap
, maxSize()) != 0)
266 createError("truncate");
268 char header
[HeaderSize
];
269 memset(header
, '\0', sizeof(header
));
270 if (write(swap
, header
, sizeof(header
)) != sizeof(header
))
271 createError("write");
277 // report Rock DB creation error and exit
279 Rock::SwapDir::createError(const char *const msg
) {
280 debugs(47, DBG_CRITICAL
, "ERROR: Failed to initialize Rock Store db in " <<
281 filePath
<< "; " << msg
<< " error: " << xstrerror());
282 fatal("Rock Store db creation error");
286 Rock::SwapDir::init()
290 // XXX: SwapDirs aren't refcounted. We make IORequestor calls, which
291 // are refcounted. We up our count once to avoid implicit delete's.
294 freeSlots
= shm_old(Ipc::Mem::PageStack
)(freeSlotsPath());
297 map
= new DirMap(inodeMapPath());
300 const char *ioModule
= needsDiskStrand() ? "IpcIo" : "Blocking";
301 if (DiskIOModule
*m
= DiskIOModule::Find(ioModule
)) {
302 debugs(47,2, HERE
<< "Using DiskIO module: " << ioModule
);
303 io
= m
->createStrategy();
306 debugs(47, DBG_CRITICAL
, "FATAL: Rock store is missing DiskIO module: " <<
308 fatal("Rock Store missing a required DiskIO module");
311 theFile
= io
->newFile(filePath
);
312 theFile
->configure(fileConfig
);
313 theFile
->open(O_RDWR
, 0644, this);
315 // Increment early. Otherwise, if one SwapDir finishes rebuild before
316 // others start, storeRebuildComplete() will think the rebuild is over!
317 // TODO: move store_dirs_rebuilding hack to store modules that need it.
318 ++StoreController::store_dirs_rebuilding
;
322 Rock::SwapDir::needsDiskStrand() const
324 const bool wontEvenWorkWithoutDisker
= Config
.workers
> 1;
325 const bool wouldWorkBetterWithDisker
= DiskIOModule::Find("IpcIo");
326 return InDaemonMode() && (wontEvenWorkWithoutDisker
||
327 wouldWorkBetterWithDisker
);
331 Rock::SwapDir::parse(int anIndex
, char *aPath
)
335 path
= xstrdup(aPath
);
337 // cache store is located at path/db
339 fname
.append("/rock");
340 filePath
= xstrdup(fname
.termedBuf());
345 // Current openForWriting() code overwrites the old slot if needed
346 // and possible, so proactively removing old slots is probably useless.
347 assert(!repl
); // repl = createRemovalPolicy(Config.replPolicy);
353 Rock::SwapDir::reconfigure()
357 // TODO: can we reconfigure the replacement policy (repl)?
361 /// parse maximum db disk size
363 Rock::SwapDir::parseSize(const bool reconfig
)
365 const int i
= GetInteger();
367 fatal("negative Rock cache_dir size value");
368 const uint64_t new_max_size
=
369 static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
371 max_size
= new_max_size
;
372 else if (new_max_size
!= max_size
) {
373 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir '" << path
<< "' size "
374 "cannot be changed dynamically, value left unchanged (" <<
375 (max_size
>> 20) << " MB)");
380 Rock::SwapDir::getOptionTree() const
382 ConfigOptionVector
*vector
= dynamic_cast<ConfigOptionVector
*>(::SwapDir::getOptionTree());
384 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseSizeOption
, &SwapDir::dumpSizeOption
));
385 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseTimeOption
, &SwapDir::dumpTimeOption
));
386 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseRateOption
, &SwapDir::dumpRateOption
));
391 Rock::SwapDir::allowOptionReconfigure(const char *const option
) const
393 return strcmp(option
, "slot-size") != 0 &&
394 ::SwapDir::allowOptionReconfigure(option
);
397 /// parses time-specific options; mimics ::SwapDir::optionObjectSizeParse()
399 Rock::SwapDir::parseTimeOption(char const *option
, const char *value
, int reconfig
)
401 // TODO: ::SwapDir or, better, Config should provide time-parsing routines,
402 // including time unit handling. Same for size and rate.
404 time_msec_t
*storedTime
;
405 if (strcmp(option
, "swap-timeout") == 0)
406 storedTime
= &fileConfig
.ioTimeout
;
413 // TODO: handle time units and detect parsing errors better
414 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
415 if (parsedValue
< 0) {
416 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
420 const time_msec_t newTime
= static_cast<time_msec_t
>(parsedValue
);
423 *storedTime
= newTime
;
424 else if (*storedTime
!= newTime
) {
425 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
426 << " cannot be changed dynamically, value left unchanged: " <<
433 /// reports time-specific options; mimics ::SwapDir::optionObjectSizeDump()
435 Rock::SwapDir::dumpTimeOption(StoreEntry
* e
) const
437 if (fileConfig
.ioTimeout
)
438 storeAppendPrintf(e
, " swap-timeout=%" PRId64
,
439 static_cast<int64_t>(fileConfig
.ioTimeout
));
442 /// parses rate-specific options; mimics ::SwapDir::optionObjectSizeParse()
444 Rock::SwapDir::parseRateOption(char const *option
, const char *value
, int isaReconfig
)
447 if (strcmp(option
, "max-swap-rate") == 0)
448 storedRate
= &fileConfig
.ioRate
;
455 // TODO: handle time units and detect parsing errors better
456 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
457 if (parsedValue
< 0) {
458 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
462 const int newRate
= static_cast<int>(parsedValue
);
465 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << newRate
);
470 *storedRate
= newRate
;
471 else if (*storedRate
!= newRate
) {
472 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
473 << " cannot be changed dynamically, value left unchanged: " <<
480 /// reports rate-specific options; mimics ::SwapDir::optionObjectSizeDump()
482 Rock::SwapDir::dumpRateOption(StoreEntry
* e
) const
484 if (fileConfig
.ioRate
>= 0)
485 storeAppendPrintf(e
, " max-swap-rate=%d", fileConfig
.ioRate
);
488 /// parses size-specific options; mimics ::SwapDir::optionObjectSizeParse()
490 Rock::SwapDir::parseSizeOption(char const *option
, const char *value
, int reconfig
)
492 uint64_t *storedSize
;
493 if (strcmp(option
, "slot-size") == 0)
494 storedSize
= &slotSize
;
501 // TODO: handle size units and detect parsing errors better
502 const uint64_t newSize
= strtoll(value
, NULL
, 10);
504 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must be positive; got: " << newSize
);
508 if (newSize
<= sizeof(DbCellHeader
)) {
509 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must exceed " << sizeof(DbCellHeader
) << "; got: " << newSize
);
514 *storedSize
= newSize
;
515 else if (*storedSize
!= newSize
) {
516 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
517 << " cannot be changed dynamically, value left unchanged: " <<
524 /// reports size-specific options; mimics ::SwapDir::optionObjectSizeDump()
526 Rock::SwapDir::dumpSizeOption(StoreEntry
* e
) const
528 storeAppendPrintf(e
, " slot-size=%" PRId64
, slotSize
);
531 /// check the results of the configuration; only level-0 debugging works here
533 Rock::SwapDir::validateOptions()
536 fatal("Rock store requires a positive slot-size");
538 const int64_t maxSizeRoundingWaste
= 1024 * 1024; // size is configured in MB
539 const int64_t slotSizeRoundingWaste
= slotSize
;
540 const int64_t maxRoundingWaste
=
541 max(maxSizeRoundingWaste
, slotSizeRoundingWaste
);
542 const int64_t usableDiskSize
= diskOffset(entryLimitAllowed());
543 const int64_t diskWasteSize
= maxSize() - usableDiskSize
;
544 Must(diskWasteSize
>= 0);
546 // warn if maximum db size is not reachable due to sfileno limit
547 if (entryLimitAllowed() == entryLimitHigh() &&
548 diskWasteSize
>= maxRoundingWaste
) {
549 debugs(47, DBG_CRITICAL
, "Rock store cache_dir[" << index
<< "] '" << path
<< "':");
550 debugs(47, DBG_CRITICAL
, "\tmaximum number of entries: " << entryLimitAllowed());
551 debugs(47, DBG_CRITICAL
, "\tdb slot size: " << slotSize
<< " Bytes");
552 debugs(47, DBG_CRITICAL
, "\tmaximum db size: " << maxSize() << " Bytes");
553 debugs(47, DBG_CRITICAL
, "\tusable db size: " << usableDiskSize
<< " Bytes");
554 debugs(47, DBG_CRITICAL
, "\tdisk space waste: " << diskWasteSize
<< " Bytes");
555 debugs(47, DBG_CRITICAL
, "WARNING: Rock store config wastes space.");
560 Rock::SwapDir::rebuild()
562 //++StoreController::store_dirs_rebuilding; // see Rock::SwapDir::init()
563 AsyncJob::Start(new Rebuild(this));
567 Rock::SwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
569 if (!::SwapDir::canStore(e
, sizeof(DbCellHeader
)+diskSpaceNeeded
, load
))
572 if (!theFile
|| !theFile
->canWrite())
578 // Do not start I/O transaction if there are less than 10% free pages left.
579 // TODO: reserve page instead
580 if (needsDiskStrand() &&
581 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
582 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
593 StoreIOState::Pointer
594 Rock::SwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
596 if (!theFile
|| theFile
->error()) {
597 debugs(47,4, HERE
<< theFile
);
602 Ipc::StoreMapAnchor
*const slot
=
603 map
->openForWriting(reinterpret_cast<const cache_key
*>(e
.key
), filen
);
605 debugs(47, 5, HERE
<< "map->add failed");
612 // XXX: We rely on our caller, storeSwapOutStart(), to set e.fileno.
613 // If that does not happen, the entry will not decrement the read level!
615 Rock::SwapDir::Pointer
self(this);
616 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
618 sio
->swap_dirn
= index
;
619 sio
->swap_filen
= filen
;
620 sio
->writeableAnchor_
= slot
;
622 debugs(47,5, HERE
<< "dir " << index
<< " created new filen " <<
623 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
624 sio
->swap_filen
<< std::dec
<< " starting at " <<
625 diskOffset(sio
->swap_filen
));
634 Rock::SwapDir::diskOffset(int filen
) const
637 return HeaderSize
+ slotSize
*filen
;
641 Rock::SwapDir::diskOffset(Ipc::Mem::PageId
&pageId
) const
644 return diskOffset(pageId
.number
- 1);
648 Rock::SwapDir::diskOffsetLimit() const
651 return diskOffset(map
->entryLimit());
655 Rock::SwapDir::entryMaxPayloadSize() const
657 return slotSize
- sizeof(DbCellHeader
);
661 Rock::SwapDir::entriesNeeded(const int64_t objSize
) const
663 return (objSize
+ entryMaxPayloadSize() - 1) / entryMaxPayloadSize();
667 Rock::SwapDir::useFreeSlot(Ipc::Mem::PageId
&pageId
)
669 if (freeSlots
->pop(pageId
)) {
670 debugs(47, 5, "got a previously free slot: " << pageId
);
674 // catch free slots delivered to noteFreeMapSlice()
675 assert(!waitingForPage
);
676 waitingForPage
= &pageId
;
677 if (map
->purgeOne()) {
678 assert(!waitingForPage
); // noteFreeMapSlice() should have cleared it
679 assert(pageId
.set());
680 debugs(47, 5, "got a previously busy slot: " << pageId
);
683 assert(waitingForPage
== &pageId
);
684 waitingForPage
= NULL
;
686 debugs(47, 3, "cannot get a slot; entries: " << map
->entryCount());
691 Rock::SwapDir::validSlotId(const SlotId slotId
) const
693 return 0 <= slotId
&& slotId
< entryLimitAllowed();
697 Rock::SwapDir::noteFreeMapSlice(const sfileno sliceId
)
699 Ipc::Mem::PageId pageId
;
700 pageId
.pool
= index
+1;
701 pageId
.number
= sliceId
+1;
702 if (waitingForPage
) {
703 *waitingForPage
= pageId
;
704 waitingForPage
= NULL
;
706 freeSlots
->push(pageId
);
710 // tries to open an old entry with swap_filen for reading
711 StoreIOState::Pointer
712 Rock::SwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
714 if (!theFile
|| theFile
->error()) {
715 debugs(47,4, HERE
<< theFile
);
719 if (e
.swap_filen
< 0) {
720 debugs(47,4, HERE
<< e
);
724 // Do not start I/O transaction if there are less than 10% free pages left.
725 // TODO: reserve page instead
726 if (needsDiskStrand() &&
727 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
728 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
732 // The are two ways an entry can get swap_filen: our get() locked it for
733 // reading or our storeSwapOutStart() locked it for writing. Peeking at our
734 // locked entry is safe, but no support for reading a filling entry.
735 const Ipc::StoreMapAnchor
*slot
= map
->peekAtReader(e
.swap_filen
);
737 return NULL
; // we were writing afterall
739 Rock::SwapDir::Pointer
self(this);
740 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
742 sio
->swap_dirn
= index
;
743 sio
->swap_filen
= e
.swap_filen
;
744 sio
->readableAnchor_
= slot
;
747 debugs(47,5, HERE
<< "dir " << index
<< " has old filen: " <<
748 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
751 assert(slot
->sameKey(static_cast<const cache_key
*>(e
.key
)));
752 assert(slot
->basics
.swap_file_sz
> 0);
753 assert(slot
->basics
.swap_file_sz
== e
.swap_file_sz
);
759 Rock::SwapDir::ioCompletedNotification()
762 fatalf("Rock cache_dir failed to initialize db file: %s", filePath
);
764 if (theFile
->error())
765 fatalf("Rock cache_dir at %s failed to open db file: %s", filePath
,
768 debugs(47, 2, "Rock cache_dir[" << index
<< "] limits: " <<
769 std::setw(12) << maxSize() << " disk bytes and " <<
770 std::setw(7) << map
->entryLimit() << " entries");
776 Rock::SwapDir::closeCompleted()
782 Rock::SwapDir::readCompleted(const char *buf
, int rlen
, int errflag
, RefCount
< ::ReadRequest
> r
)
784 ReadRequest
*request
= dynamic_cast<Rock::ReadRequest
*>(r
.getRaw());
786 IoState::Pointer sio
= request
->sio
;
788 if (errflag
== DISK_OK
&& rlen
> 0)
789 sio
->offset_
+= rlen
;
791 StoreIOState::STRCB
*callb
= sio
->read
.callback
;
793 sio
->read
.callback
= NULL
;
795 if (cbdataReferenceValidDone(sio
->read
.callback_data
, &cbdata
))
796 callb(cbdata
, r
->buf
, rlen
, sio
.getRaw());
800 Rock::SwapDir::writeCompleted(int errflag
, size_t rlen
, RefCount
< ::WriteRequest
> r
)
802 Rock::WriteRequest
*request
= dynamic_cast<Rock::WriteRequest
*>(r
.getRaw());
804 assert(request
->sio
!= NULL
);
805 IoState
&sio
= *request
->sio
;
807 // quit if somebody called IoState::close() while we were waiting
808 if (!sio
.stillWaiting()) {
809 debugs(79, 3, "ignoring closed entry " << sio
.swap_filen
);
813 if (errflag
== DISK_OK
) {
814 // do not increment sio.offset_ because we do it in sio->write()
816 // finalize the shared slice info after writing slice contents to disk
817 Ipc::StoreMap::Slice
&slice
=
818 map
->writeableSlice(sio
.swap_filen
, request
->sidCurrent
);
819 slice
.size
= request
->len
- sizeof(DbCellHeader
);
820 slice
.next
= request
->sidNext
;
822 if (request
->sidNext
< 0) {
823 // close, the entry gets the read lock
824 map
->closeForWriting(sio
.swap_filen
, true);
825 sio
.finishedWriting(errflag
);
829 sio
.finishedWriting(errflag
);
830 // and hope that Core will call disconnect() to close the map entry
833 CollapsedForwarding::Broadcast(*sio
.e
);
837 Rock::SwapDir::writeError(StoreEntry
&e
)
839 // Do not abortWriting here. The entry should keep the write lock
840 // instead of losing association with the store and confusing core.
841 map
->freeEntry(e
.swap_filen
); // will mark as unusable, just in case
843 Store::Root().transientsAbandon(e
);
845 // All callers must also call IoState callback, to propagate the error.
849 Rock::SwapDir::full() const
851 return freeSlots
!= NULL
&& !freeSlots
->size();
854 // storeSwapOutFileClosed calls this nethod on DISK_NO_SPACE_LEFT,
855 // but it should not happen for us
857 Rock::SwapDir::diskFull()
859 debugs(20, DBG_IMPORTANT
, "BUG: No space left with rock cache_dir: " <<
863 /// purge while full(); it should be sufficient to purge just one
865 Rock::SwapDir::maintain()
867 // The Store calls this to free some db space, but there is nothing wrong
868 // with a full() db, except when db has to shrink after reconfigure, and
869 // we do not support shrinking yet (it would have to purge specific slots).
870 // TODO: Disable maintain() requests when they are pointless.
874 Rock::SwapDir::reference(StoreEntry
&e
)
876 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
877 if (repl
&& repl
->Referenced
)
878 repl
->Referenced(repl
, &e
, &e
.repl
);
882 Rock::SwapDir::dereference(StoreEntry
&e
, bool)
884 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
885 if (repl
&& repl
->Dereferenced
)
886 repl
->Dereferenced(repl
, &e
, &e
.repl
);
888 // no need to keep e in the global store_table for us; we have our own map
893 Rock::SwapDir::unlinkdUseful() const
895 // no entry-specific files to unlink
900 Rock::SwapDir::unlink(StoreEntry
&e
)
902 debugs(47, 5, HERE
<< e
);
904 map
->freeEntry(e
.swap_filen
);
909 Rock::SwapDir::markForUnlink(StoreEntry
&e
)
912 map
->freeEntry(e
.swap_filen
);
916 Rock::SwapDir::trackReferences(StoreEntry
&e
)
918 debugs(47, 5, HERE
<< e
);
920 repl
->Add(repl
, &e
, &e
.repl
);
924 Rock::SwapDir::ignoreReferences(StoreEntry
&e
)
926 debugs(47, 5, HERE
<< e
);
928 repl
->Remove(repl
, &e
, &e
.repl
);
932 Rock::SwapDir::statfs(StoreEntry
&e
) const
934 storeAppendPrintf(&e
, "\n");
935 storeAppendPrintf(&e
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
936 storeAppendPrintf(&e
, "Current Size: %.2f KB %.2f%%\n",
937 currentSize() / 1024.0,
938 Math::doublePercent(currentSize(), maxSize()));
941 const int limit
= map
->entryLimit();
942 storeAppendPrintf(&e
, "Maximum entries: %9d\n", limit
);
944 const int entryCount
= map
->entryCount();
945 storeAppendPrintf(&e
, "Current entries: %9d %.2f%%\n",
946 entryCount
, (100.0 * entryCount
/ limit
));
948 const unsigned int slotsFree
= !freeSlots
? 0 : freeSlots
->size();
949 if (slotsFree
<= static_cast<const unsigned int>(limit
)) {
950 const int usedSlots
= limit
- static_cast<const int>(slotsFree
);
951 storeAppendPrintf(&e
, "Used slots: %9d %.2f%%\n",
952 usedSlots
, (100.0 * usedSlots
/ limit
));
954 if (limit
< 100) { // XXX: otherwise too expensive to count
955 Ipc::ReadWriteLockStats stats
;
956 map
->updateStats(stats
);
962 storeAppendPrintf(&e
, "Pending operations: %d out of %d\n",
963 store_open_disk_fd
, Config
.max_open_disk_fds
);
965 storeAppendPrintf(&e
, "Flags:");
968 storeAppendPrintf(&e
, " SELECTED");
971 storeAppendPrintf(&e
, " READ-ONLY");
973 storeAppendPrintf(&e
, "\n");
978 Rock::SwapDir::inodeMapPath() const {
979 static String inodesPath
;
981 inodesPath
.append("_inodes");
982 return inodesPath
.termedBuf();
986 Rock::SwapDir::freeSlotsPath() const {
987 static String spacesPath
;
989 spacesPath
.append("_spaces");
990 return spacesPath
.termedBuf();
995 RunnerRegistrationEntry(rrAfterConfig
, SwapDirRr
);
998 void Rock::SwapDirRr::create(const RunnerRegistry
&)
1000 Must(mapOwners
.empty() && freeSlotsOwners
.empty());
1001 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1002 if (const Rock::SwapDir
*const sd
= dynamic_cast<Rock::SwapDir
*>(INDEXSD(i
))) {
1003 const int64_t capacity
= sd
->entryLimitAllowed();
1005 SwapDir::DirMap::Owner
*const mapOwner
=
1006 SwapDir::DirMap::Init(sd
->inodeMapPath(), capacity
);
1007 mapOwners
.push_back(mapOwner
);
1009 // TODO: somehow remove pool id and counters from PageStack?
1010 Ipc::Mem::Owner
<Ipc::Mem::PageStack
> *const freeSlotsOwner
=
1011 shm_new(Ipc::Mem::PageStack
)(sd
->freeSlotsPath(),
1013 sizeof(DbCellHeader
));
1014 freeSlotsOwners
.push_back(freeSlotsOwner
);
1016 // TODO: add method to initialize PageStack with no free pages
1018 Ipc::Mem::PageId pageId
;
1019 if (!freeSlotsOwner
->object()->pop(pageId
))
1026 Rock::SwapDirRr::~SwapDirRr()
1028 for (size_t i
= 0; i
< mapOwners
.size(); ++i
) {
1029 delete mapOwners
[i
];
1030 delete freeSlotsOwners
[i
];