Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(686)

Side by Side Diff: net/disk_cache/v3/eviction_v3.cc

Issue 15203004: Disk cache: Reference CL for the implementation of file format version 3. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Created 7 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « net/disk_cache/v3/eviction_v3.h ('k') | net/disk_cache/v3/index_table.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
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.
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/v3/eviction_v3.h"
30
31 #include "base/bind.h"
32 #include "base/compiler_specific.h"
33 #include "base/logging.h"
34 #include "base/message_loop.h"
35 #include "base/string_util.h"
36 #include "base/time.h"
37 #include "net/base/net_errors.h"
38 #include "net/disk_cache/experiments.h"
39 #include "net/disk_cache/histogram_macros.h"
40 #include "net/disk_cache/trace.h"
41 #include "net/disk_cache/v3/backend_impl_v3.h"
42 #include "net/disk_cache/v3/entry_impl_v3.h"
43 #include "net/disk_cache/v3/index_table.h"
44
45
46 using base::Time;
47 using base::TimeDelta;
48 using base::TimeTicks;
49
50 namespace {
51
52 const int kCleanUpMargin = 1024 * 1024;
53 const int kHighUse = 10; // Reuse count to be on the HIGH_USE list.
54 const int kTargetTime = 24 * 7; // Time to be evicted (hours since last use).
55 const int kMaxDelayedTrims = 60;
56
57 int LowWaterAdjust(int high_water) {
58 if (high_water < kCleanUpMargin)
59 return 0;
60
61 return high_water - kCleanUpMargin;
62 }
63
64 bool FallingBehind(int current_size, int max_size) {
65 return current_size > max_size - kCleanUpMargin * 20;
66 }
67
68 Time TimeFromTimestamp(int timestamp, int64 base_time) {
69 return Time::FromInternalValue(base_time) + TimeDelta::FromSeconds(timestamp);
70 }
71
72 } // namespace
73
74 namespace disk_cache {
75
76 // The real initialization happens during Init(), init_ is the only member that
77 // has to be initialized here.
78 EvictionV3::EvictionV3()
79 : backend_(NULL),
80 index_(NULL),
81 header_(NULL),
82 init_(false),
83 cells_to_evict_(NULL),
84 ptr_factory_(this) {
85 }
86
87 EvictionV3::~EvictionV3() {
88 }
89
90 void EvictionV3::Init(BackendImplV3* backend) {
91 // We grab a bunch of info from the backend to make the code a little cleaner
92 // when we're actually doing work.
93 backend_ = backend;
94 index_ = &backend_->index_;
95 header_ = index_->header();
96 max_size_ = LowWaterAdjust(backend_->max_size_);
97 index_size_ = 1;//?
98 lru_ = backend->lru_eviction_;
99 first_trim_ = true;
100 trimming_ = false;
101 delay_trim_ = false;
102 trim_delays_ = 0;
103 init_ = true;
104 test_mode_ = false;
105 empty_ = false;
106 }
107
108 void EvictionV3::Stop() {
109 // It is possible for the backend initialization to fail, in which case this
110 // object was never initialized... and there is nothing to do.
111 if (!init_)
112 return;
113
114 // We want to stop further evictions, so let's pretend that we are busy from
115 // this point on.
116 DCHECK(!trimming_);//cannot do
117 trimming_ = true;
118 ptr_factory_.InvalidateWeakPtrs();
119 }
120
121 void EvictionV3::TrimCache() {
122 if (trimming_)
123 return;
124
125 if (!ShouldTrim())
126 return PostDelayedTrim();
127
128 Trace("*** Trim Cache ***");
129 trimming_ = true;
130
131 if (!TrimCacheImpl()) {
132 trimming_ = false;
133 Trace("*** Trim Cache end ***");
134 }
135 }
136
137 int EvictionV3::TrimAllCache(const net::CompletionCallback& callback) {
138 if (!callback_.is_null())
139 return net::ERR_FAILED;
140
141 empty_ = true;
142 trimming_ = true;
143 Trace("*** Trim All Cache ***");
144
145 if (!TrimCacheImpl())
146 return net::OK;
147
148 callback_ = callback;
149 return net::ERR_IO_PENDING;
150 }
151
152 void EvictionV3::OnOpenEntry(EntryImplV3* entry) {
153 if (lru_)
154 return;
155
156 EntryCell cell = index_->FindEntryCell(entry->GetHash(), entry->GetAddress());
157 DCHECK_NE(cell.group(), ENTRY_EVICTED);
158 int reuse_count = entry->GetReuseCounter();
159
160 if (reuse_count < 256) {
161 reuse_count++;
162 entry->SetReuseCounter(reuse_count);
163
164 // We may need to move this to a new list.
165 if (1 == reuse_count) {
166 DCHECK_EQ(cell.group(), ENTRY_NO_USE);
167 cell.set_group(ENTRY_LOW_USE);
168 } else if (kHighUse == reuse_count) {
169 DCHECK_EQ(cell.group(), ENTRY_LOW_USE);
170 cell.set_group(ENTRY_HIGH_USE);
171 }
172 if (reuse_count < 16) {
173 cell.set_reuse(reuse_count);
174 index_->Save(&cell);
175 }
176 }
177 }
178
179 void EvictionV3::OnCreateEntry(EntryImplV3* entry) {
180 EntryCell cell = index_->FindEntryCell(entry->GetHash(), entry->GetAddress());
181 DCHECK_EQ(cell.group(), ENTRY_NO_USE);
182 DCHECK(!entry->GetReuseCounter());
183 DCHECK(!entry->GetRefetchCounter());
184 }
185
186 void EvictionV3::OnResurrectEntry(EntryImplV3* entry) {
187 DCHECK(!lru_);
188 EntryCell cell = index_->FindEntryCell(entry->GetHash(), entry->GetAddress());
189 DCHECK_EQ(cell.group(), ENTRY_NO_USE);
190 int reuse_count = entry->GetReuseCounter();
191 int refetch_count = entry->GetRefetchCounter();
192
193 if (refetch_count < 256) {
194 refetch_count++;
195 entry->SetRefetchCounter(refetch_count);
196 }
197
198 if (refetch_count > kHighUse && reuse_count < kHighUse) {
199 reuse_count = kHighUse;
200 } else if (reuse_count < 256) {
201 reuse_count++;
202 }
203 entry->SetReuseCounter(reuse_count);
204
205 if (reuse_count >= kHighUse)
206 cell.set_group(ENTRY_HIGH_USE);
207 else
208 cell.set_group(ENTRY_LOW_USE);
209
210 if (reuse_count < 16)
211 cell.set_reuse(reuse_count);
212
213 index_->Save(&cell);
214 }
215
216 void EvictionV3::OnEvictEntryComplete() {
217 if (!test_mode_ && TrimCacheImpl())
218 return;
219
220 trimming_ = false;
221 Trace("*** Trim Cache end ***");
222
223 if (!callback_.is_null())
224 callback_.Run(net::OK);
225 }
226
227 void EvictionV3::SetTestMode() {
228 test_mode_ = true;
229 }
230
231 void EvictionV3::TrimDeletedList(bool empty) {
232 DCHECK(test_mode_ && !lru_);
233 TrimDeleted(empty);
234 }
235
236 // -----------------------------------------------------------------------
237
238 void EvictionV3::PostDelayedTrim() {
239 // Prevent posting multiple tasks.
240 if (delay_trim_)
241 return;
242 delay_trim_ = true;
243 trim_delays_++;
244 MessageLoop::current()->PostDelayedTask(FROM_HERE,
245 base::Bind(&EvictionV3::DelayedTrim, ptr_factory_.GetWeakPtr()),
246 base::TimeDelta::FromMilliseconds(1000));
247 }
248
249 void EvictionV3::DelayedTrim() {
250 delay_trim_ = false;
251 if (trim_delays_ < kMaxDelayedTrims && backend_->IsLoaded())
252 return PostDelayedTrim();
253
254 TrimCache();
255 }
256
257 bool EvictionV3::ShouldTrim() {
258 if (!FallingBehind(header_->num_bytes, max_size_) &&
259 trim_delays_ < kMaxDelayedTrims && backend_->IsLoaded()) {
260 return false;
261 }
262
263 UMA_HISTOGRAM_COUNTS("DiskCache.TrimDelays", trim_delays_);
264 trim_delays_ = 0;
265 return true;
266 }
267
268 bool EvictionV3::ShouldTrimDeleted() {
269 int index_load = header_->num_entries * 100 / index_size_;
270
271 // If the index is not loaded, the deleted list will tend to double the size
272 // of the other lists 3 lists (40% of the total). Otherwise, all lists will be
273 // about the same size.
274 int max_length = (index_load < 25) ? header_->num_entries * 2 / 5 :
275 header_->num_entries / 4;
276 return false;//(!test_mode_ && header_->lru.sizes[Rankings::DELETED] > max_len gth);
277 }
278
279 int EvictionV3::EvictEntry(uint32 hash, Addr address) {
280 if (empty_) {
281 EntryImplV3* entry = backend_->GetOpenEntry(address);
282 if (entry) {
283 entry->Doom();
284 entry->Close();
285 return net::OK;
286 }
287 }
288
289 if (backend_->EvictEntry(hash, address))
290 return net::ERR_IO_PENDING;
291
292 return net::ERR_FAILED;
293 }
294
295 bool EvictionV3::TrimCacheImpl() {
296 int target_size = empty_ ? 0 : max_size_;
297
298 if (!cells_to_evict_ || cells_to_evict_->empty()) {
299 // See if we are done.
300 if (header_->num_bytes < target_size && !test_mode_)
301 return false;
302
303 EntryGroup group = ENTRY_RESERVED;
304 index_->GetOldest(&no_use_cells_, &low_use_cells_, &high_use_cells_);
305
306 int timestamps[ENTRY_HIGH_USE + 1];
307 timestamps[ENTRY_NO_USE] = GetTimestampForGoup(ENTRY_NO_USE);
308 timestamps[ENTRY_LOW_USE] = GetTimestampForGoup(ENTRY_LOW_USE);
309 timestamps[ENTRY_HIGH_USE] = GetTimestampForGoup(ENTRY_HIGH_USE);
310
311 if (CellIsOldEnough(no_use_cells_, 1))
312 group = ENTRY_NO_USE;
313 else if (CellIsOldEnough(low_use_cells_, 2))
314 group = ENTRY_LOW_USE;
315 else if (CellIsOldEnough(high_use_cells_, 4))
316 group = ENTRY_HIGH_USE;
317 else
318 group = SelectListByLength();
319
320 if (group == ENTRY_NO_USE) {
321 cells_to_evict_ = &no_use_cells_;
322 low_use_cells_.clear();
323 high_use_cells_.clear();
324 } else if (group == ENTRY_LOW_USE) {
325 cells_to_evict_ = &low_use_cells_;
326 no_use_cells_.clear();
327 high_use_cells_.clear();
328 } else if (group == ENTRY_HIGH_USE) {
329 cells_to_evict_ = &high_use_cells_;
330 no_use_cells_.clear();
331 low_use_cells_.clear();
332 } else {
333 return false;
334 }
335
336 if (first_trim_) {
337 first_trim_ = false;
338 if (backend_->ShouldReportAgain()) {
339 int64 base_time = index_->header()->base_time;
340 CACHE_UMA(AGE, "TrimAge", 0,
341 TimeFromTimestamp(timestamps[group], base_time));
342 ReportListStats(timestamps[ENTRY_NO_USE], timestamps[ENTRY_LOW_USE],
343 timestamps[ENTRY_HIGH_USE]);
344 }
345
346 if (!(header_->flags & CACHE_EVICTED)) {
347 // This is the first entry that we have to evict, generate some noise.
348 backend_->FirstEviction();
349 }
350 }
351
352
353 DCHECK(!cells_to_evict_->empty());
354 }
355
356 int rv = net::OK;
357 while (!cells_to_evict_->empty()) {
358 rv = EvictEntry(cells_to_evict_->back().hash,
359 cells_to_evict_->back().address);
360 cells_to_evict_->pop_back();
361 if (rv != net::ERR_FAILED) {
362 if (!empty_)
363 backend_->OnEvent(Stats::TRIM_ENTRY);
364 if (rv == net::ERR_IO_PENDING)
365 break;
366 }
367 }
368
369 if (test_mode_ || rv != net::ERR_IO_PENDING)
370 return false;
371
372 return true;
373 }
374
375 // This is a minimal implementation that just discards the oldest nodes.
376 // TODO(rvargas): Do something better here.
377 void EvictionV3::TrimDeleted(bool empty) {
378 Trace("*** Trim Deleted ***");
379 if (backend_->disabled_)
380 return;
381
382 /*TimeTicks start = TimeTicks::Now();
383 Rankings::ScopedRankingsBlock node(rankings_);
384 Rankings::ScopedRankingsBlock next(
385 rankings_, rankings_->GetPrev(node.get(), Rankings::DELETED));
386 int deleted_entries = 0;
387 while (next.get() &&
388 (empty || (deleted_entries < 20 &&
389 (TimeTicks::Now() - start).InMilliseconds() < 20))) {
390 node.reset(next.release());
391 next.reset(rankings_->GetPrev(node.get(), Rankings::DELETED));
392 if (RemoveDeletedNode(node.get()))
393 deleted_entries++;
394 if (test_mode_)
395 break;
396 }
397
398 if (deleted_entries && !empty && ShouldTrimDeleted()) {
399 MessageLoop::current()->PostTask(FROM_HERE,
400 base::Bind(&EvictionV3::TrimDeleted, ptr_factory_.GetWeakPtr(), false));
401 }
402
403 CACHE_UMA(AGE_MS, "TotalTrimDeletedTime", 0, start);
404 CACHE_UMA(COUNTS, "TrimDeletedItems", 0, deleted_entries);*/
405 Trace("*** Trim Deleted end ***");
406 return;
407 }
408
409 int EvictionV3::GetTimestampForGoup(int group) {
410 CellList* cells = NULL;
411 switch (group) {
412 case ENTRY_NO_USE:
413 cells = &no_use_cells_;
414 break;
415 case ENTRY_LOW_USE:
416 cells = &low_use_cells_;
417 break;
418 case ENTRY_HIGH_USE:
419 cells = &high_use_cells_;
420 break;
421 default:
422 NOTREACHED();
423 }
424 if (cells->empty())
425 return 0;
426 EntryCell cell = index_->FindEntryCell(cells->begin()->hash,
427 cells->begin()->address);
428 return cell.GetTimestamp();
429 }
430
431 bool EvictionV3::CellIsOldEnough(const CellList& cells, int multiplier) {
432 if (cells.empty())
433 return false;
434
435 if (lru_)
436 return true;
437
438 EntryCell cell = index_->FindEntryCell(cells.begin()->hash,
439 cells.begin()->address);
440
441 Time used = Time::FromInternalValue(header_->base_time) +
442 TimeDelta::FromMinutes(cell.GetTimestamp());
443
444 // If possible, we want to keep entries on each list at least kTargetTime
445 // hours. Each successive list on the enumeration has 2x the target time of
446 // the previous list.
447 return (backend_->GetCurrentTime() - used).InHours() >
448 kTargetTime * multiplier;
449 }
450
451 EntryGroup EvictionV3::SelectListByLength() {
452 int data_entries = header_->num_entries - header_->num_evicted_entries;
453
454 // Start by having each list to be roughly the same size.
455 if (header_->num_no_use_entries > data_entries / 3) {
456 DCHECK(!no_use_cells_.empty());
457 return ENTRY_NO_USE;
458 }
459
460 // Make sure that frequently used items are kept for a minimum time; we know
461 // that this entry is not older than its current target, but it must be at
462 // least older than the target for unused entries (kTargetTime), as long as we
463 // don't exhaust that list.
464
465 bool could_delete_no_used = header_->num_no_use_entries > data_entries / 10 ||
466 (!no_use_cells_.empty() && empty_);
467
468 if (header_->num_low_use_entries > data_entries / 3 &&
469 (CellIsOldEnough(low_use_cells_, 1) || !could_delete_no_used)) {
470 DCHECK(!low_use_cells_.empty());
471 return ENTRY_LOW_USE;
472 }
473
474 if (header_->num_high_use_entries > data_entries / 3 &&
475 (CellIsOldEnough(high_use_cells_, 1) || !could_delete_no_used)) {
476 DCHECK(!high_use_cells_.empty());
477 return ENTRY_HIGH_USE;
478 }
479
480 if (could_delete_no_used)
481 return ENTRY_NO_USE;
482
483 if (!low_use_cells_.empty() && empty_)
484 return ENTRY_LOW_USE;
485
486 if (!high_use_cells_.empty() && empty_)
487 return ENTRY_HIGH_USE;
488
489 return ENTRY_RESERVED;
490 }
491
492 void EvictionV3::ReportListStats(int time1, int time2, int time3) {
493 if (lru_)
494 return;
495
496 int64 base_time = index_->header()->base_time;
497
498 if (time1)
499 CACHE_UMA(AGE, "NoUseAge", 0, TimeFromTimestamp(time1, base_time));
500
501 if (time2)
502 CACHE_UMA(AGE, "LowUseAge", 0, TimeFromTimestamp(time2, base_time));
503
504 if (time3)
505 CACHE_UMA(AGE, "HighUseAge", 0, TimeFromTimestamp(time3, base_time));
506 }
507
508 } // namespace disk_cache
OLDNEW
« no previous file with comments | « net/disk_cache/v3/eviction_v3.h ('k') | net/disk_cache/v3/index_table.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698