OLD | NEW |
---|---|
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 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 | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "net/disk_cache/backend_impl.h" | 5 #include "net/disk_cache/backend_impl.h" |
6 | 6 |
7 #include "base/bind.h" | 7 #include "base/bind.h" |
8 #include "base/bind_helpers.h" | 8 #include "base/bind_helpers.h" |
9 #include "base/file_util.h" | 9 #include "base/file_util.h" |
10 #include "base/files/file_path.h" | 10 #include "base/files/file_path.h" |
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
65 | 65 |
66 int MaxStorageSizeForTable(int table_len) { | 66 int MaxStorageSizeForTable(int table_len) { |
67 return table_len * (k64kEntriesStore / kBaseTableLen); | 67 return table_len * (k64kEntriesStore / kBaseTableLen); |
68 } | 68 } |
69 | 69 |
70 size_t GetIndexSize(int table_len) { | 70 size_t GetIndexSize(int table_len) { |
71 size_t table_size = sizeof(disk_cache::CacheAddr) * table_len; | 71 size_t table_size = sizeof(disk_cache::CacheAddr) * table_len; |
72 return sizeof(disk_cache::IndexHeader) + table_size; | 72 return sizeof(disk_cache::IndexHeader) + table_size; |
73 } | 73 } |
74 | 74 |
75 // ------------------------------------------------------------------------ | |
76 | |
77 // Sets group for the current experiment. Returns false if the files should be | |
78 // discarded. | |
79 bool InitExperiment(disk_cache::IndexHeader* header, bool cache_created) { | |
80 if (header->experiment == disk_cache::EXPERIMENT_OLD_FILE1 || | |
81 header->experiment == disk_cache::EXPERIMENT_OLD_FILE2) { | |
82 // Discard current cache. | |
83 return false; | |
84 } | |
85 | |
86 if (base::FieldTrialList::FindFullName("SimpleCacheTrial") == | |
87 "ExperimentControl") { | |
88 if (cache_created) { | |
89 header->experiment = disk_cache::EXPERIMENT_SIMPLE_CONTROL; | |
90 return true; | |
91 } else if (header->experiment != disk_cache::EXPERIMENT_SIMPLE_CONTROL) { | |
92 return false; | |
93 } | |
94 } | |
95 | |
96 header->experiment = disk_cache::NO_EXPERIMENT; | |
97 return true; | |
98 } | |
99 | |
100 // A callback to perform final cleanup on the background thread. | |
101 void FinalCleanupCallback(disk_cache::BackendImpl* backend) { | |
102 backend->CleanupCache(); | |
103 } | |
104 | |
105 } // namespace | 75 } // namespace |
106 | 76 |
107 // ------------------------------------------------------------------------ | 77 // ------------------------------------------------------------------------ |
108 | 78 |
109 namespace disk_cache { | 79 namespace disk_cache { |
110 | 80 |
111 // Returns the preferred maximum number of bytes for the cache given the | |
112 // number of available bytes. | |
113 int PreferedCacheSize(int64 available) { | |
114 // Return 80% of the available space if there is not enough space to use | |
115 // kDefaultCacheSize. | |
116 if (available < kDefaultCacheSize * 10 / 8) | |
117 return static_cast<int32>(available * 8 / 10); | |
118 | |
119 // Return kDefaultCacheSize if it uses 80% to 10% of the available space. | |
120 if (available < kDefaultCacheSize * 10) | |
121 return kDefaultCacheSize; | |
122 | |
123 // Return 10% of the available space if the target size | |
124 // (2.5 * kDefaultCacheSize) is more than 10%. | |
125 if (available < static_cast<int64>(kDefaultCacheSize) * 25) | |
126 return static_cast<int32>(available / 10); | |
127 | |
128 // Return the target size (2.5 * kDefaultCacheSize) if it uses 10% to 1% | |
129 // of the available space. | |
130 if (available < static_cast<int64>(kDefaultCacheSize) * 250) | |
131 return kDefaultCacheSize * 5 / 2; | |
132 | |
133 // Return 1% of the available space if it does not exceed kint32max. | |
134 if (available < static_cast<int64>(kint32max) * 100) | |
135 return static_cast<int32>(available / 100); | |
136 | |
137 return kint32max; | |
138 } | |
139 | |
140 // ------------------------------------------------------------------------ | |
141 | |
142 BackendImpl::BackendImpl(const base::FilePath& path, | 81 BackendImpl::BackendImpl(const base::FilePath& path, |
143 base::MessageLoopProxy* cache_thread, | 82 base::MessageLoopProxy* cache_thread, |
144 net::NetLog* net_log) | 83 net::NetLog* net_log) |
145 : background_queue_(this, cache_thread), | 84 : background_queue_(this, cache_thread), |
146 path_(path), | 85 path_(path), |
147 block_files_(path), | 86 block_files_(path), |
148 mask_(0), | 87 mask_(0), |
149 max_size_(0), | 88 max_size_(0), |
150 up_ticks_(0), | 89 up_ticks_(0), |
151 cache_type_(net::DISK_CACHE), | 90 cache_type_(net::DISK_CACHE), |
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
211 base::ThreadRestrictions::ScopedAllowWait allow_wait; | 150 base::ThreadRestrictions::ScopedAllowWait allow_wait; |
212 done_.Wait(); | 151 done_.Wait(); |
213 } | 152 } |
214 } | 153 } |
215 | 154 |
216 int BackendImpl::Init(const CompletionCallback& callback) { | 155 int BackendImpl::Init(const CompletionCallback& callback) { |
217 background_queue_.Init(callback); | 156 background_queue_.Init(callback); |
218 return net::ERR_IO_PENDING; | 157 return net::ERR_IO_PENDING; |
219 } | 158 } |
220 | 159 |
221 int BackendImpl::SyncInit() { | |
222 #if defined(NET_BUILD_STRESS_CACHE) | |
223 // Start evictions right away. | |
224 up_ticks_ = kTrimDelay * 2; | |
225 #endif | |
226 DCHECK(!init_); | |
227 if (init_) | |
228 return net::ERR_FAILED; | |
229 | |
230 bool create_files = false; | |
231 if (!InitBackingStore(&create_files)) { | |
232 ReportError(ERR_STORAGE_ERROR); | |
233 return net::ERR_FAILED; | |
234 } | |
235 | |
236 num_refs_ = num_pending_io_ = max_refs_ = 0; | |
237 entry_count_ = byte_count_ = 0; | |
238 | |
239 if (!restarted_) { | |
240 buffer_bytes_ = 0; | |
241 trace_object_ = TraceObject::GetTraceObject(); | |
242 // Create a recurrent timer of 30 secs. | |
243 int timer_delay = unit_test_ ? 1000 : 30000; | |
244 timer_.reset(new base::RepeatingTimer<BackendImpl>()); | |
245 timer_->Start(FROM_HERE, TimeDelta::FromMilliseconds(timer_delay), this, | |
246 &BackendImpl::OnStatsTimer); | |
247 } | |
248 | |
249 init_ = true; | |
250 Trace("Init"); | |
251 | |
252 if (data_->header.experiment != NO_EXPERIMENT && | |
253 cache_type_ != net::DISK_CACHE) { | |
254 // No experiment for other caches. | |
255 return net::ERR_FAILED; | |
256 } | |
257 | |
258 if (!(user_flags_ & kNoRandom)) { | |
259 // The unit test controls directly what to test. | |
260 new_eviction_ = (cache_type_ == net::DISK_CACHE); | |
261 } | |
262 | |
263 if (!CheckIndex()) { | |
264 ReportError(ERR_INIT_FAILED); | |
265 return net::ERR_FAILED; | |
266 } | |
267 | |
268 if (!restarted_ && (create_files || !data_->header.num_entries)) | |
269 ReportError(ERR_CACHE_CREATED); | |
270 | |
271 if (!(user_flags_ & kNoRandom) && cache_type_ == net::DISK_CACHE && | |
272 !InitExperiment(&data_->header, create_files)) { | |
273 return net::ERR_FAILED; | |
274 } | |
275 | |
276 // We don't care if the value overflows. The only thing we care about is that | |
277 // the id cannot be zero, because that value is used as "not dirty". | |
278 // Increasing the value once per second gives us many years before we start | |
279 // having collisions. | |
280 data_->header.this_id++; | |
281 if (!data_->header.this_id) | |
282 data_->header.this_id++; | |
283 | |
284 bool previous_crash = (data_->header.crash != 0); | |
285 data_->header.crash = 1; | |
286 | |
287 if (!block_files_.Init(create_files)) | |
288 return net::ERR_FAILED; | |
289 | |
290 // We want to minimize the changes to cache for an AppCache. | |
291 if (cache_type() == net::APP_CACHE) { | |
292 DCHECK(!new_eviction_); | |
293 read_only_ = true; | |
294 } else if (cache_type() == net::SHADER_CACHE) { | |
295 DCHECK(!new_eviction_); | |
296 } | |
297 | |
298 eviction_.Init(this); | |
299 | |
300 // stats_ and rankings_ may end up calling back to us so we better be enabled. | |
301 disabled_ = false; | |
302 if (!InitStats()) | |
303 return net::ERR_FAILED; | |
304 | |
305 disabled_ = !rankings_.Init(this, new_eviction_); | |
306 | |
307 #if defined(STRESS_CACHE_EXTENDED_VALIDATION) | |
308 trace_object_->EnableTracing(false); | |
309 int sc = SelfCheck(); | |
310 if (sc < 0 && sc != ERR_NUM_ENTRIES_MISMATCH) | |
311 NOTREACHED(); | |
312 trace_object_->EnableTracing(true); | |
313 #endif | |
314 | |
315 if (previous_crash) { | |
316 ReportError(ERR_PREVIOUS_CRASH); | |
317 } else if (!restarted_) { | |
318 ReportError(ERR_NO_ERROR); | |
319 } | |
320 | |
321 FlushIndex(); | |
322 | |
323 return disabled_ ? net::ERR_FAILED : net::OK; | |
324 } | |
325 | |
326 void BackendImpl::CleanupCache() { | |
327 Trace("Backend Cleanup"); | |
328 eviction_.Stop(); | |
329 timer_.reset(); | |
330 | |
331 if (init_) { | |
332 StoreStats(); | |
333 if (data_) | |
334 data_->header.crash = 0; | |
335 | |
336 if (user_flags_ & kNoRandom) { | |
337 // This is a net_unittest, verify that we are not 'leaking' entries. | |
338 File::WaitForPendingIO(&num_pending_io_); | |
339 DCHECK(!num_refs_); | |
340 } else { | |
341 File::DropPendingIO(); | |
342 } | |
343 } | |
344 block_files_.CloseFiles(); | |
345 FlushIndex(); | |
346 index_ = NULL; | |
347 ptr_factory_.InvalidateWeakPtrs(); | |
348 done_.Signal(); | |
349 } | |
350 | |
351 // ------------------------------------------------------------------------ | 160 // ------------------------------------------------------------------------ |
352 | 161 |
353 int BackendImpl::OpenPrevEntry(void** iter, Entry** prev_entry, | 162 int BackendImpl::OpenPrevEntry(void** iter, Entry** prev_entry, |
354 const CompletionCallback& callback) { | 163 const CompletionCallback& callback) { |
355 DCHECK(!callback.is_null()); | 164 DCHECK(!callback.is_null()); |
356 background_queue_.OpenPrevEntry(iter, prev_entry, callback); | 165 background_queue_.OpenPrevEntry(iter, prev_entry, callback); |
357 return net::ERR_IO_PENDING; | 166 return net::ERR_IO_PENDING; |
358 } | 167 } |
359 | 168 |
360 int BackendImpl::SyncOpenEntry(const std::string& key, Entry** entry) { | |
361 DCHECK(entry); | |
362 *entry = OpenEntryImpl(key); | |
363 return (*entry) ? net::OK : net::ERR_FAILED; | |
364 } | |
365 | |
366 int BackendImpl::SyncCreateEntry(const std::string& key, Entry** entry) { | |
367 DCHECK(entry); | |
368 *entry = CreateEntryImpl(key); | |
369 return (*entry) ? net::OK : net::ERR_FAILED; | |
370 } | |
371 | |
372 int BackendImpl::SyncDoomEntry(const std::string& key) { | |
373 if (disabled_) | |
374 return net::ERR_FAILED; | |
375 | |
376 EntryImpl* entry = OpenEntryImpl(key); | |
377 if (!entry) | |
378 return net::ERR_FAILED; | |
379 | |
380 entry->DoomImpl(); | |
381 entry->Release(); | |
382 return net::OK; | |
383 } | |
384 | |
385 int BackendImpl::SyncDoomAllEntries() { | |
386 // This is not really an error, but it is an interesting condition. | |
387 ReportError(ERR_CACHE_DOOMED); | |
388 stats_.OnEvent(Stats::DOOM_CACHE); | |
389 if (!num_refs_) { | |
390 RestartCache(false); | |
391 return disabled_ ? net::ERR_FAILED : net::OK; | |
392 } else { | |
393 if (disabled_) | |
394 return net::ERR_FAILED; | |
395 | |
396 eviction_.TrimCache(true); | |
397 return net::OK; | |
398 } | |
399 } | |
400 | |
401 int BackendImpl::SyncDoomEntriesBetween(const base::Time initial_time, | |
402 const base::Time end_time) { | |
403 DCHECK_NE(net::APP_CACHE, cache_type_); | |
404 if (end_time.is_null()) | |
405 return SyncDoomEntriesSince(initial_time); | |
406 | |
407 DCHECK(end_time >= initial_time); | |
408 | |
409 if (disabled_) | |
410 return net::ERR_FAILED; | |
411 | |
412 EntryImpl* node; | |
413 void* iter = NULL; | |
414 EntryImpl* next = OpenNextEntryImpl(&iter); | |
415 if (!next) | |
416 return net::OK; | |
417 | |
418 while (next) { | |
419 node = next; | |
420 next = OpenNextEntryImpl(&iter); | |
421 | |
422 if (node->GetLastUsed() >= initial_time && | |
423 node->GetLastUsed() < end_time) { | |
424 node->DoomImpl(); | |
425 } else if (node->GetLastUsed() < initial_time) { | |
426 if (next) | |
427 next->Release(); | |
428 next = NULL; | |
429 SyncEndEnumeration(iter); | |
430 } | |
431 | |
432 node->Release(); | |
433 } | |
434 | |
435 return net::OK; | |
436 } | |
437 | |
438 // We use OpenNextEntryImpl to retrieve elements from the cache, until we get | |
439 // entries that are too old. | |
440 int BackendImpl::SyncDoomEntriesSince(const base::Time initial_time) { | |
441 DCHECK_NE(net::APP_CACHE, cache_type_); | |
442 if (disabled_) | |
443 return net::ERR_FAILED; | |
444 | |
445 stats_.OnEvent(Stats::DOOM_RECENT); | |
446 for (;;) { | |
447 void* iter = NULL; | |
448 EntryImpl* entry = OpenNextEntryImpl(&iter); | |
449 if (!entry) | |
450 return net::OK; | |
451 | |
452 if (initial_time > entry->GetLastUsed()) { | |
453 entry->Release(); | |
454 SyncEndEnumeration(iter); | |
455 return net::OK; | |
456 } | |
457 | |
458 entry->DoomImpl(); | |
459 entry->Release(); | |
460 SyncEndEnumeration(iter); // Dooming the entry invalidates the iterator. | |
461 } | |
462 } | |
463 | |
464 int BackendImpl::SyncOpenNextEntry(void** iter, Entry** next_entry) { | |
465 *next_entry = OpenNextEntryImpl(iter); | |
466 return (*next_entry) ? net::OK : net::ERR_FAILED; | |
467 } | |
468 | |
469 int BackendImpl::SyncOpenPrevEntry(void** iter, Entry** prev_entry) { | |
470 *prev_entry = OpenPrevEntryImpl(iter); | |
471 return (*prev_entry) ? net::OK : net::ERR_FAILED; | |
472 } | |
473 | |
474 void BackendImpl::SyncEndEnumeration(void* iter) { | |
475 scoped_ptr<Rankings::Iterator> iterator( | |
476 reinterpret_cast<Rankings::Iterator*>(iter)); | |
477 } | |
478 | |
479 void BackendImpl::SyncOnExternalCacheHit(const std::string& key) { | |
480 if (disabled_) | |
481 return; | |
482 | |
483 uint32 hash = base::Hash(key); | |
484 bool error; | |
485 EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error); | |
486 if (cache_entry) { | |
487 if (ENTRY_NORMAL == cache_entry->entry()->Data()->state) { | |
488 UpdateRank(cache_entry, cache_type() == net::SHADER_CACHE); | |
489 } | |
490 cache_entry->Release(); | |
491 } | |
492 } | |
493 | |
494 EntryImpl* BackendImpl::OpenEntryImpl(const std::string& key) { | |
495 if (disabled_) | |
496 return NULL; | |
497 | |
498 TimeTicks start = TimeTicks::Now(); | |
499 uint32 hash = base::Hash(key); | |
500 Trace("Open hash 0x%x", hash); | |
501 | |
502 bool error; | |
503 EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error); | |
504 if (cache_entry && ENTRY_NORMAL != cache_entry->entry()->Data()->state) { | |
505 // The entry was already evicted. | |
506 cache_entry->Release(); | |
507 cache_entry = NULL; | |
508 } | |
509 | |
510 int current_size = data_->header.num_bytes / (1024 * 1024); | |
511 int64 total_hours = stats_.GetCounter(Stats::TIMER) / 120; | |
512 int64 no_use_hours = stats_.GetCounter(Stats::LAST_REPORT_TIMER) / 120; | |
513 int64 use_hours = total_hours - no_use_hours; | |
514 | |
515 if (!cache_entry) { | |
516 CACHE_UMA(AGE_MS, "OpenTime.Miss", 0, start); | |
517 CACHE_UMA(COUNTS_10000, "AllOpenBySize.Miss", 0, current_size); | |
518 CACHE_UMA(HOURS, "AllOpenByTotalHours.Miss", 0, total_hours); | |
519 CACHE_UMA(HOURS, "AllOpenByUseHours.Miss", 0, use_hours); | |
520 stats_.OnEvent(Stats::OPEN_MISS); | |
521 return NULL; | |
522 } | |
523 | |
524 eviction_.OnOpenEntry(cache_entry); | |
525 entry_count_++; | |
526 | |
527 Trace("Open hash 0x%x end: 0x%x", hash, | |
528 cache_entry->entry()->address().value()); | |
529 CACHE_UMA(AGE_MS, "OpenTime", 0, start); | |
530 CACHE_UMA(COUNTS_10000, "AllOpenBySize.Hit", 0, current_size); | |
531 CACHE_UMA(HOURS, "AllOpenByTotalHours.Hit", 0, total_hours); | |
532 CACHE_UMA(HOURS, "AllOpenByUseHours.Hit", 0, use_hours); | |
533 stats_.OnEvent(Stats::OPEN_HIT); | |
534 SIMPLE_STATS_COUNTER("disk_cache.hit"); | |
535 return cache_entry; | |
536 } | |
537 | |
538 EntryImpl* BackendImpl::CreateEntryImpl(const std::string& key) { | |
539 if (disabled_ || key.empty()) | |
540 return NULL; | |
541 | |
542 TimeTicks start = TimeTicks::Now(); | |
543 uint32 hash = base::Hash(key); | |
544 Trace("Create hash 0x%x", hash); | |
545 | |
546 scoped_refptr<EntryImpl> parent; | |
547 Addr entry_address(data_->table[hash & mask_]); | |
548 if (entry_address.is_initialized()) { | |
549 // We have an entry already. It could be the one we are looking for, or just | |
550 // a hash conflict. | |
551 bool error; | |
552 EntryImpl* old_entry = MatchEntry(key, hash, false, Addr(), &error); | |
553 if (old_entry) | |
554 return ResurrectEntry(old_entry); | |
555 | |
556 EntryImpl* parent_entry = MatchEntry(key, hash, true, Addr(), &error); | |
557 DCHECK(!error); | |
558 if (parent_entry) { | |
559 parent.swap(&parent_entry); | |
560 } else if (data_->table[hash & mask_]) { | |
561 // We should have corrected the problem. | |
562 NOTREACHED(); | |
563 return NULL; | |
564 } | |
565 } | |
566 | |
567 // The general flow is to allocate disk space and initialize the entry data, | |
568 // followed by saving that to disk, then linking the entry though the index | |
569 // and finally through the lists. If there is a crash in this process, we may | |
570 // end up with: | |
571 // a. Used, unreferenced empty blocks on disk (basically just garbage). | |
572 // b. Used, unreferenced but meaningful data on disk (more garbage). | |
573 // c. A fully formed entry, reachable only through the index. | |
574 // d. A fully formed entry, also reachable through the lists, but still dirty. | |
575 // | |
576 // Anything after (b) can be automatically cleaned up. We may consider saving | |
577 // the current operation (as we do while manipulating the lists) so that we | |
578 // can detect and cleanup (a) and (b). | |
579 | |
580 int num_blocks = EntryImpl::NumBlocksForEntry(key.size()); | |
581 if (!block_files_.CreateBlock(BLOCK_256, num_blocks, &entry_address)) { | |
582 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
583 stats_.OnEvent(Stats::CREATE_ERROR); | |
584 return NULL; | |
585 } | |
586 | |
587 Addr node_address(0); | |
588 if (!block_files_.CreateBlock(RANKINGS, 1, &node_address)) { | |
589 block_files_.DeleteBlock(entry_address, false); | |
590 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
591 stats_.OnEvent(Stats::CREATE_ERROR); | |
592 return NULL; | |
593 } | |
594 | |
595 scoped_refptr<EntryImpl> cache_entry( | |
596 new EntryImpl(this, entry_address, false)); | |
597 IncreaseNumRefs(); | |
598 | |
599 if (!cache_entry->CreateEntry(node_address, key, hash)) { | |
600 block_files_.DeleteBlock(entry_address, false); | |
601 block_files_.DeleteBlock(node_address, false); | |
602 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
603 stats_.OnEvent(Stats::CREATE_ERROR); | |
604 return NULL; | |
605 } | |
606 | |
607 cache_entry->BeginLogging(net_log_, true); | |
608 | |
609 // We are not failing the operation; let's add this to the map. | |
610 open_entries_[entry_address.value()] = cache_entry; | |
611 | |
612 // Save the entry. | |
613 cache_entry->entry()->Store(); | |
614 cache_entry->rankings()->Store(); | |
615 IncreaseNumEntries(); | |
616 entry_count_++; | |
617 | |
618 // Link this entry through the index. | |
619 if (parent.get()) { | |
620 parent->SetNextAddress(entry_address); | |
621 } else { | |
622 data_->table[hash & mask_] = entry_address.value(); | |
623 } | |
624 | |
625 // Link this entry through the lists. | |
626 eviction_.OnCreateEntry(cache_entry); | |
627 | |
628 CACHE_UMA(AGE_MS, "CreateTime", 0, start); | |
629 stats_.OnEvent(Stats::CREATE_HIT); | |
630 SIMPLE_STATS_COUNTER("disk_cache.miss"); | |
631 Trace("create entry hit "); | |
632 FlushIndex(); | |
633 cache_entry->AddRef(); | |
634 return cache_entry.get(); | |
635 } | |
636 | |
637 EntryImpl* BackendImpl::OpenNextEntryImpl(void** iter) { | |
638 return OpenFollowingEntry(true, iter); | |
639 } | |
640 | |
641 EntryImpl* BackendImpl::OpenPrevEntryImpl(void** iter) { | |
642 return OpenFollowingEntry(false, iter); | |
643 } | |
644 | |
645 bool BackendImpl::SetMaxSize(int max_bytes) { | 169 bool BackendImpl::SetMaxSize(int max_bytes) { |
646 COMPILE_ASSERT(sizeof(max_bytes) == sizeof(max_size_), unsupported_int_model); | 170 COMPILE_ASSERT(sizeof(max_bytes) == sizeof(max_size_), unsupported_int_model); |
647 if (max_bytes < 0) | 171 if (max_bytes < 0) |
648 return false; | 172 return false; |
649 | 173 |
650 // Zero size means use the default. | 174 // Zero size means use the default. |
651 if (!max_bytes) | 175 if (!max_bytes) |
652 return true; | 176 return true; |
653 | 177 |
654 // Avoid a DCHECK later on. | 178 // Avoid a DCHECK later on. |
655 if (max_bytes >= kint32max - kint32max / 10) | 179 if (max_bytes >= kint32max - kint32max / 10) |
656 max_bytes = kint32max - kint32max / 10 - 1; | 180 max_bytes = kint32max - kint32max / 10 - 1; |
657 | 181 |
658 user_flags_ |= kMaxSize; | 182 user_flags_ |= kMaxSize; |
659 max_size_ = max_bytes; | 183 max_size_ = max_bytes; |
660 return true; | 184 return true; |
661 } | 185 } |
662 | 186 |
663 void BackendImpl::SetType(net::CacheType type) { | 187 void BackendImpl::SetType(net::CacheType type) { |
664 DCHECK_NE(net::MEMORY_CACHE, type); | 188 DCHECK_NE(net::MEMORY_CACHE, type); |
665 cache_type_ = type; | 189 cache_type_ = type; |
666 } | 190 } |
667 | 191 |
668 base::FilePath BackendImpl::GetFileName(Addr address) const { | |
669 if (!address.is_separate_file() || !address.is_initialized()) { | |
670 NOTREACHED(); | |
671 return base::FilePath(); | |
672 } | |
673 | |
674 std::string tmp = base::StringPrintf("f_%06x", address.FileNumber()); | |
675 return path_.AppendASCII(tmp); | |
676 } | |
677 | |
678 MappedFile* BackendImpl::File(Addr address) { | |
679 if (disabled_) | |
680 return NULL; | |
681 return block_files_.GetFile(address); | |
682 } | |
683 | |
684 base::WeakPtr<InFlightBackendIO> BackendImpl::GetBackgroundQueue() { | |
685 return background_queue_.GetWeakPtr(); | |
686 } | |
687 | |
688 bool BackendImpl::CreateExternalFile(Addr* address) { | |
689 int file_number = data_->header.last_file + 1; | |
690 Addr file_address(0); | |
691 bool success = false; | |
692 for (int i = 0; i < 0x0fffffff; i++, file_number++) { | |
693 if (!file_address.SetFileNumber(file_number)) { | |
694 file_number = 1; | |
695 continue; | |
696 } | |
697 base::FilePath name = GetFileName(file_address); | |
698 int flags = base::PLATFORM_FILE_READ | | |
699 base::PLATFORM_FILE_WRITE | | |
700 base::PLATFORM_FILE_CREATE | | |
701 base::PLATFORM_FILE_EXCLUSIVE_WRITE; | |
702 base::PlatformFileError error; | |
703 scoped_refptr<disk_cache::File> file(new disk_cache::File( | |
704 base::CreatePlatformFile(name, flags, NULL, &error))); | |
705 if (!file->IsValid()) { | |
706 if (error != base::PLATFORM_FILE_ERROR_EXISTS) { | |
707 LOG(ERROR) << "Unable to create file: " << error; | |
708 return false; | |
709 } | |
710 continue; | |
711 } | |
712 | |
713 success = true; | |
714 break; | |
715 } | |
716 | |
717 DCHECK(success); | |
718 if (!success) | |
719 return false; | |
720 | |
721 data_->header.last_file = file_number; | |
722 address->set_value(file_address.value()); | |
723 return true; | |
724 } | |
725 | |
726 bool BackendImpl::CreateBlock(FileType block_type, int block_count, | 192 bool BackendImpl::CreateBlock(FileType block_type, int block_count, |
727 Addr* block_address) { | 193 Addr* block_address) { |
728 return block_files_.CreateBlock(block_type, block_count, block_address); | 194 return block_files_.CreateBlock(block_type, block_count, block_address); |
729 } | 195 } |
730 | 196 |
731 void BackendImpl::DeleteBlock(Addr block_address, bool deep) { | |
732 block_files_.DeleteBlock(block_address, deep); | |
733 } | |
734 | |
735 LruData* BackendImpl::GetLruData() { | |
736 return &data_->header.lru; | |
737 } | |
738 | |
739 void BackendImpl::UpdateRank(EntryImpl* entry, bool modified) { | 197 void BackendImpl::UpdateRank(EntryImpl* entry, bool modified) { |
740 if (read_only_ || (!modified && cache_type() == net::SHADER_CACHE)) | 198 if (read_only_ || (!modified && cache_type() == net::SHADER_CACHE)) |
741 return; | 199 return; |
742 eviction_.UpdateRank(entry, modified); | 200 eviction_.UpdateRank(entry, modified); |
743 } | 201 } |
744 | 202 |
745 void BackendImpl::RecoveredEntry(CacheRankingsBlock* rankings) { | |
746 Addr address(rankings->Data()->contents); | |
747 EntryImpl* cache_entry = NULL; | |
748 if (NewEntry(address, &cache_entry)) { | |
749 STRESS_NOTREACHED(); | |
750 return; | |
751 } | |
752 | |
753 uint32 hash = cache_entry->GetHash(); | |
754 cache_entry->Release(); | |
755 | |
756 // Anything on the table means that this entry is there. | |
757 if (data_->table[hash & mask_]) | |
758 return; | |
759 | |
760 data_->table[hash & mask_] = address.value(); | |
761 FlushIndex(); | |
762 } | |
763 | |
764 void BackendImpl::InternalDoomEntry(EntryImpl* entry) { | 203 void BackendImpl::InternalDoomEntry(EntryImpl* entry) { |
765 uint32 hash = entry->GetHash(); | 204 uint32 hash = entry->GetHash(); |
766 std::string key = entry->GetKey(); | 205 std::string key = entry->GetKey(); |
767 Addr entry_addr = entry->entry()->address(); | 206 Addr entry_addr = entry->entry()->address(); |
768 bool error; | 207 bool error; |
769 EntryImpl* parent_entry = MatchEntry(key, hash, true, entry_addr, &error); | 208 EntryImpl* parent_entry = MatchEntry(key, hash, true, entry_addr, &error); |
770 CacheAddr child(entry->GetNextAddress()); | 209 CacheAddr child(entry->GetNextAddress()); |
771 | 210 |
772 Trace("Doom entry 0x%p", entry); | 211 Trace("Doom entry 0x%p", entry); |
773 | 212 |
(...skipping 10 matching lines...) Expand all Loading... | |
784 if (parent_entry) { | 223 if (parent_entry) { |
785 parent_entry->SetNextAddress(Addr(child)); | 224 parent_entry->SetNextAddress(Addr(child)); |
786 parent_entry->Release(); | 225 parent_entry->Release(); |
787 } else if (!error) { | 226 } else if (!error) { |
788 data_->table[hash & mask_] = child; | 227 data_->table[hash & mask_] = child; |
789 } | 228 } |
790 | 229 |
791 FlushIndex(); | 230 FlushIndex(); |
792 } | 231 } |
793 | 232 |
794 #if defined(NET_BUILD_STRESS_CACHE) | |
795 | |
796 CacheAddr BackendImpl::GetNextAddr(Addr address) { | |
797 EntriesMap::iterator it = open_entries_.find(address.value()); | |
798 if (it != open_entries_.end()) { | |
799 EntryImpl* this_entry = it->second; | |
800 return this_entry->GetNextAddress(); | |
801 } | |
802 DCHECK(block_files_.IsValid(address)); | |
803 DCHECK(!address.is_separate_file() && address.file_type() == BLOCK_256); | |
804 | |
805 CacheEntryBlock entry(File(address), address); | |
806 CHECK(entry.Load()); | |
807 return entry.Data()->next; | |
808 } | |
809 | |
810 void BackendImpl::NotLinked(EntryImpl* entry) { | |
811 Addr entry_addr = entry->entry()->address(); | |
812 uint32 i = entry->GetHash() & mask_; | |
813 Addr address(data_->table[i]); | |
814 if (!address.is_initialized()) | |
815 return; | |
816 | |
817 for (;;) { | |
818 DCHECK(entry_addr.value() != address.value()); | |
819 address.set_value(GetNextAddr(address)); | |
820 if (!address.is_initialized()) | |
821 break; | |
822 } | |
823 } | |
824 #endif // NET_BUILD_STRESS_CACHE | |
825 | |
826 // An entry may be linked on the DELETED list for a while after being doomed. | |
827 // This function is called when we want to remove it. | |
828 void BackendImpl::RemoveEntry(EntryImpl* entry) { | |
829 #if defined(NET_BUILD_STRESS_CACHE) | |
830 NotLinked(entry); | |
831 #endif | |
832 if (!new_eviction_) | |
833 return; | |
834 | |
835 DCHECK_NE(ENTRY_NORMAL, entry->entry()->Data()->state); | |
836 | |
837 Trace("Remove entry 0x%p", entry); | |
838 eviction_.OnDestroyEntry(entry); | |
839 DecreaseNumEntries(); | |
840 } | |
841 | |
842 void BackendImpl::OnEntryDestroyBegin(Addr address) { | 233 void BackendImpl::OnEntryDestroyBegin(Addr address) { |
843 EntriesMap::iterator it = open_entries_.find(address.value()); | 234 EntriesMap::iterator it = open_entries_.find(address.value()); |
844 if (it != open_entries_.end()) | 235 if (it != open_entries_.end()) |
845 open_entries_.erase(it); | 236 open_entries_.erase(it); |
846 } | 237 } |
847 | 238 |
848 void BackendImpl::OnEntryDestroyEnd() { | 239 void BackendImpl::OnEntryDestroyEnd() { |
849 DecreaseNumRefs(); | 240 DecreaseNumRefs(); |
850 if (data_->header.num_bytes > max_size_ && !read_only_ && | 241 if (data_->header.num_bytes > max_size_ && !read_only_ && |
851 (up_ticks_ > kTrimDelay || user_flags_ & kNoRandom)) | 242 (up_ticks_ > kTrimDelay || user_flags_ & kNoRandom)) |
852 eviction_.TrimCache(false); | 243 eviction_.TrimCache(false); |
853 } | 244 } |
854 | 245 |
855 EntryImpl* BackendImpl::GetOpenEntry(CacheRankingsBlock* rankings) const { | 246 EntryImpl* BackendImpl::GetOpenEntry(CacheRankingsBlock* rankings) const { |
856 DCHECK(rankings->HasData()); | 247 DCHECK(rankings->HasData()); |
857 EntriesMap::const_iterator it = | 248 EntriesMap::const_iterator it = |
858 open_entries_.find(rankings->Data()->contents); | 249 open_entries_.find(rankings->Data()->contents); |
859 if (it != open_entries_.end()) { | 250 if (it != open_entries_.end()) { |
860 // We have this entry in memory. | 251 // We have this entry in memory. |
861 return it->second; | 252 return it->second; |
862 } | 253 } |
863 | 254 |
864 return NULL; | 255 return NULL; |
865 } | 256 } |
866 | 257 |
867 int32 BackendImpl::GetCurrentEntryId() const { | |
868 return data_->header.this_id; | |
869 } | |
870 | |
871 int BackendImpl::MaxFileSize() const { | 258 int BackendImpl::MaxFileSize() const { |
872 return max_size_ / 8; | 259 return max_size_ / 8; |
873 } | 260 } |
874 | 261 |
875 void BackendImpl::ModifyStorageSize(int32 old_size, int32 new_size) { | 262 void BackendImpl::ModifyStorageSize(int32 old_size, int32 new_size) { |
876 if (disabled_ || old_size == new_size) | 263 if (disabled_ || old_size == new_size) |
877 return; | 264 return; |
878 if (old_size > new_size) | 265 if (old_size > new_size) |
879 SubstractStorageSize(old_size - new_size); | 266 SubstractStorageSize(old_size - new_size); |
880 else | 267 else |
(...skipping 96 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
977 data_->header.lru.sizes[0] * 100 / data_->header.num_entries); | 364 data_->header.lru.sizes[0] * 100 / data_->header.num_entries); |
978 CACHE_UMA(PERCENTAGE, "FirstLowUseRatio", 0, | 365 CACHE_UMA(PERCENTAGE, "FirstLowUseRatio", 0, |
979 data_->header.lru.sizes[1] * 100 / data_->header.num_entries); | 366 data_->header.lru.sizes[1] * 100 / data_->header.num_entries); |
980 CACHE_UMA(PERCENTAGE, "FirstHighUseRatio", 0, | 367 CACHE_UMA(PERCENTAGE, "FirstHighUseRatio", 0, |
981 data_->header.lru.sizes[2] * 100 / data_->header.num_entries); | 368 data_->header.lru.sizes[2] * 100 / data_->header.num_entries); |
982 } | 369 } |
983 | 370 |
984 stats_.ResetRatios(); | 371 stats_.ResetRatios(); |
985 } | 372 } |
986 | 373 |
987 void BackendImpl::CriticalError(int error) { | |
988 STRESS_NOTREACHED(); | |
989 LOG(ERROR) << "Critical error found " << error; | |
990 if (disabled_) | |
991 return; | |
992 | |
993 stats_.OnEvent(Stats::FATAL_ERROR); | |
994 LogStats(); | |
995 ReportError(error); | |
996 | |
997 // Setting the index table length to an invalid value will force re-creation | |
998 // of the cache files. | |
999 data_->header.table_len = 1; | |
1000 disabled_ = true; | |
1001 | |
1002 if (!num_refs_) | |
1003 base::MessageLoop::current()->PostTask( | |
1004 FROM_HERE, base::Bind(&BackendImpl::RestartCache, GetWeakPtr(), true)); | |
1005 } | |
1006 | |
1007 void BackendImpl::ReportError(int error) { | |
1008 STRESS_DCHECK(!error || error == ERR_PREVIOUS_CRASH || | |
1009 error == ERR_CACHE_CREATED); | |
1010 | |
1011 // We transmit positive numbers, instead of direct error codes. | |
1012 DCHECK_LE(error, 0); | |
1013 CACHE_UMA(CACHE_ERROR, "Error", 0, error * -1); | |
1014 } | |
1015 | |
1016 void BackendImpl::OnEvent(Stats::Counters an_event) { | 374 void BackendImpl::OnEvent(Stats::Counters an_event) { |
1017 stats_.OnEvent(an_event); | 375 stats_.OnEvent(an_event); |
1018 } | 376 } |
1019 | 377 |
1020 void BackendImpl::OnRead(int32 bytes) { | 378 void BackendImpl::OnRead(int32 bytes) { |
1021 DCHECK_GE(bytes, 0); | 379 DCHECK_GE(bytes, 0); |
1022 byte_count_ += bytes; | 380 byte_count_ += bytes; |
1023 if (byte_count_ < 0) | 381 if (byte_count_ < 0) |
1024 byte_count_ = kint32max; | 382 byte_count_ = kint32max; |
1025 } | 383 } |
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1062 first_timer_ = false; | 420 first_timer_ = false; |
1063 if (ShouldReportAgain()) | 421 if (ShouldReportAgain()) |
1064 ReportStats(); | 422 ReportStats(); |
1065 } | 423 } |
1066 | 424 |
1067 // Save stats to disk at 5 min intervals. | 425 // Save stats to disk at 5 min intervals. |
1068 if (time % 10 == 0) | 426 if (time % 10 == 0) |
1069 StoreStats(); | 427 StoreStats(); |
1070 } | 428 } |
1071 | 429 |
1072 void BackendImpl::IncrementIoCount() { | |
1073 num_pending_io_++; | |
1074 } | |
1075 | |
1076 void BackendImpl::DecrementIoCount() { | |
1077 num_pending_io_--; | |
1078 } | |
1079 | |
1080 void BackendImpl::SetUnitTestMode() { | 430 void BackendImpl::SetUnitTestMode() { |
1081 user_flags_ |= kUnitTestMode; | 431 user_flags_ |= kUnitTestMode; |
1082 unit_test_ = true; | 432 unit_test_ = true; |
1083 } | 433 } |
1084 | 434 |
1085 void BackendImpl::SetUpgradeMode() { | 435 void BackendImpl::SetUpgradeMode() { |
1086 user_flags_ |= kUpgradeMode; | 436 user_flags_ |= kUpgradeMode; |
1087 read_only_ = true; | 437 read_only_ = true; |
1088 } | 438 } |
1089 | 439 |
1090 void BackendImpl::SetNewEviction() { | 440 void BackendImpl::SetNewEviction() { |
1091 user_flags_ |= kNewEviction; | 441 user_flags_ |= kNewEviction; |
1092 new_eviction_ = true; | 442 new_eviction_ = true; |
1093 } | 443 } |
1094 | 444 |
1095 void BackendImpl::SetFlags(uint32 flags) { | 445 void BackendImpl::SetFlags(uint32 flags) { |
1096 user_flags_ |= flags; | 446 user_flags_ |= flags; |
1097 } | 447 } |
1098 | 448 |
1099 void BackendImpl::ClearRefCountForTest() { | |
1100 num_refs_ = 0; | |
1101 } | |
1102 | |
1103 int BackendImpl::FlushQueueForTest(const CompletionCallback& callback) { | 449 int BackendImpl::FlushQueueForTest(const CompletionCallback& callback) { |
1104 background_queue_.FlushQueue(callback); | 450 background_queue_.FlushQueue(callback); |
1105 return net::ERR_IO_PENDING; | 451 return net::ERR_IO_PENDING; |
1106 } | 452 } |
1107 | 453 |
1108 int BackendImpl::RunTaskForTest(const base::Closure& task, | |
1109 const CompletionCallback& callback) { | |
1110 background_queue_.RunTask(task, callback); | |
1111 return net::ERR_IO_PENDING; | |
1112 } | |
1113 | |
1114 void BackendImpl::TrimForTest(bool empty) { | 454 void BackendImpl::TrimForTest(bool empty) { |
1115 eviction_.SetTestMode(); | 455 eviction_.SetTestMode(); |
1116 eviction_.TrimCache(empty); | 456 eviction_.TrimCache(empty); |
1117 } | 457 } |
1118 | 458 |
1119 void BackendImpl::TrimDeletedListForTest(bool empty) { | 459 void BackendImpl::TrimDeletedListForTest(bool empty) { |
1120 eviction_.SetTestMode(); | 460 eviction_.SetTestMode(); |
1121 eviction_.TrimDeletedList(empty); | 461 eviction_.TrimDeletedList(empty); |
1122 } | 462 } |
1123 | 463 |
(...skipping 14 matching lines...) Expand all Loading... | |
1138 if (num_entries != data_->header.num_entries) { | 478 if (num_entries != data_->header.num_entries) { |
1139 LOG(ERROR) << "Number of entries mismatch"; | 479 LOG(ERROR) << "Number of entries mismatch"; |
1140 #if !defined(NET_BUILD_STRESS_CACHE) | 480 #if !defined(NET_BUILD_STRESS_CACHE) |
1141 return ERR_NUM_ENTRIES_MISMATCH; | 481 return ERR_NUM_ENTRIES_MISMATCH; |
1142 #endif | 482 #endif |
1143 } | 483 } |
1144 | 484 |
1145 return CheckAllEntries(); | 485 return CheckAllEntries(); |
1146 } | 486 } |
1147 | 487 |
1148 void BackendImpl::FlushIndex() { | |
1149 if (index_ && !disabled_) | |
1150 index_->Flush(); | |
1151 } | |
1152 | |
1153 // ------------------------------------------------------------------------ | 488 // ------------------------------------------------------------------------ |
1154 | 489 |
1155 net::CacheType BackendImpl::GetCacheType() const { | 490 net::CacheType BackendImpl::GetCacheType() const { |
1156 return cache_type_; | 491 return cache_type_; |
1157 } | 492 } |
1158 | 493 |
1159 int32 BackendImpl::GetEntryCount() const { | 494 int32 BackendImpl::GetEntryCount() const { |
1160 if (!index_ || disabled_) | 495 if (!index_ || disabled_) |
1161 return 0; | 496 return 0; |
1162 // num_entries includes entries already evicted. | 497 // num_entries includes entries already evicted. |
1163 int32 not_deleted = data_->header.num_entries - | 498 int32 not_deleted = data_->header.num_entries - |
1164 data_->header.lru.sizes[Rankings::DELETED]; | 499 data_->header.lru.sizes[Rankings::DELETED]; |
1165 | 500 |
1166 if (not_deleted < 0) { | 501 if (not_deleted < 0) { |
1167 NOTREACHED(); | 502 NOTREACHED(); |
1168 not_deleted = 0; | 503 not_deleted = 0; |
1169 } | 504 } |
1170 | 505 |
1171 return not_deleted; | 506 return not_deleted; |
1172 } | 507 } |
1173 | 508 |
1174 int BackendImpl::OpenEntry(const std::string& key, Entry** entry, | 509 EntryImpl* BackendImpl::OpenEntryImpl(const std::string& key) { |
gavinp
2013/06/04 17:02:30
No method by this name exists in the header; I kno
rvargas (doing something else)
2013/06/04 17:31:13
Because otherwise I would be violating the premise
| |
1175 const CompletionCallback& callback) { | 510 if (disabled_) |
1176 DCHECK(!callback.is_null()); | 511 return NULL; |
1177 background_queue_.OpenEntry(key, entry, callback); | 512 |
1178 return net::ERR_IO_PENDING; | 513 TimeTicks start = TimeTicks::Now(); |
1179 } | 514 uint32 hash = base::Hash(key); |
1180 | 515 Trace("Open hash 0x%x", hash); |
1181 int BackendImpl::CreateEntry(const std::string& key, Entry** entry, | 516 |
1182 const CompletionCallback& callback) { | 517 bool error; |
1183 DCHECK(!callback.is_null()); | 518 EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error); |
1184 background_queue_.CreateEntry(key, entry, callback); | 519 if (cache_entry && ENTRY_NORMAL != cache_entry->entry()->Data()->state) { |
1185 return net::ERR_IO_PENDING; | 520 // The entry was already evicted. |
1186 } | 521 cache_entry->Release(); |
1187 | 522 cache_entry = NULL; |
1188 int BackendImpl::DoomEntry(const std::string& key, | 523 } |
1189 const CompletionCallback& callback) { | 524 |
1190 DCHECK(!callback.is_null()); | 525 int current_size = data_->header.num_bytes / (1024 * 1024); |
1191 background_queue_.DoomEntry(key, callback); | 526 int64 total_hours = stats_.GetCounter(Stats::TIMER) / 120; |
1192 return net::ERR_IO_PENDING; | 527 int64 no_use_hours = stats_.GetCounter(Stats::LAST_REPORT_TIMER) / 120; |
1193 } | 528 int64 use_hours = total_hours - no_use_hours; |
1194 | 529 |
1195 int BackendImpl::DoomAllEntries(const CompletionCallback& callback) { | 530 if (!cache_entry) { |
1196 DCHECK(!callback.is_null()); | 531 CACHE_UMA(AGE_MS, "OpenTime.Miss", 0, start); |
1197 background_queue_.DoomAllEntries(callback); | 532 CACHE_UMA(COUNTS_10000, "AllOpenBySize.Miss", 0, current_size); |
1198 return net::ERR_IO_PENDING; | 533 CACHE_UMA(HOURS, "AllOpenByTotalHours.Miss", 0, total_hours); |
1199 } | 534 CACHE_UMA(HOURS, "AllOpenByUseHours.Miss", 0, use_hours); |
1200 | 535 stats_.OnEvent(Stats::OPEN_MISS); |
1201 int BackendImpl::DoomEntriesBetween(const base::Time initial_time, | 536 return NULL; |
1202 const base::Time end_time, | 537 } |
1203 const CompletionCallback& callback) { | 538 |
1204 DCHECK(!callback.is_null()); | 539 eviction_.OnOpenEntry(cache_entry); |
1205 background_queue_.DoomEntriesBetween(initial_time, end_time, callback); | 540 entry_count_++; |
1206 return net::ERR_IO_PENDING; | 541 |
1207 } | 542 Trace("Open hash 0x%x end: 0x%x", hash, |
1208 | 543 cache_entry->entry()->address().value()); |
1209 int BackendImpl::DoomEntriesSince(const base::Time initial_time, | 544 CACHE_UMA(AGE_MS, "OpenTime", 0, start); |
1210 const CompletionCallback& callback) { | 545 CACHE_UMA(COUNTS_10000, "AllOpenBySize.Hit", 0, current_size); |
1211 DCHECK(!callback.is_null()); | 546 CACHE_UMA(HOURS, "AllOpenByTotalHours.Hit", 0, total_hours); |
1212 background_queue_.DoomEntriesSince(initial_time, callback); | 547 CACHE_UMA(HOURS, "AllOpenByUseHours.Hit", 0, use_hours); |
1213 return net::ERR_IO_PENDING; | 548 stats_.OnEvent(Stats::OPEN_HIT); |
549 SIMPLE_STATS_COUNTER("disk_cache.hit"); | |
550 return cache_entry; | |
551 } | |
552 | |
553 EntryImpl* BackendImpl::CreateEntryImpl(const std::string& key) { | |
554 if (disabled_ || key.empty()) | |
555 return NULL; | |
556 | |
557 TimeTicks start = TimeTicks::Now(); | |
558 Trace("Create hash 0x%x", hash); | |
559 | |
560 scoped_refptr<EntryImpl> parent; | |
561 Addr entry_address(data_->table[hash & mask_]); | |
562 if (entry_address.is_initialized()) { | |
563 // We have an entry already. It could be the one we are looking for, or just | |
564 // a hash conflict. | |
565 bool error; | |
566 EntryImpl* old_entry = MatchEntry(key, hash, false, Addr(), &error); | |
567 if (old_entry) | |
568 return ResurrectEntry(old_entry); | |
569 | |
570 EntryImpl* parent_entry = MatchEntry(key, hash, true, Addr(), &error); | |
571 DCHECK(!error); | |
572 if (parent_entry) { | |
573 parent.swap(&parent_entry); | |
574 } else if (data_->table[hash & mask_]) { | |
575 // We should have corrected the problem. | |
576 NOTREACHED(); | |
577 return NULL; | |
578 } | |
579 } | |
580 | |
581 // The general flow is to allocate disk space and initialize the entry data, | |
582 // followed by saving that to disk, then linking the entry though the index | |
583 // and finally through the lists. If there is a crash in this process, we may | |
584 // end up with: | |
585 // a. Used, unreferenced empty blocks on disk (basically just garbage). | |
586 // b. Used, unreferenced but meaningful data on disk (more garbage). | |
587 // c. A fully formed entry, reachable only through the index. | |
588 // d. A fully formed entry, also reachable through the lists, but still dirty. | |
589 // | |
590 // Anything after (b) can be automatically cleaned up. We may consider saving | |
591 // the current operation (as we do while manipulating the lists) so that we | |
592 // can detect and cleanup (a) and (b). | |
593 | |
594 int num_blocks = EntryImpl::NumBlocksForEntry(key.size()); | |
595 if (!block_files_.CreateBlock(BLOCK_256, num_blocks, &entry_address)) { | |
596 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
597 stats_.OnEvent(Stats::CREATE_ERROR); | |
598 return NULL; | |
599 } | |
600 | |
601 Addr node_address(0); | |
602 if (!block_files_.CreateBlock(RANKINGS, 1, &node_address)) { | |
603 block_files_.DeleteBlock(entry_address, false); | |
604 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
605 stats_.OnEvent(Stats::CREATE_ERROR); | |
606 return NULL; | |
607 } | |
608 | |
609 scoped_refptr<EntryImpl> cache_entry( | |
610 new EntryImpl(this, entry_address, false)); | |
611 IncreaseNumRefs(); | |
612 | |
613 if (!cache_entry->CreateEntry(node_address, key, hash)) { | |
614 block_files_.DeleteBlock(entry_address, false); | |
615 block_files_.DeleteBlock(node_address, false); | |
616 LOG(ERROR) << "Create entry failed " << key.c_str(); | |
617 stats_.OnEvent(Stats::CREATE_ERROR); | |
618 return NULL; | |
619 } | |
620 | |
621 cache_entry->BeginLogging(net_log_, true); | |
622 | |
623 // We are not failing the operation; let's add this to the map. | |
624 open_entries_[entry_address.value()] = cache_entry; | |
625 | |
626 // Save the entry. | |
627 cache_entry->entry()->Store(); | |
628 cache_entry->rankings()->Store(); | |
629 IncreaseNumEntries(); | |
630 entry_count_++; | |
631 | |
632 // Link this entry through the index. | |
633 if (parent.get()) { | |
634 parent->SetNextAddress(entry_address); | |
635 } else { | |
636 data_->table[hash & mask_] = entry_address.value(); | |
637 } | |
638 | |
639 // Link this entry through the lists. | |
640 eviction_.OnCreateEntry(cache_entry); | |
641 | |
642 CACHE_UMA(AGE_MS, "CreateTime", 0, start); | |
643 stats_.OnEvent(Stats::CREATE_HIT); | |
644 SIMPLE_STATS_COUNTER("disk_cache.miss"); | |
645 Trace("create entry hit "); | |
646 FlushIndex(); | |
647 cache_entry->AddRef(); | |
648 return cache_entry.get(); | |
649 } | |
650 | |
651 int BackendImpl::SyncDoomEntry(const std::string& key) { | |
652 if (disabled_) | |
653 return net::ERR_FAILED; | |
654 | |
655 EntryImpl* entry = OpenEntryImpl(key); | |
656 if (!entry) | |
657 return net::ERR_FAILED; | |
658 | |
659 entry->DoomImpl(); | |
660 entry->Release(); | |
661 return net::OK; | |
662 } | |
663 | |
664 int BackendImpl::SyncDoomAllEntries() { | |
665 // This is not really an error, but it is an interesting condition. | |
666 ReportError(ERR_CACHE_DOOMED); | |
667 stats_.OnEvent(Stats::DOOM_CACHE); | |
668 if (!num_refs_) { | |
669 RestartCache(false); | |
670 return disabled_ ? net::ERR_FAILED : net::OK; | |
671 } else { | |
672 if (disabled_) | |
673 return net::ERR_FAILED; | |
674 | |
675 eviction_.TrimCache(true); | |
676 return net::OK; | |
677 } | |
678 } | |
679 | |
680 int BackendImpl::SyncDoomEntriesBetween(const base::Time initial_time, | |
681 const base::Time end_time) { | |
682 DCHECK_NE(net::APP_CACHE, cache_type_); | |
683 if (end_time.is_null()) | |
684 return SyncDoomEntriesSince(initial_time); | |
685 | |
686 DCHECK(end_time >= initial_time); | |
687 | |
688 if (disabled_) | |
689 return net::ERR_FAILED; | |
690 | |
691 EntryImpl* node; | |
692 void* iter = NULL; | |
693 EntryImpl* next = OpenNextEntryImpl(&iter); | |
694 if (!next) | |
695 return net::OK; | |
696 | |
697 while (next) { | |
698 node = next; | |
699 next = OpenNextEntryImpl(&iter); | |
700 | |
701 if (node->GetLastUsed() >= initial_time && | |
702 node->GetLastUsed() < end_time) { | |
703 node->DoomImpl(); | |
704 } else if (node->GetLastUsed() < initial_time) { | |
705 if (next) | |
706 next->Release(); | |
707 next = NULL; | |
708 SyncEndEnumeration(iter); | |
709 } | |
710 | |
711 node->Release(); | |
712 } | |
713 | |
714 return net::OK; | |
715 } | |
716 | |
717 // We use OpenNextEntryImpl to retrieve elements from the cache, until we get | |
718 // entries that are too old. | |
719 int BackendImpl::SyncDoomEntriesSince(const base::Time initial_time) { | |
720 DCHECK_NE(net::APP_CACHE, cache_type_); | |
721 if (disabled_) | |
722 return net::ERR_FAILED; | |
723 | |
724 stats_.OnEvent(Stats::DOOM_RECENT); | |
725 for (;;) { | |
726 void* iter = NULL; | |
727 EntryImpl* entry = OpenNextEntryImpl(&iter); | |
728 if (!entry) | |
729 return net::OK; | |
730 | |
731 if (initial_time > entry->GetLastUsed()) { | |
732 entry->Release(); | |
733 SyncEndEnumeration(iter); | |
734 return net::OK; | |
735 } | |
736 | |
737 entry->DoomImpl(); | |
738 entry->Release(); | |
739 SyncEndEnumeration(iter); // Dooming the entry invalidates the iterator. | |
740 } | |
1214 } | 741 } |
1215 | 742 |
1216 int BackendImpl::OpenNextEntry(void** iter, Entry** next_entry, | 743 int BackendImpl::OpenNextEntry(void** iter, Entry** next_entry, |
1217 const CompletionCallback& callback) { | 744 const CompletionCallback& callback) { |
1218 DCHECK(!callback.is_null()); | 745 DCHECK(!callback.is_null()); |
1219 background_queue_.OpenNextEntry(iter, next_entry, callback); | 746 background_queue_.OpenNextEntry(iter, next_entry, callback); |
1220 return net::ERR_IO_PENDING; | 747 return net::ERR_IO_PENDING; |
1221 } | 748 } |
1222 | 749 |
1223 void BackendImpl::EndEnumeration(void** iter) { | 750 void BackendImpl::EndEnumeration(void** iter) { |
(...skipping 19 matching lines...) Expand all Loading... | |
1243 item.second = base::StringPrintf("%d", max_size_); | 770 item.second = base::StringPrintf("%d", max_size_); |
1244 stats->push_back(item); | 771 stats->push_back(item); |
1245 | 772 |
1246 item.first = "Current size"; | 773 item.first = "Current size"; |
1247 item.second = base::StringPrintf("%d", data_->header.num_bytes); | 774 item.second = base::StringPrintf("%d", data_->header.num_bytes); |
1248 stats->push_back(item); | 775 stats->push_back(item); |
1249 | 776 |
1250 stats_.GetItems(stats); | 777 stats_.GetItems(stats); |
1251 } | 778 } |
1252 | 779 |
1253 void BackendImpl::OnExternalCacheHit(const std::string& key) { | 780 void BackendImpl::SyncOnExternalCacheHit(const std::string& key) { |
1254 background_queue_.OnExternalCacheHit(key); | 781 if (disabled_) |
782 return; | |
783 | |
784 uint32 hash = base::Hash(key); | |
785 bool error; | |
786 EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error); | |
787 if (cache_entry) { | |
788 if (ENTRY_NORMAL == cache_entry->entry()->Data()->state) { | |
789 UpdateRank(cache_entry, cache_type() == net::SHADER_CACHE); | |
790 } | |
791 cache_entry->Release(); | |
792 } | |
1255 } | 793 } |
1256 | 794 |
1257 // ------------------------------------------------------------------------ | 795 // ------------------------------------------------------------------------ |
1258 | 796 |
1259 // We just created a new file so we're going to write the header and set the | |
1260 // file length to include the hash table (zero filled). | |
1261 bool BackendImpl::CreateBackingStore(disk_cache::File* file) { | |
1262 AdjustMaxCacheSize(0); | |
1263 | |
1264 IndexHeader header; | |
1265 header.table_len = DesiredIndexTableLen(max_size_); | |
1266 | |
1267 // We need file version 2.1 for the new eviction algorithm. | |
1268 if (new_eviction_) | |
1269 header.version = 0x20001; | |
1270 | |
1271 header.create_time = Time::Now().ToInternalValue(); | |
1272 | |
1273 if (!file->Write(&header, sizeof(header), 0)) | |
1274 return false; | |
1275 | |
1276 return file->SetLength(GetIndexSize(header.table_len)); | |
1277 } | |
1278 | |
1279 bool BackendImpl::InitBackingStore(bool* file_created) { | |
1280 if (!file_util::CreateDirectory(path_)) | |
1281 return false; | |
1282 | |
1283 base::FilePath index_name = path_.AppendASCII(kIndexName); | |
1284 | |
1285 int flags = base::PLATFORM_FILE_READ | | |
1286 base::PLATFORM_FILE_WRITE | | |
1287 base::PLATFORM_FILE_OPEN_ALWAYS | | |
1288 base::PLATFORM_FILE_EXCLUSIVE_WRITE; | |
1289 scoped_refptr<disk_cache::File> file(new disk_cache::File( | |
1290 base::CreatePlatformFile(index_name, flags, file_created, NULL))); | |
1291 | |
1292 if (!file->IsValid()) | |
1293 return false; | |
1294 | |
1295 bool ret = true; | |
1296 if (*file_created) | |
1297 ret = CreateBackingStore(file); | |
1298 | |
1299 file = NULL; | |
1300 if (!ret) | |
1301 return false; | |
1302 | |
1303 index_ = new MappedFile(); | |
1304 data_ = reinterpret_cast<Index*>(index_->Init(index_name, 0)); | |
1305 if (!data_) { | |
1306 LOG(ERROR) << "Unable to map Index file"; | |
1307 return false; | |
1308 } | |
1309 | |
1310 if (index_->GetLength() < sizeof(Index)) { | |
1311 // We verify this again on CheckIndex() but it's easier to make sure now | |
1312 // that the header is there. | |
1313 LOG(ERROR) << "Corrupt Index file"; | |
1314 return false; | |
1315 } | |
1316 | |
1317 return true; | |
1318 } | |
1319 | |
1320 // The maximum cache size will be either set explicitly by the caller, or | 797 // The maximum cache size will be either set explicitly by the caller, or |
1321 // calculated by this code. | 798 // calculated by this code. |
1322 void BackendImpl::AdjustMaxCacheSize(int table_len) { | 799 void BackendImpl::AdjustMaxCacheSize(int table_len) { |
1323 if (max_size_) | 800 if (max_size_) |
1324 return; | 801 return; |
1325 | 802 |
1326 // If table_len is provided, the index file exists. | 803 // If table_len is provided, the index file exists. |
1327 DCHECK(!table_len || data_->header.magic); | 804 DCHECK(!table_len || data_->header.magic); |
1328 | 805 |
1329 // The user is not setting the size, let's figure it out. | 806 // The user is not setting the size, let's figure it out. |
(...skipping 117 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1447 data_->header.crash = 0; | 924 data_->header.crash = 0; |
1448 index_->Flush(); | 925 index_->Flush(); |
1449 index_ = NULL; | 926 index_ = NULL; |
1450 data_ = NULL; | 927 data_ = NULL; |
1451 block_files_.CloseFiles(); | 928 block_files_.CloseFiles(); |
1452 rankings_.Reset(); | 929 rankings_.Reset(); |
1453 init_ = false; | 930 init_ = false; |
1454 restarted_ = true; | 931 restarted_ = true; |
1455 } | 932 } |
1456 | 933 |
934 void BackendImpl::CleanupCache() { | |
935 Trace("Backend Cleanup"); | |
936 eviction_.Stop(); | |
937 timer_.reset(); | |
938 | |
939 if (init_) { | |
940 StoreStats(); | |
941 if (data_) | |
942 data_->header.crash = 0; | |
943 | |
944 if (user_flags_ & kNoRandom) { | |
945 // This is a net_unittest, verify that we are not 'leaking' entries. | |
946 File::WaitForPendingIO(&num_pending_io_); | |
947 DCHECK(!num_refs_); | |
948 } else { | |
949 File::DropPendingIO(); | |
950 } | |
951 } | |
952 block_files_.CloseFiles(); | |
953 FlushIndex(); | |
954 index_ = NULL; | |
955 ptr_factory_.InvalidateWeakPtrs(); | |
956 done_.Signal(); | |
957 } | |
958 | |
1457 int BackendImpl::NewEntry(Addr address, EntryImpl** entry) { | 959 int BackendImpl::NewEntry(Addr address, EntryImpl** entry) { |
1458 EntriesMap::iterator it = open_entries_.find(address.value()); | 960 EntriesMap::iterator it = open_entries_.find(address.value()); |
1459 if (it != open_entries_.end()) { | 961 if (it != open_entries_.end()) { |
1460 // Easy job. This entry is already in memory. | 962 // Easy job. This entry is already in memory. |
1461 EntryImpl* this_entry = it->second; | 963 EntryImpl* this_entry = it->second; |
1462 this_entry->AddRef(); | 964 this_entry->AddRef(); |
1463 *entry = this_entry; | 965 *entry = this_entry; |
1464 return 0; | 966 return 0; |
1465 } | 967 } |
1466 | 968 |
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1524 address.value()); | 1026 address.value()); |
1525 } | 1027 } |
1526 | 1028 |
1527 open_entries_[address.value()] = cache_entry; | 1029 open_entries_[address.value()] = cache_entry; |
1528 | 1030 |
1529 cache_entry->BeginLogging(net_log_, false); | 1031 cache_entry->BeginLogging(net_log_, false); |
1530 cache_entry.swap(entry); | 1032 cache_entry.swap(entry); |
1531 return 0; | 1033 return 0; |
1532 } | 1034 } |
1533 | 1035 |
1534 EntryImpl* BackendImpl::MatchEntry(const std::string& key, uint32 hash, | |
1535 bool find_parent, Addr entry_addr, | |
1536 bool* match_error) { | |
1537 Addr address(data_->table[hash & mask_]); | |
1538 scoped_refptr<EntryImpl> cache_entry, parent_entry; | |
1539 EntryImpl* tmp = NULL; | |
1540 bool found = false; | |
1541 std::set<CacheAddr> visited; | |
1542 *match_error = false; | |
1543 | |
1544 for (;;) { | |
1545 if (disabled_) | |
1546 break; | |
1547 | |
1548 if (visited.find(address.value()) != visited.end()) { | |
1549 // It's possible for a buggy version of the code to write a loop. Just | |
1550 // break it. | |
1551 Trace("Hash collision loop 0x%x", address.value()); | |
1552 address.set_value(0); | |
1553 parent_entry->SetNextAddress(address); | |
1554 } | |
1555 visited.insert(address.value()); | |
1556 | |
1557 if (!address.is_initialized()) { | |
1558 if (find_parent) | |
1559 found = true; | |
1560 break; | |
1561 } | |
1562 | |
1563 int error = NewEntry(address, &tmp); | |
1564 cache_entry.swap(&tmp); | |
1565 | |
1566 if (error || cache_entry->dirty()) { | |
1567 // This entry is dirty on disk (it was not properly closed): we cannot | |
1568 // trust it. | |
1569 Addr child(0); | |
1570 if (!error) | |
1571 child.set_value(cache_entry->GetNextAddress()); | |
1572 | |
1573 if (parent_entry) { | |
1574 parent_entry->SetNextAddress(child); | |
1575 parent_entry = NULL; | |
1576 } else { | |
1577 data_->table[hash & mask_] = child.value(); | |
1578 } | |
1579 | |
1580 Trace("MatchEntry dirty %d 0x%x 0x%x", find_parent, entry_addr.value(), | |
1581 address.value()); | |
1582 | |
1583 if (!error) { | |
1584 // It is important to call DestroyInvalidEntry after removing this | |
1585 // entry from the table. | |
1586 DestroyInvalidEntry(cache_entry); | |
1587 cache_entry = NULL; | |
1588 } else { | |
1589 Trace("NewEntry failed on MatchEntry 0x%x", address.value()); | |
1590 } | |
1591 | |
1592 // Restart the search. | |
1593 address.set_value(data_->table[hash & mask_]); | |
1594 visited.clear(); | |
1595 continue; | |
1596 } | |
1597 | |
1598 DCHECK_EQ(hash & mask_, cache_entry->entry()->Data()->hash & mask_); | |
1599 if (cache_entry->IsSameEntry(key, hash)) { | |
1600 if (!cache_entry->Update()) | |
1601 cache_entry = NULL; | |
1602 found = true; | |
1603 if (find_parent && entry_addr.value() != address.value()) { | |
1604 Trace("Entry not on the index 0x%x", address.value()); | |
1605 *match_error = true; | |
1606 parent_entry = NULL; | |
1607 } | |
1608 break; | |
1609 } | |
1610 if (!cache_entry->Update()) | |
1611 cache_entry = NULL; | |
1612 parent_entry = cache_entry; | |
1613 cache_entry = NULL; | |
1614 if (!parent_entry) | |
1615 break; | |
1616 | |
1617 address.set_value(parent_entry->GetNextAddress()); | |
1618 } | |
1619 | |
1620 if (parent_entry && (!find_parent || !found)) | |
1621 parent_entry = NULL; | |
1622 | |
1623 if (find_parent && entry_addr.is_initialized() && !cache_entry) { | |
1624 *match_error = true; | |
1625 parent_entry = NULL; | |
1626 } | |
1627 | |
1628 if (cache_entry && (find_parent || !found)) | |
1629 cache_entry = NULL; | |
1630 | |
1631 find_parent ? parent_entry.swap(&tmp) : cache_entry.swap(&tmp); | |
1632 FlushIndex(); | |
1633 return tmp; | |
1634 } | |
1635 | |
1636 // This is the actual implementation for OpenNextEntry and OpenPrevEntry. | 1036 // This is the actual implementation for OpenNextEntry and OpenPrevEntry. |
1637 EntryImpl* BackendImpl::OpenFollowingEntry(bool forward, void** iter) { | 1037 EntryImpl* BackendImpl::OpenFollowingEntry(bool forward, void** iter) { |
1638 if (disabled_) | 1038 if (disabled_) |
1639 return NULL; | 1039 return NULL; |
1640 | 1040 |
1641 DCHECK(iter); | 1041 DCHECK(iter); |
1642 | 1042 |
1643 const int kListsToSearch = 3; | 1043 const int kListsToSearch = 3; |
1644 scoped_refptr<EntryImpl> entries[kListsToSearch]; | 1044 scoped_refptr<EntryImpl> entries[kListsToSearch]; |
1645 scoped_ptr<Rankings::Iterator> iterator( | 1045 scoped_ptr<Rankings::Iterator> iterator( |
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1704 } else { | 1104 } else { |
1705 next_entry = entries[oldest].get(); | 1105 next_entry = entries[oldest].get(); |
1706 iterator->list = static_cast<Rankings::List>(oldest); | 1106 iterator->list = static_cast<Rankings::List>(oldest); |
1707 } | 1107 } |
1708 | 1108 |
1709 *iter = iterator.release(); | 1109 *iter = iterator.release(); |
1710 next_entry->AddRef(); | 1110 next_entry->AddRef(); |
1711 return next_entry; | 1111 return next_entry; |
1712 } | 1112 } |
1713 | 1113 |
1714 bool BackendImpl::OpenFollowingEntryFromList(bool forward, Rankings::List list, | 1114 void BackendImpl::AddStorageSize(int32 bytes) { |
1715 CacheRankingsBlock** from_entry, | 1115 data_->header.num_bytes += bytes; |
1716 EntryImpl** next_entry) { | 1116 DCHECK_GE(data_->header.num_bytes, 0); |
1717 if (disabled_) | |
1718 return false; | |
1719 | |
1720 if (!new_eviction_ && Rankings::NO_USE != list) | |
1721 return false; | |
1722 | |
1723 Rankings::ScopedRankingsBlock rankings(&rankings_, *from_entry); | |
1724 CacheRankingsBlock* next_block = forward ? | |
1725 rankings_.GetNext(rankings.get(), list) : | |
1726 rankings_.GetPrev(rankings.get(), list); | |
1727 Rankings::ScopedRankingsBlock next(&rankings_, next_block); | |
1728 *from_entry = NULL; | |
1729 | |
1730 *next_entry = GetEnumeratedEntry(next.get(), list); | |
1731 if (!*next_entry) | |
1732 return false; | |
1733 | |
1734 *from_entry = next.release(); | |
1735 return true; | |
1736 } | 1117 } |
1737 | 1118 |
1738 EntryImpl* BackendImpl::GetEnumeratedEntry(CacheRankingsBlock* next, | 1119 void BackendImpl::SubstractStorageSize(int32 bytes) { |
1739 Rankings::List list) { | 1120 data_->header.num_bytes -= bytes; |
1740 if (!next || disabled_) | 1121 DCHECK_GE(data_->header.num_bytes, 0); |
1741 return NULL; | 1122 } |
1742 | 1123 |
1743 EntryImpl* entry; | 1124 void BackendImpl::IncreaseNumRefs() { |
1744 int rv = NewEntry(Addr(next->Data()->contents), &entry); | 1125 num_refs_++; |
1745 if (rv) { | 1126 if (max_refs_ < num_refs_) |
1746 STRESS_NOTREACHED(); | 1127 max_refs_ = num_refs_; |
1747 rankings_.Remove(next, list, false); | 1128 } |
1748 if (rv == ERR_INVALID_ADDRESS) { | 1129 |
1749 // There is nothing linked from the index. Delete the rankings node. | 1130 void BackendImpl::DecreaseNumRefs() { |
1750 DeleteBlock(next->address(), true); | 1131 DCHECK(num_refs_); |
1751 } | 1132 num_refs_--; |
1752 return NULL; | 1133 |
1134 if (!num_refs_ && disabled_) | |
1135 base::MessageLoop::current()->PostTask( | |
1136 FROM_HERE, base::Bind(&BackendImpl::RestartCache, GetWeakPtr(), true)); | |
1137 } | |
1138 | |
1139 void BackendImpl::IncreaseNumEntries() { | |
1140 data_->header.num_entries++; | |
1141 DCHECK_GT(data_->header.num_entries, 0); | |
1142 } | |
1143 | |
1144 void BackendImpl::DecreaseNumEntries() { | |
1145 data_->header.num_entries--; | |
1146 if (data_->header.num_entries < 0) { | |
1147 NOTREACHED(); | |
1148 data_->header.num_entries = 0; | |
1149 } | |
1150 } | |
1151 | |
1152 int BackendImpl::SyncInit() { | |
1153 #if defined(NET_BUILD_STRESS_CACHE) | |
1154 // Start evictions right away. | |
1155 up_ticks_ = kTrimDelay * 2; | |
1156 #endif | |
1157 DCHECK(!init_); | |
1158 if (init_) | |
1159 return net::ERR_FAILED; | |
1160 | |
1161 bool create_files = false; | |
1162 if (!InitBackingStore(&create_files)) { | |
1163 ReportError(ERR_STORAGE_ERROR); | |
1164 return net::ERR_FAILED; | |
1753 } | 1165 } |
1754 | 1166 |
1755 if (entry->dirty()) { | 1167 num_refs_ = num_pending_io_ = max_refs_ = 0; |
1756 // We cannot trust this entry. | 1168 entry_count_ = byte_count_ = 0; |
1757 InternalDoomEntry(entry); | 1169 |
1758 entry->Release(); | 1170 if (!restarted_) { |
1759 return NULL; | 1171 buffer_bytes_ = 0; |
1172 trace_object_ = TraceObject::GetTraceObject(); | |
1173 // Create a recurrent timer of 30 secs. | |
1174 int timer_delay = unit_test_ ? 1000 : 30000; | |
1175 timer_.reset(new base::RepeatingTimer<BackendImpl>()); | |
1176 timer_->Start(FROM_HERE, TimeDelta::FromMilliseconds(timer_delay), this, | |
1177 &BackendImpl::OnStatsTimer); | |
1760 } | 1178 } |
1761 | 1179 |
1762 if (!entry->Update()) { | 1180 init_ = true; |
1763 STRESS_NOTREACHED(); | 1181 Trace("Init"); |
1764 entry->Release(); | 1182 |
1765 return NULL; | 1183 if (data_->header.experiment != NO_EXPERIMENT && |
1184 cache_type_ != net::DISK_CACHE) { | |
1185 // No experiment for other caches. | |
1186 return net::ERR_FAILED; | |
1766 } | 1187 } |
1767 | 1188 |
1768 // Note that it is unfortunate (but possible) for this entry to be clean, but | 1189 if (!(user_flags_ & kNoRandom)) { |
1769 // not actually the real entry. In other words, we could have lost this entry | 1190 // The unit test controls directly what to test. |
1770 // from the index, and it could have been replaced with a newer one. It's not | 1191 new_eviction_ = (cache_type_ == net::DISK_CACHE); |
1771 // worth checking that this entry is "the real one", so we just return it and | 1192 } |
1772 // let the enumeration continue; this entry will be evicted at some point, and | |
1773 // the regular path will work with the real entry. With time, this problem | |
1774 // will disasappear because this scenario is just a bug. | |
1775 | 1193 |
1776 // Make sure that we save the key for later. | 1194 if (!CheckIndex()) { |
1777 entry->GetKey(); | 1195 ReportError(ERR_INIT_FAILED); |
1196 return net::ERR_FAILED; | |
1197 } | |
1778 | 1198 |
1779 return entry; | 1199 if (!restarted_ && (create_files || !data_->header.num_entries)) |
1200 ReportError(ERR_CACHE_CREATED); | |
1201 | |
1202 if (!(user_flags_ & kNoRandom) && cache_type_ == net::DISK_CACHE && | |
1203 !InitExperiment(&data_->header, create_files)) { | |
1204 return net::ERR_FAILED; | |
1205 } | |
1206 | |
1207 // We don't care if the value overflows. The only thing we care about is that | |
1208 // the id cannot be zero, because that value is used as "not dirty". | |
1209 // Increasing the value once per second gives us many years before we start | |
1210 // having collisions. | |
1211 data_->header.this_id++; | |
1212 if (!data_->header.this_id) | |
1213 data_->header.this_id++; | |
1214 | |
1215 bool previous_crash = (data_->header.crash != 0); | |
1216 data_->header.crash = 1; | |
1217 | |
1218 if (!block_files_.Init(create_files)) | |
1219 return net::ERR_FAILED; | |
1220 | |
1221 // We want to minimize the changes to cache for an AppCache. | |
1222 if (cache_type() == net::APP_CACHE) { | |
1223 DCHECK(!new_eviction_); | |
1224 read_only_ = true; | |
1225 } else if (cache_type() == net::SHADER_CACHE) { | |
1226 DCHECK(!new_eviction_); | |
1227 } | |
1228 | |
1229 eviction_.Init(this); | |
1230 | |
1231 // stats_ and rankings_ may end up calling back to us so we better be enabled. | |
1232 disabled_ = false; | |
1233 if (!InitStats()) | |
1234 return net::ERR_FAILED; | |
1235 | |
1236 disabled_ = !rankings_.Init(this, new_eviction_); | |
1237 | |
1238 #if defined(STRESS_CACHE_EXTENDED_VALIDATION) | |
1239 trace_object_->EnableTracing(false); | |
1240 int sc = SelfCheck(); | |
1241 if (sc < 0 && sc != ERR_NUM_ENTRIES_MISMATCH) | |
1242 NOTREACHED(); | |
1243 trace_object_->EnableTracing(true); | |
1244 #endif | |
1245 | |
1246 if (previous_crash) { | |
1247 ReportError(ERR_PREVIOUS_CRASH); | |
1248 } else if (!restarted_) { | |
1249 ReportError(ERR_NO_ERROR); | |
1250 } | |
1251 | |
1252 FlushIndex(); | |
1253 | |
1254 return disabled_ ? net::ERR_FAILED : net::OK; | |
1780 } | 1255 } |
1781 | 1256 |
1782 EntryImpl* BackendImpl::ResurrectEntry(EntryImpl* deleted_entry) { | 1257 EntryImpl* BackendImpl::ResurrectEntry(EntryImpl* deleted_entry) { |
1783 if (ENTRY_NORMAL == deleted_entry->entry()->Data()->state) { | 1258 if (ENTRY_NORMAL == deleted_entry->entry()->Data()->state) { |
1784 deleted_entry->Release(); | 1259 deleted_entry->Release(); |
1785 stats_.OnEvent(Stats::CREATE_MISS); | 1260 stats_.OnEvent(Stats::CREATE_MISS); |
1786 Trace("create entry miss "); | 1261 Trace("create entry miss "); |
1787 return NULL; | 1262 return NULL; |
1788 } | 1263 } |
1789 | 1264 |
1790 // We are attempting to create an entry and found out that the entry was | 1265 // We are attempting to create an entry and found out that the entry was |
1791 // previously deleted. | 1266 // previously deleted. |
1792 | 1267 |
1793 eviction_.OnCreateEntry(deleted_entry); | 1268 eviction_.OnCreateEntry(deleted_entry); |
1794 entry_count_++; | 1269 entry_count_++; |
1795 | 1270 |
1796 stats_.OnEvent(Stats::RESURRECT_HIT); | 1271 stats_.OnEvent(Stats::RESURRECT_HIT); |
1797 Trace("Resurrect entry hit "); | 1272 Trace("Resurrect entry hit "); |
1798 return deleted_entry; | 1273 return deleted_entry; |
1799 } | 1274 } |
1800 | 1275 |
1801 void BackendImpl::DestroyInvalidEntry(EntryImpl* entry) { | 1276 EntryImpl* BackendImpl::CreateEntryImpl(const std::string& key) { |
1802 LOG(WARNING) << "Destroying invalid entry."; | 1277 if (disabled_ || key.empty()) |
1803 Trace("Destroying invalid entry 0x%p", entry); | 1278 return NULL; |
1804 | 1279 |
1805 entry->SetPointerForInvalidEntry(GetCurrentEntryId()); | 1280 TimeTicks start = TimeTicks::Now(); |
1281 Trace("Create hash 0x%x", hash); | |
1806 | 1282 |
1807 eviction_.OnDoomEntry(entry); | 1283 scoped_refptr<EntryImpl> parent; |
1808 entry->InternalDoom(); | 1284 Addr entry_address(data_->table[hash & mask_]); |
1285 if (entry_address.is_initialized()) { | |
1286 // We have an entry already. It could be the one we are looking for, or just | |
1287 // a hash conflict. | |
1288 bool error; | |
1289 EntryImpl* old_entry = MatchEntry(key, hash, false, Addr(), &error); | |
1290 if (old_entry) | |
1291 return ResurrectEntry(old_entry); | |
1809 | 1292 |
1810 if (!new_eviction_) | 1293 EntryImpl* parent_entry = MatchEntry(key, hash, true, Addr(), &error); |
1811 DecreaseNumEntries(); | 1294 DCHECK(!error); |
1812 stats_.OnEvent(Stats::INVALID_ENTRY); | 1295 if (parent_entry) { |
1813 } | 1296 parent.swap(&parent_entry); |
1297 } else if (data_->table[hash & mask_]) { | |
1298 // We should have corrected the problem. | |
1299 NOTREACHED(); | |
1300 return NULL; | |
1301 } | |
1302 } | |
1814 | 1303 |
1815 void BackendImpl::AddStorageSize(int32 bytes) { | 1304 // The general flow is to allocate disk space and initialize the entry data, |
1816 data_->header.num_bytes += bytes; | 1305 // followed by saving that to disk, then linking the entry though the index |
1817 DCHECK_GE(data_->header.num_bytes, 0); | 1306 // and finally through the lists. If there is a crash in this process, we may |
1818 } | 1307 // end up with: |
1308 // a. Used, unreferenced empty blocks on disk (basically just garbage). | |
1309 // b. Used, unreferenced but meaningful data on disk (more garbage). | |
1310 // c. A fully formed entry, reachable only through the index. | |
1311 // d. A fully formed entry, also reachable through the lists, but still dirty. | |
1312 // | |
1313 // Anything after (b) can be automatically cleaned up. We may consider saving | |
1314 // the current operation (as we do while manipulating the lists) so that we | |
1315 // can detect and cleanup (a) and (b). | |
1819 | 1316 |
1820 void BackendImpl::SubstractStorageSize(int32 bytes) { | 1317 int num_blocks = EntryImpl::NumBlocksForEntry(key.size()); |
1821 data_->header.num_bytes -= bytes; | 1318 if (!block_files_.CreateBlock(BLOCK_256, num_blocks, &entry_address)) { |
1822 DCHECK_GE(data_->header.num_bytes, 0); | 1319 LOG(ERROR) << "Create entry failed " << key.c_str(); |
1823 } | 1320 stats_.OnEvent(Stats::CREATE_ERROR); |
1321 return NULL; | |
1322 } | |
1824 | 1323 |
1825 void BackendImpl::IncreaseNumRefs() { | 1324 Addr node_address(0); |
1826 num_refs_++; | 1325 if (!block_files_.CreateBlock(RANKINGS, 1, &node_address)) { |
1827 if (max_refs_ < num_refs_) | 1326 block_files_.DeleteBlock(entry_address, false); |
1828 max_refs_ = num_refs_; | 1327 LOG(ERROR) << "Create entry failed " << key.c_str(); |
1829 } | 1328 stats_.OnEvent(Stats::CREATE_ERROR); |
1329 return NULL; | |
1330 } | |
1830 | 1331 |
1831 void BackendImpl::DecreaseNumRefs() { | 1332 scoped_refptr<EntryImpl> cache_entry( |
1832 DCHECK(num_refs_); | 1333 new EntryImpl(this, entry_address, false)); |
1833 num_refs_--; | 1334 IncreaseNumRefs(); |
1834 | 1335 |
1835 if (!num_refs_ && disabled_) | 1336 if (!cache_entry->CreateEntry(node_address, key, hash)) { |
1836 base::MessageLoop::current()->PostTask( | 1337 block_files_.DeleteBlock(entry_address, false); |
1837 FROM_HERE, base::Bind(&BackendImpl::RestartCache, GetWeakPtr(), true)); | 1338 block_files_.DeleteBlock(node_address, false); |
1838 } | 1339 LOG(ERROR) << "Create entry failed " << key.c_str(); |
1340 stats_.OnEvent(Stats::CREATE_ERROR); | |
1341 return NULL; | |
1342 } | |
1839 | 1343 |
1840 void BackendImpl::IncreaseNumEntries() { | 1344 cache_entry->BeginLogging(net_log_, true); |
1841 data_->header.num_entries++; | |
1842 DCHECK_GT(data_->header.num_entries, 0); | |
1843 } | |
1844 | 1345 |
1845 void BackendImpl::DecreaseNumEntries() { | 1346 // We are not failing the operation; let's add this to the map. |
1846 data_->header.num_entries--; | 1347 open_entries_[entry_address.value()] = cache_entry; |
1847 if (data_->header.num_entries < 0) { | 1348 |
1848 NOTREACHED(); | 1349 // Save the entry. |
1849 data_->header.num_entries = 0; | 1350 cache_entry->entry()->Store(); |
1351 cache_entry->rankings()->Store(); | |
1352 IncreaseNumEntries(); | |
1353 entry_count_++; | |
1354 | |
1355 // Link this entry through the index. | |
1356 if (parent.get()) { | |
1357 parent->SetNextAddress(entry_address); | |
1358 } else { | |
1359 data_->table[hash & mask_] = entry_address.value(); | |
1850 } | 1360 } |
1361 | |
1362 // Link this entry through the lists. | |
1363 eviction_.OnCreateEntry(cache_entry); | |
1364 | |
1365 CACHE_UMA(AGE_MS, "CreateTime", 0, start); | |
1366 stats_.OnEvent(Stats::CREATE_HIT); | |
1367 SIMPLE_STATS_COUNTER("disk_cache.miss"); | |
1368 Trace("create entry hit "); | |
1369 FlushIndex(); | |
1370 cache_entry->AddRef(); | |
1371 return cache_entry.get(); | |
1851 } | 1372 } |
1852 | 1373 |
1853 void BackendImpl::LogStats() { | 1374 void BackendImpl::LogStats() { |
1854 StatsItems stats; | 1375 StatsItems stats; |
1855 GetStats(&stats); | 1376 GetStats(&stats); |
1856 | 1377 |
1857 for (size_t index = 0; index < stats.size(); index++) | 1378 for (size_t index = 0; index < stats.size(); index++) |
1858 VLOG(1) << stats[index].first << ": " << stats[index].second; | 1379 VLOG(1) << stats[index].first << ": " << stats[index].second; |
1859 } | 1380 } |
1860 | 1381 |
(...skipping 96 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
1957 data_->header.lru.sizes[4] * 100 / data_->header.num_entries); | 1478 data_->header.lru.sizes[4] * 100 / data_->header.num_entries); |
1958 } | 1479 } |
1959 | 1480 |
1960 stats_.ResetRatios(); | 1481 stats_.ResetRatios(); |
1961 stats_.SetCounter(Stats::TRIM_ENTRY, 0); | 1482 stats_.SetCounter(Stats::TRIM_ENTRY, 0); |
1962 | 1483 |
1963 if (cache_type_ == net::DISK_CACHE) | 1484 if (cache_type_ == net::DISK_CACHE) |
1964 block_files_.ReportStats(); | 1485 block_files_.ReportStats(); |
1965 } | 1486 } |
1966 | 1487 |
1967 void BackendImpl::UpgradeTo2_1() { | 1488 void BackendImpl::ReportError(int error) { |
1968 // 2.1 is basically the same as 2.0, except that new fields are actually | 1489 STRESS_DCHECK(!error || error == ERR_PREVIOUS_CRASH || |
1969 // updated by the new eviction algorithm. | 1490 error == ERR_CACHE_CREATED); |
1970 DCHECK(0x20000 == data_->header.version); | 1491 |
1971 data_->header.version = 0x20001; | 1492 // We transmit positive numbers, instead of direct error codes. |
1972 data_->header.lru.sizes[Rankings::NO_USE] = data_->header.num_entries; | 1493 DCHECK_LE(error, 0); |
1494 CACHE_UMA(CACHE_ERROR, "Error", 0, error * -1); | |
1973 } | 1495 } |
1974 | 1496 |
1975 bool BackendImpl::CheckIndex() { | 1497 bool BackendImpl::CheckIndex() { |
1976 DCHECK(data_); | 1498 DCHECK(data_); |
1977 | 1499 |
1978 size_t current_size = index_->GetLength(); | 1500 size_t current_size = index_->GetLength(); |
1979 if (current_size < sizeof(Index)) { | 1501 if (current_size < sizeof(Index)) { |
1980 LOG(ERROR) << "Corrupt Index file"; | 1502 LOG(ERROR) << "Corrupt Index file"; |
1981 return false; | 1503 return false; |
1982 } | 1504 } |
(...skipping 122 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
2105 if (total_memory > kMaxBuffersSize || total_memory <= 0) | 1627 if (total_memory > kMaxBuffersSize || total_memory <= 0) |
2106 total_memory = kMaxBuffersSize; | 1628 total_memory = kMaxBuffersSize; |
2107 | 1629 |
2108 done = true; | 1630 done = true; |
2109 } | 1631 } |
2110 | 1632 |
2111 return static_cast<int>(total_memory); | 1633 return static_cast<int>(total_memory); |
2112 } | 1634 } |
2113 | 1635 |
2114 } // namespace disk_cache | 1636 } // namespace disk_cache |
OLD | NEW |