cc: Added inline to Tile::IsReadyToDraw
[chromium-blink-merge.git] / net / disk_cache / v3 / eviction_v3.cc
blob91275fc7bc2e1fa566d6f8dff17682922ee660a5
1 // Copyright (c) 2012 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.
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.
10 // The new (in-development) eviction policy adds re-use as a factor to evict
11 // an entry. The story so far:
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.
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.
29 #include "net/disk_cache/eviction.h"
31 #include "base/bind.h"
32 #include "base/compiler_specific.h"
33 #include "base/logging.h"
34 #include "base/message_loop/message_loop.h"
35 #include "base/strings/string_util.h"
36 #include "base/time/time.h"
37 #include "net/disk_cache/backend_impl.h"
38 #include "net/disk_cache/entry_impl.h"
39 #include "net/disk_cache/experiments.h"
40 #include "net/disk_cache/histogram_macros.h"
41 #include "net/disk_cache/trace.h"
43 using base::Time;
44 using base::TimeTicks;
46 namespace {
48 const int kCleanUpMargin = 1024 * 1024;
49 const int kHighUse = 10; // Reuse count to be on the HIGH_USE list.
50 const int kTargetTime = 24 * 7; // Time to be evicted (hours since last use).
51 const int kMaxDelayedTrims = 60;
53 int LowWaterAdjust(int high_water) {
54 if (high_water < kCleanUpMargin)
55 return 0;
57 return high_water - kCleanUpMargin;
60 bool FallingBehind(int current_size, int max_size) {
61 return current_size > max_size - kCleanUpMargin * 20;
64 } // namespace
66 namespace disk_cache {
68 // The real initialization happens during Init(), init_ is the only member that
69 // has to be initialized here.
70 Eviction::Eviction()
71 : backend_(NULL),
72 init_(false),
73 ptr_factory_(this) {
76 Eviction::~Eviction() {
79 void Eviction::Init(BackendImpl* backend) {
80 // We grab a bunch of info from the backend to make the code a little cleaner
81 // when we're actually doing work.
82 backend_ = backend;
83 rankings_ = &backend->rankings_;
84 header_ = &backend_->data_->header;
85 max_size_ = LowWaterAdjust(backend_->max_size_);
86 index_size_ = backend->mask_ + 1;
87 new_eviction_ = backend->new_eviction_;
88 first_trim_ = true;
89 trimming_ = false;
90 delay_trim_ = false;
91 trim_delays_ = 0;
92 init_ = true;
93 test_mode_ = false;
96 void Eviction::Stop() {
97 // It is possible for the backend initialization to fail, in which case this
98 // object was never initialized... and there is nothing to do.
99 if (!init_)
100 return;
102 // We want to stop further evictions, so let's pretend that we are busy from
103 // this point on.
104 DCHECK(!trimming_);
105 trimming_ = true;
106 ptr_factory_.InvalidateWeakPtrs();
109 void Eviction::TrimCache(bool empty) {
110 if (backend_->disabled_ || trimming_)
111 return;
113 if (!empty && !ShouldTrim())
114 return PostDelayedTrim();
116 if (new_eviction_)
117 return TrimCacheV2(empty);
119 Trace("*** Trim Cache ***");
120 trimming_ = true;
121 TimeTicks start = TimeTicks::Now();
122 Rankings::ScopedRankingsBlock node(rankings_);
123 Rankings::ScopedRankingsBlock next(
124 rankings_, rankings_->GetPrev(node.get(), Rankings::NO_USE));
125 int deleted_entries = 0;
126 int target_size = empty ? 0 : max_size_;
127 while ((header_->num_bytes > target_size || test_mode_) && next.get()) {
128 // The iterator could be invalidated within EvictEntry().
129 if (!next->HasData())
130 break;
131 node.reset(next.release());
132 next.reset(rankings_->GetPrev(node.get(), Rankings::NO_USE));
133 if (node->Data()->dirty != backend_->GetCurrentEntryId() || empty) {
134 // This entry is not being used by anybody.
135 // Do NOT use node as an iterator after this point.
136 rankings_->TrackRankingsBlock(node.get(), false);
137 if (EvictEntry(node.get(), empty, Rankings::NO_USE) && !test_mode_)
138 deleted_entries++;
140 if (!empty && test_mode_)
141 break;
143 if (!empty && (deleted_entries > 20 ||
144 (TimeTicks::Now() - start).InMilliseconds() > 20)) {
145 base::MessageLoop::current()->PostTask(
146 FROM_HERE,
147 base::Bind(&Eviction::TrimCache, ptr_factory_.GetWeakPtr(), false));
148 break;
152 if (empty) {
153 CACHE_UMA(AGE_MS, "TotalClearTimeV1", 0, start);
154 } else {
155 CACHE_UMA(AGE_MS, "TotalTrimTimeV1", 0, start);
157 CACHE_UMA(COUNTS, "TrimItemsV1", 0, deleted_entries);
159 trimming_ = false;
160 Trace("*** Trim Cache end ***");
161 return;
164 void Eviction::OnOpenEntryV2(EntryImpl* entry) {
165 EntryStore* info = entry->entry()->Data();
166 DCHECK_EQ(ENTRY_NORMAL, info->state);
168 if (info->reuse_count < kint32max) {
169 info->reuse_count++;
170 entry->entry()->set_modified();
172 // We may need to move this to a new list.
173 if (1 == info->reuse_count) {
174 rankings_->Remove(entry->rankings(), Rankings::NO_USE, true);
175 rankings_->Insert(entry->rankings(), false, Rankings::LOW_USE);
176 entry->entry()->Store();
177 } else if (kHighUse == info->reuse_count) {
178 rankings_->Remove(entry->rankings(), Rankings::LOW_USE, true);
179 rankings_->Insert(entry->rankings(), false, Rankings::HIGH_USE);
180 entry->entry()->Store();
185 void Eviction::OnCreateEntryV2(EntryImpl* entry) {
186 EntryStore* info = entry->entry()->Data();
187 switch (info->state) {
188 case ENTRY_NORMAL: {
189 DCHECK(!info->reuse_count);
190 DCHECK(!info->refetch_count);
191 break;
193 case ENTRY_EVICTED: {
194 if (info->refetch_count < kint32max)
195 info->refetch_count++;
197 if (info->refetch_count > kHighUse && info->reuse_count < kHighUse) {
198 info->reuse_count = kHighUse;
199 } else {
200 info->reuse_count++;
202 info->state = ENTRY_NORMAL;
203 entry->entry()->Store();
204 rankings_->Remove(entry->rankings(), Rankings::DELETED, true);
205 break;
207 default:
208 NOTREACHED();
211 rankings_->Insert(entry->rankings(), true, GetListForEntryV2(entry));
214 void Eviction::SetTestMode() {
215 test_mode_ = true;
218 void Eviction::TrimDeletedList(bool empty) {
219 DCHECK(test_mode_ && new_eviction_);
220 TrimDeleted(empty);
223 // -----------------------------------------------------------------------
225 void Eviction::PostDelayedTrim() {
226 // Prevent posting multiple tasks.
227 if (delay_trim_)
228 return;
229 delay_trim_ = true;
230 trim_delays_++;
231 base::MessageLoop::current()->PostDelayedTask(
232 FROM_HERE,
233 base::Bind(&Eviction::DelayedTrim, ptr_factory_.GetWeakPtr()),
234 base::TimeDelta::FromMilliseconds(1000));
237 void Eviction::DelayedTrim() {
238 delay_trim_ = false;
239 if (trim_delays_ < kMaxDelayedTrims && backend_->IsLoaded())
240 return PostDelayedTrim();
242 TrimCache(false);
245 bool Eviction::ShouldTrim() {
246 if (!FallingBehind(header_->num_bytes, max_size_) &&
247 trim_delays_ < kMaxDelayedTrims && backend_->IsLoaded()) {
248 return false;
251 UMA_HISTOGRAM_COUNTS("DiskCache.TrimDelays", trim_delays_);
252 trim_delays_ = 0;
253 return true;
256 bool Eviction::ShouldTrimDeleted() {
257 int index_load = header_->num_entries * 100 / index_size_;
259 // If the index is not loaded, the deleted list will tend to double the size
260 // of the other lists 3 lists (40% of the total). Otherwise, all lists will be
261 // about the same size.
262 int max_length = (index_load < 25) ? header_->num_entries * 2 / 5 :
263 header_->num_entries / 4;
264 return (!test_mode_ && header_->lru.sizes[Rankings::DELETED] > max_length);
267 bool Eviction::EvictEntry(CacheRankingsBlock* node, bool empty,
268 Rankings::List list) {
269 EntryImpl* entry = backend_->GetEnumeratedEntry(node, list);
270 if (!entry) {
271 Trace("NewEntry failed on Trim 0x%x", node->address().value());
272 return false;
275 ReportTrimTimes(entry);
276 if (empty || !new_eviction_) {
277 entry->DoomImpl();
278 } else {
279 entry->DeleteEntryData(false);
280 EntryStore* info = entry->entry()->Data();
281 DCHECK_EQ(ENTRY_NORMAL, info->state);
283 rankings_->Remove(entry->rankings(), GetListForEntryV2(entry), true);
284 info->state = ENTRY_EVICTED;
285 entry->entry()->Store();
286 rankings_->Insert(entry->rankings(), true, Rankings::DELETED);
288 if (!empty)
289 backend_->OnEvent(Stats::TRIM_ENTRY);
291 entry->Release();
293 return true;
296 void Eviction::TrimCacheV2(bool empty) {
297 Trace("*** Trim Cache ***");
298 trimming_ = true;
299 TimeTicks start = TimeTicks::Now();
301 const int kListsToSearch = 3;
302 Rankings::ScopedRankingsBlock next[kListsToSearch];
303 int list = Rankings::LAST_ELEMENT;
305 // Get a node from each list.
306 for (int i = 0; i < kListsToSearch; i++) {
307 bool done = false;
308 next[i].set_rankings(rankings_);
309 if (done)
310 continue;
311 next[i].reset(rankings_->GetPrev(NULL, static_cast<Rankings::List>(i)));
312 if (!empty && NodeIsOldEnough(next[i].get(), i)) {
313 list = static_cast<Rankings::List>(i);
314 done = true;
318 // If we are not meeting the time targets lets move on to list length.
319 if (!empty && Rankings::LAST_ELEMENT == list)
320 list = SelectListByLength(next);
322 if (empty)
323 list = 0;
325 Rankings::ScopedRankingsBlock node(rankings_);
326 int deleted_entries = 0;
327 int target_size = empty ? 0 : max_size_;
329 for (; list < kListsToSearch; list++) {
330 while ((header_->num_bytes > target_size || test_mode_) &&
331 next[list].get()) {
332 // The iterator could be invalidated within EvictEntry().
333 if (!next[list]->HasData())
334 break;
335 node.reset(next[list].release());
336 next[list].reset(rankings_->GetPrev(node.get(),
337 static_cast<Rankings::List>(list)));
338 if (node->Data()->dirty != backend_->GetCurrentEntryId() || empty) {
339 // This entry is not being used by anybody.
340 // Do NOT use node as an iterator after this point.
341 rankings_->TrackRankingsBlock(node.get(), false);
342 if (EvictEntry(node.get(), empty, static_cast<Rankings::List>(list)))
343 deleted_entries++;
345 if (!empty && test_mode_)
346 break;
348 if (!empty && (deleted_entries > 20 ||
349 (TimeTicks::Now() - start).InMilliseconds() > 20)) {
350 base::MessageLoop::current()->PostTask(
351 FROM_HERE,
352 base::Bind(&Eviction::TrimCache, ptr_factory_.GetWeakPtr(), false));
353 break;
356 if (!empty)
357 list = kListsToSearch;
360 if (empty) {
361 TrimDeleted(true);
362 } else if (ShouldTrimDeleted()) {
363 base::MessageLoop::current()->PostTask(
364 FROM_HERE,
365 base::Bind(&Eviction::TrimDeleted, ptr_factory_.GetWeakPtr(), empty));
368 if (empty) {
369 CACHE_UMA(AGE_MS, "TotalClearTimeV2", 0, start);
370 } else {
371 CACHE_UMA(AGE_MS, "TotalTrimTimeV2", 0, start);
373 CACHE_UMA(COUNTS, "TrimItemsV2", 0, deleted_entries);
375 Trace("*** Trim Cache end ***");
376 trimming_ = false;
377 return;
380 // This is a minimal implementation that just discards the oldest nodes.
381 // TODO(rvargas): Do something better here.
382 void Eviction::TrimDeleted(bool empty) {
383 Trace("*** Trim Deleted ***");
384 if (backend_->disabled_)
385 return;
387 TimeTicks start = TimeTicks::Now();
388 Rankings::ScopedRankingsBlock node(rankings_);
389 Rankings::ScopedRankingsBlock next(
390 rankings_, rankings_->GetPrev(node.get(), Rankings::DELETED));
391 int deleted_entries = 0;
392 while (next.get() &&
393 (empty || (deleted_entries < 20 &&
394 (TimeTicks::Now() - start).InMilliseconds() < 20))) {
395 node.reset(next.release());
396 next.reset(rankings_->GetPrev(node.get(), Rankings::DELETED));
397 if (RemoveDeletedNode(node.get()))
398 deleted_entries++;
399 if (test_mode_)
400 break;
403 if (deleted_entries && !empty && ShouldTrimDeleted()) {
404 base::MessageLoop::current()->PostTask(
405 FROM_HERE,
406 base::Bind(&Eviction::TrimDeleted, ptr_factory_.GetWeakPtr(), false));
409 CACHE_UMA(AGE_MS, "TotalTrimDeletedTime", 0, start);
410 CACHE_UMA(COUNTS, "TrimDeletedItems", 0, deleted_entries);
411 Trace("*** Trim Deleted end ***");
412 return;
415 void Eviction::ReportTrimTimes(EntryImpl* entry) {
416 if (first_trim_) {
417 first_trim_ = false;
418 if (backend_->ShouldReportAgain()) {
419 CACHE_UMA(AGE, "TrimAge", 0, entry->GetLastUsed());
420 ReportListStats();
423 if (header_->lru.filled)
424 return;
426 header_->lru.filled = 1;
428 if (header_->create_time) {
429 // This is the first entry that we have to evict, generate some noise.
430 backend_->FirstEviction();
431 } else {
432 // This is an old file, but we may want more reports from this user so
433 // lets save some create_time.
434 Time::Exploded old = {0};
435 old.year = 2009;
436 old.month = 3;
437 old.day_of_month = 1;
438 header_->create_time = Time::FromLocalExploded(old).ToInternalValue();
443 bool Eviction::NodeIsOldEnough(CacheRankingsBlock* node, int list) {
444 if (!node)
445 return false;
447 // If possible, we want to keep entries on each list at least kTargetTime
448 // hours. Each successive list on the enumeration has 2x the target time of
449 // the previous list.
450 Time used = Time::FromInternalValue(node->Data()->last_used);
451 int multiplier = 1 << list;
452 return (Time::Now() - used).InHours() > kTargetTime * multiplier;
455 int Eviction::SelectListByLength(Rankings::ScopedRankingsBlock* next) {
456 int data_entries = header_->num_entries -
457 header_->lru.sizes[Rankings::DELETED];
458 // Start by having each list to be roughly the same size.
459 if (header_->lru.sizes[0] > data_entries / 3)
460 return 0;
462 int list = (header_->lru.sizes[1] > data_entries / 3) ? 1 : 2;
464 // Make sure that frequently used items are kept for a minimum time; we know
465 // that this entry is not older than its current target, but it must be at
466 // least older than the target for list 0 (kTargetTime), as long as we don't
467 // exhaust list 0.
468 if (!NodeIsOldEnough(next[list].get(), 0) &&
469 header_->lru.sizes[0] > data_entries / 10)
470 list = 0;
472 return list;
475 void Eviction::ReportListStats() {
476 if (!new_eviction_)
477 return;
479 Rankings::ScopedRankingsBlock last1(rankings_,
480 rankings_->GetPrev(NULL, Rankings::NO_USE));
481 Rankings::ScopedRankingsBlock last2(rankings_,
482 rankings_->GetPrev(NULL, Rankings::LOW_USE));
483 Rankings::ScopedRankingsBlock last3(rankings_,
484 rankings_->GetPrev(NULL, Rankings::HIGH_USE));
485 Rankings::ScopedRankingsBlock last4(rankings_,
486 rankings_->GetPrev(NULL, Rankings::DELETED));
488 if (last1.get())
489 CACHE_UMA(AGE, "NoUseAge", 0,
490 Time::FromInternalValue(last1.get()->Data()->last_used));
491 if (last2.get())
492 CACHE_UMA(AGE, "LowUseAge", 0,
493 Time::FromInternalValue(last2.get()->Data()->last_used));
494 if (last3.get())
495 CACHE_UMA(AGE, "HighUseAge", 0,
496 Time::FromInternalValue(last3.get()->Data()->last_used));
497 if (last4.get())
498 CACHE_UMA(AGE, "DeletedAge", 0,
499 Time::FromInternalValue(last4.get()->Data()->last_used));
502 } // namespace disk_cache