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 */
14 #include "profiler/Profiler.h"
15 #include "SquidConfig.h"
17 #include "store/Disk.h"
18 #include "store/Disks.h"
19 #include "swap_log_op.h"
20 #include "util.h" // for tvSubDsec() which should be in SquidTime.h
22 static STDIRSELECT storeDirSelectSwapDirRoundRobin
;
23 static STDIRSELECT storeDirSelectSwapDirLeastLoad
;
25 * This function pointer is set according to 'store_dir_select_algorithm'
28 STDIRSELECT
*storeDirSelectSwapDir
= storeDirSelectSwapDirLeastLoad
;
31 * This new selection scheme simply does round-robin on all SwapDirs.
32 * A SwapDir is skipped if it is over the max_size (100%) limit, or
36 storeDirSelectSwapDirRoundRobin(const StoreEntry
* e
)
38 // e->objectLen() is negative at this point when we are still STORE_PENDING
39 ssize_t objsize
= e
->mem_obj
->expectedReplySize();
41 objsize
+= e
->mem_obj
->swap_hdr_sz
;
43 // Increment the first candidate once per selection (not once per
44 // iteration) to reduce bias when some disk(s) attract more entries.
45 static int firstCandidate
= 0;
46 if (++firstCandidate
>= Config
.cacheSwap
.n_configured
)
49 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
50 const int dirn
= (firstCandidate
+ i
) % Config
.cacheSwap
.n_configured
;
51 const SwapDir
*sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
54 if (!sd
->canStore(*e
, objsize
, load
))
57 if (load
< 0 || load
> 1000) {
68 * Spread load across all of the store directories
70 * Note: We should modify this later on to prefer sticking objects
71 * in the *tightest fit* swapdir to conserve space, along with the
72 * actual swapdir usage. But for now, this hack will do while
73 * testing, so you should order your swapdirs in the config file
74 * from smallest max-size= to largest max-size=.
76 * We also have to choose nleast == nconf since we need to consider
77 * ALL swapdirs, regardless of state. Again, this is a hack while
78 * we sort out the real usefulness of this algorithm.
81 storeDirSelectSwapDirLeastLoad(const StoreEntry
* e
)
83 int64_t most_free
= 0;
84 ssize_t least_objsize
= -1;
85 int least_load
= INT_MAX
;
91 // e->objectLen() is negative at this point when we are still STORE_PENDING
92 ssize_t objsize
= e
->mem_obj
->expectedReplySize();
95 objsize
+= e
->mem_obj
->swap_hdr_sz
;
97 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
98 SD
= dynamic_cast<SwapDir
*>(INDEXSD(i
));
99 SD
->flags
.selected
= false;
101 if (!SD
->canStore(*e
, objsize
, load
))
104 if (load
< 0 || load
> 1000)
107 if (load
> least_load
)
110 const int64_t cur_free
= SD
->maxSize() - SD
->currentSize();
112 /* If the load is equal, then look in more details */
113 if (load
== least_load
) {
114 /* closest max-size fit */
116 if (least_objsize
!= -1)
117 if (SD
->maxObjectSize() > least_objsize
)
121 if (cur_free
< most_free
)
126 least_objsize
= SD
->maxObjectSize();
127 most_free
= cur_free
;
132 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->flags
.selected
= true;
138 Store::Disks::store(int const x
) const
144 Store::Disks::dir(const int i
) const
146 SwapDir
*sd
= INDEXSD(i
);
152 Store::Disks::callback()
161 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
162 if (ndir
>= Config
.cacheSwap
.n_configured
)
163 ndir
= ndir
% Config
.cacheSwap
.n_configured
;
165 int temp_result
= store(ndir
)->callback();
171 result
+= temp_result
;
174 fatal ("too much io\n");
184 Store::Disks::create()
186 if (Config
.cacheSwap
.n_configured
== 0) {
187 debugs(0, DBG_PARSE_NOTE(DBG_CRITICAL
), "No cache_dir stores are configured.");
190 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
197 Store::Disks::get(const cache_key
*key
)
199 if (const int cacheDirs
= Config
.cacheSwap
.n_configured
) {
200 // ask each cache_dir until the entry is found; use static starting
201 // point to avoid asking the same subset of disks more often
202 // TODO: coordinate with put() to be able to guess the right disk often
204 for (int n
= 0; n
< cacheDirs
; ++n
) {
205 idx
= (idx
+ 1) % cacheDirs
;
206 SwapDir
*sd
= dynamic_cast<SwapDir
*>(INDEXSD(idx
));
210 if (StoreEntry
*e
= sd
->get(key
)) {
211 debugs(20, 7, "cache_dir " << idx
<< " has: " << *e
);
217 debugs(20, 6, "none of " << Config
.cacheSwap
.n_configured
<<
218 " cache_dirs have " << storeKeyText(key
));
225 if (Config
.Store
.objectsPerBucket
<= 0)
226 fatal("'store_objects_per_bucket' should be larger than 0.");
228 if (Config
.Store
.avgObjectSize
<= 0)
229 fatal("'store_avg_object_size' should be larger than 0.");
231 /* Calculate size of hash table (maximum currently 64k buckets). */
232 /* this is very bogus, its specific to the any Store maintaining an
233 * in-core index, not global */
234 size_t buckets
= (Store::Root().maxSize() + Config
.memMaxSize
) / Config
.Store
.avgObjectSize
;
235 debugs(20, DBG_IMPORTANT
, "Swap maxSize " << (Store::Root().maxSize() >> 10) <<
236 " + " << ( Config
.memMaxSize
>> 10) << " KB, estimated " << buckets
<< " objects");
237 buckets
/= Config
.Store
.objectsPerBucket
;
238 debugs(20, DBG_IMPORTANT
, "Target number of buckets: " << buckets
);
239 /* ideally the full scan period should be configurable, for the
240 * moment it remains at approximately 24 hours. */
241 store_hash_buckets
= storeKeyHashBuckets(buckets
);
242 debugs(20, DBG_IMPORTANT
, "Using " << store_hash_buckets
<< " Store buckets");
243 debugs(20, DBG_IMPORTANT
, "Max Mem size: " << ( Config
.memMaxSize
>> 10) << " KB" <<
244 (Config
.memShared
? " [shared]" : ""));
245 debugs(20, DBG_IMPORTANT
, "Max Swap size: " << (Store::Root().maxSize() >> 10) << " KB");
247 store_table
= hash_create(storeKeyHashCmp
,
248 store_hash_buckets
, storeKeyHashHash
);
250 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
251 /* this starts a search of the store dirs, loading their
252 * index. under the new Store api this should be
253 * driven by the StoreHashIndex, not by each store.
255 * That is, the HashIndex should perform a search of each dir it is
256 * indexing to do the hash insertions. The search is then able to
257 * decide 'from-memory', or 'from-clean-log' or 'from-dirty-log' or
260 * Step 1: make the store rebuilds use a search internally
261 * Step 2: change the search logic to use the four modes described
263 * Step 3: have the hash index walk the searches itself.
269 if (strcasecmp(Config
.store_dir_select_algorithm
, "round-robin") == 0) {
270 storeDirSelectSwapDir
= storeDirSelectSwapDirRoundRobin
;
271 debugs(47, DBG_IMPORTANT
, "Using Round Robin store dir selection");
273 storeDirSelectSwapDir
= storeDirSelectSwapDirLeastLoad
;
274 debugs(47, DBG_IMPORTANT
, "Using Least Load store dir selection");
279 Store::Disks::maxSize() const
283 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
284 if (dir(i
).doReportStat())
285 result
+= store(i
)->maxSize();
292 Store::Disks::minSize() const
296 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
297 if (dir(i
).doReportStat())
298 result
+= store(i
)->minSize();
305 Store::Disks::currentSize() const
309 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
310 if (dir(i
).doReportStat())
311 result
+= store(i
)->currentSize();
318 Store::Disks::currentCount() const
322 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
323 if (dir(i
).doReportStat())
324 result
+= store(i
)->currentCount();
331 Store::Disks::maxObjectSize() const
335 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
336 if (dir(i
).active() && store(i
)->maxObjectSize() > result
)
337 result
= store(i
)->maxObjectSize();
344 Store::Disks::getStats(StoreInfoStats
&stats
) const
346 // accumulate per-disk cache stats
347 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
348 StoreInfoStats dirStats
;
349 store(i
)->getStats(dirStats
);
353 // common to all disks
354 stats
.swap
.open_disk_fd
= store_open_disk_fd
;
356 // memory cache stats are collected in StoreController::getStats(), for now
360 Store::Disks::stat(StoreEntry
& output
) const
364 /* Now go through each store, calling its stat routine */
366 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
367 storeAppendPrintf(&output
, "\n");
368 store(i
)->stat(output
);
373 Store::Disks::reference(StoreEntry
&e
)
375 e
.disk().reference(e
);
379 Store::Disks::dereference(StoreEntry
&e
)
381 return e
.disk().dereference(e
);
385 Store::Disks::maintain()
390 for (i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
) {
391 /* XXX FixMe: This should be done "in parallell" on the different
392 * cache_dirs, not one at a time.
394 /* call the maintain function .. */
395 store(i
)->maintain();
402 for (int i
= 0; i
< Config
.cacheSwap
.n_configured
; ++i
)
407 Store::Disks::markForUnlink(StoreEntry
&e
) {
408 if (e
.swap_filen
>= 0)
409 store(e
.swap_dirn
)->markForUnlink(e
);
413 Store::Disks::unlink(StoreEntry
&e
) {
414 if (e
.swap_filen
>= 0)
415 store(e
.swap_dirn
)->unlink(e
);
419 Store::Disks::anchorCollapsed(StoreEntry
&collapsed
, bool &inSync
)
421 if (const int cacheDirs
= Config
.cacheSwap
.n_configured
) {
422 // ask each cache_dir until the entry is found; use static starting
423 // point to avoid asking the same subset of disks more often
424 // TODO: coordinate with put() to be able to guess the right disk often
426 for (int n
= 0; n
< cacheDirs
; ++n
) {
427 idx
= (idx
+ 1) % cacheDirs
;
428 SwapDir
&sd
= dir(idx
);
432 if (sd
.anchorCollapsed(collapsed
, inSync
)) {
433 debugs(20, 3, "cache_dir " << idx
<< " anchors " << collapsed
);
439 debugs(20, 4, "none of " << Config
.cacheSwap
.n_configured
<<
440 " cache_dirs have " << collapsed
);
445 Store::Disks::updateCollapsed(StoreEntry
&collapsed
)
447 return collapsed
.swap_filen
>= 0 &&
448 dir(collapsed
.swap_dirn
).updateCollapsed(collapsed
);
451 /* Store::Disks globals that should be converted to use RegisteredRunner */
454 storeDirOpenSwapLogs()
456 for (int dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
457 INDEXSD(dirn
)->openLog();
461 storeDirCloseSwapLogs()
463 for (int dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
464 INDEXSD(dirn
)->closeLog();
468 * storeDirWriteCleanLogs
470 * Writes a "clean" swap log file from in-memory metadata.
471 * This is a rewrite of the original function to troll each
472 * StoreDir and write the logs, and flush at the end of
473 * the run. Thanks goes to Eric Stern, since this solution
474 * came out of his COSS code.
477 storeDirWriteCleanLogs(int reopen
)
479 const StoreEntry
*e
= NULL
;
482 struct timeval start
;
484 RefCount
<SwapDir
> sd
;
488 // Check for store_dirs_rebuilding because fatal() often calls us in early
489 // initialization phases, before store log is initialized and ready. Also,
490 // some stores probably do not support log cleanup during Store rebuilding.
491 if (StoreController::store_dirs_rebuilding
) {
492 debugs(20, DBG_IMPORTANT
, "Not currently OK to rewrite swap log.");
493 debugs(20, DBG_IMPORTANT
, "storeDirWriteCleanLogs: Operation aborted.");
497 debugs(20, DBG_IMPORTANT
, "storeDirWriteCleanLogs: Starting...");
499 start
= current_time
;
501 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
) {
502 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
504 if (sd
->writeCleanStart() < 0) {
505 debugs(20, DBG_IMPORTANT
, "log.clean.start() failed for dir #" << sd
->index
);
511 * This may look inefficient as CPU wise it is more efficient to do this
512 * sequentially, but I/O wise the parallellism helps as it allows more
513 * hdd spindles to be active.
518 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
) {
519 sd
= dynamic_cast<SwapDir
*>(INDEXSD(dirn
));
521 if (NULL
== sd
->cleanLog
)
524 e
= sd
->cleanLog
->nextEntry();
534 sd
->cleanLog
->write(*e
);
536 if ((++n
& 0xFFFF) == 0) {
538 debugs(20, DBG_IMPORTANT
, " " << std::setw(7) << n
<<
539 " entries written so far.");
545 for (dirn
= 0; dirn
< Config
.cacheSwap
.n_configured
; ++dirn
)
546 dynamic_cast<SwapDir
*>(INDEXSD(dirn
))->writeCleanDone();
549 storeDirOpenSwapLogs();
553 dt
= tvSubDsec(start
, current_time
);
555 debugs(20, DBG_IMPORTANT
, " Finished. Wrote " << n
<< " entries.");
556 debugs(20, DBG_IMPORTANT
, " Took "<< std::setw(3)<< std::setprecision(2) << dt
<<
557 " seconds ("<< std::setw(6) << ((double) n
/ (dt
> 0.0 ? dt
: 1.0)) << " entries/sec).");
562 /* Globals that should be converted to static Store::Disks methods */
565 allocate_new_swapdir(Store::DiskConfig
*swap
)
567 if (swap
->swapDirs
== NULL
) {
568 swap
->n_allocated
= 4;
569 swap
->swapDirs
= static_cast<SwapDir::Pointer
*>(xcalloc(swap
->n_allocated
, sizeof(SwapDir::Pointer
)));
572 if (swap
->n_allocated
== swap
->n_configured
) {
573 swap
->n_allocated
<<= 1;
574 SwapDir::Pointer
*const tmp
= static_cast<SwapDir::Pointer
*>(xcalloc(swap
->n_allocated
, sizeof(SwapDir::Pointer
)));
575 memcpy(tmp
, swap
->swapDirs
, swap
->n_configured
* sizeof(SwapDir
*));
576 xfree(swap
->swapDirs
);
577 swap
->swapDirs
= tmp
;
582 free_cachedir(Store::DiskConfig
*swap
)
585 /* DON'T FREE THESE FOR RECONFIGURE */
590 for (i
= 0; i
< swap
->n_configured
; ++i
) {
591 /* TODO XXX this lets the swapdir free resources asynchronously
592 * swap->swapDirs[i]->deactivate();
593 * but there may be such a means already.
596 swap
->swapDirs
[i
] = NULL
;
599 safe_free(swap
->swapDirs
);
600 swap
->swapDirs
= NULL
;
601 swap
->n_allocated
= 0;
602 swap
->n_configured
= 0;
605 /* Globals that should be moved to some Store::UFS-specific logging module */
608 * An entry written to the swap log MUST have the following
610 * 1. It MUST be a public key. It does no good to log
611 * a public ADD, change the key, then log a private
612 * DEL. So we need to log a DEL before we change a
613 * key from public to private.
614 * 2. It MUST have a valid (> -1) swap_filen.
617 storeDirSwapLog(const StoreEntry
* e
, int op
)
620 assert(!EBIT_TEST(e
->flags
, KEY_PRIVATE
));
621 assert(e
->swap_filen
>= 0);
623 * icons and such; don't write them to the swap log
626 if (EBIT_TEST(e
->flags
, ENTRY_SPECIAL
))
629 assert(op
> SWAP_LOG_NOP
&& op
< SWAP_LOG_MAX
);
631 debugs(20, 3, "storeDirSwapLog: " <<
632 swap_log_op_str
[op
] << " " <<
633 e
->getMD5Text() << " " <<
634 e
->swap_dirn
<< " " <<
635 std::hex
<< std::uppercase
<< std::setfill('0') << std::setw(8) << e
->swap_filen
);
637 dynamic_cast<SwapDir
*>(INDEXSD(e
->swap_dirn
))->logEntry(*e
, op
);