This repository was archived by the owner on Jul 9, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathCacheFileIOManager.cpp
More file actions
4302 lines (3481 loc) · 120 KB
/
Copy pathCacheFileIOManager.cpp
File metadata and controls
4302 lines (3481 loc) · 120 KB
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
/* 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 "CacheLog.h"
#include "CacheFileIOManager.h"
#include "../cache/nsCacheUtils.h"
#include "CacheHashUtils.h"
#include "CacheStorageService.h"
#include "CacheIndex.h"
#include "CacheFileUtils.h"
#include "nsThreadUtils.h"
#include "CacheFile.h"
#include "CacheObserver.h"
#include "nsIFile.h"
#include "CacheFileContextEvictor.h"
#include "nsITimer.h"
#include "nsISimpleEnumerator.h"
#include "nsIDirectoryEnumerator.h"
#include "nsIObserverService.h"
#include "nsICacheStorageVisitor.h"
#include "nsISizeOf.h"
#include "mozilla/net/MozURL.h"
#include "mozilla/Telemetry.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/Services.h"
#include "nsDirectoryServiceUtils.h"
#include "nsAppDirectoryServiceDefs.h"
#include "private/pprio.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Preferences.h"
#include "nsNetUtil.h"
// include files for ftruncate (or equivalent)
#if defined(XP_UNIX)
# include <unistd.h>
#elif defined(XP_WIN)
# include <windows.h>
# undef CreateFile
# undef CREATE_NEW
#else
// XXX add necessary include file for ftruncate (or equivalent)
#endif
namespace mozilla {
namespace net {
#define kOpenHandlesLimit 128
#define kMetadataWriteDelay 5000
#define kRemoveTrashStartDelay 60000 // in milliseconds
#define kSmartSizeUpdateInterval 60000 // in milliseconds
#ifdef ANDROID
const uint32_t kMaxCacheSizeKB = 512 * 1024; // 512 MB
#else
const uint32_t kMaxCacheSizeKB = 1024 * 1024; // 1 GB
#endif
const uint32_t kMaxClearOnShutdownCacheSizeKB = 150 * 1024; // 150 MB
bool CacheFileHandle::DispatchRelease() {
if (CacheFileIOManager::IsOnIOThreadOrCeased()) {
return false;
}
nsCOMPtr<nsIEventTarget> ioTarget = CacheFileIOManager::IOTarget();
if (!ioTarget) {
return false;
}
nsresult rv = ioTarget->Dispatch(
NewNonOwningRunnableMethod("net::CacheFileHandle::Release", this,
&CacheFileHandle::Release),
nsIEventTarget::DISPATCH_NORMAL);
if (NS_FAILED(rv)) {
return false;
}
return true;
}
NS_IMPL_ADDREF(CacheFileHandle)
NS_IMETHODIMP_(MozExternalRefCountType)
CacheFileHandle::Release() {
nsrefcnt count = mRefCnt - 1;
if (DispatchRelease()) {
// Redispatched to the IO thread.
return count;
}
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
LOG(("CacheFileHandle::Release() [this=%p, refcnt=%" PRIuPTR "]", this,
mRefCnt.get()));
MOZ_ASSERT(0 != mRefCnt, "dup release");
count = --mRefCnt;
NS_LOG_RELEASE(this, count, "CacheFileHandle");
if (0 == count) {
mRefCnt = 1;
delete (this);
return 0;
}
return count;
}
NS_INTERFACE_MAP_BEGIN(CacheFileHandle)
NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END
CacheFileHandle::CacheFileHandle(const SHA1Sum::Hash* aHash, bool aPriority,
PinningStatus aPinning)
: mHash(aHash),
mIsDoomed(false),
mClosed(false),
mPriority(aPriority),
mSpecialFile(false),
mInvalid(false),
mFileExists(false),
mDoomWhenFoundPinned(false),
mDoomWhenFoundNonPinned(false),
mKilled(false),
mPinning(aPinning),
mFileSize(-1),
mFD(nullptr) {
// If we initialize mDoomed in the initialization list, that initialization is
// not guaranteeded to be atomic. Whereas this assignment here is guaranteed
// to be atomic. TSan will see this (atomic) assignment and be satisfied
// that cross-thread accesses to mIsDoomed are properly synchronized.
mIsDoomed = false;
LOG((
"CacheFileHandle::CacheFileHandle() [this=%p, hash=%08x%08x%08x%08x%08x]",
this, LOGSHA1(aHash)));
}
CacheFileHandle::CacheFileHandle(const nsACString& aKey, bool aPriority,
PinningStatus aPinning)
: mHash(nullptr),
mIsDoomed(false),
mClosed(false),
mPriority(aPriority),
mSpecialFile(true),
mInvalid(false),
mFileExists(false),
mDoomWhenFoundPinned(false),
mDoomWhenFoundNonPinned(false),
mKilled(false),
mPinning(aPinning),
mFileSize(-1),
mFD(nullptr),
mKey(aKey) {
// See comment above about the initialization of mIsDoomed.
mIsDoomed = false;
LOG(("CacheFileHandle::CacheFileHandle() [this=%p, key=%s]", this,
PromiseFlatCString(aKey).get()));
}
CacheFileHandle::~CacheFileHandle() {
LOG(("CacheFileHandle::~CacheFileHandle() [this=%p]", this));
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
RefPtr<CacheFileIOManager> ioMan = CacheFileIOManager::gInstance;
if (!IsClosed() && ioMan) {
ioMan->CloseHandleInternal(this);
}
}
void CacheFileHandle::Log() {
nsAutoCString leafName;
if (mFile) {
mFile->GetNativeLeafName(leafName);
}
if (mSpecialFile) {
LOG(
("CacheFileHandle::Log() - special file [this=%p, "
"isDoomed=%d, priority=%d, closed=%d, invalid=%d, "
"pinning=%" PRIu32 ", fileExists=%d, fileSize=%" PRId64
", leafName=%s, key=%s]",
this, bool(mIsDoomed), bool(mPriority), bool(mClosed), bool(mInvalid),
static_cast<uint32_t>(mPinning), bool(mFileExists), mFileSize,
leafName.get(), mKey.get()));
} else {
LOG(
("CacheFileHandle::Log() - entry file [this=%p, "
"hash=%08x%08x%08x%08x%08x, "
"isDoomed=%d, priority=%d, closed=%d, invalid=%d, "
"pinning=%" PRIu32 ", fileExists=%d, fileSize=%" PRId64
", leafName=%s, key=%s]",
this, LOGSHA1(mHash), bool(mIsDoomed), bool(mPriority), bool(mClosed),
bool(mInvalid), static_cast<uint32_t>(mPinning), bool(mFileExists),
mFileSize, leafName.get(), mKey.get()));
}
}
uint32_t CacheFileHandle::FileSizeInK() const {
MOZ_ASSERT(mFileSize != -1);
uint64_t size64 = mFileSize;
size64 += 0x3FF;
size64 >>= 10;
uint32_t size;
if (size64 >> 32) {
NS_WARNING(
"CacheFileHandle::FileSizeInK() - FileSize is too large, "
"truncating to PR_UINT32_MAX");
size = PR_UINT32_MAX;
} else {
size = static_cast<uint32_t>(size64);
}
return size;
}
bool CacheFileHandle::SetPinned(bool aPinned) {
LOG(("CacheFileHandle::SetPinned [this=%p, pinned=%d]", this, aPinned));
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
mPinning = aPinned ? PinningStatus::PINNED : PinningStatus::NON_PINNED;
if ((MOZ_UNLIKELY(mDoomWhenFoundPinned) && aPinned) ||
(MOZ_UNLIKELY(mDoomWhenFoundNonPinned) && !aPinned)) {
LOG((" dooming, when: pinned=%d, non-pinned=%d, found: pinned=%d",
bool(mDoomWhenFoundPinned), bool(mDoomWhenFoundNonPinned), aPinned));
mDoomWhenFoundPinned = false;
mDoomWhenFoundNonPinned = false;
return false;
}
return true;
}
// Memory reporting
size_t CacheFileHandle::SizeOfExcludingThis(
mozilla::MallocSizeOf mallocSizeOf) const {
size_t n = 0;
nsCOMPtr<nsISizeOf> sizeOf;
sizeOf = do_QueryInterface(mFile);
if (sizeOf) {
n += sizeOf->SizeOfIncludingThis(mallocSizeOf);
}
n += mallocSizeOf(mFD);
n += mKey.SizeOfExcludingThisIfUnshared(mallocSizeOf);
return n;
}
size_t CacheFileHandle::SizeOfIncludingThis(
mozilla::MallocSizeOf mallocSizeOf) const {
return mallocSizeOf(this) + SizeOfExcludingThis(mallocSizeOf);
}
/******************************************************************************
* CacheFileHandles::HandleHashKey
*****************************************************************************/
void CacheFileHandles::HandleHashKey::AddHandle(CacheFileHandle* aHandle) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
mHandles.InsertElementAt(0, aHandle);
}
void CacheFileHandles::HandleHashKey::RemoveHandle(CacheFileHandle* aHandle) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
DebugOnly<bool> found;
found = mHandles.RemoveElement(aHandle);
MOZ_ASSERT(found);
}
already_AddRefed<CacheFileHandle>
CacheFileHandles::HandleHashKey::GetNewestHandle() {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
RefPtr<CacheFileHandle> handle;
if (mHandles.Length()) {
handle = mHandles[0];
}
return handle.forget();
}
void CacheFileHandles::HandleHashKey::GetHandles(
nsTArray<RefPtr<CacheFileHandle> >& aResult) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
for (uint32_t i = 0; i < mHandles.Length(); ++i) {
CacheFileHandle* handle = mHandles[i];
aResult.AppendElement(handle);
}
}
#ifdef DEBUG
void CacheFileHandles::HandleHashKey::AssertHandlesState() {
for (uint32_t i = 0; i < mHandles.Length(); ++i) {
CacheFileHandle* handle = mHandles[i];
MOZ_ASSERT(handle->IsDoomed());
}
}
#endif
size_t CacheFileHandles::HandleHashKey::SizeOfExcludingThis(
mozilla::MallocSizeOf mallocSizeOf) const {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThread());
size_t n = 0;
n += mallocSizeOf(mHash.get());
for (uint32_t i = 0; i < mHandles.Length(); ++i) {
n += mHandles[i]->SizeOfIncludingThis(mallocSizeOf);
}
return n;
}
/******************************************************************************
* CacheFileHandles
*****************************************************************************/
CacheFileHandles::CacheFileHandles() {
LOG(("CacheFileHandles::CacheFileHandles() [this=%p]", this));
MOZ_COUNT_CTOR(CacheFileHandles);
}
CacheFileHandles::~CacheFileHandles() {
LOG(("CacheFileHandles::~CacheFileHandles() [this=%p]", this));
MOZ_COUNT_DTOR(CacheFileHandles);
}
nsresult CacheFileHandles::GetHandle(const SHA1Sum::Hash* aHash,
CacheFileHandle** _retval) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
MOZ_ASSERT(aHash);
#ifdef DEBUG_HANDLES
LOG(("CacheFileHandles::GetHandle() [hash=%08x%08x%08x%08x%08x]",
LOGSHA1(aHash)));
#endif
// find hash entry for key
HandleHashKey* entry = mTable.GetEntry(*aHash);
if (!entry) {
LOG(
("CacheFileHandles::GetHandle() hash=%08x%08x%08x%08x%08x "
"no handle entries found",
LOGSHA1(aHash)));
return NS_ERROR_NOT_AVAILABLE;
}
#ifdef DEBUG_HANDLES
Log(entry);
#endif
// Check if the entry is doomed
RefPtr<CacheFileHandle> handle = entry->GetNewestHandle();
if (!handle) {
LOG(
("CacheFileHandles::GetHandle() hash=%08x%08x%08x%08x%08x "
"no handle found %p, entry %p",
LOGSHA1(aHash), handle.get(), entry));
return NS_ERROR_NOT_AVAILABLE;
}
if (handle->IsDoomed()) {
LOG(
("CacheFileHandles::GetHandle() hash=%08x%08x%08x%08x%08x "
"found doomed handle %p, entry %p",
LOGSHA1(aHash), handle.get(), entry));
return NS_ERROR_NOT_AVAILABLE;
}
LOG(
("CacheFileHandles::GetHandle() hash=%08x%08x%08x%08x%08x "
"found handle %p, entry %p",
LOGSHA1(aHash), handle.get(), entry));
handle.forget(_retval);
return NS_OK;
}
nsresult CacheFileHandles::NewHandle(const SHA1Sum::Hash* aHash, bool aPriority,
CacheFileHandle::PinningStatus aPinning,
CacheFileHandle** _retval) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
MOZ_ASSERT(aHash);
#ifdef DEBUG_HANDLES
LOG(("CacheFileHandles::NewHandle() [hash=%08x%08x%08x%08x%08x]",
LOGSHA1(aHash)));
#endif
// find hash entry for key
HandleHashKey* entry = mTable.PutEntry(*aHash);
#ifdef DEBUG_HANDLES
Log(entry);
#endif
#ifdef DEBUG
entry->AssertHandlesState();
#endif
RefPtr<CacheFileHandle> handle =
new CacheFileHandle(entry->Hash(), aPriority, aPinning);
entry->AddHandle(handle);
LOG(
("CacheFileHandles::NewHandle() hash=%08x%08x%08x%08x%08x "
"created new handle %p, entry=%p",
LOGSHA1(aHash), handle.get(), entry));
handle.forget(_retval);
return NS_OK;
}
void CacheFileHandles::RemoveHandle(CacheFileHandle* aHandle) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
MOZ_ASSERT(aHandle);
if (!aHandle) {
return;
}
#ifdef DEBUG_HANDLES
LOG((
"CacheFileHandles::RemoveHandle() [handle=%p, hash=%08x%08x%08x%08x%08x]",
aHandle, LOGSHA1(aHandle->Hash())));
#endif
// find hash entry for key
HandleHashKey* entry = mTable.GetEntry(*aHandle->Hash());
if (!entry) {
MOZ_ASSERT(CacheFileIOManager::IsShutdown(),
"Should find entry when removing a handle before shutdown");
LOG(
("CacheFileHandles::RemoveHandle() hash=%08x%08x%08x%08x%08x "
"no entries found",
LOGSHA1(aHandle->Hash())));
return;
}
#ifdef DEBUG_HANDLES
Log(entry);
#endif
LOG(
("CacheFileHandles::RemoveHandle() hash=%08x%08x%08x%08x%08x "
"removing handle %p",
LOGSHA1(entry->Hash()), aHandle));
entry->RemoveHandle(aHandle);
if (entry->IsEmpty()) {
LOG(
("CacheFileHandles::RemoveHandle() hash=%08x%08x%08x%08x%08x "
"list is empty, removing entry %p",
LOGSHA1(entry->Hash()), entry));
mTable.RemoveEntry(entry);
}
}
void CacheFileHandles::GetAllHandles(
nsTArray<RefPtr<CacheFileHandle> >* _retval) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
for (auto iter = mTable.Iter(); !iter.Done(); iter.Next()) {
iter.Get()->GetHandles(*_retval);
}
}
void CacheFileHandles::GetActiveHandles(
nsTArray<RefPtr<CacheFileHandle> >* _retval) {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
for (auto iter = mTable.Iter(); !iter.Done(); iter.Next()) {
RefPtr<CacheFileHandle> handle = iter.Get()->GetNewestHandle();
MOZ_ASSERT(handle);
if (!handle->IsDoomed()) {
_retval->AppendElement(handle);
}
}
}
void CacheFileHandles::ClearAll() {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThreadOrCeased());
mTable.Clear();
}
uint32_t CacheFileHandles::HandleCount() { return mTable.Count(); }
#ifdef DEBUG_HANDLES
void CacheFileHandles::Log(CacheFileHandlesEntry* entry) {
LOG(("CacheFileHandles::Log() BEGIN [entry=%p]", entry));
nsTArray<RefPtr<CacheFileHandle> > array;
aEntry->GetHandles(array);
for (uint32_t i = 0; i < array.Length(); ++i) {
CacheFileHandle* handle = array[i];
handle->Log();
}
LOG(("CacheFileHandles::Log() END [entry=%p]", entry));
}
#endif
// Memory reporting
size_t CacheFileHandles::SizeOfExcludingThis(
mozilla::MallocSizeOf mallocSizeOf) const {
MOZ_ASSERT(CacheFileIOManager::IsOnIOThread());
return mTable.SizeOfExcludingThis(mallocSizeOf);
}
// Events
class ShutdownEvent : public Runnable {
public:
ShutdownEvent()
: Runnable("net::ShutdownEvent"),
mMonitor("ShutdownEvent.mMonitor"),
mNotified(false) {}
protected:
~ShutdownEvent() = default;
public:
NS_IMETHOD Run() override {
MonitorAutoLock mon(mMonitor);
CacheFileIOManager::gInstance->ShutdownInternal();
mNotified = true;
mon.Notify();
return NS_OK;
}
void PostAndWait() {
MonitorAutoLock mon(mMonitor);
DebugOnly<nsresult> rv;
rv = CacheFileIOManager::gInstance->mIOThread->Dispatch(
this,
CacheIOThread::WRITE); // When writes and closing of handles is done
MOZ_ASSERT(NS_SUCCEEDED(rv));
TimeDuration waitTime = TimeDuration::FromSeconds(1);
while (!mNotified) {
mon.Wait(waitTime);
if (!mNotified) {
// If there is any IO blocking on the IO thread, this will
// try to cancel it. Returns no later than after two seconds.
MonitorAutoUnlock unmon(mMonitor); // Prevent delays
CacheFileIOManager::gInstance->mIOThread->CancelBlockingIO();
}
}
}
protected:
mozilla::Monitor mMonitor;
bool mNotified;
};
// Class responsible for reporting IO performance stats
class IOPerfReportEvent {
public:
explicit IOPerfReportEvent(CacheFileUtils::CachePerfStats::EDataType aType)
: mType(aType), mEventCounter(0) {}
void Start(CacheIOThread* aIOThread) {
mStartTime = TimeStamp::Now();
mEventCounter = aIOThread->EventCounter();
}
void Report(CacheIOThread* aIOThread) {
if (mStartTime.IsNull()) {
return;
}
// Single IO operations can take less than 1ms. So we use microseconds to
// keep a good resolution of data.
uint32_t duration = (TimeStamp::Now() - mStartTime).ToMicroseconds();
// This is a simple prefiltering of values that might differ a lot from the
// average value. Do not add the value to the filtered stats when the event
// had to wait in a long queue.
uint32_t eventCounter = aIOThread->EventCounter();
bool shortOnly = eventCounter - mEventCounter < 5 ? false : true;
CacheFileUtils::CachePerfStats::AddValue(mType, duration, shortOnly);
}
protected:
CacheFileUtils::CachePerfStats::EDataType mType;
TimeStamp mStartTime;
uint32_t mEventCounter;
};
class OpenFileEvent : public Runnable, public IOPerfReportEvent {
public:
OpenFileEvent(const nsACString& aKey, uint32_t aFlags,
CacheFileIOListener* aCallback)
: Runnable("net::OpenFileEvent"),
IOPerfReportEvent(CacheFileUtils::CachePerfStats::IO_OPEN),
mFlags(aFlags),
mCallback(aCallback),
mKey(aKey) {
mIOMan = CacheFileIOManager::gInstance;
if (!(mFlags & CacheFileIOManager::SPECIAL_FILE)) {
Start(mIOMan->mIOThread);
}
}
protected:
~OpenFileEvent() = default;
public:
NS_IMETHOD Run() override {
nsresult rv = NS_OK;
if (!(mFlags & CacheFileIOManager::SPECIAL_FILE)) {
SHA1Sum sum;
sum.update(mKey.BeginReading(), mKey.Length());
sum.finish(mHash);
}
if (!mIOMan) {
rv = NS_ERROR_NOT_INITIALIZED;
} else {
if (mFlags & CacheFileIOManager::SPECIAL_FILE) {
rv = mIOMan->OpenSpecialFileInternal(mKey, mFlags,
getter_AddRefs(mHandle));
} else {
rv = mIOMan->OpenFileInternal(&mHash, mKey, mFlags,
getter_AddRefs(mHandle));
if (NS_SUCCEEDED(rv)) {
Report(mIOMan->mIOThread);
}
}
mIOMan = nullptr;
if (mHandle) {
if (mHandle->Key().IsEmpty()) {
mHandle->Key() = mKey;
}
}
}
mCallback->OnFileOpened(mHandle, rv);
return NS_OK;
}
protected:
SHA1Sum::Hash mHash;
uint32_t mFlags;
nsCOMPtr<CacheFileIOListener> mCallback;
RefPtr<CacheFileIOManager> mIOMan;
RefPtr<CacheFileHandle> mHandle;
nsCString mKey;
};
class ReadEvent : public Runnable, public IOPerfReportEvent {
public:
ReadEvent(CacheFileHandle* aHandle, int64_t aOffset, char* aBuf,
int32_t aCount, CacheFileIOListener* aCallback)
: Runnable("net::ReadEvent"),
IOPerfReportEvent(CacheFileUtils::CachePerfStats::IO_READ),
mHandle(aHandle),
mOffset(aOffset),
mBuf(aBuf),
mCount(aCount),
mCallback(aCallback) {
if (!mHandle->IsSpecialFile()) {
Start(CacheFileIOManager::gInstance->mIOThread);
}
}
protected:
~ReadEvent() = default;
public:
NS_IMETHOD Run() override {
nsresult rv;
if (mHandle->IsClosed() || (mCallback && mCallback->IsKilled())) {
rv = NS_ERROR_NOT_INITIALIZED;
} else {
rv = CacheFileIOManager::gInstance->ReadInternal(mHandle, mOffset, mBuf,
mCount);
if (NS_SUCCEEDED(rv)) {
Report(CacheFileIOManager::gInstance->mIOThread);
}
}
mCallback->OnDataRead(mHandle, mBuf, rv);
return NS_OK;
}
protected:
RefPtr<CacheFileHandle> mHandle;
int64_t mOffset;
char* mBuf;
int32_t mCount;
nsCOMPtr<CacheFileIOListener> mCallback;
};
class WriteEvent : public Runnable, public IOPerfReportEvent {
public:
WriteEvent(CacheFileHandle* aHandle, int64_t aOffset, const char* aBuf,
int32_t aCount, bool aValidate, bool aTruncate,
CacheFileIOListener* aCallback)
: Runnable("net::WriteEvent"),
IOPerfReportEvent(CacheFileUtils::CachePerfStats::IO_WRITE),
mHandle(aHandle),
mOffset(aOffset),
mBuf(aBuf),
mCount(aCount),
mValidate(aValidate),
mTruncate(aTruncate),
mCallback(aCallback) {
if (!mHandle->IsSpecialFile()) {
Start(CacheFileIOManager::gInstance->mIOThread);
}
}
protected:
~WriteEvent() {
if (!mCallback && mBuf) {
free(const_cast<char*>(mBuf));
}
}
public:
NS_IMETHOD Run() override {
nsresult rv;
if (mHandle->IsClosed() || (mCallback && mCallback->IsKilled())) {
// We usually get here only after the internal shutdown
// (i.e. mShuttingDown == true). Pretend write has succeeded
// to avoid any past-shutdown file dooming.
rv = (CacheObserver::IsPastShutdownIOLag() ||
CacheFileIOManager::gInstance->mShuttingDown)
? NS_OK
: NS_ERROR_NOT_INITIALIZED;
} else {
rv = CacheFileIOManager::gInstance->WriteInternal(
mHandle, mOffset, mBuf, mCount, mValidate, mTruncate);
if (NS_SUCCEEDED(rv)) {
Report(CacheFileIOManager::gInstance->mIOThread);
}
if (NS_FAILED(rv) && !mCallback) {
// No listener is going to handle the error, doom the file
CacheFileIOManager::gInstance->DoomFileInternal(mHandle);
}
}
if (mCallback) {
mCallback->OnDataWritten(mHandle, mBuf, rv);
} else {
free(const_cast<char*>(mBuf));
mBuf = nullptr;
}
return NS_OK;
}
protected:
RefPtr<CacheFileHandle> mHandle;
int64_t mOffset;
const char* mBuf;
int32_t mCount;
bool mValidate : 1;
bool mTruncate : 1;
nsCOMPtr<CacheFileIOListener> mCallback;
};
class DoomFileEvent : public Runnable {
public:
DoomFileEvent(CacheFileHandle* aHandle, CacheFileIOListener* aCallback)
: Runnable("net::DoomFileEvent"),
mCallback(aCallback),
mHandle(aHandle) {}
protected:
~DoomFileEvent() = default;
public:
NS_IMETHOD Run() override {
nsresult rv;
if (mHandle->IsClosed()) {
rv = NS_ERROR_NOT_INITIALIZED;
} else {
rv = CacheFileIOManager::gInstance->DoomFileInternal(mHandle);
}
if (mCallback) {
mCallback->OnFileDoomed(mHandle, rv);
}
return NS_OK;
}
protected:
nsCOMPtr<CacheFileIOListener> mCallback;
nsCOMPtr<nsIEventTarget> mTarget;
RefPtr<CacheFileHandle> mHandle;
};
class DoomFileByKeyEvent : public Runnable {
public:
DoomFileByKeyEvent(const nsACString& aKey, CacheFileIOListener* aCallback)
: Runnable("net::DoomFileByKeyEvent"), mCallback(aCallback) {
SHA1Sum sum;
sum.update(aKey.BeginReading(), aKey.Length());
sum.finish(mHash);
mIOMan = CacheFileIOManager::gInstance;
}
protected:
~DoomFileByKeyEvent() = default;
public:
NS_IMETHOD Run() override {
nsresult rv;
if (!mIOMan) {
rv = NS_ERROR_NOT_INITIALIZED;
} else {
rv = mIOMan->DoomFileByKeyInternal(&mHash);
mIOMan = nullptr;
}
if (mCallback) {
mCallback->OnFileDoomed(nullptr, rv);
}
return NS_OK;
}
protected:
SHA1Sum::Hash mHash;
nsCOMPtr<CacheFileIOListener> mCallback;
RefPtr<CacheFileIOManager> mIOMan;
};
class ReleaseNSPRHandleEvent : public Runnable {
public:
explicit ReleaseNSPRHandleEvent(CacheFileHandle* aHandle)
: Runnable("net::ReleaseNSPRHandleEvent"), mHandle(aHandle) {}
protected:
~ReleaseNSPRHandleEvent() = default;
public:
NS_IMETHOD Run() override {
if (!mHandle->IsClosed()) {
CacheFileIOManager::gInstance->MaybeReleaseNSPRHandleInternal(mHandle);
}
return NS_OK;
}
protected:
RefPtr<CacheFileHandle> mHandle;
};
class TruncateSeekSetEOFEvent : public Runnable {
public:
TruncateSeekSetEOFEvent(CacheFileHandle* aHandle, int64_t aTruncatePos,
int64_t aEOFPos, CacheFileIOListener* aCallback)
: Runnable("net::TruncateSeekSetEOFEvent"),
mHandle(aHandle),
mTruncatePos(aTruncatePos),
mEOFPos(aEOFPos),
mCallback(aCallback) {}
protected:
~TruncateSeekSetEOFEvent() = default;
public:
NS_IMETHOD Run() override {
nsresult rv;
if (mHandle->IsClosed() || (mCallback && mCallback->IsKilled())) {
rv = NS_ERROR_NOT_INITIALIZED;
} else {
rv = CacheFileIOManager::gInstance->TruncateSeekSetEOFInternal(
mHandle, mTruncatePos, mEOFPos);
}
if (mCallback) {
mCallback->OnEOFSet(mHandle, rv);
}
return NS_OK;
}
protected:
RefPtr<CacheFileHandle> mHandle;
int64_t mTruncatePos;
int64_t mEOFPos;
nsCOMPtr<CacheFileIOListener> mCallback;
};
class RenameFileEvent : public Runnable {
public:
RenameFileEvent(CacheFileHandle* aHandle, const nsACString& aNewName,
CacheFileIOListener* aCallback)
: Runnable("net::RenameFileEvent"),
mHandle(aHandle),
mNewName(aNewName),
mCallback(aCallback) {}
protected:
~RenameFileEvent() = default;
public:
NS_IMETHOD Run() override {
nsresult rv;
if (mHandle->IsClosed()) {
rv = NS_ERROR_NOT_INITIALIZED;
} else {
rv = CacheFileIOManager::gInstance->RenameFileInternal(mHandle, mNewName);
}
if (mCallback) {
mCallback->OnFileRenamed(mHandle, rv);
}
return NS_OK;
}
protected:
RefPtr<CacheFileHandle> mHandle;
nsCString mNewName;
nsCOMPtr<CacheFileIOListener> mCallback;
};
class InitIndexEntryEvent : public Runnable {
public:
InitIndexEntryEvent(CacheFileHandle* aHandle,
OriginAttrsHash aOriginAttrsHash, bool aAnonymous,
bool aPinning)
: Runnable("net::InitIndexEntryEvent"),
mHandle(aHandle),
mOriginAttrsHash(aOriginAttrsHash),
mAnonymous(aAnonymous),
mPinning(aPinning) {}
protected:
~InitIndexEntryEvent() = default;
public:
NS_IMETHOD Run() override {
if (mHandle->IsClosed() || mHandle->IsDoomed()) {
return NS_OK;
}
CacheIndex::InitEntry(mHandle->Hash(), mOriginAttrsHash, mAnonymous,
mPinning);
// We cannot set the filesize before we init the entry. If we're opening
// an existing entry file, frecency will be set after parsing the entry
// file, but we must set the filesize here since nobody is going to set it
// if there is no write to the file.
uint32_t sizeInK = mHandle->FileSizeInK();
CacheIndex::UpdateEntry(mHandle->Hash(), nullptr, nullptr, nullptr, nullptr,
nullptr, nullptr, 0, &sizeInK);
return NS_OK;
}
protected:
RefPtr<CacheFileHandle> mHandle;
OriginAttrsHash mOriginAttrsHash;
bool mAnonymous;
bool mPinning;
};
class UpdateIndexEntryEvent : public Runnable {
public:
UpdateIndexEntryEvent(CacheFileHandle* aHandle, const uint32_t* aFrecency,
const bool* aHasAltData, const uint16_t* aOnStartTime,
const uint16_t* aOnStopTime,
const uint8_t* aContentType,
const uint16_t* aBaseDomainAccessCount,
const uint32_t aTelemetryReportID)
: Runnable("net::UpdateIndexEntryEvent"),
mHandle(aHandle),