]> git.ipfire.org Git - thirdparty/squid.git/blob - src/fs/ufs/UFSSwapDir.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / fs / ufs / UFSSwapDir.cc
1 /*
2 * Copyright (C) 1996-2015 The Squid Software Foundation and contributors
3 *
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.
7 */
8
9 /* DEBUG: section 47 Store Directory Routines */
10
11 #define CLEAN_BUF_SZ 16384
12
13 #include "squid.h"
14 #include "cache_cf.h"
15 #include "ConfigOption.h"
16 #include "disk.h"
17 #include "DiskIO/DiskIOModule.h"
18 #include "DiskIO/DiskIOStrategy.h"
19 #include "fde.h"
20 #include "FileMap.h"
21 #include "globals.h"
22 #include "Parsing.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"
31 #include "tools.h"
32 #include "UFSSwapDir.h"
33
34 #include <cerrno>
35 #include <cmath>
36 #if HAVE_SYS_STAT_H
37 #include <sys/stat.h>
38 #endif
39
40 int Fs::Ufs::UFSSwapDir::NumberOfUFSDirs = 0;
41 int *Fs::Ufs::UFSSwapDir::UFSDirToGlobalDirMapping = NULL;
42
43 class UFSCleanLog : public SwapDir::CleanLog
44 {
45
46 public:
47 UFSCleanLog(SwapDir *);
48 /** Get the next entry that is a candidate for clean log writing
49 */
50 virtual const StoreEntry *nextEntry();
51 /** "write" an entry to the clean log file.
52 */
53 virtual void write(StoreEntry const &);
54 char *cur;
55 char *newLog;
56 char *cln;
57 char *outbuf;
58 off_t outbuf_offset;
59 int fd;
60 RemovalPolicyWalker *walker;
61 SwapDir *sd;
62 };
63
64 UFSCleanLog::UFSCleanLog(SwapDir *aSwapDir) :
65 cur(NULL), newLog(NULL), cln(NULL), outbuf(NULL),
66 outbuf_offset(0), fd(-1),walker(NULL), sd(aSwapDir)
67 {}
68
69 const StoreEntry *
70 UFSCleanLog::nextEntry()
71 {
72 const StoreEntry *entry = NULL;
73
74 if (walker)
75 entry = walker->Next(walker);
76
77 return entry;
78 }
79
80 void
81 UFSCleanLog::write(StoreEntry const &e)
82 {
83 StoreSwapLogData s;
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;
93 s.flags = e.flags;
94 memcpy(&s.key, e.key, SQUID_MD5_DIGEST_LENGTH);
95 s.finalize();
96 memcpy(outbuf + outbuf_offset, &s, ss);
97 outbuf_offset += ss;
98 /* buffered write */
99
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.");
105 file_close(fd);
106 fd = -1;
107 unlink(newLog);
108 sd->cleanLog = NULL;
109 delete this;
110 return;
111 }
112
113 outbuf_offset = 0;
114 }
115 }
116
117 bool
118 Fs::Ufs::UFSSwapDir::canStore(const StoreEntry &e, int64_t diskSpaceNeeded, int &load) const
119 {
120 if (!SwapDir::canStore(e, diskSpaceNeeded, load))
121 return false;
122
123 if (IO->shedLoad())
124 return false;
125
126 load = IO->load();
127 return true;
128 }
129
130 static void
131 FreeObject(void *address)
132 {
133 StoreSwapLogData *anObject = static_cast <StoreSwapLogData *>(address);
134 delete anObject;
135 }
136
137 static QS rev_int_sort;
138 static int
139 rev_int_sort(const void *A, const void *B)
140 {
141 const int *i1 = (const int *)A;
142 const int *i2 = (const int *)B;
143 return *i2 - *i1;
144 }
145
146 void
147 Fs::Ufs::UFSSwapDir::parseSizeL1L2()
148 {
149 int i = GetInteger();
150 if (i <= 0)
151 fatal("UFSSwapDir::parseSizeL1L2: invalid size value");
152
153 const uint64_t size = static_cast<uint64_t>(i) << 20; // MBytes to Bytes
154
155 /* just reconfigure it */
156 if (reconfiguring) {
157 if (size == maxSize())
158 debugs(3, 2, "Cache dir '" << path << "' size remains unchanged at " << i << " MB");
159 else
160 debugs(3, DBG_IMPORTANT, "Cache dir '" << path << "' size changed to " << i << " MB");
161 }
162
163 max_size = size;
164
165 l1 = GetInteger();
166
167 if (l1 <= 0)
168 fatal("UFSSwapDir::parseSizeL1L2: invalid level 1 directories value");
169
170 l2 = GetInteger();
171
172 if (l2 <= 0)
173 fatal("UFSSwapDir::parseSizeL1L2: invalid level 2 directories value");
174 }
175
176 void
177 Fs::Ufs::UFSSwapDir::reconfigure()
178 {
179 parseSizeL1L2();
180 parseOptions(1);
181 }
182
183 void
184 Fs::Ufs::UFSSwapDir::parse (int anIndex, char *aPath)
185 {
186 index = anIndex;
187 path = xstrdup(aPath);
188
189 parseSizeL1L2();
190
191 /* Initialise replacement policy stuff */
192 repl = createRemovalPolicy(Config.replPolicy);
193
194 parseOptions(0);
195 }
196
197 void
198 Fs::Ufs::UFSSwapDir::changeIO(DiskIOModule *module)
199 {
200 DiskIOStrategy *anIO = module->createStrategy();
201 safe_free(ioType);
202 ioType = xstrdup(module->type());
203
204 delete IO->io;
205 IO->io = anIO;
206 /* Change the IO Options */
207
208 if (currentIOOptions && currentIOOptions->options.size() > 2) {
209 delete currentIOOptions->options.back();
210 currentIOOptions->options.pop_back();
211 }
212
213 /* TODO: factor out these 4 lines */
214 ConfigOption *ioOptions = IO->io->getOptionTree();
215
216 if (currentIOOptions && ioOptions)
217 currentIOOptions->options.push_back(ioOptions);
218 }
219
220 bool
221 Fs::Ufs::UFSSwapDir::optionIOParse(char const *option, const char *value, int isaReconfig)
222 {
223 if (strcmp(option, "IOEngine") != 0)
224 return false;
225
226 if (isaReconfig)
227 /* silently ignore this */
228 return true;
229
230 if (!value)
231 self_destruct();
232
233 DiskIOModule *module = DiskIOModule::Find(value);
234
235 if (!module)
236 self_destruct();
237
238 changeIO(module);
239
240 return true;
241 }
242
243 void
244 Fs::Ufs::UFSSwapDir::optionIODump(StoreEntry * e) const
245 {
246 storeAppendPrintf(e, " IOEngine=%s", ioType);
247 }
248
249 ConfigOption *
250 Fs::Ufs::UFSSwapDir::getOptionTree() const
251 {
252 ConfigOption *parentResult = SwapDir::getOptionTree();
253
254 if (currentIOOptions == NULL)
255 currentIOOptions = new ConfigOptionVector();
256
257 currentIOOptions->options.push_back(parentResult);
258
259 currentIOOptions->options.push_back(new ConfigOptionAdapter<UFSSwapDir>(*const_cast<UFSSwapDir *>(this), &UFSSwapDir::optionIOParse, &UFSSwapDir::optionIODump));
260
261 if (ConfigOption *ioOptions = IO->io->getOptionTree())
262 currentIOOptions->options.push_back(ioOptions);
263
264 ConfigOption* result = currentIOOptions;
265
266 currentIOOptions = NULL;
267
268 return result;
269 }
270
271 void
272 Fs::Ufs::UFSSwapDir::init()
273 {
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.";
282 IO->init();
283
284 if (verifyCacheDirs())
285 fatal(errmsg);
286
287 openLog();
288
289 rebuild();
290
291 if (!started_clean_event) {
292 eventAdd("UFS storeDirClean", CleanEvent, NULL, 15.0, 1);
293 started_clean_event = 1;
294 }
295
296 (void) storeDirGetBlkSize(path, &fs.blksize);
297 }
298
299 void
300 Fs::Ufs::UFSSwapDir::create()
301 {
302 debugs(47, 3, "Creating swap space in " << path);
303 createDirectory(path, 0);
304 createSwapSubDirs();
305 }
306
307 Fs::Ufs::UFSSwapDir::UFSSwapDir(char const *aType, const char *anIOType) :
308 SwapDir(aType),
309 IO(NULL),
310 fsdata(NULL),
311 map(new FileMap()),
312 suggest(0),
313 l1(16),
314 l2(256),
315 swaplog_fd(-1),
316 currentIOOptions(new ConfigOptionVector()),
317 ioType(xstrdup(anIOType)),
318 cur_size(0),
319 n_disk_objects(0)
320 {
321 /* modulename is only set to disk modules that are built, by configure,
322 * so the Find call should never return NULL here.
323 */
324 IO = new Fs::Ufs::UFSStrategy(DiskIOModule::Find(anIOType)->createStrategy());
325 }
326
327 Fs::Ufs::UFSSwapDir::~UFSSwapDir()
328 {
329 if (swaplog_fd > -1) {
330 file_close(swaplog_fd);
331 swaplog_fd = -1;
332 }
333 xfree(ioType);
334 delete map;
335 delete IO;
336 delete currentIOOptions;
337 }
338
339 void
340 Fs::Ufs::UFSSwapDir::dumpEntry(StoreEntry &e) const
341 {
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) );
344 e.dump(0);
345 }
346
347 bool
348 Fs::Ufs::UFSSwapDir::doubleCheck(StoreEntry & e)
349 {
350
351 struct stat sb;
352
353 if (::stat(fullPath(e.swap_filen, NULL), &sb) < 0) {
354 debugs(47, DBG_CRITICAL, HERE << "WARNING: Missing swap file");
355 dumpEntry(e);
356 return true;
357 }
358
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);
362 dumpEntry(e);
363 return true;
364 }
365
366 return false;
367 }
368
369 void
370 Fs::Ufs::UFSSwapDir::statfs(StoreEntry & sentry) const
371 {
372 int totl_kb = 0;
373 int free_kb = 0;
374 int totl_in = 0;
375 int free_in = 0;
376 int x;
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);
387
388 if (0 == x) {
389 storeAppendPrintf(&sentry, "Filesystem Space in use: %d/%d KB (%d%%)\n",
390 totl_kb - free_kb,
391 totl_kb,
392 Math::intPercent(totl_kb - free_kb, totl_kb));
393 storeAppendPrintf(&sentry, "Filesystem Inodes in use: %d/%d (%d%%)\n",
394 totl_in - free_in,
395 totl_in,
396 Math::intPercent(totl_in - free_in, totl_in));
397 }
398
399 storeAppendPrintf(&sentry, "Flags:");
400
401 if (flags.selected)
402 storeAppendPrintf(&sentry, " SELECTED");
403
404 if (flags.read_only)
405 storeAppendPrintf(&sentry, " READ-ONLY");
406
407 storeAppendPrintf(&sentry, "\n");
408
409 IO->statfs(sentry);
410 }
411
412 void
413 Fs::Ufs::UFSSwapDir::maintain()
414 {
415 /* We can't delete objects while rebuilding swap */
416
417 /* XXX FIXME each store should start maintaining as it comes online. */
418
419 if (StoreController::store_dirs_rebuilding)
420 return;
421
422 StoreEntry *e = NULL;
423
424 int removed = 0;
425
426 RemovalPurgeWalker *walker;
427
428 double f = (double) (currentSize() - minSize()) / (maxSize() - minSize());
429
430 f = f < 0.0 ? 0.0 : f > 1.0 ? 1.0 : f;
431
432 int max_scan = (int) (f * 400.0 + 100.0);
433
434 int max_remove = (int) (f * 70.0 + 10.0);
435
436 /*
437 * This is kinda cheap, but so we need this priority hack?
438 */
439
440 debugs(47, 3, HERE << "f=" << f << ", max_scan=" << max_scan << ", max_remove=" << max_remove );
441
442 walker = repl->PurgeInit(repl, max_scan);
443
444 while (1) {
445 if (currentSize() < minSize())
446 break;
447
448 if (removed >= max_remove)
449 break;
450
451 e = walker->Next(walker);
452
453 if (!e)
454 break; /* no more objects */
455
456 ++removed;
457
458 e->release();
459 }
460
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);
465 }
466
467 void
468 Fs::Ufs::UFSSwapDir::reference(StoreEntry &e)
469 {
470 debugs(47, 3, HERE << "referencing " << &e << " " <<
471 e.swap_dirn << "/" << e.swap_filen);
472
473 if (repl->Referenced)
474 repl->Referenced(repl, &e, &e.repl);
475 }
476
477 bool
478 Fs::Ufs::UFSSwapDir::dereference(StoreEntry & e, bool)
479 {
480 debugs(47, 3, HERE << "dereferencing " << &e << " " <<
481 e.swap_dirn << "/" << e.swap_filen);
482
483 if (repl->Dereferenced)
484 repl->Dereferenced(repl, &e, &e.repl);
485
486 return true; // keep e in the global store_table
487 }
488
489 StoreIOState::Pointer
490 Fs::Ufs::UFSSwapDir::createStoreIO(StoreEntry &e, StoreIOState::STFNCB * file_callback, StoreIOState::STIOCB * aCallback, void *callback_data)
491 {
492 return IO->create (this, &e, file_callback, aCallback, callback_data);
493 }
494
495 StoreIOState::Pointer
496 Fs::Ufs::UFSSwapDir::openStoreIO(StoreEntry &e, StoreIOState::STFNCB * file_callback, StoreIOState::STIOCB * aCallback, void *callback_data)
497 {
498 return IO->open (this, &e, file_callback, aCallback, callback_data);
499 }
500
501 int
502 Fs::Ufs::UFSSwapDir::mapBitTest(sfileno filn)
503 {
504 return map->testBit(filn);
505 }
506
507 void
508 Fs::Ufs::UFSSwapDir::mapBitSet(sfileno filn)
509 {
510 map->setBit(filn);
511 }
512
513 void
514 Fs::Ufs::UFSSwapDir::mapBitReset(sfileno filn)
515 {
516 /*
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.
522 */
523
524 if (map->testBit(filn))
525 map->clearBit(filn);
526 }
527
528 int
529 Fs::Ufs::UFSSwapDir::mapBitAllocate()
530 {
531 int fn;
532 fn = map->allocate(suggest);
533 map->setBit(fn);
534 suggest = fn + 1;
535 return fn;
536 }
537
538 char *
539 Fs::Ufs::UFSSwapDir::swapSubDir(int subdirn)const
540 {
541 LOCAL_ARRAY(char, fullfilename, MAXPATHLEN);
542 assert(0 <= subdirn && subdirn < l1);
543 snprintf(fullfilename, MAXPATHLEN, "%s/%02X", path, subdirn);
544 return fullfilename;
545 }
546
547 int
548 Fs::Ufs::UFSSwapDir::createDirectory(const char *aPath, int should_exist)
549 {
550 int created = 0;
551
552 struct stat st;
553 getCurrentTime();
554
555 if (0 == ::stat(aPath, &st)) {
556 if (S_ISDIR(st.st_mode)) {
557 debugs(47, (should_exist ? 3 : DBG_IMPORTANT), aPath << " exists");
558 } else {
559 fatalf("Swap directory %s is not a directory.", aPath);
560 }
561 } else if (0 == mkdir(aPath, 0755)) {
562 debugs(47, (should_exist ? DBG_IMPORTANT : 3), aPath << " created");
563 created = 1;
564 } else {
565 fatalf("Failed to make swap directory %s: %s",
566 aPath, xstrerror());
567 }
568
569 return created;
570 }
571
572 bool
573 Fs::Ufs::UFSSwapDir::pathIsDirectory(const char *aPath)const
574 {
575
576 struct stat sb;
577
578 if (::stat(aPath, &sb) < 0) {
579 debugs(47, DBG_CRITICAL, "ERROR: " << aPath << ": " << xstrerror());
580 return false;
581 }
582
583 if (S_ISDIR(sb.st_mode) == 0) {
584 debugs(47, DBG_CRITICAL, "WARNING: " << aPath << " is not a directory");
585 return false;
586 }
587
588 return true;
589 }
590
591 bool
592 Fs::Ufs::UFSSwapDir::verifyCacheDirs()
593 {
594 if (!pathIsDirectory(path))
595 return true;
596
597 for (int j = 0; j < l1; ++j) {
598 char const *aPath = swapSubDir(j);
599
600 if (!pathIsDirectory(aPath))
601 return true;
602 }
603
604 return false;
605 }
606
607 void
608 Fs::Ufs::UFSSwapDir::createSwapSubDirs()
609 {
610 LOCAL_ARRAY(char, name, MAXPATHLEN);
611
612 for (int i = 0; i < l1; ++i) {
613 snprintf(name, MAXPATHLEN, "%s/%02X", path, i);
614
615 int should_exist;
616
617 if (createDirectory(name, 0))
618 should_exist = 0;
619 else
620 should_exist = 1;
621
622 debugs(47, DBG_IMPORTANT, "Making directories in " << name);
623
624 for (int k = 0; k < l2; ++k) {
625 snprintf(name, MAXPATHLEN, "%s/%02X/%02X", path, i, k);
626 createDirectory(name, should_exist);
627 }
628 }
629 }
630
631 char *
632 Fs::Ufs::UFSSwapDir::logFile(char const *ext) const
633 {
634 LOCAL_ARRAY(char, lpath, MAXPATHLEN);
635 LOCAL_ARRAY(char, pathtmp, MAXPATHLEN);
636 LOCAL_ARRAY(char, digit, 32);
637 char *pathtmp2;
638
639 if (Config.Log.swap) {
640 xstrncpy(pathtmp, path, MAXPATHLEN - 64);
641 pathtmp2 = pathtmp;
642
643 while ((pathtmp2 = strchr(pathtmp2, '/')) != NULL)
644 *pathtmp2 = '.';
645
646 while (strlen(pathtmp) && pathtmp[strlen(pathtmp) - 1] == '.')
647 pathtmp[strlen(pathtmp) - 1] = '\0';
648
649 for (pathtmp2 = pathtmp; *pathtmp2 == '.'; ++pathtmp2);
650 snprintf(lpath, MAXPATHLEN - 64, Config.Log.swap, pathtmp2);
651
652 if (strncmp(lpath, Config.Log.swap, MAXPATHLEN - 64) == 0) {
653 strcat(lpath, ".");
654 snprintf(digit, 32, "%02d", index);
655 strncat(lpath, digit, 3);
656 }
657 } else {
658 xstrncpy(lpath, path, MAXPATHLEN - 64);
659 strcat(lpath, "/swap.state");
660 }
661
662 if (ext)
663 strncat(lpath, ext, 16);
664
665 return lpath;
666 }
667
668 void
669 Fs::Ufs::UFSSwapDir::openLog()
670 {
671 char *logPath;
672 logPath = logFile();
673 swaplog_fd = file_open(logPath, O_WRONLY | O_CREAT | O_BINARY);
674
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.");
678 }
679
680 debugs(50, 3, HERE << "Cache Dir #" << index << " log opened on FD " << swaplog_fd);
681
682 if (0 == NumberOfUFSDirs)
683 assert(NULL == UFSDirToGlobalDirMapping);
684
685 ++NumberOfUFSDirs;
686
687 assert(NumberOfUFSDirs <= Config.cacheSwap.n_configured);
688 }
689
690 void
691 Fs::Ufs::UFSSwapDir::closeLog()
692 {
693 if (swaplog_fd < 0) /* not open */
694 return;
695
696 file_close(swaplog_fd);
697
698 debugs(47, 3, "Cache Dir #" << index << " log closed on FD " << swaplog_fd);
699
700 swaplog_fd = -1;
701
702 --NumberOfUFSDirs;
703
704 assert(NumberOfUFSDirs >= 0);
705
706 if (0 == NumberOfUFSDirs)
707 safe_free(UFSDirToGlobalDirMapping);
708 }
709
710 bool
711 Fs::Ufs::UFSSwapDir::validL1(int anInt) const
712 {
713 return anInt < l1;
714 }
715
716 bool
717 Fs::Ufs::UFSSwapDir::validL2(int anInt) const
718 {
719 return anInt < l2;
720 }
721
722 StoreEntry *
723 Fs::Ufs::UFSSwapDir::addDiskRestore(const cache_key * key,
724 sfileno file_number,
725 uint64_t swap_file_sz,
726 time_t expires,
727 time_t timestamp,
728 time_t lastref,
729 time_t lastmod,
730 uint32_t refcount,
731 uint16_t newFlags,
732 int)
733 {
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
738 * already in use! */
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;
751 e->flags = newFlags;
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);
758 ++n_disk_objects;
759 e->hashInsert(key); /* do it after we clear KEY_PRIVATE */
760 replacementAdd (e);
761 return e;
762 }
763
764 void
765 Fs::Ufs::UFSSwapDir::undoAddDiskRestore(StoreEntry *e)
766 {
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);
771 e->swap_filen = -1;
772 e->swap_dirn = -1;
773 cur_size -= fs.blksize * sizeInBlocks(e->swap_file_sz);
774 --n_disk_objects;
775 }
776
777 void
778 Fs::Ufs::UFSSwapDir::rebuild()
779 {
780 ++StoreController::store_dirs_rebuilding;
781 eventAdd("storeRebuild", Fs::Ufs::RebuildState::RebuildStep, new Fs::Ufs::RebuildState(this), 0.0, 1);
782 }
783
784 void
785 Fs::Ufs::UFSSwapDir::closeTmpSwapLog()
786 {
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
789 int fd;
790 file_close(swaplog_fd);
791
792 if (xrename(tmp_path, swaplog_path) < 0) {
793 fatalf("Failed to rename log file %s to %s", tmp_path, swaplog_path);
794 }
795
796 fd = file_open(swaplog_path, O_WRONLY | O_CREAT | O_BINARY);
797
798 if (fd < 0) {
799 debugs(50, DBG_IMPORTANT, "ERROR: " << swaplog_path << ": " << xstrerror());
800 fatalf("Failed to open swap log %s", swaplog_path);
801 }
802
803 xfree(swaplog_path);
804 xfree(tmp_path);
805 swaplog_fd = fd;
806 debugs(47, 3, "Cache Dir #" << index << " log opened on FD " << fd);
807 }
808
809 FILE *
810 Fs::Ufs::UFSSwapDir::openTmpSwapLog(int *clean_flag, int *zero_flag)
811 {
812 char *swaplog_path = xstrdup(logFile(NULL));
813 char *clean_path = xstrdup(logFile(".last-clean"));
814 char *new_path = xstrdup(logFile(".new"));
815
816 struct stat log_sb;
817
818 struct stat clean_sb;
819 FILE *fp;
820 int fd;
821
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);
826 safe_free(new_path);
827 return NULL;
828 }
829
830 *zero_flag = log_sb.st_size == 0 ? 1 : 0;
831 /* close the existing write-only FD */
832
833 if (swaplog_fd >= 0)
834 file_close(swaplog_fd);
835
836 /* open a write-only FD for the new log */
837 fd = file_open(new_path, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY);
838
839 if (fd < 0) {
840 debugs(50, DBG_IMPORTANT, "ERROR: while opening swap log" << new_path << ": " << xstrerror());
841 fatalf("Failed to open swap log %s", new_path);
842 }
843
844 swaplog_fd = fd;
845
846 {
847 const StoreSwapLogHeader header;
848 MemBuf buf;
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());
856 }
857
858 /* open a read-only stream of the old log */
859 fp = fopen(swaplog_path, "rb");
860
861 if (fp == NULL) {
862 debugs(50, DBG_CRITICAL, "ERROR: while opening " << swaplog_path << ": " << xstrerror());
863 fatalf("Failed to open swap log for reading %s", swaplog_path);
864 }
865
866 memset(&clean_sb, '\0', sizeof(struct stat));
867
868 if (::stat(clean_path, &clean_sb) < 0)
869 *clean_flag = 0;
870 else if (clean_sb.st_mtime < log_sb.st_mtime)
871 *clean_flag = 0;
872 else
873 *clean_flag = 1;
874
875 safeunlink(clean_path, 1);
876
877 safe_free(swaplog_path);
878
879 safe_free(clean_path);
880
881 safe_free(new_path);
882
883 return fp;
884 }
885
886 /*
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.
890 */
891 int
892 Fs::Ufs::UFSSwapDir::writeCleanStart()
893 {
894 UFSCleanLog *state = new UFSCleanLog(this);
895 StoreSwapLogHeader header;
896 #if HAVE_FCHMOD
897
898 struct stat sb;
899 #endif
900
901 cleanLog = NULL;
902 state->newLog = xstrdup(logFile(".clean"));
903 state->fd = file_open(state->newLog, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY);
904
905 if (state->fd < 0) {
906 xfree(state->newLog);
907 delete state;
908 return -1;
909 }
910
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;
915 /*copy the header */
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;
920
921 state->walker = repl->WalkInit(repl);
922 ::unlink(state->cln);
923 debugs(47, 3, HERE << "opened " << state->newLog << ", FD " << state->fd);
924 #if HAVE_FCHMOD
925
926 if (::stat(state->cur, &sb) == 0)
927 fchmod(state->fd, sb.st_mode);
928
929 #endif
930
931 cleanLog = state;
932 return 0;
933 }
934
935 void
936 Fs::Ufs::UFSSwapDir::writeCleanDone()
937 {
938 UFSCleanLog *state = (UFSCleanLog *)cleanLog;
939 int fd;
940
941 if (NULL == state)
942 return;
943
944 if (state->fd < 0)
945 return;
946
947 state->walker->Done(state->walker);
948
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);
953 state->fd = -1;
954 ::unlink(state->newLog);
955 }
956
957 safe_free(state->outbuf);
958 /*
959 * You can't rename open files on Microsoft "operating systems"
960 * so we have to close before renaming.
961 */
962 closeLog();
963 /* save the fd value for a later test */
964 fd = state->fd;
965 /* rename */
966
967 if (state->fd >= 0) {
968 #if _SQUID_OS2_ || _SQUID_WINDOWS_
969 file_close(state->fd);
970 state->fd = -1;
971 #endif
972
973 xrename(state->newLog, state->cur);
974 }
975
976 /* touch a timestamp file if we're not still validating */
977 if (StoreController::store_dirs_rebuilding)
978 (void) 0;
979 else if (fd < 0)
980 (void) 0;
981 else
982 file_close(file_open(state->cln, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY));
983
984 /* close */
985 safe_free(state->cur);
986
987 safe_free(state->newLog);
988
989 safe_free(state->cln);
990
991 if (state->fd >= 0)
992 file_close(state->fd);
993
994 state->fd = -1;
995
996 delete state;
997
998 cleanLog = NULL;
999 }
1000
1001 void
1002 Fs::Ufs::UFSSwapDir::CleanEvent(void *)
1003 {
1004 static int swap_index = 0;
1005 int i;
1006 int j = 0;
1007 int n = 0;
1008 /*
1009 * Assert that there are UFS cache_dirs configured, otherwise
1010 * we should never be called.
1011 */
1012 assert(NumberOfUFSDirs);
1013
1014 if (NULL == UFSDirToGlobalDirMapping) {
1015 SwapDir *sd;
1016 /*
1017 * Initialize the little array that translates UFS cache_dir
1018 * number into the Config.cacheSwap.swapDirs array index.
1019 */
1020 UFSDirToGlobalDirMapping = (int *)xcalloc(NumberOfUFSDirs, sizeof(*UFSDirToGlobalDirMapping));
1021
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));
1025
1026 if (!UFSSwapDir::IsUFSDir(sd))
1027 continue;
1028
1029 UFSSwapDir *usd = dynamic_cast<UFSSwapDir *>(sd);
1030
1031 assert (usd);
1032
1033 UFSDirToGlobalDirMapping[n] = i;
1034 ++n;
1035
1036 j += (usd->l1 * usd->l2);
1037 }
1038
1039 assert(n == NumberOfUFSDirs);
1040 /*
1041 * Start the commonUfsDirClean() swap_index with a random
1042 * value. j equals the total number of UFS level 2
1043 * swap directories
1044 */
1045 swap_index = (int) (squid_random() % j);
1046 }
1047
1048 /* if the rebuild is finished, start cleaning directories. */
1049 if (0 == StoreController::store_dirs_rebuilding) {
1050 n = DirClean(swap_index);
1051 ++swap_index;
1052 }
1053
1054 eventAdd("storeDirClean", CleanEvent, NULL,
1055 15.0 * exp(-0.25 * n), 1);
1056 }
1057
1058 bool
1059 Fs::Ufs::UFSSwapDir::IsUFSDir(SwapDir * sd)
1060 {
1061 UFSSwapDir *mySD = dynamic_cast<UFSSwapDir *>(sd);
1062 return (mySD != 0) ;
1063 }
1064
1065 /*
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;
1069 */
1070 bool
1071 Fs::Ufs::UFSSwapDir::FilenoBelongsHere(int fn, int F0, int F1, int F2)
1072 {
1073 int D1, D2;
1074 int L1, L2;
1075 int filn = fn;
1076 assert(F0 < Config.cacheSwap.n_configured);
1077 assert (UFSSwapDir::IsUFSDir (dynamic_cast<SwapDir *>(INDEXSD(F0))));
1078 UFSSwapDir *sd = dynamic_cast<UFSSwapDir *>(INDEXSD(F0));
1079
1080 if (!sd)
1081 return 0;
1082
1083 L1 = sd->l1;
1084
1085 L2 = sd->l2;
1086
1087 D1 = ((filn / L2) / L2) % L1;
1088
1089 if (F1 != D1)
1090 return 0;
1091
1092 D2 = (filn / L2) % L2;
1093
1094 if (F2 != D2)
1095 return 0;
1096
1097 return 1;
1098 }
1099
1100 int
1101 Fs::Ufs::UFSSwapDir::validFileno(sfileno filn, int flag) const
1102 {
1103 if (filn < 0)
1104 return 0;
1105
1106 /*
1107 * If flag is set it means out-of-range file number should
1108 * be considered invalid.
1109 */
1110 if (flag)
1111 if (filn > map->capacity())
1112 return 0;
1113
1114 return 1;
1115 }
1116
1117 void
1118 Fs::Ufs::UFSSwapDir::unlinkFile(sfileno f)
1119 {
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));
1125 }
1126
1127 bool
1128 Fs::Ufs::UFSSwapDir::unlinkdUseful() const
1129 {
1130 // unlinkd may be useful only in workers
1131 return IamWorkerProcess() && IO->io->unlinkdUseful();
1132 }
1133
1134 void
1135 Fs::Ufs::UFSSwapDir::unlink(StoreEntry & e)
1136 {
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);
1141 --n_disk_objects;
1142 }
1143 replacementRemove(&e);
1144 mapBitReset(e.swap_filen);
1145 UFSSwapDir::unlinkFile(e.swap_filen);
1146 }
1147
1148 void
1149 Fs::Ufs::UFSSwapDir::replacementAdd(StoreEntry * e)
1150 {
1151 debugs(47, 4, HERE << "added node " << e << " to dir " << index);
1152 repl->Add(repl, e, &e->repl);
1153 }
1154
1155 void
1156 Fs::Ufs::UFSSwapDir::replacementRemove(StoreEntry * e)
1157 {
1158 StorePointer SD;
1159
1160 if (e->swap_dirn < 0)
1161 return;
1162
1163 SD = INDEXSD(e->swap_dirn);
1164
1165 assert (dynamic_cast<UFSSwapDir *>(SD.getRaw()) == this);
1166
1167 debugs(47, 4, HERE << "remove node " << e << " from dir " << index);
1168
1169 repl->Remove(repl, e, &e->repl);
1170 }
1171
1172 void
1173 Fs::Ufs::UFSSwapDir::dump(StoreEntry & entry) const
1174 {
1175 storeAppendPrintf(&entry, " %" PRIu64 " %d %d", maxSize() >> 20, l1, l2);
1176 dumpOptions(&entry);
1177 }
1178
1179 char *
1180 Fs::Ufs::UFSSwapDir::fullPath(sfileno filn, char *fullpath) const
1181 {
1182 LOCAL_ARRAY(char, fullfilename, MAXPATHLEN);
1183 int L1 = l1;
1184 int L2 = l2;
1185
1186 if (!fullpath)
1187 fullpath = fullfilename;
1188
1189 fullpath[0] = '\0';
1190
1191 snprintf(fullpath, MAXPATHLEN, "%s/%02X/%02X/%08X",
1192 path,
1193 ((filn / L2) / L2) % L1,
1194 (filn / L2) % L2,
1195 filn);
1196
1197 return fullpath;
1198 }
1199
1200 int
1201 Fs::Ufs::UFSSwapDir::callback()
1202 {
1203 return IO->callback();
1204 }
1205
1206 void
1207 Fs::Ufs::UFSSwapDir::sync()
1208 {
1209 IO->sync();
1210 }
1211
1212 void
1213 Fs::Ufs::UFSSwapDir::swappedOut(const StoreEntry &e)
1214 {
1215 cur_size += fs.blksize * sizeInBlocks(e.swap_file_sz);
1216 ++n_disk_objects;
1217 }
1218
1219 StoreSearch *
1220 Fs::Ufs::UFSSwapDir::search(String const url, HttpRequest *)
1221 {
1222 if (url.size())
1223 fatal ("Cannot search by url yet\n");
1224
1225 return new Fs::Ufs::StoreSearchUFS (this);
1226 }
1227
1228 void
1229 Fs::Ufs::UFSSwapDir::logEntry(const StoreEntry & e, int op) const
1230 {
1231 StoreSwapLogData *s = new StoreSwapLogData;
1232 s->op = (char) op;
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;
1240 s->flags = e.flags;
1241 memcpy(s->key, e.key, SQUID_MD5_DIGEST_LENGTH);
1242 s->finalize();
1243 file_write(swaplog_fd,
1244 -1,
1245 s,
1246 sizeof(StoreSwapLogData),
1247 NULL,
1248 NULL,
1249 FreeObject);
1250 }
1251
1252 int
1253 Fs::Ufs::UFSSwapDir::DirClean(int swap_index)
1254 {
1255 DIR *dir_pointer = NULL;
1256
1257 LOCAL_ARRAY(char, p1, MAXPATHLEN + 1);
1258 LOCAL_ARRAY(char, p2, MAXPATHLEN + 1);
1259
1260 int files[20];
1261 int swapfileno;
1262 int fn; /* same as swapfileno, but with dirn bits set */
1263 int n = 0;
1264 int k = 0;
1265 int N0, N1, N2;
1266 int D0, D1, D2;
1267 UFSSwapDir *SD;
1268 N0 = NumberOfUFSDirs;
1269 D0 = UFSDirToGlobalDirMapping[swap_index % N0];
1270 SD = dynamic_cast<UFSSwapDir *>(INDEXSD(D0));
1271 assert (SD);
1272 N1 = SD->l1;
1273 D1 = (swap_index / N0) % N1;
1274 N2 = SD->l2;
1275 D2 = ((swap_index / N0) / N1) % N2;
1276 snprintf(p1, MAXPATHLEN, "%s/%02X/%02X",
1277 SD->path, D1, D2);
1278 debugs(36, 3, HERE << "Cleaning directory " << p1);
1279 dir_pointer = opendir(p1);
1280
1281 if (dir_pointer == NULL) {
1282 if (errno == ENOENT) {
1283 debugs(36, DBG_CRITICAL, HERE << "WARNING: Creating " << p1);
1284 if (mkdir(p1, 0777) == 0)
1285 return 0;
1286 }
1287
1288 debugs(50, DBG_CRITICAL, HERE << p1 << ": " << xstrerror());
1289 safeunlink(p1, 1);
1290 return 0;
1291 }
1292
1293 dirent_t *de;
1294 while ((de = readdir(dir_pointer)) != NULL && k < 20) {
1295 if (sscanf(de->d_name, "%X", &swapfileno) != 1)
1296 continue;
1297
1298 fn = swapfileno; /* XXX should remove this cruft ! */
1299
1300 if (SD->validFileno(fn, 1))
1301 if (SD->mapBitTest(fn))
1302 if (UFSSwapDir::FilenoBelongsHere(fn, D0, D1, D2))
1303 continue;
1304
1305 files[k] = swapfileno;
1306 ++k;
1307 }
1308
1309 closedir(dir_pointer);
1310
1311 if (k == 0)
1312 return 0;
1313
1314 qsort(files, k, sizeof(int), rev_int_sort);
1315
1316 if (k > 10)
1317 k = 10;
1318
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]);
1322 safeunlink(p2, 0);
1323 ++statCounter.swap.files_cleaned;
1324 }
1325
1326 debugs(36, 3, HERE << "Cleaned " << k << " unused files from " << p1);
1327 return k;
1328 }
1329