forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nsCacheService.cpp
3212 lines (2642 loc) · 104 KB
/
nsCacheService.cpp
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set ts=8 sts=4 et sw=4 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/Assertions.h"
#include "mozilla/DebugOnly.h"
#include "necko-config.h"
#include "nsCache.h"
#include "nsCacheService.h"
#include "nsCacheRequest.h"
#include "nsCacheEntry.h"
#include "nsCacheEntryDescriptor.h"
#include "nsCacheDevice.h"
#include "nsMemoryCacheDevice.h"
#include "nsICacheVisitor.h"
#include "nsDiskCacheDevice.h"
#include "nsDiskCacheDeviceSQL.h"
#include "nsCacheUtils.h"
#include "../cache2/CacheObserver.h"
#include "nsIObserverService.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsIFile.h"
#include "nsIOService.h"
#include "nsDirectoryServiceDefs.h"
#include "nsAppDirectoryServiceDefs.h"
#include "nsThreadUtils.h"
#include "nsProxyRelease.h"
#include "nsDeleteDir.h"
#include "nsNetCID.h"
#include <math.h> // for log()
#include "mozilla/Services.h"
#include "nsITimer.h"
#include "mozIStorageService.h"
#include "mozilla/net/NeckoCommon.h"
#include <algorithm>
using namespace mozilla;
using namespace mozilla::net;
/******************************************************************************
* nsCacheProfilePrefObserver
*****************************************************************************/
#define DISK_CACHE_ENABLE_PREF "browser.cache.disk.enable"
#define DISK_CACHE_DIR_PREF "browser.cache.disk.parent_directory"
#define DISK_CACHE_SMART_SIZE_FIRST_RUN_PREF\
"browser.cache.disk.smart_size.first_run"
#define DISK_CACHE_SMART_SIZE_ENABLED_PREF \
"browser.cache.disk.smart_size.enabled"
#define DISK_CACHE_SMART_SIZE_PREF "browser.cache.disk.smart_size_cached_value"
#define DISK_CACHE_CAPACITY_PREF "browser.cache.disk.capacity"
#define DISK_CACHE_MAX_ENTRY_SIZE_PREF "browser.cache.disk.max_entry_size"
#define DISK_CACHE_CAPACITY 256000
#define DISK_CACHE_USE_OLD_MAX_SMART_SIZE_PREF \
"browser.cache.disk.smart_size.use_old_max"
#define OFFLINE_CACHE_ENABLE_PREF "browser.cache.offline.enable"
#define OFFLINE_CACHE_DIR_PREF "browser.cache.offline.parent_directory"
#define OFFLINE_CACHE_CAPACITY_PREF "browser.cache.offline.capacity"
#define OFFLINE_CACHE_CAPACITY 512000
#define MEMORY_CACHE_ENABLE_PREF "browser.cache.memory.enable"
#define MEMORY_CACHE_CAPACITY_PREF "browser.cache.memory.capacity"
#define MEMORY_CACHE_MAX_ENTRY_SIZE_PREF "browser.cache.memory.max_entry_size"
#define CACHE_COMPRESSION_LEVEL_PREF "browser.cache.compression_level"
#define CACHE_COMPRESSION_LEVEL 1
#define SANITIZE_ON_SHUTDOWN_PREF "privacy.sanitize.sanitizeOnShutdown"
#define CLEAR_ON_SHUTDOWN_PREF "privacy.clearOnShutdown.cache"
static const char * observerList[] = {
"profile-before-change",
"profile-do-change",
NS_XPCOM_SHUTDOWN_OBSERVER_ID,
"last-pb-context-exited",
"suspend_process_notification",
"resume_process_notification"
};
static const char * prefList[] = {
DISK_CACHE_ENABLE_PREF,
DISK_CACHE_SMART_SIZE_ENABLED_PREF,
DISK_CACHE_CAPACITY_PREF,
DISK_CACHE_DIR_PREF,
DISK_CACHE_MAX_ENTRY_SIZE_PREF,
DISK_CACHE_USE_OLD_MAX_SMART_SIZE_PREF,
OFFLINE_CACHE_ENABLE_PREF,
OFFLINE_CACHE_CAPACITY_PREF,
OFFLINE_CACHE_DIR_PREF,
MEMORY_CACHE_ENABLE_PREF,
MEMORY_CACHE_CAPACITY_PREF,
MEMORY_CACHE_MAX_ENTRY_SIZE_PREF,
CACHE_COMPRESSION_LEVEL_PREF,
SANITIZE_ON_SHUTDOWN_PREF,
CLEAR_ON_SHUTDOWN_PREF
};
// Cache sizes, in KB
const int32_t DEFAULT_CACHE_SIZE = 250 * 1024; // 250 MB
#ifdef ANDROID
const int32_t MAX_CACHE_SIZE = 200 * 1024; // 200 MB
const int32_t OLD_MAX_CACHE_SIZE = 200 * 1024; // 200 MB
#else
const int32_t MAX_CACHE_SIZE = 350 * 1024; // 350 MB
const int32_t OLD_MAX_CACHE_SIZE = 1024 * 1024; // 1 GB
#endif
// Default cache size was 50 MB for many years until FF 4:
const int32_t PRE_GECKO_2_0_DEFAULT_CACHE_SIZE = 50 * 1024;
class nsCacheProfilePrefObserver : public nsIObserver
{
virtual ~nsCacheProfilePrefObserver() {}
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_DECL_NSIOBSERVER
nsCacheProfilePrefObserver()
: mHaveProfile(false)
, mDiskCacheEnabled(false)
, mDiskCacheCapacity(0)
, mDiskCacheMaxEntrySize(-1) // -1 means "no limit"
, mSmartSizeEnabled(false)
, mShouldUseOldMaxSmartSize(false)
, mOfflineCacheEnabled(false)
, mOfflineCacheCapacity(0)
, mMemoryCacheEnabled(true)
, mMemoryCacheCapacity(-1)
, mMemoryCacheMaxEntrySize(-1) // -1 means "no limit"
, mCacheCompressionLevel(CACHE_COMPRESSION_LEVEL)
, mSanitizeOnShutdown(false)
, mClearCacheOnShutdown(false)
{
}
nsresult Install();
void Remove();
nsresult ReadPrefs(nsIPrefBranch* branch);
bool DiskCacheEnabled();
int32_t DiskCacheCapacity() { return mDiskCacheCapacity; }
void SetDiskCacheCapacity(int32_t);
int32_t DiskCacheMaxEntrySize() { return mDiskCacheMaxEntrySize; }
nsIFile * DiskCacheParentDirectory() { return mDiskCacheParentDirectory; }
bool SmartSizeEnabled() { return mSmartSizeEnabled; }
bool ShouldUseOldMaxSmartSize() { return mShouldUseOldMaxSmartSize; }
void SetUseNewMaxSmartSize(bool useNew) { mShouldUseOldMaxSmartSize = !useNew; }
bool OfflineCacheEnabled();
int32_t OfflineCacheCapacity() { return mOfflineCacheCapacity; }
nsIFile * OfflineCacheParentDirectory() { return mOfflineCacheParentDirectory; }
bool MemoryCacheEnabled();
int32_t MemoryCacheCapacity();
int32_t MemoryCacheMaxEntrySize() { return mMemoryCacheMaxEntrySize; }
int32_t CacheCompressionLevel();
bool SanitizeAtShutdown() { return mSanitizeOnShutdown && mClearCacheOnShutdown; }
static uint32_t GetSmartCacheSize(const nsAString& cachePath,
uint32_t currentSize,
bool shouldUseOldMaxSmartSize);
bool PermittedToSmartSize(nsIPrefBranch*, bool firstRun);
private:
bool mHaveProfile;
bool mDiskCacheEnabled;
int32_t mDiskCacheCapacity; // in kilobytes
int32_t mDiskCacheMaxEntrySize; // in kilobytes
nsCOMPtr<nsIFile> mDiskCacheParentDirectory;
bool mSmartSizeEnabled;
bool mShouldUseOldMaxSmartSize;
bool mOfflineCacheEnabled;
int32_t mOfflineCacheCapacity; // in kilobytes
nsCOMPtr<nsIFile> mOfflineCacheParentDirectory;
bool mMemoryCacheEnabled;
int32_t mMemoryCacheCapacity; // in kilobytes
int32_t mMemoryCacheMaxEntrySize; // in kilobytes
int32_t mCacheCompressionLevel;
bool mSanitizeOnShutdown;
bool mClearCacheOnShutdown;
};
NS_IMPL_ISUPPORTS(nsCacheProfilePrefObserver, nsIObserver)
class nsSetDiskSmartSizeCallback final : public nsITimerCallback
{
~nsSetDiskSmartSizeCallback() {}
public:
NS_DECL_THREADSAFE_ISUPPORTS
NS_IMETHOD Notify(nsITimer* aTimer) override {
if (nsCacheService::gService) {
nsCacheServiceAutoLock autoLock(LOCK_TELEM(NSSETDISKSMARTSIZECALLBACK_NOTIFY));
nsCacheService::gService->SetDiskSmartSize_Locked();
nsCacheService::gService->mSmartSizeTimer = nullptr;
}
return NS_OK;
}
};
NS_IMPL_ISUPPORTS(nsSetDiskSmartSizeCallback, nsITimerCallback)
// Runnable sent to main thread after the cache IO thread calculates available
// disk space, so that there is no race in setting mDiskCacheCapacity.
class nsSetSmartSizeEvent: public Runnable
{
public:
explicit nsSetSmartSizeEvent(int32_t smartSize)
: mSmartSize(smartSize) {}
NS_IMETHOD Run()
{
NS_ASSERTION(NS_IsMainThread(),
"Setting smart size data off the main thread");
// Main thread may have already called nsCacheService::Shutdown
if (!nsCacheService::IsInitialized())
return NS_ERROR_NOT_AVAILABLE;
// Ensure smart sizing wasn't switched off while event was pending.
// It is safe to access the observer without the lock since we are
// on the main thread and the value changes only on the main thread.
if (!nsCacheService::gService->mObserver->SmartSizeEnabled())
return NS_OK;
nsCacheService::SetDiskCacheCapacity(mSmartSize);
nsCOMPtr<nsIPrefBranch> ps = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (!ps ||
NS_FAILED(ps->SetIntPref(DISK_CACHE_SMART_SIZE_PREF, mSmartSize)))
NS_WARNING("Failed to set smart size pref");
return NS_OK;
}
private:
int32_t mSmartSize;
};
// Runnable sent from main thread to cacheIO thread
class nsGetSmartSizeEvent: public Runnable
{
public:
nsGetSmartSizeEvent(const nsAString& cachePath, uint32_t currentSize,
bool shouldUseOldMaxSmartSize)
: mCachePath(cachePath)
, mCurrentSize(currentSize)
, mShouldUseOldMaxSmartSize(shouldUseOldMaxSmartSize)
{}
// Calculates user's disk space available on a background thread and
// dispatches this value back to the main thread.
NS_IMETHOD Run() override
{
uint32_t size;
size = nsCacheProfilePrefObserver::GetSmartCacheSize(mCachePath,
mCurrentSize,
mShouldUseOldMaxSmartSize);
NS_DispatchToMainThread(new nsSetSmartSizeEvent(size));
return NS_OK;
}
private:
nsString mCachePath;
uint32_t mCurrentSize;
bool mShouldUseOldMaxSmartSize;
};
class nsBlockOnCacheThreadEvent : public Runnable {
public:
nsBlockOnCacheThreadEvent()
{
}
NS_IMETHOD Run() override
{
nsCacheServiceAutoLock autoLock(LOCK_TELEM(NSBLOCKONCACHETHREADEVENT_RUN));
CACHE_LOG_DEBUG(("nsBlockOnCacheThreadEvent [%p]\n", this));
nsCacheService::gService->mNotified = true;
nsCacheService::gService->mCondVar.Notify();
return NS_OK;
}
};
nsresult
nsCacheProfilePrefObserver::Install()
{
// install profile-change observer
nsCOMPtr<nsIObserverService> observerService =
mozilla::services::GetObserverService();
if (!observerService)
return NS_ERROR_FAILURE;
nsresult rv, rv2 = NS_OK;
for (unsigned int i=0; i<ArrayLength(observerList); i++) {
rv = observerService->AddObserver(this, observerList[i], false);
if (NS_FAILED(rv))
rv2 = rv;
}
// install preferences observer
nsCOMPtr<nsIPrefBranch> branch = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (!branch) return NS_ERROR_FAILURE;
for (unsigned int i=0; i<ArrayLength(prefList); i++) {
rv = branch->AddObserver(prefList[i], this, false);
if (NS_FAILED(rv))
rv2 = rv;
}
// Determine if we have a profile already
// Install() is called *after* the profile-after-change notification
// when there is only a single profile, or it is specified on the
// commandline at startup.
// In that case, we detect the presence of a profile by the existence
// of the NS_APP_USER_PROFILE_50_DIR directory.
nsCOMPtr<nsIFile> directory;
rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
getter_AddRefs(directory));
if (NS_SUCCEEDED(rv))
mHaveProfile = true;
rv = ReadPrefs(branch);
NS_ENSURE_SUCCESS(rv, rv);
return rv2;
}
void
nsCacheProfilePrefObserver::Remove()
{
// remove Observer Service observers
nsCOMPtr<nsIObserverService> obs =
mozilla::services::GetObserverService();
if (obs) {
for (unsigned int i=0; i<ArrayLength(observerList); i++) {
obs->RemoveObserver(this, observerList[i]);
}
}
// remove Pref Service observers
nsCOMPtr<nsIPrefBranch> prefs =
do_GetService(NS_PREFSERVICE_CONTRACTID);
if (!prefs)
return;
for (unsigned int i=0; i<ArrayLength(prefList); i++)
prefs->RemoveObserver(prefList[i], this); // remove cache pref observers
}
void
nsCacheProfilePrefObserver::SetDiskCacheCapacity(int32_t capacity)
{
mDiskCacheCapacity = std::max(0, capacity);
}
NS_IMETHODIMP
nsCacheProfilePrefObserver::Observe(nsISupports * subject,
const char * topic,
const char16_t * data_unicode)
{
nsresult rv;
NS_ConvertUTF16toUTF8 data(data_unicode);
CACHE_LOG_INFO(("Observe [topic=%s data=%s]\n", topic, data.get()));
if (!nsCacheService::IsInitialized()) {
if (!strcmp("resume_process_notification", topic)) {
// A suspended process has a closed cache, so re-open it here.
nsCacheService::GlobalInstance()->Init();
}
return NS_OK;
}
if (!strcmp(NS_XPCOM_SHUTDOWN_OBSERVER_ID, topic)) {
// xpcom going away, shutdown cache service
nsCacheService::GlobalInstance()->Shutdown();
} else if (!strcmp("profile-before-change", topic)) {
// profile before change
mHaveProfile = false;
// XXX shutdown devices
nsCacheService::OnProfileShutdown();
} else if (!strcmp("suspend_process_notification", topic)) {
// A suspended process may never return, so shutdown the cache to reduce
// cache corruption.
nsCacheService::GlobalInstance()->Shutdown();
} else if (!strcmp("profile-do-change", topic)) {
// profile after change
mHaveProfile = true;
nsCOMPtr<nsIPrefBranch> branch = do_GetService(NS_PREFSERVICE_CONTRACTID);
if (!branch) {
return NS_ERROR_FAILURE;
}
(void)ReadPrefs(branch);
nsCacheService::OnProfileChanged();
} else if (!strcmp(NS_PREFBRANCH_PREFCHANGE_TOPIC_ID, topic)) {
// ignore pref changes until we're done switch profiles
if (!mHaveProfile)
return NS_OK;
nsCOMPtr<nsIPrefBranch> branch = do_QueryInterface(subject, &rv);
if (NS_FAILED(rv))
return rv;
// which preference changed?
if (!strcmp(DISK_CACHE_ENABLE_PREF, data.get())) {
rv = branch->GetBoolPref(DISK_CACHE_ENABLE_PREF,
&mDiskCacheEnabled);
if (NS_FAILED(rv))
return rv;
nsCacheService::SetDiskCacheEnabled(DiskCacheEnabled());
} else if (!strcmp(DISK_CACHE_CAPACITY_PREF, data.get())) {
int32_t capacity = 0;
rv = branch->GetIntPref(DISK_CACHE_CAPACITY_PREF, &capacity);
if (NS_FAILED(rv))
return rv;
mDiskCacheCapacity = std::max(0, capacity);
nsCacheService::SetDiskCacheCapacity(mDiskCacheCapacity);
// Update the cache capacity when smart sizing is turned on/off
} else if (!strcmp(DISK_CACHE_SMART_SIZE_ENABLED_PREF, data.get())) {
// Is the update because smartsizing was turned on, or off?
rv = branch->GetBoolPref(DISK_CACHE_SMART_SIZE_ENABLED_PREF,
&mSmartSizeEnabled);
if (NS_FAILED(rv))
return rv;
int32_t newCapacity = 0;
if (mSmartSizeEnabled) {
nsCacheService::SetDiskSmartSize();
} else {
// Smart sizing switched off: use user specified size
rv = branch->GetIntPref(DISK_CACHE_CAPACITY_PREF, &newCapacity);
if (NS_FAILED(rv))
return rv;
mDiskCacheCapacity = std::max(0, newCapacity);
nsCacheService::SetDiskCacheCapacity(mDiskCacheCapacity);
}
} else if (!strcmp(DISK_CACHE_USE_OLD_MAX_SMART_SIZE_PREF, data.get())) {
rv = branch->GetBoolPref(DISK_CACHE_USE_OLD_MAX_SMART_SIZE_PREF,
&mShouldUseOldMaxSmartSize);
if (NS_FAILED(rv))
return rv;
} else if (!strcmp(DISK_CACHE_MAX_ENTRY_SIZE_PREF, data.get())) {
int32_t newMaxSize;
rv = branch->GetIntPref(DISK_CACHE_MAX_ENTRY_SIZE_PREF,
&newMaxSize);
if (NS_FAILED(rv))
return rv;
mDiskCacheMaxEntrySize = std::max(-1, newMaxSize);
nsCacheService::SetDiskCacheMaxEntrySize(mDiskCacheMaxEntrySize);
#if 0
} else if (!strcmp(DISK_CACHE_DIR_PREF, data.get())) {
// XXX We probaby don't want to respond to this pref except after
// XXX profile changes. Ideally, there should be somekind of user
// XXX notification that the pref change won't take effect until
// XXX the next time the profile changes (browser launch)
#endif
} else
// which preference changed?
if (!strcmp(OFFLINE_CACHE_ENABLE_PREF, data.get())) {
rv = branch->GetBoolPref(OFFLINE_CACHE_ENABLE_PREF,
&mOfflineCacheEnabled);
if (NS_FAILED(rv)) return rv;
nsCacheService::SetOfflineCacheEnabled(OfflineCacheEnabled());
} else if (!strcmp(OFFLINE_CACHE_CAPACITY_PREF, data.get())) {
int32_t capacity = 0;
rv = branch->GetIntPref(OFFLINE_CACHE_CAPACITY_PREF, &capacity);
if (NS_FAILED(rv)) return rv;
mOfflineCacheCapacity = std::max(0, capacity);
nsCacheService::SetOfflineCacheCapacity(mOfflineCacheCapacity);
#if 0
} else if (!strcmp(OFFLINE_CACHE_DIR_PREF, data.get())) {
// XXX We probaby don't want to respond to this pref except after
// XXX profile changes. Ideally, there should be some kind of user
// XXX notification that the pref change won't take effect until
// XXX the next time the profile changes (browser launch)
#endif
} else
if (!strcmp(MEMORY_CACHE_ENABLE_PREF, data.get())) {
rv = branch->GetBoolPref(MEMORY_CACHE_ENABLE_PREF,
&mMemoryCacheEnabled);
if (NS_FAILED(rv))
return rv;
nsCacheService::SetMemoryCache();
} else if (!strcmp(MEMORY_CACHE_CAPACITY_PREF, data.get())) {
mMemoryCacheCapacity = -1;
(void) branch->GetIntPref(MEMORY_CACHE_CAPACITY_PREF,
&mMemoryCacheCapacity);
nsCacheService::SetMemoryCache();
} else if (!strcmp(MEMORY_CACHE_MAX_ENTRY_SIZE_PREF, data.get())) {
int32_t newMaxSize;
rv = branch->GetIntPref(MEMORY_CACHE_MAX_ENTRY_SIZE_PREF,
&newMaxSize);
if (NS_FAILED(rv))
return rv;
mMemoryCacheMaxEntrySize = std::max(-1, newMaxSize);
nsCacheService::SetMemoryCacheMaxEntrySize(mMemoryCacheMaxEntrySize);
} else if (!strcmp(CACHE_COMPRESSION_LEVEL_PREF, data.get())) {
mCacheCompressionLevel = CACHE_COMPRESSION_LEVEL;
(void)branch->GetIntPref(CACHE_COMPRESSION_LEVEL_PREF,
&mCacheCompressionLevel);
mCacheCompressionLevel = std::max(0, mCacheCompressionLevel);
mCacheCompressionLevel = std::min(9, mCacheCompressionLevel);
} else if (!strcmp(SANITIZE_ON_SHUTDOWN_PREF, data.get())) {
rv = branch->GetBoolPref(SANITIZE_ON_SHUTDOWN_PREF,
&mSanitizeOnShutdown);
if (NS_FAILED(rv))
return rv;
nsCacheService::SetDiskCacheEnabled(DiskCacheEnabled());
} else if (!strcmp(CLEAR_ON_SHUTDOWN_PREF, data.get())) {
rv = branch->GetBoolPref(CLEAR_ON_SHUTDOWN_PREF,
&mClearCacheOnShutdown);
if (NS_FAILED(rv))
return rv;
nsCacheService::SetDiskCacheEnabled(DiskCacheEnabled());
}
} else if (!strcmp("last-pb-context-exited", topic)) {
nsCacheService::LeavePrivateBrowsing();
}
return NS_OK;
}
// Returns default ("smart") size (in KB) of cache, given available disk space
// (also in KB)
static uint32_t
SmartCacheSize(const uint32_t availKB, bool shouldUseOldMaxSmartSize)
{
uint32_t maxSize = shouldUseOldMaxSmartSize ? OLD_MAX_CACHE_SIZE : MAX_CACHE_SIZE;
if (availKB > 100 * 1024 * 1024)
return maxSize; // skip computing if we're over 100 GB
// Grow/shrink in 10 MB units, deliberately, so that in the common case we
// don't shrink cache and evict items every time we startup (it's important
// that we don't slow down startup benchmarks).
uint32_t sz10MBs = 0;
uint32_t avail10MBs = availKB / (1024*10);
// .5% of space above 25 GB
if (avail10MBs > 2500) {
sz10MBs += static_cast<uint32_t>((avail10MBs - 2500)*.005);
avail10MBs = 2500;
}
// 1% of space between 7GB -> 25 GB
if (avail10MBs > 700) {
sz10MBs += static_cast<uint32_t>((avail10MBs - 700)*.01);
avail10MBs = 700;
}
// 5% of space between 500 MB -> 7 GB
if (avail10MBs > 50) {
sz10MBs += static_cast<uint32_t>((avail10MBs - 50)*.05);
avail10MBs = 50;
}
#ifdef ANDROID
// On Android, smaller/older devices may have very little storage and
// device owners may be sensitive to storage footprint: Use a smaller
// percentage of available space and a smaller minimum.
// 20% of space up to 500 MB (10 MB min)
sz10MBs += std::max<uint32_t>(1, static_cast<uint32_t>(avail10MBs * .2));
#else
// 40% of space up to 500 MB (50 MB min)
sz10MBs += std::max<uint32_t>(5, static_cast<uint32_t>(avail10MBs * .4));
#endif
return std::min<uint32_t>(maxSize, sz10MBs * 10 * 1024);
}
/* Computes our best guess for the default size of the user's disk cache,
* based on the amount of space they have free on their hard drive.
* We use a tiered scheme: the more space available,
* the larger the disk cache will be. However, we do not want
* to enable the disk cache to grow to an unbounded size, so the larger the
* user's available space is, the smaller of a percentage we take. We set a
* lower bound of 50MB and an upper bound of 1GB.
*
*@param: None.
*@return: The size that the user's disk cache should default to, in kBytes.
*/
uint32_t
nsCacheProfilePrefObserver::GetSmartCacheSize(const nsAString& cachePath,
uint32_t currentSize,
bool shouldUseOldMaxSmartSize)
{
// Check for free space on device where cache directory lives
nsresult rv;
nsCOMPtr<nsIFile>
cacheDirectory (do_CreateInstance(NS_LOCAL_FILE_CONTRACTID, &rv));
if (NS_FAILED(rv) || !cacheDirectory)
return DEFAULT_CACHE_SIZE;
rv = cacheDirectory->InitWithPath(cachePath);
if (NS_FAILED(rv))
return DEFAULT_CACHE_SIZE;
int64_t bytesAvailable;
rv = cacheDirectory->GetDiskSpaceAvailable(&bytesAvailable);
if (NS_FAILED(rv))
return DEFAULT_CACHE_SIZE;
return SmartCacheSize(static_cast<uint32_t>((bytesAvailable / 1024) +
currentSize),
shouldUseOldMaxSmartSize);
}
/* Determine if we are permitted to dynamically size the user's disk cache based
* on their disk space available. We may do this so long as the pref
* smart_size.enabled is true.
*/
bool
nsCacheProfilePrefObserver::PermittedToSmartSize(nsIPrefBranch* branch, bool
firstRun)
{
nsresult rv;
if (firstRun) {
// check if user has set cache size in the past
bool userSet;
rv = branch->PrefHasUserValue(DISK_CACHE_CAPACITY_PREF, &userSet);
if (NS_FAILED(rv)) userSet = true;
if (userSet) {
int32_t oldCapacity;
// If user explicitly set cache size to be smaller than old default
// of 50 MB, then keep user's value. Otherwise use smart sizing.
rv = branch->GetIntPref(DISK_CACHE_CAPACITY_PREF, &oldCapacity);
if (oldCapacity < PRE_GECKO_2_0_DEFAULT_CACHE_SIZE) {
mSmartSizeEnabled = false;
branch->SetBoolPref(DISK_CACHE_SMART_SIZE_ENABLED_PREF,
mSmartSizeEnabled);
return mSmartSizeEnabled;
}
}
// Set manual setting to MAX cache size as starting val for any
// adjustment by user: (bug 559942 comment 65)
int32_t maxSize = mShouldUseOldMaxSmartSize ? OLD_MAX_CACHE_SIZE : MAX_CACHE_SIZE;
branch->SetIntPref(DISK_CACHE_CAPACITY_PREF, maxSize);
}
rv = branch->GetBoolPref(DISK_CACHE_SMART_SIZE_ENABLED_PREF,
&mSmartSizeEnabled);
if (NS_FAILED(rv))
mSmartSizeEnabled = false;
return mSmartSizeEnabled;
}
nsresult
nsCacheProfilePrefObserver::ReadPrefs(nsIPrefBranch* branch)
{
nsresult rv = NS_OK;
// read disk cache device prefs
mDiskCacheEnabled = true; // presume disk cache is enabled
(void) branch->GetBoolPref(DISK_CACHE_ENABLE_PREF, &mDiskCacheEnabled);
mDiskCacheCapacity = DISK_CACHE_CAPACITY;
(void)branch->GetIntPref(DISK_CACHE_CAPACITY_PREF, &mDiskCacheCapacity);
mDiskCacheCapacity = std::max(0, mDiskCacheCapacity);
(void) branch->GetIntPref(DISK_CACHE_MAX_ENTRY_SIZE_PREF,
&mDiskCacheMaxEntrySize);
mDiskCacheMaxEntrySize = std::max(-1, mDiskCacheMaxEntrySize);
(void) branch->GetComplexValue(DISK_CACHE_DIR_PREF, // ignore error
NS_GET_IID(nsIFile),
getter_AddRefs(mDiskCacheParentDirectory));
(void) branch->GetBoolPref(DISK_CACHE_USE_OLD_MAX_SMART_SIZE_PREF,
&mShouldUseOldMaxSmartSize);
if (!mDiskCacheParentDirectory) {
nsCOMPtr<nsIFile> directory;
// try to get the disk cache parent directory
rv = NS_GetSpecialDirectory(NS_APP_CACHE_PARENT_DIR,
getter_AddRefs(directory));
if (NS_FAILED(rv)) {
// try to get the profile directory (there may not be a profile yet)
nsCOMPtr<nsIFile> profDir;
NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
getter_AddRefs(profDir));
NS_GetSpecialDirectory(NS_APP_USER_PROFILE_LOCAL_50_DIR,
getter_AddRefs(directory));
if (!directory)
directory = profDir;
else if (profDir) {
nsCacheService::MoveOrRemoveDiskCache(profDir, directory,
"Cache");
}
}
// use file cache in build tree only if asked, to avoid cache dir litter
if (!directory && PR_GetEnv("NECKO_DEV_ENABLE_DISK_CACHE")) {
rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR,
getter_AddRefs(directory));
}
if (directory)
mDiskCacheParentDirectory = do_QueryInterface(directory, &rv);
}
if (mDiskCacheParentDirectory) {
bool firstSmartSizeRun;
rv = branch->GetBoolPref(DISK_CACHE_SMART_SIZE_FIRST_RUN_PREF,
&firstSmartSizeRun);
if (NS_FAILED(rv))
firstSmartSizeRun = false;
if (PermittedToSmartSize(branch, firstSmartSizeRun)) {
// Avoid evictions: use previous cache size until smart size event
// updates mDiskCacheCapacity
rv = branch->GetIntPref(firstSmartSizeRun ?
DISK_CACHE_CAPACITY_PREF :
DISK_CACHE_SMART_SIZE_PREF,
&mDiskCacheCapacity);
if (NS_FAILED(rv))
mDiskCacheCapacity = DEFAULT_CACHE_SIZE;
}
if (firstSmartSizeRun) {
// It is no longer our first run
rv = branch->SetBoolPref(DISK_CACHE_SMART_SIZE_FIRST_RUN_PREF,
false);
if (NS_FAILED(rv))
NS_WARNING("Failed setting first_run pref in ReadPrefs.");
}
}
// read offline cache device prefs
mOfflineCacheEnabled = true; // presume offline cache is enabled
(void) branch->GetBoolPref(OFFLINE_CACHE_ENABLE_PREF,
&mOfflineCacheEnabled);
mOfflineCacheCapacity = OFFLINE_CACHE_CAPACITY;
(void)branch->GetIntPref(OFFLINE_CACHE_CAPACITY_PREF,
&mOfflineCacheCapacity);
mOfflineCacheCapacity = std::max(0, mOfflineCacheCapacity);
(void) branch->GetComplexValue(OFFLINE_CACHE_DIR_PREF, // ignore error
NS_GET_IID(nsIFile),
getter_AddRefs(mOfflineCacheParentDirectory));
if (!mOfflineCacheParentDirectory) {
nsCOMPtr<nsIFile> directory;
// try to get the offline cache parent directory
rv = NS_GetSpecialDirectory(NS_APP_CACHE_PARENT_DIR,
getter_AddRefs(directory));
if (NS_FAILED(rv)) {
// try to get the profile directory (there may not be a profile yet)
nsCOMPtr<nsIFile> profDir;
NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR,
getter_AddRefs(profDir));
NS_GetSpecialDirectory(NS_APP_USER_PROFILE_LOCAL_50_DIR,
getter_AddRefs(directory));
if (!directory)
directory = profDir;
else if (profDir) {
nsCacheService::MoveOrRemoveDiskCache(profDir, directory,
"OfflineCache");
}
}
#if DEBUG
if (!directory) {
// use current process directory during development
rv = NS_GetSpecialDirectory(NS_XPCOM_CURRENT_PROCESS_DIR,
getter_AddRefs(directory));
}
#endif
if (directory)
mOfflineCacheParentDirectory = do_QueryInterface(directory, &rv);
}
// read memory cache device prefs
(void) branch->GetBoolPref(MEMORY_CACHE_ENABLE_PREF, &mMemoryCacheEnabled);
mMemoryCacheCapacity = -1;
(void) branch->GetIntPref(MEMORY_CACHE_CAPACITY_PREF,
&mMemoryCacheCapacity);
(void) branch->GetIntPref(MEMORY_CACHE_MAX_ENTRY_SIZE_PREF,
&mMemoryCacheMaxEntrySize);
mMemoryCacheMaxEntrySize = std::max(-1, mMemoryCacheMaxEntrySize);
// read cache compression level pref
mCacheCompressionLevel = CACHE_COMPRESSION_LEVEL;
(void)branch->GetIntPref(CACHE_COMPRESSION_LEVEL_PREF,
&mCacheCompressionLevel);
mCacheCompressionLevel = std::max(0, mCacheCompressionLevel);
mCacheCompressionLevel = std::min(9, mCacheCompressionLevel);
// read cache shutdown sanitization prefs
(void) branch->GetBoolPref(SANITIZE_ON_SHUTDOWN_PREF,
&mSanitizeOnShutdown);
(void) branch->GetBoolPref(CLEAR_ON_SHUTDOWN_PREF,
&mClearCacheOnShutdown);
return rv;
}
nsresult
nsCacheService::DispatchToCacheIOThread(nsIRunnable* event)
{
if (!gService->mCacheIOThread) return NS_ERROR_NOT_AVAILABLE;
return gService->mCacheIOThread->Dispatch(event, NS_DISPATCH_NORMAL);
}
nsresult
nsCacheService::SyncWithCacheIOThread()
{
gService->mLock.AssertCurrentThreadOwns();
if (!gService->mCacheIOThread) return NS_ERROR_NOT_AVAILABLE;
nsCOMPtr<nsIRunnable> event = new nsBlockOnCacheThreadEvent();
// dispatch event - it will notify the monitor when it's done
nsresult rv =
gService->mCacheIOThread->Dispatch(event, NS_DISPATCH_NORMAL);
if (NS_FAILED(rv)) {
NS_WARNING("Failed dispatching block-event");
return NS_ERROR_UNEXPECTED;
}
// wait until notified, then return
gService->mNotified = false;
while (!gService->mNotified) {
gService->mCondVar.Wait();
}
return NS_OK;
}
bool
nsCacheProfilePrefObserver::DiskCacheEnabled()
{
if ((mDiskCacheCapacity == 0) || (!mDiskCacheParentDirectory)) return false;
return mDiskCacheEnabled && (!mSanitizeOnShutdown || !mClearCacheOnShutdown);
}
bool
nsCacheProfilePrefObserver::OfflineCacheEnabled()
{
if ((mOfflineCacheCapacity == 0) || (!mOfflineCacheParentDirectory))
return false;
return mOfflineCacheEnabled;
}
bool
nsCacheProfilePrefObserver::MemoryCacheEnabled()
{
if (mMemoryCacheCapacity == 0) return false;
return mMemoryCacheEnabled;
}
/**
* MemoryCacheCapacity
*
* If the browser.cache.memory.capacity preference is positive, we use that
* value for the amount of memory available for the cache.
*
* If browser.cache.memory.capacity is zero, the memory cache is disabled.
*
* If browser.cache.memory.capacity is negative or not present, we use a
* formula that grows less than linearly with the amount of system memory,
* with an upper limit on the cache size. No matter how much physical RAM is
* present, the default cache size would not exceed 32 MB. This maximum would
* apply only to systems with more than 4 GB of RAM (e.g. terminal servers)
*
* RAM Cache
* --- -----
* 32 Mb 2 Mb
* 64 Mb 4 Mb
* 128 Mb 6 Mb
* 256 Mb 10 Mb
* 512 Mb 14 Mb
* 1024 Mb 18 Mb
* 2048 Mb 24 Mb
* 4096 Mb 30 Mb
*
* The equation for this is (for cache size C and memory size K (kbytes)):
* x = log2(K) - 14
* C = x^2/3 + x + 2/3 + 0.1 (0.1 for rounding)
* if (C > 32) C = 32
*/
int32_t
nsCacheProfilePrefObserver::MemoryCacheCapacity()
{
int32_t capacity = mMemoryCacheCapacity;
if (capacity >= 0) {
CACHE_LOG_DEBUG(("Memory cache capacity forced to %d\n", capacity));
return capacity;
}
static uint64_t bytes = PR_GetPhysicalMemorySize();
CACHE_LOG_DEBUG(("Physical Memory size is %llu\n", bytes));
// If getting the physical memory failed, arbitrarily assume
// 32 MB of RAM. We use a low default to have a reasonable
// size on all the devices we support.
if (bytes == 0)
bytes = 32 * 1024 * 1024;
// Conversion from unsigned int64_t to double doesn't work on all platforms.
// We need to truncate the value at INT64_MAX to make sure we don't
// overflow.
if (bytes > INT64_MAX)
bytes = INT64_MAX;
uint64_t kbytes = bytes >> 10;
double kBytesD = double(kbytes);
double x = log(kBytesD)/log(2.0) - 14;
if (x > 0) {
capacity = (int32_t)(x * x / 3.0 + x + 2.0 / 3 + 0.1); // 0.1 for rounding
if (capacity > 32)
capacity = 32;
capacity *= 1024;
} else {
capacity = 0;
}
return capacity;
}
int32_t
nsCacheProfilePrefObserver::CacheCompressionLevel()
{
return mCacheCompressionLevel;
}
/******************************************************************************
* nsProcessRequestEvent
*****************************************************************************/
class nsProcessRequestEvent : public Runnable {
public:
explicit nsProcessRequestEvent(nsCacheRequest *aRequest)
{
mRequest = aRequest;
}
NS_IMETHOD Run() override
{
nsresult rv;
NS_ASSERTION(mRequest->mListener,
"Sync OpenCacheEntry() posted to background thread!");
nsCacheServiceAutoLock lock(LOCK_TELEM(NSPROCESSREQUESTEVENT_RUN));
rv = nsCacheService::gService->ProcessRequest(mRequest,
false,
nullptr);
// Don't delete the request if it was queued
if (!(mRequest->IsBlocking() &&
rv == NS_ERROR_CACHE_WAIT_FOR_VALIDATION))
delete mRequest;