Source code

Revision control

Other Tools

1
/* This Source Code Form is subject to the terms of the Mozilla Public
2
* License, v. 2.0. If a copy of the MPL was not distributed with this
3
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5
#include "CacheLog.h"
6
#include "CacheFileChunk.h"
7
8
#include "CacheFile.h"
9
#include "nsThreadUtils.h"
10
11
#include "mozilla/IntegerPrintfMacros.h"
12
13
namespace mozilla {
14
namespace net {
15
16
#define kMinBufSize 512
17
18
CacheFileChunkBuffer::CacheFileChunkBuffer(CacheFileChunk* aChunk)
19
: mChunk(aChunk),
20
mBuf(nullptr),
21
mBufSize(0),
22
mDataSize(0),
23
mReadHandlesCount(0),
24
mWriteHandleExists(false) {}
25
26
CacheFileChunkBuffer::~CacheFileChunkBuffer() {
27
if (mBuf) {
28
CacheFileUtils::FreeBuffer(mBuf);
29
mBuf = nullptr;
30
mChunk->BuffersAllocationChanged(mBufSize, 0);
31
mBufSize = 0;
32
}
33
}
34
35
void CacheFileChunkBuffer::CopyFrom(CacheFileChunkBuffer* aOther) {
36
MOZ_RELEASE_ASSERT(mBufSize >= aOther->mDataSize);
37
mDataSize = aOther->mDataSize;
38
memcpy(mBuf, aOther->mBuf, mDataSize);
39
}
40
41
nsresult CacheFileChunkBuffer::FillInvalidRanges(
42
CacheFileChunkBuffer* aOther, CacheFileUtils::ValidityMap* aMap) {
43
nsresult rv;
44
45
rv = EnsureBufSize(aOther->mDataSize);
46
if (NS_FAILED(rv)) {
47
return rv;
48
}
49
50
uint32_t invalidOffset = 0;
51
uint32_t invalidLength;
52
53
for (uint32_t i = 0; i < aMap->Length(); ++i) {
54
uint32_t validOffset = (*aMap)[i].Offset();
55
uint32_t validLength = (*aMap)[i].Len();
56
57
MOZ_RELEASE_ASSERT(invalidOffset <= validOffset);
58
invalidLength = validOffset - invalidOffset;
59
if (invalidLength > 0) {
60
MOZ_RELEASE_ASSERT(invalidOffset + invalidLength <= aOther->mDataSize);
61
memcpy(mBuf + invalidOffset, aOther->mBuf + invalidOffset, invalidLength);
62
}
63
invalidOffset = validOffset + validLength;
64
}
65
66
if (invalidOffset < aOther->mDataSize) {
67
invalidLength = aOther->mDataSize - invalidOffset;
68
memcpy(mBuf + invalidOffset, aOther->mBuf + invalidOffset, invalidLength);
69
}
70
71
return NS_OK;
72
}
73
74
MOZ_MUST_USE nsresult CacheFileChunkBuffer::EnsureBufSize(uint32_t aBufSize) {
75
AssertOwnsLock();
76
77
if (mBufSize >= aBufSize) {
78
return NS_OK;
79
}
80
81
// find smallest power of 2 greater than or equal to aBufSize
82
aBufSize--;
83
aBufSize |= aBufSize >> 1;
84
aBufSize |= aBufSize >> 2;
85
aBufSize |= aBufSize >> 4;
86
aBufSize |= aBufSize >> 8;
87
aBufSize |= aBufSize >> 16;
88
aBufSize++;
89
90
const uint32_t minBufSize = kMinBufSize;
91
const uint32_t maxBufSize = kChunkSize;
92
aBufSize = clamped(aBufSize, minBufSize, maxBufSize);
93
94
if (!mChunk->CanAllocate(aBufSize - mBufSize)) {
95
return NS_ERROR_OUT_OF_MEMORY;
96
}
97
98
char* newBuf = static_cast<char*>(realloc(mBuf, aBufSize));
99
if (!newBuf) {
100
return NS_ERROR_OUT_OF_MEMORY;
101
}
102
103
mChunk->BuffersAllocationChanged(mBufSize, aBufSize);
104
mBuf = newBuf;
105
mBufSize = aBufSize;
106
107
return NS_OK;
108
}
109
110
void CacheFileChunkBuffer::SetDataSize(uint32_t aDataSize) {
111
MOZ_RELEASE_ASSERT(
112
// EnsureBufSize must be called before SetDataSize, so the new data size
113
// is guaranteed to be smaller than or equal to mBufSize.
114
aDataSize <= mBufSize ||
115
// The only exception is an optimization when we read the data from the
116
// disk. The data is read to a separate buffer and CacheFileChunk::mBuf is
117
// empty (see CacheFileChunk::Read). We need to set mBuf::mDataSize
118
// accordingly so that DataSize() methods return correct value, but we
119
// don't want to allocate the buffer since it wouldn't be used in most
120
// cases.
121
(mBufSize == 0 && mChunk->mState == CacheFileChunk::READING));
122
123
mDataSize = aDataSize;
124
}
125
126
void CacheFileChunkBuffer::AssertOwnsLock() const { mChunk->AssertOwnsLock(); }
127
128
void CacheFileChunkBuffer::RemoveReadHandle() {
129
AssertOwnsLock();
130
MOZ_RELEASE_ASSERT(mReadHandlesCount);
131
MOZ_RELEASE_ASSERT(!mWriteHandleExists);
132
mReadHandlesCount--;
133
134
if (mReadHandlesCount == 0 && mChunk->mBuf != this) {
135
DebugOnly<bool> removed = mChunk->mOldBufs.RemoveElement(this);
136
MOZ_ASSERT(removed);
137
}
138
}
139
140
void CacheFileChunkBuffer::RemoveWriteHandle() {
141
AssertOwnsLock();
142
MOZ_RELEASE_ASSERT(mReadHandlesCount == 0);
143
MOZ_RELEASE_ASSERT(mWriteHandleExists);
144
mWriteHandleExists = false;
145
}
146
147
size_t CacheFileChunkBuffer::SizeOfIncludingThis(
148
mozilla::MallocSizeOf mallocSizeOf) const {
149
size_t n = mallocSizeOf(this);
150
151
if (mBuf) {
152
n += mallocSizeOf(mBuf);
153
}
154
155
return n;
156
}
157
158
uint32_t CacheFileChunkHandle::DataSize() {
159
MOZ_ASSERT(mBuf, "Unexpected call on dummy handle");
160
mBuf->AssertOwnsLock();
161
return mBuf->mDataSize;
162
}
163
164
uint32_t CacheFileChunkHandle::Offset() {
165
MOZ_ASSERT(mBuf, "Unexpected call on dummy handle");
166
mBuf->AssertOwnsLock();
167
return mBuf->mChunk->Index() * kChunkSize;
168
}
169
170
CacheFileChunkReadHandle::CacheFileChunkReadHandle(CacheFileChunkBuffer* aBuf) {
171
mBuf = aBuf;
172
mBuf->mReadHandlesCount++;
173
}
174
175
CacheFileChunkReadHandle::~CacheFileChunkReadHandle() {
176
mBuf->RemoveReadHandle();
177
}
178
179
const char* CacheFileChunkReadHandle::Buf() { return mBuf->mBuf; }
180
181
CacheFileChunkWriteHandle::CacheFileChunkWriteHandle(
182
CacheFileChunkBuffer* aBuf) {
183
mBuf = aBuf;
184
if (mBuf) {
185
MOZ_ASSERT(!mBuf->mWriteHandleExists);
186
mBuf->mWriteHandleExists = true;
187
}
188
}
189
190
CacheFileChunkWriteHandle::~CacheFileChunkWriteHandle() {
191
if (mBuf) {
192
mBuf->RemoveWriteHandle();
193
}
194
}
195
196
char* CacheFileChunkWriteHandle::Buf() { return mBuf ? mBuf->mBuf : nullptr; }
197
198
void CacheFileChunkWriteHandle::UpdateDataSize(uint32_t aOffset,
199
uint32_t aLen) {
200
MOZ_ASSERT(mBuf, "Write performed on dummy handle?");
201
MOZ_ASSERT(aOffset <= mBuf->mDataSize);
202
MOZ_ASSERT(aOffset + aLen <= mBuf->mBufSize);
203
204
if (aOffset + aLen > mBuf->mDataSize) {
205
mBuf->mDataSize = aOffset + aLen;
206
}
207
208
mBuf->mChunk->UpdateDataSize(aOffset, aLen);
209
}
210
211
class NotifyUpdateListenerEvent : public Runnable {
212
public:
213
NotifyUpdateListenerEvent(CacheFileChunkListener* aCallback,
214
CacheFileChunk* aChunk)
215
: Runnable("net::NotifyUpdateListenerEvent"),
216
mCallback(aCallback),
217
mChunk(aChunk) {
218
LOG(("NotifyUpdateListenerEvent::NotifyUpdateListenerEvent() [this=%p]",
219
this));
220
}
221
222
protected:
223
~NotifyUpdateListenerEvent() {
224
LOG(("NotifyUpdateListenerEvent::~NotifyUpdateListenerEvent() [this=%p]",
225
this));
226
}
227
228
public:
229
NS_IMETHOD Run() override {
230
LOG(("NotifyUpdateListenerEvent::Run() [this=%p]", this));
231
232
mCallback->OnChunkUpdated(mChunk);
233
return NS_OK;
234
}
235
236
protected:
237
nsCOMPtr<CacheFileChunkListener> mCallback;
238
RefPtr<CacheFileChunk> mChunk;
239
};
240
241
bool CacheFileChunk::DispatchRelease() {
242
if (NS_IsMainThread()) {
243
return false;
244
}
245
246
NS_DispatchToMainThread(NewNonOwningRunnableMethod(
247
"net::CacheFileChunk::Release", this, &CacheFileChunk::Release));
248
249
return true;
250
}
251
252
NS_IMPL_ADDREF(CacheFileChunk)
253
NS_IMETHODIMP_(MozExternalRefCountType)
254
CacheFileChunk::Release() {
255
nsrefcnt count = mRefCnt - 1;
256
if (DispatchRelease()) {
257
// Redispatched to the main thread.
258
return count;
259
}
260
261
MOZ_ASSERT(0 != mRefCnt, "dup release");
262
count = --mRefCnt;
263
NS_LOG_RELEASE(this, count, "CacheFileChunk");
264
265
if (0 == count) {
266
mRefCnt = 1;
267
delete (this);
268
return 0;
269
}
270
271
// We can safely access this chunk after decreasing mRefCnt since we re-post
272
// all calls to Release() happening off the main thread to the main thread.
273
// I.e. no other Release() that would delete the object could be run before
274
// we call CacheFile::DeactivateChunk().
275
//
276
// NOTE: we don't grab the CacheFile's lock, so the chunk might be addrefed
277
// on another thread before CacheFile::DeactivateChunk() grabs the lock on
278
// this thread. To make sure we won't deactivate chunk that was just returned
279
// to a new consumer we check mRefCnt once again in
280
// CacheFile::DeactivateChunk() after we grab the lock.
281
if (mActiveChunk && count == 1) {
282
mFile->DeactivateChunk(this);
283
}
284
285
return count;
286
}
287
288
NS_INTERFACE_MAP_BEGIN(CacheFileChunk)
289
NS_INTERFACE_MAP_ENTRY(mozilla::net::CacheFileIOListener)
290
NS_INTERFACE_MAP_ENTRY(nsISupports)
291
NS_INTERFACE_MAP_END
292
293
CacheFileChunk::CacheFileChunk(CacheFile* aFile, uint32_t aIndex,
294
bool aInitByWriter)
295
: CacheMemoryConsumer(aFile->mOpenAsMemoryOnly ? MEMORY_ONLY : DONT_REPORT),
296
mIndex(aIndex),
297
mState(INITIAL),
298
mStatus(NS_OK),
299
mActiveChunk(false),
300
mIsDirty(false),
301
mDiscardedChunk(false),
302
mBuffersSize(0),
303
mLimitAllocation(!aFile->mOpenAsMemoryOnly && aInitByWriter),
304
mIsPriority(aFile->mPriority),
305
mExpectedHash(0),
306
mFile(aFile) {
307
LOG(("CacheFileChunk::CacheFileChunk() [this=%p, index=%u, initByWriter=%d]",
308
this, aIndex, aInitByWriter));
309
mBuf = new CacheFileChunkBuffer(this);
310
}
311
312
CacheFileChunk::~CacheFileChunk() {
313
LOG(("CacheFileChunk::~CacheFileChunk() [this=%p]", this));
314
}
315
316
void CacheFileChunk::AssertOwnsLock() const { mFile->AssertOwnsLock(); }
317
318
void CacheFileChunk::InitNew() {
319
AssertOwnsLock();
320
321
LOG(("CacheFileChunk::InitNew() [this=%p]", this));
322
323
MOZ_ASSERT(mState == INITIAL);
324
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
325
MOZ_ASSERT(!mBuf->Buf());
326
MOZ_ASSERT(!mWritingStateHandle);
327
MOZ_ASSERT(!mReadingStateBuf);
328
MOZ_ASSERT(!mIsDirty);
329
330
mBuf = new CacheFileChunkBuffer(this);
331
mState = READY;
332
}
333
334
nsresult CacheFileChunk::Read(CacheFileHandle* aHandle, uint32_t aLen,
335
CacheHash::Hash16_t aHash,
336
CacheFileChunkListener* aCallback) {
337
AssertOwnsLock();
338
339
LOG(("CacheFileChunk::Read() [this=%p, handle=%p, len=%d, listener=%p]", this,
340
aHandle, aLen, aCallback));
341
342
MOZ_ASSERT(mState == INITIAL);
343
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
344
MOZ_ASSERT(!mBuf->Buf());
345
MOZ_ASSERT(!mWritingStateHandle);
346
MOZ_ASSERT(!mReadingStateBuf);
347
MOZ_ASSERT(aLen);
348
349
nsresult rv;
350
351
mState = READING;
352
353
RefPtr<CacheFileChunkBuffer> tmpBuf = new CacheFileChunkBuffer(this);
354
rv = tmpBuf->EnsureBufSize(aLen);
355
if (NS_FAILED(rv)) {
356
SetError(rv);
357
return mStatus;
358
}
359
tmpBuf->SetDataSize(aLen);
360
361
rv = CacheFileIOManager::Read(aHandle, mIndex * kChunkSize, tmpBuf->Buf(),
362
aLen, this);
363
if (NS_WARN_IF(NS_FAILED(rv))) {
364
rv = mIndex ? NS_ERROR_FILE_CORRUPTED : NS_ERROR_FILE_NOT_FOUND;
365
SetError(rv);
366
} else {
367
mReadingStateBuf.swap(tmpBuf);
368
mListener = aCallback;
369
// mBuf contains no data but we set datasize to size of the data that will
370
// be read from the disk. No handle is allowed to access the non-existent
371
// data until reading finishes, but data can be appended or overwritten.
372
// These pieces are tracked in mValidityMap and will be merged with the data
373
// read from disk in OnDataRead().
374
mBuf->SetDataSize(aLen);
375
mExpectedHash = aHash;
376
}
377
378
return rv;
379
}
380
381
nsresult CacheFileChunk::Write(CacheFileHandle* aHandle,
382
CacheFileChunkListener* aCallback) {
383
AssertOwnsLock();
384
385
LOG(("CacheFileChunk::Write() [this=%p, handle=%p, listener=%p]", this,
386
aHandle, aCallback));
387
388
MOZ_ASSERT(mState == READY);
389
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
390
MOZ_ASSERT(!mWritingStateHandle);
391
MOZ_ASSERT(mBuf->DataSize()); // Don't write chunk when it is empty
392
MOZ_ASSERT(mBuf->ReadHandlesCount() == 0);
393
MOZ_ASSERT(!mBuf->WriteHandleExists());
394
395
nsresult rv;
396
397
mState = WRITING;
398
mWritingStateHandle = new CacheFileChunkReadHandle(mBuf);
399
400
rv = CacheFileIOManager::Write(
401
aHandle, mIndex * kChunkSize, mWritingStateHandle->Buf(),
402
mWritingStateHandle->DataSize(), false, false, this);
403
if (NS_WARN_IF(NS_FAILED(rv))) {
404
mWritingStateHandle = nullptr;
405
SetError(rv);
406
} else {
407
mListener = aCallback;
408
mIsDirty = false;
409
}
410
411
return rv;
412
}
413
414
void CacheFileChunk::WaitForUpdate(CacheFileChunkListener* aCallback) {
415
AssertOwnsLock();
416
417
LOG(("CacheFileChunk::WaitForUpdate() [this=%p, listener=%p]", this,
418
aCallback));
419
420
MOZ_ASSERT(mFile->mOutput);
421
MOZ_ASSERT(IsReady());
422
423
#ifdef DEBUG
424
for (uint32_t i = 0; i < mUpdateListeners.Length(); i++) {
425
MOZ_ASSERT(mUpdateListeners[i]->mCallback != aCallback);
426
}
427
#endif
428
429
ChunkListenerItem* item = new ChunkListenerItem();
430
item->mTarget = CacheFileIOManager::IOTarget();
431
if (!item->mTarget) {
432
LOG(
433
("CacheFileChunk::WaitForUpdate() - Cannot get Cache I/O thread! Using "
434
"main thread for callback."));
435
item->mTarget = GetMainThreadEventTarget();
436
}
437
item->mCallback = aCallback;
438
MOZ_ASSERT(item->mTarget);
439
item->mCallback = aCallback;
440
441
mUpdateListeners.AppendElement(item);
442
}
443
444
nsresult CacheFileChunk::CancelWait(CacheFileChunkListener* aCallback) {
445
AssertOwnsLock();
446
447
LOG(("CacheFileChunk::CancelWait() [this=%p, listener=%p]", this, aCallback));
448
449
MOZ_ASSERT(IsReady());
450
451
uint32_t i;
452
for (i = 0; i < mUpdateListeners.Length(); i++) {
453
ChunkListenerItem* item = mUpdateListeners[i];
454
455
if (item->mCallback == aCallback) {
456
mUpdateListeners.RemoveElementAt(i);
457
delete item;
458
break;
459
}
460
}
461
462
#ifdef DEBUG
463
for (; i < mUpdateListeners.Length(); i++) {
464
MOZ_ASSERT(mUpdateListeners[i]->mCallback != aCallback);
465
}
466
#endif
467
468
return NS_OK;
469
}
470
471
nsresult CacheFileChunk::NotifyUpdateListeners() {
472
AssertOwnsLock();
473
474
LOG(("CacheFileChunk::NotifyUpdateListeners() [this=%p]", this));
475
476
MOZ_ASSERT(IsReady());
477
478
nsresult rv, rv2;
479
480
rv = NS_OK;
481
for (uint32_t i = 0; i < mUpdateListeners.Length(); i++) {
482
ChunkListenerItem* item = mUpdateListeners[i];
483
484
LOG(
485
("CacheFileChunk::NotifyUpdateListeners() - Notifying listener %p "
486
"[this=%p]",
487
item->mCallback.get(), this));
488
489
RefPtr<NotifyUpdateListenerEvent> ev;
490
ev = new NotifyUpdateListenerEvent(item->mCallback, this);
491
rv2 = item->mTarget->Dispatch(ev, NS_DISPATCH_NORMAL);
492
if (NS_FAILED(rv2) && NS_SUCCEEDED(rv)) rv = rv2;
493
delete item;
494
}
495
496
mUpdateListeners.Clear();
497
498
return rv;
499
}
500
501
uint32_t CacheFileChunk::Index() const { return mIndex; }
502
503
CacheHash::Hash16_t CacheFileChunk::Hash() const {
504
MOZ_ASSERT(IsReady());
505
506
return CacheHash::Hash16(mBuf->Buf(), mBuf->DataSize());
507
}
508
509
uint32_t CacheFileChunk::DataSize() const { return mBuf->DataSize(); }
510
511
void CacheFileChunk::UpdateDataSize(uint32_t aOffset, uint32_t aLen) {
512
AssertOwnsLock();
513
514
// UpdateDataSize() is called only when we've written some data to the chunk
515
// and we never write data anymore once some error occurs.
516
MOZ_ASSERT(NS_SUCCEEDED(mStatus));
517
518
LOG(("CacheFileChunk::UpdateDataSize() [this=%p, offset=%d, len=%d]", this,
519
aOffset, aLen));
520
521
mIsDirty = true;
522
523
int64_t fileSize = static_cast<int64_t>(kChunkSize) * mIndex + aOffset + aLen;
524
bool notify = false;
525
526
if (fileSize > mFile->mDataSize) {
527
mFile->mDataSize = fileSize;
528
notify = true;
529
}
530
531
if (mState == READY || mState == WRITING) {
532
MOZ_ASSERT(mValidityMap.Length() == 0);
533
534
if (notify) {
535
NotifyUpdateListeners();
536
}
537
538
return;
539
}
540
541
// We're still waiting for data from the disk. This chunk cannot be used by
542
// input stream, so there must be no update listener. We also need to keep
543
// track of where the data is written so that we can correctly merge the new
544
// data with the old one.
545
546
MOZ_ASSERT(mUpdateListeners.Length() == 0);
547
MOZ_ASSERT(mState == READING);
548
549
mValidityMap.AddPair(aOffset, aLen);
550
mValidityMap.Log();
551
}
552
553
nsresult CacheFileChunk::Truncate(uint32_t aOffset) {
554
MOZ_RELEASE_ASSERT(mState == READY || mState == WRITING || mState == READING);
555
556
if (mState == READING) {
557
mIsDirty = true;
558
}
559
560
mBuf->SetDataSize(aOffset);
561
return NS_OK;
562
}
563
564
nsresult CacheFileChunk::OnFileOpened(CacheFileHandle* aHandle,
565
nsresult aResult) {
566
MOZ_CRASH("CacheFileChunk::OnFileOpened should not be called!");
567
return NS_ERROR_UNEXPECTED;
568
}
569
570
nsresult CacheFileChunk::OnDataWritten(CacheFileHandle* aHandle,
571
const char* aBuf, nsresult aResult) {
572
LOG((
573
"CacheFileChunk::OnDataWritten() [this=%p, handle=%p, result=0x%08" PRIx32
574
"]",
575
this, aHandle, static_cast<uint32_t>(aResult)));
576
577
nsCOMPtr<CacheFileChunkListener> listener;
578
579
{
580
CacheFileAutoLock lock(mFile);
581
582
MOZ_ASSERT(mState == WRITING);
583
MOZ_ASSERT(mListener);
584
585
mWritingStateHandle = nullptr;
586
587
if (NS_WARN_IF(NS_FAILED(aResult))) {
588
SetError(aResult);
589
}
590
591
mState = READY;
592
mListener.swap(listener);
593
}
594
595
listener->OnChunkWritten(aResult, this);
596
597
return NS_OK;
598
}
599
600
nsresult CacheFileChunk::OnDataRead(CacheFileHandle* aHandle, char* aBuf,
601
nsresult aResult) {
602
LOG(("CacheFileChunk::OnDataRead() [this=%p, handle=%p, result=0x%08" PRIx32
603
"]",
604
this, aHandle, static_cast<uint32_t>(aResult)));
605
606
nsCOMPtr<CacheFileChunkListener> listener;
607
608
{
609
CacheFileAutoLock lock(mFile);
610
611
MOZ_ASSERT(mState == READING);
612
MOZ_ASSERT(mListener);
613
MOZ_ASSERT(mReadingStateBuf);
614
MOZ_RELEASE_ASSERT(mBuf->ReadHandlesCount() == 0);
615
MOZ_RELEASE_ASSERT(!mBuf->WriteHandleExists());
616
617
RefPtr<CacheFileChunkBuffer> tmpBuf;
618
tmpBuf.swap(mReadingStateBuf);
619
620
if (NS_SUCCEEDED(aResult)) {
621
CacheHash::Hash16_t hash =
622
CacheHash::Hash16(tmpBuf->Buf(), tmpBuf->DataSize());
623
if (hash != mExpectedHash) {
624
LOG(
625
("CacheFileChunk::OnDataRead() - Hash mismatch! Hash of the data is"
626
" %hx, hash in metadata is %hx. [this=%p, idx=%d]",
627
hash, mExpectedHash, this, mIndex));
628
aResult = NS_ERROR_FILE_CORRUPTED;
629
} else {
630
if (mBuf->DataSize() < tmpBuf->DataSize()) {
631
// Truncate() was called while the data was being read.
632
tmpBuf->SetDataSize(mBuf->DataSize());
633
}
634
635
if (!mBuf->Buf()) {
636
// Just swap the buffers if mBuf is still empty
637
mBuf.swap(tmpBuf);
638
} else {
639
LOG(("CacheFileChunk::OnDataRead() - Merging buffers. [this=%p]",
640
this));
641
642
mValidityMap.Log();
643
aResult = mBuf->FillInvalidRanges(tmpBuf, &mValidityMap);
644
mValidityMap.Clear();
645
}
646
}
647
}
648
649
if (NS_FAILED(aResult)) {
650
aResult = mIndex ? NS_ERROR_FILE_CORRUPTED : NS_ERROR_FILE_NOT_FOUND;
651
SetError(aResult);
652
mBuf->SetDataSize(0);
653
}
654
655
mState = READY;
656
mListener.swap(listener);
657
}
658
659
listener->OnChunkRead(aResult, this);
660
661
return NS_OK;
662
}
663
664
nsresult CacheFileChunk::OnFileDoomed(CacheFileHandle* aHandle,
665
nsresult aResult) {
666
MOZ_CRASH("CacheFileChunk::OnFileDoomed should not be called!");
667
return NS_ERROR_UNEXPECTED;
668
}
669
670
nsresult CacheFileChunk::OnEOFSet(CacheFileHandle* aHandle, nsresult aResult) {
671
MOZ_CRASH("CacheFileChunk::OnEOFSet should not be called!");
672
return NS_ERROR_UNEXPECTED;
673
}
674
675
nsresult CacheFileChunk::OnFileRenamed(CacheFileHandle* aHandle,
676
nsresult aResult) {
677
MOZ_CRASH("CacheFileChunk::OnFileRenamed should not be called!");
678
return NS_ERROR_UNEXPECTED;
679
}
680
681
bool CacheFileChunk::IsKilled() { return mFile->IsKilled(); }
682
683
bool CacheFileChunk::IsReady() const {
684
return (NS_SUCCEEDED(mStatus) && (mState == READY || mState == WRITING));
685
}
686
687
bool CacheFileChunk::IsDirty() const {
688
AssertOwnsLock();
689
690
return mIsDirty;
691
}
692
693
nsresult CacheFileChunk::GetStatus() { return mStatus; }
694
695
void CacheFileChunk::SetError(nsresult aStatus) {
696
LOG(("CacheFileChunk::SetError() [this=%p, status=0x%08" PRIx32 "]", this,
697
static_cast<uint32_t>(aStatus)));
698
699
MOZ_ASSERT(NS_FAILED(aStatus));
700
701
if (NS_FAILED(mStatus)) {
702
// Remember only the first error code.
703
return;
704
}
705
706
mStatus = aStatus;
707
}
708
709
CacheFileChunkReadHandle CacheFileChunk::GetReadHandle() {
710
LOG(("CacheFileChunk::GetReadHandle() [this=%p]", this));
711
712
AssertOwnsLock();
713
714
MOZ_RELEASE_ASSERT(mState == READY || mState == WRITING);
715
// We don't release the lock when writing the data and CacheFileOutputStream
716
// doesn't get the read handle, so there cannot be a write handle when read
717
// handle is obtained.
718
MOZ_RELEASE_ASSERT(!mBuf->WriteHandleExists());
719
720
return CacheFileChunkReadHandle(mBuf);
721
}
722
723
CacheFileChunkWriteHandle CacheFileChunk::GetWriteHandle(
724
uint32_t aEnsuredBufSize) {
725
LOG(("CacheFileChunk::GetWriteHandle() [this=%p, ensuredBufSize=%u]", this,
726
aEnsuredBufSize));
727
728
AssertOwnsLock();
729
730
if (NS_FAILED(mStatus)) {
731
return CacheFileChunkWriteHandle(nullptr); // dummy handle
732
}
733
734
nsresult rv;
735
736
// We don't support multiple write handles
737
MOZ_RELEASE_ASSERT(!mBuf->WriteHandleExists());
738
739
if (mBuf->ReadHandlesCount()) {
740
LOG(
741
("CacheFileChunk::GetWriteHandle() - cloning buffer because of existing"
742
" read handle"));
743
744
MOZ_RELEASE_ASSERT(mState != READING);
745
RefPtr<CacheFileChunkBuffer> newBuf = new CacheFileChunkBuffer(this);
746
rv = newBuf->EnsureBufSize(std::max(aEnsuredBufSize, mBuf->DataSize()));
747
if (NS_SUCCEEDED(rv)) {
748
newBuf->CopyFrom(mBuf);
749
mOldBufs.AppendElement(mBuf);
750
mBuf = newBuf;
751
}
752
} else {
753
rv = mBuf->EnsureBufSize(aEnsuredBufSize);
754
}
755
756
if (NS_FAILED(rv)) {
757
SetError(NS_ERROR_OUT_OF_MEMORY);
758
return CacheFileChunkWriteHandle(nullptr); // dummy handle
759
}
760
761
return CacheFileChunkWriteHandle(mBuf);
762
}
763
764
// Memory reporting
765
766
size_t CacheFileChunk::SizeOfExcludingThis(
767
mozilla::MallocSizeOf mallocSizeOf) const {
768
size_t n = mBuf->SizeOfIncludingThis(mallocSizeOf);
769
770
if (mReadingStateBuf) {
771
n += mReadingStateBuf->SizeOfIncludingThis(mallocSizeOf);
772
}
773
774
for (uint32_t i = 0; i < mOldBufs.Length(); ++i) {
775
n += mOldBufs[i]->SizeOfIncludingThis(mallocSizeOf);
776
}
777
778
n += mValidityMap.SizeOfExcludingThis(mallocSizeOf);
779
780
return n;
781
}
782
783
size_t CacheFileChunk::SizeOfIncludingThis(
784
mozilla::MallocSizeOf mallocSizeOf) const {
785
return mallocSizeOf(this) + SizeOfExcludingThis(mallocSizeOf);
786
}
787
788
bool CacheFileChunk::CanAllocate(uint32_t aSize) const {
789
if (!mLimitAllocation) {
790
return true;
791
}
792
793
LOG(("CacheFileChunk::CanAllocate() [this=%p, size=%u]", this, aSize));
794
795
int64_t limit = CacheObserver::MaxDiskChunksMemoryUsage(mIsPriority);
796
if (limit == 0) {
797
return true;
798
}
799
800
limit <<= 10;
801
if (limit > UINT32_MAX) {
802
limit = UINT32_MAX;
803
}
804
805
int64_t usage = ChunksMemoryUsage();
806
if (usage + aSize > limit) {
807
LOG(("CacheFileChunk::CanAllocate() - Returning false. [this=%p]", this));
808
return false;
809
}
810
811
return true;
812
}
813
814
void CacheFileChunk::BuffersAllocationChanged(uint32_t aFreed,
815
uint32_t aAllocated) {
816
uint32_t oldBuffersSize = mBuffersSize;
817
mBuffersSize += aAllocated;
818
mBuffersSize -= aFreed;
819
820
DoMemoryReport(sizeof(CacheFileChunk) + mBuffersSize);
821
822
if (!mLimitAllocation) {
823
return;
824
}
825
826
ChunksMemoryUsage() -= oldBuffersSize;
827
ChunksMemoryUsage() += mBuffersSize;
828
LOG(
829
("CacheFileChunk::BuffersAllocationChanged() - %s chunks usage %u "
830
"[this=%p]",
831
mIsPriority ? "Priority" : "Normal",
832
static_cast<uint32_t>(ChunksMemoryUsage()), this));
833
}
834
835
mozilla::Atomic<uint32_t, ReleaseAcquire>& CacheFileChunk::ChunksMemoryUsage()
836
const {
837
static mozilla::Atomic<uint32_t, ReleaseAcquire> chunksMemoryUsage(0);
838
static mozilla::Atomic<uint32_t, ReleaseAcquire> prioChunksMemoryUsage(0);
839
return mIsPriority ? prioChunksMemoryUsage : chunksMemoryUsage;
840
}
841
842
} // namespace net
843
} // namespace mozilla