2 * Copyright (C) 1996-2014 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 url
, 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 ConfigOptionVector
*vector
= dynamic_cast<ConfigOptionVector
*>(::SwapDir::getOptionTree());
410 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseSizeOption
, &SwapDir::dumpSizeOption
));
411 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseTimeOption
, &SwapDir::dumpTimeOption
));
412 vector
->options
.push_back(new ConfigOptionAdapter
<SwapDir
>(*const_cast<SwapDir
*>(this), &SwapDir::parseRateOption
, &SwapDir::dumpRateOption
));
417 Rock::SwapDir::allowOptionReconfigure(const char *const option
) const
419 return strcmp(option
, "slot-size") != 0 &&
420 ::SwapDir::allowOptionReconfigure(option
);
423 /// parses time-specific options; mimics ::SwapDir::optionObjectSizeParse()
425 Rock::SwapDir::parseTimeOption(char const *option
, const char *value
, int reconfig
)
427 // TODO: ::SwapDir or, better, Config should provide time-parsing routines,
428 // including time unit handling. Same for size and rate.
430 time_msec_t
*storedTime
;
431 if (strcmp(option
, "swap-timeout") == 0)
432 storedTime
= &fileConfig
.ioTimeout
;
439 // TODO: handle time units and detect parsing errors better
440 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
441 if (parsedValue
< 0) {
442 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
446 const time_msec_t newTime
= static_cast<time_msec_t
>(parsedValue
);
449 *storedTime
= newTime
;
450 else if (*storedTime
!= newTime
) {
451 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
452 << " cannot be changed dynamically, value left unchanged: " <<
459 /// reports time-specific options; mimics ::SwapDir::optionObjectSizeDump()
461 Rock::SwapDir::dumpTimeOption(StoreEntry
* e
) const
463 if (fileConfig
.ioTimeout
)
464 storeAppendPrintf(e
, " swap-timeout=%" PRId64
,
465 static_cast<int64_t>(fileConfig
.ioTimeout
));
468 /// parses rate-specific options; mimics ::SwapDir::optionObjectSizeParse()
470 Rock::SwapDir::parseRateOption(char const *option
, const char *value
, int isaReconfig
)
473 if (strcmp(option
, "max-swap-rate") == 0)
474 storedRate
= &fileConfig
.ioRate
;
481 // TODO: handle time units and detect parsing errors better
482 const int64_t parsedValue
= strtoll(value
, NULL
, 10);
483 if (parsedValue
< 0) {
484 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << parsedValue
);
488 const int newRate
= static_cast<int>(parsedValue
);
491 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must not be negative but is: " << newRate
);
496 *storedRate
= newRate
;
497 else if (*storedRate
!= newRate
) {
498 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
499 << " cannot be changed dynamically, value left unchanged: " <<
506 /// reports rate-specific options; mimics ::SwapDir::optionObjectSizeDump()
508 Rock::SwapDir::dumpRateOption(StoreEntry
* e
) const
510 if (fileConfig
.ioRate
>= 0)
511 storeAppendPrintf(e
, " max-swap-rate=%d", fileConfig
.ioRate
);
514 /// parses size-specific options; mimics ::SwapDir::optionObjectSizeParse()
516 Rock::SwapDir::parseSizeOption(char const *option
, const char *value
, int reconfig
)
518 uint64_t *storedSize
;
519 if (strcmp(option
, "slot-size") == 0)
520 storedSize
= &slotSize
;
527 // TODO: handle size units and detect parsing errors better
528 const uint64_t newSize
= strtoll(value
, NULL
, 10);
530 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must be positive; got: " << newSize
);
534 if (newSize
<= sizeof(DbCellHeader
)) {
535 debugs(3, DBG_CRITICAL
, "FATAL: cache_dir " << path
<< ' ' << option
<< " must exceed " << sizeof(DbCellHeader
) << "; got: " << newSize
);
540 *storedSize
= newSize
;
541 else if (*storedSize
!= newSize
) {
542 debugs(3, DBG_IMPORTANT
, "WARNING: cache_dir " << path
<< ' ' << option
543 << " cannot be changed dynamically, value left unchanged: " <<
550 /// reports size-specific options; mimics ::SwapDir::optionObjectSizeDump()
552 Rock::SwapDir::dumpSizeOption(StoreEntry
* e
) const
554 storeAppendPrintf(e
, " slot-size=%" PRId64
, slotSize
);
557 /// check the results of the configuration; only level-0 debugging works here
559 Rock::SwapDir::validateOptions()
562 fatal("Rock store requires a positive slot-size");
564 const int64_t maxSizeRoundingWaste
= 1024 * 1024; // size is configured in MB
565 const int64_t slotSizeRoundingWaste
= slotSize
;
566 const int64_t maxRoundingWaste
=
567 max(maxSizeRoundingWaste
, slotSizeRoundingWaste
);
569 // an entry consumes at least one slot; round up to reduce false warnings
570 const int64_t blockSize
= static_cast<int64_t>(slotSize
);
571 const int64_t maxObjSize
= max(blockSize
,
572 ((maxObjectSize()+blockSize
-1)/blockSize
)*blockSize
);
574 // Does the "sfileno*max-size" limit match configured db capacity?
575 const double entriesMayOccupy
= entryLimitAbsolute()*static_cast<double>(maxObjSize
);
576 if (entriesMayOccupy
+ maxRoundingWaste
< maxSize()) {
577 const int64_t diskWasteSize
= maxSize() - static_cast<int64_t>(entriesMayOccupy
);
578 debugs(47, DBG_CRITICAL
, "WARNING: Rock cache_dir " << path
<< " wastes disk space due to entry limits:" <<
579 "\n\tconfigured db capacity: " << maxSize() << " bytes" <<
580 "\n\tconfigured db slot size: " << slotSize
<< " bytes" <<
581 "\n\tconfigured maximum entry size: " << maxObjectSize() << " bytes" <<
582 "\n\tmaximum number of cache_dir entries supported by Squid: " << entryLimitAbsolute() <<
583 "\n\tdisk space all entries may use: " << entriesMayOccupy
<< " bytes" <<
584 "\n\tdisk space wasted: " << diskWasteSize
<< " bytes");
587 // Does the "absolute slot count" limit match configured db capacity?
588 const double slotsMayOccupy
= slotLimitAbsolute()*static_cast<double>(slotSize
);
589 if (slotsMayOccupy
+ maxRoundingWaste
< maxSize()) {
590 const int64_t diskWasteSize
= maxSize() - static_cast<int64_t>(entriesMayOccupy
);
591 debugs(47, DBG_CRITICAL
, "WARNING: Rock cache_dir " << path
<< " wastes disk space due to slot limits:" <<
592 "\n\tconfigured db capacity: " << maxSize() << " bytes" <<
593 "\n\tconfigured db slot size: " << slotSize
<< " bytes" <<
594 "\n\tmaximum number of rock cache_dir slots supported by Squid: " << slotLimitAbsolute() <<
595 "\n\tdisk space all slots may use: " << slotsMayOccupy
<< " bytes" <<
596 "\n\tdisk space wasted: " << diskWasteSize
<< " bytes");
601 Rock::SwapDir::rebuild()
603 //++StoreController::store_dirs_rebuilding; // see Rock::SwapDir::init()
604 AsyncJob::Start(new Rebuild(this));
608 Rock::SwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
610 if (!::SwapDir::canStore(e
, sizeof(DbCellHeader
)+diskSpaceNeeded
, load
))
613 if (!theFile
|| !theFile
->canWrite())
619 // Do not start I/O transaction if there are less than 10% free pages left.
620 // TODO: reserve page instead
621 if (needsDiskStrand() &&
622 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
623 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
634 StoreIOState::Pointer
635 Rock::SwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
637 if (!theFile
|| theFile
->error()) {
638 debugs(47,4, HERE
<< theFile
);
643 Ipc::StoreMapAnchor
*const slot
=
644 map
->openForWriting(reinterpret_cast<const cache_key
*>(e
.key
), filen
);
646 debugs(47, 5, HERE
<< "map->add failed");
653 // XXX: We rely on our caller, storeSwapOutStart(), to set e.fileno.
654 // If that does not happen, the entry will not decrement the read level!
656 Rock::SwapDir::Pointer
self(this);
657 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
659 sio
->swap_dirn
= index
;
660 sio
->swap_filen
= filen
;
661 sio
->writeableAnchor_
= slot
;
663 debugs(47,5, HERE
<< "dir " << index
<< " created new filen " <<
664 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
665 sio
->swap_filen
<< std::dec
<< " starting at " <<
666 diskOffset(sio
->swap_filen
));
675 Rock::SwapDir::diskOffset(const SlotId sid
) const
678 return HeaderSize
+ slotSize
*sid
;
682 Rock::SwapDir::diskOffset(Ipc::Mem::PageId
&pageId
) const
685 return diskOffset(pageId
.number
- 1);
689 Rock::SwapDir::diskOffsetLimit() const
692 return diskOffset(map
->sliceLimit());
696 Rock::SwapDir::useFreeSlot(Ipc::Mem::PageId
&pageId
)
698 if (freeSlots
->pop(pageId
)) {
699 debugs(47, 5, "got a previously free slot: " << pageId
);
703 // catch free slots delivered to noteFreeMapSlice()
704 assert(!waitingForPage
);
705 waitingForPage
= &pageId
;
706 if (map
->purgeOne()) {
707 assert(!waitingForPage
); // noteFreeMapSlice() should have cleared it
708 assert(pageId
.set());
709 debugs(47, 5, "got a previously busy slot: " << pageId
);
712 assert(waitingForPage
== &pageId
);
713 waitingForPage
= NULL
;
715 debugs(47, 3, "cannot get a slot; entries: " << map
->entryCount());
720 Rock::SwapDir::validSlotId(const SlotId slotId
) const
722 return 0 <= slotId
&& slotId
< slotLimitActual();
726 Rock::SwapDir::noteFreeMapSlice(const Ipc::StoreMapSliceId sliceId
)
728 Ipc::Mem::PageId pageId
;
729 pageId
.pool
= index
+1;
730 pageId
.number
= sliceId
+1;
731 if (waitingForPage
) {
732 *waitingForPage
= pageId
;
733 waitingForPage
= NULL
;
735 freeSlots
->push(pageId
);
739 // tries to open an old entry with swap_filen for reading
740 StoreIOState::Pointer
741 Rock::SwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
*cbFile
, StoreIOState::STIOCB
*cbIo
, void *data
)
743 if (!theFile
|| theFile
->error()) {
744 debugs(47,4, HERE
<< theFile
);
748 if (e
.swap_filen
< 0) {
749 debugs(47,4, HERE
<< e
);
753 // Do not start I/O transaction if there are less than 10% free pages left.
754 // TODO: reserve page instead
755 if (needsDiskStrand() &&
756 Ipc::Mem::PageLevel(Ipc::Mem::PageId::ioPage
) >= 0.9 * Ipc::Mem::PageLimit(Ipc::Mem::PageId::ioPage
)) {
757 debugs(47, 5, HERE
<< "too few shared pages for IPC I/O left");
761 // The are two ways an entry can get swap_filen: our get() locked it for
762 // reading or our storeSwapOutStart() locked it for writing. Peeking at our
763 // locked entry is safe, but no support for reading the entry we swap out.
764 const Ipc::StoreMapAnchor
*slot
= map
->peekAtReader(e
.swap_filen
);
766 return NULL
; // we were writing afterall
768 Rock::SwapDir::Pointer
self(this);
769 IoState
*sio
= new IoState(self
, &e
, cbFile
, cbIo
, data
);
771 sio
->swap_dirn
= index
;
772 sio
->swap_filen
= e
.swap_filen
;
773 sio
->readableAnchor_
= slot
;
776 debugs(47,5, HERE
<< "dir " << index
<< " has old filen: " <<
777 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) <<
780 assert(slot
->sameKey(static_cast<const cache_key
*>(e
.key
)));
781 // For collapsed disk hits: e.swap_file_sz and slot->basics.swap_file_sz
782 // may still be zero and basics.swap_file_sz may grow.
783 assert(slot
->basics
.swap_file_sz
>= e
.swap_file_sz
);
789 Rock::SwapDir::ioCompletedNotification()
792 fatalf("Rock cache_dir failed to initialize db file: %s", filePath
);
794 if (theFile
->error())
795 fatalf("Rock cache_dir at %s failed to open db file: %s", filePath
,
798 debugs(47, 2, "Rock cache_dir[" << index
<< "] limits: " <<
799 std::setw(12) << maxSize() << " disk bytes, " <<
800 std::setw(7) << map
->entryLimit() << " entries, and " <<
801 std::setw(7) << map
->sliceLimit() << " slots");
807 Rock::SwapDir::closeCompleted()
813 Rock::SwapDir::readCompleted(const char *buf
, int rlen
, int errflag
, RefCount
< ::ReadRequest
> r
)
815 ReadRequest
*request
= dynamic_cast<Rock::ReadRequest
*>(r
.getRaw());
817 IoState::Pointer sio
= request
->sio
;
819 if (errflag
== DISK_OK
&& rlen
> 0)
820 sio
->offset_
+= rlen
;
822 sio
->callReaderBack(r
->buf
, rlen
);
826 Rock::SwapDir::writeCompleted(int errflag
, size_t rlen
, RefCount
< ::WriteRequest
> r
)
828 Rock::WriteRequest
*request
= dynamic_cast<Rock::WriteRequest
*>(r
.getRaw());
830 assert(request
->sio
!= NULL
);
831 IoState
&sio
= *request
->sio
;
833 // quit if somebody called IoState::close() while we were waiting
834 if (!sio
.stillWaiting()) {
835 debugs(79, 3, "ignoring closed entry " << sio
.swap_filen
);
836 noteFreeMapSlice(request
->sidNext
);
840 // TODO: Fail if disk dropped one of the previous write requests.
842 if (errflag
== DISK_OK
) {
843 // do not increment sio.offset_ because we do it in sio->write()
845 // finalize the shared slice info after writing slice contents to disk
846 Ipc::StoreMap::Slice
&slice
=
847 map
->writeableSlice(sio
.swap_filen
, request
->sidCurrent
);
848 slice
.size
= request
->len
- sizeof(DbCellHeader
);
849 slice
.next
= request
->sidNext
;
853 assert(sio
.writeableAnchor_
);
854 sio
.e
->swap_file_sz
= sio
.writeableAnchor_
->basics
.swap_file_sz
=
857 // close, the entry gets the read lock
858 map
->closeForWriting(sio
.swap_filen
, true);
859 sio
.writeableAnchor_
= NULL
;
860 sio
.finishedWriting(errflag
);
863 noteFreeMapSlice(request
->sidNext
);
866 sio
.finishedWriting(errflag
);
867 // and hope that Core will call disconnect() to close the map entry
870 CollapsedForwarding::Broadcast(*sio
.e
);
874 Rock::SwapDir::writeError(StoreEntry
&e
)
876 // Do not abortWriting here. The entry should keep the write lock
877 // instead of losing association with the store and confusing core.
878 map
->freeEntry(e
.swap_filen
); // will mark as unusable, just in case
880 Store::Root().transientsAbandon(e
);
882 // All callers must also call IoState callback, to propagate the error.
886 Rock::SwapDir::full() const
888 return freeSlots
!= NULL
&& !freeSlots
->size();
891 // storeSwapOutFileClosed calls this nethod on DISK_NO_SPACE_LEFT,
892 // but it should not happen for us
894 Rock::SwapDir::diskFull()
896 debugs(20, DBG_IMPORTANT
, "BUG: No space left with rock cache_dir: " <<
900 /// purge while full(); it should be sufficient to purge just one
902 Rock::SwapDir::maintain()
904 // The Store calls this to free some db space, but there is nothing wrong
905 // with a full() db, except when db has to shrink after reconfigure, and
906 // we do not support shrinking yet (it would have to purge specific slots).
907 // TODO: Disable maintain() requests when they are pointless.
911 Rock::SwapDir::reference(StoreEntry
&e
)
913 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
914 if (repl
&& repl
->Referenced
)
915 repl
->Referenced(repl
, &e
, &e
.repl
);
919 Rock::SwapDir::dereference(StoreEntry
&e
, bool)
921 debugs(47, 5, HERE
<< &e
<< ' ' << e
.swap_dirn
<< ' ' << e
.swap_filen
);
922 if (repl
&& repl
->Dereferenced
)
923 repl
->Dereferenced(repl
, &e
, &e
.repl
);
925 // no need to keep e in the global store_table for us; we have our own map
930 Rock::SwapDir::unlinkdUseful() const
932 // no entry-specific files to unlink
937 Rock::SwapDir::unlink(StoreEntry
&e
)
939 debugs(47, 5, HERE
<< e
);
941 map
->freeEntry(e
.swap_filen
);
946 Rock::SwapDir::markForUnlink(StoreEntry
&e
)
949 map
->freeEntry(e
.swap_filen
);
953 Rock::SwapDir::trackReferences(StoreEntry
&e
)
955 debugs(47, 5, HERE
<< e
);
957 repl
->Add(repl
, &e
, &e
.repl
);
961 Rock::SwapDir::ignoreReferences(StoreEntry
&e
)
963 debugs(47, 5, HERE
<< e
);
965 repl
->Remove(repl
, &e
, &e
.repl
);
969 Rock::SwapDir::statfs(StoreEntry
&e
) const
971 storeAppendPrintf(&e
, "\n");
972 storeAppendPrintf(&e
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
973 storeAppendPrintf(&e
, "Current Size: %.2f KB %.2f%%\n",
974 currentSize() / 1024.0,
975 Math::doublePercent(currentSize(), maxSize()));
977 const int entryLimit
= entryLimitActual();
978 const int slotLimit
= slotLimitActual();
979 storeAppendPrintf(&e
, "Maximum entries: %9d\n", entryLimit
);
980 if (map
&& entryLimit
> 0) {
981 const int entryCount
= map
->entryCount();
982 storeAppendPrintf(&e
, "Current entries: %9d %.2f%%\n",
983 entryCount
, (100.0 * entryCount
/ entryLimit
));
986 storeAppendPrintf(&e
, "Maximum slots: %9d\n", slotLimit
);
987 if (map
&& slotLimit
> 0) {
988 const unsigned int slotsFree
= !freeSlots
? 0 : freeSlots
->size();
989 if (slotsFree
<= static_cast<const unsigned int>(slotLimit
)) {
990 const int usedSlots
= slotLimit
- static_cast<const int>(slotsFree
);
991 storeAppendPrintf(&e
, "Used slots: %9d %.2f%%\n",
992 usedSlots
, (100.0 * usedSlots
/ slotLimit
));
994 if (slotLimit
< 100) { // XXX: otherwise too expensive to count
995 Ipc::ReadWriteLockStats stats
;
996 map
->updateStats(stats
);
1001 storeAppendPrintf(&e
, "Pending operations: %d out of %d\n",
1002 store_open_disk_fd
, Config
.max_open_disk_fds
);
1004 storeAppendPrintf(&e
, "Flags:");
1007 storeAppendPrintf(&e
, " SELECTED");
1009 if (flags
.read_only
)
1010 storeAppendPrintf(&e
, " READ-ONLY");
1012 storeAppendPrintf(&e
, "\n");
1017 Rock::SwapDir::inodeMapPath() const
1019 return Ipc::Mem::Segment::Name(SBuf(path
), "map");
1023 Rock::SwapDir::freeSlotsPath() const
1025 static String spacesPath
;
1027 spacesPath
.append("_spaces");
1028 return spacesPath
.termedBuf();
1033 RunnerRegistrationEntry(SwapDirRr
);
1036 void Rock::SwapDirRr::create()
1038 Must(mapOwners
.empty() && freeSlotsOwners
.empty());
1039 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1040 if (const Rock::SwapDir
*const sd
= dynamic_cast<Rock::SwapDir
*>(INDEXSD(i
))) {
1041 const int64_t capacity
= sd
->slotLimitActual();
1043 SwapDir::DirMap::Owner
*const mapOwner
=
1044 SwapDir::DirMap::Init(sd
->inodeMapPath(), capacity
);
1045 mapOwners
.push_back(mapOwner
);
1047 // TODO: somehow remove pool id and counters from PageStack?
1048 Ipc::Mem::Owner
<Ipc::Mem::PageStack
> *const freeSlotsOwner
=
1049 shm_new(Ipc::Mem::PageStack
)(sd
->freeSlotsPath(),
1051 freeSlotsOwners
.push_back(freeSlotsOwner
);
1053 // TODO: add method to initialize PageStack with no free pages
1055 Ipc::Mem::PageId pageId
;
1056 if (!freeSlotsOwner
->object()->pop(pageId
))
1063 Rock::SwapDirRr::~SwapDirRr()
1065 for (size_t i
= 0; i
< mapOwners
.size(); ++i
) {
1066 delete mapOwners
[i
];
1067 delete freeSlotsOwners
[i
];