1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/disk_cache/blockfile/backend_impl_v3.h"
8 #include "base/bind_helpers.h"
9 #include "base/file_util.h"
10 #include "base/files/file_path.h"
11 #include "base/hash.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/metrics/histogram.h"
15 #include "base/metrics/stats_counters.h"
16 #include "base/rand_util.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/sys_info.h"
20 #include "base/threading/thread_restrictions.h"
21 #include "base/time/time.h"
22 #include "base/timer/timer.h"
23 #include "net/base/net_errors.h"
24 #include "net/disk_cache/blockfile/disk_format_v3.h"
25 #include "net/disk_cache/blockfile/entry_impl_v3.h"
26 #include "net/disk_cache/blockfile/errors.h"
27 #include "net/disk_cache/blockfile/experiments.h"
28 #include "net/disk_cache/blockfile/file.h"
29 #include "net/disk_cache/blockfile/histogram_macros_v3.h"
30 #include "net/disk_cache/blockfile/index_table_v3.h"
31 #include "net/disk_cache/blockfile/storage_block-inl.h"
32 #include "net/disk_cache/cache_util.h"
34 // Provide a BackendImpl object to macros from histogram_macros.h.
35 #define CACHE_UMA_BACKEND_IMPL_OBJ this
38 using base::TimeDelta
;
39 using base::TimeTicks
;
43 #if defined(V3_NOT_JUST_YET_READY)
44 const int kDefaultCacheSize
= 80 * 1024 * 1024;
46 // Avoid trimming the cache for the first 5 minutes (10 timer ticks).
47 const int kTrimDelay
= 10;
48 #endif // defined(V3_NOT_JUST_YET_READY).
52 // ------------------------------------------------------------------------
54 namespace disk_cache
{
56 BackendImplV3::BackendImplV3(
57 const base::FilePath
& path
,
58 const scoped_refptr
<base::SingleThreadTaskRunner
>& cache_thread
,
65 cache_type_(net::DISK_CACHE
),
79 BackendImplV3::~BackendImplV3() {
83 int BackendImplV3::Init(const CompletionCallback
& callback
) {
86 return net::ERR_FAILED
;
88 return net::ERR_IO_PENDING
;
91 // ------------------------------------------------------------------------
93 #if defined(V3_NOT_JUST_YET_READY)
94 int BackendImplV3::OpenPrevEntry(void** iter
, Entry
** prev_entry
,
95 const CompletionCallback
& callback
) {
96 DCHECK(!callback
.is_null());
97 return OpenFollowingEntry(true, iter
, prev_entry
, callback
);
99 #endif // defined(V3_NOT_JUST_YET_READY).
101 bool BackendImplV3::SetMaxSize(int max_bytes
) {
102 COMPILE_ASSERT(sizeof(max_bytes
) == sizeof(max_size_
), unsupported_int_model
);
106 // Zero size means use the default.
110 // Avoid a DCHECK later on.
111 if (max_bytes
>= kint32max
- kint32max
/ 10)
112 max_bytes
= kint32max
- kint32max
/ 10 - 1;
114 user_flags_
|= MAX_SIZE
;
115 max_size_
= max_bytes
;
119 void BackendImplV3::SetType(net::CacheType type
) {
120 DCHECK_NE(net::MEMORY_CACHE
, type
);
124 bool BackendImplV3::CreateBlock(FileType block_type
, int block_count
,
125 Addr
* block_address
) {
126 return block_files_
.CreateBlock(block_type
, block_count
, block_address
);
129 #if defined(V3_NOT_JUST_YET_READY)
130 void BackendImplV3::UpdateRank(EntryImplV3
* entry
, bool modified
) {
131 if (read_only_
|| (!modified
&& cache_type() == net::SHADER_CACHE
))
133 eviction_
.UpdateRank(entry
, modified
);
136 void BackendImplV3::InternalDoomEntry(EntryImplV3
* entry
) {
137 uint32 hash
= entry
->GetHash();
138 std::string key
= entry
->GetKey();
139 Addr entry_addr
= entry
->entry()->address();
141 EntryImpl
* parent_entry
= MatchEntry(key
, hash
, true, entry_addr
, &error
);
142 CacheAddr
child(entry
->GetNextAddress());
144 Trace("Doom entry 0x%p", entry
);
146 if (!entry
->doomed()) {
147 // We may have doomed this entry from within MatchEntry.
148 eviction_
.OnDoomEntry(entry
);
149 entry
->InternalDoom();
150 if (!new_eviction_
) {
151 DecreaseNumEntries();
153 stats_
.OnEvent(Stats::DOOM_ENTRY
);
157 parent_entry
->SetNextAddress(Addr(child
));
158 parent_entry
->Release();
160 data_
->table
[hash
& mask_
] = child
;
166 void BackendImplV3::OnEntryDestroyBegin(Addr address
) {
167 EntriesMap::iterator it
= open_entries_
.find(address
.value());
168 if (it
!= open_entries_
.end())
169 open_entries_
.erase(it
);
172 void BackendImplV3::OnEntryDestroyEnd() {
174 if (data_
->header
.num_bytes
> max_size_
&& !read_only_
&&
175 (up_ticks_
> kTrimDelay
|| user_flags_
& kNoRandom
))
176 eviction_
.TrimCache(false);
179 EntryImplV3
* BackendImplV3::GetOpenEntry(Addr address
) const {
180 DCHECK(rankings
->HasData());
181 EntriesMap::const_iterator it
=
182 open_entries_
.find(rankings
->Data()->contents
);
183 if (it
!= open_entries_
.end()) {
184 // We have this entry in memory.
191 int BackendImplV3::MaxFileSize() const {
192 return max_size_
/ 8;
195 void BackendImplV3::ModifyStorageSize(int32 old_size
, int32 new_size
) {
196 if (disabled_
|| old_size
== new_size
)
198 if (old_size
> new_size
)
199 SubstractStorageSize(old_size
- new_size
);
201 AddStorageSize(new_size
- old_size
);
203 // Update the usage statistics.
204 stats_
.ModifyStorageStats(old_size
, new_size
);
207 void BackendImplV3::TooMuchStorageRequested(int32 size
) {
208 stats_
.ModifyStorageStats(0, size
);
211 bool BackendImplV3::IsAllocAllowed(int current_size
, int new_size
) {
212 DCHECK_GT(new_size
, current_size
);
213 if (user_flags_
& NO_BUFFERING
)
216 int to_add
= new_size
- current_size
;
217 if (buffer_bytes_
+ to_add
> MaxBuffersSize())
220 buffer_bytes_
+= to_add
;
221 CACHE_UMA(COUNTS_50000
, "BufferBytes", buffer_bytes_
/ 1024);
224 #endif // defined(V3_NOT_JUST_YET_READY).
226 void BackendImplV3::BufferDeleted(int size
) {
228 buffer_bytes_
-= size
;
229 DCHECK_GE(buffer_bytes_
, 0);
232 bool BackendImplV3::IsLoaded() const {
233 if (user_flags_
& NO_LOAD_PROTECTION
)
239 std::string
BackendImplV3::HistogramName(const char* name
) const {
240 static const char* names
[] = { "Http", "", "Media", "AppCache", "Shader" };
241 DCHECK_NE(cache_type_
, net::MEMORY_CACHE
);
242 return base::StringPrintf("DiskCache3.%s_%s", name
, names
[cache_type_
]);
245 base::WeakPtr
<BackendImplV3
> BackendImplV3::GetWeakPtr() {
246 return ptr_factory_
.GetWeakPtr();
249 #if defined(V3_NOT_JUST_YET_READY)
250 // We want to remove biases from some histograms so we only send data once per
252 bool BackendImplV3::ShouldReportAgain() {
254 return uma_report_
== 2;
257 int64 last_report
= stats_
.GetCounter(Stats::LAST_REPORT
);
258 Time last_time
= Time::FromInternalValue(last_report
);
259 if (!last_report
|| (Time::Now() - last_time
).InDays() >= 7) {
260 stats_
.SetCounter(Stats::LAST_REPORT
, Time::Now().ToInternalValue());
267 void BackendImplV3::FirstEviction() {
268 IndexHeaderV3
* header
= index_
.header();
269 header
->flags
|= CACHE_EVICTED
;
270 DCHECK(header
->create_time
);
271 if (!GetEntryCount())
272 return; // This is just for unit tests.
274 Time create_time
= Time::FromInternalValue(header
->create_time
);
275 CACHE_UMA(AGE
, "FillupAge", create_time
);
277 int64 use_time
= stats_
.GetCounter(Stats::TIMER
);
278 CACHE_UMA(HOURS
, "FillupTime", static_cast<int>(use_time
/ 120));
279 CACHE_UMA(PERCENTAGE
, "FirstHitRatio", stats_
.GetHitRatio());
283 CACHE_UMA(COUNTS_10000
, "FirstEntryAccessRate",
284 static_cast<int>(header
->num_entries
/ use_time
));
285 CACHE_UMA(COUNTS
, "FirstByteIORate",
286 static_cast<int>((header
->num_bytes
/ 1024) / use_time
));
288 int avg_size
= header
->num_bytes
/ GetEntryCount();
289 CACHE_UMA(COUNTS
, "FirstEntrySize", avg_size
);
291 int large_entries_bytes
= stats_
.GetLargeEntriesSize();
292 int large_ratio
= large_entries_bytes
* 100 / header
->num_bytes
;
293 CACHE_UMA(PERCENTAGE
, "FirstLargeEntriesRatio", large_ratio
);
295 if (!lru_eviction_
) {
296 CACHE_UMA(PERCENTAGE
, "FirstResurrectRatio", stats_
.GetResurrectRatio());
297 CACHE_UMA(PERCENTAGE
, "FirstNoUseRatio",
298 header
->num_no_use_entries
* 100 / header
->num_entries
);
299 CACHE_UMA(PERCENTAGE
, "FirstLowUseRatio",
300 header
->num_low_use_entries
* 100 / header
->num_entries
);
301 CACHE_UMA(PERCENTAGE
, "FirstHighUseRatio",
302 header
->num_high_use_entries
* 100 / header
->num_entries
);
305 stats_
.ResetRatios();
308 void BackendImplV3::OnEvent(Stats::Counters an_event
) {
309 stats_
.OnEvent(an_event
);
312 void BackendImplV3::OnRead(int32 bytes
) {
314 byte_count_
+= bytes
;
316 byte_count_
= kint32max
;
319 void BackendImplV3::OnWrite(int32 bytes
) {
320 // We use the same implementation as OnRead... just log the number of bytes.
324 void BackendImplV3::OnTimerTick() {
325 stats_
.OnEvent(Stats::TIMER
);
326 int64 time
= stats_
.GetCounter(Stats::TIMER
);
327 int64 current
= stats_
.GetCounter(Stats::OPEN_ENTRIES
);
329 // OPEN_ENTRIES is a sampled average of the number of open entries, avoiding
330 // the bias towards 0.
331 if (num_refs_
&& (current
!= num_refs_
)) {
332 int64 diff
= (num_refs_
- current
) / 50;
334 diff
= num_refs_
> current
? 1 : -1;
335 current
= current
+ diff
;
336 stats_
.SetCounter(Stats::OPEN_ENTRIES
, current
);
337 stats_
.SetCounter(Stats::MAX_ENTRIES
, max_refs_
);
340 CACHE_UMA(COUNTS
, "NumberOfReferences", num_refs_
);
342 CACHE_UMA(COUNTS_10000
, "EntryAccessRate", entry_count_
);
343 CACHE_UMA(COUNTS
, "ByteIORate", byte_count_
/ 1024);
345 // These values cover about 99.5% of the population (Oct 2011).
346 user_load_
= (entry_count_
> 300 || byte_count_
> 7 * 1024 * 1024);
352 first_timer_
= false;
354 first_timer_
= false;
355 if (ShouldReportAgain())
359 // Save stats to disk at 5 min intervals.
364 void BackendImplV3::SetUnitTestMode() {
365 user_flags_
|= UNIT_TEST_MODE
;
368 void BackendImplV3::SetUpgradeMode() {
369 user_flags_
|= UPGRADE_MODE
;
373 void BackendImplV3::SetNewEviction() {
374 user_flags_
|= EVICTION_V2
;
375 lru_eviction_
= false;
378 void BackendImplV3::SetFlags(uint32 flags
) {
379 user_flags_
|= flags
;
382 int BackendImplV3::FlushQueueForTest(const CompletionCallback
& callback
) {
383 background_queue_
.FlushQueue(callback
);
384 return net::ERR_IO_PENDING
;
387 void BackendImplV3::TrimForTest(bool empty
) {
388 eviction_
.SetTestMode();
389 eviction_
.TrimCache(empty
);
392 void BackendImplV3::TrimDeletedListForTest(bool empty
) {
393 eviction_
.SetTestMode();
394 eviction_
.TrimDeletedList(empty
);
397 int BackendImplV3::SelfCheck() {
399 LOG(ERROR
) << "Init failed";
400 return ERR_INIT_FAILED
;
403 int num_entries
= rankings_
.SelfCheck();
404 if (num_entries
< 0) {
405 LOG(ERROR
) << "Invalid rankings list, error " << num_entries
;
406 #if !defined(NET_BUILD_STRESS_CACHE)
411 if (num_entries
!= data_
->header
.num_entries
) {
412 LOG(ERROR
) << "Number of entries mismatch";
413 #if !defined(NET_BUILD_STRESS_CACHE)
414 return ERR_NUM_ENTRIES_MISMATCH
;
418 return CheckAllEntries();
421 // ------------------------------------------------------------------------
423 net::CacheType
BackendImplV3::GetCacheType() const {
427 int32
BackendImplV3::GetEntryCount() const {
431 return index_
.header()->num_entries
;
434 int BackendImplV3::OpenEntry(const std::string
& key
, Entry
** entry
,
435 const CompletionCallback
& callback
) {
439 TimeTicks start
= TimeTicks::Now();
440 uint32 hash
= base::Hash(key
);
441 Trace("Open hash 0x%x", hash
);
444 EntryImpl
* cache_entry
= MatchEntry(key
, hash
, false, Addr(), &error
);
445 if (cache_entry
&& ENTRY_NORMAL
!= cache_entry
->entry()->Data()->state
) {
446 // The entry was already evicted.
447 cache_entry
->Release();
451 int current_size
= data_
->header
.num_bytes
/ (1024 * 1024);
452 int64 total_hours
= stats_
.GetCounter(Stats::TIMER
) / 120;
453 int64 no_use_hours
= stats_
.GetCounter(Stats::LAST_REPORT_TIMER
) / 120;
454 int64 use_hours
= total_hours
- no_use_hours
;
457 CACHE_UMA(AGE_MS
, "OpenTime.Miss", 0, start
);
458 CACHE_UMA(COUNTS_10000
, "AllOpenBySize.Miss", 0, current_size
);
459 CACHE_UMA(HOURS
, "AllOpenByTotalHours.Miss", 0, total_hours
);
460 CACHE_UMA(HOURS
, "AllOpenByUseHours.Miss", 0, use_hours
);
461 stats_
.OnEvent(Stats::OPEN_MISS
);
465 eviction_
.OnOpenEntry(cache_entry
);
468 Trace("Open hash 0x%x end: 0x%x", hash
,
469 cache_entry
->entry()->address().value());
470 CACHE_UMA(AGE_MS
, "OpenTime", 0, start
);
471 CACHE_UMA(COUNTS_10000
, "AllOpenBySize.Hit", 0, current_size
);
472 CACHE_UMA(HOURS
, "AllOpenByTotalHours.Hit", 0, total_hours
);
473 CACHE_UMA(HOURS
, "AllOpenByUseHours.Hit", 0, use_hours
);
474 stats_
.OnEvent(Stats::OPEN_HIT
);
475 SIMPLE_STATS_COUNTER("disk_cache.hit");
479 int BackendImplV3::CreateEntry(const std::string
& key
, Entry
** entry
,
480 const CompletionCallback
& callback
) {
481 if (disabled_
|| key
.empty())
484 TimeTicks start
= TimeTicks::Now();
485 Trace("Create hash 0x%x", hash
);
487 scoped_refptr
<EntryImpl
> parent
;
488 Addr
entry_address(data_
->table
[hash
& mask_
]);
489 if (entry_address
.is_initialized()) {
490 // We have an entry already. It could be the one we are looking for, or just
493 EntryImpl
* old_entry
= MatchEntry(key
, hash
, false, Addr(), &error
);
495 return ResurrectEntry(old_entry
);
497 EntryImpl
* parent_entry
= MatchEntry(key
, hash
, true, Addr(), &error
);
500 parent
.swap(&parent_entry
);
501 } else if (data_
->table
[hash
& mask_
]) {
502 // We should have corrected the problem.
508 // The general flow is to allocate disk space and initialize the entry data,
509 // followed by saving that to disk, then linking the entry though the index
510 // and finally through the lists. If there is a crash in this process, we may
512 // a. Used, unreferenced empty blocks on disk (basically just garbage).
513 // b. Used, unreferenced but meaningful data on disk (more garbage).
514 // c. A fully formed entry, reachable only through the index.
515 // d. A fully formed entry, also reachable through the lists, but still dirty.
517 // Anything after (b) can be automatically cleaned up. We may consider saving
518 // the current operation (as we do while manipulating the lists) so that we
519 // can detect and cleanup (a) and (b).
521 int num_blocks
= EntryImpl::NumBlocksForEntry(key
.size());
522 if (!block_files_
.CreateBlock(BLOCK_256
, num_blocks
, &entry_address
)) {
523 LOG(ERROR
) << "Create entry failed " << key
.c_str();
524 stats_
.OnEvent(Stats::CREATE_ERROR
);
528 Addr
node_address(0);
529 if (!block_files_
.CreateBlock(RANKINGS
, 1, &node_address
)) {
530 block_files_
.DeleteBlock(entry_address
, false);
531 LOG(ERROR
) << "Create entry failed " << key
.c_str();
532 stats_
.OnEvent(Stats::CREATE_ERROR
);
536 scoped_refptr
<EntryImpl
> cache_entry(
537 new EntryImpl(this, entry_address
, false));
540 if (!cache_entry
->CreateEntry(node_address
, key
, hash
)) {
541 block_files_
.DeleteBlock(entry_address
, false);
542 block_files_
.DeleteBlock(node_address
, false);
543 LOG(ERROR
) << "Create entry failed " << key
.c_str();
544 stats_
.OnEvent(Stats::CREATE_ERROR
);
548 cache_entry
->BeginLogging(net_log_
, true);
550 // We are not failing the operation; let's add this to the map.
551 open_entries_
[entry_address
.value()] = cache_entry
.get();
554 cache_entry
->entry()->Store();
555 cache_entry
->rankings()->Store();
556 IncreaseNumEntries();
559 // Link this entry through the index.
561 parent
->SetNextAddress(entry_address
);
563 data_
->table
[hash
& mask_
] = entry_address
.value();
566 // Link this entry through the lists.
567 eviction_
.OnCreateEntry(cache_entry
.get());
569 CACHE_UMA(AGE_MS
, "CreateTime", 0, start
);
570 stats_
.OnEvent(Stats::CREATE_HIT
);
571 SIMPLE_STATS_COUNTER("disk_cache.miss");
572 Trace("create entry hit ");
574 cache_entry
->AddRef();
575 return cache_entry
.get();
578 int BackendImplV3::DoomEntry(const std::string
& key
,
579 const CompletionCallback
& callback
) {
581 return net::ERR_FAILED
;
583 EntryImpl
* entry
= OpenEntryImpl(key
);
585 return net::ERR_FAILED
;
592 int BackendImplV3::DoomAllEntries(const CompletionCallback
& callback
) {
593 // This is not really an error, but it is an interesting condition.
594 ReportError(ERR_CACHE_DOOMED
);
595 stats_
.OnEvent(Stats::DOOM_CACHE
);
598 return disabled_
? net::ERR_FAILED
: net::OK
;
601 return net::ERR_FAILED
;
603 eviction_
.TrimCache(true);
608 int BackendImplV3::DoomEntriesBetween(base::Time initial_time
,
610 const CompletionCallback
& callback
) {
611 DCHECK_NE(net::APP_CACHE
, cache_type_
);
612 if (end_time
.is_null())
613 return SyncDoomEntriesSince(initial_time
);
615 DCHECK(end_time
>= initial_time
);
618 return net::ERR_FAILED
;
622 EntryImpl
* next
= OpenNextEntryImpl(&iter
);
628 next
= OpenNextEntryImpl(&iter
);
630 if (node
->GetLastUsed() >= initial_time
&&
631 node
->GetLastUsed() < end_time
) {
633 } else if (node
->GetLastUsed() < initial_time
) {
637 SyncEndEnumeration(iter
);
646 int BackendImplV3::DoomEntriesSince(base::Time initial_time
,
647 const CompletionCallback
& callback
) {
648 DCHECK_NE(net::APP_CACHE
, cache_type_
);
650 return net::ERR_FAILED
;
652 stats_
.OnEvent(Stats::DOOM_RECENT
);
655 EntryImpl
* entry
= OpenNextEntryImpl(&iter
);
659 if (initial_time
> entry
->GetLastUsed()) {
661 SyncEndEnumeration(iter
);
667 SyncEndEnumeration(iter
); // Dooming the entry invalidates the iterator.
671 int BackendImplV3::OpenNextEntry(void** iter
, Entry
** next_entry
,
672 const CompletionCallback
& callback
) {
673 DCHECK(!callback
.is_null());
674 background_queue_
.OpenNextEntry(iter
, next_entry
, callback
);
675 return net::ERR_IO_PENDING
;
678 void BackendImplV3::EndEnumeration(void** iter
) {
679 scoped_ptr
<IndexIterator
> iterator(
680 reinterpret_cast<IndexIterator
*>(*iter
));
684 void BackendImplV3::GetStats(StatsItems
* stats
) {
688 std::pair
<std::string
, std::string
> item
;
690 item
.first
= "Entries";
691 item
.second
= base::StringPrintf("%d", data_
->header
.num_entries
);
692 stats
->push_back(item
);
694 item
.first
= "Pending IO";
695 item
.second
= base::StringPrintf("%d", num_pending_io_
);
696 stats
->push_back(item
);
698 item
.first
= "Max size";
699 item
.second
= base::StringPrintf("%d", max_size_
);
700 stats
->push_back(item
);
702 item
.first
= "Current size";
703 item
.second
= base::StringPrintf("%d", data_
->header
.num_bytes
);
704 stats
->push_back(item
);
706 item
.first
= "Cache type";
707 item
.second
= "Blockfile Cache";
708 stats
->push_back(item
);
710 stats_
.GetItems(stats
);
713 void BackendImplV3::OnExternalCacheHit(const std::string
& key
) {
717 uint32 hash
= base::Hash(key
);
719 EntryImpl
* cache_entry
= MatchEntry(key
, hash
, false, Addr(), &error
);
721 if (ENTRY_NORMAL
== cache_entry
->entry()->Data()->state
) {
722 UpdateRank(cache_entry
, cache_type() == net::SHADER_CACHE
);
724 cache_entry
->Release();
728 // ------------------------------------------------------------------------
730 // The maximum cache size will be either set explicitly by the caller, or
731 // calculated by this code.
732 void BackendImplV3::AdjustMaxCacheSize(int table_len
) {
736 // If table_len is provided, the index file exists.
737 DCHECK(!table_len
|| data_
->header
.magic
);
739 // The user is not setting the size, let's figure it out.
740 int64 available
= base::SysInfo::AmountOfFreeDiskSpace(path_
);
742 max_size_
= kDefaultCacheSize
;
747 available
+= data_
->header
.num_bytes
;
749 max_size_
= PreferedCacheSize(available
);
751 // Let's not use more than the default size while we tune-up the performance
752 // of bigger caches. TODO(rvargas): remove this limit.
753 if (max_size_
> kDefaultCacheSize
* 4)
754 max_size_
= kDefaultCacheSize
* 4;
759 // If we already have a table, adjust the size to it.
760 int current_max_size
= MaxStorageSizeForTable(table_len
);
761 if (max_size_
> current_max_size
)
762 max_size_
= current_max_size
;
765 bool BackendImplV3::InitStats() {
766 Addr
address(data_
->header
.stats
);
767 int size
= stats_
.StorageSize();
769 if (!address
.is_initialized()) {
770 FileType file_type
= Addr::RequiredFileType(size
);
771 DCHECK_NE(file_type
, EXTERNAL
);
772 int num_blocks
= Addr::RequiredBlocks(size
, file_type
);
774 if (!CreateBlock(file_type
, num_blocks
, &address
))
776 return stats_
.Init(NULL
, 0, address
);
779 if (!address
.is_block_file()) {
784 // Load the required data.
785 size
= address
.num_blocks() * address
.BlockSize();
786 MappedFile
* file
= File(address
);
790 scoped_ptr
<char[]> data(new char[size
]);
791 size_t offset
= address
.start_block() * address
.BlockSize() +
793 if (!file
->Read(data
.get(), size
, offset
))
796 if (!stats_
.Init(data
.get(), size
, address
))
798 if (cache_type_
== net::DISK_CACHE
&& ShouldReportAgain())
799 stats_
.InitSizeHistogram();
803 void BackendImplV3::StoreStats() {
804 int size
= stats_
.StorageSize();
805 scoped_ptr
<char[]> data(new char[size
]);
807 size
= stats_
.SerializeStats(data
.get(), size
, &address
);
809 if (!address
.is_initialized())
812 MappedFile
* file
= File(address
);
816 size_t offset
= address
.start_block() * address
.BlockSize() +
818 file
->Write(data
.get(), size
, offset
); // ignore result.
821 void BackendImplV3::RestartCache(bool failure
) {
822 int64 errors
= stats_
.GetCounter(Stats::FATAL_ERROR
);
823 int64 full_dooms
= stats_
.GetCounter(Stats::DOOM_CACHE
);
824 int64 partial_dooms
= stats_
.GetCounter(Stats::DOOM_RECENT
);
825 int64 last_report
= stats_
.GetCounter(Stats::LAST_REPORT
);
830 DCHECK(!open_entries_
.size());
831 DelayedCacheCleanup(path_
);
833 DeleteCache(path_
, false);
836 // Don't call Init() if directed by the unit test: we are simulating a failure
837 // trying to re-enable the cache.
839 init_
= true; // Let the destructor do proper cleanup.
840 else if (SyncInit() == net::OK
) {
841 stats_
.SetCounter(Stats::FATAL_ERROR
, errors
);
842 stats_
.SetCounter(Stats::DOOM_CACHE
, full_dooms
);
843 stats_
.SetCounter(Stats::DOOM_RECENT
, partial_dooms
);
844 stats_
.SetCounter(Stats::LAST_REPORT
, last_report
);
848 void BackendImplV3::PrepareForRestart() {
849 if (!(user_flags_
& EVICTION_V2
))
850 lru_eviction_
= true;
853 data_
->header
.crash
= 0;
857 block_files_
.CloseFiles();
863 void BackendImplV3::CleanupCache() {
864 Trace("Backend Cleanup");
871 data_
->header
.crash
= 0;
873 if (user_flags_
& kNoRandom
) {
874 // This is a net_unittest, verify that we are not 'leaking' entries.
875 File::WaitForPendingIO(&num_pending_io_
);
878 File::DropPendingIO();
881 block_files_
.CloseFiles();
884 ptr_factory_
.InvalidateWeakPtrs();
888 int BackendImplV3::NewEntry(Addr address
, EntryImplV3
** entry
) {
889 EntriesMap::iterator it
= open_entries_
.find(address
.value());
890 if (it
!= open_entries_
.end()) {
891 // Easy job. This entry is already in memory.
892 EntryImpl
* this_entry
= it
->second
;
893 this_entry
->AddRef();
898 STRESS_DCHECK(block_files_
.IsValid(address
));
900 if (!address
.SanityCheckForEntry()) {
901 LOG(WARNING
) << "Wrong entry address.";
903 return ERR_INVALID_ADDRESS
;
906 scoped_refptr
<EntryImpl
> cache_entry(
907 new EntryImpl(this, address
, read_only_
));
911 TimeTicks start
= TimeTicks::Now();
912 if (!cache_entry
->entry()->Load())
913 return ERR_READ_FAILURE
;
916 CACHE_UMA(AGE_MS
, "LoadTime", 0, start
);
919 if (!cache_entry
->SanityCheck()) {
920 LOG(WARNING
) << "Messed up entry found.";
922 return ERR_INVALID_ENTRY
;
925 STRESS_DCHECK(block_files_
.IsValid(
926 Addr(cache_entry
->entry()->Data()->rankings_node
)));
928 if (!cache_entry
->LoadNodeAddress())
929 return ERR_READ_FAILURE
;
931 if (!rankings_
.SanityCheck(cache_entry
->rankings(), false)) {
933 cache_entry
->SetDirtyFlag(0);
934 // Don't remove this from the list (it is not linked properly). Instead,
935 // break the link back to the entry because it is going away, and leave the
936 // rankings node to be deleted if we find it through a list.
937 rankings_
.SetContents(cache_entry
->rankings(), 0);
938 } else if (!rankings_
.DataSanityCheck(cache_entry
->rankings(), false)) {
940 cache_entry
->SetDirtyFlag(0);
941 rankings_
.SetContents(cache_entry
->rankings(), address
.value());
944 if (!cache_entry
->DataSanityCheck()) {
945 LOG(WARNING
) << "Messed up entry found.";
946 cache_entry
->SetDirtyFlag(0);
947 cache_entry
->FixForDelete();
950 // Prevent overwriting the dirty flag on the destructor.
951 cache_entry
->SetDirtyFlag(GetCurrentEntryId());
953 if (cache_entry
->dirty()) {
954 Trace("Dirty entry 0x%p 0x%x", reinterpret_cast<void*>(cache_entry
.get()),
958 open_entries_
[address
.value()] = cache_entry
.get();
960 cache_entry
->BeginLogging(net_log_
, false);
961 cache_entry
.swap(entry
);
965 // This is the actual implementation for OpenNextEntry and OpenPrevEntry.
966 int BackendImplV3::OpenFollowingEntry(bool forward
, void** iter
,
968 const CompletionCallback
& callback
) {
970 return net::ERR_FAILED
;
974 const int kListsToSearch
= 3;
975 scoped_refptr
<EntryImpl
> entries
[kListsToSearch
];
976 scoped_ptr
<Rankings::Iterator
> iterator(
977 reinterpret_cast<Rankings::Iterator
*>(*iter
));
980 if (!iterator
.get()) {
981 iterator
.reset(new Rankings::Iterator(&rankings_
));
984 // Get an entry from each list.
985 for (int i
= 0; i
< kListsToSearch
; i
++) {
986 EntryImpl
* temp
= NULL
;
987 ret
|= OpenFollowingEntryFromList(forward
, static_cast<Rankings::List
>(i
),
988 &iterator
->nodes
[i
], &temp
);
989 entries
[i
].swap(&temp
); // The entry was already addref'd.
994 // Get the next entry from the last list, and the actual entries for the
995 // elements on the other lists.
996 for (int i
= 0; i
< kListsToSearch
; i
++) {
997 EntryImpl
* temp
= NULL
;
998 if (iterator
->list
== i
) {
999 OpenFollowingEntryFromList(forward
, iterator
->list
,
1000 &iterator
->nodes
[i
], &temp
);
1002 temp
= GetEnumeratedEntry(iterator
->nodes
[i
],
1003 static_cast<Rankings::List
>(i
));
1006 entries
[i
].swap(&temp
); // The entry was already addref'd.
1012 Time access_times
[kListsToSearch
];
1013 for (int i
= 0; i
< kListsToSearch
; i
++) {
1014 if (entries
[i
].get()) {
1015 access_times
[i
] = entries
[i
]->GetLastUsed();
1017 DCHECK_LT(oldest
, 0);
1018 newest
= oldest
= i
;
1021 if (access_times
[i
] > access_times
[newest
])
1023 if (access_times
[i
] < access_times
[oldest
])
1028 if (newest
< 0 || oldest
< 0)
1031 EntryImpl
* next_entry
;
1033 next_entry
= entries
[newest
].get();
1034 iterator
->list
= static_cast<Rankings::List
>(newest
);
1036 next_entry
= entries
[oldest
].get();
1037 iterator
->list
= static_cast<Rankings::List
>(oldest
);
1040 *iter
= iterator
.release();
1041 next_entry
->AddRef();
1045 void BackendImplV3::AddStorageSize(int32 bytes
) {
1046 data_
->header
.num_bytes
+= bytes
;
1047 DCHECK_GE(data_
->header
.num_bytes
, 0);
1050 void BackendImplV3::SubstractStorageSize(int32 bytes
) {
1051 data_
->header
.num_bytes
-= bytes
;
1052 DCHECK_GE(data_
->header
.num_bytes
, 0);
1055 void BackendImplV3::IncreaseNumRefs() {
1057 if (max_refs_
< num_refs_
)
1058 max_refs_
= num_refs_
;
1061 void BackendImplV3::DecreaseNumRefs() {
1065 if (!num_refs_
&& disabled_
)
1066 base::MessageLoop::current()->PostTask(
1067 FROM_HERE
, base::Bind(&BackendImpl::RestartCache
, GetWeakPtr(), true));
1070 void BackendImplV3::IncreaseNumEntries() {
1071 index_
.header()->num_entries
++;
1072 DCHECK_GT(index_
.header()->num_entries
, 0);
1075 void BackendImplV3::DecreaseNumEntries() {
1076 index_
.header()->num_entries
--;
1077 if (index_
.header()->num_entries
< 0) {
1079 index_
.header()->num_entries
= 0;
1083 int BackendImplV3::SyncInit() {
1084 #if defined(NET_BUILD_STRESS_CACHE)
1085 // Start evictions right away.
1086 up_ticks_
= kTrimDelay
* 2;
1090 return net::ERR_FAILED
;
1092 bool create_files
= false;
1093 if (!InitBackingStore(&create_files
)) {
1094 ReportError(ERR_STORAGE_ERROR
);
1095 return net::ERR_FAILED
;
1098 num_refs_
= num_pending_io_
= max_refs_
= 0;
1099 entry_count_
= byte_count_
= 0;
1103 trace_object_
= TraceObject::GetTraceObject();
1104 // Create a recurrent timer of 30 secs.
1105 int timer_delay
= unit_test_
? 1000 : 30000;
1106 timer_
.reset(new base::RepeatingTimer
<BackendImplV3
>());
1107 timer_
->Start(FROM_HERE
, TimeDelta::FromMilliseconds(timer_delay
), this,
1108 &BackendImplV3::OnStatsTimer
);
1114 if (data_
->header
.experiment
!= NO_EXPERIMENT
&&
1115 cache_type_
!= net::DISK_CACHE
) {
1116 // No experiment for other caches.
1117 return net::ERR_FAILED
;
1120 if (!(user_flags_
& kNoRandom
)) {
1121 // The unit test controls directly what to test.
1122 new_eviction_
= (cache_type_
== net::DISK_CACHE
);
1125 if (!CheckIndex()) {
1126 ReportError(ERR_INIT_FAILED
);
1127 return net::ERR_FAILED
;
1130 if (!restarted_
&& (create_files
|| !data_
->header
.num_entries
))
1131 ReportError(ERR_CACHE_CREATED
);
1133 if (!(user_flags_
& kNoRandom
) && cache_type_
== net::DISK_CACHE
&&
1134 !InitExperiment(&data_
->header
, create_files
)) {
1135 return net::ERR_FAILED
;
1138 // We don't care if the value overflows. The only thing we care about is that
1139 // the id cannot be zero, because that value is used as "not dirty".
1140 // Increasing the value once per second gives us many years before we start
1141 // having collisions.
1142 data_
->header
.this_id
++;
1143 if (!data_
->header
.this_id
)
1144 data_
->header
.this_id
++;
1146 bool previous_crash
= (data_
->header
.crash
!= 0);
1147 data_
->header
.crash
= 1;
1149 if (!block_files_
.Init(create_files
))
1150 return net::ERR_FAILED
;
1152 // We want to minimize the changes to cache for an AppCache.
1153 if (cache_type() == net::APP_CACHE
) {
1154 DCHECK(!new_eviction_
);
1156 } else if (cache_type() == net::SHADER_CACHE
) {
1157 DCHECK(!new_eviction_
);
1160 eviction_
.Init(this);
1162 // stats_ and rankings_ may end up calling back to us so we better be enabled.
1165 return net::ERR_FAILED
;
1167 disabled_
= !rankings_
.Init(this, new_eviction_
);
1169 #if defined(STRESS_CACHE_EXTENDED_VALIDATION)
1170 trace_object_
->EnableTracing(false);
1171 int sc
= SelfCheck();
1172 if (sc
< 0 && sc
!= ERR_NUM_ENTRIES_MISMATCH
)
1174 trace_object_
->EnableTracing(true);
1177 if (previous_crash
) {
1178 ReportError(ERR_PREVIOUS_CRASH
);
1179 } else if (!restarted_
) {
1180 ReportError(ERR_NO_ERROR
);
1185 return disabled_
? net::ERR_FAILED
: net::OK
;
1188 EntryImpl
* BackendImplV3::ResurrectEntry(EntryImpl
* deleted_entry
) {
1189 if (ENTRY_NORMAL
== deleted_entry
->entry()->Data()->state
) {
1190 deleted_entry
->Release();
1191 stats_
.OnEvent(Stats::CREATE_MISS
);
1192 Trace("create entry miss ");
1196 // We are attempting to create an entry and found out that the entry was
1197 // previously deleted.
1199 eviction_
.OnCreateEntry(deleted_entry
);
1202 stats_
.OnEvent(Stats::RESURRECT_HIT
);
1203 Trace("Resurrect entry hit ");
1204 return deleted_entry
;
1207 EntryImpl
* BackendImplV3::CreateEntryImpl(const std::string
& key
) {
1208 if (disabled_
|| key
.empty())
1211 TimeTicks start
= TimeTicks::Now();
1212 Trace("Create hash 0x%x", hash
);
1214 scoped_refptr
<EntryImpl
> parent
;
1215 Addr
entry_address(data_
->table
[hash
& mask_
]);
1216 if (entry_address
.is_initialized()) {
1217 // We have an entry already. It could be the one we are looking for, or just
1220 EntryImpl
* old_entry
= MatchEntry(key
, hash
, false, Addr(), &error
);
1222 return ResurrectEntry(old_entry
);
1224 EntryImpl
* parent_entry
= MatchEntry(key
, hash
, true, Addr(), &error
);
1227 parent
.swap(&parent_entry
);
1228 } else if (data_
->table
[hash
& mask_
]) {
1229 // We should have corrected the problem.
1235 // The general flow is to allocate disk space and initialize the entry data,
1236 // followed by saving that to disk, then linking the entry though the index
1237 // and finally through the lists. If there is a crash in this process, we may
1239 // a. Used, unreferenced empty blocks on disk (basically just garbage).
1240 // b. Used, unreferenced but meaningful data on disk (more garbage).
1241 // c. A fully formed entry, reachable only through the index.
1242 // d. A fully formed entry, also reachable through the lists, but still dirty.
1244 // Anything after (b) can be automatically cleaned up. We may consider saving
1245 // the current operation (as we do while manipulating the lists) so that we
1246 // can detect and cleanup (a) and (b).
1248 int num_blocks
= EntryImpl::NumBlocksForEntry(key
.size());
1249 if (!block_files_
.CreateBlock(BLOCK_256
, num_blocks
, &entry_address
)) {
1250 LOG(ERROR
) << "Create entry failed " << key
.c_str();
1251 stats_
.OnEvent(Stats::CREATE_ERROR
);
1255 Addr
node_address(0);
1256 if (!block_files_
.CreateBlock(RANKINGS
, 1, &node_address
)) {
1257 block_files_
.DeleteBlock(entry_address
, false);
1258 LOG(ERROR
) << "Create entry failed " << key
.c_str();
1259 stats_
.OnEvent(Stats::CREATE_ERROR
);
1263 scoped_refptr
<EntryImpl
> cache_entry(
1264 new EntryImpl(this, entry_address
, false));
1267 if (!cache_entry
->CreateEntry(node_address
, key
, hash
)) {
1268 block_files_
.DeleteBlock(entry_address
, false);
1269 block_files_
.DeleteBlock(node_address
, false);
1270 LOG(ERROR
) << "Create entry failed " << key
.c_str();
1271 stats_
.OnEvent(Stats::CREATE_ERROR
);
1275 cache_entry
->BeginLogging(net_log_
, true);
1277 // We are not failing the operation; let's add this to the map.
1278 open_entries_
[entry_address
.value()] = cache_entry
;
1281 cache_entry
->entry()->Store();
1282 cache_entry
->rankings()->Store();
1283 IncreaseNumEntries();
1286 // Link this entry through the index.
1288 parent
->SetNextAddress(entry_address
);
1290 data_
->table
[hash
& mask_
] = entry_address
.value();
1293 // Link this entry through the lists.
1294 eviction_
.OnCreateEntry(cache_entry
);
1296 CACHE_UMA(AGE_MS
, "CreateTime", 0, start
);
1297 stats_
.OnEvent(Stats::CREATE_HIT
);
1298 SIMPLE_STATS_COUNTER("disk_cache.miss");
1299 Trace("create entry hit ");
1301 cache_entry
->AddRef();
1302 return cache_entry
.get();
1305 void BackendImplV3::LogStats() {
1309 for (size_t index
= 0; index
< stats
.size(); index
++)
1310 VLOG(1) << stats
[index
].first
<< ": " << stats
[index
].second
;
1313 void BackendImplV3::ReportStats() {
1314 IndexHeaderV3
* header
= index_
.header();
1315 CACHE_UMA(COUNTS
, "Entries", header
->num_entries
);
1317 int current_size
= header
->num_bytes
/ (1024 * 1024);
1318 int max_size
= max_size_
/ (1024 * 1024);
1320 CACHE_UMA(COUNTS_10000
, "Size", current_size
);
1321 CACHE_UMA(COUNTS_10000
, "MaxSize", max_size
);
1324 CACHE_UMA(PERCENTAGE
, "UsedSpace", current_size
* 100 / max_size
);
1326 CACHE_UMA(COUNTS_10000
, "AverageOpenEntries",
1327 static_cast<int>(stats_
.GetCounter(Stats::OPEN_ENTRIES
)));
1328 CACHE_UMA(COUNTS_10000
, "MaxOpenEntries",
1329 static_cast<int>(stats_
.GetCounter(Stats::MAX_ENTRIES
)));
1330 stats_
.SetCounter(Stats::MAX_ENTRIES
, 0);
1332 CACHE_UMA(COUNTS_10000
, "TotalFatalErrors",
1333 static_cast<int>(stats_
.GetCounter(Stats::FATAL_ERROR
)));
1334 CACHE_UMA(COUNTS_10000
, "TotalDoomCache",
1335 static_cast<int>(stats_
.GetCounter(Stats::DOOM_CACHE
)));
1336 CACHE_UMA(COUNTS_10000
, "TotalDoomRecentEntries",
1337 static_cast<int>(stats_
.GetCounter(Stats::DOOM_RECENT
)));
1338 stats_
.SetCounter(Stats::FATAL_ERROR
, 0);
1339 stats_
.SetCounter(Stats::DOOM_CACHE
, 0);
1340 stats_
.SetCounter(Stats::DOOM_RECENT
, 0);
1342 int64 total_hours
= stats_
.GetCounter(Stats::TIMER
) / 120;
1343 if (!(header
->flags
& CACHE_EVICTED
)) {
1344 CACHE_UMA(HOURS
, "TotalTimeNotFull", static_cast<int>(total_hours
));
1348 // This is an up to date client that will report FirstEviction() data. After
1349 // that event, start reporting this:
1351 CACHE_UMA(HOURS
, "TotalTime", static_cast<int>(total_hours
));
1353 int64 use_hours
= stats_
.GetCounter(Stats::LAST_REPORT_TIMER
) / 120;
1354 stats_
.SetCounter(Stats::LAST_REPORT_TIMER
, stats_
.GetCounter(Stats::TIMER
));
1356 // We may see users with no use_hours at this point if this is the first time
1357 // we are running this code.
1359 use_hours
= total_hours
- use_hours
;
1361 if (!use_hours
|| !GetEntryCount() || !header
->num_bytes
)
1364 CACHE_UMA(HOURS
, "UseTime", static_cast<int>(use_hours
));
1366 int64 trim_rate
= stats_
.GetCounter(Stats::TRIM_ENTRY
) / use_hours
;
1367 CACHE_UMA(COUNTS
, "TrimRate", static_cast<int>(trim_rate
));
1369 int avg_size
= header
->num_bytes
/ GetEntryCount();
1370 CACHE_UMA(COUNTS
, "EntrySize", avg_size
);
1371 CACHE_UMA(COUNTS
, "EntriesFull", header
->num_entries
);
1373 int large_entries_bytes
= stats_
.GetLargeEntriesSize();
1374 int large_ratio
= large_entries_bytes
* 100 / header
->num_bytes
;
1375 CACHE_UMA(PERCENTAGE
, "LargeEntriesRatio", large_ratio
);
1377 if (!lru_eviction_
) {
1378 CACHE_UMA(PERCENTAGE
, "ResurrectRatio", stats_
.GetResurrectRatio());
1379 CACHE_UMA(PERCENTAGE
, "NoUseRatio",
1380 header
->num_no_use_entries
* 100 / header
->num_entries
);
1381 CACHE_UMA(PERCENTAGE
, "LowUseRatio",
1382 header
->num_low_use_entries
* 100 / header
->num_entries
);
1383 CACHE_UMA(PERCENTAGE
, "HighUseRatio",
1384 header
->num_high_use_entries
* 100 / header
->num_entries
);
1385 CACHE_UMA(PERCENTAGE
, "DeletedRatio",
1386 header
->num_evicted_entries
* 100 / header
->num_entries
);
1389 stats_
.ResetRatios();
1390 stats_
.SetCounter(Stats::TRIM_ENTRY
, 0);
1392 if (cache_type_
== net::DISK_CACHE
)
1393 block_files_
.ReportStats();
1396 void BackendImplV3::ReportError(int error
) {
1397 STRESS_DCHECK(!error
|| error
== ERR_PREVIOUS_CRASH
||
1398 error
== ERR_CACHE_CREATED
);
1400 // We transmit positive numbers, instead of direct error codes.
1401 DCHECK_LE(error
, 0);
1402 CACHE_UMA(CACHE_ERROR
, "Error", error
* -1);
1405 bool BackendImplV3::CheckIndex() {
1408 size_t current_size
= index_
->GetLength();
1409 if (current_size
< sizeof(Index
)) {
1410 LOG(ERROR
) << "Corrupt Index file";
1414 if (new_eviction_
) {
1415 // We support versions 2.0 and 2.1, upgrading 2.0 to 2.1.
1416 if (kIndexMagic
!= data_
->header
.magic
||
1417 kCurrentVersion
>> 16 != data_
->header
.version
>> 16) {
1418 LOG(ERROR
) << "Invalid file version or magic";
1421 if (kCurrentVersion
== data_
->header
.version
) {
1422 // We need file version 2.1 for the new eviction algorithm.
1426 if (kIndexMagic
!= data_
->header
.magic
||
1427 kCurrentVersion
!= data_
->header
.version
) {
1428 LOG(ERROR
) << "Invalid file version or magic";
1433 if (!data_
->header
.table_len
) {
1434 LOG(ERROR
) << "Invalid table size";
1438 if (current_size
< GetIndexSize(data_
->header
.table_len
) ||
1439 data_
->header
.table_len
& (kBaseTableLen
- 1)) {
1440 LOG(ERROR
) << "Corrupt Index file";
1444 AdjustMaxCacheSize(data_
->header
.table_len
);
1446 #if !defined(NET_BUILD_STRESS_CACHE)
1447 if (data_
->header
.num_bytes
< 0 ||
1448 (max_size_
< kint32max
- kDefaultCacheSize
&&
1449 data_
->header
.num_bytes
> max_size_
+ kDefaultCacheSize
)) {
1450 LOG(ERROR
) << "Invalid cache (current) size";
1455 if (data_
->header
.num_entries
< 0) {
1456 LOG(ERROR
) << "Invalid number of entries";
1461 mask_
= data_
->header
.table_len
- 1;
1463 // Load the table into memory with a single read.
1464 scoped_ptr
<char[]> buf(new char[current_size
]);
1465 return index_
->Read(buf
.get(), current_size
, 0);
1468 int BackendImplV3::CheckAllEntries() {
1470 int num_entries
= 0;
1471 DCHECK(mask_
< kuint32max
);
1472 for (unsigned int i
= 0; i
<= mask_
; i
++) {
1473 Addr
address(data_
->table
[i
]);
1474 if (!address
.is_initialized())
1478 int ret
= NewEntry(address
, &tmp
);
1480 STRESS_NOTREACHED();
1483 scoped_refptr
<EntryImpl
> cache_entry
;
1484 cache_entry
.swap(&tmp
);
1486 if (cache_entry
->dirty())
1488 else if (CheckEntry(cache_entry
.get()))
1491 return ERR_INVALID_ENTRY
;
1493 DCHECK_EQ(i
, cache_entry
->entry()->Data()->hash
& mask_
);
1494 address
.set_value(cache_entry
->GetNextAddress());
1495 if (!address
.is_initialized())
1500 Trace("CheckAllEntries End");
1501 if (num_entries
+ num_dirty
!= data_
->header
.num_entries
) {
1502 LOG(ERROR
) << "Number of entries " << num_entries
<< " " << num_dirty
<<
1503 " " << data_
->header
.num_entries
;
1504 DCHECK_LT(num_entries
, data_
->header
.num_entries
);
1505 return ERR_NUM_ENTRIES_MISMATCH
;
1511 bool BackendImplV3::CheckEntry(EntryImpl
* cache_entry
) {
1512 bool ok
= block_files_
.IsValid(cache_entry
->entry()->address());
1513 ok
= ok
&& block_files_
.IsValid(cache_entry
->rankings()->address());
1514 EntryStore
* data
= cache_entry
->entry()->Data();
1515 for (size_t i
= 0; i
< arraysize(data
->data_addr
); i
++) {
1516 if (data
->data_addr
[i
]) {
1517 Addr
address(data
->data_addr
[i
]);
1518 if (address
.is_block_file())
1519 ok
= ok
&& block_files_
.IsValid(address
);
1523 return ok
&& cache_entry
->rankings()->VerifyHash();
1526 int BackendImplV3::MaxBuffersSize() {
1527 static int64 total_memory
= base::SysInfo::AmountOfPhysicalMemory();
1528 static bool done
= false;
1531 const int kMaxBuffersSize
= 30 * 1024 * 1024;
1533 // We want to use up to 2% of the computer's memory.
1534 total_memory
= total_memory
* 2 / 100;
1535 if (total_memory
> kMaxBuffersSize
|| total_memory
<= 0)
1536 total_memory
= kMaxBuffersSize
;
1541 return static_cast<int>(total_memory
);
1544 #endif // defined(V3_NOT_JUST_YET_READY).
1546 bool BackendImplV3::IsAllocAllowed(int current_size
, int new_size
) {
1550 net::CacheType
BackendImplV3::GetCacheType() const {
1554 int32
BackendImplV3::GetEntryCount() const {
1558 int BackendImplV3::OpenEntry(const std::string
& key
, Entry
** entry
,
1559 const CompletionCallback
& callback
) {
1560 return net::ERR_FAILED
;
1563 int BackendImplV3::CreateEntry(const std::string
& key
, Entry
** entry
,
1564 const CompletionCallback
& callback
) {
1565 return net::ERR_FAILED
;
1568 int BackendImplV3::DoomEntry(const std::string
& key
,
1569 const CompletionCallback
& callback
) {
1570 return net::ERR_FAILED
;
1573 int BackendImplV3::DoomAllEntries(const CompletionCallback
& callback
) {
1574 return net::ERR_FAILED
;
1577 int BackendImplV3::DoomEntriesBetween(base::Time initial_time
,
1578 base::Time end_time
,
1579 const CompletionCallback
& callback
) {
1580 return net::ERR_FAILED
;
1583 int BackendImplV3::DoomEntriesSince(base::Time initial_time
,
1584 const CompletionCallback
& callback
) {
1585 return net::ERR_FAILED
;
1588 int BackendImplV3::OpenNextEntry(void** iter
, Entry
** next_entry
,
1589 const CompletionCallback
& callback
) {
1590 return net::ERR_FAILED
;
1593 void BackendImplV3::EndEnumeration(void** iter
) {
1597 void BackendImplV3::GetStats(StatsItems
* stats
) {
1601 void BackendImplV3::OnExternalCacheHit(const std::string
& key
) {
1605 void BackendImplV3::CleanupCache() {
1608 } // namespace disk_cache