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"
40 int Fs::Ufs::UFSSwapDir::NumberOfUFSDirs
= 0;
41 int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping
= NULL
;
43 class UFSCleanLog
: public SwapDir::CleanLog
47 UFSCleanLog(SwapDir
*);
48 /** Get the next entry that is a candidate for clean log writing
50 virtual const StoreEntry
*nextEntry();
51 /** "write" an entry to the clean log file.
53 virtual void write(StoreEntry
const &);
60 RemovalPolicyWalker
*walker
;
64 UFSCleanLog::UFSCleanLog(SwapDir
*aSwapDir
) :
65 cur(NULL
), newLog(NULL
), cln(NULL
), outbuf(NULL
),
66 outbuf_offset(0), fd(-1),walker(NULL
), sd(aSwapDir
)
70 UFSCleanLog::nextEntry()
72 const StoreEntry
*entry
= NULL
;
75 entry
= walker
->Next(walker
);
81 UFSCleanLog::write(StoreEntry
const &e
)
84 static size_t ss
= sizeof(StoreSwapLogData
);
85 s
.op
= (char) SWAP_LOG_ADD
;
86 s
.swap_filen
= e
.swap_filen
;
87 s
.timestamp
= e
.timestamp
;
88 s
.lastref
= e
.lastref
;
89 s
.expires
= e
.expires
;
90 s
.lastmod
= e
.lastmod
;
91 s
.swap_file_sz
= e
.swap_file_sz
;
92 s
.refcount
= e
.refcount
;
94 memcpy(&s
.key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
96 memcpy(outbuf
+ outbuf_offset
, &s
, ss
);
100 if (outbuf_offset
+ ss
>= CLEAN_BUF_SZ
) {
101 if (FD_WRITE_METHOD(fd
, outbuf
, outbuf_offset
) < 0) {
102 /* XXX This error handling should probably move up to the caller */
103 debugs(50, DBG_CRITICAL
, HERE
<< newLog
<< ": write: " << xstrerror());
104 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
118 Fs::Ufs::UFSSwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
120 if (!SwapDir::canStore(e
, diskSpaceNeeded
, load
))
131 FreeObject(void *address
)
133 StoreSwapLogData
*anObject
= static_cast <StoreSwapLogData
*>(address
);
137 static QS rev_int_sort
;
139 rev_int_sort(const void *A
, const void *B
)
141 const int *i1
= (const int *)A
;
142 const int *i2
= (const int *)B
;
147 Fs::Ufs::UFSSwapDir::parseSizeL1L2()
149 int i
= GetInteger();
151 fatal("UFSSwapDir::parseSizeL1L2: invalid size value");
153 const uint64_t size
= static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
155 /* just reconfigure it */
157 if (size
== maxSize())
158 debugs(3, 2, "Cache dir '" << path
<< "' size remains unchanged at " << i
<< " MB");
160 debugs(3, DBG_IMPORTANT
, "Cache dir '" << path
<< "' size changed to " << i
<< " MB");
168 fatal("UFSSwapDir::parseSizeL1L2: invalid level 1 directories value");
173 fatal("UFSSwapDir::parseSizeL1L2: invalid level 2 directories value");
177 Fs::Ufs::UFSSwapDir::reconfigure()
184 Fs::Ufs::UFSSwapDir::parse (int anIndex
, char *aPath
)
187 path
= xstrdup(aPath
);
191 /* Initialise replacement policy stuff */
192 repl
= createRemovalPolicy(Config
.replPolicy
);
198 Fs::Ufs::UFSSwapDir::changeIO(DiskIOModule
*module
)
200 DiskIOStrategy
*anIO
= module
->createStrategy();
202 ioType
= xstrdup(module
->type());
206 /* Change the IO Options */
208 if (currentIOOptions
&& currentIOOptions
->options
.size() > 2) {
209 delete currentIOOptions
->options
.back();
210 currentIOOptions
->options
.pop_back();
213 /* TODO: factor out these 4 lines */
214 ConfigOption
*ioOptions
= IO
->io
->getOptionTree();
216 if (currentIOOptions
&& ioOptions
)
217 currentIOOptions
->options
.push_back(ioOptions
);
221 Fs::Ufs::UFSSwapDir::optionIOParse(char const *option
, const char *value
, int isaReconfig
)
223 if (strcmp(option
, "IOEngine") != 0)
227 /* silently ignore this */
233 DiskIOModule
*module
= DiskIOModule::Find(value
);
244 Fs::Ufs::UFSSwapDir::optionIODump(StoreEntry
* e
) const
246 storeAppendPrintf(e
, " IOEngine=%s", ioType
);
250 Fs::Ufs::UFSSwapDir::getOptionTree() const
252 ConfigOption
*parentResult
= SwapDir::getOptionTree();
254 if (currentIOOptions
== NULL
)
255 currentIOOptions
= new ConfigOptionVector();
257 currentIOOptions
->options
.push_back(parentResult
);
259 currentIOOptions
->options
.push_back(new ConfigOptionAdapter
<UFSSwapDir
>(*const_cast<UFSSwapDir
*>(this), &UFSSwapDir::optionIOParse
, &UFSSwapDir::optionIODump
));
261 if (ConfigOption
*ioOptions
= IO
->io
->getOptionTree())
262 currentIOOptions
->options
.push_back(ioOptions
);
264 ConfigOption
* result
= currentIOOptions
;
266 currentIOOptions
= NULL
;
272 Fs::Ufs::UFSSwapDir::init()
274 debugs(47, 3, HERE
<< "Initialising UFS SwapDir engine.");
275 /* Parsing must be finished by now - force to NULL, don't delete */
276 currentIOOptions
= NULL
;
277 static int started_clean_event
= 0;
278 static const char *errmsg
=
279 "\tFailed to verify one of the swap directories, Check cache.log\n"
280 "\tfor details. Run 'squid -z' to create swap directories\n"
281 "\tif needed, or if running Squid for the first time.";
284 if (verifyCacheDirs())
291 if (!started_clean_event
) {
292 eventAdd("UFS storeDirClean", CleanEvent
, NULL
, 15.0, 1);
293 started_clean_event
= 1;
296 (void) storeDirGetBlkSize(path
, &fs
.blksize
);
300 Fs::Ufs::UFSSwapDir::create()
302 debugs(47, 3, "Creating swap space in " << path
);
303 createDirectory(path
, 0);
307 Fs::Ufs::UFSSwapDir::UFSSwapDir(char const *aType
, const char *anIOType
) :
316 currentIOOptions(new ConfigOptionVector()),
317 ioType(xstrdup(anIOType
)),
321 /* modulename is only set to disk modules that are built, by configure,
322 * so the Find call should never return NULL here.
324 IO
= new Fs::Ufs::UFSStrategy(DiskIOModule::Find(anIOType
)->createStrategy());
327 Fs::Ufs::UFSSwapDir::~UFSSwapDir()
329 if (swaplog_fd
> -1) {
330 file_close(swaplog_fd
);
336 delete currentIOOptions
;
340 Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry
&e
) const
342 debugs(47, DBG_CRITICAL
, HERE
<< "FILENO "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
343 debugs(47, DBG_CRITICAL
, HERE
<< "PATH " << fullPath(e
.swap_filen
, NULL
) );
348 Fs::Ufs::UFSSwapDir::doubleCheck(StoreEntry
& e
)
353 if (::stat(fullPath(e
.swap_filen
, NULL
), &sb
) < 0) {
354 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Missing swap file");
359 if ((off_t
)e
.swap_file_sz
!= sb
.st_size
) {
360 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Size Mismatch. Entry size: "
361 << e
.swap_file_sz
<< ", file size: " << sb
.st_size
);
370 Fs::Ufs::UFSSwapDir::statfs(StoreEntry
& sentry
) const
377 storeAppendPrintf(&sentry
, "First level subdirectories: %d\n", l1
);
378 storeAppendPrintf(&sentry
, "Second level subdirectories: %d\n", l2
);
379 storeAppendPrintf(&sentry
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
380 storeAppendPrintf(&sentry
, "Current Size: %.2f KB\n", currentSize() / 1024.0);
381 storeAppendPrintf(&sentry
, "Percent Used: %0.2f%%\n",
382 Math::doublePercent(currentSize(), maxSize()));
383 storeAppendPrintf(&sentry
, "Filemap bits in use: %d of %d (%d%%)\n",
384 map
->numFilesInMap(), map
->capacity(),
385 Math::intPercent(map
->numFilesInMap(), map
->capacity()));
386 x
= storeDirGetUFSStats(path
, &totl_kb
, &free_kb
, &totl_in
, &free_in
);
389 storeAppendPrintf(&sentry
, "Filesystem Space in use: %d/%d KB (%d%%)\n",
392 Math::intPercent(totl_kb
- free_kb
, totl_kb
));
393 storeAppendPrintf(&sentry
, "Filesystem Inodes in use: %d/%d (%d%%)\n",
396 Math::intPercent(totl_in
- free_in
, totl_in
));
399 storeAppendPrintf(&sentry
, "Flags:");
402 storeAppendPrintf(&sentry
, " SELECTED");
405 storeAppendPrintf(&sentry
, " READ-ONLY");
407 storeAppendPrintf(&sentry
, "\n");
413 Fs::Ufs::UFSSwapDir::maintain()
415 /* We can't delete objects while rebuilding swap */
417 /* XXX FIXME each store should start maintaining as it comes online. */
419 if (StoreController::store_dirs_rebuilding
)
422 StoreEntry
*e
= NULL
;
426 RemovalPurgeWalker
*walker
;
428 double f
= (double) (currentSize() - minSize()) / (maxSize() - minSize());
430 f
= f
< 0.0 ? 0.0 : f
> 1.0 ? 1.0 : f
;
432 int max_scan
= (int) (f
* 400.0 + 100.0);
434 int max_remove
= (int) (f
* 70.0 + 10.0);
437 * This is kinda cheap, but so we need this priority hack?
440 debugs(47, 3, HERE
<< "f=" << f
<< ", max_scan=" << max_scan
<< ", max_remove=" << max_remove
);
442 walker
= repl
->PurgeInit(repl
, max_scan
);
445 if (currentSize() < minSize())
448 if (removed
>= max_remove
)
451 e
= walker
->Next(walker
);
454 break; /* no more objects */
461 walker
->Done(walker
);
462 debugs(47, (removed
? 2 : 3), HERE
<< path
<<
463 " removed " << removed
<< "/" << max_remove
<< " f=" <<
464 std::setprecision(4) << f
<< " max_scan=" << max_scan
);
468 Fs::Ufs::UFSSwapDir::reference(StoreEntry
&e
)
470 debugs(47, 3, HERE
<< "referencing " << &e
<< " " <<
471 e
.swap_dirn
<< "/" << e
.swap_filen
);
473 if (repl
->Referenced
)
474 repl
->Referenced(repl
, &e
, &e
.repl
);
478 Fs::Ufs::UFSSwapDir::dereference(StoreEntry
& e
, bool)
480 debugs(47, 3, HERE
<< "dereferencing " << &e
<< " " <<
481 e
.swap_dirn
<< "/" << e
.swap_filen
);
483 if (repl
->Dereferenced
)
484 repl
->Dereferenced(repl
, &e
, &e
.repl
);
486 return true; // keep e in the global store_table
489 StoreIOState::Pointer
490 Fs::Ufs::UFSSwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
492 return IO
->create (this, &e
, file_callback
, aCallback
, callback_data
);
495 StoreIOState::Pointer
496 Fs::Ufs::UFSSwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
498 return IO
->open (this, &e
, file_callback
, aCallback
, callback_data
);
502 Fs::Ufs::UFSSwapDir::mapBitTest(sfileno filn
)
504 return map
->testBit(filn
);
508 Fs::Ufs::UFSSwapDir::mapBitSet(sfileno filn
)
514 Fs::Ufs::UFSSwapDir::mapBitReset(sfileno filn
)
517 * We have to test the bit before calling clearBit as
518 * it doesn't do bounds checking and blindly assumes
519 * filn is a valid file number, but it might not be because
520 * the map is dynamic in size. Also clearing an already clear
521 * bit puts the map counter of-of-whack.
524 if (map
->testBit(filn
))
529 Fs::Ufs::UFSSwapDir::mapBitAllocate()
532 fn
= map
->allocate(suggest
);
539 Fs::Ufs::UFSSwapDir::swapSubDir(int subdirn
)const
541 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
542 assert(0 <= subdirn
&& subdirn
< l1
);
543 snprintf(fullfilename
, MAXPATHLEN
, "%s/%02X", path
, subdirn
);
548 Fs::Ufs::UFSSwapDir::createDirectory(const char *aPath
, int should_exist
)
555 if (0 == ::stat(aPath
, &st
)) {
556 if (S_ISDIR(st
.st_mode
)) {
557 debugs(47, (should_exist
? 3 : DBG_IMPORTANT
), aPath
<< " exists");
559 fatalf("Swap directory %s is not a directory.", aPath
);
561 } else if (0 == mkdir(aPath
, 0755)) {
562 debugs(47, (should_exist
? DBG_IMPORTANT
: 3), aPath
<< " created");
565 fatalf("Failed to make swap directory %s: %s",
573 Fs::Ufs::UFSSwapDir::pathIsDirectory(const char *aPath
)const
578 if (::stat(aPath
, &sb
) < 0) {
579 debugs(47, DBG_CRITICAL
, "ERROR: " << aPath
<< ": " << xstrerror());
583 if (S_ISDIR(sb
.st_mode
) == 0) {
584 debugs(47, DBG_CRITICAL
, "WARNING: " << aPath
<< " is not a directory");
592 Fs::Ufs::UFSSwapDir::verifyCacheDirs()
594 if (!pathIsDirectory(path
))
597 for (int j
= 0; j
< l1
; ++j
) {
598 char const *aPath
= swapSubDir(j
);
600 if (!pathIsDirectory(aPath
))
608 Fs::Ufs::UFSSwapDir::createSwapSubDirs()
610 LOCAL_ARRAY(char, name
, MAXPATHLEN
);
612 for (int i
= 0; i
< l1
; ++i
) {
613 snprintf(name
, MAXPATHLEN
, "%s/%02X", path
, i
);
617 if (createDirectory(name
, 0))
622 debugs(47, DBG_IMPORTANT
, "Making directories in " << name
);
624 for (int k
= 0; k
< l2
; ++k
) {
625 snprintf(name
, MAXPATHLEN
, "%s/%02X/%02X", path
, i
, k
);
626 createDirectory(name
, should_exist
);
632 Fs::Ufs::UFSSwapDir::logFile(char const *ext
) const
634 LOCAL_ARRAY(char, lpath
, MAXPATHLEN
);
635 LOCAL_ARRAY(char, pathtmp
, MAXPATHLEN
);
636 LOCAL_ARRAY(char, digit
, 32);
639 if (Config
.Log
.swap
) {
640 xstrncpy(pathtmp
, path
, MAXPATHLEN
- 64);
643 while ((pathtmp2
= strchr(pathtmp2
, '/')) != NULL
)
646 while (strlen(pathtmp
) && pathtmp
[strlen(pathtmp
) - 1] == '.')
647 pathtmp
[strlen(pathtmp
) - 1] = '\0';
649 for (pathtmp2
= pathtmp
; *pathtmp2
== '.'; ++pathtmp2
);
650 snprintf(lpath
, MAXPATHLEN
- 64, Config
.Log
.swap
, pathtmp2
);
652 if (strncmp(lpath
, Config
.Log
.swap
, MAXPATHLEN
- 64) == 0) {
654 snprintf(digit
, 32, "%02d", index
);
655 strncat(lpath
, digit
, 3);
658 xstrncpy(lpath
, path
, MAXPATHLEN
- 64);
659 strcat(lpath
, "/swap.state");
663 strncat(lpath
, ext
, 16);
669 Fs::Ufs::UFSSwapDir::openLog()
673 swaplog_fd
= file_open(logPath
, O_WRONLY
| O_CREAT
| O_BINARY
);
675 if (swaplog_fd
< 0) {
676 debugs(50, DBG_IMPORTANT
, "ERROR opening swap log " << logPath
<< ": " << xstrerror());
677 fatal("UFSSwapDir::openLog: Failed to open swap log.");
680 debugs(50, 3, HERE
<< "Cache Dir #" << index
<< " log opened on FD " << swaplog_fd
);
682 if (0 == NumberOfUFSDirs
)
683 assert(NULL
== UFSDirToGlobalDirMapping
);
687 assert(NumberOfUFSDirs
<= Config
.cacheSwap
.n_configured
);
691 Fs::Ufs::UFSSwapDir::closeLog()
693 if (swaplog_fd
< 0) /* not open */
696 file_close(swaplog_fd
);
698 debugs(47, 3, "Cache Dir #" << index
<< " log closed on FD " << swaplog_fd
);
704 assert(NumberOfUFSDirs
>= 0);
706 if (0 == NumberOfUFSDirs
)
707 safe_free(UFSDirToGlobalDirMapping
);
711 Fs::Ufs::UFSSwapDir::validL1(int anInt
) const
717 Fs::Ufs::UFSSwapDir::validL2(int anInt
) const
723 Fs::Ufs::UFSSwapDir::addDiskRestore(const cache_key
* key
,
725 uint64_t swap_file_sz
,
734 StoreEntry
*e
= NULL
;
735 debugs(47, 5, HERE
<< storeKeyText(key
) <<
736 ", fileno="<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << file_number
);
737 /* if you call this you'd better be sure file_number is not
739 e
= new StoreEntry();
740 e
->store_status
= STORE_OK
;
741 e
->setMemStatus(NOT_IN_MEMORY
);
742 e
->swap_status
= SWAPOUT_DONE
;
743 e
->swap_filen
= file_number
;
744 e
->swap_dirn
= index
;
745 e
->swap_file_sz
= swap_file_sz
;
746 e
->lastref
= lastref
;
747 e
->timestamp
= timestamp
;
748 e
->expires
= expires
;
749 e
->lastmod
= lastmod
;
750 e
->refcount
= refcount
;
752 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
753 EBIT_CLR(e
->flags
, KEY_PRIVATE
);
754 e
->ping_status
= PING_NONE
;
755 EBIT_CLR(e
->flags
, ENTRY_VALIDATED
);
756 mapBitSet(e
->swap_filen
);
757 cur_size
+= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
759 e
->hashInsert(key
); /* do it after we clear KEY_PRIVATE */
765 Fs::Ufs::UFSSwapDir::undoAddDiskRestore(StoreEntry
*e
)
767 debugs(47, 5, HERE
<< *e
);
768 replacementRemove(e
); // checks swap_dirn so do it before we invalidate it
769 // Do not unlink the file as it might be used by a subsequent entry.
770 mapBitReset(e
->swap_filen
);
773 cur_size
-= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
778 Fs::Ufs::UFSSwapDir::rebuild()
780 ++StoreController::store_dirs_rebuilding
;
781 eventAdd("storeRebuild", Fs::Ufs::RebuildState::RebuildStep
, new Fs::Ufs::RebuildState(this), 0.0, 1);
785 Fs::Ufs::UFSSwapDir::closeTmpSwapLog()
787 char *swaplog_path
= xstrdup(logFile(NULL
)); // where the swaplog should be
788 char *tmp_path
= xstrdup(logFile(".new")); // the temporary file we have generated
790 file_close(swaplog_fd
);
792 if (xrename(tmp_path
, swaplog_path
) < 0) {
793 fatalf("Failed to rename log file %s to %s", tmp_path
, swaplog_path
);
796 fd
= file_open(swaplog_path
, O_WRONLY
| O_CREAT
| O_BINARY
);
799 debugs(50, DBG_IMPORTANT
, "ERROR: " << swaplog_path
<< ": " << xstrerror());
800 fatalf("Failed to open swap log %s", swaplog_path
);
806 debugs(47, 3, "Cache Dir #" << index
<< " log opened on FD " << fd
);
810 Fs::Ufs::UFSSwapDir::openTmpSwapLog(int *clean_flag
, int *zero_flag
)
812 char *swaplog_path
= xstrdup(logFile(NULL
));
813 char *clean_path
= xstrdup(logFile(".last-clean"));
814 char *new_path
= xstrdup(logFile(".new"));
818 struct stat clean_sb
;
822 if (::stat(swaplog_path
, &log_sb
) < 0) {
823 debugs(47, DBG_IMPORTANT
, "Cache Dir #" << index
<< ": No log file");
824 safe_free(swaplog_path
);
825 safe_free(clean_path
);
830 *zero_flag
= log_sb
.st_size
== 0 ? 1 : 0;
831 /* close the existing write-only FD */
834 file_close(swaplog_fd
);
836 /* open a write-only FD for the new log */
837 fd
= file_open(new_path
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
840 debugs(50, DBG_IMPORTANT
, "ERROR: while opening swap log" << new_path
<< ": " << xstrerror());
841 fatalf("Failed to open swap log %s", new_path
);
847 const StoreSwapLogHeader header
;
849 buf
.init(header
.record_size
, header
.record_size
);
850 buf
.append(reinterpret_cast<const char*>(&header
), sizeof(header
));
851 // Pad to keep in sync with UFSSwapDir::writeCleanStart().
852 memset(buf
.space(), 0, header
.gapSize());
853 buf
.appended(header
.gapSize());
854 file_write(swaplog_fd
, -1, buf
.content(), buf
.contentSize(),
855 NULL
, NULL
, buf
.freeFunc());
858 /* open a read-only stream of the old log */
859 fp
= fopen(swaplog_path
, "rb");
862 debugs(50, DBG_CRITICAL
, "ERROR: while opening " << swaplog_path
<< ": " << xstrerror());
863 fatalf("Failed to open swap log for reading %s", swaplog_path
);
866 memset(&clean_sb
, '\0', sizeof(struct stat
));
868 if (::stat(clean_path
, &clean_sb
) < 0)
870 else if (clean_sb
.st_mtime
< log_sb
.st_mtime
)
875 safeunlink(clean_path
, 1);
877 safe_free(swaplog_path
);
879 safe_free(clean_path
);
887 * Begin the process to write clean cache state. For AUFS this means
888 * opening some log files and allocating write buffers. Return 0 if
889 * we succeed, and assign the 'func' and 'data' return pointers.
892 Fs::Ufs::UFSSwapDir::writeCleanStart()
894 UFSCleanLog
*state
= new UFSCleanLog(this);
895 StoreSwapLogHeader header
;
902 state
->newLog
= xstrdup(logFile(".clean"));
903 state
->fd
= file_open(state
->newLog
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
906 xfree(state
->newLog
);
911 state
->cur
= xstrdup(logFile(NULL
));
912 state
->cln
= xstrdup(logFile(".last-clean"));
913 state
->outbuf
= (char *)xcalloc(CLEAN_BUF_SZ
, 1);
914 state
->outbuf_offset
= 0;
916 memcpy(state
->outbuf
, &header
, sizeof(StoreSwapLogHeader
));
917 // Leave a gap to keep in sync with UFSSwapDir::openTmpSwapLog().
918 memset(state
->outbuf
+ sizeof(StoreSwapLogHeader
), 0, header
.gapSize());
919 state
->outbuf_offset
+= header
.record_size
;
921 state
->walker
= repl
->WalkInit(repl
);
922 ::unlink(state
->cln
);
923 debugs(47, 3, HERE
<< "opened " << state
->newLog
<< ", FD " << state
->fd
);
926 if (::stat(state
->cur
, &sb
) == 0)
927 fchmod(state
->fd
, sb
.st_mode
);
936 Fs::Ufs::UFSSwapDir::writeCleanDone()
938 UFSCleanLog
*state
= (UFSCleanLog
*)cleanLog
;
947 state
->walker
->Done(state
->walker
);
949 if (FD_WRITE_METHOD(state
->fd
, state
->outbuf
, state
->outbuf_offset
) < 0) {
950 debugs(50, DBG_CRITICAL
, HERE
<< state
->newLog
<< ": write: " << xstrerror());
951 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
952 file_close(state
->fd
);
954 ::unlink(state
->newLog
);
957 safe_free(state
->outbuf
);
959 * You can't rename open files on Microsoft "operating systems"
960 * so we have to close before renaming.
963 /* save the fd value for a later test */
967 if (state
->fd
>= 0) {
968 #if _SQUID_OS2_ || _SQUID_WINDOWS_
969 file_close(state
->fd
);
973 xrename(state
->newLog
, state
->cur
);
976 /* touch a timestamp file if we're not still validating */
977 if (StoreController::store_dirs_rebuilding
)
982 file_close(file_open(state
->cln
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
));
985 safe_free(state
->cur
);
987 safe_free(state
->newLog
);
989 safe_free(state
->cln
);
992 file_close(state
->fd
);
1002 Fs::Ufs::UFSSwapDir::CleanEvent(void *)
1004 static int swap_index
= 0;
1009 * Assert that there are UFS cache_dirs configured, otherwise
1010 * we should never be called.
1012 assert(NumberOfUFSDirs
);
1014 if (NULL
== UFSDirToGlobalDirMapping
) {
1017 * Initialize the little array that translates UFS cache_dir
1018 * number into the Config.cacheSwap.swapDirs array index.
1020 UFSDirToGlobalDirMapping
= (int *)xcalloc(NumberOfUFSDirs
, sizeof(*UFSDirToGlobalDirMapping
));
1022 for (i
= 0, n
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1023 /* This is bogus, the controller should just clean each instance once */
1024 sd
= dynamic_cast <SwapDir
*>(INDEXSD(i
));
1026 if (!UFSSwapDir::IsUFSDir(sd
))
1029 UFSSwapDir
*usd
= dynamic_cast<UFSSwapDir
*>(sd
);
1033 UFSDirToGlobalDirMapping
[n
] = i
;
1036 j
+= (usd
->l1
* usd
->l2
);
1039 assert(n
== NumberOfUFSDirs
);
1041 * Start the commonUfsDirClean() swap_index with a random
1042 * value. j equals the total number of UFS level 2
1045 swap_index
= (int) (squid_random() % j
);
1048 /* if the rebuild is finished, start cleaning directories. */
1049 if (0 == StoreController::store_dirs_rebuilding
) {
1050 n
= DirClean(swap_index
);
1054 eventAdd("storeDirClean", CleanEvent
, NULL
,
1055 15.0 * exp(-0.25 * n
), 1);
1059 Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir
* sd
)
1061 UFSSwapDir
*mySD
= dynamic_cast<UFSSwapDir
*>(sd
);
1062 return (mySD
!= 0) ;
1066 * XXX: this is broken - it assumes all cache dirs use the same
1067 * l1 and l2 scheme. -RBC 20021215. Partial fix is in place -
1068 * if not UFSSwapDir return 0;
1071 Fs::Ufs::UFSSwapDir::FilenoBelongsHere(int fn
, int F0
, int F1
, int F2
)
1076 assert(F0
< Config
.cacheSwap
.n_configured
);
1077 assert (UFSSwapDir::IsUFSDir (dynamic_cast<SwapDir
*>(INDEXSD(F0
))));
1078 UFSSwapDir
*sd
= dynamic_cast<UFSSwapDir
*>(INDEXSD(F0
));
1087 D1
= ((filn
/ L2
) / L2
) % L1
;
1092 D2
= (filn
/ L2
) % L2
;
1101 Fs::Ufs::UFSSwapDir::validFileno(sfileno filn
, int flag
) const
1107 * If flag is set it means out-of-range file number should
1108 * be considered invalid.
1111 if (filn
> map
->capacity())
1118 Fs::Ufs::UFSSwapDir::unlinkFile(sfileno f
)
1120 debugs(79, 3, HERE
<< "unlinking fileno " << std::setfill('0') <<
1121 std::hex
<< std::uppercase
<< std::setw(8) << f
<< " '" <<
1122 fullPath(f
,NULL
) << "'");
1123 /* commonUfsDirMapBitReset(this, f); */
1124 IO
->unlinkFile(fullPath(f
,NULL
));
1128 Fs::Ufs::UFSSwapDir::unlinkdUseful() const
1130 // unlinkd may be useful only in workers
1131 return IamWorkerProcess() && IO
->io
->unlinkdUseful();
1135 Fs::Ufs::UFSSwapDir::unlink(StoreEntry
& e
)
1137 debugs(79, 3, HERE
<< "dirno " << index
<< ", fileno "<<
1138 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
1139 if (e
.swap_status
== SWAPOUT_DONE
) {
1140 cur_size
-= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1143 replacementRemove(&e
);
1144 mapBitReset(e
.swap_filen
);
1145 UFSSwapDir::unlinkFile(e
.swap_filen
);
1149 Fs::Ufs::UFSSwapDir::replacementAdd(StoreEntry
* e
)
1151 debugs(47, 4, HERE
<< "added node " << e
<< " to dir " << index
);
1152 repl
->Add(repl
, e
, &e
->repl
);
1156 Fs::Ufs::UFSSwapDir::replacementRemove(StoreEntry
* e
)
1160 if (e
->swap_dirn
< 0)
1163 SD
= INDEXSD(e
->swap_dirn
);
1165 assert (dynamic_cast<UFSSwapDir
*>(SD
.getRaw()) == this);
1167 debugs(47, 4, HERE
<< "remove node " << e
<< " from dir " << index
);
1169 repl
->Remove(repl
, e
, &e
->repl
);
1173 Fs::Ufs::UFSSwapDir::dump(StoreEntry
& entry
) const
1175 storeAppendPrintf(&entry
, " %" PRIu64
" %d %d", maxSize() >> 20, l1
, l2
);
1176 dumpOptions(&entry
);
1180 Fs::Ufs::UFSSwapDir::fullPath(sfileno filn
, char *fullpath
) const
1182 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
1187 fullpath
= fullfilename
;
1191 snprintf(fullpath
, MAXPATHLEN
, "%s/%02X/%02X/%08X",
1193 ((filn
/ L2
) / L2
) % L1
,
1201 Fs::Ufs::UFSSwapDir::callback()
1203 return IO
->callback();
1207 Fs::Ufs::UFSSwapDir::sync()
1213 Fs::Ufs::UFSSwapDir::swappedOut(const StoreEntry
&e
)
1215 cur_size
+= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1220 Fs::Ufs::UFSSwapDir::search(String
const url
, HttpRequest
*)
1223 fatal ("Cannot search by url yet\n");
1225 return new Fs::Ufs::StoreSearchUFS (this);
1229 Fs::Ufs::UFSSwapDir::logEntry(const StoreEntry
& e
, int op
) const
1231 StoreSwapLogData
*s
= new StoreSwapLogData
;
1233 s
->swap_filen
= e
.swap_filen
;
1234 s
->timestamp
= e
.timestamp
;
1235 s
->lastref
= e
.lastref
;
1236 s
->expires
= e
.expires
;
1237 s
->lastmod
= e
.lastmod
;
1238 s
->swap_file_sz
= e
.swap_file_sz
;
1239 s
->refcount
= e
.refcount
;
1241 memcpy(s
->key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
1243 file_write(swaplog_fd
,
1246 sizeof(StoreSwapLogData
),
1253 Fs::Ufs::UFSSwapDir::DirClean(int swap_index
)
1255 DIR *dir_pointer
= NULL
;
1257 LOCAL_ARRAY(char, p1
, MAXPATHLEN
+ 1);
1258 LOCAL_ARRAY(char, p2
, MAXPATHLEN
+ 1);
1262 int fn
; /* same as swapfileno, but with dirn bits set */
1268 N0
= NumberOfUFSDirs
;
1269 D0
= UFSDirToGlobalDirMapping
[swap_index
% N0
];
1270 SD
= dynamic_cast<UFSSwapDir
*>(INDEXSD(D0
));
1273 D1
= (swap_index
/ N0
) % N1
;
1275 D2
= ((swap_index
/ N0
) / N1
) % N2
;
1276 snprintf(p1
, MAXPATHLEN
, "%s/%02X/%02X",
1278 debugs(36, 3, HERE
<< "Cleaning directory " << p1
);
1279 dir_pointer
= opendir(p1
);
1281 if (dir_pointer
== NULL
) {
1282 if (errno
== ENOENT
) {
1283 debugs(36, DBG_CRITICAL
, HERE
<< "WARNING: Creating " << p1
);
1284 if (mkdir(p1
, 0777) == 0)
1288 debugs(50, DBG_CRITICAL
, HERE
<< p1
<< ": " << xstrerror());
1294 while ((de
= readdir(dir_pointer
)) != NULL
&& k
< 20) {
1295 if (sscanf(de
->d_name
, "%X", &swapfileno
) != 1)
1298 fn
= swapfileno
; /* XXX should remove this cruft ! */
1300 if (SD
->validFileno(fn
, 1))
1301 if (SD
->mapBitTest(fn
))
1302 if (UFSSwapDir::FilenoBelongsHere(fn
, D0
, D1
, D2
))
1305 files
[k
] = swapfileno
;
1309 closedir(dir_pointer
);
1314 qsort(files
, k
, sizeof(int), rev_int_sort
);
1319 for (n
= 0; n
< k
; ++n
) {
1320 debugs(36, 3, HERE
<< "Cleaning file "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << files
[n
]);
1321 snprintf(p2
, MAXPATHLEN
+ 1, "%s/%08X", p1
, files
[n
]);
1323 ++statCounter
.swap
.files_cleaned
;
1326 debugs(36, 3, HERE
<< "Cleaned " << k
<< " unused files from " << p1
);