2 * Copyright (C) 1996-2017 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 */
11 #define CLEAN_BUF_SZ 16384
15 #include "ConfigOption.h"
16 #include "DiskIO/DiskIOModule.h"
17 #include "DiskIO/DiskIOStrategy.h"
23 #include "RebuildState.h"
24 #include "SquidConfig.h"
25 #include "SquidMath.h"
26 #include "SquidTime.h"
27 #include "StatCounters.h"
28 #include "store_key_md5.h"
29 #include "StoreSearchUFS.h"
30 #include "StoreSwapLogData.h"
32 #include "UFSSwapDir.h"
41 int Fs::Ufs::UFSSwapDir::NumberOfUFSDirs
= 0;
42 int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping
= NULL
;
44 class UFSCleanLog
: public SwapDir::CleanLog
48 UFSCleanLog(SwapDir
*);
49 /** Get the next entry that is a candidate for clean log writing
51 virtual const StoreEntry
*nextEntry();
52 /** "write" an entry to the clean log file.
54 virtual void write(StoreEntry
const &);
61 RemovalPolicyWalker
*walker
;
65 UFSCleanLog::UFSCleanLog(SwapDir
*aSwapDir
) :
66 cur(NULL
), newLog(NULL
), cln(NULL
), outbuf(NULL
),
67 outbuf_offset(0), fd(-1),walker(NULL
), sd(aSwapDir
)
71 UFSCleanLog::nextEntry()
73 const StoreEntry
*entry
= NULL
;
76 entry
= walker
->Next(walker
);
82 UFSCleanLog::write(StoreEntry
const &e
)
85 static size_t ss
= sizeof(StoreSwapLogData
);
86 s
.op
= (char) SWAP_LOG_ADD
;
87 s
.swap_filen
= e
.swap_filen
;
88 s
.timestamp
= e
.timestamp
;
89 s
.lastref
= e
.lastref
;
90 s
.expires
= e
.expires
;
91 s
.lastmod
= e
.lastModified();
92 s
.swap_file_sz
= e
.swap_file_sz
;
93 s
.refcount
= e
.refcount
;
95 memcpy(&s
.key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
97 memcpy(outbuf
+ outbuf_offset
, &s
, ss
);
101 if (outbuf_offset
+ ss
>= CLEAN_BUF_SZ
) {
102 if (FD_WRITE_METHOD(fd
, outbuf
, outbuf_offset
) < 0) {
104 /* XXX This error handling should probably move up to the caller */
105 debugs(50, DBG_CRITICAL
, MYNAME
<< newLog
<< ": write: " << xstrerr(xerrno
));
106 debugs(50, DBG_CRITICAL
, MYNAME
<< "Current swap logfile not replaced.");
120 Fs::Ufs::UFSSwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
122 if (!SwapDir::canStore(e
, diskSpaceNeeded
, load
))
133 FreeObject(void *address
)
135 StoreSwapLogData
*anObject
= static_cast <StoreSwapLogData
*>(address
);
140 rev_int_sort(const void *A
, const void *B
)
142 const int *i1
= (const int *)A
;
143 const int *i2
= (const int *)B
;
148 Fs::Ufs::UFSSwapDir::parseSizeL1L2()
150 int i
= GetInteger();
152 fatal("UFSSwapDir::parseSizeL1L2: invalid size value");
154 const uint64_t size
= static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
156 /* just reconfigure it */
158 if (size
== maxSize())
159 debugs(3, 2, "Cache dir '" << path
<< "' size remains unchanged at " << i
<< " MB");
161 debugs(3, DBG_IMPORTANT
, "Cache dir '" << path
<< "' size changed to " << i
<< " MB");
169 fatal("UFSSwapDir::parseSizeL1L2: invalid level 1 directories value");
174 fatal("UFSSwapDir::parseSizeL1L2: invalid level 2 directories value");
178 Fs::Ufs::UFSSwapDir::reconfigure()
185 Fs::Ufs::UFSSwapDir::parse (int anIndex
, char *aPath
)
188 path
= xstrdup(aPath
);
192 /* Initialise replacement policy stuff */
193 repl
= createRemovalPolicy(Config
.replPolicy
);
199 Fs::Ufs::UFSSwapDir::changeIO(DiskIOModule
*module
)
201 DiskIOStrategy
*anIO
= module
->createStrategy();
203 ioType
= xstrdup(module
->type());
207 /* Change the IO Options */
209 if (currentIOOptions
&& currentIOOptions
->options
.size() > 2) {
210 delete currentIOOptions
->options
.back();
211 currentIOOptions
->options
.pop_back();
214 /* TODO: factor out these 4 lines */
215 ConfigOption
*ioOptions
= IO
->io
->getOptionTree();
217 if (currentIOOptions
&& ioOptions
)
218 currentIOOptions
->options
.push_back(ioOptions
);
222 Fs::Ufs::UFSSwapDir::optionIOParse(char const *option
, const char *value
, int isaReconfig
)
224 if (strcmp(option
, "IOEngine") != 0)
228 /* silently ignore this */
234 DiskIOModule
*module
= DiskIOModule::Find(value
);
245 Fs::Ufs::UFSSwapDir::optionIODump(StoreEntry
* e
) const
247 storeAppendPrintf(e
, " IOEngine=%s", ioType
);
251 Fs::Ufs::UFSSwapDir::getOptionTree() const
253 ConfigOption
*parentResult
= SwapDir::getOptionTree();
255 if (currentIOOptions
== NULL
)
256 currentIOOptions
= new ConfigOptionVector();
258 currentIOOptions
->options
.push_back(parentResult
);
260 currentIOOptions
->options
.push_back(new ConfigOptionAdapter
<UFSSwapDir
>(*const_cast<UFSSwapDir
*>(this), &UFSSwapDir::optionIOParse
, &UFSSwapDir::optionIODump
));
262 if (ConfigOption
*ioOptions
= IO
->io
->getOptionTree())
263 currentIOOptions
->options
.push_back(ioOptions
);
265 ConfigOption
* result
= currentIOOptions
;
267 currentIOOptions
= NULL
;
273 Fs::Ufs::UFSSwapDir::init()
275 debugs(47, 3, HERE
<< "Initialising UFS SwapDir engine.");
276 /* Parsing must be finished by now - force to NULL, don't delete */
277 currentIOOptions
= NULL
;
278 static int started_clean_event
= 0;
279 static const char *errmsg
=
280 "\tFailed to verify one of the swap directories, Check cache.log\n"
281 "\tfor details. Run 'squid -z' to create swap directories\n"
282 "\tif needed, or if running Squid for the first time.";
285 if (verifyCacheDirs())
292 if (!started_clean_event
) {
293 eventAdd("UFS storeDirClean", CleanEvent
, NULL
, 15.0, 1);
294 started_clean_event
= 1;
297 (void) fsBlockSize(path
, &fs
.blksize
);
301 Fs::Ufs::UFSSwapDir::create()
303 debugs(47, 3, "Creating swap space in " << path
);
304 createDirectory(path
, 0);
308 Fs::Ufs::UFSSwapDir::UFSSwapDir(char const *aType
, const char *anIOType
) :
317 currentIOOptions(new ConfigOptionVector()),
318 ioType(xstrdup(anIOType
)),
323 /* modulename is only set to disk modules that are built, by configure,
324 * so the Find call should never return NULL here.
326 IO
= new Fs::Ufs::UFSStrategy(DiskIOModule::Find(anIOType
)->createStrategy());
329 Fs::Ufs::UFSSwapDir::~UFSSwapDir()
331 if (swaplog_fd
> -1) {
332 file_close(swaplog_fd
);
338 delete currentIOOptions
;
342 Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry
&e
) const
344 debugs(47, DBG_CRITICAL
, HERE
<< "FILENO "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
345 debugs(47, DBG_CRITICAL
, HERE
<< "PATH " << fullPath(e
.swap_filen
, NULL
) );
350 Fs::Ufs::UFSSwapDir::doubleCheck(StoreEntry
& e
)
355 if (::stat(fullPath(e
.swap_filen
, NULL
), &sb
) < 0) {
356 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Missing swap file");
361 if ((off_t
)e
.swap_file_sz
!= sb
.st_size
) {
362 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Size Mismatch. Entry size: "
363 << e
.swap_file_sz
<< ", file size: " << sb
.st_size
);
372 Fs::Ufs::UFSSwapDir::statfs(StoreEntry
& sentry
) const
379 storeAppendPrintf(&sentry
, "First level subdirectories: %d\n", l1
);
380 storeAppendPrintf(&sentry
, "Second level subdirectories: %d\n", l2
);
381 storeAppendPrintf(&sentry
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
382 storeAppendPrintf(&sentry
, "Current Size: %.2f KB\n", currentSize() / 1024.0);
383 storeAppendPrintf(&sentry
, "Percent Used: %0.2f%%\n",
384 Math::doublePercent(currentSize(), maxSize()));
385 storeAppendPrintf(&sentry
, "Filemap bits in use: %d of %d (%d%%)\n",
386 map
->numFilesInMap(), map
->capacity(),
387 Math::intPercent(map
->numFilesInMap(), map
->capacity()));
388 x
= fsStats(path
, &totl_kb
, &free_kb
, &totl_in
, &free_in
);
391 storeAppendPrintf(&sentry
, "Filesystem Space in use: %d/%d KB (%d%%)\n",
394 Math::intPercent(totl_kb
- free_kb
, totl_kb
));
395 storeAppendPrintf(&sentry
, "Filesystem Inodes in use: %d/%d (%d%%)\n",
398 Math::intPercent(totl_in
- free_in
, totl_in
));
401 storeAppendPrintf(&sentry
, "Flags:");
404 storeAppendPrintf(&sentry
, " SELECTED");
407 storeAppendPrintf(&sentry
, " READ-ONLY");
409 storeAppendPrintf(&sentry
, "\n");
415 Fs::Ufs::UFSSwapDir::maintain()
417 /* TODO: possible options for improvement;
419 * Note that too much aggression here is not good. It means that disk
420 * controller is getting a long queue of removals to act on, along
421 * with its regular I/O queue, and that client traffic is 'paused'
422 * and growing the network I/O queue as well while the scan happens.
423 * Possibly bad knock-on effects as Squid catches up on all that.
425 * Bug 2448 may have been a sign of what can wrong. At the least it
426 * provides a test case for aggression effects in overflow conditions.
428 * - base removal limit on space saved, instead of count ?
430 * - base removal rate on a traffic speed counter ?
431 * as the purge took up more time out of the second it would grow to
432 * a graceful full pause
434 * - pass out a value to cause another event to be scheduled immediately
435 * instead of waiting a whole second more ?
436 * knock on; schedule less if all caches are under low-water
438 * - admin configurable removal rate or count ?
439 * the current numbers are arbitrary, config helps with experimental
440 * trials and future-proofing the install base.
441 * we also have this indirectly by shifting the relative positions
442 * of low-, high- water and the total capacity limit.
445 // minSize() is swap_low_watermark in bytes
446 const uint64_t lowWaterSz
= minSize();
448 if (currentSize() < lowWaterSz
) {
449 debugs(47, 5, "space still available in " << path
);
453 /* We can't delete objects while rebuilding swap */
454 /* XXX each store should start maintaining as it comes online. */
455 if (StoreController::store_dirs_rebuilding
) {
456 // suppress the warnings, except once each minute
457 static int64_t lastWarn
= 0;
459 if (lastWarn
+60 < squid_curtime
) {
460 lastWarn
= squid_curtime
;
461 warnLevel
= DBG_IMPORTANT
;
463 debugs(47, warnLevel
, StoreController::store_dirs_rebuilding
<< " cache_dir still rebuilding. Skip GC for " << path
);
467 // maxSize() is cache_dir total size in bytes
468 const uint64_t highWaterSz
= ((maxSize() * Config
.Swap
.highWaterMark
) / 100);
470 // f is percentage of 'gap' filled between low- and high-water.
471 // Used to reduced purge rate when between water markers, and
472 // to multiply it more agressively the further above high-water
473 // it reaches. But in a graceful linear growth curve.
475 if (highWaterSz
> lowWaterSz
) {
476 // might be equal. n/0 is bad.
477 f
= (double) (currentSize() - lowWaterSz
) / (highWaterSz
- lowWaterSz
);
480 // how deep to look for a single object that can be removed
481 int max_scan
= (int) (f
* 400.0 + 100.0);
483 // try to purge only this many objects this cycle.
484 int max_remove
= (int) (f
* 300.0 + 20.0);
487 * This is kinda cheap, but so we need this priority hack?
489 debugs(47, 3, "f=" << f
<< ", max_scan=" << max_scan
<< ", max_remove=" << max_remove
);
491 RemovalPurgeWalker
*walker
= repl
->PurgeInit(repl
, max_scan
);
494 // only purge while above low-water
495 while (currentSize() >= lowWaterSz
) {
497 // stop if we reached max removals for this cycle,
498 // Bug 2448 may be from this not clearing enough,
499 // but it predates the current algorithm so not sure
500 if (removed
>= max_remove
)
503 StoreEntry
*e
= walker
->Next(walker
);
505 // stop if all objects are locked / in-use,
506 // or the cache is empty
508 break; /* no more objects */
515 walker
->Done(walker
);
516 debugs(47, (removed
? 2 : 3), path
<<
517 " removed " << removed
<< "/" << max_remove
<< " f=" <<
518 std::setprecision(4) << f
<< " max_scan=" << max_scan
);
520 // what if cache is still over the high watermark ?
521 // Store::Maintain() schedules another purge in 1 second.
525 Fs::Ufs::UFSSwapDir::reference(StoreEntry
&e
)
527 debugs(47, 3, HERE
<< "referencing " << &e
<< " " <<
528 e
.swap_dirn
<< "/" << e
.swap_filen
);
530 if (repl
->Referenced
)
531 repl
->Referenced(repl
, &e
, &e
.repl
);
535 Fs::Ufs::UFSSwapDir::dereference(StoreEntry
& e
)
537 debugs(47, 3, HERE
<< "dereferencing " << &e
<< " " <<
538 e
.swap_dirn
<< "/" << e
.swap_filen
);
540 if (repl
->Dereferenced
)
541 repl
->Dereferenced(repl
, &e
, &e
.repl
);
543 return true; // keep e in the global store_table
546 StoreIOState::Pointer
547 Fs::Ufs::UFSSwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
549 return IO
->create (this, &e
, file_callback
, aCallback
, callback_data
);
552 StoreIOState::Pointer
553 Fs::Ufs::UFSSwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
555 return IO
->open (this, &e
, file_callback
, aCallback
, callback_data
);
559 Fs::Ufs::UFSSwapDir::mapBitTest(sfileno filn
)
561 return map
->testBit(filn
);
565 Fs::Ufs::UFSSwapDir::mapBitSet(sfileno filn
)
571 Fs::Ufs::UFSSwapDir::mapBitReset(sfileno filn
)
574 * We have to test the bit before calling clearBit as
575 * it doesn't do bounds checking and blindly assumes
576 * filn is a valid file number, but it might not be because
577 * the map is dynamic in size. Also clearing an already clear
578 * bit puts the map counter of-of-whack.
581 if (map
->testBit(filn
))
586 Fs::Ufs::UFSSwapDir::mapBitAllocate()
589 fn
= map
->allocate(suggest
);
596 Fs::Ufs::UFSSwapDir::swapSubDir(int subdirn
)const
598 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
599 assert(0 <= subdirn
&& subdirn
< l1
);
600 snprintf(fullfilename
, MAXPATHLEN
, "%s/%02X", path
, subdirn
);
605 Fs::Ufs::UFSSwapDir::createDirectory(const char *aPath
, int should_exist
)
612 if (0 == ::stat(aPath
, &st
)) {
613 if (S_ISDIR(st
.st_mode
)) {
614 debugs(47, (should_exist
? 3 : DBG_IMPORTANT
), aPath
<< " exists");
616 fatalf("Swap directory %s is not a directory.", aPath
);
618 } else if (0 == mkdir(aPath
, 0755)) {
619 debugs(47, (should_exist
? DBG_IMPORTANT
: 3), aPath
<< " created");
623 fatalf("Failed to make swap directory %s: %s", aPath
, xstrerr(xerrno
));
630 Fs::Ufs::UFSSwapDir::pathIsDirectory(const char *aPath
)const
635 if (::stat(aPath
, &sb
) < 0) {
637 debugs(47, DBG_CRITICAL
, "ERROR: " << aPath
<< ": " << xstrerr(xerrno
));
641 if (S_ISDIR(sb
.st_mode
) == 0) {
642 debugs(47, DBG_CRITICAL
, "WARNING: " << aPath
<< " is not a directory");
650 Fs::Ufs::UFSSwapDir::verifyCacheDirs()
652 if (!pathIsDirectory(path
))
655 for (int j
= 0; j
< l1
; ++j
) {
656 char const *aPath
= swapSubDir(j
);
658 if (!pathIsDirectory(aPath
))
666 Fs::Ufs::UFSSwapDir::createSwapSubDirs()
668 LOCAL_ARRAY(char, name
, MAXPATHLEN
);
670 for (int i
= 0; i
< l1
; ++i
) {
671 snprintf(name
, MAXPATHLEN
, "%s/%02X", path
, i
);
675 if (createDirectory(name
, 0))
680 debugs(47, DBG_IMPORTANT
, "Making directories in " << name
);
682 for (int k
= 0; k
< l2
; ++k
) {
683 snprintf(name
, MAXPATHLEN
, "%s/%02X/%02X", path
, i
, k
);
684 createDirectory(name
, should_exist
);
690 Fs::Ufs::UFSSwapDir::logFile(char const *ext
) const
692 LOCAL_ARRAY(char, lpath
, MAXPATHLEN
);
693 LOCAL_ARRAY(char, pathtmp
, MAXPATHLEN
);
694 LOCAL_ARRAY(char, digit
, 32);
697 if (Config
.Log
.swap
) {
698 xstrncpy(pathtmp
, path
, MAXPATHLEN
- 64);
701 while ((pathtmp2
= strchr(pathtmp2
, '/')) != NULL
)
704 while (strlen(pathtmp
) && pathtmp
[strlen(pathtmp
) - 1] == '.')
705 pathtmp
[strlen(pathtmp
) - 1] = '\0';
707 for (pathtmp2
= pathtmp
; *pathtmp2
== '.'; ++pathtmp2
);
708 snprintf(lpath
, MAXPATHLEN
- 64, Config
.Log
.swap
, pathtmp2
);
710 if (strncmp(lpath
, Config
.Log
.swap
, MAXPATHLEN
- 64) == 0) {
712 snprintf(digit
, 32, "%02d", index
);
713 strncat(lpath
, digit
, 3);
716 xstrncpy(lpath
, path
, MAXPATHLEN
- 64);
717 strcat(lpath
, "/swap.state");
721 strncat(lpath
, ext
, 16);
727 Fs::Ufs::UFSSwapDir::openLog()
729 assert(NumberOfUFSDirs
|| !UFSDirToGlobalDirMapping
);
731 assert(NumberOfUFSDirs
<= Config
.cacheSwap
.n_configured
);
733 if (rebuilding_
) { // we did not close the temporary log used for rebuilding
734 assert(swaplog_fd
>= 0);
740 swaplog_fd
= file_open(logPath
, O_WRONLY
| O_CREAT
| O_BINARY
);
742 if (swaplog_fd
< 0) {
744 debugs(50, DBG_IMPORTANT
, "ERROR opening swap log " << logPath
<< ": " << xstrerr(xerrno
));
745 fatal("UFSSwapDir::openLog: Failed to open swap log.");
748 debugs(50, 3, HERE
<< "Cache Dir #" << index
<< " log opened on FD " << swaplog_fd
);
752 Fs::Ufs::UFSSwapDir::closeLog()
754 if (swaplog_fd
< 0) /* not open */
758 assert(NumberOfUFSDirs
>= 0);
759 if (!NumberOfUFSDirs
)
760 safe_free(UFSDirToGlobalDirMapping
);
762 if (rebuilding_
) // we cannot close the temporary log used for rebuilding
765 file_close(swaplog_fd
);
767 debugs(47, 3, "Cache Dir #" << index
<< " log closed on FD " << swaplog_fd
);
773 Fs::Ufs::UFSSwapDir::validL1(int anInt
) const
779 Fs::Ufs::UFSSwapDir::validL2(int anInt
) const
785 Fs::Ufs::UFSSwapDir::addDiskRestore(const cache_key
* key
,
787 uint64_t swap_file_sz
,
796 StoreEntry
*e
= NULL
;
797 debugs(47, 5, HERE
<< storeKeyText(key
) <<
798 ", fileno="<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << file_number
);
799 /* if you call this you'd better be sure file_number is not
801 e
= new StoreEntry();
802 e
->store_status
= STORE_OK
;
803 e
->setMemStatus(NOT_IN_MEMORY
);
804 e
->swap_status
= SWAPOUT_DONE
;
805 e
->swap_filen
= file_number
;
806 e
->swap_dirn
= index
;
807 e
->swap_file_sz
= swap_file_sz
;
808 e
->lastref
= lastref
;
809 e
->timestamp
= timestamp
;
810 e
->expires
= expires
;
811 e
->lastModified(lastmod
);
812 e
->refcount
= refcount
;
814 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
815 EBIT_CLR(e
->flags
, KEY_PRIVATE
);
816 e
->ping_status
= PING_NONE
;
817 EBIT_CLR(e
->flags
, ENTRY_VALIDATED
);
818 mapBitSet(e
->swap_filen
);
819 cur_size
+= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
821 e
->hashInsert(key
); /* do it after we clear KEY_PRIVATE */
827 Fs::Ufs::UFSSwapDir::undoAddDiskRestore(StoreEntry
*e
)
829 debugs(47, 5, HERE
<< *e
);
830 replacementRemove(e
); // checks swap_dirn so do it before we invalidate it
831 // Do not unlink the file as it might be used by a subsequent entry.
832 mapBitReset(e
->swap_filen
);
835 cur_size
-= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
840 Fs::Ufs::UFSSwapDir::rebuild()
842 ++StoreController::store_dirs_rebuilding
;
843 eventAdd("storeRebuild", Fs::Ufs::RebuildState::RebuildStep
, new Fs::Ufs::RebuildState(this), 0.0, 1);
847 Fs::Ufs::UFSSwapDir::closeTmpSwapLog()
852 char *swaplog_path
= xstrdup(logFile(NULL
)); // where the swaplog should be
853 char *tmp_path
= xstrdup(logFile(".new")); // the temporary file we have generated
855 file_close(swaplog_fd
);
857 if (xrename(tmp_path
, swaplog_path
) < 0) {
858 fatalf("Failed to rename log file %s to %s", tmp_path
, swaplog_path
);
861 fd
= file_open(swaplog_path
, O_WRONLY
| O_CREAT
| O_BINARY
);
865 debugs(50, DBG_IMPORTANT
, "ERROR: " << swaplog_path
<< ": " << xstrerr(xerrno
));
866 fatalf("Failed to open swap log %s", swaplog_path
);
872 debugs(47, 3, "Cache Dir #" << index
<< " log opened on FD " << fd
);
876 Fs::Ufs::UFSSwapDir::openTmpSwapLog(int *clean_flag
, int *zero_flag
)
878 assert(!rebuilding_
);
880 char *swaplog_path
= xstrdup(logFile(NULL
));
881 char *clean_path
= xstrdup(logFile(".last-clean"));
882 char *new_path
= xstrdup(logFile(".new"));
886 struct stat clean_sb
;
890 if (::stat(swaplog_path
, &log_sb
) < 0) {
891 debugs(47, DBG_IMPORTANT
, "Cache Dir #" << index
<< ": No log file");
892 safe_free(swaplog_path
);
893 safe_free(clean_path
);
898 *zero_flag
= log_sb
.st_size
== 0 ? 1 : 0;
899 /* close the existing write-only FD */
902 file_close(swaplog_fd
);
904 /* open a write-only FD for the new log */
905 fd
= file_open(new_path
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
909 debugs(50, DBG_IMPORTANT
, "ERROR: while opening swap log" << new_path
<< ": " << xstrerr(xerrno
));
910 fatalf("Failed to open swap log %s", new_path
);
917 const StoreSwapLogHeader header
;
919 buf
.init(header
.record_size
, header
.record_size
);
920 buf
.append(reinterpret_cast<const char*>(&header
), sizeof(header
));
921 // Pad to keep in sync with UFSSwapDir::writeCleanStart().
922 memset(buf
.space(), 0, header
.gapSize());
923 buf
.appended(header
.gapSize());
924 file_write(swaplog_fd
, -1, buf
.content(), buf
.contentSize(),
925 NULL
, NULL
, buf
.freeFunc());
928 /* open a read-only stream of the old log */
929 fp
= fopen(swaplog_path
, "rb");
933 debugs(50, DBG_CRITICAL
, "ERROR: while opening " << swaplog_path
<< ": " << xstrerr(xerrno
));
934 fatalf("Failed to open swap log for reading %s", swaplog_path
);
937 memset(&clean_sb
, '\0', sizeof(struct stat
));
939 if (::stat(clean_path
, &clean_sb
) < 0)
941 else if (clean_sb
.st_mtime
< log_sb
.st_mtime
)
946 safeunlink(clean_path
, 1);
948 safe_free(swaplog_path
);
950 safe_free(clean_path
);
958 * Begin the process to write clean cache state. For AUFS this means
959 * opening some log files and allocating write buffers. Return 0 if
960 * we succeed, and assign the 'func' and 'data' return pointers.
963 Fs::Ufs::UFSSwapDir::writeCleanStart()
965 UFSCleanLog
*state
= new UFSCleanLog(this);
966 StoreSwapLogHeader header
;
973 state
->newLog
= xstrdup(logFile(".clean"));
974 state
->fd
= file_open(state
->newLog
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
977 xfree(state
->newLog
);
982 state
->cur
= xstrdup(logFile(NULL
));
983 state
->cln
= xstrdup(logFile(".last-clean"));
984 state
->outbuf
= (char *)xcalloc(CLEAN_BUF_SZ
, 1);
985 state
->outbuf_offset
= 0;
987 memcpy(state
->outbuf
, &header
, sizeof(StoreSwapLogHeader
));
988 // Leave a gap to keep in sync with UFSSwapDir::openTmpSwapLog().
989 memset(state
->outbuf
+ sizeof(StoreSwapLogHeader
), 0, header
.gapSize());
990 state
->outbuf_offset
+= header
.record_size
;
992 state
->walker
= repl
->WalkInit(repl
);
993 ::unlink(state
->cln
);
994 debugs(47, 3, HERE
<< "opened " << state
->newLog
<< ", FD " << state
->fd
);
997 if (::stat(state
->cur
, &sb
) == 0)
998 fchmod(state
->fd
, sb
.st_mode
);
1007 Fs::Ufs::UFSSwapDir::writeCleanDone()
1009 UFSCleanLog
*state
= (UFSCleanLog
*)cleanLog
;
1018 state
->walker
->Done(state
->walker
);
1020 if (FD_WRITE_METHOD(state
->fd
, state
->outbuf
, state
->outbuf_offset
) < 0) {
1022 debugs(50, DBG_CRITICAL
, MYNAME
<< state
->newLog
<< ": write: " << xstrerr(xerrno
));
1023 debugs(50, DBG_CRITICAL
, MYNAME
<< "Current swap logfile not replaced.");
1024 file_close(state
->fd
);
1026 ::unlink(state
->newLog
);
1029 safe_free(state
->outbuf
);
1031 * You can't rename open files on Microsoft "operating systems"
1032 * so we have to close before renaming.
1035 /* save the fd value for a later test */
1039 if (state
->fd
>= 0) {
1040 #if _SQUID_OS2_ || _SQUID_WINDOWS_
1041 file_close(state
->fd
);
1045 xrename(state
->newLog
, state
->cur
);
1048 /* touch a timestamp file if we're not still validating */
1049 if (StoreController::store_dirs_rebuilding
)
1054 file_close(file_open(state
->cln
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
));
1057 safe_free(state
->cur
);
1059 safe_free(state
->newLog
);
1061 safe_free(state
->cln
);
1064 file_close(state
->fd
);
1073 /// safely cleans a few unused files if possible
1075 Fs::Ufs::UFSSwapDir::HandleCleanEvent()
1077 static int swap_index
= 0;
1082 if (!NumberOfUFSDirs
)
1083 return 0; // probably in the middle of reconfiguration
1085 if (NULL
== UFSDirToGlobalDirMapping
) {
1088 * Initialize the little array that translates UFS cache_dir
1089 * number into the Config.cacheSwap.swapDirs array index.
1091 UFSDirToGlobalDirMapping
= (int *)xcalloc(NumberOfUFSDirs
, sizeof(*UFSDirToGlobalDirMapping
));
1093 for (i
= 0, n
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1094 /* This is bogus, the controller should just clean each instance once */
1095 sd
= dynamic_cast <SwapDir
*>(INDEXSD(i
));
1097 if (!UFSSwapDir::IsUFSDir(sd
))
1100 UFSSwapDir
*usd
= dynamic_cast<UFSSwapDir
*>(sd
);
1104 UFSDirToGlobalDirMapping
[n
] = i
;
1107 j
+= (usd
->l1
* usd
->l2
);
1110 assert(n
== NumberOfUFSDirs
);
1112 * Start the commonUfsDirClean() swap_index with a random
1113 * value. j equals the total number of UFS level 2
1116 std::mt19937
mt(static_cast<uint32_t>(getCurrentTime() & 0xFFFFFFFF));
1117 xuniform_int_distribution
<> dist(0, j
);
1118 swap_index
= dist(mt
);
1121 /* if the rebuild is finished, start cleaning directories. */
1122 if (0 == StoreController::store_dirs_rebuilding
) {
1123 n
= DirClean(swap_index
);
1131 Fs::Ufs::UFSSwapDir::CleanEvent(void *)
1133 const int n
= HandleCleanEvent();
1134 eventAdd("storeDirClean", CleanEvent
, NULL
,
1135 15.0 * exp(-0.25 * n
), 1);
1139 Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir
* sd
)
1141 UFSSwapDir
*mySD
= dynamic_cast<UFSSwapDir
*>(sd
);
1142 return (mySD
!= 0) ;
1146 * XXX: this is broken - it assumes all cache dirs use the same
1147 * l1 and l2 scheme. -RBC 20021215. Partial fix is in place -
1148 * if not UFSSwapDir return 0;
1151 Fs::Ufs::UFSSwapDir::FilenoBelongsHere(int fn
, int F0
, int F1
, int F2
)
1156 assert(F0
< Config
.cacheSwap
.n_configured
);
1157 assert (UFSSwapDir::IsUFSDir (dynamic_cast<SwapDir
*>(INDEXSD(F0
))));
1158 UFSSwapDir
*sd
= dynamic_cast<UFSSwapDir
*>(INDEXSD(F0
));
1167 D1
= ((filn
/ L2
) / L2
) % L1
;
1172 D2
= (filn
/ L2
) % L2
;
1181 Fs::Ufs::UFSSwapDir::validFileno(sfileno filn
, int flag
) const
1187 * If flag is set it means out-of-range file number should
1188 * be considered invalid.
1191 if (filn
> map
->capacity())
1198 Fs::Ufs::UFSSwapDir::unlinkFile(sfileno f
)
1200 debugs(79, 3, HERE
<< "unlinking fileno " << std::setfill('0') <<
1201 std::hex
<< std::uppercase
<< std::setw(8) << f
<< " '" <<
1202 fullPath(f
,NULL
) << "'");
1203 /* commonUfsDirMapBitReset(this, f); */
1204 IO
->unlinkFile(fullPath(f
,NULL
));
1208 Fs::Ufs::UFSSwapDir::unlinkdUseful() const
1210 // unlinkd may be useful only in workers
1211 return IamWorkerProcess() && IO
->io
->unlinkdUseful();
1215 Fs::Ufs::UFSSwapDir::unlink(StoreEntry
& e
)
1217 debugs(79, 3, HERE
<< "dirno " << index
<< ", fileno "<<
1218 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
1219 if (e
.swap_status
== SWAPOUT_DONE
) {
1220 cur_size
-= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1223 replacementRemove(&e
);
1224 mapBitReset(e
.swap_filen
);
1225 UFSSwapDir::unlinkFile(e
.swap_filen
);
1228 e
.swap_status
= SWAPOUT_NONE
;
1232 Fs::Ufs::UFSSwapDir::replacementAdd(StoreEntry
* e
)
1234 debugs(47, 4, HERE
<< "added node " << e
<< " to dir " << index
);
1235 repl
->Add(repl
, e
, &e
->repl
);
1239 Fs::Ufs::UFSSwapDir::replacementRemove(StoreEntry
* e
)
1241 if (e
->swap_dirn
< 0)
1244 SwapDirPointer SD
= INDEXSD(e
->swap_dirn
);
1246 assert (dynamic_cast<UFSSwapDir
*>(SD
.getRaw()) == this);
1248 debugs(47, 4, HERE
<< "remove node " << e
<< " from dir " << index
);
1250 repl
->Remove(repl
, e
, &e
->repl
);
1254 Fs::Ufs::UFSSwapDir::dump(StoreEntry
& entry
) const
1256 storeAppendPrintf(&entry
, " %" PRIu64
" %d %d", maxSize() >> 20, l1
, l2
);
1257 dumpOptions(&entry
);
1261 Fs::Ufs::UFSSwapDir::fullPath(sfileno filn
, char *fullpath
) const
1263 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
1268 fullpath
= fullfilename
;
1272 snprintf(fullpath
, MAXPATHLEN
, "%s/%02X/%02X/%08X",
1274 ((filn
/ L2
) / L2
) % L1
,
1282 Fs::Ufs::UFSSwapDir::callback()
1284 return IO
->callback();
1288 Fs::Ufs::UFSSwapDir::sync()
1294 Fs::Ufs::UFSSwapDir::swappedOut(const StoreEntry
&e
)
1296 cur_size
+= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1301 Fs::Ufs::UFSSwapDir::logEntry(const StoreEntry
& e
, int op
) const
1303 if (swaplog_fd
< 0) {
1304 debugs(36, 5, "cannot log " << e
<< " in the middle of reconfiguration");
1308 StoreSwapLogData
*s
= new StoreSwapLogData
;
1310 s
->swap_filen
= e
.swap_filen
;
1311 s
->timestamp
= e
.timestamp
;
1312 s
->lastref
= e
.lastref
;
1313 s
->expires
= e
.expires
;
1314 s
->lastmod
= e
.lastModified();
1315 s
->swap_file_sz
= e
.swap_file_sz
;
1316 s
->refcount
= e
.refcount
;
1318 memcpy(s
->key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
1320 file_write(swaplog_fd
,
1323 sizeof(StoreSwapLogData
),
1330 Fs::Ufs::UFSSwapDir::DirClean(int swap_index
)
1332 DIR *dir_pointer
= NULL
;
1334 LOCAL_ARRAY(char, p1
, MAXPATHLEN
+ 1);
1335 LOCAL_ARRAY(char, p2
, MAXPATHLEN
+ 1);
1339 int fn
; /* same as swapfileno, but with dirn bits set */
1345 N0
= NumberOfUFSDirs
;
1346 D0
= UFSDirToGlobalDirMapping
[swap_index
% N0
];
1347 SD
= dynamic_cast<UFSSwapDir
*>(INDEXSD(D0
));
1350 D1
= (swap_index
/ N0
) % N1
;
1352 D2
= ((swap_index
/ N0
) / N1
) % N2
;
1353 snprintf(p1
, MAXPATHLEN
, "%s/%02X/%02X",
1355 debugs(36, 3, HERE
<< "Cleaning directory " << p1
);
1356 dir_pointer
= opendir(p1
);
1360 if (xerrno
== ENOENT
) {
1361 debugs(36, DBG_CRITICAL
, MYNAME
<< "WARNING: Creating " << p1
);
1362 if (mkdir(p1
, 0777) == 0)
1366 debugs(50, DBG_CRITICAL
, MYNAME
<< p1
<< ": " << xstrerr(xerrno
));
1372 while ((de
= readdir(dir_pointer
)) != NULL
&& k
< 20) {
1373 if (sscanf(de
->d_name
, "%X", &swapfileno
) != 1)
1376 fn
= swapfileno
; /* XXX should remove this cruft ! */
1378 if (SD
->validFileno(fn
, 1))
1379 if (SD
->mapBitTest(fn
))
1380 if (UFSSwapDir::FilenoBelongsHere(fn
, D0
, D1
, D2
))
1383 files
[k
] = swapfileno
;
1387 closedir(dir_pointer
);
1392 qsort(files
, k
, sizeof(int), rev_int_sort
);
1397 for (n
= 0; n
< k
; ++n
) {
1398 debugs(36, 3, HERE
<< "Cleaning file "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << files
[n
]);
1399 snprintf(p2
, MAXPATHLEN
+ 1, "%s/%08X", p1
, files
[n
]);
1401 ++statCounter
.swap
.files_cleaned
;
1404 debugs(36, 3, HERE
<< "Cleaned " << k
<< " unused files from " << p1
);