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