2 * DEBUG: section 47 Store Directory Routines
3 * AUTHOR: Robert Collins
5 * SQUID Web Proxy Cache http://www.squid-cache.org/
6 * ----------------------------------------------------------
8 * Squid is the result of efforts by numerous individuals from
9 * the Internet community; see the CONTRIBUTORS file for full
10 * details. Many organizations have provided support for Squid's
11 * development; see the SPONSORS file for full details. Squid is
12 * Copyrighted (C) 2001 by the Regents of the University of
13 * California; see the COPYRIGHT file for full details. Squid
14 * incorporates software developed and/or copyrighted by other
15 * sources; see the CREDITS file for full details.
17 * This program is free software; you can redistribute it and/or modify
18 * it under the terms of the GNU General Public License as published by
19 * the Free Software Foundation; either version 2 of the License, or
20 * (at your option) any later version.
22 * This program is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, write to the Free Software
29 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
34 #define CLEAN_BUF_SZ 16384
36 #include "ConfigOption.h"
37 #include "DiskIO/DiskIOModule.h"
42 #include "RebuildState.h"
43 #include "SquidMath.h"
44 #include "DiskIO/DiskIOStrategy.h"
45 #include "StoreSearchUFS.h"
46 #include "StoreSwapLogData.h"
47 #include "SquidTime.h"
48 #include "StatCounters.h"
49 #include "UFSSwapDir.h"
61 int Fs::Ufs::UFSSwapDir::NumberOfUFSDirs
= 0;
62 int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping
= NULL
;
64 class UFSCleanLog
: public SwapDir::CleanLog
68 UFSCleanLog(SwapDir
*);
69 /** Get the next entry that is a candidate for clean log writing
71 virtual const StoreEntry
*nextEntry();
72 /** "write" an entry to the clean log file.
74 virtual void write(StoreEntry
const &);
81 RemovalPolicyWalker
*walker
;
85 UFSCleanLog::UFSCleanLog(SwapDir
*aSwapDir
) :
86 cur(NULL
), newLog(NULL
), cln(NULL
), outbuf(NULL
),
87 outbuf_offset(0), fd(-1),walker(NULL
), sd(aSwapDir
)
91 UFSCleanLog::nextEntry()
93 const StoreEntry
*entry
= NULL
;
96 entry
= walker
->Next(walker
);
102 UFSCleanLog::write(StoreEntry
const &e
)
105 static size_t ss
= sizeof(StoreSwapLogData
);
106 s
.op
= (char) SWAP_LOG_ADD
;
107 s
.swap_filen
= e
.swap_filen
;
108 s
.timestamp
= e
.timestamp
;
109 s
.lastref
= e
.lastref
;
110 s
.expires
= e
.expires
;
111 s
.lastmod
= e
.lastmod
;
112 s
.swap_file_sz
= e
.swap_file_sz
;
113 s
.refcount
= e
.refcount
;
115 memcpy(&s
.key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
117 memcpy(outbuf
+ outbuf_offset
, &s
, ss
);
121 if (outbuf_offset
+ ss
>= CLEAN_BUF_SZ
) {
122 if (FD_WRITE_METHOD(fd
, outbuf
, outbuf_offset
) < 0) {
123 /* XXX This error handling should probably move up to the caller */
124 debugs(50, DBG_CRITICAL
, HERE
<< newLog
<< ": write: " << xstrerror());
125 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
139 Fs::Ufs::UFSSwapDir::canStore(const StoreEntry
&e
, int64_t diskSpaceNeeded
, int &load
) const
141 if (!SwapDir::canStore(e
, diskSpaceNeeded
, load
))
152 FreeObject(void *address
)
154 StoreSwapLogData
*anObject
= static_cast <StoreSwapLogData
*>(address
);
158 static QS rev_int_sort
;
160 rev_int_sort(const void *A
, const void *B
)
162 const int *i1
= (const int *)A
;
163 const int *i2
= (const int *)B
;
168 Fs::Ufs::UFSSwapDir::parseSizeL1L2()
170 int i
= GetInteger();
172 fatal("UFSSwapDir::parseSizeL1L2: invalid size value");
174 const uint64_t size
= static_cast<uint64_t>(i
) << 20; // MBytes to Bytes
176 /* just reconfigure it */
178 if (size
== maxSize())
179 debugs(3, 2, "Cache dir '" << path
<< "' size remains unchanged at " << i
<< " MB");
181 debugs(3, DBG_IMPORTANT
, "Cache dir '" << path
<< "' size changed to " << i
<< " MB");
189 fatal("UFSSwapDir::parseSizeL1L2: invalid level 1 directories value");
194 fatal("UFSSwapDir::parseSizeL1L2: invalid level 2 directories value");
198 Fs::Ufs::UFSSwapDir::reconfigure()
205 Fs::Ufs::UFSSwapDir::parse (int anIndex
, char *aPath
)
208 path
= xstrdup(aPath
);
212 /* Initialise replacement policy stuff */
213 repl
= createRemovalPolicy(Config
.replPolicy
);
219 Fs::Ufs::UFSSwapDir::changeIO(DiskIOModule
*module
)
221 DiskIOStrategy
*anIO
= module
->createStrategy();
223 ioType
= xstrdup(module
->type());
227 /* Change the IO Options */
229 if (currentIOOptions
&& currentIOOptions
->options
.size() > 2)
230 delete currentIOOptions
->options
.pop_back();
232 /* TODO: factor out these 4 lines */
233 ConfigOption
*ioOptions
= IO
->io
->getOptionTree();
236 currentIOOptions
->options
.push_back(ioOptions
);
240 Fs::Ufs::UFSSwapDir::optionIOParse(char const *option
, const char *value
, int isaReconfig
)
242 if (strcmp(option
, "IOEngine") != 0)
246 /* silently ignore this */
252 DiskIOModule
*module
= DiskIOModule::Find(value
);
263 Fs::Ufs::UFSSwapDir::optionIODump(StoreEntry
* e
) const
265 storeAppendPrintf(e
, " IOEngine=%s", ioType
);
269 Fs::Ufs::UFSSwapDir::getOptionTree() const
271 ConfigOption
*parentResult
= SwapDir::getOptionTree();
273 if (currentIOOptions
== NULL
)
274 currentIOOptions
= new ConfigOptionVector();
276 currentIOOptions
->options
.push_back(parentResult
);
278 currentIOOptions
->options
.push_back(new ConfigOptionAdapter
<UFSSwapDir
>(*const_cast<UFSSwapDir
*>(this), &UFSSwapDir::optionIOParse
, &UFSSwapDir::optionIODump
));
280 if (ConfigOption
*ioOptions
= IO
->io
->getOptionTree())
281 currentIOOptions
->options
.push_back(ioOptions
);
283 ConfigOption
* result
= currentIOOptions
;
285 currentIOOptions
= NULL
;
291 Fs::Ufs::UFSSwapDir::init()
293 debugs(47, 3, HERE
<< "Initialising UFS SwapDir engine.");
294 /* Parsing must be finished by now - force to NULL, don't delete */
295 currentIOOptions
= NULL
;
296 static int started_clean_event
= 0;
297 static const char *errmsg
=
298 "\tFailed to verify one of the swap directories, Check cache.log\n"
299 "\tfor details. Run 'squid -z' to create swap directories\n"
300 "\tif needed, or if running Squid for the first time.";
303 if (verifyCacheDirs())
310 if (!started_clean_event
) {
311 eventAdd("UFS storeDirClean", CleanEvent
, NULL
, 15.0, 1);
312 started_clean_event
= 1;
315 (void) storeDirGetBlkSize(path
, &fs
.blksize
);
319 Fs::Ufs::UFSSwapDir::create()
321 debugs(47, 3, "Creating swap space in " << path
);
322 createDirectory(path
, 0);
326 Fs::Ufs::UFSSwapDir::UFSSwapDir(char const *aType
, const char *anIOType
) : SwapDir(aType
), IO(NULL
), map(new FileMap()), suggest(0), swaplog_fd (-1), currentIOOptions(new ConfigOptionVector()), ioType(xstrdup(anIOType
)), cur_size(0), n_disk_objects(0)
328 /* modulename is only set to disk modules that are built, by configure,
329 * so the Find call should never return NULL here.
331 IO
= new Fs::Ufs::UFSStrategy(DiskIOModule::Find(anIOType
)->createStrategy());
334 Fs::Ufs::UFSSwapDir::~UFSSwapDir()
336 if (swaplog_fd
> -1) {
337 file_close(swaplog_fd
);
352 Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry
&e
) const
354 debugs(47, DBG_CRITICAL
, HERE
<< "FILENO "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
355 debugs(47, DBG_CRITICAL
, HERE
<< "PATH " << fullPath(e
.swap_filen
, NULL
) );
360 Fs::Ufs::UFSSwapDir::doubleCheck(StoreEntry
& e
)
365 if (::stat(fullPath(e
.swap_filen
, NULL
), &sb
) < 0) {
366 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Missing swap file");
371 if ((off_t
)e
.swap_file_sz
!= sb
.st_size
) {
372 debugs(47, DBG_CRITICAL
, HERE
<< "WARNING: Size Mismatch. Entry size: "
373 << e
.swap_file_sz
<< ", file size: " << sb
.st_size
);
382 Fs::Ufs::UFSSwapDir::statfs(StoreEntry
& sentry
) const
389 storeAppendPrintf(&sentry
, "First level subdirectories: %d\n", l1
);
390 storeAppendPrintf(&sentry
, "Second level subdirectories: %d\n", l2
);
391 storeAppendPrintf(&sentry
, "Maximum Size: %" PRIu64
" KB\n", maxSize() >> 10);
392 storeAppendPrintf(&sentry
, "Current Size: %.2f KB\n", currentSize() / 1024.0);
393 storeAppendPrintf(&sentry
, "Percent Used: %0.2f%%\n",
394 Math::doublePercent(currentSize(), maxSize()));
395 storeAppendPrintf(&sentry
, "Filemap bits in use: %d of %d (%d%%)\n",
396 map
->numFilesInMap(), map
->capacity(),
397 Math::intPercent(map
->numFilesInMap(), map
->capacity()));
398 x
= storeDirGetUFSStats(path
, &totl_kb
, &free_kb
, &totl_in
, &free_in
);
401 storeAppendPrintf(&sentry
, "Filesystem Space in use: %d/%d KB (%d%%)\n",
404 Math::intPercent(totl_kb
- free_kb
, totl_kb
));
405 storeAppendPrintf(&sentry
, "Filesystem Inodes in use: %d/%d (%d%%)\n",
408 Math::intPercent(totl_in
- free_in
, totl_in
));
411 storeAppendPrintf(&sentry
, "Flags:");
414 storeAppendPrintf(&sentry
, " SELECTED");
417 storeAppendPrintf(&sentry
, " READ-ONLY");
419 storeAppendPrintf(&sentry
, "\n");
425 Fs::Ufs::UFSSwapDir::maintain()
427 /* We can't delete objects while rebuilding swap */
429 /* XXX FIXME each store should start maintaining as it comes online. */
431 if (StoreController::store_dirs_rebuilding
)
434 StoreEntry
*e
= NULL
;
438 RemovalPurgeWalker
*walker
;
440 double f
= (double) (currentSize() - minSize()) / (maxSize() - minSize());
442 f
= f
< 0.0 ? 0.0 : f
> 1.0 ? 1.0 : f
;
444 int max_scan
= (int) (f
* 400.0 + 100.0);
446 int max_remove
= (int) (f
* 70.0 + 10.0);
449 * This is kinda cheap, but so we need this priority hack?
452 debugs(47, 3, HERE
<< "f=" << f
<< ", max_scan=" << max_scan
<< ", max_remove=" << max_remove
);
454 walker
= repl
->PurgeInit(repl
, max_scan
);
457 if (currentSize() < minSize())
460 if (removed
>= max_remove
)
463 e
= walker
->Next(walker
);
466 break; /* no more objects */
473 walker
->Done(walker
);
474 debugs(47, (removed
? 2 : 3), HERE
<< path
<<
475 " removed " << removed
<< "/" << max_remove
<< " f=" <<
476 std::setprecision(4) << f
<< " max_scan=" << max_scan
);
480 Fs::Ufs::UFSSwapDir::reference(StoreEntry
&e
)
482 debugs(47, 3, HERE
<< "referencing " << &e
<< " " <<
483 e
.swap_dirn
<< "/" << e
.swap_filen
);
485 if (repl
->Referenced
)
486 repl
->Referenced(repl
, &e
, &e
.repl
);
490 Fs::Ufs::UFSSwapDir::dereference(StoreEntry
& e
)
492 debugs(47, 3, HERE
<< "dereferencing " << &e
<< " " <<
493 e
.swap_dirn
<< "/" << e
.swap_filen
);
495 if (repl
->Dereferenced
)
496 repl
->Dereferenced(repl
, &e
, &e
.repl
);
498 return true; // keep e in the global store_table
501 StoreIOState::Pointer
502 Fs::Ufs::UFSSwapDir::createStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
504 return IO
->create (this, &e
, file_callback
, aCallback
, callback_data
);
507 StoreIOState::Pointer
508 Fs::Ufs::UFSSwapDir::openStoreIO(StoreEntry
&e
, StoreIOState::STFNCB
* file_callback
, StoreIOState::STIOCB
* aCallback
, void *callback_data
)
510 return IO
->open (this, &e
, file_callback
, aCallback
, callback_data
);
514 Fs::Ufs::UFSSwapDir::mapBitTest(sfileno filn
)
516 return map
->testBit(filn
);
520 Fs::Ufs::UFSSwapDir::mapBitSet(sfileno filn
)
526 Fs::Ufs::UFSSwapDir::mapBitReset(sfileno filn
)
529 * We have to test the bit before calling clearBit as
530 * it doesn't do bounds checking and blindly assumes
531 * filn is a valid file number, but it might not be because
532 * the map is dynamic in size. Also clearing an already clear
533 * bit puts the map counter of-of-whack.
536 if (map
->testBit(filn
))
541 Fs::Ufs::UFSSwapDir::mapBitAllocate()
544 fn
= map
->allocate(suggest
);
551 Fs::Ufs::UFSSwapDir::swapSubDir(int subdirn
)const
553 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
554 assert(0 <= subdirn
&& subdirn
< l1
);
555 snprintf(fullfilename
, MAXPATHLEN
, "%s/%02X", path
, subdirn
);
560 Fs::Ufs::UFSSwapDir::createDirectory(const char *aPath
, int should_exist
)
567 if (0 == ::stat(aPath
, &st
)) {
568 if (S_ISDIR(st
.st_mode
)) {
569 debugs(47, (should_exist
? 3 : DBG_IMPORTANT
), aPath
<< " exists");
571 fatalf("Swap directory %s is not a directory.", aPath
);
576 } else if (0 == mkdir(aPath
)) {
579 } else if (0 == mkdir(aPath
, 0755)) {
581 debugs(47, (should_exist
? DBG_IMPORTANT
: 3), aPath
<< " created");
584 fatalf("Failed to make swap directory %s: %s",
592 Fs::Ufs::UFSSwapDir::pathIsDirectory(const char *aPath
)const
597 if (::stat(aPath
, &sb
) < 0) {
598 debugs(47, DBG_CRITICAL
, "ERROR: " << aPath
<< ": " << xstrerror());
602 if (S_ISDIR(sb
.st_mode
) == 0) {
603 debugs(47, DBG_CRITICAL
, "WARNING: " << aPath
<< " is not a directory");
611 Fs::Ufs::UFSSwapDir::verifyCacheDirs()
613 if (!pathIsDirectory(path
))
616 for (int j
= 0; j
< l1
; ++j
) {
617 char const *aPath
= swapSubDir(j
);
619 if (!pathIsDirectory(aPath
))
627 Fs::Ufs::UFSSwapDir::createSwapSubDirs()
629 LOCAL_ARRAY(char, name
, MAXPATHLEN
);
631 for (int i
= 0; i
< l1
; ++i
) {
632 snprintf(name
, MAXPATHLEN
, "%s/%02X", path
, i
);
636 if (createDirectory(name
, 0))
641 debugs(47, DBG_IMPORTANT
, "Making directories in " << name
);
643 for (int k
= 0; k
< l2
; ++k
) {
644 snprintf(name
, MAXPATHLEN
, "%s/%02X/%02X", path
, i
, k
);
645 createDirectory(name
, should_exist
);
651 Fs::Ufs::UFSSwapDir::logFile(char const *ext
) const
653 LOCAL_ARRAY(char, lpath
, MAXPATHLEN
);
654 LOCAL_ARRAY(char, pathtmp
, MAXPATHLEN
);
655 LOCAL_ARRAY(char, digit
, 32);
658 if (Config
.Log
.swap
) {
659 xstrncpy(pathtmp
, path
, MAXPATHLEN
- 64);
662 while ((pathtmp2
= strchr(pathtmp2
, '/')) != NULL
)
665 while (strlen(pathtmp
) && pathtmp
[strlen(pathtmp
) - 1] == '.')
666 pathtmp
[strlen(pathtmp
) - 1] = '\0';
668 for (pathtmp2
= pathtmp
; *pathtmp2
== '.'; ++pathtmp2
);
669 snprintf(lpath
, MAXPATHLEN
- 64, Config
.Log
.swap
, pathtmp2
);
671 if (strncmp(lpath
, Config
.Log
.swap
, MAXPATHLEN
- 64) == 0) {
673 snprintf(digit
, 32, "%02d", index
);
674 strncat(lpath
, digit
, 3);
677 xstrncpy(lpath
, path
, MAXPATHLEN
- 64);
678 strcat(lpath
, "/swap.state");
682 strncat(lpath
, ext
, 16);
688 Fs::Ufs::UFSSwapDir::openLog()
692 swaplog_fd
= file_open(logPath
, O_WRONLY
| O_CREAT
| O_BINARY
);
694 if (swaplog_fd
< 0) {
695 debugs(50, DBG_IMPORTANT
, "ERROR opening swap log " << logPath
<< ": " << xstrerror());
696 fatal("UFSSwapDir::openLog: Failed to open swap log.");
699 debugs(50, 3, HERE
<< "Cache Dir #" << index
<< " log opened on FD " << swaplog_fd
);
701 if (0 == NumberOfUFSDirs
)
702 assert(NULL
== UFSDirToGlobalDirMapping
);
706 assert(NumberOfUFSDirs
<= Config
.cacheSwap
.n_configured
);
710 Fs::Ufs::UFSSwapDir::closeLog()
712 if (swaplog_fd
< 0) /* not open */
715 file_close(swaplog_fd
);
717 debugs(47, 3, "Cache Dir #" << index
<< " log closed on FD " << swaplog_fd
);
723 assert(NumberOfUFSDirs
>= 0);
725 if (0 == NumberOfUFSDirs
)
726 safe_free(UFSDirToGlobalDirMapping
);
730 Fs::Ufs::UFSSwapDir::validL1(int anInt
) const
736 Fs::Ufs::UFSSwapDir::validL2(int anInt
) const
742 Fs::Ufs::UFSSwapDir::addDiskRestore(const cache_key
* key
,
744 uint64_t swap_file_sz
,
753 StoreEntry
*e
= NULL
;
754 debugs(47, 5, HERE
<< storeKeyText(key
) <<
755 ", fileno="<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << file_number
);
756 /* if you call this you'd better be sure file_number is not
758 e
= new StoreEntry();
759 e
->store_status
= STORE_OK
;
760 e
->setMemStatus(NOT_IN_MEMORY
);
761 e
->swap_status
= SWAPOUT_DONE
;
762 e
->swap_filen
= file_number
;
763 e
->swap_dirn
= index
;
764 e
->swap_file_sz
= swap_file_sz
;
766 e
->lastref
= lastref
;
767 e
->timestamp
= timestamp
;
768 e
->expires
= expires
;
769 e
->lastmod
= lastmod
;
770 e
->refcount
= refcount
;
772 EBIT_SET(e
->flags
, ENTRY_CACHABLE
);
773 EBIT_CLR(e
->flags
, RELEASE_REQUEST
);
774 EBIT_CLR(e
->flags
, KEY_PRIVATE
);
775 e
->ping_status
= PING_NONE
;
776 EBIT_CLR(e
->flags
, ENTRY_VALIDATED
);
777 mapBitSet(e
->swap_filen
);
778 cur_size
+= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
780 e
->hashInsert(key
); /* do it after we clear KEY_PRIVATE */
786 Fs::Ufs::UFSSwapDir::undoAddDiskRestore(StoreEntry
*e
)
788 debugs(47, 5, HERE
<< *e
);
789 replacementRemove(e
); // checks swap_dirn so do it before we invalidate it
790 // Do not unlink the file as it might be used by a subsequent entry.
791 mapBitReset(e
->swap_filen
);
794 cur_size
-= fs
.blksize
* sizeInBlocks(e
->swap_file_sz
);
799 Fs::Ufs::UFSSwapDir::rebuild()
801 ++StoreController::store_dirs_rebuilding
;
802 eventAdd("storeRebuild", Fs::Ufs::RebuildState::RebuildStep
, new Fs::Ufs::RebuildState(this), 0.0, 1);
806 Fs::Ufs::UFSSwapDir::closeTmpSwapLog()
808 char *swaplog_path
= xstrdup(logFile(NULL
));
809 char *new_path
= xstrdup(logFile(".new"));
811 file_close(swaplog_fd
);
813 if (xrename(new_path
, swaplog_path
) < 0) {
814 debugs(50, DBG_IMPORTANT
, HERE
<< "ERROR: " << swaplog_path
<< ": " << xstrerror());
815 fatalf("Failed to rename log file %s to %s.new", swaplog_path
, swaplog_path
);
818 fd
= file_open(swaplog_path
, O_WRONLY
| O_CREAT
| O_BINARY
);
821 debugs(50, DBG_IMPORTANT
, HERE
<< "ERROR: " << swaplog_path
<< ": " << xstrerror());
822 fatalf("Failed to open swap log %s", swaplog_path
);
825 safe_free(swaplog_path
);
828 debugs(47, 3, HERE
<< "Cache Dir #" << index
<< " log opened on FD " << fd
);
832 Fs::Ufs::UFSSwapDir::openTmpSwapLog(int *clean_flag
, int *zero_flag
)
834 char *swaplog_path
= xstrdup(logFile(NULL
));
835 char *clean_path
= xstrdup(logFile(".last-clean"));
836 char *new_path
= xstrdup(logFile(".new"));
840 struct stat clean_sb
;
844 if (::stat(swaplog_path
, &log_sb
) < 0) {
845 debugs(47, DBG_IMPORTANT
, HERE
<< "Cache Dir #" << index
<< ": No log file");
846 safe_free(swaplog_path
);
847 safe_free(clean_path
);
852 *zero_flag
= log_sb
.st_size
== 0 ? 1 : 0;
853 /* close the existing write-only FD */
856 file_close(swaplog_fd
);
858 /* open a write-only FD for the new log */
859 fd
= file_open(new_path
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
862 debugs(50, DBG_IMPORTANT
, "ERROR: while opening swap log" << new_path
<< ": " << xstrerror());
863 fatal("UFSSwapDir::openTmpSwapLog: Failed to open swap log.");
869 const StoreSwapLogHeader header
;
871 buf
.init(header
.record_size
, header
.record_size
);
872 buf
.append(reinterpret_cast<const char*>(&header
), sizeof(header
));
873 // Pad to keep in sync with UFSSwapDir::writeCleanStart().
874 memset(buf
.space(), 0, header
.gapSize());
875 buf
.appended(header
.gapSize());
876 file_write(swaplog_fd
, -1, buf
.content(), buf
.contentSize(),
877 NULL
, NULL
, buf
.freeFunc());
880 /* open a read-only stream of the old log */
881 fp
= fopen(swaplog_path
, "rb");
884 debugs(50, DBG_CRITICAL
, "ERROR: while opening " << swaplog_path
<< ": " << xstrerror());
885 fatal("Failed to open swap log for reading");
888 memset(&clean_sb
, '\0', sizeof(struct stat
));
890 if (::stat(clean_path
, &clean_sb
) < 0)
892 else if (clean_sb
.st_mtime
< log_sb
.st_mtime
)
897 safeunlink(clean_path
, 1);
899 safe_free(swaplog_path
);
901 safe_free(clean_path
);
909 * Begin the process to write clean cache state. For AUFS this means
910 * opening some log files and allocating write buffers. Return 0 if
911 * we succeed, and assign the 'func' and 'data' return pointers.
914 Fs::Ufs::UFSSwapDir::writeCleanStart()
916 UFSCleanLog
*state
= new UFSCleanLog(this);
917 StoreSwapLogHeader header
;
924 state
->newLog
= xstrdup(logFile(".clean"));
925 state
->fd
= file_open(state
->newLog
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
);
928 xfree(state
->newLog
);
933 state
->cur
= xstrdup(logFile(NULL
));
934 state
->cln
= xstrdup(logFile(".last-clean"));
935 state
->outbuf
= (char *)xcalloc(CLEAN_BUF_SZ
, 1);
936 state
->outbuf_offset
= 0;
938 memcpy(state
->outbuf
, &header
, sizeof(StoreSwapLogHeader
));
939 // Leave a gap to keep in sync with UFSSwapDir::openTmpSwapLog().
940 memset(state
->outbuf
+ sizeof(StoreSwapLogHeader
), 0, header
.gapSize());
941 state
->outbuf_offset
+= header
.record_size
;
943 state
->walker
= repl
->WalkInit(repl
);
944 ::unlink(state
->cln
);
945 debugs(47, 3, HERE
<< "opened " << state
->newLog
<< ", FD " << state
->fd
);
948 if (::stat(state
->cur
, &sb
) == 0)
949 fchmod(state
->fd
, sb
.st_mode
);
958 Fs::Ufs::UFSSwapDir::writeCleanDone()
960 UFSCleanLog
*state
= (UFSCleanLog
*)cleanLog
;
969 state
->walker
->Done(state
->walker
);
971 if (FD_WRITE_METHOD(state
->fd
, state
->outbuf
, state
->outbuf_offset
) < 0) {
972 debugs(50, DBG_CRITICAL
, HERE
<< state
->newLog
<< ": write: " << xstrerror());
973 debugs(50, DBG_CRITICAL
, HERE
<< "Current swap logfile not replaced.");
974 file_close(state
->fd
);
976 ::unlink(state
->newLog
);
979 safe_free(state
->outbuf
);
981 * You can't rename open files on Microsoft "operating systems"
982 * so we have to close before renaming.
985 /* save the fd value for a later test */
989 if (state
->fd
>= 0) {
990 #if _SQUID_OS2_ || _SQUID_WINDOWS_
991 file_close(state
->fd
);
995 xrename(state
->newLog
, state
->cur
);
998 /* touch a timestamp file if we're not still validating */
999 if (StoreController::store_dirs_rebuilding
)
1004 file_close(file_open(state
->cln
, O_WRONLY
| O_CREAT
| O_TRUNC
| O_BINARY
));
1007 safe_free(state
->cur
);
1009 safe_free(state
->newLog
);
1011 safe_free(state
->cln
);
1014 file_close(state
->fd
);
1024 Fs::Ufs::UFSSwapDir::CleanEvent(void *unused
)
1026 static int swap_index
= 0;
1031 * Assert that there are UFS cache_dirs configured, otherwise
1032 * we should never be called.
1034 assert(NumberOfUFSDirs
);
1036 if (NULL
== UFSDirToGlobalDirMapping
) {
1039 * Initialize the little array that translates UFS cache_dir
1040 * number into the Config.cacheSwap.swapDirs array index.
1042 UFSDirToGlobalDirMapping
= (int *)xcalloc(NumberOfUFSDirs
, sizeof(*UFSDirToGlobalDirMapping
));
1044 for (i
= 0, n
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
1045 /* This is bogus, the controller should just clean each instance once */
1046 sd
= dynamic_cast <SwapDir
*>(INDEXSD(i
));
1048 if (!UFSSwapDir::IsUFSDir(sd
))
1051 UFSSwapDir
*usd
= dynamic_cast<UFSSwapDir
*>(sd
);
1055 UFSDirToGlobalDirMapping
[n
] = i
;
1058 j
+= (usd
->l1
* usd
->l2
);
1061 assert(n
== NumberOfUFSDirs
);
1063 * Start the commonUfsDirClean() swap_index with a random
1064 * value. j equals the total number of UFS level 2
1067 swap_index
= (int) (squid_random() % j
);
1070 /* if the rebuild is finished, start cleaning directories. */
1071 if (0 == StoreController::store_dirs_rebuilding
) {
1072 n
= DirClean(swap_index
);
1076 eventAdd("storeDirClean", CleanEvent
, NULL
,
1077 15.0 * exp(-0.25 * n
), 1);
1081 Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir
* sd
)
1083 UFSSwapDir
*mySD
= dynamic_cast<UFSSwapDir
*>(sd
);
1084 return (mySD
!= 0) ;
1088 * XXX: this is broken - it assumes all cache dirs use the same
1089 * l1 and l2 scheme. -RBC 20021215. Partial fix is in place -
1090 * if not UFSSwapDir return 0;
1093 Fs::Ufs::UFSSwapDir::FilenoBelongsHere(int fn
, int F0
, int F1
, int F2
)
1098 assert(F0
< Config
.cacheSwap
.n_configured
);
1099 assert (UFSSwapDir::IsUFSDir (dynamic_cast<SwapDir
*>(INDEXSD(F0
))));
1100 UFSSwapDir
*sd
= dynamic_cast<UFSSwapDir
*>(INDEXSD(F0
));
1109 D1
= ((filn
/ L2
) / L2
) % L1
;
1114 D2
= (filn
/ L2
) % L2
;
1123 Fs::Ufs::UFSSwapDir::validFileno(sfileno filn
, int flag
) const
1129 * If flag is set it means out-of-range file number should
1130 * be considered invalid.
1133 if (filn
> map
->capacity())
1140 Fs::Ufs::UFSSwapDir::unlinkFile(sfileno f
)
1142 debugs(79, 3, HERE
<< "unlinking fileno " << std::setfill('0') <<
1143 std::hex
<< std::uppercase
<< std::setw(8) << f
<< " '" <<
1144 fullPath(f
,NULL
) << "'");
1145 /* commonUfsDirMapBitReset(this, f); */
1146 IO
->unlinkFile(fullPath(f
,NULL
));
1150 Fs::Ufs::UFSSwapDir::unlinkdUseful() const
1152 // unlinkd may be useful only in workers
1153 return IamWorkerProcess() && IO
->io
->unlinkdUseful();
1157 Fs::Ufs::UFSSwapDir::unlink(StoreEntry
& e
)
1159 debugs(79, 3, HERE
<< "dirno " << index
<< ", fileno "<<
1160 std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << e
.swap_filen
);
1161 if (e
.swap_status
== SWAPOUT_DONE
) {
1162 cur_size
-= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1165 replacementRemove(&e
);
1166 mapBitReset(e
.swap_filen
);
1167 UFSSwapDir::unlinkFile(e
.swap_filen
);
1171 Fs::Ufs::UFSSwapDir::replacementAdd(StoreEntry
* e
)
1173 debugs(47, 4, HERE
<< "added node " << e
<< " to dir " << index
);
1174 repl
->Add(repl
, e
, &e
->repl
);
1178 Fs::Ufs::UFSSwapDir::replacementRemove(StoreEntry
* e
)
1182 if (e
->swap_dirn
< 0)
1185 SD
= INDEXSD(e
->swap_dirn
);
1187 assert (dynamic_cast<UFSSwapDir
*>(SD
.getRaw()) == this);
1189 debugs(47, 4, HERE
<< "remove node " << e
<< " from dir " << index
);
1191 repl
->Remove(repl
, e
, &e
->repl
);
1195 Fs::Ufs::UFSSwapDir::dump(StoreEntry
& entry
) const
1197 storeAppendPrintf(&entry
, " %" PRIu64
" %d %d", maxSize() >> 20, l1
, l2
);
1198 dumpOptions(&entry
);
1202 Fs::Ufs::UFSSwapDir::fullPath(sfileno filn
, char *fullpath
) const
1204 LOCAL_ARRAY(char, fullfilename
, MAXPATHLEN
);
1209 fullpath
= fullfilename
;
1213 snprintf(fullpath
, MAXPATHLEN
, "%s/%02X/%02X/%08X",
1215 ((filn
/ L2
) / L2
) % L1
,
1223 Fs::Ufs::UFSSwapDir::callback()
1225 return IO
->callback();
1229 Fs::Ufs::UFSSwapDir::sync()
1235 Fs::Ufs::UFSSwapDir::swappedOut(const StoreEntry
&e
)
1237 cur_size
+= fs
.blksize
* sizeInBlocks(e
.swap_file_sz
);
1242 Fs::Ufs::UFSSwapDir::search(String
const url
, HttpRequest
*request
)
1245 fatal ("Cannot search by url yet\n");
1247 return new Fs::Ufs::StoreSearchUFS (this);
1251 Fs::Ufs::UFSSwapDir::logEntry(const StoreEntry
& e
, int op
) const
1253 StoreSwapLogData
*s
= new StoreSwapLogData
;
1255 s
->swap_filen
= e
.swap_filen
;
1256 s
->timestamp
= e
.timestamp
;
1257 s
->lastref
= e
.lastref
;
1258 s
->expires
= e
.expires
;
1259 s
->lastmod
= e
.lastmod
;
1260 s
->swap_file_sz
= e
.swap_file_sz
;
1261 s
->refcount
= e
.refcount
;
1263 memcpy(s
->key
, e
.key
, SQUID_MD5_DIGEST_LENGTH
);
1265 file_write(swaplog_fd
,
1268 sizeof(StoreSwapLogData
),
1275 Fs::Ufs::UFSSwapDir::DirClean(int swap_index
)
1277 DIR *dir_pointer
= NULL
;
1279 LOCAL_ARRAY(char, p1
, MAXPATHLEN
+ 1);
1280 LOCAL_ARRAY(char, p2
, MAXPATHLEN
+ 1);
1284 int fn
; /* same as swapfileno, but with dirn bits set */
1290 N0
= NumberOfUFSDirs
;
1291 D0
= UFSDirToGlobalDirMapping
[swap_index
% N0
];
1292 SD
= dynamic_cast<UFSSwapDir
*>(INDEXSD(D0
));
1295 D1
= (swap_index
/ N0
) % N1
;
1297 D2
= ((swap_index
/ N0
) / N1
) % N2
;
1298 snprintf(p1
, MAXPATHLEN
, "%s/%02X/%02X",
1300 debugs(36, 3, HERE
<< "Cleaning directory " << p1
);
1301 dir_pointer
= opendir(p1
);
1303 if (dir_pointer
== NULL
) {
1304 if (errno
== ENOENT
) {
1305 debugs(36, DBG_CRITICAL
, HERE
<< "WARNING: Creating " << p1
);
1311 if (mkdir(p1
, 0777) == 0)
1317 debugs(50, DBG_CRITICAL
, HERE
<< p1
<< ": " << xstrerror());
1323 while ((de
= readdir(dir_pointer
)) != NULL
&& k
< 20) {
1324 if (sscanf(de
->d_name
, "%X", &swapfileno
) != 1)
1327 fn
= swapfileno
; /* XXX should remove this cruft ! */
1329 if (SD
->validFileno(fn
, 1))
1330 if (SD
->mapBitTest(fn
))
1331 if (UFSSwapDir::FilenoBelongsHere(fn
, D0
, D1
, D2
))
1334 files
[k
] = swapfileno
;
1338 closedir(dir_pointer
);
1343 qsort(files
, k
, sizeof(int), rev_int_sort
);
1348 for (n
= 0; n
< k
; ++n
) {
1349 debugs(36, 3, HERE
<< "Cleaning file "<< std::setfill('0') << std::hex
<< std::uppercase
<< std::setw(8) << files
[n
]);
1350 snprintf(p2
, MAXPATHLEN
+ 1, "%s/%08X", p1
, files
[n
]);
1352 ++statCounter
.swap
.files_cleaned
;
1355 debugs(36, 3, HERE
<< "Cleaned " << k
<< " unused files from " << p1
);