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
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"
44 using base::TimeTicks
;
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
)
57 return high_water
- kCleanUpMargin
;
60 bool FallingBehind(int current_size
, int max_size
) {
61 return current_size
> max_size
- kCleanUpMargin
* 20;
66 namespace disk_cache
{
68 // The real initialization happens during Init(), init_ is the only member that
69 // has to be initialized here.
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.
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_
;
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.
102 // We want to stop further evictions, so let's pretend that we are busy from
106 ptr_factory_
.InvalidateWeakPtrs();
109 void Eviction::TrimCache(bool empty
) {
110 if (backend_
->disabled_
|| trimming_
)
113 if (!empty
&& !ShouldTrim())
114 return PostDelayedTrim();
117 return TrimCacheV2(empty
);
119 Trace("*** Trim Cache ***");
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())
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_
)
140 if (!empty
&& test_mode_
)
143 if (!empty
&& (deleted_entries
> 20 ||
144 (TimeTicks::Now() - start
).InMilliseconds() > 20)) {
145 base::MessageLoop::current()->PostTask(
147 base::Bind(&Eviction::TrimCache
, ptr_factory_
.GetWeakPtr(), false));
153 CACHE_UMA(AGE_MS
, "TotalClearTimeV1", 0, start
);
155 CACHE_UMA(AGE_MS
, "TotalTrimTimeV1", 0, start
);
157 CACHE_UMA(COUNTS
, "TrimItemsV1", 0, deleted_entries
);
160 Trace("*** Trim Cache end ***");
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
) {
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
) {
189 DCHECK(!info
->reuse_count
);
190 DCHECK(!info
->refetch_count
);
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
;
202 info
->state
= ENTRY_NORMAL
;
203 entry
->entry()->Store();
204 rankings_
->Remove(entry
->rankings(), Rankings::DELETED
, true);
211 rankings_
->Insert(entry
->rankings(), true, GetListForEntryV2(entry
));
214 void Eviction::SetTestMode() {
218 void Eviction::TrimDeletedList(bool empty
) {
219 DCHECK(test_mode_
&& new_eviction_
);
223 // -----------------------------------------------------------------------
225 void Eviction::PostDelayedTrim() {
226 // Prevent posting multiple tasks.
231 base::MessageLoop::current()->PostDelayedTask(
233 base::Bind(&Eviction::DelayedTrim
, ptr_factory_
.GetWeakPtr()),
234 base::TimeDelta::FromMilliseconds(1000));
237 void Eviction::DelayedTrim() {
239 if (trim_delays_
< kMaxDelayedTrims
&& backend_
->IsLoaded())
240 return PostDelayedTrim();
245 bool Eviction::ShouldTrim() {
246 if (!FallingBehind(header_
->num_bytes
, max_size_
) &&
247 trim_delays_
< kMaxDelayedTrims
&& backend_
->IsLoaded()) {
251 UMA_HISTOGRAM_COUNTS("DiskCache.TrimDelays", trim_delays_
);
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
);
271 Trace("NewEntry failed on Trim 0x%x", node
->address().value());
275 ReportTrimTimes(entry
);
276 if (empty
|| !new_eviction_
) {
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
);
289 backend_
->OnEvent(Stats::TRIM_ENTRY
);
296 void Eviction::TrimCacheV2(bool empty
) {
297 Trace("*** Trim Cache ***");
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
++) {
308 next
[i
].set_rankings(rankings_
);
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
);
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
);
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_
) &&
332 // The iterator could be invalidated within EvictEntry().
333 if (!next
[list
]->HasData())
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
)))
345 if (!empty
&& test_mode_
)
348 if (!empty
&& (deleted_entries
> 20 ||
349 (TimeTicks::Now() - start
).InMilliseconds() > 20)) {
350 base::MessageLoop::current()->PostTask(
352 base::Bind(&Eviction::TrimCache
, ptr_factory_
.GetWeakPtr(), false));
357 list
= kListsToSearch
;
362 } else if (ShouldTrimDeleted()) {
363 base::MessageLoop::current()->PostTask(
365 base::Bind(&Eviction::TrimDeleted
, ptr_factory_
.GetWeakPtr(), empty
));
369 CACHE_UMA(AGE_MS
, "TotalClearTimeV2", 0, start
);
371 CACHE_UMA(AGE_MS
, "TotalTrimTimeV2", 0, start
);
373 CACHE_UMA(COUNTS
, "TrimItemsV2", 0, deleted_entries
);
375 Trace("*** Trim Cache end ***");
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_
)
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;
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()))
403 if (deleted_entries
&& !empty
&& ShouldTrimDeleted()) {
404 base::MessageLoop::current()->PostTask(
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 ***");
415 void Eviction::ReportTrimTimes(EntryImpl
* entry
) {
418 if (backend_
->ShouldReportAgain()) {
419 CACHE_UMA(AGE
, "TrimAge", 0, entry
->GetLastUsed());
423 if (header_
->lru
.filled
)
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();
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};
437 old
.day_of_month
= 1;
438 header_
->create_time
= Time::FromLocalExploded(old
).ToInternalValue();
443 bool Eviction::NodeIsOldEnough(CacheRankingsBlock
* node
, int list
) {
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)
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
468 if (!NodeIsOldEnough(next
[list
].get(), 0) &&
469 header_
->lru
.sizes
[0] > data_entries
/ 10)
475 void Eviction::ReportListStats() {
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
));
489 CACHE_UMA(AGE
, "NoUseAge", 0,
490 Time::FromInternalValue(last1
.get()->Data()->last_used
));
492 CACHE_UMA(AGE
, "LowUseAge", 0,
493 Time::FromInternalValue(last2
.get()->Data()->last_used
));
495 CACHE_UMA(AGE
, "HighUseAge", 0,
496 Time::FromInternalValue(last3
.get()->Data()->last_used
));
498 CACHE_UMA(AGE
, "DeletedAge", 0,
499 Time::FromInternalValue(last4
.get()->Data()->last_used
));
502 } // namespace disk_cache