forked from sanyaade-mobiledev/chromium.src
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend_impl.cc
2119 lines (1744 loc) · 60.8 KB
/
backend_impl.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/disk_cache/backend_impl.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/hash.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram.h"
#include "base/metrics/stats_counters.h"
#include "base/rand_util.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/sys_info.h"
#include "base/threading/thread_restrictions.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "net/base/net_errors.h"
#include "net/disk_cache/cache_util.h"
#include "net/disk_cache/disk_format.h"
#include "net/disk_cache/entry_impl.h"
#include "net/disk_cache/errors.h"
#include "net/disk_cache/experiments.h"
#include "net/disk_cache/file.h"
// This has to be defined before including histogram_macros.h from this file.
#define NET_DISK_CACHE_BACKEND_IMPL_CC_
#include "net/disk_cache/histogram_macros.h"
using base::Time;
using base::TimeDelta;
using base::TimeTicks;
namespace {
const char* kIndexName = "index";
// Seems like ~240 MB correspond to less than 50k entries for 99% of the people.
// Note that the actual target is to keep the index table load factor under 55%
// for most users.
const int k64kEntriesStore = 240 * 1000 * 1000;
const int kBaseTableLen = 64 * 1024;
const int kDefaultCacheSize = 80 * 1024 * 1024;
// Avoid trimming the cache for the first 5 minutes (10 timer ticks).
const int kTrimDelay = 10;
int DesiredIndexTableLen(int32 storage_size) {
if (storage_size <= k64kEntriesStore)
return kBaseTableLen;
if (storage_size <= k64kEntriesStore * 2)
return kBaseTableLen * 2;
if (storage_size <= k64kEntriesStore * 4)
return kBaseTableLen * 4;
if (storage_size <= k64kEntriesStore * 8)
return kBaseTableLen * 8;
// The biggest storage_size for int32 requires a 4 MB table.
return kBaseTableLen * 16;
}
int MaxStorageSizeForTable(int table_len) {
return table_len * (k64kEntriesStore / kBaseTableLen);
}
size_t GetIndexSize(int table_len) {
size_t table_size = sizeof(disk_cache::CacheAddr) * table_len;
return sizeof(disk_cache::IndexHeader) + table_size;
}
// ------------------------------------------------------------------------
// Sets group for the current experiment. Returns false if the files should be
// discarded.
bool InitExperiment(disk_cache::IndexHeader* header, bool cache_created) {
if (header->experiment == disk_cache::EXPERIMENT_OLD_FILE1 ||
header->experiment == disk_cache::EXPERIMENT_OLD_FILE2) {
// Discard current cache.
return false;
}
if (base::FieldTrialList::FindFullName("SimpleCacheTrial") ==
"ExperimentControl") {
if (cache_created) {
header->experiment = disk_cache::EXPERIMENT_SIMPLE_CONTROL;
return true;
} else if (header->experiment != disk_cache::EXPERIMENT_SIMPLE_CONTROL) {
return false;
}
}
header->experiment = disk_cache::NO_EXPERIMENT;
return true;
}
// A callback to perform final cleanup on the background thread.
void FinalCleanupCallback(disk_cache::BackendImpl* backend) {
backend->CleanupCache();
}
} // namespace
// ------------------------------------------------------------------------
namespace disk_cache {
// Returns the preferred maximum number of bytes for the cache given the
// number of available bytes.
int PreferedCacheSize(int64 available) {
// Return 80% of the available space if there is not enough space to use
// kDefaultCacheSize.
if (available < kDefaultCacheSize * 10 / 8)
return static_cast<int32>(available * 8 / 10);
// Return kDefaultCacheSize if it uses 80% to 10% of the available space.
if (available < kDefaultCacheSize * 10)
return kDefaultCacheSize;
// Return 10% of the available space if the target size
// (2.5 * kDefaultCacheSize) is more than 10%.
if (available < static_cast<int64>(kDefaultCacheSize) * 25)
return static_cast<int32>(available / 10);
// Return the target size (2.5 * kDefaultCacheSize) if it uses 10% to 1%
// of the available space.
if (available < static_cast<int64>(kDefaultCacheSize) * 250)
return kDefaultCacheSize * 5 / 2;
// Return 1% of the available space if it does not exceed kint32max.
if (available < static_cast<int64>(kint32max) * 100)
return static_cast<int32>(available / 100);
return kint32max;
}
// ------------------------------------------------------------------------
BackendImpl::BackendImpl(const base::FilePath& path,
base::MessageLoopProxy* cache_thread,
net::NetLog* net_log)
: background_queue_(this, cache_thread),
path_(path),
block_files_(path),
mask_(0),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(0),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
net_log_(net_log),
done_(true, false),
ptr_factory_(this) {
}
BackendImpl::BackendImpl(const base::FilePath& path,
uint32 mask,
base::MessageLoopProxy* cache_thread,
net::NetLog* net_log)
: background_queue_(this, cache_thread),
path_(path),
block_files_(path),
mask_(mask),
max_size_(0),
up_ticks_(0),
cache_type_(net::DISK_CACHE),
uma_report_(0),
user_flags_(kMask),
init_(false),
restarted_(false),
unit_test_(false),
read_only_(false),
disabled_(false),
new_eviction_(false),
first_timer_(true),
user_load_(false),
net_log_(net_log),
done_(true, false),
ptr_factory_(this) {
}
BackendImpl::~BackendImpl() {
if (user_flags_ & kNoRandom) {
// This is a unit test, so we want to be strict about not leaking entries
// and completing all the work.
background_queue_.WaitForPendingIO();
} else {
// This is most likely not a test, so we want to do as little work as
// possible at this time, at the price of leaving dirty entries behind.
background_queue_.DropPendingIO();
}
if (background_queue_.BackgroundIsCurrentThread()) {
// Unit tests may use the same thread for everything.
CleanupCache();
} else {
background_queue_.background_thread()->PostTask(
FROM_HERE, base::Bind(&FinalCleanupCallback, base::Unretained(this)));
// http://crbug.com/74623
base::ThreadRestrictions::ScopedAllowWait allow_wait;
done_.Wait();
}
}
int BackendImpl::Init(const CompletionCallback& callback) {
background_queue_.Init(callback);
return net::ERR_IO_PENDING;
}
int BackendImpl::SyncInit() {
#if defined(NET_BUILD_STRESS_CACHE)
// Start evictions right away.
up_ticks_ = kTrimDelay * 2;
#endif
DCHECK(!init_);
if (init_)
return net::ERR_FAILED;
bool create_files = false;
if (!InitBackingStore(&create_files)) {
ReportError(ERR_STORAGE_ERROR);
return net::ERR_FAILED;
}
num_refs_ = num_pending_io_ = max_refs_ = 0;
entry_count_ = byte_count_ = 0;
if (!restarted_) {
buffer_bytes_ = 0;
trace_object_ = TraceObject::GetTraceObject();
// Create a recurrent timer of 30 secs.
int timer_delay = unit_test_ ? 1000 : 30000;
timer_.reset(new base::RepeatingTimer<BackendImpl>());
timer_->Start(FROM_HERE, TimeDelta::FromMilliseconds(timer_delay), this,
&BackendImpl::OnStatsTimer);
}
init_ = true;
Trace("Init");
if (data_->header.experiment != NO_EXPERIMENT &&
cache_type_ != net::DISK_CACHE) {
// No experiment for other caches.
return net::ERR_FAILED;
}
if (!(user_flags_ & kNoRandom)) {
// The unit test controls directly what to test.
new_eviction_ = (cache_type_ == net::DISK_CACHE);
}
if (!CheckIndex()) {
ReportError(ERR_INIT_FAILED);
return net::ERR_FAILED;
}
if (!restarted_ && (create_files || !data_->header.num_entries))
ReportError(ERR_CACHE_CREATED);
if (!(user_flags_ & kNoRandom) && cache_type_ == net::DISK_CACHE &&
!InitExperiment(&data_->header, create_files)) {
return net::ERR_FAILED;
}
// We don't care if the value overflows. The only thing we care about is that
// the id cannot be zero, because that value is used as "not dirty".
// Increasing the value once per second gives us many years before we start
// having collisions.
data_->header.this_id++;
if (!data_->header.this_id)
data_->header.this_id++;
bool previous_crash = (data_->header.crash != 0);
data_->header.crash = 1;
if (!block_files_.Init(create_files))
return net::ERR_FAILED;
// We want to minimize the changes to cache for an AppCache.
if (cache_type() == net::APP_CACHE) {
DCHECK(!new_eviction_);
read_only_ = true;
} else if (cache_type() == net::SHADER_CACHE) {
DCHECK(!new_eviction_);
}
eviction_.Init(this);
// stats_ and rankings_ may end up calling back to us so we better be enabled.
disabled_ = false;
if (!InitStats())
return net::ERR_FAILED;
disabled_ = !rankings_.Init(this, new_eviction_);
#if defined(STRESS_CACHE_EXTENDED_VALIDATION)
trace_object_->EnableTracing(false);
int sc = SelfCheck();
if (sc < 0 && sc != ERR_NUM_ENTRIES_MISMATCH)
NOTREACHED();
trace_object_->EnableTracing(true);
#endif
if (previous_crash) {
ReportError(ERR_PREVIOUS_CRASH);
} else if (!restarted_) {
ReportError(ERR_NO_ERROR);
}
FlushIndex();
return disabled_ ? net::ERR_FAILED : net::OK;
}
void BackendImpl::CleanupCache() {
Trace("Backend Cleanup");
eviction_.Stop();
timer_.reset();
if (init_) {
StoreStats();
if (data_)
data_->header.crash = 0;
if (user_flags_ & kNoRandom) {
// This is a net_unittest, verify that we are not 'leaking' entries.
File::WaitForPendingIO(&num_pending_io_);
DCHECK(!num_refs_);
} else {
File::DropPendingIO();
}
}
block_files_.CloseFiles();
FlushIndex();
index_ = NULL;
ptr_factory_.InvalidateWeakPtrs();
done_.Signal();
}
// ------------------------------------------------------------------------
int BackendImpl::OpenPrevEntry(void** iter, Entry** prev_entry,
const CompletionCallback& callback) {
DCHECK(!callback.is_null());
background_queue_.OpenPrevEntry(iter, prev_entry, callback);
return net::ERR_IO_PENDING;
}
int BackendImpl::SyncOpenEntry(const std::string& key, Entry** entry) {
DCHECK(entry);
*entry = OpenEntryImpl(key);
return (*entry) ? net::OK : net::ERR_FAILED;
}
int BackendImpl::SyncCreateEntry(const std::string& key, Entry** entry) {
DCHECK(entry);
*entry = CreateEntryImpl(key);
return (*entry) ? net::OK : net::ERR_FAILED;
}
int BackendImpl::SyncDoomEntry(const std::string& key) {
if (disabled_)
return net::ERR_FAILED;
EntryImpl* entry = OpenEntryImpl(key);
if (!entry)
return net::ERR_FAILED;
entry->DoomImpl();
entry->Release();
return net::OK;
}
int BackendImpl::SyncDoomAllEntries() {
// This is not really an error, but it is an interesting condition.
ReportError(ERR_CACHE_DOOMED);
stats_.OnEvent(Stats::DOOM_CACHE);
if (!num_refs_) {
RestartCache(false);
return disabled_ ? net::ERR_FAILED : net::OK;
} else {
if (disabled_)
return net::ERR_FAILED;
eviction_.TrimCache(true);
return net::OK;
}
}
int BackendImpl::SyncDoomEntriesBetween(const base::Time initial_time,
const base::Time end_time) {
DCHECK_NE(net::APP_CACHE, cache_type_);
if (end_time.is_null())
return SyncDoomEntriesSince(initial_time);
DCHECK(end_time >= initial_time);
if (disabled_)
return net::ERR_FAILED;
EntryImpl* node;
void* iter = NULL;
EntryImpl* next = OpenNextEntryImpl(&iter);
if (!next)
return net::OK;
while (next) {
node = next;
next = OpenNextEntryImpl(&iter);
if (node->GetLastUsed() >= initial_time &&
node->GetLastUsed() < end_time) {
node->DoomImpl();
} else if (node->GetLastUsed() < initial_time) {
if (next)
next->Release();
next = NULL;
SyncEndEnumeration(iter);
}
node->Release();
}
return net::OK;
}
// We use OpenNextEntryImpl to retrieve elements from the cache, until we get
// entries that are too old.
int BackendImpl::SyncDoomEntriesSince(const base::Time initial_time) {
DCHECK_NE(net::APP_CACHE, cache_type_);
if (disabled_)
return net::ERR_FAILED;
stats_.OnEvent(Stats::DOOM_RECENT);
for (;;) {
void* iter = NULL;
EntryImpl* entry = OpenNextEntryImpl(&iter);
if (!entry)
return net::OK;
if (initial_time > entry->GetLastUsed()) {
entry->Release();
SyncEndEnumeration(iter);
return net::OK;
}
entry->DoomImpl();
entry->Release();
SyncEndEnumeration(iter); // Dooming the entry invalidates the iterator.
}
}
int BackendImpl::SyncOpenNextEntry(void** iter, Entry** next_entry) {
*next_entry = OpenNextEntryImpl(iter);
return (*next_entry) ? net::OK : net::ERR_FAILED;
}
int BackendImpl::SyncOpenPrevEntry(void** iter, Entry** prev_entry) {
*prev_entry = OpenPrevEntryImpl(iter);
return (*prev_entry) ? net::OK : net::ERR_FAILED;
}
void BackendImpl::SyncEndEnumeration(void* iter) {
scoped_ptr<Rankings::Iterator> iterator(
reinterpret_cast<Rankings::Iterator*>(iter));
}
void BackendImpl::SyncOnExternalCacheHit(const std::string& key) {
if (disabled_)
return;
uint32 hash = base::Hash(key);
bool error;
EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error);
if (cache_entry) {
if (ENTRY_NORMAL == cache_entry->entry()->Data()->state) {
UpdateRank(cache_entry, cache_type() == net::SHADER_CACHE);
}
cache_entry->Release();
}
}
EntryImpl* BackendImpl::OpenEntryImpl(const std::string& key) {
if (disabled_)
return NULL;
TimeTicks start = TimeTicks::Now();
uint32 hash = base::Hash(key);
Trace("Open hash 0x%x", hash);
bool error;
EntryImpl* cache_entry = MatchEntry(key, hash, false, Addr(), &error);
if (cache_entry && ENTRY_NORMAL != cache_entry->entry()->Data()->state) {
// The entry was already evicted.
cache_entry->Release();
cache_entry = NULL;
}
int current_size = data_->header.num_bytes / (1024 * 1024);
int64 total_hours = stats_.GetCounter(Stats::TIMER) / 120;
int64 no_use_hours = stats_.GetCounter(Stats::LAST_REPORT_TIMER) / 120;
int64 use_hours = total_hours - no_use_hours;
if (!cache_entry) {
CACHE_UMA(AGE_MS, "OpenTime.Miss", 0, start);
CACHE_UMA(COUNTS_10000, "AllOpenBySize.Miss", 0, current_size);
CACHE_UMA(HOURS, "AllOpenByTotalHours.Miss", 0, total_hours);
CACHE_UMA(HOURS, "AllOpenByUseHours.Miss", 0, use_hours);
stats_.OnEvent(Stats::OPEN_MISS);
return NULL;
}
eviction_.OnOpenEntry(cache_entry);
entry_count_++;
Trace("Open hash 0x%x end: 0x%x", hash,
cache_entry->entry()->address().value());
CACHE_UMA(AGE_MS, "OpenTime", 0, start);
CACHE_UMA(COUNTS_10000, "AllOpenBySize.Hit", 0, current_size);
CACHE_UMA(HOURS, "AllOpenByTotalHours.Hit", 0, total_hours);
CACHE_UMA(HOURS, "AllOpenByUseHours.Hit", 0, use_hours);
stats_.OnEvent(Stats::OPEN_HIT);
SIMPLE_STATS_COUNTER("disk_cache.hit");
return cache_entry;
}
EntryImpl* BackendImpl::CreateEntryImpl(const std::string& key) {
if (disabled_ || key.empty())
return NULL;
TimeTicks start = TimeTicks::Now();
uint32 hash = base::Hash(key);
Trace("Create hash 0x%x", hash);
scoped_refptr<EntryImpl> parent;
Addr entry_address(data_->table[hash & mask_]);
if (entry_address.is_initialized()) {
// We have an entry already. It could be the one we are looking for, or just
// a hash conflict.
bool error;
EntryImpl* old_entry = MatchEntry(key, hash, false, Addr(), &error);
if (old_entry)
return ResurrectEntry(old_entry);
EntryImpl* parent_entry = MatchEntry(key, hash, true, Addr(), &error);
DCHECK(!error);
if (parent_entry) {
parent.swap(&parent_entry);
} else if (data_->table[hash & mask_]) {
// We should have corrected the problem.
NOTREACHED();
return NULL;
}
}
// The general flow is to allocate disk space and initialize the entry data,
// followed by saving that to disk, then linking the entry though the index
// and finally through the lists. If there is a crash in this process, we may
// end up with:
// a. Used, unreferenced empty blocks on disk (basically just garbage).
// b. Used, unreferenced but meaningful data on disk (more garbage).
// c. A fully formed entry, reachable only through the index.
// d. A fully formed entry, also reachable through the lists, but still dirty.
//
// Anything after (b) can be automatically cleaned up. We may consider saving
// the current operation (as we do while manipulating the lists) so that we
// can detect and cleanup (a) and (b).
int num_blocks = EntryImpl::NumBlocksForEntry(key.size());
if (!block_files_.CreateBlock(BLOCK_256, num_blocks, &entry_address)) {
LOG(ERROR) << "Create entry failed " << key.c_str();
stats_.OnEvent(Stats::CREATE_ERROR);
return NULL;
}
Addr node_address(0);
if (!block_files_.CreateBlock(RANKINGS, 1, &node_address)) {
block_files_.DeleteBlock(entry_address, false);
LOG(ERROR) << "Create entry failed " << key.c_str();
stats_.OnEvent(Stats::CREATE_ERROR);
return NULL;
}
scoped_refptr<EntryImpl> cache_entry(
new EntryImpl(this, entry_address, false));
IncreaseNumRefs();
if (!cache_entry->CreateEntry(node_address, key, hash)) {
block_files_.DeleteBlock(entry_address, false);
block_files_.DeleteBlock(node_address, false);
LOG(ERROR) << "Create entry failed " << key.c_str();
stats_.OnEvent(Stats::CREATE_ERROR);
return NULL;
}
cache_entry->BeginLogging(net_log_, true);
// We are not failing the operation; let's add this to the map.
open_entries_[entry_address.value()] = cache_entry.get();
// Save the entry.
cache_entry->entry()->Store();
cache_entry->rankings()->Store();
IncreaseNumEntries();
entry_count_++;
// Link this entry through the index.
if (parent.get()) {
parent->SetNextAddress(entry_address);
} else {
data_->table[hash & mask_] = entry_address.value();
}
// Link this entry through the lists.
eviction_.OnCreateEntry(cache_entry.get());
CACHE_UMA(AGE_MS, "CreateTime", 0, start);
stats_.OnEvent(Stats::CREATE_HIT);
SIMPLE_STATS_COUNTER("disk_cache.miss");
Trace("create entry hit ");
FlushIndex();
cache_entry->AddRef();
return cache_entry.get();
}
EntryImpl* BackendImpl::OpenNextEntryImpl(void** iter) {
return OpenFollowingEntry(true, iter);
}
EntryImpl* BackendImpl::OpenPrevEntryImpl(void** iter) {
return OpenFollowingEntry(false, iter);
}
bool BackendImpl::SetMaxSize(int max_bytes) {
COMPILE_ASSERT(sizeof(max_bytes) == sizeof(max_size_), unsupported_int_model);
if (max_bytes < 0)
return false;
// Zero size means use the default.
if (!max_bytes)
return true;
// Avoid a DCHECK later on.
if (max_bytes >= kint32max - kint32max / 10)
max_bytes = kint32max - kint32max / 10 - 1;
user_flags_ |= kMaxSize;
max_size_ = max_bytes;
return true;
}
void BackendImpl::SetType(net::CacheType type) {
DCHECK_NE(net::MEMORY_CACHE, type);
cache_type_ = type;
}
base::FilePath BackendImpl::GetFileName(Addr address) const {
if (!address.is_separate_file() || !address.is_initialized()) {
NOTREACHED();
return base::FilePath();
}
std::string tmp = base::StringPrintf("f_%06x", address.FileNumber());
return path_.AppendASCII(tmp);
}
MappedFile* BackendImpl::File(Addr address) {
if (disabled_)
return NULL;
return block_files_.GetFile(address);
}
base::WeakPtr<InFlightBackendIO> BackendImpl::GetBackgroundQueue() {
return background_queue_.GetWeakPtr();
}
bool BackendImpl::CreateExternalFile(Addr* address) {
int file_number = data_->header.last_file + 1;
Addr file_address(0);
bool success = false;
for (int i = 0; i < 0x0fffffff; i++, file_number++) {
if (!file_address.SetFileNumber(file_number)) {
file_number = 1;
continue;
}
base::FilePath name = GetFileName(file_address);
int flags = base::PLATFORM_FILE_READ |
base::PLATFORM_FILE_WRITE |
base::PLATFORM_FILE_CREATE |
base::PLATFORM_FILE_EXCLUSIVE_WRITE;
base::PlatformFileError error;
scoped_refptr<disk_cache::File> file(new disk_cache::File(
base::CreatePlatformFile(name, flags, NULL, &error)));
if (!file->IsValid()) {
if (error != base::PLATFORM_FILE_ERROR_EXISTS) {
LOG(ERROR) << "Unable to create file: " << error;
return false;
}
continue;
}
success = true;
break;
}
DCHECK(success);
if (!success)
return false;
data_->header.last_file = file_number;
address->set_value(file_address.value());
return true;
}
bool BackendImpl::CreateBlock(FileType block_type, int block_count,
Addr* block_address) {
return block_files_.CreateBlock(block_type, block_count, block_address);
}
void BackendImpl::DeleteBlock(Addr block_address, bool deep) {
block_files_.DeleteBlock(block_address, deep);
}
LruData* BackendImpl::GetLruData() {
return &data_->header.lru;
}
void BackendImpl::UpdateRank(EntryImpl* entry, bool modified) {
if (read_only_ || (!modified && cache_type() == net::SHADER_CACHE))
return;
eviction_.UpdateRank(entry, modified);
}
void BackendImpl::RecoveredEntry(CacheRankingsBlock* rankings) {
Addr address(rankings->Data()->contents);
EntryImpl* cache_entry = NULL;
if (NewEntry(address, &cache_entry)) {
STRESS_NOTREACHED();
return;
}
uint32 hash = cache_entry->GetHash();
cache_entry->Release();
// Anything on the table means that this entry is there.
if (data_->table[hash & mask_])
return;
data_->table[hash & mask_] = address.value();
FlushIndex();
}
void BackendImpl::InternalDoomEntry(EntryImpl* entry) {
uint32 hash = entry->GetHash();
std::string key = entry->GetKey();
Addr entry_addr = entry->entry()->address();
bool error;
EntryImpl* parent_entry = MatchEntry(key, hash, true, entry_addr, &error);
CacheAddr child(entry->GetNextAddress());
Trace("Doom entry 0x%p", entry);
if (!entry->doomed()) {
// We may have doomed this entry from within MatchEntry.
eviction_.OnDoomEntry(entry);
entry->InternalDoom();
if (!new_eviction_) {
DecreaseNumEntries();
}
stats_.OnEvent(Stats::DOOM_ENTRY);
}
if (parent_entry) {
parent_entry->SetNextAddress(Addr(child));
parent_entry->Release();
} else if (!error) {
data_->table[hash & mask_] = child;
}
FlushIndex();
}
#if defined(NET_BUILD_STRESS_CACHE)
CacheAddr BackendImpl::GetNextAddr(Addr address) {
EntriesMap::iterator it = open_entries_.find(address.value());
if (it != open_entries_.end()) {
EntryImpl* this_entry = it->second;
return this_entry->GetNextAddress();
}
DCHECK(block_files_.IsValid(address));
DCHECK(!address.is_separate_file() && address.file_type() == BLOCK_256);
CacheEntryBlock entry(File(address), address);
CHECK(entry.Load());
return entry.Data()->next;
}
void BackendImpl::NotLinked(EntryImpl* entry) {
Addr entry_addr = entry->entry()->address();
uint32 i = entry->GetHash() & mask_;
Addr address(data_->table[i]);
if (!address.is_initialized())
return;
for (;;) {
DCHECK(entry_addr.value() != address.value());
address.set_value(GetNextAddr(address));
if (!address.is_initialized())
break;
}
}
#endif // NET_BUILD_STRESS_CACHE
// An entry may be linked on the DELETED list for a while after being doomed.
// This function is called when we want to remove it.
void BackendImpl::RemoveEntry(EntryImpl* entry) {
#if defined(NET_BUILD_STRESS_CACHE)
NotLinked(entry);
#endif
if (!new_eviction_)
return;
DCHECK_NE(ENTRY_NORMAL, entry->entry()->Data()->state);
Trace("Remove entry 0x%p", entry);
eviction_.OnDestroyEntry(entry);
DecreaseNumEntries();
}
void BackendImpl::OnEntryDestroyBegin(Addr address) {
EntriesMap::iterator it = open_entries_.find(address.value());
if (it != open_entries_.end())
open_entries_.erase(it);
}
void BackendImpl::OnEntryDestroyEnd() {
DecreaseNumRefs();
if (data_->header.num_bytes > max_size_ && !read_only_ &&
(up_ticks_ > kTrimDelay || user_flags_ & kNoRandom))
eviction_.TrimCache(false);
}
EntryImpl* BackendImpl::GetOpenEntry(CacheRankingsBlock* rankings) const {
DCHECK(rankings->HasData());
EntriesMap::const_iterator it =
open_entries_.find(rankings->Data()->contents);
if (it != open_entries_.end()) {
// We have this entry in memory.
return it->second;
}
return NULL;
}
int32 BackendImpl::GetCurrentEntryId() const {
return data_->header.this_id;
}
int BackendImpl::MaxFileSize() const {
return max_size_ / 8;
}
void BackendImpl::ModifyStorageSize(int32 old_size, int32 new_size) {
if (disabled_ || old_size == new_size)
return;
if (old_size > new_size)
SubstractStorageSize(old_size - new_size);
else
AddStorageSize(new_size - old_size);
FlushIndex();
// Update the usage statistics.
stats_.ModifyStorageStats(old_size, new_size);
}
void BackendImpl::TooMuchStorageRequested(int32 size) {
stats_.ModifyStorageStats(0, size);
}
bool BackendImpl::IsAllocAllowed(int current_size, int new_size) {
DCHECK_GT(new_size, current_size);
if (user_flags_ & kNoBuffering)
return false;
int to_add = new_size - current_size;
if (buffer_bytes_ + to_add > MaxBuffersSize())
return false;
buffer_bytes_ += to_add;
CACHE_UMA(COUNTS_50000, "BufferBytes", 0, buffer_bytes_ / 1024);
return true;
}
void BackendImpl::BufferDeleted(int size) {
buffer_bytes_ -= size;
DCHECK_GE(size, 0);
}
bool BackendImpl::IsLoaded() const {
CACHE_UMA(COUNTS, "PendingIO", 0, num_pending_io_);
if (user_flags_ & kNoLoadProtection)
return false;
return (num_pending_io_ > 5 || user_load_);
}
std::string BackendImpl::HistogramName(const char* name, int experiment) const {
if (!experiment)
return base::StringPrintf("DiskCache.%d.%s", cache_type_, name);
return base::StringPrintf("DiskCache.%d.%s_%d", cache_type_,
name, experiment);
}
base::WeakPtr<BackendImpl> BackendImpl::GetWeakPtr() {
return ptr_factory_.GetWeakPtr();
}
// We want to remove biases from some histograms so we only send data once per
// week.
bool BackendImpl::ShouldReportAgain() {
if (uma_report_)
return uma_report_ == 2;
uma_report_++;
int64 last_report = stats_.GetCounter(Stats::LAST_REPORT);
Time last_time = Time::FromInternalValue(last_report);
if (!last_report || (Time::Now() - last_time).InDays() >= 7) {
stats_.SetCounter(Stats::LAST_REPORT, Time::Now().ToInternalValue());
uma_report_++;
return true;
}
return false;
}
void BackendImpl::FirstEviction() {
DCHECK(data_->header.create_time);
if (!GetEntryCount())
return; // This is just for unit tests.
Time create_time = Time::FromInternalValue(data_->header.create_time);
CACHE_UMA(AGE, "FillupAge", 0, create_time);
int64 use_time = stats_.GetCounter(Stats::TIMER);
CACHE_UMA(HOURS, "FillupTime", 0, static_cast<int>(use_time / 120));
CACHE_UMA(PERCENTAGE, "FirstHitRatio", 0, stats_.GetHitRatio());
if (!use_time)
use_time = 1;
CACHE_UMA(COUNTS_10000, "FirstEntryAccessRate", 0,
static_cast<int>(data_->header.num_entries / use_time));
CACHE_UMA(COUNTS, "FirstByteIORate", 0,
static_cast<int>((data_->header.num_bytes / 1024) / use_time));
int avg_size = data_->header.num_bytes / GetEntryCount();
CACHE_UMA(COUNTS, "FirstEntrySize", 0, avg_size);
int large_entries_bytes = stats_.GetLargeEntriesSize();
int large_ratio = large_entries_bytes * 100 / data_->header.num_bytes;
CACHE_UMA(PERCENTAGE, "FirstLargeEntriesRatio", 0, large_ratio);
if (new_eviction_) {
CACHE_UMA(PERCENTAGE, "FirstResurrectRatio", 0, stats_.GetResurrectRatio());
CACHE_UMA(PERCENTAGE, "FirstNoUseRatio", 0,
data_->header.lru.sizes[0] * 100 / data_->header.num_entries);
CACHE_UMA(PERCENTAGE, "FirstLowUseRatio", 0,
data_->header.lru.sizes[1] * 100 / data_->header.num_entries);
CACHE_UMA(PERCENTAGE, "FirstHighUseRatio", 0,
data_->header.lru.sizes[2] * 100 / data_->header.num_entries);
}
stats_.ResetRatios();
}
void BackendImpl::CriticalError(int error) {
STRESS_NOTREACHED();
LOG(ERROR) << "Critical error found " << error;
if (disabled_)
return;
stats_.OnEvent(Stats::FATAL_ERROR);
LogStats();
ReportError(error);
// Setting the index table length to an invalid value will force re-creation
// of the cache files.
data_->header.table_len = 1;