1 // Copyright (c) 2006-2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // The eviction policy is a very simple pure LRU, so the elements at the end of
6 // the list are evicted until kCleanUpMargin free space is available. There is
7 // only one list in use (Rankings::NO_USE), and elements are sent to the front
8 // of the list whenever they are accessed.
9
10 // The new (in-development) eviction policy adds re-use as a factor to evict
11 // an entry. The story so far:
12
13 // Entries are linked on separate lists depending on how often they are used.
14 // When we see an element for the first time, it goes to the NO_USE list; if
15 // the object is reused later on, we move it to the LOW_USE list, until it is
16 // used kHighUse times, at which point it is moved to the HIGH_USE list.
17 // Whenever an element is evicted, we move it to the DELETED list so that if the
18 // element is accessed again, we remember the fact that it was already stored
19 // and maybe in the future we don't evict that element.
20
21 // When we have to evict an element, first we try to use the last element from
22 // the NO_USE list, then we move to the LOW_USE and only then we evict an entry
23 // from the HIGH_USE. We attempt to keep entries on the cache for at least
24 // kTargetTime hours (with frequently accessed items stored for longer periods),
25 // but if we cannot do that, we fall-back to keep each list roughly the same
26 // size so that we have a chance to see an element again and move it to another
27 // list.
28
29 #include "net/disk_cache/eviction.h"
30
31 #include "base/compiler_specific.h"
32 #include "base/logging.h"
33 #include "base/message_loop.h"
34 #include "base/string_util.h"
35 #include "base/time.h"
36 #include "net/disk_cache/backend_impl.h"
37 #include "net/disk_cache/entry_impl.h"
38 #include "net/disk_cache/experiments.h"
39 #include "net/disk_cache/histogram_macros.h"
40 #include "net/disk_cache/trace.h"
41
42 using base::Time;
43 using base::TimeTicks;
44
45 namespace {
46
47 const int kCleanUpMargin = 1024 * 1024;
48 const int kHighUse = 10; // Reuse count to be on the HIGH_USE list.
49 const int kTargetTime = 24 * 7; // Time to be evicted (hours since last use).
50 const int kMaxDelayedTrims = 60;
51
LowWaterAdjust(int high_water)52 int LowWaterAdjust(int high_water) {
53 if (high_water < kCleanUpMargin)
54 return 0;
55
56 return high_water - kCleanUpMargin;
57 }
58
59 } // namespace
60
61 namespace disk_cache {
62
Eviction()63 Eviction::Eviction()
64 : backend_(NULL),
65 init_(false),
66 ALLOW_THIS_IN_INITIALIZER_LIST(factory_(this)) {
67 }
68
~Eviction()69 Eviction::~Eviction() {
70 }
71
Init(BackendImpl * backend)72 void Eviction::Init(BackendImpl* backend) {
73 // We grab a bunch of info from the backend to make the code a little cleaner
74 // when we're actually doing work.
75 backend_ = backend;
76 rankings_ = &backend->rankings_;
77 header_ = &backend_->data_->header;
78 max_size_ = LowWaterAdjust(backend_->max_size_);
79 new_eviction_ = backend->new_eviction_;
80 first_trim_ = true;
81 trimming_ = false;
82 delay_trim_ = false;
83 trim_delays_ = 0;
84 init_ = true;
85 test_mode_ = false;
86 in_experiment_ = (header_->experiment == EXPERIMENT_DELETED_LIST_IN);
87 }
88
Stop()89 void Eviction::Stop() {
90 // It is possible for the backend initialization to fail, in which case this
91 // object was never initialized... and there is nothing to do.
92 if (!init_)
93 return;
94
95 // We want to stop further evictions, so let's pretend that we are busy from
96 // this point on.
97 DCHECK(!trimming_);
98 trimming_ = true;
99 factory_.RevokeAll();
100 }
101
TrimCache(bool empty)102 void Eviction::TrimCache(bool empty) {
103 if (backend_->disabled_ || trimming_)
104 return;
105
106 if (!empty && !ShouldTrim())
107 return PostDelayedTrim();
108
109 if (new_eviction_)
110 return TrimCacheV2(empty);
111
112 Trace("*** Trim Cache ***");
113 trimming_ = true;
114 TimeTicks start = TimeTicks::Now();
115 Rankings::ScopedRankingsBlock node(rankings_);
116 Rankings::ScopedRankingsBlock next(rankings_,
117 rankings_->GetPrev(node.get(), Rankings::NO_USE));
118 int target_size = empty ? 0 : max_size_;
119 while (header_->num_bytes > target_size && next.get()) {
120 // The iterator could be invalidated within EvictEntry().
121 if (!next->HasData())
122 break;
123 node.reset(next.release());
124 next.reset(rankings_->GetPrev(node.get(), Rankings::NO_USE));
125 if (node->Data()->dirty != backend_->GetCurrentEntryId() || empty) {
126 // This entry is not being used by anybody.
127 // Do NOT use node as an iterator after this point.
128 rankings_->TrackRankingsBlock(node.get(), false);
129 if (!EvictEntry(node.get(), empty) && !test_mode_)
130 continue;
131
132 if (!empty) {
133 backend_->OnEvent(Stats::TRIM_ENTRY);
134 if (test_mode_)
135 break;
136
137 if ((TimeTicks::Now() - start).InMilliseconds() > 20) {
138 MessageLoop::current()->PostTask(FROM_HERE,
139 factory_.NewRunnableMethod(&Eviction::TrimCache, false));
140 break;
141 }
142 }
143 }
144 }
145
146 if (empty) {
147 CACHE_UMA(AGE_MS, "TotalClearTimeV1", 0, start);
148 } else {
149 CACHE_UMA(AGE_MS, "TotalTrimTimeV1", backend_->GetSizeGroup(), start);
150 }
151
152 trimming_ = false;
153 Trace("*** Trim Cache end ***");
154 return;
155 }
156
UpdateRank(EntryImpl * entry,bool modified)157 void Eviction::UpdateRank(EntryImpl* entry, bool modified) {
158 if (new_eviction_)
159 return UpdateRankV2(entry, modified);
160
161 rankings_->UpdateRank(entry->rankings(), modified, GetListForEntry(entry));
162 }
163
OnOpenEntry(EntryImpl * entry)164 void Eviction::OnOpenEntry(EntryImpl* entry) {
165 if (new_eviction_)
166 return OnOpenEntryV2(entry);
167 }
168
OnCreateEntry(EntryImpl * entry)169 void Eviction::OnCreateEntry(EntryImpl* entry) {
170 if (new_eviction_)
171 return OnCreateEntryV2(entry);
172
173 rankings_->Insert(entry->rankings(), true, GetListForEntry(entry));
174 }
175
OnDoomEntry(EntryImpl * entry)176 void Eviction::OnDoomEntry(EntryImpl* entry) {
177 if (new_eviction_)
178 return OnDoomEntryV2(entry);
179
180 rankings_->Remove(entry->rankings(), GetListForEntry(entry));
181 }
182
OnDestroyEntry(EntryImpl * entry)183 void Eviction::OnDestroyEntry(EntryImpl* entry) {
184 if (new_eviction_)
185 return OnDestroyEntryV2(entry);
186 }
187
SetTestMode()188 void Eviction::SetTestMode() {
189 test_mode_ = true;
190 }
191
TrimDeletedList(bool empty)192 void Eviction::TrimDeletedList(bool empty) {
193 DCHECK(test_mode_ && new_eviction_);
194 TrimDeleted(empty);
195 }
196
PostDelayedTrim()197 void Eviction::PostDelayedTrim() {
198 // Prevent posting multiple tasks.
199 if (delay_trim_)
200 return;
201 delay_trim_ = true;
202 trim_delays_++;
203 MessageLoop::current()->PostDelayedTask(FROM_HERE,
204 factory_.NewRunnableMethod(&Eviction::DelayedTrim), 1000);
205 }
206
DelayedTrim()207 void Eviction::DelayedTrim() {
208 delay_trim_ = false;
209 if (trim_delays_ < kMaxDelayedTrims && backend_->IsLoaded())
210 return PostDelayedTrim();
211
212 TrimCache(false);
213 }
214
ShouldTrim()215 bool Eviction::ShouldTrim() {
216 if (trim_delays_ < kMaxDelayedTrims && backend_->IsLoaded())
217 return false;
218
219 UMA_HISTOGRAM_COUNTS("DiskCache.TrimDelays", trim_delays_);
220 trim_delays_ = 0;
221 return true;
222 }
223
ReportTrimTimes(EntryImpl * entry)224 void Eviction::ReportTrimTimes(EntryImpl* entry) {
225 if (first_trim_) {
226 first_trim_ = false;
227 if (backend_->ShouldReportAgain()) {
228 CACHE_UMA(AGE, "TrimAge", 0, entry->GetLastUsed());
229 ReportListStats();
230 }
231
232 if (header_->lru.filled)
233 return;
234
235 header_->lru.filled = 1;
236
237 if (header_->create_time) {
238 // This is the first entry that we have to evict, generate some noise.
239 backend_->FirstEviction();
240 } else {
241 // This is an old file, but we may want more reports from this user so
242 // lets save some create_time.
243 Time::Exploded old = {0};
244 old.year = 2009;
245 old.month = 3;
246 old.day_of_month = 1;
247 header_->create_time = Time::FromLocalExploded(old).ToInternalValue();
248 }
249 }
250 }
251
GetListForEntry(EntryImpl * entry)252 Rankings::List Eviction::GetListForEntry(EntryImpl* entry) {
253 return Rankings::NO_USE;
254 }
255
EvictEntry(CacheRankingsBlock * node,bool empty)256 bool Eviction::EvictEntry(CacheRankingsBlock* node, bool empty) {
257 EntryImpl* entry = backend_->GetEnumeratedEntry(node);
258 if (!entry) {
259 Trace("NewEntry failed on Trim 0x%x", node->address().value());
260 return false;
261 }
262
263 ReportTrimTimes(entry);
264 if (empty || !new_eviction_) {
265 entry->DoomImpl();
266 } else {
267 entry->DeleteEntryData(false);
268 EntryStore* info = entry->entry()->Data();
269 DCHECK(ENTRY_NORMAL == info->state);
270
271 rankings_->Remove(entry->rankings(), GetListForEntryV2(entry));
272 info->state = ENTRY_EVICTED;
273 entry->entry()->Store();
274 rankings_->Insert(entry->rankings(), true, Rankings::DELETED);
275 backend_->OnEvent(Stats::TRIM_ENTRY);
276 }
277 entry->Release();
278
279 return true;
280 }
281
282 // -----------------------------------------------------------------------
283
TrimCacheV2(bool empty)284 void Eviction::TrimCacheV2(bool empty) {
285 Trace("*** Trim Cache ***");
286 trimming_ = true;
287 TimeTicks start = TimeTicks::Now();
288
289 const int kListsToSearch = 3;
290 Rankings::ScopedRankingsBlock next[kListsToSearch];
291 int list = Rankings::LAST_ELEMENT;
292
293 // Get a node from each list.
294 for (int i = 0; i < kListsToSearch; i++) {
295 bool done = false;
296 next[i].set_rankings(rankings_);
297 if (done)
298 continue;
299 next[i].reset(rankings_->GetPrev(NULL, static_cast<Rankings::List>(i)));
300 if (!empty && NodeIsOldEnough(next[i].get(), i)) {
301 list = static_cast<Rankings::List>(i);
302 done = true;
303 }
304 }
305
306 // If we are not meeting the time targets lets move on to list length.
307 if (!empty && Rankings::LAST_ELEMENT == list) {
308 list = SelectListByLenght();
309 // Make sure that frequently used items are kept for a minimum time; we know
310 // that this entry is not older than its current target, but it must be at
311 // least older than the target for list 0 (kTargetTime).
312 if ((Rankings::HIGH_USE == list || Rankings::LOW_USE == list) &&
313 !NodeIsOldEnough(next[list].get(), 0))
314 list = 0;
315 }
316
317 if (empty)
318 list = 0;
319
320 Rankings::ScopedRankingsBlock node(rankings_);
321
322 int target_size = empty ? 0 : max_size_;
323 for (; list < kListsToSearch; list++) {
324 while (header_->num_bytes > target_size && next[list].get()) {
325 // The iterator could be invalidated within EvictEntry().
326 if (!next[list]->HasData())
327 break;
328 node.reset(next[list].release());
329 next[list].reset(rankings_->GetPrev(node.get(),
330 static_cast<Rankings::List>(list)));
331 if (node->Data()->dirty != backend_->GetCurrentEntryId() || empty) {
332 // This entry is not being used by anybody.
333 // Do NOT use node as an iterator after this point.
334 rankings_->TrackRankingsBlock(node.get(), false);
335 if (!EvictEntry(node.get(), empty) && !test_mode_)
336 continue;
337
338 if (!empty && test_mode_)
339 break;
340
341 if (!empty && (TimeTicks::Now() - start).InMilliseconds() > 20) {
342 MessageLoop::current()->PostTask(FROM_HERE,
343 factory_.NewRunnableMethod(&Eviction::TrimCache, false));
344 break;
345 }
346 }
347 }
348 if (!empty)
349 list = kListsToSearch;
350 }
351
352 if (empty) {
353 TrimDeleted(true);
354 } else if (header_->lru.sizes[Rankings::DELETED] > header_->num_entries / 4 &&
355 !test_mode_) {
356 MessageLoop::current()->PostTask(FROM_HERE,
357 factory_.NewRunnableMethod(&Eviction::TrimDeleted, empty));
358 }
359
360 if (empty) {
361 CACHE_UMA(AGE_MS, "TotalClearTimeV2", 0, start);
362 } else {
363 CACHE_UMA(AGE_MS, "TotalTrimTimeV2", backend_->GetSizeGroup(), start);
364 }
365
366 Trace("*** Trim Cache end ***");
367 trimming_ = false;
368 return;
369 }
370
UpdateRankV2(EntryImpl * entry,bool modified)371 void Eviction::UpdateRankV2(EntryImpl* entry, bool modified) {
372 rankings_->UpdateRank(entry->rankings(), modified, GetListForEntryV2(entry));
373 }
374
OnOpenEntryV2(EntryImpl * entry)375 void Eviction::OnOpenEntryV2(EntryImpl* entry) {
376 EntryStore* info = entry->entry()->Data();
377 DCHECK(ENTRY_NORMAL == info->state);
378
379 if (info->reuse_count < kint32max) {
380 info->reuse_count++;
381 entry->entry()->set_modified();
382
383 // We may need to move this to a new list.
384 if (1 == info->reuse_count) {
385 rankings_->Remove(entry->rankings(), Rankings::NO_USE);
386 rankings_->Insert(entry->rankings(), false, Rankings::LOW_USE);
387 entry->entry()->Store();
388 } else if (kHighUse == info->reuse_count) {
389 rankings_->Remove(entry->rankings(), Rankings::LOW_USE);
390 rankings_->Insert(entry->rankings(), false, Rankings::HIGH_USE);
391 entry->entry()->Store();
392 }
393 }
394 }
395
OnCreateEntryV2(EntryImpl * entry)396 void Eviction::OnCreateEntryV2(EntryImpl* entry) {
397 EntryStore* info = entry->entry()->Data();
398 switch (info->state) {
399 case ENTRY_NORMAL: {
400 DCHECK(!info->reuse_count);
401 DCHECK(!info->refetch_count);
402 break;
403 };
404 case ENTRY_EVICTED: {
405 if (info->refetch_count < kint32max)
406 info->refetch_count++;
407
408 if (info->refetch_count > kHighUse && info->reuse_count < kHighUse) {
409 info->reuse_count = kHighUse;
410 } else {
411 info->reuse_count++;
412 }
413 info->state = ENTRY_NORMAL;
414 entry->entry()->Store();
415 rankings_->Remove(entry->rankings(), Rankings::DELETED);
416 break;
417 };
418 default:
419 NOTREACHED();
420 }
421
422 rankings_->Insert(entry->rankings(), true, GetListForEntryV2(entry));
423 }
424
OnDoomEntryV2(EntryImpl * entry)425 void Eviction::OnDoomEntryV2(EntryImpl* entry) {
426 EntryStore* info = entry->entry()->Data();
427 if (ENTRY_NORMAL != info->state)
428 return;
429
430 rankings_->Remove(entry->rankings(), GetListForEntryV2(entry));
431
432 info->state = ENTRY_DOOMED;
433 entry->entry()->Store();
434 rankings_->Insert(entry->rankings(), true, Rankings::DELETED);
435 }
436
OnDestroyEntryV2(EntryImpl * entry)437 void Eviction::OnDestroyEntryV2(EntryImpl* entry) {
438 rankings_->Remove(entry->rankings(), Rankings::DELETED);
439 }
440
GetListForEntryV2(EntryImpl * entry)441 Rankings::List Eviction::GetListForEntryV2(EntryImpl* entry) {
442 EntryStore* info = entry->entry()->Data();
443 DCHECK(ENTRY_NORMAL == info->state);
444
445 if (!info->reuse_count)
446 return Rankings::NO_USE;
447
448 if (info->reuse_count < kHighUse)
449 return Rankings::LOW_USE;
450
451 return Rankings::HIGH_USE;
452 }
453
454 // This is a minimal implementation that just discards the oldest nodes.
455 // TODO(rvargas): Do something better here.
TrimDeleted(bool empty)456 void Eviction::TrimDeleted(bool empty) {
457 Trace("*** Trim Deleted ***");
458 if (backend_->disabled_)
459 return;
460
461 TimeTicks start = TimeTicks::Now();
462 Rankings::ScopedRankingsBlock node(rankings_);
463 Rankings::ScopedRankingsBlock next(rankings_,
464 rankings_->GetPrev(node.get(), Rankings::DELETED));
465 bool deleted = false;
466 for (int i = 0; (i < 4 || empty) && next.get(); i++) {
467 node.reset(next.release());
468 next.reset(rankings_->GetPrev(node.get(), Rankings::DELETED));
469 deleted |= RemoveDeletedNode(node.get());
470 if (test_mode_)
471 break;
472 }
473
474 // Normally we use 25% for each list. The experiment doubles the number of
475 // deleted entries, so the total number of entries increases by 25%. Using
476 // 40% of that value for deleted entries leaves the size of the other three
477 // lists intact.
478 int max_length = in_experiment_ ? header_->num_entries * 2 / 5 :
479 header_->num_entries / 4;
480 if (deleted && !empty && !test_mode_ &&
481 header_->lru.sizes[Rankings::DELETED] > max_length) {
482 MessageLoop::current()->PostTask(FROM_HERE,
483 factory_.NewRunnableMethod(&Eviction::TrimDeleted, false));
484 }
485
486 CACHE_UMA(AGE_MS, "TotalTrimDeletedTime", 0, start);
487 Trace("*** Trim Deleted end ***");
488 return;
489 }
490
RemoveDeletedNode(CacheRankingsBlock * node)491 bool Eviction::RemoveDeletedNode(CacheRankingsBlock* node) {
492 EntryImpl* entry = backend_->GetEnumeratedEntry(node);
493 if (!entry) {
494 Trace("NewEntry failed on Trim 0x%x", node->address().value());
495 return false;
496 }
497
498 bool doomed = (entry->entry()->Data()->state == ENTRY_DOOMED);
499 entry->entry()->Data()->state = ENTRY_DOOMED;
500 entry->DoomImpl();
501 entry->Release();
502 return !doomed;
503 }
504
NodeIsOldEnough(CacheRankingsBlock * node,int list)505 bool Eviction::NodeIsOldEnough(CacheRankingsBlock* node, int list) {
506 if (!node)
507 return false;
508
509 // If possible, we want to keep entries on each list at least kTargetTime
510 // hours. Each successive list on the enumeration has 2x the target time of
511 // the previous list.
512 Time used = Time::FromInternalValue(node->Data()->last_used);
513 int multiplier = 1 << list;
514 return (Time::Now() - used).InHours() > kTargetTime * multiplier;
515 }
516
SelectListByLenght()517 int Eviction::SelectListByLenght() {
518 int data_entries = header_->num_entries -
519 header_->lru.sizes[Rankings::DELETED];
520 // Start by having each list to be roughly the same size.
521 if (header_->lru.sizes[0] > data_entries / 3)
522 return 0;
523 if (header_->lru.sizes[1] > data_entries / 3)
524 return 1;
525 return 2;
526 }
527
ReportListStats()528 void Eviction::ReportListStats() {
529 if (!new_eviction_)
530 return;
531
532 Rankings::ScopedRankingsBlock last1(rankings_,
533 rankings_->GetPrev(NULL, Rankings::NO_USE));
534 Rankings::ScopedRankingsBlock last2(rankings_,
535 rankings_->GetPrev(NULL, Rankings::LOW_USE));
536 Rankings::ScopedRankingsBlock last3(rankings_,
537 rankings_->GetPrev(NULL, Rankings::HIGH_USE));
538 Rankings::ScopedRankingsBlock last4(rankings_,
539 rankings_->GetPrev(NULL, Rankings::DELETED));
540
541 if (last1.get())
542 CACHE_UMA(AGE, "NoUseAge", 0,
543 Time::FromInternalValue(last1.get()->Data()->last_used));
544 if (last2.get())
545 CACHE_UMA(AGE, "LowUseAge", 0,
546 Time::FromInternalValue(last2.get()->Data()->last_used));
547 if (last3.get())
548 CACHE_UMA(AGE, "HighUseAge", 0,
549 Time::FromInternalValue(last3.get()->Data()->last_used));
550 if (last4.get())
551 CACHE_UMA(AGE, "DeletedAge", 0,
552 Time::FromInternalValue(last4.get()->Data()->last_used));
553 }
554
555 } // namespace disk_cache
556