2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
9 /* DEBUG: section 47 Store Directory Routines */
11 #define CLEAN_BUF_SZ 16384
15 #include "ConfigOption.h"
17 #include "DiskIO/DiskIOModule.h"
18 #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
.lastmod
;
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) {
103 /* XXX This error handling should probably move up to the caller */
104 debugs(50, DBG_CRITICAL
, HERE
<< newLog
<< ": write: " << xstrerror());
105 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
119 Fs::Ufs::UFSSwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
121 if (!SwapDir::canStore(e
, diskSpaceNeeded
, load
))
132 FreeObject(void *address
)
134 StoreSwapLogData
*anObject
= static_cast <StoreSwapLogData
*>(address
);
138 static QS rev_int_sort
;
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) storeDirGetBlkSize(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
)),
322 /* modulename is only set to disk modules that are built, by configure,
323 * so the Find call should never return NULL here.
325 IO
= new Fs::Ufs::UFSStrategy(DiskIOModule::Find(anIOType
)->createStrategy());
328 Fs::Ufs::UFSSwapDir::~UFSSwapDir()
330 if (swaplog_fd
> -1) {
331 file_close(swaplog_fd
);
337 delete currentIOOptions
;
341 Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry
&e
) const
343 debugs(47, DBG_CRITICAL
, HERE
<< "FILENO "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
344 debugs(47, DBG_CRITICAL
, HERE
<< "PATH " << fullPath(e
.swap_filen
, NULL
) );
349 Fs::Ufs::UFSSwapDir::doubleCheck(StoreEntry
& e
)
354 if (::stat(fullPath(e
.swap_filen
, NULL
), &sb
) < 0) {
355 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Missing swap file");
360 if ((off_t
)e
.swap_file_sz
!= sb
.st_size
) {
361 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Size Mismatch. Entry size: "
362 << e
.swap_file_sz
<< ", file size: " << sb
.st_size
);
371 Fs::Ufs::UFSSwapDir::statfs(StoreEntry
& sentry
) const
378 storeAppendPrintf(&sentry
, "First level subdirectories: %d\n", l1
);
379 storeAppendPrintf(&sentry
, "Second level subdirectories: %d\n", l2
);
380 storeAppendPrintf(&sentry
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
381 storeAppendPrintf(&sentry
, "Current Size: %.2f KB\n", currentSize() / 1024.0);
382 storeAppendPrintf(&sentry
, "Percent Used: %0.2f%%\n",
383 Math::doublePercent(currentSize(), maxSize()));
384 storeAppendPrintf(&sentry
, "Filemap bits in use: %d of %d (%d%%)\n",
385 map
->numFilesInMap(), map
->capacity(),
386 Math::intPercent(map
->numFilesInMap(), map
->capacity()));
387 x
= storeDirGetUFSStats(path
, &totl_kb
, &free_kb
, &totl_in
, &free_in
);
390 storeAppendPrintf(&sentry
, "Filesystem Space in use: %d/%d KB (%d%%)\n",
393 Math::intPercent(totl_kb
- free_kb
, totl_kb
));
394 storeAppendPrintf(&sentry
, "Filesystem Inodes in use: %d/%d (%d%%)\n",
397 Math::intPercent(totl_in
- free_in
, totl_in
));
400 storeAppendPrintf(&sentry
, "Flags:");
403 storeAppendPrintf(&sentry
, " SELECTED");
406 storeAppendPrintf(&sentry
, " READ-ONLY");
408 storeAppendPrintf(&sentry
, "\n");
414 Fs::Ufs::UFSSwapDir::maintain()
416 /* We can't delete objects while rebuilding swap */
418 /* XXX FIXME each store should start maintaining as it comes online. */
420 if (StoreController::store_dirs_rebuilding
)
423 StoreEntry
*e
= NULL
;
427 RemovalPurgeWalker
*walker
;
429 double f
= (double) (currentSize() - minSize()) / (maxSize() - minSize());
431 f
= f
< 0.0 ? 0.0 : f
> 1.0 ? 1.0 : f
;
433 int max_scan
= (int) (f
* 400.0 + 100.0);
435 int max_remove
= (int) (f
* 70.0 + 10.0);
438 * This is kinda cheap, but so we need this priority hack?
441 debugs(47, 3, HERE
<< "f=" << f
<< ", max_scan=" << max_scan
<< ", max_remove=" << max_remove
);
443 walker
= repl
->PurgeInit(repl
, max_scan
);
446 if (currentSize() < minSize())
449 if (removed
>= max_remove
)
452 e
= walker
->Next(walker
);
455 break; /* no more objects */
462 walker
->Done(walker
);
463 debugs(47, (removed
? 2 : 3), HERE
<< path
<<
464 " removed " << removed
<< "/" << max_remove
<< " f=" <<
465 std::setprecision(4) << f
<< " max_scan=" << max_scan
);
469 Fs::Ufs::UFSSwapDir::reference(StoreEntry
&e
)
471 debugs(47, 3, HERE
<< "referencing " << &e
<< " " <<
472 e
.swap_dirn
<< "/" << e
.swap_filen
);
474 if (repl
->Referenced
)
475 repl
->Referenced(repl
, &e
, &e
.repl
);
479 Fs::Ufs::UFSSwapDir::dereference(StoreEntry
& e
, bool)
481 debugs(47, 3, HERE
<< "dereferencing " << &e
<< " " <<
482 e
.swap_dirn
<< "/" << e
.swap_filen
);
484 if (repl
->Dereferenced
)
485 repl
->Dereferenced(repl
, &e
, &e
.repl
);
487 return true; // keep e in the global store_table
490 StoreIOState::Pointer
491 Fs::Ufs::UFSSwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
493 return IO
->create (this, &e
, file_callback
, aCallback
, callback_data
);
496 StoreIOState::Pointer
497 Fs::Ufs::UFSSwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
499 return IO
->open (this, &e
, file_callback
, aCallback
, callback_data
);
503 Fs::Ufs::UFSSwapDir::mapBitTest(sfileno filn
)
505 return map
->testBit(filn
);
509 Fs::Ufs::UFSSwapDir::mapBitSet(sfileno filn
)
515 Fs::Ufs::UFSSwapDir::mapBitReset(sfileno filn
)
518 * We have to test the bit before calling clearBit as
519 * it doesn't do bounds checking and blindly assumes
520 * filn is a valid file number, but it might not be because
521 * the map is dynamic in size. Also clearing an already clear
522 * bit puts the map counter of-of-whack.
525 if (map
->testBit(filn
))
530 Fs::Ufs::UFSSwapDir::mapBitAllocate()
533 fn
= map
->allocate(suggest
);
540 Fs::Ufs::UFSSwapDir::swapSubDir(int subdirn
)const
542 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
543 assert(0 <= subdirn
&& subdirn
< l1
);
544 snprintf(fullfilename
, MAXPATHLEN
, "%s/%02X", path
, subdirn
);
549 Fs::Ufs::UFSSwapDir::createDirectory(const char *aPath
, int should_exist
)
556 if (0 == ::stat(aPath
, &st
)) {
557 if (S_ISDIR(st
.st_mode
)) {
558 debugs(47, (should_exist
? 3 : DBG_IMPORTANT
), aPath
<< " exists");
560 fatalf("Swap directory %s is not a directory.", aPath
);
562 } else if (0 == mkdir(aPath
, 0755)) {
563 debugs(47, (should_exist
? DBG_IMPORTANT
: 3), aPath
<< " created");
566 fatalf("Failed to make swap directory %s: %s",
574 Fs::Ufs::UFSSwapDir::pathIsDirectory(const char *aPath
)const
579 if (::stat(aPath
, &sb
) < 0) {
580 debugs(47, DBG_CRITICAL
, "ERROR: " << aPath
<< ": " << xstrerror());
584 if (S_ISDIR(sb
.st_mode
) == 0) {
585 debugs(47, DBG_CRITICAL
, "WARNING: " << aPath
<< " is not a directory");
593 Fs::Ufs::UFSSwapDir::verifyCacheDirs()
595 if (!pathIsDirectory(path
))
598 for (int j
= 0; j
< l1
; ++j
) {
599 char const *aPath
= swapSubDir(j
);
601 if (!pathIsDirectory(aPath
))
609 Fs::Ufs::UFSSwapDir::createSwapSubDirs()
611 LOCAL_ARRAY(char, name
, MAXPATHLEN
);
613 for (int i
= 0; i
< l1
; ++i
) {
614 snprintf(name
, MAXPATHLEN
, "%s/%02X", path
, i
);
618 if (createDirectory(name
, 0))
623 debugs(47, DBG_IMPORTANT
, "Making directories in " << name
);
625 for (int k
= 0; k
< l2
; ++k
) {
626 snprintf(name
, MAXPATHLEN
, "%s/%02X/%02X", path
, i
, k
);
627 createDirectory(name
, should_exist
);
633 Fs::Ufs::UFSSwapDir::logFile(char const *ext
) const
635 LOCAL_ARRAY(char, lpath
, MAXPATHLEN
);
636 LOCAL_ARRAY(char, pathtmp
, MAXPATHLEN
);
637 LOCAL_ARRAY(char, digit
, 32);
640 if (Config
.Log
.swap
) {
641 xstrncpy(pathtmp
, path
, MAXPATHLEN
- 64);
644 while ((pathtmp2
= strchr(pathtmp2
, '/')) != NULL
)
647 while (strlen(pathtmp
) && pathtmp
[strlen(pathtmp
) - 1] == '.')
648 pathtmp
[strlen(pathtmp
) - 1] = '\0';
650 for (pathtmp2
= pathtmp
; *pathtmp2
== '.'; ++pathtmp2
);
651 snprintf(lpath
, MAXPATHLEN
- 64, Config
.Log
.swap
, pathtmp2
);
653 if (strncmp(lpath
, Config
.Log
.swap
, MAXPATHLEN
- 64) == 0) {
655 snprintf(digit
, 32, "%02d", index
);
656 strncat(lpath
, digit
, 3);
659 xstrncpy(lpath
, path
, MAXPATHLEN
- 64);
660 strcat(lpath
, "/swap.state");
664 strncat(lpath
, ext
, 16);
670 Fs::Ufs::UFSSwapDir::openLog()
674 swaplog_fd
= file_open(logPath
, O_WRONLY
| O_CREAT
| O_BINARY
);
676 if (swaplog_fd
< 0) {
677 debugs(50, DBG_IMPORTANT
, "ERROR opening swap log " << logPath
<< ": " << xstrerror());
678 fatal("UFSSwapDir::openLog: Failed to open swap log.");
681 debugs(50, 3, HERE
<< "Cache Dir #" << index
<< " log opened on FD " << swaplog_fd
);
683 if (0 == NumberOfUFSDirs
)
684 assert(NULL
== UFSDirToGlobalDirMapping
);
688 assert(NumberOfUFSDirs
<= Config
.cacheSwap
.n_configured
);
692 Fs::Ufs::UFSSwapDir::closeLog()
694 if (swaplog_fd
< 0) /* not open */
697 file_close(swaplog_fd
);
699 debugs(47, 3, "Cache Dir #" << index
<< " log closed on FD " << swaplog_fd
);
705 assert(NumberOfUFSDirs
>= 0);
707 if (0 == NumberOfUFSDirs
)
708 safe_free(UFSDirToGlobalDirMapping
);
712 Fs::Ufs::UFSSwapDir::validL1(int anInt
) const
718 Fs::Ufs::UFSSwapDir::validL2(int anInt
) const
724 Fs::Ufs::UFSSwapDir::addDiskRestore(const cache_key
* key
,
726 uint64_t swap_file_sz
,
735 StoreEntry
*e
= NULL
;
736 debugs(47, 5, HERE
<< storeKeyText(key
) <<
737 ", fileno="<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << file_number
);
738 /* if you call this you'd better be sure file_number is not
740 e
= new StoreEntry();
741 e
->store_status
= STORE_OK
;
742 e
->setMemStatus(NOT_IN_MEMORY
);
743 e
->swap_status
= SWAPOUT_DONE
;
744 e
->swap_filen
= file_number
;
745 e
->swap_dirn
= index
;
746 e
->swap_file_sz
= swap_file_sz
;
747 e
->lastref
= lastref
;
748 e
->timestamp
= timestamp
;
749 e
->expires
= expires
;
750 e
->lastmod
= lastmod
;
751 e
->refcount
= refcount
;
753 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
754 EBIT_CLR(e
->flags
, KEY_PRIVATE
);
755 e
->ping_status
= PING_NONE
;
756 EBIT_CLR(e
->flags
, ENTRY_VALIDATED
);
757 mapBitSet(e
->swap_filen
);
758 cur_size
+= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
760 e
->hashInsert(key
); /* do it after we clear KEY_PRIVATE */
766 Fs::Ufs::UFSSwapDir::undoAddDiskRestore(StoreEntry
*e
)
768 debugs(47, 5, HERE
<< *e
);
769 replacementRemove(e
); // checks swap_dirn so do it before we invalidate it
770 // Do not unlink the file as it might be used by a subsequent entry.
771 mapBitReset(e
->swap_filen
);
774 cur_size
-= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
779 Fs::Ufs::UFSSwapDir::rebuild()
781 ++StoreController::store_dirs_rebuilding
;
782 eventAdd("storeRebuild", Fs::Ufs::RebuildState::RebuildStep
, new Fs::Ufs::RebuildState(this), 0.0, 1);
786 Fs::Ufs::UFSSwapDir::closeTmpSwapLog()
788 char *swaplog_path
= xstrdup(logFile(NULL
)); // where the swaplog should be
789 char *tmp_path
= xstrdup(logFile(".new")); // the temporary file we have generated
791 file_close(swaplog_fd
);
793 if (xrename(tmp_path
, swaplog_path
) < 0) {
794 fatalf("Failed to rename log file %s to %s", tmp_path
, swaplog_path
);
797 fd
= file_open(swaplog_path
, O_WRONLY
| O_CREAT
| O_BINARY
);
800 debugs(50, DBG_IMPORTANT
, "ERROR: " << swaplog_path
<< ": " << xstrerror());
801 fatalf("Failed to open swap log %s", swaplog_path
);
807 debugs(47, 3, "Cache Dir #" << index
<< " log opened on FD " << fd
);
811 Fs::Ufs::UFSSwapDir::openTmpSwapLog(int *clean_flag
, int *zero_flag
)
813 char *swaplog_path
= xstrdup(logFile(NULL
));
814 char *clean_path
= xstrdup(logFile(".last-clean"));
815 char *new_path
= xstrdup(logFile(".new"));
819 struct stat clean_sb
;
823 if (::stat(swaplog_path
, &log_sb
) < 0) {
824 debugs(47, DBG_IMPORTANT
, "Cache Dir #" << index
<< ": No log file");
825 safe_free(swaplog_path
);
826 safe_free(clean_path
);
831 *zero_flag
= log_sb
.st_size
== 0 ? 1 : 0;
832 /* close the existing write-only FD */
835 file_close(swaplog_fd
);
837 /* open a write-only FD for the new log */
838 fd
= file_open(new_path
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
841 debugs(50, DBG_IMPORTANT
, "ERROR: while opening swap log" << new_path
<< ": " << xstrerror());
842 fatalf("Failed to open swap log %s", new_path
);
848 const StoreSwapLogHeader header
;
850 buf
.init(header
.record_size
, header
.record_size
);
851 buf
.append(reinterpret_cast<const char*>(&header
), sizeof(header
));
852 // Pad to keep in sync with UFSSwapDir::writeCleanStart().
853 memset(buf
.space(), 0, header
.gapSize());
854 buf
.appended(header
.gapSize());
855 file_write(swaplog_fd
, -1, buf
.content(), buf
.contentSize(),
856 NULL
, NULL
, buf
.freeFunc());
859 /* open a read-only stream of the old log */
860 fp
= fopen(swaplog_path
, "rb");
863 debugs(50, DBG_CRITICAL
, "ERROR: while opening " << swaplog_path
<< ": " << xstrerror());
864 fatalf("Failed to open swap log for reading %s", swaplog_path
);
867 memset(&clean_sb
, '\0', sizeof(struct stat
));
869 if (::stat(clean_path
, &clean_sb
) < 0)
871 else if (clean_sb
.st_mtime
< log_sb
.st_mtime
)
876 safeunlink(clean_path
, 1);
878 safe_free(swaplog_path
);
880 safe_free(clean_path
);
888 * Begin the process to write clean cache state. For AUFS this means
889 * opening some log files and allocating write buffers. Return 0 if
890 * we succeed, and assign the 'func' and 'data' return pointers.
893 Fs::Ufs::UFSSwapDir::writeCleanStart()
895 UFSCleanLog
*state
= new UFSCleanLog(this);
896 StoreSwapLogHeader header
;
903 state
->newLog
= xstrdup(logFile(".clean"));
904 state
->fd
= file_open(state
->newLog
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
907 xfree(state
->newLog
);
912 state
->cur
= xstrdup(logFile(NULL
));
913 state
->cln
= xstrdup(logFile(".last-clean"));
914 state
->outbuf
= (char *)xcalloc(CLEAN_BUF_SZ
, 1);
915 state
->outbuf_offset
= 0;
917 memcpy(state
->outbuf
, &header
, sizeof(StoreSwapLogHeader
));
918 // Leave a gap to keep in sync with UFSSwapDir::openTmpSwapLog().
919 memset(state
->outbuf
+ sizeof(StoreSwapLogHeader
), 0, header
.gapSize());
920 state
->outbuf_offset
+= header
.record_size
;
922 state
->walker
= repl
->WalkInit(repl
);
923 ::unlink(state
->cln
);
924 debugs(47, 3, HERE
<< "opened " << state
->newLog
<< ", FD " << state
->fd
);
927 if (::stat(state
->cur
, &sb
) == 0)
928 fchmod(state
->fd
, sb
.st_mode
);
937 Fs::Ufs::UFSSwapDir::writeCleanDone()
939 UFSCleanLog
*state
= (UFSCleanLog
*)cleanLog
;
948 state
->walker
->Done(state
->walker
);
950 if (FD_WRITE_METHOD(state
->fd
, state
->outbuf
, state
->outbuf_offset
) < 0) {
951 debugs(50, DBG_CRITICAL
, HERE
<< state
->newLog
<< ": write: " << xstrerror());
952 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
953 file_close(state
->fd
);
955 ::unlink(state
->newLog
);
958 safe_free(state
->outbuf
);
960 * You can't rename open files on Microsoft "operating systems"
961 * so we have to close before renaming.
964 /* save the fd value for a later test */
968 if (state
->fd
>= 0) {
969 #if _SQUID_OS2_ || _SQUID_WINDOWS_
970 file_close(state
->fd
);
974 xrename(state
->newLog
, state
->cur
);
977 /* touch a timestamp file if we're not still validating */
978 if (StoreController::store_dirs_rebuilding
)
983 file_close(file_open(state
->cln
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
));
986 safe_free(state
->cur
);
988 safe_free(state
->newLog
);
990 safe_free(state
->cln
);
993 file_close(state
->fd
);
1003 Fs::Ufs::UFSSwapDir::CleanEvent(void *)
1005 static int swap_index
= 0;
1010 * Assert that there are UFS cache_dirs configured, otherwise
1011 * we should never be called.
1013 assert(NumberOfUFSDirs
);
1015 if (NULL
== UFSDirToGlobalDirMapping
) {
1018 * Initialize the little array that translates UFS cache_dir
1019 * number into the Config.cacheSwap.swapDirs array index.
1021 UFSDirToGlobalDirMapping
= (int *)xcalloc(NumberOfUFSDirs
, sizeof(*UFSDirToGlobalDirMapping
));
1023 for (i
= 0, n
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1024 /* This is bogus, the controller should just clean each instance once */
1025 sd
= dynamic_cast <SwapDir
*>(INDEXSD(i
));
1027 if (!UFSSwapDir::IsUFSDir(sd
))
1030 UFSSwapDir
*usd
= dynamic_cast<UFSSwapDir
*>(sd
);
1034 UFSDirToGlobalDirMapping
[n
] = i
;
1037 j
+= (usd
->l1
* usd
->l2
);
1040 assert(n
== NumberOfUFSDirs
);
1042 * Start the commonUfsDirClean() swap_index with a random
1043 * value. j equals the total number of UFS level 2
1046 std::mt19937
mt(static_cast<uint32_t>(getCurrentTime() & 0xFFFFFFFF));
1047 std::uniform_int_distribution
<> dist(0, j
);
1048 swap_index
= dist(mt
);
1051 /* if the rebuild is finished, start cleaning directories. */
1052 if (0 == StoreController::store_dirs_rebuilding
) {
1053 n
= DirClean(swap_index
);
1057 eventAdd("storeDirClean", CleanEvent
, NULL
,
1058 15.0 * exp(-0.25 * n
), 1);
1062 Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir
* sd
)
1064 UFSSwapDir
*mySD
= dynamic_cast<UFSSwapDir
*>(sd
);
1065 return (mySD
!= 0) ;
1069 * XXX: this is broken - it assumes all cache dirs use the same
1070 * l1 and l2 scheme. -RBC 20021215. Partial fix is in place -
1071 * if not UFSSwapDir return 0;
1074 Fs::Ufs::UFSSwapDir::FilenoBelongsHere(int fn
, int F0
, int F1
, int F2
)
1079 assert(F0
< Config
.cacheSwap
.n_configured
);
1080 assert (UFSSwapDir::IsUFSDir (dynamic_cast<SwapDir
*>(INDEXSD(F0
))));
1081 UFSSwapDir
*sd
= dynamic_cast<UFSSwapDir
*>(INDEXSD(F0
));
1090 D1
= ((filn
/ L2
) / L2
) % L1
;
1095 D2
= (filn
/ L2
) % L2
;
1104 Fs::Ufs::UFSSwapDir::validFileno(sfileno filn
, int flag
) const
1110 * If flag is set it means out-of-range file number should
1111 * be considered invalid.
1114 if (filn
> map
->capacity())
1121 Fs::Ufs::UFSSwapDir::unlinkFile(sfileno f
)
1123 debugs(79, 3, HERE
<< "unlinking fileno " << std::setfill('0') <<
1124 std::hex
<< std::uppercase
<< std::setw(8) << f
<< " '" <<
1125 fullPath(f
,NULL
) << "'");
1126 /* commonUfsDirMapBitReset(this, f); */
1127 IO
->unlinkFile(fullPath(f
,NULL
));
1131 Fs::Ufs::UFSSwapDir::unlinkdUseful() const
1133 // unlinkd may be useful only in workers
1134 return IamWorkerProcess() && IO
->io
->unlinkdUseful();
1138 Fs::Ufs::UFSSwapDir::unlink(StoreEntry
& e
)
1140 debugs(79, 3, HERE
<< "dirno " << index
<< ", fileno "<<
1141 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
1142 if (e
.swap_status
== SWAPOUT_DONE
) {
1143 cur_size
-= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1146 replacementRemove(&e
);
1147 mapBitReset(e
.swap_filen
);
1148 UFSSwapDir::unlinkFile(e
.swap_filen
);
1152 Fs::Ufs::UFSSwapDir::replacementAdd(StoreEntry
* e
)
1154 debugs(47, 4, HERE
<< "added node " << e
<< " to dir " << index
);
1155 repl
->Add(repl
, e
, &e
->repl
);
1159 Fs::Ufs::UFSSwapDir::replacementRemove(StoreEntry
* e
)
1163 if (e
->swap_dirn
< 0)
1166 SD
= INDEXSD(e
->swap_dirn
);
1168 assert (dynamic_cast<UFSSwapDir
*>(SD
.getRaw()) == this);
1170 debugs(47, 4, HERE
<< "remove node " << e
<< " from dir " << index
);
1172 repl
->Remove(repl
, e
, &e
->repl
);
1176 Fs::Ufs::UFSSwapDir::dump(StoreEntry
& entry
) const
1178 storeAppendPrintf(&entry
, " %" PRIu64
" %d %d", maxSize() >> 20, l1
, l2
);
1179 dumpOptions(&entry
);
1183 Fs::Ufs::UFSSwapDir::fullPath(sfileno filn
, char *fullpath
) const
1185 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
1190 fullpath
= fullfilename
;
1194 snprintf(fullpath
, MAXPATHLEN
, "%s/%02X/%02X/%08X",
1196 ((filn
/ L2
) / L2
) % L1
,
1204 Fs::Ufs::UFSSwapDir::callback()
1206 return IO
->callback();
1210 Fs::Ufs::UFSSwapDir::sync()
1216 Fs::Ufs::UFSSwapDir::swappedOut(const StoreEntry
&e
)
1218 cur_size
+= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1223 Fs::Ufs::UFSSwapDir::search(String
const url
, HttpRequest
*)
1226 fatal ("Cannot search by url yet\n");
1228 return new Fs::Ufs::StoreSearchUFS (this);
1232 Fs::Ufs::UFSSwapDir::logEntry(const StoreEntry
& e
, int op
) const
1234 StoreSwapLogData
*s
= new StoreSwapLogData
;
1236 s
->swap_filen
= e
.swap_filen
;
1237 s
->timestamp
= e
.timestamp
;
1238 s
->lastref
= e
.lastref
;
1239 s
->expires
= e
.expires
;
1240 s
->lastmod
= e
.lastmod
;
1241 s
->swap_file_sz
= e
.swap_file_sz
;
1242 s
->refcount
= e
.refcount
;
1244 memcpy(s
->key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
1246 file_write(swaplog_fd
,
1249 sizeof(StoreSwapLogData
),
1256 Fs::Ufs::UFSSwapDir::DirClean(int swap_index
)
1258 DIR *dir_pointer
= NULL
;
1260 LOCAL_ARRAY(char, p1
, MAXPATHLEN
+ 1);
1261 LOCAL_ARRAY(char, p2
, MAXPATHLEN
+ 1);
1265 int fn
; /* same as swapfileno, but with dirn bits set */
1271 N0
= NumberOfUFSDirs
;
1272 D0
= UFSDirToGlobalDirMapping
[swap_index
% N0
];
1273 SD
= dynamic_cast<UFSSwapDir
*>(INDEXSD(D0
));
1276 D1
= (swap_index
/ N0
) % N1
;
1278 D2
= ((swap_index
/ N0
) / N1
) % N2
;
1279 snprintf(p1
, MAXPATHLEN
, "%s/%02X/%02X",
1281 debugs(36, 3, HERE
<< "Cleaning directory " << p1
);
1282 dir_pointer
= opendir(p1
);
1284 if (dir_pointer
== NULL
) {
1285 if (errno
== ENOENT
) {
1286 debugs(36, DBG_CRITICAL
, HERE
<< "WARNING: Creating " << p1
);
1287 if (mkdir(p1
, 0777) == 0)
1291 debugs(50, DBG_CRITICAL
, HERE
<< p1
<< ": " << xstrerror());
1297 while ((de
= readdir(dir_pointer
)) != NULL
&& k
< 20) {
1298 if (sscanf(de
->d_name
, "%X", &swapfileno
) != 1)
1301 fn
= swapfileno
; /* XXX should remove this cruft ! */
1303 if (SD
->validFileno(fn
, 1))
1304 if (SD
->mapBitTest(fn
))
1305 if (UFSSwapDir::FilenoBelongsHere(fn
, D0
, D1
, D2
))
1308 files
[k
] = swapfileno
;
1312 closedir(dir_pointer
);
1317 qsort(files
, k
, sizeof(int), rev_int_sort
);
1322 for (n
= 0; n
< k
; ++n
) {
1323 debugs(36, 3, HERE
<< "Cleaning file "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << files
[n
]);
1324 snprintf(p2
, MAXPATHLEN
+ 1, "%s/%08X", p1
, files
[n
]);
1326 ++statCounter
.swap
.files_cleaned
;
1329 debugs(36, 3, HERE
<< "Cleaned " << k
<< " unused files from " << p1
);