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

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

Issue 14991008: Disk cache: Add base files for implementation of file format version 3. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: rebase Created 7 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « net/disk_cache/v3/backend_impl_v3.h ('k') | net/disk_cache/v3/backend_worker.h » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
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
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
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.get();
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.get());
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
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
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
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
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_.get() && !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_.get() || disabled_) 495 if (!index_.get() || 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) {
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.get();
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.get());
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 23 matching lines...) Expand all
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 item.first = "Cache type"; 777 item.first = "Cache type";
1251 item.second = "Blockfile Cache"; 778 item.second = "Blockfile Cache";
1252 stats->push_back(item); 779 stats->push_back(item);
1253 780
1254 stats_.GetItems(stats); 781 stats_.GetItems(stats);
1255 } 782 }
1256 783
1257 void BackendImpl::OnExternalCacheHit(const std::string& key) { 784 void BackendImpl::SyncOnExternalCacheHit(const std::string& key) {
1258 background_queue_.OnExternalCacheHit(key); 785 if (disabled_)
786 return;
787
788 uint32 hash = base::Hash(key);
789 bool error;
790 EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error);
791 if (cache_entry) {
792 if (ENTRY_NORMAL == cache_entry->entry()->Data()->state) {
793 UpdateRank(cache_entry, cache_type() == net::SHADER_CACHE);
794 }
795 cache_entry->Release();
796 }
1259 } 797 }
1260 798
1261 // ------------------------------------------------------------------------ 799 // ------------------------------------------------------------------------
1262 800
1263 // We just created a new file so we're going to write the header and set the
1264 // file length to include the hash table (zero filled).
1265 bool BackendImpl::CreateBackingStore(disk_cache::File* file) {
1266 AdjustMaxCacheSize(0);
1267
1268 IndexHeader header;
1269 header.table_len = DesiredIndexTableLen(max_size_);
1270
1271 // We need file version 2.1 for the new eviction algorithm.
1272 if (new_eviction_)
1273 header.version = 0x20001;
1274
1275 header.create_time = Time::Now().ToInternalValue();
1276
1277 if (!file->Write(&header, sizeof(header), 0))
1278 return false;
1279
1280 return file->SetLength(GetIndexSize(header.table_len));
1281 }
1282
1283 bool BackendImpl::InitBackingStore(bool* file_created) {
1284 if (!file_util::CreateDirectory(path_))
1285 return false;
1286
1287 base::FilePath index_name = path_.AppendASCII(kIndexName);
1288
1289 int flags = base::PLATFORM_FILE_READ |
1290 base::PLATFORM_FILE_WRITE |
1291 base::PLATFORM_FILE_OPEN_ALWAYS |
1292 base::PLATFORM_FILE_EXCLUSIVE_WRITE;
1293 scoped_refptr<disk_cache::File> file(new disk_cache::File(
1294 base::CreatePlatformFile(index_name, flags, file_created, NULL)));
1295
1296 if (!file->IsValid())
1297 return false;
1298
1299 bool ret = true;
1300 if (*file_created)
1301 ret = CreateBackingStore(file.get());
1302
1303 file = NULL;
1304 if (!ret)
1305 return false;
1306
1307 index_ = new MappedFile();
1308 data_ = reinterpret_cast<Index*>(index_->Init(index_name, 0));
1309 if (!data_) {
1310 LOG(ERROR) << "Unable to map Index file";
1311 return false;
1312 }
1313
1314 if (index_->GetLength() < sizeof(Index)) {
1315 // We verify this again on CheckIndex() but it's easier to make sure now
1316 // that the header is there.
1317 LOG(ERROR) << "Corrupt Index file";
1318 return false;
1319 }
1320
1321 return true;
1322 }
1323
1324 // The maximum cache size will be either set explicitly by the caller, or 801 // The maximum cache size will be either set explicitly by the caller, or
1325 // calculated by this code. 802 // calculated by this code.
1326 void BackendImpl::AdjustMaxCacheSize(int table_len) { 803 void BackendImpl::AdjustMaxCacheSize(int table_len) {
1327 if (max_size_) 804 if (max_size_)
1328 return; 805 return;
1329 806
1330 // If table_len is provided, the index file exists. 807 // If table_len is provided, the index file exists.
1331 DCHECK(!table_len || data_->header.magic); 808 DCHECK(!table_len || data_->header.magic);
1332 809
1333 // The user is not setting the size, let's figure it out. 810 // The user is not setting the size, let's figure it out.
(...skipping 117 matching lines...) Expand 10 before | Expand all | Expand 10 after
1451 data_->header.crash = 0; 928 data_->header.crash = 0;
1452 index_->Flush(); 929 index_->Flush();
1453 index_ = NULL; 930 index_ = NULL;
1454 data_ = NULL; 931 data_ = NULL;
1455 block_files_.CloseFiles(); 932 block_files_.CloseFiles();
1456 rankings_.Reset(); 933 rankings_.Reset();
1457 init_ = false; 934 init_ = false;
1458 restarted_ = true; 935 restarted_ = true;
1459 } 936 }
1460 937
938 void BackendImpl::CleanupCache() {
939 Trace("Backend Cleanup");
940 eviction_.Stop();
941 timer_.reset();
942
943 if (init_) {
944 StoreStats();
945 if (data_)
946 data_->header.crash = 0;
947
948 if (user_flags_ & kNoRandom) {
949 // This is a net_unittest, verify that we are not 'leaking' entries.
950 File::WaitForPendingIO(&num_pending_io_);
951 DCHECK(!num_refs_);
952 } else {
953 File::DropPendingIO();
954 }
955 }
956 block_files_.CloseFiles();
957 FlushIndex();
958 index_ = NULL;
959 ptr_factory_.InvalidateWeakPtrs();
960 done_.Signal();
961 }
962
1461 int BackendImpl::NewEntry(Addr address, EntryImpl** entry) { 963 int BackendImpl::NewEntry(Addr address, EntryImpl** entry) {
1462 EntriesMap::iterator it = open_entries_.find(address.value()); 964 EntriesMap::iterator it = open_entries_.find(address.value());
1463 if (it != open_entries_.end()) { 965 if (it != open_entries_.end()) {
1464 // Easy job. This entry is already in memory. 966 // Easy job. This entry is already in memory.
1465 EntryImpl* this_entry = it->second; 967 EntryImpl* this_entry = it->second;
1466 this_entry->AddRef(); 968 this_entry->AddRef();
1467 *entry = this_entry; 969 *entry = this_entry;
1468 return 0; 970 return 0;
1469 } 971 }
1470 972
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after
1528 address.value()); 1030 address.value());
1529 } 1031 }
1530 1032
1531 open_entries_[address.value()] = cache_entry.get(); 1033 open_entries_[address.value()] = cache_entry.get();
1532 1034
1533 cache_entry->BeginLogging(net_log_, false); 1035 cache_entry->BeginLogging(net_log_, false);
1534 cache_entry.swap(entry); 1036 cache_entry.swap(entry);
1535 return 0; 1037 return 0;
1536 } 1038 }
1537 1039
1538 EntryImpl* BackendImpl::MatchEntry(const std::string& key, uint32 hash,
1539 bool find_parent, Addr entry_addr,
1540 bool* match_error) {
1541 Addr address(data_->table[hash & mask_]);
1542 scoped_refptr<EntryImpl> cache_entry, parent_entry;
1543 EntryImpl* tmp = NULL;
1544 bool found = false;
1545 std::set<CacheAddr> visited;
1546 *match_error = false;
1547
1548 for (;;) {
1549 if (disabled_)
1550 break;
1551
1552 if (visited.find(address.value()) != visited.end()) {
1553 // It's possible for a buggy version of the code to write a loop. Just
1554 // break it.
1555 Trace("Hash collision loop 0x%x", address.value());
1556 address.set_value(0);
1557 parent_entry->SetNextAddress(address);
1558 }
1559 visited.insert(address.value());
1560
1561 if (!address.is_initialized()) {
1562 if (find_parent)
1563 found = true;
1564 break;
1565 }
1566
1567 int error = NewEntry(address, &tmp);
1568 cache_entry.swap(&tmp);
1569
1570 if (error || cache_entry->dirty()) {
1571 // This entry is dirty on disk (it was not properly closed): we cannot
1572 // trust it.
1573 Addr child(0);
1574 if (!error)
1575 child.set_value(cache_entry->GetNextAddress());
1576
1577 if (parent_entry.get()) {
1578 parent_entry->SetNextAddress(child);
1579 parent_entry = NULL;
1580 } else {
1581 data_->table[hash & mask_] = child.value();
1582 }
1583
1584 Trace("MatchEntry dirty %d 0x%x 0x%x", find_parent, entry_addr.value(),
1585 address.value());
1586
1587 if (!error) {
1588 // It is important to call DestroyInvalidEntry after removing this
1589 // entry from the table.
1590 DestroyInvalidEntry(cache_entry.get());
1591 cache_entry = NULL;
1592 } else {
1593 Trace("NewEntry failed on MatchEntry 0x%x", address.value());
1594 }
1595
1596 // Restart the search.
1597 address.set_value(data_->table[hash & mask_]);
1598 visited.clear();
1599 continue;
1600 }
1601
1602 DCHECK_EQ(hash & mask_, cache_entry->entry()->Data()->hash & mask_);
1603 if (cache_entry->IsSameEntry(key, hash)) {
1604 if (!cache_entry->Update())
1605 cache_entry = NULL;
1606 found = true;
1607 if (find_parent && entry_addr.value() != address.value()) {
1608 Trace("Entry not on the index 0x%x", address.value());
1609 *match_error = true;
1610 parent_entry = NULL;
1611 }
1612 break;
1613 }
1614 if (!cache_entry->Update())
1615 cache_entry = NULL;
1616 parent_entry = cache_entry;
1617 cache_entry = NULL;
1618 if (!parent_entry.get())
1619 break;
1620
1621 address.set_value(parent_entry->GetNextAddress());
1622 }
1623
1624 if (parent_entry.get() && (!find_parent || !found))
1625 parent_entry = NULL;
1626
1627 if (find_parent && entry_addr.is_initialized() && !cache_entry.get()) {
1628 *match_error = true;
1629 parent_entry = NULL;
1630 }
1631
1632 if (cache_entry.get() && (find_parent || !found))
1633 cache_entry = NULL;
1634
1635 find_parent ? parent_entry.swap(&tmp) : cache_entry.swap(&tmp);
1636 FlushIndex();
1637 return tmp;
1638 }
1639
1640 // This is the actual implementation for OpenNextEntry and OpenPrevEntry. 1040 // This is the actual implementation for OpenNextEntry and OpenPrevEntry.
1641 EntryImpl* BackendImpl::OpenFollowingEntry(bool forward, void** iter) { 1041 EntryImpl* BackendImpl::OpenFollowingEntry(bool forward, void** iter) {
1642 if (disabled_) 1042 if (disabled_)
1643 return NULL; 1043 return NULL;
1644 1044
1645 DCHECK(iter); 1045 DCHECK(iter);
1646 1046
1647 const int kListsToSearch = 3; 1047 const int kListsToSearch = 3;
1648 scoped_refptr<EntryImpl> entries[kListsToSearch]; 1048 scoped_refptr<EntryImpl> entries[kListsToSearch];
1649 scoped_ptr<Rankings::Iterator> iterator( 1049 scoped_ptr<Rankings::Iterator> iterator(
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after
1708 } else { 1108 } else {
1709 next_entry = entries[oldest].get(); 1109 next_entry = entries[oldest].get();
1710 iterator->list = static_cast<Rankings::List>(oldest); 1110 iterator->list = static_cast<Rankings::List>(oldest);
1711 } 1111 }
1712 1112
1713 *iter = iterator.release(); 1113 *iter = iterator.release();
1714 next_entry->AddRef(); 1114 next_entry->AddRef();
1715 return next_entry; 1115 return next_entry;
1716 } 1116 }
1717 1117
1718 bool BackendImpl::OpenFollowingEntryFromList(bool forward, Rankings::List list, 1118 void BackendImpl::AddStorageSize(int32 bytes) {
1719 CacheRankingsBlock** from_entry, 1119 data_->header.num_bytes += bytes;
1720 EntryImpl** next_entry) { 1120 DCHECK_GE(data_->header.num_bytes, 0);
1721 if (disabled_)
1722 return false;
1723
1724 if (!new_eviction_ && Rankings::NO_USE != list)
1725 return false;
1726
1727 Rankings::ScopedRankingsBlock rankings(&rankings_, *from_entry);
1728 CacheRankingsBlock* next_block = forward ?
1729 rankings_.GetNext(rankings.get(), list) :
1730 rankings_.GetPrev(rankings.get(), list);
1731 Rankings::ScopedRankingsBlock next(&rankings_, next_block);
1732 *from_entry = NULL;
1733
1734 *next_entry = GetEnumeratedEntry(next.get(), list);
1735 if (!*next_entry)
1736 return false;
1737
1738 *from_entry = next.release();
1739 return true;
1740 } 1121 }
1741 1122
1742 EntryImpl* BackendImpl::GetEnumeratedEntry(CacheRankingsBlock* next, 1123 void BackendImpl::SubstractStorageSize(int32 bytes) {
1743 Rankings::List list) { 1124 data_->header.num_bytes -= bytes;
1744 if (!next || disabled_) 1125 DCHECK_GE(data_->header.num_bytes, 0);
1745 return NULL; 1126 }
1746 1127
1747 EntryImpl* entry; 1128 void BackendImpl::IncreaseNumRefs() {
1748 int rv = NewEntry(Addr(next->Data()->contents), &entry); 1129 num_refs_++;
1749 if (rv) { 1130 if (max_refs_ < num_refs_)
1750 STRESS_NOTREACHED(); 1131 max_refs_ = num_refs_;
1751 rankings_.Remove(next, list, false); 1132 }
1752 if (rv == ERR_INVALID_ADDRESS) { 1133
1753 // There is nothing linked from the index. Delete the rankings node. 1134 void BackendImpl::DecreaseNumRefs() {
1754 DeleteBlock(next->address(), true); 1135 DCHECK(num_refs_);
1755 } 1136 num_refs_--;
1756 return NULL; 1137
1138 if (!num_refs_ && disabled_)
1139 base::MessageLoop::current()->PostTask(
1140 FROM_HERE, base::Bind(&BackendImpl::RestartCache, GetWeakPtr(), true));
1141 }
1142
1143 void BackendImpl::IncreaseNumEntries() {
1144 data_->header.num_entries++;
1145 DCHECK_GT(data_->header.num_entries, 0);
1146 }
1147
1148 void BackendImpl::DecreaseNumEntries() {
1149 data_->header.num_entries--;
1150 if (data_->header.num_entries < 0) {
1151 NOTREACHED();
1152 data_->header.num_entries = 0;
1153 }
1154 }
1155
1156 int BackendImpl::SyncInit() {
1157 #if defined(NET_BUILD_STRESS_CACHE)
1158 // Start evictions right away.
1159 up_ticks_ = kTrimDelay * 2;
1160 #endif
1161 DCHECK(!init_);
1162 if (init_)
1163 return net::ERR_FAILED;
1164
1165 bool create_files = false;
1166 if (!InitBackingStore(&create_files)) {
1167 ReportError(ERR_STORAGE_ERROR);
1168 return net::ERR_FAILED;
1757 } 1169 }
1758 1170
1759 if (entry->dirty()) { 1171 num_refs_ = num_pending_io_ = max_refs_ = 0;
1760 // We cannot trust this entry. 1172 entry_count_ = byte_count_ = 0;
1761 InternalDoomEntry(entry); 1173
1762 entry->Release(); 1174 if (!restarted_) {
1763 return NULL; 1175 buffer_bytes_ = 0;
1176 trace_object_ = TraceObject::GetTraceObject();
1177 // Create a recurrent timer of 30 secs.
1178 int timer_delay = unit_test_ ? 1000 : 30000;
1179 timer_.reset(new base::RepeatingTimer<BackendImpl>());
1180 timer_->Start(FROM_HERE, TimeDelta::FromMilliseconds(timer_delay), this,
1181 &BackendImpl::OnStatsTimer);
1764 } 1182 }
1765 1183
1766 if (!entry->Update()) { 1184 init_ = true;
1767 STRESS_NOTREACHED(); 1185 Trace("Init");
1768 entry->Release(); 1186
1769 return NULL; 1187 if (data_->header.experiment != NO_EXPERIMENT &&
1188 cache_type_ != net::DISK_CACHE) {
1189 // No experiment for other caches.
1190 return net::ERR_FAILED;
1770 } 1191 }
1771 1192
1772 // Note that it is unfortunate (but possible) for this entry to be clean, but 1193 if (!(user_flags_ & kNoRandom)) {
1773 // not actually the real entry. In other words, we could have lost this entry 1194 // The unit test controls directly what to test.
1774 // from the index, and it could have been replaced with a newer one. It's not 1195 new_eviction_ = (cache_type_ == net::DISK_CACHE);
1775 // worth checking that this entry is "the real one", so we just return it and 1196 }
1776 // let the enumeration continue; this entry will be evicted at some point, and
1777 // the regular path will work with the real entry. With time, this problem
1778 // will disasappear because this scenario is just a bug.
1779 1197
1780 // Make sure that we save the key for later. 1198 if (!CheckIndex()) {
1781 entry->GetKey(); 1199 ReportError(ERR_INIT_FAILED);
1200 return net::ERR_FAILED;
1201 }
1782 1202
1783 return entry; 1203 if (!restarted_ && (create_files || !data_->header.num_entries))
1204 ReportError(ERR_CACHE_CREATED);
1205
1206 if (!(user_flags_ & kNoRandom) && cache_type_ == net::DISK_CACHE &&
1207 !InitExperiment(&data_->header, create_files)) {
1208 return net::ERR_FAILED;
1209 }
1210
1211 // We don't care if the value overflows. The only thing we care about is that
1212 // the id cannot be zero, because that value is used as "not dirty".
1213 // Increasing the value once per second gives us many years before we start
1214 // having collisions.
1215 data_->header.this_id++;
1216 if (!data_->header.this_id)
1217 data_->header.this_id++;
1218
1219 bool previous_crash = (data_->header.crash != 0);
1220 data_->header.crash = 1;
1221
1222 if (!block_files_.Init(create_files))
1223 return net::ERR_FAILED;
1224
1225 // We want to minimize the changes to cache for an AppCache.
1226 if (cache_type() == net::APP_CACHE) {
1227 DCHECK(!new_eviction_);
1228 read_only_ = true;
1229 } else if (cache_type() == net::SHADER_CACHE) {
1230 DCHECK(!new_eviction_);
1231 }
1232
1233 eviction_.Init(this);
1234
1235 // stats_ and rankings_ may end up calling back to us so we better be enabled.
1236 disabled_ = false;
1237 if (!InitStats())
1238 return net::ERR_FAILED;
1239
1240 disabled_ = !rankings_.Init(this, new_eviction_);
1241
1242 #if defined(STRESS_CACHE_EXTENDED_VALIDATION)
1243 trace_object_->EnableTracing(false);
1244 int sc = SelfCheck();
1245 if (sc < 0 && sc != ERR_NUM_ENTRIES_MISMATCH)
1246 NOTREACHED();
1247 trace_object_->EnableTracing(true);
1248 #endif
1249
1250 if (previous_crash) {
1251 ReportError(ERR_PREVIOUS_CRASH);
1252 } else if (!restarted_) {
1253 ReportError(ERR_NO_ERROR);
1254 }
1255
1256 FlushIndex();
1257
1258 return disabled_ ? net::ERR_FAILED : net::OK;
1784 } 1259 }
1785 1260
1786 EntryImpl* BackendImpl::ResurrectEntry(EntryImpl* deleted_entry) { 1261 EntryImpl* BackendImpl::ResurrectEntry(EntryImpl* deleted_entry) {
1787 if (ENTRY_NORMAL == deleted_entry->entry()->Data()->state) { 1262 if (ENTRY_NORMAL == deleted_entry->entry()->Data()->state) {
1788 deleted_entry->Release(); 1263 deleted_entry->Release();
1789 stats_.OnEvent(Stats::CREATE_MISS); 1264 stats_.OnEvent(Stats::CREATE_MISS);
1790 Trace("create entry miss "); 1265 Trace("create entry miss ");
1791 return NULL; 1266 return NULL;
1792 } 1267 }
1793 1268
1794 // We are attempting to create an entry and found out that the entry was 1269 // We are attempting to create an entry and found out that the entry was
1795 // previously deleted. 1270 // previously deleted.
1796 1271
1797 eviction_.OnCreateEntry(deleted_entry); 1272 eviction_.OnCreateEntry(deleted_entry);
1798 entry_count_++; 1273 entry_count_++;
1799 1274
1800 stats_.OnEvent(Stats::RESURRECT_HIT); 1275 stats_.OnEvent(Stats::RESURRECT_HIT);
1801 Trace("Resurrect entry hit "); 1276 Trace("Resurrect entry hit ");
1802 return deleted_entry; 1277 return deleted_entry;
1803 } 1278 }
1804 1279
1805 void BackendImpl::DestroyInvalidEntry(EntryImpl* entry) { 1280 EntryImpl* BackendImpl::CreateEntryImpl(const std::string& key) {
1806 LOG(WARNING) << "Destroying invalid entry."; 1281 if (disabled_ || key.empty())
1807 Trace("Destroying invalid entry 0x%p", entry); 1282 return NULL;
1808 1283
1809 entry->SetPointerForInvalidEntry(GetCurrentEntryId()); 1284 TimeTicks start = TimeTicks::Now();
1285 Trace("Create hash 0x%x", hash);
1810 1286
1811 eviction_.OnDoomEntry(entry); 1287 scoped_refptr<EntryImpl> parent;
1812 entry->InternalDoom(); 1288 Addr entry_address(data_->table[hash & mask_]);
1289 if (entry_address.is_initialized()) {
1290 // We have an entry already. It could be the one we are looking for, or just
1291 // a hash conflict.
1292 bool error;
1293 EntryImpl* old_entry = MatchEntry(key, hash, false, Addr(), &error);
1294 if (old_entry)
1295 return ResurrectEntry(old_entry);
1813 1296
1814 if (!new_eviction_) 1297 EntryImpl* parent_entry = MatchEntry(key, hash, true, Addr(), &error);
1815 DecreaseNumEntries(); 1298 DCHECK(!error);
1816 stats_.OnEvent(Stats::INVALID_ENTRY); 1299 if (parent_entry) {
1817 } 1300 parent.swap(&parent_entry);
1301 } else if (data_->table[hash & mask_]) {
1302 // We should have corrected the problem.
1303 NOTREACHED();
1304 return NULL;
1305 }
1306 }
1818 1307
1819 void BackendImpl::AddStorageSize(int32 bytes) { 1308 // The general flow is to allocate disk space and initialize the entry data,
1820 data_->header.num_bytes += bytes; 1309 // followed by saving that to disk, then linking the entry though the index
1821 DCHECK_GE(data_->header.num_bytes, 0); 1310 // and finally through the lists. If there is a crash in this process, we may
1822 } 1311 // end up with:
1312 // a. Used, unreferenced empty blocks on disk (basically just garbage).
1313 // b. Used, unreferenced but meaningful data on disk (more garbage).
1314 // c. A fully formed entry, reachable only through the index.
1315 // d. A fully formed entry, also reachable through the lists, but still dirty.
1316 //
1317 // Anything after (b) can be automatically cleaned up. We may consider saving
1318 // the current operation (as we do while manipulating the lists) so that we
1319 // can detect and cleanup (a) and (b).
1823 1320
1824 void BackendImpl::SubstractStorageSize(int32 bytes) { 1321 int num_blocks = EntryImpl::NumBlocksForEntry(key.size());
1825 data_->header.num_bytes -= bytes; 1322 if (!block_files_.CreateBlock(BLOCK_256, num_blocks, &entry_address)) {
1826 DCHECK_GE(data_->header.num_bytes, 0); 1323 LOG(ERROR) << "Create entry failed " << key.c_str();
1827 } 1324 stats_.OnEvent(Stats::CREATE_ERROR);
1325 return NULL;
1326 }
1828 1327
1829 void BackendImpl::IncreaseNumRefs() { 1328 Addr node_address(0);
1830 num_refs_++; 1329 if (!block_files_.CreateBlock(RANKINGS, 1, &node_address)) {
1831 if (max_refs_ < num_refs_) 1330 block_files_.DeleteBlock(entry_address, false);
1832 max_refs_ = num_refs_; 1331 LOG(ERROR) << "Create entry failed " << key.c_str();
1833 } 1332 stats_.OnEvent(Stats::CREATE_ERROR);
1333 return NULL;
1334 }
1834 1335
1835 void BackendImpl::DecreaseNumRefs() { 1336 scoped_refptr<EntryImpl> cache_entry(
1836 DCHECK(num_refs_); 1337 new EntryImpl(this, entry_address, false));
1837 num_refs_--; 1338 IncreaseNumRefs();
1838 1339
1839 if (!num_refs_ && disabled_) 1340 if (!cache_entry->CreateEntry(node_address, key, hash)) {
1840 base::MessageLoop::current()->PostTask( 1341 block_files_.DeleteBlock(entry_address, false);
1841 FROM_HERE, base::Bind(&BackendImpl::RestartCache, GetWeakPtr(), true)); 1342 block_files_.DeleteBlock(node_address, false);
1842 } 1343 LOG(ERROR) << "Create entry failed " << key.c_str();
1344 stats_.OnEvent(Stats::CREATE_ERROR);
1345 return NULL;
1346 }
1843 1347
1844 void BackendImpl::IncreaseNumEntries() { 1348 cache_entry->BeginLogging(net_log_, true);
1845 data_->header.num_entries++;
1846 DCHECK_GT(data_->header.num_entries, 0);
1847 }
1848 1349
1849 void BackendImpl::DecreaseNumEntries() { 1350 // We are not failing the operation; let's add this to the map.
1850 data_->header.num_entries--; 1351 open_entries_[entry_address.value()] = cache_entry;
1851 if (data_->header.num_entries < 0) { 1352
1852 NOTREACHED(); 1353 // Save the entry.
1853 data_->header.num_entries = 0; 1354 cache_entry->entry()->Store();
1355 cache_entry->rankings()->Store();
1356 IncreaseNumEntries();
1357 entry_count_++;
1358
1359 // Link this entry through the index.
1360 if (parent.get()) {
1361 parent->SetNextAddress(entry_address);
1362 } else {
1363 data_->table[hash & mask_] = entry_address.value();
1854 } 1364 }
1365
1366 // Link this entry through the lists.
1367 eviction_.OnCreateEntry(cache_entry);
1368
1369 CACHE_UMA(AGE_MS, "CreateTime", 0, start);
1370 stats_.OnEvent(Stats::CREATE_HIT);
1371 SIMPLE_STATS_COUNTER("disk_cache.miss");
1372 Trace("create entry hit ");
1373 FlushIndex();
1374 cache_entry->AddRef();
1375 return cache_entry.get();
1855 } 1376 }
1856 1377
1857 void BackendImpl::LogStats() { 1378 void BackendImpl::LogStats() {
1858 StatsItems stats; 1379 StatsItems stats;
1859 GetStats(&stats); 1380 GetStats(&stats);
1860 1381
1861 for (size_t index = 0; index < stats.size(); index++) 1382 for (size_t index = 0; index < stats.size(); index++)
1862 VLOG(1) << stats[index].first << ": " << stats[index].second; 1383 VLOG(1) << stats[index].first << ": " << stats[index].second;
1863 } 1384 }
1864 1385
(...skipping 96 matching lines...) Expand 10 before | Expand all | Expand 10 after
1961 data_->header.lru.sizes[4] * 100 / data_->header.num_entries); 1482 data_->header.lru.sizes[4] * 100 / data_->header.num_entries);
1962 } 1483 }
1963 1484
1964 stats_.ResetRatios(); 1485 stats_.ResetRatios();
1965 stats_.SetCounter(Stats::TRIM_ENTRY, 0); 1486 stats_.SetCounter(Stats::TRIM_ENTRY, 0);
1966 1487
1967 if (cache_type_ == net::DISK_CACHE) 1488 if (cache_type_ == net::DISK_CACHE)
1968 block_files_.ReportStats(); 1489 block_files_.ReportStats();
1969 } 1490 }
1970 1491
1971 void BackendImpl::UpgradeTo2_1() { 1492 void BackendImpl::ReportError(int error) {
1972 // 2.1 is basically the same as 2.0, except that new fields are actually 1493 STRESS_DCHECK(!error || error == ERR_PREVIOUS_CRASH ||
1973 // updated by the new eviction algorithm. 1494 error == ERR_CACHE_CREATED);
1974 DCHECK(0x20000 == data_->header.version); 1495
1975 data_->header.version = 0x20001; 1496 // We transmit positive numbers, instead of direct error codes.
1976 data_->header.lru.sizes[Rankings::NO_USE] = data_->header.num_entries; 1497 DCHECK_LE(error, 0);
1498 CACHE_UMA(CACHE_ERROR, "Error", 0, error * -1);
1977 } 1499 }
1978 1500
1979 bool BackendImpl::CheckIndex() { 1501 bool BackendImpl::CheckIndex() {
1980 DCHECK(data_); 1502 DCHECK(data_);
1981 1503
1982 size_t current_size = index_->GetLength(); 1504 size_t current_size = index_->GetLength();
1983 if (current_size < sizeof(Index)) { 1505 if (current_size < sizeof(Index)) {
1984 LOG(ERROR) << "Corrupt Index file"; 1506 LOG(ERROR) << "Corrupt Index file";
1985 return false; 1507 return false;
1986 } 1508 }
(...skipping 122 matching lines...) Expand 10 before | Expand all | Expand 10 after
2109 if (total_memory > kMaxBuffersSize || total_memory <= 0) 1631 if (total_memory > kMaxBuffersSize || total_memory <= 0)
2110 total_memory = kMaxBuffersSize; 1632 total_memory = kMaxBuffersSize;
2111 1633
2112 done = true; 1634 done = true;
2113 } 1635 }
2114 1636
2115 return static_cast<int>(total_memory); 1637 return static_cast<int>(total_memory);
2116 } 1638 }
2117 1639
2118 } // namespace disk_cache 1640 } // namespace disk_cache
OLDNEW
« no previous file with comments | « net/disk_cache/v3/backend_impl_v3.h ('k') | net/disk_cache/v3/backend_worker.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698