xref: /aosp_15_r20/external/cronet/net/disk_cache/blockfile/eviction.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2012 The Chromium Authors
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/blockfile/eviction.h"
30 
31 #include <stdint.h>
32 
33 #include <limits>
34 
35 #include "base/check_op.h"
36 #include "base/compiler_specific.h"
37 #include "base/functional/bind.h"
38 #include "base/location.h"
39 #include "base/metrics/histogram_macros.h"
40 #include "base/notreached.h"
41 #include "base/strings/string_util.h"
42 #include "base/task/single_thread_task_runner.h"
43 #include "base/time/time.h"
44 #include "net/base/tracing.h"
45 #include "net/disk_cache/blockfile/backend_impl.h"
46 #include "net/disk_cache/blockfile/disk_format.h"
47 #include "net/disk_cache/blockfile/entry_impl.h"
48 #include "net/disk_cache/blockfile/experiments.h"
49 
50 using base::Time;
51 using base::TimeTicks;
52 
53 namespace {
54 
55 const int kCleanUpMargin = 1024 * 1024;
56 const int kHighUse = 10;  // Reuse count to be on the HIGH_USE list.
57 const int kTargetTime = 24 * 7;  // Time to be evicted (hours since last use).
58 const int kMaxDelayedTrims = 60;
59 
LowWaterAdjust(int high_water)60 int LowWaterAdjust(int high_water) {
61   if (high_water < kCleanUpMargin)
62     return 0;
63 
64   return high_water - kCleanUpMargin;
65 }
66 
FallingBehind(int current_size,int max_size)67 bool FallingBehind(int current_size, int max_size) {
68   return current_size > max_size - kCleanUpMargin * 20;
69 }
70 
71 }  // namespace
72 
73 namespace disk_cache {
74 
75 // The real initialization happens during Init(), init_ is the only member that
76 // has to be initialized here.
77 Eviction::Eviction() = default;
78 
79 Eviction::~Eviction() = default;
80 
Init(BackendImpl * backend)81 void Eviction::Init(BackendImpl* backend) {
82   // We grab a bunch of info from the backend to make the code a little cleaner
83   // when we're actually doing work.
84   backend_ = backend;
85   rankings_ = &backend->rankings_;
86   header_ = &backend_->data_->header;
87   max_size_ = LowWaterAdjust(backend_->max_size_);
88   index_size_ = backend->mask_ + 1;
89   new_eviction_ = backend->new_eviction_;
90   first_trim_ = true;
91   trimming_ = false;
92   delay_trim_ = false;
93   trim_delays_ = 0;
94   init_ = true;
95   test_mode_ = false;
96 }
97 
Stop()98 void Eviction::Stop() {
99   // It is possible for the backend initialization to fail, in which case this
100   // object was never initialized... and there is nothing to do.
101   if (!init_)
102     return;
103 
104   // We want to stop further evictions, so let's pretend that we are busy from
105   // this point on.
106   DCHECK(!trimming_);
107   trimming_ = true;
108   ptr_factory_.InvalidateWeakPtrs();
109 }
110 
TrimCache(bool empty)111 void Eviction::TrimCache(bool empty) {
112   TRACE_EVENT0("disk_cache", "Eviction::TrimCache");
113   if (backend_->disabled_ || trimming_)
114     return;
115 
116   if (!empty && !ShouldTrim())
117     return PostDelayedTrim();
118 
119   if (new_eviction_)
120     return TrimCacheV2(empty);
121 
122   trimming_ = true;
123   TimeTicks start = TimeTicks::Now();
124   Rankings::ScopedRankingsBlock node(rankings_);
125   Rankings::ScopedRankingsBlock next(
126       rankings_, rankings_->GetPrev(node.get(), Rankings::NO_USE));
127   int deleted_entries = 0;
128   int target_size = empty ? 0 : max_size_;
129   while ((header_->num_bytes > target_size || test_mode_) && next.get()) {
130     // The iterator could be invalidated within EvictEntry().
131     if (!next->HasData())
132       break;
133     node.reset(next.release());
134     next.reset(rankings_->GetPrev(node.get(), Rankings::NO_USE));
135     if (node->Data()->dirty != backend_->GetCurrentEntryId() || empty) {
136       // This entry is not being used by anybody.
137       // Do NOT use node as an iterator after this point.
138       rankings_->TrackRankingsBlock(node.get(), false);
139       if (EvictEntry(node.get(), empty, Rankings::NO_USE) && !test_mode_)
140         deleted_entries++;
141 
142       if (!empty && test_mode_)
143         break;
144     }
145     if (!empty && (deleted_entries > 20 ||
146                    (TimeTicks::Now() - start).InMilliseconds() > 20)) {
147       base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
148           FROM_HERE, base::BindOnce(&Eviction::TrimCache,
149                                     ptr_factory_.GetWeakPtr(), false));
150       break;
151     }
152   }
153 
154   trimming_ = false;
155   return;
156 }
157 
UpdateRank(EntryImpl * entry,bool modified)158 void Eviction::UpdateRank(EntryImpl* entry, bool modified) {
159   if (new_eviction_)
160     return UpdateRankV2(entry, modified);
161 
162   rankings_->UpdateRank(entry->rankings(), modified, GetListForEntry(entry));
163 }
164 
OnOpenEntry(EntryImpl * entry)165 void Eviction::OnOpenEntry(EntryImpl* entry) {
166   if (new_eviction_)
167     return OnOpenEntryV2(entry);
168 }
169 
OnCreateEntry(EntryImpl * entry)170 void Eviction::OnCreateEntry(EntryImpl* entry) {
171   if (new_eviction_)
172     return OnCreateEntryV2(entry);
173 
174   rankings_->Insert(entry->rankings(), true, GetListForEntry(entry));
175 }
176 
OnDoomEntry(EntryImpl * entry)177 void Eviction::OnDoomEntry(EntryImpl* entry) {
178   if (new_eviction_)
179     return OnDoomEntryV2(entry);
180 
181   if (entry->LeaveRankingsBehind())
182     return;
183 
184   rankings_->Remove(entry->rankings(), GetListForEntry(entry), true);
185 }
186 
OnDestroyEntry(EntryImpl * entry)187 void Eviction::OnDestroyEntry(EntryImpl* entry) {
188   if (new_eviction_)
189     return OnDestroyEntryV2(entry);
190 }
191 
SetTestMode()192 void Eviction::SetTestMode() {
193   test_mode_ = true;
194 }
195 
TrimDeletedList(bool empty)196 void Eviction::TrimDeletedList(bool empty) {
197   TRACE_EVENT0("disk_cache", "Eviction::TrimDeletedList");
198 
199   DCHECK(test_mode_ && new_eviction_);
200   TrimDeleted(empty);
201 }
202 
PostDelayedTrim()203 void Eviction::PostDelayedTrim() {
204   // Prevent posting multiple tasks.
205   if (delay_trim_)
206     return;
207   delay_trim_ = true;
208   trim_delays_++;
209   base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
210       FROM_HERE,
211       base::BindOnce(&Eviction::DelayedTrim, ptr_factory_.GetWeakPtr()),
212       base::Milliseconds(1000));
213 }
214 
DelayedTrim()215 void Eviction::DelayedTrim() {
216   delay_trim_ = false;
217   if (trim_delays_ < kMaxDelayedTrims && backend_->IsLoaded())
218     return PostDelayedTrim();
219 
220   TrimCache(false);
221 }
222 
ShouldTrim()223 bool Eviction::ShouldTrim() {
224   if (!FallingBehind(header_->num_bytes, max_size_) &&
225       trim_delays_ < kMaxDelayedTrims && backend_->IsLoaded()) {
226     return false;
227   }
228 
229   trim_delays_ = 0;
230   return true;
231 }
232 
ShouldTrimDeleted()233 bool Eviction::ShouldTrimDeleted() {
234   int index_load = header_->num_entries * 100 / index_size_;
235 
236   // If the index is not loaded, the deleted list will tend to double the size
237   // of the other lists 3 lists (40% of the total). Otherwise, all lists will be
238   // about the same size.
239   int max_length = (index_load < 25) ? header_->num_entries * 2 / 5 :
240                                        header_->num_entries / 4;
241   return (!test_mode_ && header_->lru.sizes[Rankings::DELETED] > max_length);
242 }
243 
ReportTrimTimes(EntryImpl * entry)244 void Eviction::ReportTrimTimes(EntryImpl* entry) {
245   if (first_trim_) {
246     first_trim_ = false;
247 
248     if (header_->lru.filled)
249       return;
250 
251     header_->lru.filled = 1;
252 
253     if (header_->create_time) {
254       // This is the first entry that we have to evict, generate some noise.
255       backend_->FirstEviction();
256     } else {
257       // This is an old file, but we may want more reports from this user so
258       // lets save some create_time. Conversion cannot fail here.
259       const base::Time time_2009_3_1 =
260           base::Time::FromInternalValue(12985574400000000);
261       header_->create_time = time_2009_3_1.ToInternalValue();
262     }
263   }
264 }
265 
GetListForEntry(EntryImpl * entry)266 Rankings::List Eviction::GetListForEntry(EntryImpl* entry) {
267   return Rankings::NO_USE;
268 }
269 
EvictEntry(CacheRankingsBlock * node,bool empty,Rankings::List list)270 bool Eviction::EvictEntry(CacheRankingsBlock* node, bool empty,
271                           Rankings::List list) {
272   scoped_refptr<EntryImpl> entry = backend_->GetEnumeratedEntry(node, list);
273   if (!entry)
274     return false;
275 
276   ReportTrimTimes(entry.get());
277   if (empty || !new_eviction_) {
278     entry->DoomImpl();
279   } else {
280     entry->DeleteEntryData(false);
281     EntryStore* info = entry->entry()->Data();
282     DCHECK_EQ(ENTRY_NORMAL, info->state);
283 
284     rankings_->Remove(entry->rankings(), GetListForEntryV2(entry.get()), true);
285     info->state = ENTRY_EVICTED;
286     entry->entry()->Store();
287     rankings_->Insert(entry->rankings(), true, Rankings::DELETED);
288   }
289   if (!empty)
290     backend_->OnEvent(Stats::TRIM_ENTRY);
291 
292   return true;
293 }
294 
295 // -----------------------------------------------------------------------
296 
TrimCacheV2(bool empty)297 void Eviction::TrimCacheV2(bool empty) {
298   TRACE_EVENT0("disk_cache", "Eviction::TrimCacheV2");
299 
300   trimming_ = true;
301   TimeTicks start = TimeTicks::Now();
302 
303   const int kListsToSearch = 3;
304   Rankings::ScopedRankingsBlock next[kListsToSearch];
305   int list = Rankings::LAST_ELEMENT;
306 
307   // Get a node from each list.
308   bool done = false;
309   for (int i = 0; i < kListsToSearch; i++) {
310     next[i].set_rankings(rankings_);
311     if (done)
312       continue;
313     next[i].reset(rankings_->GetPrev(nullptr, static_cast<Rankings::List>(i)));
314     if (!empty && NodeIsOldEnough(next[i].get(), i)) {
315       list = static_cast<Rankings::List>(i);
316       done = true;
317     }
318   }
319 
320   // If we are not meeting the time targets lets move on to list length.
321   if (!empty && Rankings::LAST_ELEMENT == list)
322     list = SelectListByLength(next);
323 
324   if (empty)
325     list = 0;
326 
327   Rankings::ScopedRankingsBlock node(rankings_);
328   int deleted_entries = 0;
329   int target_size = empty ? 0 : max_size_;
330 
331   for (; list < kListsToSearch; list++) {
332     while ((header_->num_bytes > target_size || test_mode_) &&
333            next[list].get()) {
334       // The iterator could be invalidated within EvictEntry().
335       if (!next[list]->HasData())
336         break;
337       node.reset(next[list].release());
338       next[list].reset(rankings_->GetPrev(node.get(),
339                                           static_cast<Rankings::List>(list)));
340       if (node->Data()->dirty != backend_->GetCurrentEntryId() || empty) {
341         // This entry is not being used by anybody.
342         // Do NOT use node as an iterator after this point.
343         rankings_->TrackRankingsBlock(node.get(), false);
344         if (EvictEntry(node.get(), empty, static_cast<Rankings::List>(list)))
345           deleted_entries++;
346 
347         if (!empty && test_mode_)
348           break;
349       }
350       if (!empty && (deleted_entries > 20 ||
351                      (TimeTicks::Now() - start).InMilliseconds() > 20)) {
352         base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
353             FROM_HERE, base::BindOnce(&Eviction::TrimCache,
354                                       ptr_factory_.GetWeakPtr(), false));
355         break;
356       }
357     }
358     if (!empty)
359       list = kListsToSearch;
360   }
361 
362   if (empty) {
363     TrimDeleted(true);
364   } else if (ShouldTrimDeleted()) {
365     base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
366         FROM_HERE, base::BindOnce(&Eviction::TrimDeleted,
367                                   ptr_factory_.GetWeakPtr(), empty));
368   }
369 
370   trimming_ = false;
371   return;
372 }
373 
UpdateRankV2(EntryImpl * entry,bool modified)374 void Eviction::UpdateRankV2(EntryImpl* entry, bool modified) {
375   rankings_->UpdateRank(entry->rankings(), modified, GetListForEntryV2(entry));
376 }
377 
OnOpenEntryV2(EntryImpl * entry)378 void Eviction::OnOpenEntryV2(EntryImpl* entry) {
379   EntryStore* info = entry->entry()->Data();
380   DCHECK_EQ(ENTRY_NORMAL, info->state);
381 
382   if (info->reuse_count < std::numeric_limits<int32_t>::max()) {
383     info->reuse_count++;
384     entry->entry()->set_modified();
385 
386     // We may need to move this to a new list.
387     if (1 == info->reuse_count) {
388       rankings_->Remove(entry->rankings(), Rankings::NO_USE, true);
389       rankings_->Insert(entry->rankings(), false, Rankings::LOW_USE);
390       entry->entry()->Store();
391     } else if (kHighUse == info->reuse_count) {
392       rankings_->Remove(entry->rankings(), Rankings::LOW_USE, true);
393       rankings_->Insert(entry->rankings(), false, Rankings::HIGH_USE);
394       entry->entry()->Store();
395     }
396   }
397 }
398 
OnCreateEntryV2(EntryImpl * entry)399 void Eviction::OnCreateEntryV2(EntryImpl* entry) {
400   EntryStore* info = entry->entry()->Data();
401   switch (info->state) {
402     case ENTRY_NORMAL: {
403       DCHECK(!info->reuse_count);
404       DCHECK(!info->refetch_count);
405       break;
406     };
407     case ENTRY_EVICTED: {
408       if (info->refetch_count < std::numeric_limits<int32_t>::max())
409         info->refetch_count++;
410 
411       if (info->refetch_count > kHighUse && info->reuse_count < kHighUse) {
412         info->reuse_count = kHighUse;
413       } else {
414         info->reuse_count++;
415       }
416       info->state = ENTRY_NORMAL;
417       entry->entry()->Store();
418       rankings_->Remove(entry->rankings(), Rankings::DELETED, true);
419       break;
420     };
421     default:
422       NOTREACHED();
423   }
424 
425   rankings_->Insert(entry->rankings(), true, GetListForEntryV2(entry));
426 }
427 
OnDoomEntryV2(EntryImpl * entry)428 void Eviction::OnDoomEntryV2(EntryImpl* entry) {
429   EntryStore* info = entry->entry()->Data();
430   if (ENTRY_NORMAL != info->state)
431     return;
432 
433   if (entry->LeaveRankingsBehind()) {
434     info->state = ENTRY_DOOMED;
435     entry->entry()->Store();
436     return;
437   }
438 
439   rankings_->Remove(entry->rankings(), GetListForEntryV2(entry), true);
440 
441   info->state = ENTRY_DOOMED;
442   entry->entry()->Store();
443   rankings_->Insert(entry->rankings(), true, Rankings::DELETED);
444 }
445 
OnDestroyEntryV2(EntryImpl * entry)446 void Eviction::OnDestroyEntryV2(EntryImpl* entry) {
447   if (entry->LeaveRankingsBehind())
448     return;
449 
450   rankings_->Remove(entry->rankings(), Rankings::DELETED, true);
451 }
452 
GetListForEntryV2(EntryImpl * entry)453 Rankings::List Eviction::GetListForEntryV2(EntryImpl* entry) {
454   EntryStore* info = entry->entry()->Data();
455   DCHECK_EQ(ENTRY_NORMAL, info->state);
456 
457   if (!info->reuse_count)
458     return Rankings::NO_USE;
459 
460   if (info->reuse_count < kHighUse)
461     return Rankings::LOW_USE;
462 
463   return Rankings::HIGH_USE;
464 }
465 
466 // This is a minimal implementation that just discards the oldest nodes.
467 // TODO(rvargas): Do something better here.
TrimDeleted(bool empty)468 void Eviction::TrimDeleted(bool empty) {
469   TRACE_EVENT0("disk_cache", "Eviction::TrimDeleted");
470 
471   if (backend_->disabled_)
472     return;
473 
474   TimeTicks start = TimeTicks::Now();
475   Rankings::ScopedRankingsBlock node(rankings_);
476   Rankings::ScopedRankingsBlock next(
477     rankings_, rankings_->GetPrev(node.get(), Rankings::DELETED));
478   int deleted_entries = 0;
479   while (next.get() &&
480          (empty || (deleted_entries < 20 &&
481                     (TimeTicks::Now() - start).InMilliseconds() < 20))) {
482     node.reset(next.release());
483     next.reset(rankings_->GetPrev(node.get(), Rankings::DELETED));
484     if (RemoveDeletedNode(node.get()))
485       deleted_entries++;
486     if (test_mode_)
487       break;
488   }
489 
490   if (deleted_entries && !empty && ShouldTrimDeleted()) {
491     base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
492         FROM_HERE, base::BindOnce(&Eviction::TrimDeleted,
493                                   ptr_factory_.GetWeakPtr(), false));
494   }
495 
496   return;
497 }
498 
RemoveDeletedNode(CacheRankingsBlock * node)499 bool Eviction::RemoveDeletedNode(CacheRankingsBlock* node) {
500   scoped_refptr<EntryImpl> entry =
501       backend_->GetEnumeratedEntry(node, Rankings::DELETED);
502   if (!entry)
503     return false;
504 
505   bool doomed = (entry->entry()->Data()->state == ENTRY_DOOMED);
506   entry->entry()->Data()->state = ENTRY_DOOMED;
507   entry->DoomImpl();
508   return !doomed;
509 }
510 
NodeIsOldEnough(CacheRankingsBlock * node,int list)511 bool Eviction::NodeIsOldEnough(CacheRankingsBlock* node, int list) {
512   if (!node)
513     return false;
514 
515   // If possible, we want to keep entries on each list at least kTargetTime
516   // hours. Each successive list on the enumeration has 2x the target time of
517   // the previous list.
518   Time used = Time::FromInternalValue(node->Data()->last_used);
519   int multiplier = 1 << list;
520   return (Time::Now() - used).InHours() > kTargetTime * multiplier;
521 }
522 
SelectListByLength(Rankings::ScopedRankingsBlock * next)523 int Eviction::SelectListByLength(Rankings::ScopedRankingsBlock* next) {
524   int data_entries = header_->num_entries -
525                      header_->lru.sizes[Rankings::DELETED];
526   // Start by having each list to be roughly the same size.
527   if (header_->lru.sizes[0] > data_entries / 3)
528     return 0;
529 
530   int list = (header_->lru.sizes[1] > data_entries / 3) ? 1 : 2;
531 
532   // Make sure that frequently used items are kept for a minimum time; we know
533   // that this entry is not older than its current target, but it must be at
534   // least older than the target for list 0 (kTargetTime), as long as we don't
535   // exhaust list 0.
536   if (!NodeIsOldEnough(next[list].get(), 0) &&
537       header_->lru.sizes[0] > data_entries / 10)
538     list = 0;
539 
540   return list;
541 }
542 
543 }  // namespace disk_cache
544