OLD | NEW |
| (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 #include "net/disk_cache/backend_impl.h" | |
6 | |
7 #include "base/bind.h" | |
8 #include "base/bind_helpers.h" | |
9 #include "base/file_util.h" | |
10 #include "base/files/file_path.h" | |
11 #include "base/hash.h" | |
12 #include "base/message_loop/message_loop.h" | |
13 #include "base/metrics/field_trial.h" | |
14 #include "base/metrics/histogram.h" | |
15 #include "base/metrics/stats_counters.h" | |
16 #include "base/rand_util.h" | |
17 #include "base/strings/string_util.h" | |
18 #include "base/strings/stringprintf.h" | |
19 #include "base/sys_info.h" | |
20 #include "base/threading/thread_restrictions.h" | |
21 #include "base/time/time.h" | |
22 #include "base/timer/timer.h" | |
23 #include "net/base/net_errors.h" | |
24 #include "net/disk_cache/cache_util.h" | |
25 #include "net/disk_cache/disk_format.h" | |
26 #include "net/disk_cache/entry_impl.h" | |
27 #include "net/disk_cache/errors.h" | |
28 #include "net/disk_cache/experiments.h" | |
29 #include "net/disk_cache/file.h" | |
30 | |
31 #define CACHE_HISTOGRAM_MACROS_BACKEND_IMPL_OBJ this | |
32 #include "net/disk_cache/histogram_macros.h" | |
33 | |
34 using base::Time; | |
35 using base::TimeDelta; | |
36 using base::TimeTicks; | |
37 | |
38 namespace { | |
39 | |
40 const char* kIndexName = "index"; | |
41 | |
42 // Seems like ~240 MB correspond to less than 50k entries for 99% of the people. | |
43 // Note that the actual target is to keep the index table load factor under 55% | |
44 // for most users. | |
45 const int k64kEntriesStore = 240 * 1000 * 1000; | |
46 const int kBaseTableLen = 64 * 1024; | |
47 | |
48 // Avoid trimming the cache for the first 5 minutes (10 timer ticks). | |
49 const int kTrimDelay = 10; | |
50 | |
51 int DesiredIndexTableLen(int32 storage_size) { | |
52 if (storage_size <= k64kEntriesStore) | |
53 return kBaseTableLen; | |
54 if (storage_size <= k64kEntriesStore * 2) | |
55 return kBaseTableLen * 2; | |
56 if (storage_size <= k64kEntriesStore * 4) | |
57 return kBaseTableLen * 4; | |
58 if (storage_size <= k64kEntriesStore * 8) | |
59 return kBaseTableLen * 8; | |
60 | |
61 // The biggest storage_size for int32 requires a 4 MB table. | |
62 return kBaseTableLen * 16; | |
63 } | |
64 | |
65 int MaxStorageSizeForTable(int table_len) { | |
66 return table_len * (k64kEntriesStore / kBaseTableLen); | |
67 } | |
68 | |
69 size_t GetIndexSize(int table_len) { | |
70 size_t table_size = sizeof(disk_cache::CacheAddr) * table_len; | |
71 return sizeof(disk_cache::IndexHeader) + table_size; | |
72 } | |
73 | |
74 // ------------------------------------------------------------------------ | |
75 | |
76 // Sets group for the current experiment. Returns false if the files should be | |
77 // discarded. | |
78 bool InitExperiment(disk_cache::IndexHeader* header, bool cache_created) { | |
79 if (header->experiment == disk_cache::EXPERIMENT_OLD_FILE1 || | |
80 header->experiment == disk_cache::EXPERIMENT_OLD_FILE2) { | |
81 // Discard current cache. | |
82 return false; | |
83 } | |
84 | |
85 if (base::FieldTrialList::FindFullName("SimpleCacheTrial") == | |
86 "ExperimentControl") { | |
87 if (cache_created) { | |
88 header->experiment = disk_cache::EXPERIMENT_SIMPLE_CONTROL; | |
89 return true; | |
90 } | |
91 return header->experiment == disk_cache::EXPERIMENT_SIMPLE_CONTROL; | |
92 } | |
93 | |
94 header->experiment = disk_cache::NO_EXPERIMENT; | |
95 return true; | |
96 } | |
97 | |
98 // A callback to perform final cleanup on the background thread. | |
99 void FinalCleanupCallback(disk_cache::BackendImpl* backend) { | |
100 backend->CleanupCache(); | |
101 } | |
102 | |
103 } // namespace | |
104 | |
105 // ------------------------------------------------------------------------ | |
106 | |
107 namespace disk_cache { | |
108 | |
109 BackendImpl::BackendImpl(const base::FilePath& path, | |
110 base::MessageLoopProxy* cache_thread, | |
111 net::NetLog* net_log) | |
112 : background_queue_(this, cache_thread), | |
113 path_(path), | |
114 block_files_(path), | |
115 mask_(0), | |
116 max_size_(0), | |
117 up_ticks_(0), | |
118 cache_type_(net::DISK_CACHE), | |
119 uma_report_(0), | |
120 user_flags_(0), | |
121 init_(false), | |
122 restarted_(false), | |
123 unit_test_(false), | |
124 read_only_(false), | |
125 disabled_(false), | |
126 new_eviction_(false), | |
127 first_timer_(true), | |
128 user_load_(false), | |
129 net_log_(net_log), | |
130 done_(true, false), | |
131 ptr_factory_(this) { | |
132 } | |
133 | |
134 BackendImpl::BackendImpl(const base::FilePath& path, | |
135 uint32 mask, | |
136 base::MessageLoopProxy* cache_thread, | |
137 net::NetLog* net_log) | |
138 : background_queue_(this, cache_thread), | |
139 path_(path), | |
140 block_files_(path), | |
141 mask_(mask), | |
142 max_size_(0), | |
143 up_ticks_(0), | |
144 cache_type_(net::DISK_CACHE), | |
145 uma_report_(0), | |
146 user_flags_(kMask), | |
147 init_(false), | |
148 restarted_(false), | |
149 unit_test_(false), | |
150 read_only_(false), | |
151 disabled_(false), | |
152 new_eviction_(false), | |
153 first_timer_(true), | |
154 user_load_(false), | |
155 net_log_(net_log), | |
156 done_(true, false), | |
157 ptr_factory_(this) { | |
158 } | |
159 | |
160 BackendImpl::~BackendImpl() { | |
161 if (user_flags_ & kNoRandom) { | |
162 // This is a unit test, so we want to be strict about not leaking entries | |
163 // and completing all the work. | |
164 background_queue_.WaitForPendingIO(); | |
165 } else { | |
166 // This is most likely not a test, so we want to do as little work as | |
167 // possible at this time, at the price of leaving dirty entries behind. | |
168 background_queue_.DropPendingIO(); | |
169 } | |
170 | |
171 if (background_queue_.BackgroundIsCurrentThread()) { | |
172 // Unit tests may use the same thread for everything. | |
173 CleanupCache(); | |
174 } else { | |
175 background_queue_.background_thread()->PostTask( | |
176 FROM_HERE, base::Bind(&FinalCleanupCallback, base::Unretained(this))); | |
177 // http://crbug.com/74623 | |
178 base::ThreadRestrictions::ScopedAllowWait allow_wait; | |
179 done_.Wait(); | |
180 } | |
181 } | |
182 | |
183 int BackendImpl::Init(const CompletionCallback& callback) { | |
184 background_queue_.Init(callback); | |
185 return net::ERR_IO_PENDING; | |
186 } | |
187 | |
188 int BackendImpl::SyncInit() { | |
189 #if defined(NET_BUILD_STRESS_CACHE) | |
190 // Start evictions right away. | |
191 up_ticks_ = kTrimDelay * 2; | |
192 #endif | |
193 DCHECK(!init_); | |
194 if (init_) | |
195 return net::ERR_FAILED; | |
196 | |
197 bool create_files = false; | |
198 if (!InitBackingStore(&create_files)) { | |
199 ReportError(ERR_STORAGE_ERROR); | |
200 return net::ERR_FAILED; | |
201 } | |
202 | |
203 num_refs_ = num_pending_io_ = max_refs_ = 0; | |
204 entry_count_ = byte_count_ = 0; | |
205 | |
206 bool should_create_timer = false; | |
207 if (!restarted_) { | |
208 buffer_bytes_ = 0; | |
209 trace_object_ = TraceObject::GetTraceObject(); | |
210 should_create_timer = true; | |
211 } | |
212 | |
213 init_ = true; | |
214 Trace("Init"); | |
215 | |
216 if (data_->header.experiment != NO_EXPERIMENT && | |
217 cache_type_ != net::DISK_CACHE) { | |
218 // No experiment for other caches. | |
219 return net::ERR_FAILED; | |
220 } | |
221 | |
222 if (!(user_flags_ & kNoRandom)) { | |
223 // The unit test controls directly what to test. | |
224 new_eviction_ = (cache_type_ == net::DISK_CACHE); | |
225 } | |
226 | |
227 if (!CheckIndex()) { | |
228 ReportError(ERR_INIT_FAILED); | |
229 return net::ERR_FAILED; | |
230 } | |
231 | |
232 if (!restarted_ && (create_files || !data_->header.num_entries)) | |
233 ReportError(ERR_CACHE_CREATED); | |
234 | |
235 if (!(user_flags_ & kNoRandom) && cache_type_ == net::DISK_CACHE && | |
236 !InitExperiment(&data_->header, create_files)) { | |
237 return net::ERR_FAILED; | |
238 } | |
239 | |
240 // We don't care if the value overflows. The only thing we care about is that | |
241 // the id cannot be zero, because that value is used as "not dirty". | |
242 // Increasing the value once per second gives us many years before we start | |
243 // having collisions. | |
244 data_->header.this_id++; | |
245 if (!data_->header.this_id) | |
246 data_->header.this_id++; | |
247 | |
248 bool previous_crash = (data_->header.crash != 0); | |
249 data_->header.crash = 1; | |
250 | |
251 if (!block_files_.Init(create_files)) | |
252 return net::ERR_FAILED; | |
253 | |
254 // We want to minimize the changes to cache for an AppCache. | |
255 if (cache_type() == net::APP_CACHE) { | |
256 DCHECK(!new_eviction_); | |
257 read_only_ = true; | |
258 } else if (cache_type() == net::SHADER_CACHE) { | |
259 DCHECK(!new_eviction_); | |
260 } | |
261 | |
262 eviction_.Init(this); | |
263 | |
264 // stats_ and rankings_ may end up calling back to us so we better be enabled. | |
265 disabled_ = false; | |
266 if (!InitStats()) | |
267 return net::ERR_FAILED; | |
268 | |
269 disabled_ = !rankings_.Init(this, new_eviction_); | |
270 | |
271 #if defined(STRESS_CACHE_EXTENDED_VALIDATION) | |
272 trace_object_->EnableTracing(false); | |
273 int sc = SelfCheck(); | |
274 if (sc < 0 && sc != ERR_NUM_ENTRIES_MISMATCH) | |
275 NOTREACHED(); | |
276 trace_object_->EnableTracing(true); | |
277 #endif | |
278 | |
279 if (previous_crash) { | |
280 ReportError(ERR_PREVIOUS_CRASH); | |
281 } else if (!restarted_) { | |
282 ReportError(ERR_NO_ERROR); | |
283 } | |
284 | |
285 FlushIndex(); | |
286 | |
287 if (!disabled_ && should_create_timer) { | |
288 // Create a recurrent timer of 30 secs. | |
289 int timer_delay = unit_test_ ? 1000 : 30000; | |
290 timer_.reset(new base::RepeatingTimer<BackendImpl>()); | |
291 timer_->Start(FROM_HERE, TimeDelta::FromMilliseconds(timer_delay), this, | |
292 &BackendImpl::OnStatsTimer); | |
293 } | |
294 | |
295 return disabled_ ? net::ERR_FAILED : net::OK; | |
296 } | |
297 | |
298 void BackendImpl::CleanupCache() { | |
299 Trace("Backend Cleanup"); | |
300 eviction_.Stop(); | |
301 timer_.reset(); | |
302 | |
303 if (init_) { | |
304 StoreStats(); | |
305 if (data_) | |
306 data_->header.crash = 0; | |
307 | |
308 if (user_flags_ & kNoRandom) { | |
309 // This is a net_unittest, verify that we are not 'leaking' entries. | |
310 File::WaitForPendingIO(&num_pending_io_); | |
311 DCHECK(!num_refs_); | |
312 } else { | |
313 File::DropPendingIO(); | |
314 } | |
315 } | |
316 block_files_.CloseFiles(); | |
317 FlushIndex(); | |
318 index_ = NULL; | |
319 ptr_factory_.InvalidateWeakPtrs(); | |
320 done_.Signal(); | |
321 } | |
322 | |
323 // ------------------------------------------------------------------------ | |
324 | |
325 int BackendImpl::OpenPrevEntry(void** iter, Entry** prev_entry, | |
326 const CompletionCallback& callback) { | |
327 DCHECK(!callback.is_null()); | |
328 background_queue_.OpenPrevEntry(iter, prev_entry, callback); | |
329 return net::ERR_IO_PENDING; | |
330 } | |
331 | |
332 int BackendImpl::SyncOpenEntry(const std::string& key, Entry** entry) { | |
333 DCHECK(entry); | |
334 *entry = OpenEntryImpl(key); | |
335 return (*entry) ? net::OK : net::ERR_FAILED; | |
336 } | |
337 | |
338 int BackendImpl::SyncCreateEntry(const std::string& key, Entry** entry) { | |
339 DCHECK(entry); | |
340 *entry = CreateEntryImpl(key); | |
341 return (*entry) ? net::OK : net::ERR_FAILED; | |
342 } | |
343 | |
344 int BackendImpl::SyncDoomEntry(const std::string& key) { | |
345 if (disabled_) | |
346 return net::ERR_FAILED; | |
347 | |
348 EntryImpl* entry = OpenEntryImpl(key); | |
349 if (!entry) | |
350 return net::ERR_FAILED; | |
351 | |
352 entry->DoomImpl(); | |
353 entry->Release(); | |
354 return net::OK; | |
355 } | |
356 | |
357 int BackendImpl::SyncDoomAllEntries() { | |
358 // This is not really an error, but it is an interesting condition. | |
359 ReportError(ERR_CACHE_DOOMED); | |
360 stats_.OnEvent(Stats::DOOM_CACHE); | |
361 if (!num_refs_) { | |
362 RestartCache(false); | |
363 return disabled_ ? net::ERR_FAILED : net::OK; | |
364 } else { | |
365 if (disabled_) | |
366 return net::ERR_FAILED; | |
367 | |
368 eviction_.TrimCache(true); | |
369 return net::OK; | |
370 } | |
371 } | |
372 | |
373 int BackendImpl::SyncDoomEntriesBetween(const base::Time initial_time, | |
374 const base::Time end_time) { | |
375 DCHECK_NE(net::APP_CACHE, cache_type_); | |
376 if (end_time.is_null()) | |
377 return SyncDoomEntriesSince(initial_time); | |
378 | |
379 DCHECK(end_time >= initial_time); | |
380 | |
381 if (disabled_) | |
382 return net::ERR_FAILED; | |
383 | |
384 EntryImpl* node; | |
385 void* iter = NULL; | |
386 EntryImpl* next = OpenNextEntryImpl(&iter); | |
387 if (!next) | |
388 return net::OK; | |
389 | |
390 while (next) { | |
391 node = next; | |
392 next = OpenNextEntryImpl(&iter); | |
393 | |
394 if (node->GetLastUsed() >= initial_time && | |
395 node->GetLastUsed() < end_time) { | |
396 node->DoomImpl(); | |
397 } else if (node->GetLastUsed() < initial_time) { | |
398 if (next) | |
399 next->Release(); | |
400 next = NULL; | |
401 SyncEndEnumeration(iter); | |
402 } | |
403 | |
404 node->Release(); | |
405 } | |
406 | |
407 return net::OK; | |
408 } | |
409 | |
410 // We use OpenNextEntryImpl to retrieve elements from the cache, until we get | |
411 // entries that are too old. | |
412 int BackendImpl::SyncDoomEntriesSince(const base::Time initial_time) { | |
413 DCHECK_NE(net::APP_CACHE, cache_type_); | |
414 if (disabled_) | |
415 return net::ERR_FAILED; | |
416 | |
417 stats_.OnEvent(Stats::DOOM_RECENT); | |
418 for (;;) { | |
419 void* iter = NULL; | |
420 EntryImpl* entry = OpenNextEntryImpl(&iter); | |
421 if (!entry) | |
422 return net::OK; | |
423 | |
424 if (initial_time > entry->GetLastUsed()) { | |
425 entry->Release(); | |
426 SyncEndEnumeration(iter); | |
427 return net::OK; | |
428 } | |
429 | |
430 entry->DoomImpl(); | |
431 entry->Release(); | |
432 SyncEndEnumeration(iter); // Dooming the entry invalidates the iterator. | |
433 } | |
434 } | |
435 | |
436 int BackendImpl::SyncOpenNextEntry(void** iter, Entry** next_entry) { | |
437 *next_entry = OpenNextEntryImpl(iter); | |
438 return (*next_entry) ? net::OK : net::ERR_FAILED; | |
439 } | |
440 | |
441 int BackendImpl::SyncOpenPrevEntry(void** iter, Entry** prev_entry) { | |
442 *prev_entry = OpenPrevEntryImpl(iter); | |
443 return (*prev_entry) ? net::OK : net::ERR_FAILED; | |
444 } | |
445 | |
446 void BackendImpl::SyncEndEnumeration(void* iter) { | |
447 scoped_ptr<Rankings::Iterator> iterator( | |
448 reinterpret_cast<Rankings::Iterator*>(iter)); | |
449 } | |
450 | |
451 void BackendImpl::SyncOnExternalCacheHit(const std::string& key) { | |
452 if (disabled_) | |
453 return; | |
454 | |
455 uint32 hash = base::Hash(key); | |
456 bool error; | |
457 EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error); | |
458 if (cache_entry) { | |
459 if (ENTRY_NORMAL == cache_entry->entry()->Data()->state) { | |
460 UpdateRank(cache_entry, cache_type() == net::SHADER_CACHE); | |
461 } | |
462 cache_entry->Release(); | |
463 } | |
464 } | |
465 | |
466 EntryImpl* BackendImpl::OpenEntryImpl(const std::string& key) { | |
467 if (disabled_) | |
468 return NULL; | |
469 | |
470 TimeTicks start = TimeTicks::Now(); | |
471 uint32 hash = base::Hash(key); | |
472 Trace("Open hash 0x%x", hash); | |
473 | |
474 bool error; | |
475 EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error); | |
476 if (cache_entry && ENTRY_NORMAL != cache_entry->entry()->Data()->state) { | |
477 // The entry was already evicted. | |
478 cache_entry->Release(); | |
479 cache_entry = NULL; | |
480 } | |
481 | |
482 int current_size = data_->header.num_bytes / (1024 * 1024); | |
483 int64 total_hours = stats_.GetCounter(Stats::TIMER) / 120; | |
484 int64 no_use_hours = stats_.GetCounter(Stats::LAST_REPORT_TIMER) / 120; | |
485 int64 use_hours = total_hours - no_use_hours; | |
486 | |
487 if (!cache_entry) { | |
488 CACHE_UMA(AGE_MS, "OpenTime.Miss", 0, start); | |
489 CACHE_UMA(COUNTS_10000, "AllOpenBySize.Miss", 0, current_size); | |
490 CACHE_UMA(HOURS, "AllOpenByTotalHours.Miss", 0, total_hours); | |
491 CACHE_UMA(HOURS, "AllOpenByUseHours.Miss", 0, use_hours); | |
492 stats_.OnEvent(Stats::OPEN_MISS); | |
493 return NULL; | |
494 } | |
495 | |
496 eviction_.OnOpenEntry(cache_entry); | |
497 entry_count_++; | |
498 | |
499 Trace("Open hash 0x%x end: 0x%x", hash, | |
500 cache_entry->entry()->address().value()); | |
501 CACHE_UMA(AGE_MS, "OpenTime", 0, start); | |
502 CACHE_UMA(COUNTS_10000, "AllOpenBySize.Hit", 0, current_size); | |
503 CACHE_UMA(HOURS, "AllOpenByTotalHours.Hit", 0, total_hours); | |
504 CACHE_UMA(HOURS, "AllOpenByUseHours.Hit", 0, use_hours); | |
505 stats_.OnEvent(Stats::OPEN_HIT); | |
506 SIMPLE_STATS_COUNTER("disk_cache.hit"); | |
507 return cache_entry; | |
508 } | |
509 | |
510 EntryImpl* BackendImpl::CreateEntryImpl(const std::string& key) { | |
511 if (disabled_ || key.empty()) | |
512 return NULL; | |
513 | |
514 TimeTicks start = TimeTicks::Now(); | |
515 uint32 hash = base::Hash(key); | |
516 Trace("Create hash 0x%x", hash); | |
517 | |
518 scoped_refptr<EntryImpl> parent; | |
519 Addr entry_address(data_->table[hash & mask_]); | |
520 if (entry_address.is_initialized()) { | |
521 // We have an entry already. It could be the one we are looking for, or just | |
522 // a hash conflict. | |
523 bool error; | |
524 EntryImpl* old_entry = MatchEntry(key, hash, false, Addr(), &error); | |
525 if (old_entry) | |
526 return ResurrectEntry(old_entry); | |
527 | |
528 EntryImpl* parent_entry = MatchEntry(key, hash, true, Addr(), &error); | |
529 DCHECK(!error); | |
530 if (parent_entry) { | |
531 parent.swap(&parent_entry); | |
532 } else if (data_->table[hash & mask_]) { | |
533 // We should have corrected the problem. | |
534 NOTREACHED(); | |
535 return NULL; | |
536 } | |
537 } | |
538 | |
539 // The general flow is to allocate disk space and initialize the entry data, | |
540 // followed by saving that to disk, then linking the entry though the index | |
541 // and finally through the lists. If there is a crash in this process, we may | |
542 // end up with: | |
543 // a. Used, unreferenced empty blocks on disk (basically just garbage). | |
544 // b. Used, unreferenced but meaningful data on disk (more garbage). | |
545 // c. A fully formed entry, reachable only through the index. | |
546 // d. A fully formed entry, also reachable through the lists, but still dirty. | |
547 // | |
548 // Anything after (b) can be automatically cleaned up. We may consider saving | |
549 // the current operation (as we do while manipulating the lists) so that we | |
550 // can detect and cleanup (a) and (b). | |
551 | |
552 int num_blocks = EntryImpl::NumBlocksForEntry(key.size()); | |
553 if (!block_files_.CreateBlock(BLOCK_256, num_blocks, &entry_address)) { | |
554 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
555 stats_.OnEvent(Stats::CREATE_ERROR); | |
556 return NULL; | |
557 } | |
558 | |
559 Addr node_address(0); | |
560 if (!block_files_.CreateBlock(RANKINGS, 1, &node_address)) { | |
561 block_files_.DeleteBlock(entry_address, false); | |
562 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
563 stats_.OnEvent(Stats::CREATE_ERROR); | |
564 return NULL; | |
565 } | |
566 | |
567 scoped_refptr<EntryImpl> cache_entry( | |
568 new EntryImpl(this, entry_address, false)); | |
569 IncreaseNumRefs(); | |
570 | |
571 if (!cache_entry->CreateEntry(node_address, key, hash)) { | |
572 block_files_.DeleteBlock(entry_address, false); | |
573 block_files_.DeleteBlock(node_address, false); | |
574 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
575 stats_.OnEvent(Stats::CREATE_ERROR); | |
576 return NULL; | |
577 } | |
578 | |
579 cache_entry->BeginLogging(net_log_, true); | |
580 | |
581 // We are not failing the operation; let's add this to the map. | |
582 open_entries_[entry_address.value()] = cache_entry.get(); | |
583 | |
584 // Save the entry. | |
585 cache_entry->entry()->Store(); | |
586 cache_entry->rankings()->Store(); | |
587 IncreaseNumEntries(); | |
588 entry_count_++; | |
589 | |
590 // Link this entry through the index. | |
591 if (parent.get()) { | |
592 parent->SetNextAddress(entry_address); | |
593 } else { | |
594 data_->table[hash & mask_] = entry_address.value(); | |
595 } | |
596 | |
597 // Link this entry through the lists. | |
598 eviction_.OnCreateEntry(cache_entry.get()); | |
599 | |
600 CACHE_UMA(AGE_MS, "CreateTime", 0, start); | |
601 stats_.OnEvent(Stats::CREATE_HIT); | |
602 SIMPLE_STATS_COUNTER("disk_cache.miss"); | |
603 Trace("create entry hit "); | |
604 FlushIndex(); | |
605 cache_entry->AddRef(); | |
606 return cache_entry.get(); | |
607 } | |
608 | |
609 EntryImpl* BackendImpl::OpenNextEntryImpl(void** iter) { | |
610 return OpenFollowingEntry(true, iter); | |
611 } | |
612 | |
613 EntryImpl* BackendImpl::OpenPrevEntryImpl(void** iter) { | |
614 return OpenFollowingEntry(false, iter); | |
615 } | |
616 | |
617 bool BackendImpl::SetMaxSize(int max_bytes) { | |
618 COMPILE_ASSERT(sizeof(max_bytes) == sizeof(max_size_), unsupported_int_model); | |
619 if (max_bytes < 0) | |
620 return false; | |
621 | |
622 // Zero size means use the default. | |
623 if (!max_bytes) | |
624 return true; | |
625 | |
626 // Avoid a DCHECK later on. | |
627 if (max_bytes >= kint32max - kint32max / 10) | |
628 max_bytes = kint32max - kint32max / 10 - 1; | |
629 | |
630 user_flags_ |= kMaxSize; | |
631 max_size_ = max_bytes; | |
632 return true; | |
633 } | |
634 | |
635 void BackendImpl::SetType(net::CacheType type) { | |
636 DCHECK_NE(net::MEMORY_CACHE, type); | |
637 cache_type_ = type; | |
638 } | |
639 | |
640 base::FilePath BackendImpl::GetFileName(Addr address) const { | |
641 if (!address.is_separate_file() || !address.is_initialized()) { | |
642 NOTREACHED(); | |
643 return base::FilePath(); | |
644 } | |
645 | |
646 std::string tmp = base::StringPrintf("f_%06x", address.FileNumber()); | |
647 return path_.AppendASCII(tmp); | |
648 } | |
649 | |
650 MappedFile* BackendImpl::File(Addr address) { | |
651 if (disabled_) | |
652 return NULL; | |
653 return block_files_.GetFile(address); | |
654 } | |
655 | |
656 base::WeakPtr<InFlightBackendIO> BackendImpl::GetBackgroundQueue() { | |
657 return background_queue_.GetWeakPtr(); | |
658 } | |
659 | |
660 bool BackendImpl::CreateExternalFile(Addr* address) { | |
661 int file_number = data_->header.last_file + 1; | |
662 Addr file_address(0); | |
663 bool success = false; | |
664 for (int i = 0; i < 0x0fffffff; i++, file_number++) { | |
665 if (!file_address.SetFileNumber(file_number)) { | |
666 file_number = 1; | |
667 continue; | |
668 } | |
669 base::FilePath name = GetFileName(file_address); | |
670 int flags = base::PLATFORM_FILE_READ | | |
671 base::PLATFORM_FILE_WRITE | | |
672 base::PLATFORM_FILE_CREATE | | |
673 base::PLATFORM_FILE_EXCLUSIVE_WRITE; | |
674 base::PlatformFileError error; | |
675 scoped_refptr<disk_cache::File> file(new disk_cache::File( | |
676 base::CreatePlatformFile(name, flags, NULL, &error))); | |
677 if (!file->IsValid()) { | |
678 if (error != base::PLATFORM_FILE_ERROR_EXISTS) { | |
679 LOG(ERROR) << "Unable to create file: " << error; | |
680 return false; | |
681 } | |
682 continue; | |
683 } | |
684 | |
685 success = true; | |
686 break; | |
687 } | |
688 | |
689 DCHECK(success); | |
690 if (!success) | |
691 return false; | |
692 | |
693 data_->header.last_file = file_number; | |
694 address->set_value(file_address.value()); | |
695 return true; | |
696 } | |
697 | |
698 bool BackendImpl::CreateBlock(FileType block_type, int block_count, | |
699 Addr* block_address) { | |
700 return block_files_.CreateBlock(block_type, block_count, block_address); | |
701 } | |
702 | |
703 void BackendImpl::DeleteBlock(Addr block_address, bool deep) { | |
704 block_files_.DeleteBlock(block_address, deep); | |
705 } | |
706 | |
707 LruData* BackendImpl::GetLruData() { | |
708 return &data_->header.lru; | |
709 } | |
710 | |
711 void BackendImpl::UpdateRank(EntryImpl* entry, bool modified) { | |
712 if (read_only_ || (!modified && cache_type() == net::SHADER_CACHE)) | |
713 return; | |
714 eviction_.UpdateRank(entry, modified); | |
715 } | |
716 | |
717 void BackendImpl::RecoveredEntry(CacheRankingsBlock* rankings) { | |
718 Addr address(rankings->Data()->contents); | |
719 EntryImpl* cache_entry = NULL; | |
720 if (NewEntry(address, &cache_entry)) { | |
721 STRESS_NOTREACHED(); | |
722 return; | |
723 } | |
724 | |
725 uint32 hash = cache_entry->GetHash(); | |
726 cache_entry->Release(); | |
727 | |
728 // Anything on the table means that this entry is there. | |
729 if (data_->table[hash & mask_]) | |
730 return; | |
731 | |
732 data_->table[hash & mask_] = address.value(); | |
733 FlushIndex(); | |
734 } | |
735 | |
736 void BackendImpl::InternalDoomEntry(EntryImpl* entry) { | |
737 uint32 hash = entry->GetHash(); | |
738 std::string key = entry->GetKey(); | |
739 Addr entry_addr = entry->entry()->address(); | |
740 bool error; | |
741 EntryImpl* parent_entry = MatchEntry(key, hash, true, entry_addr, &error); | |
742 CacheAddr child(entry->GetNextAddress()); | |
743 | |
744 Trace("Doom entry 0x%p", entry); | |
745 | |
746 if (!entry->doomed()) { | |
747 // We may have doomed this entry from within MatchEntry. | |
748 eviction_.OnDoomEntry(entry); | |
749 entry->InternalDoom(); | |
750 if (!new_eviction_) { | |
751 DecreaseNumEntries(); | |
752 } | |
753 stats_.OnEvent(Stats::DOOM_ENTRY); | |
754 } | |
755 | |
756 if (parent_entry) { | |
757 parent_entry->SetNextAddress(Addr(child)); | |
758 parent_entry->Release(); | |
759 } else if (!error) { | |
760 data_->table[hash & mask_] = child; | |
761 } | |
762 | |
763 FlushIndex(); | |
764 } | |
765 | |
766 #if defined(NET_BUILD_STRESS_CACHE) | |
767 | |
768 CacheAddr BackendImpl::GetNextAddr(Addr address) { | |
769 EntriesMap::iterator it = open_entries_.find(address.value()); | |
770 if (it != open_entries_.end()) { | |
771 EntryImpl* this_entry = it->second; | |
772 return this_entry->GetNextAddress(); | |
773 } | |
774 DCHECK(block_files_.IsValid(address)); | |
775 DCHECK(!address.is_separate_file() && address.file_type() == BLOCK_256); | |
776 | |
777 CacheEntryBlock entry(File(address), address); | |
778 CHECK(entry.Load()); | |
779 return entry.Data()->next; | |
780 } | |
781 | |
782 void BackendImpl::NotLinked(EntryImpl* entry) { | |
783 Addr entry_addr = entry->entry()->address(); | |
784 uint32 i = entry->GetHash() & mask_; | |
785 Addr address(data_->table[i]); | |
786 if (!address.is_initialized()) | |
787 return; | |
788 | |
789 for (;;) { | |
790 DCHECK(entry_addr.value() != address.value()); | |
791 address.set_value(GetNextAddr(address)); | |
792 if (!address.is_initialized()) | |
793 break; | |
794 } | |
795 } | |
796 #endif // NET_BUILD_STRESS_CACHE | |
797 | |
798 // An entry may be linked on the DELETED list for a while after being doomed. | |
799 // This function is called when we want to remove it. | |
800 void BackendImpl::RemoveEntry(EntryImpl* entry) { | |
801 #if defined(NET_BUILD_STRESS_CACHE) | |
802 NotLinked(entry); | |
803 #endif | |
804 if (!new_eviction_) | |
805 return; | |
806 | |
807 DCHECK_NE(ENTRY_NORMAL, entry->entry()->Data()->state); | |
808 | |
809 Trace("Remove entry 0x%p", entry); | |
810 eviction_.OnDestroyEntry(entry); | |
811 DecreaseNumEntries(); | |
812 } | |
813 | |
814 void BackendImpl::OnEntryDestroyBegin(Addr address) { | |
815 EntriesMap::iterator it = open_entries_.find(address.value()); | |
816 if (it != open_entries_.end()) | |
817 open_entries_.erase(it); | |
818 } | |
819 | |
820 void BackendImpl::OnEntryDestroyEnd() { | |
821 DecreaseNumRefs(); | |
822 if (data_->header.num_bytes > max_size_ && !read_only_ && | |
823 (up_ticks_ > kTrimDelay || user_flags_ & kNoRandom)) | |
824 eviction_.TrimCache(false); | |
825 } | |
826 | |
827 EntryImpl* BackendImpl::GetOpenEntry(CacheRankingsBlock* rankings) const { | |
828 DCHECK(rankings->HasData()); | |
829 EntriesMap::const_iterator it = | |
830 open_entries_.find(rankings->Data()->contents); | |
831 if (it != open_entries_.end()) { | |
832 // We have this entry in memory. | |
833 return it->second; | |
834 } | |
835 | |
836 return NULL; | |
837 } | |
838 | |
839 int32 BackendImpl::GetCurrentEntryId() const { | |
840 return data_->header.this_id; | |
841 } | |
842 | |
843 int BackendImpl::MaxFileSize() const { | |
844 return cache_type() == net::PNACL_CACHE ? max_size_ : max_size_ / 8; | |
845 } | |
846 | |
847 void BackendImpl::ModifyStorageSize(int32 old_size, int32 new_size) { | |
848 if (disabled_ || old_size == new_size) | |
849 return; | |
850 if (old_size > new_size) | |
851 SubstractStorageSize(old_size - new_size); | |
852 else | |
853 AddStorageSize(new_size - old_size); | |
854 | |
855 FlushIndex(); | |
856 | |
857 // Update the usage statistics. | |
858 stats_.ModifyStorageStats(old_size, new_size); | |
859 } | |
860 | |
861 void BackendImpl::TooMuchStorageRequested(int32 size) { | |
862 stats_.ModifyStorageStats(0, size); | |
863 } | |
864 | |
865 bool BackendImpl::IsAllocAllowed(int current_size, int new_size) { | |
866 DCHECK_GT(new_size, current_size); | |
867 if (user_flags_ & kNoBuffering) | |
868 return false; | |
869 | |
870 int to_add = new_size - current_size; | |
871 if (buffer_bytes_ + to_add > MaxBuffersSize()) | |
872 return false; | |
873 | |
874 buffer_bytes_ += to_add; | |
875 CACHE_UMA(COUNTS_50000, "BufferBytes", 0, buffer_bytes_ / 1024); | |
876 return true; | |
877 } | |
878 | |
879 void BackendImpl::BufferDeleted(int size) { | |
880 buffer_bytes_ -= size; | |
881 DCHECK_GE(size, 0); | |
882 } | |
883 | |
884 bool BackendImpl::IsLoaded() const { | |
885 CACHE_UMA(COUNTS, "PendingIO", 0, num_pending_io_); | |
886 if (user_flags_ & kNoLoadProtection) | |
887 return false; | |
888 | |
889 return (num_pending_io_ > 5 || user_load_); | |
890 } | |
891 | |
892 std::string BackendImpl::HistogramName(const char* name, int experiment) const { | |
893 if (!experiment) | |
894 return base::StringPrintf("DiskCache.%d.%s", cache_type_, name); | |
895 return base::StringPrintf("DiskCache.%d.%s_%d", cache_type_, | |
896 name, experiment); | |
897 } | |
898 | |
899 base::WeakPtr<BackendImpl> BackendImpl::GetWeakPtr() { | |
900 return ptr_factory_.GetWeakPtr(); | |
901 } | |
902 | |
903 // We want to remove biases from some histograms so we only send data once per | |
904 // week. | |
905 bool BackendImpl::ShouldReportAgain() { | |
906 if (uma_report_) | |
907 return uma_report_ == 2; | |
908 | |
909 uma_report_++; | |
910 int64 last_report = stats_.GetCounter(Stats::LAST_REPORT); | |
911 Time last_time = Time::FromInternalValue(last_report); | |
912 if (!last_report || (Time::Now() - last_time).InDays() >= 7) { | |
913 stats_.SetCounter(Stats::LAST_REPORT, Time::Now().ToInternalValue()); | |
914 uma_report_++; | |
915 return true; | |
916 } | |
917 return false; | |
918 } | |
919 | |
920 void BackendImpl::FirstEviction() { | |
921 DCHECK(data_->header.create_time); | |
922 if (!GetEntryCount()) | |
923 return; // This is just for unit tests. | |
924 | |
925 Time create_time = Time::FromInternalValue(data_->header.create_time); | |
926 CACHE_UMA(AGE, "FillupAge", 0, create_time); | |
927 | |
928 int64 use_time = stats_.GetCounter(Stats::TIMER); | |
929 CACHE_UMA(HOURS, "FillupTime", 0, static_cast<int>(use_time / 120)); | |
930 CACHE_UMA(PERCENTAGE, "FirstHitRatio", 0, stats_.GetHitRatio()); | |
931 | |
932 if (!use_time) | |
933 use_time = 1; | |
934 CACHE_UMA(COUNTS_10000, "FirstEntryAccessRate", 0, | |
935 static_cast<int>(data_->header.num_entries / use_time)); | |
936 CACHE_UMA(COUNTS, "FirstByteIORate", 0, | |
937 static_cast<int>((data_->header.num_bytes / 1024) / use_time)); | |
938 | |
939 int avg_size = data_->header.num_bytes / GetEntryCount(); | |
940 CACHE_UMA(COUNTS, "FirstEntrySize", 0, avg_size); | |
941 | |
942 int large_entries_bytes = stats_.GetLargeEntriesSize(); | |
943 int large_ratio = large_entries_bytes * 100 / data_->header.num_bytes; | |
944 CACHE_UMA(PERCENTAGE, "FirstLargeEntriesRatio", 0, large_ratio); | |
945 | |
946 if (new_eviction_) { | |
947 CACHE_UMA(PERCENTAGE, "FirstResurrectRatio", 0, stats_.GetResurrectRatio()); | |
948 CACHE_UMA(PERCENTAGE, "FirstNoUseRatio", 0, | |
949 data_->header.lru.sizes[0] * 100 / data_->header.num_entries); | |
950 CACHE_UMA(PERCENTAGE, "FirstLowUseRatio", 0, | |
951 data_->header.lru.sizes[1] * 100 / data_->header.num_entries); | |
952 CACHE_UMA(PERCENTAGE, "FirstHighUseRatio", 0, | |
953 data_->header.lru.sizes[2] * 100 / data_->header.num_entries); | |
954 } | |
955 | |
956 stats_.ResetRatios(); | |
957 } | |
958 | |
959 void BackendImpl::CriticalError(int error) { | |
960 STRESS_NOTREACHED(); | |
961 LOG(ERROR) << "Critical error found " << error; | |
962 if (disabled_) | |
963 return; | |
964 | |
965 stats_.OnEvent(Stats::FATAL_ERROR); | |
966 LogStats(); | |
967 ReportError(error); | |
968 | |
969 // Setting the index table length to an invalid value will force re-creation | |
970 // of the cache files. | |
971 data_->header.table_len = 1; | |
972 disabled_ = true; | |
973 | |
974 if (!num_refs_) | |
975 base::MessageLoop::current()->PostTask( | |
976 FROM_HERE, base::Bind(&BackendImpl::RestartCache, GetWeakPtr(), true)); | |
977 } | |
978 | |
979 void BackendImpl::ReportError(int error) { | |
980 STRESS_DCHECK(!error || error == ERR_PREVIOUS_CRASH || | |
981 error == ERR_CACHE_CREATED); | |
982 | |
983 // We transmit positive numbers, instead of direct error codes. | |
984 DCHECK_LE(error, 0); | |
985 CACHE_UMA(CACHE_ERROR, "Error", 0, error * -1); | |
986 } | |
987 | |
988 void BackendImpl::OnEvent(Stats::Counters an_event) { | |
989 stats_.OnEvent(an_event); | |
990 } | |
991 | |
992 void BackendImpl::OnRead(int32 bytes) { | |
993 DCHECK_GE(bytes, 0); | |
994 byte_count_ += bytes; | |
995 if (byte_count_ < 0) | |
996 byte_count_ = kint32max; | |
997 } | |
998 | |
999 void BackendImpl::OnWrite(int32 bytes) { | |
1000 // We use the same implementation as OnRead... just log the number of bytes. | |
1001 OnRead(bytes); | |
1002 } | |
1003 | |
1004 void BackendImpl::OnStatsTimer() { | |
1005 if (disabled_) | |
1006 return; | |
1007 | |
1008 stats_.OnEvent(Stats::TIMER); | |
1009 int64 time = stats_.GetCounter(Stats::TIMER); | |
1010 int64 current = stats_.GetCounter(Stats::OPEN_ENTRIES); | |
1011 | |
1012 // OPEN_ENTRIES is a sampled average of the number of open entries, avoiding | |
1013 // the bias towards 0. | |
1014 if (num_refs_ && (current != num_refs_)) { | |
1015 int64 diff = (num_refs_ - current) / 50; | |
1016 if (!diff) | |
1017 diff = num_refs_ > current ? 1 : -1; | |
1018 current = current + diff; | |
1019 stats_.SetCounter(Stats::OPEN_ENTRIES, current); | |
1020 stats_.SetCounter(Stats::MAX_ENTRIES, max_refs_); | |
1021 } | |
1022 | |
1023 CACHE_UMA(COUNTS, "NumberOfReferences", 0, num_refs_); | |
1024 | |
1025 CACHE_UMA(COUNTS_10000, "EntryAccessRate", 0, entry_count_); | |
1026 CACHE_UMA(COUNTS, "ByteIORate", 0, byte_count_ / 1024); | |
1027 | |
1028 // These values cover about 99.5% of the population (Oct 2011). | |
1029 user_load_ = (entry_count_ > 300 || byte_count_ > 7 * 1024 * 1024); | |
1030 entry_count_ = 0; | |
1031 byte_count_ = 0; | |
1032 up_ticks_++; | |
1033 | |
1034 if (!data_) | |
1035 first_timer_ = false; | |
1036 if (first_timer_) { | |
1037 first_timer_ = false; | |
1038 if (ShouldReportAgain()) | |
1039 ReportStats(); | |
1040 } | |
1041 | |
1042 // Save stats to disk at 5 min intervals. | |
1043 if (time % 10 == 0) | |
1044 StoreStats(); | |
1045 } | |
1046 | |
1047 void BackendImpl::IncrementIoCount() { | |
1048 num_pending_io_++; | |
1049 } | |
1050 | |
1051 void BackendImpl::DecrementIoCount() { | |
1052 num_pending_io_--; | |
1053 } | |
1054 | |
1055 void BackendImpl::SetUnitTestMode() { | |
1056 user_flags_ |= kUnitTestMode; | |
1057 unit_test_ = true; | |
1058 } | |
1059 | |
1060 void BackendImpl::SetUpgradeMode() { | |
1061 user_flags_ |= kUpgradeMode; | |
1062 read_only_ = true; | |
1063 } | |
1064 | |
1065 void BackendImpl::SetNewEviction() { | |
1066 user_flags_ |= kNewEviction; | |
1067 new_eviction_ = true; | |
1068 } | |
1069 | |
1070 void BackendImpl::SetFlags(uint32 flags) { | |
1071 user_flags_ |= flags; | |
1072 } | |
1073 | |
1074 void BackendImpl::ClearRefCountForTest() { | |
1075 num_refs_ = 0; | |
1076 } | |
1077 | |
1078 int BackendImpl::FlushQueueForTest(const CompletionCallback& callback) { | |
1079 background_queue_.FlushQueue(callback); | |
1080 return net::ERR_IO_PENDING; | |
1081 } | |
1082 | |
1083 int BackendImpl::RunTaskForTest(const base::Closure& task, | |
1084 const CompletionCallback& callback) { | |
1085 background_queue_.RunTask(task, callback); | |
1086 return net::ERR_IO_PENDING; | |
1087 } | |
1088 | |
1089 void BackendImpl::TrimForTest(bool empty) { | |
1090 eviction_.SetTestMode(); | |
1091 eviction_.TrimCache(empty); | |
1092 } | |
1093 | |
1094 void BackendImpl::TrimDeletedListForTest(bool empty) { | |
1095 eviction_.SetTestMode(); | |
1096 eviction_.TrimDeletedList(empty); | |
1097 } | |
1098 | |
1099 base::RepeatingTimer<BackendImpl>* BackendImpl::GetTimerForTest() { | |
1100 return timer_.get(); | |
1101 } | |
1102 | |
1103 int BackendImpl::SelfCheck() { | |
1104 if (!init_) { | |
1105 LOG(ERROR) << "Init failed"; | |
1106 return ERR_INIT_FAILED; | |
1107 } | |
1108 | |
1109 int num_entries = rankings_.SelfCheck(); | |
1110 if (num_entries < 0) { | |
1111 LOG(ERROR) << "Invalid rankings list, error " << num_entries; | |
1112 #if !defined(NET_BUILD_STRESS_CACHE) | |
1113 return num_entries; | |
1114 #endif | |
1115 } | |
1116 | |
1117 if (num_entries != data_->header.num_entries) { | |
1118 LOG(ERROR) << "Number of entries mismatch"; | |
1119 #if !defined(NET_BUILD_STRESS_CACHE) | |
1120 return ERR_NUM_ENTRIES_MISMATCH; | |
1121 #endif | |
1122 } | |
1123 | |
1124 return CheckAllEntries(); | |
1125 } | |
1126 | |
1127 void BackendImpl::FlushIndex() { | |
1128 if (index_.get() && !disabled_) | |
1129 index_->Flush(); | |
1130 } | |
1131 | |
1132 // ------------------------------------------------------------------------ | |
1133 | |
1134 net::CacheType BackendImpl::GetCacheType() const { | |
1135 return cache_type_; | |
1136 } | |
1137 | |
1138 int32 BackendImpl::GetEntryCount() const { | |
1139 if (!index_.get() || disabled_) | |
1140 return 0; | |
1141 // num_entries includes entries already evicted. | |
1142 int32 not_deleted = data_->header.num_entries - | |
1143 data_->header.lru.sizes[Rankings::DELETED]; | |
1144 | |
1145 if (not_deleted < 0) { | |
1146 NOTREACHED(); | |
1147 not_deleted = 0; | |
1148 } | |
1149 | |
1150 return not_deleted; | |
1151 } | |
1152 | |
1153 int BackendImpl::OpenEntry(const std::string& key, Entry** entry, | |
1154 const CompletionCallback& callback) { | |
1155 DCHECK(!callback.is_null()); | |
1156 background_queue_.OpenEntry(key, entry, callback); | |
1157 return net::ERR_IO_PENDING; | |
1158 } | |
1159 | |
1160 int BackendImpl::CreateEntry(const std::string& key, Entry** entry, | |
1161 const CompletionCallback& callback) { | |
1162 DCHECK(!callback.is_null()); | |
1163 background_queue_.CreateEntry(key, entry, callback); | |
1164 return net::ERR_IO_PENDING; | |
1165 } | |
1166 | |
1167 int BackendImpl::DoomEntry(const std::string& key, | |
1168 const CompletionCallback& callback) { | |
1169 DCHECK(!callback.is_null()); | |
1170 background_queue_.DoomEntry(key, callback); | |
1171 return net::ERR_IO_PENDING; | |
1172 } | |
1173 | |
1174 int BackendImpl::DoomAllEntries(const CompletionCallback& callback) { | |
1175 DCHECK(!callback.is_null()); | |
1176 background_queue_.DoomAllEntries(callback); | |
1177 return net::ERR_IO_PENDING; | |
1178 } | |
1179 | |
1180 int BackendImpl::DoomEntriesBetween(const base::Time initial_time, | |
1181 const base::Time end_time, | |
1182 const CompletionCallback& callback) { | |
1183 DCHECK(!callback.is_null()); | |
1184 background_queue_.DoomEntriesBetween(initial_time, end_time, callback); | |
1185 return net::ERR_IO_PENDING; | |
1186 } | |
1187 | |
1188 int BackendImpl::DoomEntriesSince(const base::Time initial_time, | |
1189 const CompletionCallback& callback) { | |
1190 DCHECK(!callback.is_null()); | |
1191 background_queue_.DoomEntriesSince(initial_time, callback); | |
1192 return net::ERR_IO_PENDING; | |
1193 } | |
1194 | |
1195 int BackendImpl::OpenNextEntry(void** iter, Entry** next_entry, | |
1196 const CompletionCallback& callback) { | |
1197 DCHECK(!callback.is_null()); | |
1198 background_queue_.OpenNextEntry(iter, next_entry, callback); | |
1199 return net::ERR_IO_PENDING; | |
1200 } | |
1201 | |
1202 void BackendImpl::EndEnumeration(void** iter) { | |
1203 background_queue_.EndEnumeration(*iter); | |
1204 *iter = NULL; | |
1205 } | |
1206 | |
1207 void BackendImpl::GetStats(StatsItems* stats) { | |
1208 if (disabled_) | |
1209 return; | |
1210 | |
1211 std::pair<std::string, std::string> item; | |
1212 | |
1213 item.first = "Entries"; | |
1214 item.second = base::StringPrintf("%d", data_->header.num_entries); | |
1215 stats->push_back(item); | |
1216 | |
1217 item.first = "Pending IO"; | |
1218 item.second = base::StringPrintf("%d", num_pending_io_); | |
1219 stats->push_back(item); | |
1220 | |
1221 item.first = "Max size"; | |
1222 item.second = base::StringPrintf("%d", max_size_); | |
1223 stats->push_back(item); | |
1224 | |
1225 item.first = "Current size"; | |
1226 item.second = base::StringPrintf("%d", data_->header.num_bytes); | |
1227 stats->push_back(item); | |
1228 | |
1229 item.first = "Cache type"; | |
1230 item.second = "Blockfile Cache"; | |
1231 stats->push_back(item); | |
1232 | |
1233 stats_.GetItems(stats); | |
1234 } | |
1235 | |
1236 void BackendImpl::OnExternalCacheHit(const std::string& key) { | |
1237 background_queue_.OnExternalCacheHit(key); | |
1238 } | |
1239 | |
1240 // ------------------------------------------------------------------------ | |
1241 | |
1242 // We just created a new file so we're going to write the header and set the | |
1243 // file length to include the hash table (zero filled). | |
1244 bool BackendImpl::CreateBackingStore(disk_cache::File* file) { | |
1245 AdjustMaxCacheSize(0); | |
1246 | |
1247 IndexHeader header; | |
1248 header.table_len = DesiredIndexTableLen(max_size_); | |
1249 | |
1250 // We need file version 2.1 for the new eviction algorithm. | |
1251 if (new_eviction_) | |
1252 header.version = 0x20001; | |
1253 | |
1254 header.create_time = Time::Now().ToInternalValue(); | |
1255 | |
1256 if (!file->Write(&header, sizeof(header), 0)) | |
1257 return false; | |
1258 | |
1259 return file->SetLength(GetIndexSize(header.table_len)); | |
1260 } | |
1261 | |
1262 bool BackendImpl::InitBackingStore(bool* file_created) { | |
1263 if (!base::CreateDirectory(path_)) | |
1264 return false; | |
1265 | |
1266 base::FilePath index_name = path_.AppendASCII(kIndexName); | |
1267 | |
1268 int flags = base::PLATFORM_FILE_READ | | |
1269 base::PLATFORM_FILE_WRITE | | |
1270 base::PLATFORM_FILE_OPEN_ALWAYS | | |
1271 base::PLATFORM_FILE_EXCLUSIVE_WRITE; | |
1272 scoped_refptr<disk_cache::File> file(new disk_cache::File( | |
1273 base::CreatePlatformFile(index_name, flags, file_created, NULL))); | |
1274 | |
1275 if (!file->IsValid()) | |
1276 return false; | |
1277 | |
1278 bool ret = true; | |
1279 if (*file_created) | |
1280 ret = CreateBackingStore(file.get()); | |
1281 | |
1282 file = NULL; | |
1283 if (!ret) | |
1284 return false; | |
1285 | |
1286 index_ = new MappedFile(); | |
1287 data_ = reinterpret_cast<Index*>(index_->Init(index_name, 0)); | |
1288 if (!data_) { | |
1289 LOG(ERROR) << "Unable to map Index file"; | |
1290 return false; | |
1291 } | |
1292 | |
1293 if (index_->GetLength() < sizeof(Index)) { | |
1294 // We verify this again on CheckIndex() but it's easier to make sure now | |
1295 // that the header is there. | |
1296 LOG(ERROR) << "Corrupt Index file"; | |
1297 return false; | |
1298 } | |
1299 | |
1300 return true; | |
1301 } | |
1302 | |
1303 // The maximum cache size will be either set explicitly by the caller, or | |
1304 // calculated by this code. | |
1305 void BackendImpl::AdjustMaxCacheSize(int table_len) { | |
1306 if (max_size_) | |
1307 return; | |
1308 | |
1309 // If table_len is provided, the index file exists. | |
1310 DCHECK(!table_len || data_->header.magic); | |
1311 | |
1312 // The user is not setting the size, let's figure it out. | |
1313 int64 available = base::SysInfo::AmountOfFreeDiskSpace(path_); | |
1314 if (available < 0) { | |
1315 max_size_ = kDefaultCacheSize; | |
1316 return; | |
1317 } | |
1318 | |
1319 if (table_len) | |
1320 available += data_->header.num_bytes; | |
1321 | |
1322 max_size_ = PreferredCacheSize(available); | |
1323 | |
1324 if (!table_len) | |
1325 return; | |
1326 | |
1327 // If we already have a table, adjust the size to it. | |
1328 int current_max_size = MaxStorageSizeForTable(table_len); | |
1329 if (max_size_ > current_max_size) | |
1330 max_size_= current_max_size; | |
1331 } | |
1332 | |
1333 bool BackendImpl::InitStats() { | |
1334 Addr address(data_->header.stats); | |
1335 int size = stats_.StorageSize(); | |
1336 | |
1337 if (!address.is_initialized()) { | |
1338 FileType file_type = Addr::RequiredFileType(size); | |
1339 DCHECK_NE(file_type, EXTERNAL); | |
1340 int num_blocks = Addr::RequiredBlocks(size, file_type); | |
1341 | |
1342 if (!CreateBlock(file_type, num_blocks, &address)) | |
1343 return false; | |
1344 | |
1345 data_->header.stats = address.value(); | |
1346 return stats_.Init(NULL, 0, address); | |
1347 } | |
1348 | |
1349 if (!address.is_block_file()) { | |
1350 NOTREACHED(); | |
1351 return false; | |
1352 } | |
1353 | |
1354 // Load the required data. | |
1355 size = address.num_blocks() * address.BlockSize(); | |
1356 MappedFile* file = File(address); | |
1357 if (!file) | |
1358 return false; | |
1359 | |
1360 scoped_ptr<char[]> data(new char[size]); | |
1361 size_t offset = address.start_block() * address.BlockSize() + | |
1362 kBlockHeaderSize; | |
1363 if (!file->Read(data.get(), size, offset)) | |
1364 return false; | |
1365 | |
1366 if (!stats_.Init(data.get(), size, address)) | |
1367 return false; | |
1368 if (cache_type_ == net::DISK_CACHE && ShouldReportAgain()) | |
1369 stats_.InitSizeHistogram(); | |
1370 return true; | |
1371 } | |
1372 | |
1373 void BackendImpl::StoreStats() { | |
1374 int size = stats_.StorageSize(); | |
1375 scoped_ptr<char[]> data(new char[size]); | |
1376 Addr address; | |
1377 size = stats_.SerializeStats(data.get(), size, &address); | |
1378 DCHECK(size); | |
1379 if (!address.is_initialized()) | |
1380 return; | |
1381 | |
1382 MappedFile* file = File(address); | |
1383 if (!file) | |
1384 return; | |
1385 | |
1386 size_t offset = address.start_block() * address.BlockSize() + | |
1387 kBlockHeaderSize; | |
1388 file->Write(data.get(), size, offset); // ignore result. | |
1389 } | |
1390 | |
1391 void BackendImpl::RestartCache(bool failure) { | |
1392 int64 errors = stats_.GetCounter(Stats::FATAL_ERROR); | |
1393 int64 full_dooms = stats_.GetCounter(Stats::DOOM_CACHE); | |
1394 int64 partial_dooms = stats_.GetCounter(Stats::DOOM_RECENT); | |
1395 int64 last_report = stats_.GetCounter(Stats::LAST_REPORT); | |
1396 | |
1397 PrepareForRestart(); | |
1398 if (failure) { | |
1399 DCHECK(!num_refs_); | |
1400 DCHECK(!open_entries_.size()); | |
1401 DelayedCacheCleanup(path_); | |
1402 } else { | |
1403 DeleteCache(path_, false); | |
1404 } | |
1405 | |
1406 // Don't call Init() if directed by the unit test: we are simulating a failure | |
1407 // trying to re-enable the cache. | |
1408 if (unit_test_) | |
1409 init_ = true; // Let the destructor do proper cleanup. | |
1410 else if (SyncInit() == net::OK) { | |
1411 stats_.SetCounter(Stats::FATAL_ERROR, errors); | |
1412 stats_.SetCounter(Stats::DOOM_CACHE, full_dooms); | |
1413 stats_.SetCounter(Stats::DOOM_RECENT, partial_dooms); | |
1414 stats_.SetCounter(Stats::LAST_REPORT, last_report); | |
1415 } | |
1416 } | |
1417 | |
1418 void BackendImpl::PrepareForRestart() { | |
1419 // Reset the mask_ if it was not given by the user. | |
1420 if (!(user_flags_ & kMask)) | |
1421 mask_ = 0; | |
1422 | |
1423 if (!(user_flags_ & kNewEviction)) | |
1424 new_eviction_ = false; | |
1425 | |
1426 disabled_ = true; | |
1427 data_->header.crash = 0; | |
1428 index_->Flush(); | |
1429 index_ = NULL; | |
1430 data_ = NULL; | |
1431 block_files_.CloseFiles(); | |
1432 rankings_.Reset(); | |
1433 init_ = false; | |
1434 restarted_ = true; | |
1435 } | |
1436 | |
1437 int BackendImpl::NewEntry(Addr address, EntryImpl** entry) { | |
1438 EntriesMap::iterator it = open_entries_.find(address.value()); | |
1439 if (it != open_entries_.end()) { | |
1440 // Easy job. This entry is already in memory. | |
1441 EntryImpl* this_entry = it->second; | |
1442 this_entry->AddRef(); | |
1443 *entry = this_entry; | |
1444 return 0; | |
1445 } | |
1446 | |
1447 STRESS_DCHECK(block_files_.IsValid(address)); | |
1448 | |
1449 if (!address.SanityCheckForEntryV2()) { | |
1450 LOG(WARNING) << "Wrong entry address."; | |
1451 STRESS_NOTREACHED(); | |
1452 return ERR_INVALID_ADDRESS; | |
1453 } | |
1454 | |
1455 scoped_refptr<EntryImpl> cache_entry( | |
1456 new EntryImpl(this, address, read_only_)); | |
1457 IncreaseNumRefs(); | |
1458 *entry = NULL; | |
1459 | |
1460 TimeTicks start = TimeTicks::Now(); | |
1461 if (!cache_entry->entry()->Load()) | |
1462 return ERR_READ_FAILURE; | |
1463 | |
1464 if (IsLoaded()) { | |
1465 CACHE_UMA(AGE_MS, "LoadTime", 0, start); | |
1466 } | |
1467 | |
1468 if (!cache_entry->SanityCheck()) { | |
1469 LOG(WARNING) << "Messed up entry found."; | |
1470 STRESS_NOTREACHED(); | |
1471 return ERR_INVALID_ENTRY; | |
1472 } | |
1473 | |
1474 STRESS_DCHECK(block_files_.IsValid( | |
1475 Addr(cache_entry->entry()->Data()->rankings_node))); | |
1476 | |
1477 if (!cache_entry->LoadNodeAddress()) | |
1478 return ERR_READ_FAILURE; | |
1479 | |
1480 if (!rankings_.SanityCheck(cache_entry->rankings(), false)) { | |
1481 STRESS_NOTREACHED(); | |
1482 cache_entry->SetDirtyFlag(0); | |
1483 // Don't remove this from the list (it is not linked properly). Instead, | |
1484 // break the link back to the entry because it is going away, and leave the | |
1485 // rankings node to be deleted if we find it through a list. | |
1486 rankings_.SetContents(cache_entry->rankings(), 0); | |
1487 } else if (!rankings_.DataSanityCheck(cache_entry->rankings(), false)) { | |
1488 STRESS_NOTREACHED(); | |
1489 cache_entry->SetDirtyFlag(0); | |
1490 rankings_.SetContents(cache_entry->rankings(), address.value()); | |
1491 } | |
1492 | |
1493 if (!cache_entry->DataSanityCheck()) { | |
1494 LOG(WARNING) << "Messed up entry found."; | |
1495 cache_entry->SetDirtyFlag(0); | |
1496 cache_entry->FixForDelete(); | |
1497 } | |
1498 | |
1499 // Prevent overwriting the dirty flag on the destructor. | |
1500 cache_entry->SetDirtyFlag(GetCurrentEntryId()); | |
1501 | |
1502 if (cache_entry->dirty()) { | |
1503 Trace("Dirty entry 0x%p 0x%x", reinterpret_cast<void*>(cache_entry.get()), | |
1504 address.value()); | |
1505 } | |
1506 | |
1507 open_entries_[address.value()] = cache_entry.get(); | |
1508 | |
1509 cache_entry->BeginLogging(net_log_, false); | |
1510 cache_entry.swap(entry); | |
1511 return 0; | |
1512 } | |
1513 | |
1514 EntryImpl* BackendImpl::MatchEntry(const std::string& key, uint32 hash, | |
1515 bool find_parent, Addr entry_addr, | |
1516 bool* match_error) { | |
1517 Addr address(data_->table[hash & mask_]); | |
1518 scoped_refptr<EntryImpl> cache_entry, parent_entry; | |
1519 EntryImpl* tmp = NULL; | |
1520 bool found = false; | |
1521 std::set<CacheAddr> visited; | |
1522 *match_error = false; | |
1523 | |
1524 for (;;) { | |
1525 if (disabled_) | |
1526 break; | |
1527 | |
1528 if (visited.find(address.value()) != visited.end()) { | |
1529 // It's possible for a buggy version of the code to write a loop. Just | |
1530 // break it. | |
1531 Trace("Hash collision loop 0x%x", address.value()); | |
1532 address.set_value(0); | |
1533 parent_entry->SetNextAddress(address); | |
1534 } | |
1535 visited.insert(address.value()); | |
1536 | |
1537 if (!address.is_initialized()) { | |
1538 if (find_parent) | |
1539 found = true; | |
1540 break; | |
1541 } | |
1542 | |
1543 int error = NewEntry(address, &tmp); | |
1544 cache_entry.swap(&tmp); | |
1545 | |
1546 if (error || cache_entry->dirty()) { | |
1547 // This entry is dirty on disk (it was not properly closed): we cannot | |
1548 // trust it. | |
1549 Addr child(0); | |
1550 if (!error) | |
1551 child.set_value(cache_entry->GetNextAddress()); | |
1552 | |
1553 if (parent_entry.get()) { | |
1554 parent_entry->SetNextAddress(child); | |
1555 parent_entry = NULL; | |
1556 } else { | |
1557 data_->table[hash & mask_] = child.value(); | |
1558 } | |
1559 | |
1560 Trace("MatchEntry dirty %d 0x%x 0x%x", find_parent, entry_addr.value(), | |
1561 address.value()); | |
1562 | |
1563 if (!error) { | |
1564 // It is important to call DestroyInvalidEntry after removing this | |
1565 // entry from the table. | |
1566 DestroyInvalidEntry(cache_entry.get()); | |
1567 cache_entry = NULL; | |
1568 } else { | |
1569 Trace("NewEntry failed on MatchEntry 0x%x", address.value()); | |
1570 } | |
1571 | |
1572 // Restart the search. | |
1573 address.set_value(data_->table[hash & mask_]); | |
1574 visited.clear(); | |
1575 continue; | |
1576 } | |
1577 | |
1578 DCHECK_EQ(hash & mask_, cache_entry->entry()->Data()->hash & mask_); | |
1579 if (cache_entry->IsSameEntry(key, hash)) { | |
1580 if (!cache_entry->Update()) | |
1581 cache_entry = NULL; | |
1582 found = true; | |
1583 if (find_parent && entry_addr.value() != address.value()) { | |
1584 Trace("Entry not on the index 0x%x", address.value()); | |
1585 *match_error = true; | |
1586 parent_entry = NULL; | |
1587 } | |
1588 break; | |
1589 } | |
1590 if (!cache_entry->Update()) | |
1591 cache_entry = NULL; | |
1592 parent_entry = cache_entry; | |
1593 cache_entry = NULL; | |
1594 if (!parent_entry.get()) | |
1595 break; | |
1596 | |
1597 address.set_value(parent_entry->GetNextAddress()); | |
1598 } | |
1599 | |
1600 if (parent_entry.get() && (!find_parent || !found)) | |
1601 parent_entry = NULL; | |
1602 | |
1603 if (find_parent && entry_addr.is_initialized() && !cache_entry.get()) { | |
1604 *match_error = true; | |
1605 parent_entry = NULL; | |
1606 } | |
1607 | |
1608 if (cache_entry.get() && (find_parent || !found)) | |
1609 cache_entry = NULL; | |
1610 | |
1611 find_parent ? parent_entry.swap(&tmp) : cache_entry.swap(&tmp); | |
1612 FlushIndex(); | |
1613 return tmp; | |
1614 } | |
1615 | |
1616 // This is the actual implementation for OpenNextEntry and OpenPrevEntry. | |
1617 EntryImpl* BackendImpl::OpenFollowingEntry(bool forward, void** iter) { | |
1618 if (disabled_) | |
1619 return NULL; | |
1620 | |
1621 DCHECK(iter); | |
1622 | |
1623 const int kListsToSearch = 3; | |
1624 scoped_refptr<EntryImpl> entries[kListsToSearch]; | |
1625 scoped_ptr<Rankings::Iterator> iterator( | |
1626 reinterpret_cast<Rankings::Iterator*>(*iter)); | |
1627 *iter = NULL; | |
1628 | |
1629 if (!iterator.get()) { | |
1630 iterator.reset(new Rankings::Iterator(&rankings_)); | |
1631 bool ret = false; | |
1632 | |
1633 // Get an entry from each list. | |
1634 for (int i = 0; i < kListsToSearch; i++) { | |
1635 EntryImpl* temp = NULL; | |
1636 ret |= OpenFollowingEntryFromList(forward, static_cast<Rankings::List>(i), | |
1637 &iterator->nodes[i], &temp); | |
1638 entries[i].swap(&temp); // The entry was already addref'd. | |
1639 } | |
1640 if (!ret) | |
1641 return NULL; | |
1642 } else { | |
1643 // Get the next entry from the last list, and the actual entries for the | |
1644 // elements on the other lists. | |
1645 for (int i = 0; i < kListsToSearch; i++) { | |
1646 EntryImpl* temp = NULL; | |
1647 if (iterator->list == i) { | |
1648 OpenFollowingEntryFromList(forward, iterator->list, | |
1649 &iterator->nodes[i], &temp); | |
1650 } else { | |
1651 temp = GetEnumeratedEntry(iterator->nodes[i], | |
1652 static_cast<Rankings::List>(i)); | |
1653 } | |
1654 | |
1655 entries[i].swap(&temp); // The entry was already addref'd. | |
1656 } | |
1657 } | |
1658 | |
1659 int newest = -1; | |
1660 int oldest = -1; | |
1661 Time access_times[kListsToSearch]; | |
1662 for (int i = 0; i < kListsToSearch; i++) { | |
1663 if (entries[i].get()) { | |
1664 access_times[i] = entries[i]->GetLastUsed(); | |
1665 if (newest < 0) { | |
1666 DCHECK_LT(oldest, 0); | |
1667 newest = oldest = i; | |
1668 continue; | |
1669 } | |
1670 if (access_times[i] > access_times[newest]) | |
1671 newest = i; | |
1672 if (access_times[i] < access_times[oldest]) | |
1673 oldest = i; | |
1674 } | |
1675 } | |
1676 | |
1677 if (newest < 0 || oldest < 0) | |
1678 return NULL; | |
1679 | |
1680 EntryImpl* next_entry; | |
1681 if (forward) { | |
1682 next_entry = entries[newest].get(); | |
1683 iterator->list = static_cast<Rankings::List>(newest); | |
1684 } else { | |
1685 next_entry = entries[oldest].get(); | |
1686 iterator->list = static_cast<Rankings::List>(oldest); | |
1687 } | |
1688 | |
1689 *iter = iterator.release(); | |
1690 next_entry->AddRef(); | |
1691 return next_entry; | |
1692 } | |
1693 | |
1694 bool BackendImpl::OpenFollowingEntryFromList(bool forward, Rankings::List list, | |
1695 CacheRankingsBlock** from_entry, | |
1696 EntryImpl** next_entry) { | |
1697 if (disabled_) | |
1698 return false; | |
1699 | |
1700 if (!new_eviction_ && Rankings::NO_USE != list) | |
1701 return false; | |
1702 | |
1703 Rankings::ScopedRankingsBlock rankings(&rankings_, *from_entry); | |
1704 CacheRankingsBlock* next_block = forward ? | |
1705 rankings_.GetNext(rankings.get(), list) : | |
1706 rankings_.GetPrev(rankings.get(), list); | |
1707 Rankings::ScopedRankingsBlock next(&rankings_, next_block); | |
1708 *from_entry = NULL; | |
1709 | |
1710 *next_entry = GetEnumeratedEntry(next.get(), list); | |
1711 if (!*next_entry) | |
1712 return false; | |
1713 | |
1714 *from_entry = next.release(); | |
1715 return true; | |
1716 } | |
1717 | |
1718 EntryImpl* BackendImpl::GetEnumeratedEntry(CacheRankingsBlock* next, | |
1719 Rankings::List list) { | |
1720 if (!next || disabled_) | |
1721 return NULL; | |
1722 | |
1723 EntryImpl* entry; | |
1724 int rv = NewEntry(Addr(next->Data()->contents), &entry); | |
1725 if (rv) { | |
1726 STRESS_NOTREACHED(); | |
1727 rankings_.Remove(next, list, false); | |
1728 if (rv == ERR_INVALID_ADDRESS) { | |
1729 // There is nothing linked from the index. Delete the rankings node. | |
1730 DeleteBlock(next->address(), true); | |
1731 } | |
1732 return NULL; | |
1733 } | |
1734 | |
1735 if (entry->dirty()) { | |
1736 // We cannot trust this entry. | |
1737 InternalDoomEntry(entry); | |
1738 entry->Release(); | |
1739 return NULL; | |
1740 } | |
1741 | |
1742 if (!entry->Update()) { | |
1743 STRESS_NOTREACHED(); | |
1744 entry->Release(); | |
1745 return NULL; | |
1746 } | |
1747 | |
1748 // Note that it is unfortunate (but possible) for this entry to be clean, but | |
1749 // not actually the real entry. In other words, we could have lost this entry | |
1750 // from the index, and it could have been replaced with a newer one. It's not | |
1751 // worth checking that this entry is "the real one", so we just return it and | |
1752 // let the enumeration continue; this entry will be evicted at some point, and | |
1753 // the regular path will work with the real entry. With time, this problem | |
1754 // will disasappear because this scenario is just a bug. | |
1755 | |
1756 // Make sure that we save the key for later. | |
1757 entry->GetKey(); | |
1758 | |
1759 return entry; | |
1760 } | |
1761 | |
1762 EntryImpl* BackendImpl::ResurrectEntry(EntryImpl* deleted_entry) { | |
1763 if (ENTRY_NORMAL == deleted_entry->entry()->Data()->state) { | |
1764 deleted_entry->Release(); | |
1765 stats_.OnEvent(Stats::CREATE_MISS); | |
1766 Trace("create entry miss "); | |
1767 return NULL; | |
1768 } | |
1769 | |
1770 // We are attempting to create an entry and found out that the entry was | |
1771 // previously deleted. | |
1772 | |
1773 eviction_.OnCreateEntry(deleted_entry); | |
1774 entry_count_++; | |
1775 | |
1776 stats_.OnEvent(Stats::RESURRECT_HIT); | |
1777 Trace("Resurrect entry hit "); | |
1778 return deleted_entry; | |
1779 } | |
1780 | |
1781 void BackendImpl::DestroyInvalidEntry(EntryImpl* entry) { | |
1782 LOG(WARNING) << "Destroying invalid entry."; | |
1783 Trace("Destroying invalid entry 0x%p", entry); | |
1784 | |
1785 entry->SetPointerForInvalidEntry(GetCurrentEntryId()); | |
1786 | |
1787 eviction_.OnDoomEntry(entry); | |
1788 entry->InternalDoom(); | |
1789 | |
1790 if (!new_eviction_) | |
1791 DecreaseNumEntries(); | |
1792 stats_.OnEvent(Stats::INVALID_ENTRY); | |
1793 } | |
1794 | |
1795 void BackendImpl::AddStorageSize(int32 bytes) { | |
1796 data_->header.num_bytes += bytes; | |
1797 DCHECK_GE(data_->header.num_bytes, 0); | |
1798 } | |
1799 | |
1800 void BackendImpl::SubstractStorageSize(int32 bytes) { | |
1801 data_->header.num_bytes -= bytes; | |
1802 DCHECK_GE(data_->header.num_bytes, 0); | |
1803 } | |
1804 | |
1805 void BackendImpl::IncreaseNumRefs() { | |
1806 num_refs_++; | |
1807 if (max_refs_ < num_refs_) | |
1808 max_refs_ = num_refs_; | |
1809 } | |
1810 | |
1811 void BackendImpl::DecreaseNumRefs() { | |
1812 DCHECK(num_refs_); | |
1813 num_refs_--; | |
1814 | |
1815 if (!num_refs_ && disabled_) | |
1816 base::MessageLoop::current()->PostTask( | |
1817 FROM_HERE, base::Bind(&BackendImpl::RestartCache, GetWeakPtr(), true)); | |
1818 } | |
1819 | |
1820 void BackendImpl::IncreaseNumEntries() { | |
1821 data_->header.num_entries++; | |
1822 DCHECK_GT(data_->header.num_entries, 0); | |
1823 } | |
1824 | |
1825 void BackendImpl::DecreaseNumEntries() { | |
1826 data_->header.num_entries--; | |
1827 if (data_->header.num_entries < 0) { | |
1828 NOTREACHED(); | |
1829 data_->header.num_entries = 0; | |
1830 } | |
1831 } | |
1832 | |
1833 void BackendImpl::LogStats() { | |
1834 StatsItems stats; | |
1835 GetStats(&stats); | |
1836 | |
1837 for (size_t index = 0; index < stats.size(); index++) | |
1838 VLOG(1) << stats[index].first << ": " << stats[index].second; | |
1839 } | |
1840 | |
1841 void BackendImpl::ReportStats() { | |
1842 CACHE_UMA(COUNTS, "Entries", 0, data_->header.num_entries); | |
1843 | |
1844 int current_size = data_->header.num_bytes / (1024 * 1024); | |
1845 int max_size = max_size_ / (1024 * 1024); | |
1846 int hit_ratio_as_percentage = stats_.GetHitRatio(); | |
1847 | |
1848 CACHE_UMA(COUNTS_10000, "Size2", 0, current_size); | |
1849 // For any bin in HitRatioBySize2, the hit ratio of caches of that size is the | |
1850 // ratio of that bin's total count to the count in the same bin in the Size2 | |
1851 // histogram. | |
1852 if (base::RandInt(0, 99) < hit_ratio_as_percentage) | |
1853 CACHE_UMA(COUNTS_10000, "HitRatioBySize2", 0, current_size); | |
1854 CACHE_UMA(COUNTS_10000, "MaxSize2", 0, max_size); | |
1855 if (!max_size) | |
1856 max_size++; | |
1857 CACHE_UMA(PERCENTAGE, "UsedSpace", 0, current_size * 100 / max_size); | |
1858 | |
1859 CACHE_UMA(COUNTS_10000, "AverageOpenEntries2", 0, | |
1860 static_cast<int>(stats_.GetCounter(Stats::OPEN_ENTRIES))); | |
1861 CACHE_UMA(COUNTS_10000, "MaxOpenEntries2", 0, | |
1862 static_cast<int>(stats_.GetCounter(Stats::MAX_ENTRIES))); | |
1863 stats_.SetCounter(Stats::MAX_ENTRIES, 0); | |
1864 | |
1865 CACHE_UMA(COUNTS_10000, "TotalFatalErrors", 0, | |
1866 static_cast<int>(stats_.GetCounter(Stats::FATAL_ERROR))); | |
1867 CACHE_UMA(COUNTS_10000, "TotalDoomCache", 0, | |
1868 static_cast<int>(stats_.GetCounter(Stats::DOOM_CACHE))); | |
1869 CACHE_UMA(COUNTS_10000, "TotalDoomRecentEntries", 0, | |
1870 static_cast<int>(stats_.GetCounter(Stats::DOOM_RECENT))); | |
1871 stats_.SetCounter(Stats::FATAL_ERROR, 0); | |
1872 stats_.SetCounter(Stats::DOOM_CACHE, 0); | |
1873 stats_.SetCounter(Stats::DOOM_RECENT, 0); | |
1874 | |
1875 int age = (Time::Now() - | |
1876 Time::FromInternalValue(data_->header.create_time)).InHours(); | |
1877 if (age) | |
1878 CACHE_UMA(HOURS, "FilesAge", 0, age); | |
1879 | |
1880 int64 total_hours = stats_.GetCounter(Stats::TIMER) / 120; | |
1881 if (!data_->header.create_time || !data_->header.lru.filled) { | |
1882 int cause = data_->header.create_time ? 0 : 1; | |
1883 if (!data_->header.lru.filled) | |
1884 cause |= 2; | |
1885 CACHE_UMA(CACHE_ERROR, "ShortReport", 0, cause); | |
1886 CACHE_UMA(HOURS, "TotalTimeNotFull", 0, static_cast<int>(total_hours)); | |
1887 return; | |
1888 } | |
1889 | |
1890 // This is an up to date client that will report FirstEviction() data. After | |
1891 // that event, start reporting this: | |
1892 | |
1893 CACHE_UMA(HOURS, "TotalTime", 0, static_cast<int>(total_hours)); | |
1894 // For any bin in HitRatioByTotalTime, the hit ratio of caches of that total | |
1895 // time is the ratio of that bin's total count to the count in the same bin in | |
1896 // the TotalTime histogram. | |
1897 if (base::RandInt(0, 99) < hit_ratio_as_percentage) | |
1898 CACHE_UMA(HOURS, "HitRatioByTotalTime", 0, implicit_cast<int>(total_hours)); | |
1899 | |
1900 int64 use_hours = stats_.GetCounter(Stats::LAST_REPORT_TIMER) / 120; | |
1901 stats_.SetCounter(Stats::LAST_REPORT_TIMER, stats_.GetCounter(Stats::TIMER)); | |
1902 | |
1903 // We may see users with no use_hours at this point if this is the first time | |
1904 // we are running this code. | |
1905 if (use_hours) | |
1906 use_hours = total_hours - use_hours; | |
1907 | |
1908 if (!use_hours || !GetEntryCount() || !data_->header.num_bytes) | |
1909 return; | |
1910 | |
1911 CACHE_UMA(HOURS, "UseTime", 0, static_cast<int>(use_hours)); | |
1912 // For any bin in HitRatioByUseTime, the hit ratio of caches of that use time | |
1913 // is the ratio of that bin's total count to the count in the same bin in the | |
1914 // UseTime histogram. | |
1915 if (base::RandInt(0, 99) < hit_ratio_as_percentage) | |
1916 CACHE_UMA(HOURS, "HitRatioByUseTime", 0, implicit_cast<int>(use_hours)); | |
1917 CACHE_UMA(PERCENTAGE, "HitRatio", 0, hit_ratio_as_percentage); | |
1918 | |
1919 int64 trim_rate = stats_.GetCounter(Stats::TRIM_ENTRY) / use_hours; | |
1920 CACHE_UMA(COUNTS, "TrimRate", 0, static_cast<int>(trim_rate)); | |
1921 | |
1922 int avg_size = data_->header.num_bytes / GetEntryCount(); | |
1923 CACHE_UMA(COUNTS, "EntrySize", 0, avg_size); | |
1924 CACHE_UMA(COUNTS, "EntriesFull", 0, data_->header.num_entries); | |
1925 | |
1926 CACHE_UMA(PERCENTAGE, "IndexLoad", 0, | |
1927 data_->header.num_entries * 100 / (mask_ + 1)); | |
1928 | |
1929 int large_entries_bytes = stats_.GetLargeEntriesSize(); | |
1930 int large_ratio = large_entries_bytes * 100 / data_->header.num_bytes; | |
1931 CACHE_UMA(PERCENTAGE, "LargeEntriesRatio", 0, large_ratio); | |
1932 | |
1933 if (new_eviction_) { | |
1934 CACHE_UMA(PERCENTAGE, "ResurrectRatio", 0, stats_.GetResurrectRatio()); | |
1935 CACHE_UMA(PERCENTAGE, "NoUseRatio", 0, | |
1936 data_->header.lru.sizes[0] * 100 / data_->header.num_entries); | |
1937 CACHE_UMA(PERCENTAGE, "LowUseRatio", 0, | |
1938 data_->header.lru.sizes[1] * 100 / data_->header.num_entries); | |
1939 CACHE_UMA(PERCENTAGE, "HighUseRatio", 0, | |
1940 data_->header.lru.sizes[2] * 100 / data_->header.num_entries); | |
1941 CACHE_UMA(PERCENTAGE, "DeletedRatio", 0, | |
1942 data_->header.lru.sizes[4] * 100 / data_->header.num_entries); | |
1943 } | |
1944 | |
1945 stats_.ResetRatios(); | |
1946 stats_.SetCounter(Stats::TRIM_ENTRY, 0); | |
1947 | |
1948 if (cache_type_ == net::DISK_CACHE) | |
1949 block_files_.ReportStats(); | |
1950 } | |
1951 | |
1952 void BackendImpl::UpgradeTo2_1() { | |
1953 // 2.1 is basically the same as 2.0, except that new fields are actually | |
1954 // updated by the new eviction algorithm. | |
1955 DCHECK(0x20000 == data_->header.version); | |
1956 data_->header.version = 0x20001; | |
1957 data_->header.lru.sizes[Rankings::NO_USE] = data_->header.num_entries; | |
1958 } | |
1959 | |
1960 bool BackendImpl::CheckIndex() { | |
1961 DCHECK(data_); | |
1962 | |
1963 size_t current_size = index_->GetLength(); | |
1964 if (current_size < sizeof(Index)) { | |
1965 LOG(ERROR) << "Corrupt Index file"; | |
1966 return false; | |
1967 } | |
1968 | |
1969 if (new_eviction_) { | |
1970 // We support versions 2.0 and 2.1, upgrading 2.0 to 2.1. | |
1971 if (kIndexMagic != data_->header.magic || | |
1972 kCurrentVersion >> 16 != data_->header.version >> 16) { | |
1973 LOG(ERROR) << "Invalid file version or magic"; | |
1974 return false; | |
1975 } | |
1976 if (kCurrentVersion == data_->header.version) { | |
1977 // We need file version 2.1 for the new eviction algorithm. | |
1978 UpgradeTo2_1(); | |
1979 } | |
1980 } else { | |
1981 if (kIndexMagic != data_->header.magic || | |
1982 kCurrentVersion != data_->header.version) { | |
1983 LOG(ERROR) << "Invalid file version or magic"; | |
1984 return false; | |
1985 } | |
1986 } | |
1987 | |
1988 if (!data_->header.table_len) { | |
1989 LOG(ERROR) << "Invalid table size"; | |
1990 return false; | |
1991 } | |
1992 | |
1993 if (current_size < GetIndexSize(data_->header.table_len) || | |
1994 data_->header.table_len & (kBaseTableLen - 1)) { | |
1995 LOG(ERROR) << "Corrupt Index file"; | |
1996 return false; | |
1997 } | |
1998 | |
1999 AdjustMaxCacheSize(data_->header.table_len); | |
2000 | |
2001 #if !defined(NET_BUILD_STRESS_CACHE) | |
2002 if (data_->header.num_bytes < 0 || | |
2003 (max_size_ < kint32max - kDefaultCacheSize && | |
2004 data_->header.num_bytes > max_size_ + kDefaultCacheSize)) { | |
2005 LOG(ERROR) << "Invalid cache (current) size"; | |
2006 return false; | |
2007 } | |
2008 #endif | |
2009 | |
2010 if (data_->header.num_entries < 0) { | |
2011 LOG(ERROR) << "Invalid number of entries"; | |
2012 return false; | |
2013 } | |
2014 | |
2015 if (!mask_) | |
2016 mask_ = data_->header.table_len - 1; | |
2017 | |
2018 // Load the table into memory with a single read. | |
2019 scoped_ptr<char[]> buf(new char[current_size]); | |
2020 return index_->Read(buf.get(), current_size, 0); | |
2021 } | |
2022 | |
2023 int BackendImpl::CheckAllEntries() { | |
2024 int num_dirty = 0; | |
2025 int num_entries = 0; | |
2026 DCHECK(mask_ < kuint32max); | |
2027 for (unsigned int i = 0; i <= mask_; i++) { | |
2028 Addr address(data_->table[i]); | |
2029 if (!address.is_initialized()) | |
2030 continue; | |
2031 for (;;) { | |
2032 EntryImpl* tmp; | |
2033 int ret = NewEntry(address, &tmp); | |
2034 if (ret) { | |
2035 STRESS_NOTREACHED(); | |
2036 return ret; | |
2037 } | |
2038 scoped_refptr<EntryImpl> cache_entry; | |
2039 cache_entry.swap(&tmp); | |
2040 | |
2041 if (cache_entry->dirty()) | |
2042 num_dirty++; | |
2043 else if (CheckEntry(cache_entry.get())) | |
2044 num_entries++; | |
2045 else | |
2046 return ERR_INVALID_ENTRY; | |
2047 | |
2048 DCHECK_EQ(i, cache_entry->entry()->Data()->hash & mask_); | |
2049 address.set_value(cache_entry->GetNextAddress()); | |
2050 if (!address.is_initialized()) | |
2051 break; | |
2052 } | |
2053 } | |
2054 | |
2055 Trace("CheckAllEntries End"); | |
2056 if (num_entries + num_dirty != data_->header.num_entries) { | |
2057 LOG(ERROR) << "Number of entries " << num_entries << " " << num_dirty << | |
2058 " " << data_->header.num_entries; | |
2059 DCHECK_LT(num_entries, data_->header.num_entries); | |
2060 return ERR_NUM_ENTRIES_MISMATCH; | |
2061 } | |
2062 | |
2063 return num_dirty; | |
2064 } | |
2065 | |
2066 bool BackendImpl::CheckEntry(EntryImpl* cache_entry) { | |
2067 bool ok = block_files_.IsValid(cache_entry->entry()->address()); | |
2068 ok = ok && block_files_.IsValid(cache_entry->rankings()->address()); | |
2069 EntryStore* data = cache_entry->entry()->Data(); | |
2070 for (size_t i = 0; i < arraysize(data->data_addr); i++) { | |
2071 if (data->data_addr[i]) { | |
2072 Addr address(data->data_addr[i]); | |
2073 if (address.is_block_file()) | |
2074 ok = ok && block_files_.IsValid(address); | |
2075 } | |
2076 } | |
2077 | |
2078 return ok && cache_entry->rankings()->VerifyHash(); | |
2079 } | |
2080 | |
2081 int BackendImpl::MaxBuffersSize() { | |
2082 static int64 total_memory = base::SysInfo::AmountOfPhysicalMemory(); | |
2083 static bool done = false; | |
2084 | |
2085 if (!done) { | |
2086 const int kMaxBuffersSize = 30 * 1024 * 1024; | |
2087 | |
2088 // We want to use up to 2% of the computer's memory. | |
2089 total_memory = total_memory * 2 / 100; | |
2090 if (total_memory > kMaxBuffersSize || total_memory <= 0) | |
2091 total_memory = kMaxBuffersSize; | |
2092 | |
2093 done = true; | |
2094 } | |
2095 | |
2096 return static_cast<int>(total_memory); | |
2097 } | |
2098 | |
2099 } // namespace disk_cache | |
OLD | NEW |