summaryrefslogtreecommitdiffstats
path: root/netwerk/cache2/CacheFileChunk.cpp
blob: 83d79f79fceb7b886ee4fa89bfa54230323b9deb (plain)
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
/* 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 "CacheFileChunk.h"

#include "CacheFile.h"
#include "nsThreadUtils.h"

namespace mozilla {
namespace net {

#define kMinBufSize        512

CacheFileChunkBuffer::CacheFileChunkBuffer(CacheFileChunk *aChunk)
  : mChunk(aChunk)
  , mBuf(nullptr)
  , mBufSize(0)
  , mDataSize(0)
  , mReadHandlesCount(0)
  , mWriteHandleExists(false)
{
}

CacheFileChunkBuffer::~CacheFileChunkBuffer()
{
  if (mBuf) {
    CacheFileUtils::FreeBuffer(mBuf);
    mBuf = nullptr;
    mChunk->BuffersAllocationChanged(mBufSize, 0);
    mBufSize = 0;
  }
}

void
CacheFileChunkBuffer::CopyFrom(CacheFileChunkBuffer *aOther)
{
  MOZ_RELEASE_ASSERT(mBufSize >= aOther->mDataSize);
  mDataSize = aOther->mDataSize;
  memcpy(mBuf, aOther->mBuf, mDataSize);
}

nsresult
CacheFileChunkBuffer::FillInvalidRanges(CacheFileChunkBuffer *aOther,
                                        CacheFileUtils::ValidityMap *aMap)
{
  nsresult rv;

  rv = EnsureBufSize(aOther->mDataSize);
  if (NS_FAILED(rv)) {
    return rv;
  }

  uint32_t invalidOffset = 0;
  uint32_t invalidLength;

  for (uint32_t i = 0; i < aMap->Length(); ++i) {
    uint32_t validOffset = (*aMap)[i].Offset();
    uint32_t validLength = (*aMap)[i].Len();

    MOZ_RELEASE_ASSERT(invalidOffset <= validOffset);
    invalidLength = validOffset - invalidOffset;
    if (invalidLength > 0) {
      MOZ_RELEASE_ASSERT(invalidOffset + invalidLength <= aOther->mBufSize);
      memcpy(mBuf + invalidOffset, aOther->mBuf + invalidOffset, invalidLength);
    }
    invalidOffset = validOffset + validLength;
  }

  if (invalidOffset < aOther->mBufSize) {
    invalidLength = aOther->mBufSize - invalidOffset;
    memcpy(mBuf + invalidOffset, aOther->mBuf + invalidOffset, invalidLength);
  }

  return NS_OK;
}

MOZ_MUST_USE nsresult
CacheFileChunkBuffer::EnsureBufSize(uint32_t aBufSize)
{
  AssertOwnsLock();

  if (mBufSize >= aBufSize) {
    return NS_OK;
  }

  // find smallest power of 2 greater than or equal to aBufSize
  aBufSize--;
  aBufSize |= aBufSize >> 1;
  aBufSize |= aBufSize >> 2;
  aBufSize |= aBufSize >> 4;
  aBufSize |= aBufSize >> 8;
  aBufSize |= aBufSize >> 16;
  aBufSize++;

  const uint32_t minBufSize = kMinBufSize;
  const uint32_t maxBufSize = kChunkSize;
  aBufSize = clamped(aBufSize, minBufSize, maxBufSize);

  if (!mChunk->CanAllocate(aBufSize - mBufSize)) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  char *newBuf = static_cast<char *>(realloc(mBuf, aBufSize));
  if (!newBuf) {
    return NS_ERROR_OUT_OF_MEMORY;
  }

  mChunk->BuffersAllocationChanged(mBufSize, aBufSize);
  mBuf = newBuf;
  mBufSize = aBufSize;

  return NS_OK;
}

void
CacheFileChunkBuffer::SetDataSize(uint32_t aDataSize)
{
  MOZ_RELEASE_ASSERT(
    // EnsureBufSize must be called before SetDataSize, so the new data size
    // is guaranteed to be smaller than or equal to mBufSize.
    aDataSize <= mBufSize ||
    // The only exception is an optimization when we read the data from the
    // disk. The data is read to a separate buffer and CacheFileChunk::mBuf is
    // empty (see CacheFileChunk::Read). We need to set mBuf::mDataSize
    // accordingly so that DataSize() methods return correct value, but we don't
    // want to allocate the buffer since it wouldn't be used in most cases.
    (mDataSize == 0 && mBufSize == 0 && mChunk->mState == CacheFileChunk::READING));

  mDataSize = aDataSize;
}

void
CacheFileChunkBuffer::AssertOwnsLock() const
{
  mChunk->AssertOwnsLock();
}

void
CacheFileChunkBuffer::RemoveReadHandle()
{
  AssertOwnsLock();
  MOZ_RELEASE_ASSERT(mReadHandlesCount);
  MOZ_RELEASE_ASSERT(!mWriteHandleExists);
  mReadHandlesCount--;

  if (mReadHandlesCount == 0 && mChunk->mBuf != this) {
    DebugOnly<bool> removed = mChunk->mOldBufs.RemoveElement(this);
    MOZ_ASSERT(removed);
  }
}

void
CacheFileChunkBuffer::RemoveWriteHandle()
{
  AssertOwnsLock();
  MOZ_RELEASE_ASSERT(mReadHandlesCount == 0);
  MOZ_RELEASE_ASSERT(mWriteHandleExists);
  mWriteHandleExists = false;
}

size_t
CacheFileChunkBuffer::SizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const
{
  size_t n = mallocSizeOf(this);

  if (mBuf) {
    n += mallocSizeOf(mBuf);
  }

  return n;
}

uint32_t
CacheFileChunkHandle::DataSize()
{
  MOZ_ASSERT(mBuf, "Unexpected call on dummy handle");
  mBuf->AssertOwnsLock();
  return mBuf->mDataSize;
}

uint32_t
CacheFileChunkHandle::Offset()
{
  MOZ_ASSERT(mBuf, "Unexpected call on dummy handle");
  mBuf->AssertOwnsLock();
  return mBuf->mChunk->Index() * kChunkSize;
}

CacheFileChunkReadHandle::CacheFileChunkReadHandle(CacheFileChunkBuffer *aBuf)
{
  mBuf = aBuf;
  mBuf->mReadHandlesCount++;
}

CacheFileChunkReadHandle::~CacheFileChunkReadHandle()
{
  mBuf->RemoveReadHandle();
}

const char *
CacheFileChunkReadHandle::Buf()
{
  return mBuf->mBuf;
}

CacheFileChunkWriteHandle::CacheFileChunkWriteHandle(CacheFileChunkBuffer *aBuf)
{
  mBuf = aBuf;
  if (mBuf) {
    MOZ_ASSERT(!mBuf->mWriteHandleExists);
    mBuf->mWriteHandleExists = true;
  }
}

CacheFileChunkWriteHandle::~CacheFileChunkWriteHandle()
{
  if (mBuf) {
    mBuf->RemoveWriteHandle();
  }
}

char *
CacheFileChunkWriteHandle::Buf()
{
  return mBuf ? mBuf->mBuf : nullptr;
}

void
CacheFileChunkWriteHandle::UpdateDataSize(uint32_t aOffset, uint32_t aLen)
{
  MOZ_ASSERT(mBuf, "Write performed on dummy handle?");
  MOZ_ASSERT(aOffset <= mBuf->mDataSize);
  MOZ_ASSERT(aOffset + aLen <= mBuf->mBufSize);

  if (aOffset + aLen > mBuf->mDataSize) {
    mBuf->mDataSize = aOffset + aLen;
  }

  mBuf->mChunk->UpdateDataSize(aOffset, aLen);
}


class NotifyUpdateListenerEvent : public Runnable {
public:
  NotifyUpdateListenerEvent(CacheFileChunkListener *aCallback,
                            CacheFileChunk *aChunk)
    : mCallback(aCallback)
    , mChunk(aChunk)
  {
    LOG(("NotifyUpdateListenerEvent::NotifyUpdateListenerEvent() [this=%p]",
         this));
    MOZ_COUNT_CTOR(NotifyUpdateListenerEvent);
  }

protected:
  ~NotifyUpdateListenerEvent()
  {
    LOG(("NotifyUpdateListenerEvent::~NotifyUpdateListenerEvent() [this=%p]",
         this));
    MOZ_COUNT_DTOR(NotifyUpdateListenerEvent);
  }

public:
  NS_IMETHOD Run() override
  {
    LOG(("NotifyUpdateListenerEvent::Run() [this=%p]", this));

    mCallback->OnChunkUpdated(mChunk);
    return NS_OK;
  }

protected:
  nsCOMPtr<CacheFileChunkListener> mCallback;
  RefPtr<CacheFileChunk>           mChunk;
};

bool
CacheFileChunk::DispatchRelease()
{
  if (NS_IsMainThread()) {
    return false;
  }

  NS_DispatchToMainThread(NewNonOwningRunnableMethod(this, &CacheFileChunk::Release));

  return true;
}

NS_IMPL_ADDREF(CacheFileChunk)
NS_IMETHODIMP_(MozExternalRefCountType)
CacheFileChunk::Release()
{
  nsrefcnt count = mRefCnt - 1;
  if (DispatchRelease()) {
    // Redispatched to the main thread.
    return count;
  }

  NS_PRECONDITION(0 != mRefCnt, "dup release");
  count = --mRefCnt;
  NS_LOG_RELEASE(this, count, "CacheFileChunk");

  if (0 == count) {
    mRefCnt = 1;
    delete (this);
    return 0;
  }

  // We can safely access this chunk after decreasing mRefCnt since we re-post
  // all calls to Release() happening off the main thread to the main thread.
  // I.e. no other Release() that would delete the object could be run before
  // we call CacheFile::DeactivateChunk().
  //
  // NOTE: we don't grab the CacheFile's lock, so the chunk might be addrefed
  // on another thread before CacheFile::DeactivateChunk() grabs the lock on
  // this thread. To make sure we won't deactivate chunk that was just returned
  // to a new consumer we check mRefCnt once again in
  // CacheFile::DeactivateChunk() after we grab the lock.
  if (mActiveChunk && count == 1) {
    mFile->DeactivateChunk(this);
  }

  return count;
}

NS_INTERFACE_MAP_BEGIN(CacheFileChunk)
  NS_INTERFACE_MAP_ENTRY(mozilla::net::CacheFileIOListener)
  NS_INTERFACE_MAP_ENTRY(nsISupports)
NS_INTERFACE_MAP_END_THREADSAFE

CacheFileChunk::CacheFileChunk(CacheFile *aFile, uint32_t aIndex,
                               bool aInitByWriter)
  : CacheMemoryConsumer(aFile->mOpenAsMemoryOnly ? MEMORY_ONLY : DONT_REPORT)
  , mIndex(aIndex)
  , mState(INITIAL)
  , mStatus(NS_OK)
  , mActiveChunk(false)
  , mIsDirty(false)
  , mDiscardedChunk(false)
  , mBuffersSize(0)
  , mLimitAllocation(!aFile->mOpenAsMemoryOnly && aInitByWriter)
  , mIsPriority(aFile->mPriority)
  , mExpectedHash(0)
  , mFile(aFile)
{
  LOG(("CacheFileChunk::CacheFileChunk() [this=%p, index=%u, initByWriter=%d]",
       this, aIndex, aInitByWriter));
  MOZ_COUNT_CTOR(CacheFileChunk);

  mBuf = new CacheFileChunkBuffer(this);
}

CacheFileChunk::~CacheFileChunk()
{
  LOG(("CacheFileChunk::~CacheFileChunk() [this=%p]", this));
  MOZ_COUNT_DTOR(CacheFileChunk);
}

void
CacheFileChunk::AssertOwnsLock() const
{
  mFile->AssertOwnsLock();
}

void
CacheFileChunk::InitNew()
{
  AssertOwnsLock();

  LOG(("CacheFileChunk::InitNew() [this=%p]", this));

  MOZ_ASSERT(mState == INITIAL);
  MOZ_ASSERT(NS_SUCCEEDED(mStatus));
  MOZ_ASSERT(!mBuf->Buf());
  MOZ_ASSERT(!mWritingStateHandle);
  MOZ_ASSERT(!mReadingStateBuf);
  MOZ_ASSERT(!mIsDirty);

  mBuf = new CacheFileChunkBuffer(this);
  mState = READY;
}

nsresult
CacheFileChunk::Read(CacheFileHandle *aHandle, uint32_t aLen,
                     CacheHash::Hash16_t aHash,
                     CacheFileChunkListener *aCallback)
{
  AssertOwnsLock();

  LOG(("CacheFileChunk::Read() [this=%p, handle=%p, len=%d, listener=%p]",
       this, aHandle, aLen, aCallback));

  MOZ_ASSERT(mState == INITIAL);
  MOZ_ASSERT(NS_SUCCEEDED(mStatus));
  MOZ_ASSERT(!mBuf->Buf());
  MOZ_ASSERT(!mWritingStateHandle);
  MOZ_ASSERT(!mReadingStateBuf);
  MOZ_ASSERT(aLen);

  nsresult rv;

  mState = READING;

  RefPtr<CacheFileChunkBuffer> tmpBuf = new CacheFileChunkBuffer(this);
  rv = tmpBuf->EnsureBufSize(aLen);
  if (NS_FAILED(rv)) {
    SetError(rv);
    return mStatus;
  }
  tmpBuf->SetDataSize(aLen);

  rv = CacheFileIOManager::Read(aHandle, mIndex * kChunkSize,
                                tmpBuf->Buf(), aLen,
                                this);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    rv = mIndex ? NS_ERROR_FILE_CORRUPTED : NS_ERROR_FILE_NOT_FOUND;
    SetError(rv);
  } else {
    mReadingStateBuf.swap(tmpBuf);
    mListener = aCallback;
    // mBuf contains no data but we set datasize to size of the data that will
    // be read from the disk. No handle is allowed to access the non-existent
    // data until reading finishes, but data can be appended or overwritten.
    // These pieces are tracked in mValidityMap and will be merged with the data
    // read from disk in OnDataRead().
    mBuf->SetDataSize(aLen);
    mExpectedHash = aHash;
  }

  return rv;
}

nsresult
CacheFileChunk::Write(CacheFileHandle *aHandle,
                      CacheFileChunkListener *aCallback)
{
  AssertOwnsLock();

  LOG(("CacheFileChunk::Write() [this=%p, handle=%p, listener=%p]",
       this, aHandle, aCallback));

  MOZ_ASSERT(mState == READY);
  MOZ_ASSERT(NS_SUCCEEDED(mStatus));
  MOZ_ASSERT(!mWritingStateHandle);
  MOZ_ASSERT(mBuf->DataSize()); // Don't write chunk when it is empty
  MOZ_ASSERT(mBuf->ReadHandlesCount() == 0);
  MOZ_ASSERT(!mBuf->WriteHandleExists());

  nsresult rv;

  mState = WRITING;
  mWritingStateHandle = new CacheFileChunkReadHandle(mBuf);

  rv = CacheFileIOManager::Write(aHandle, mIndex * kChunkSize,
                                 mWritingStateHandle->Buf(),
                                 mWritingStateHandle->DataSize(),
                                 false, false, this);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    mWritingStateHandle = nullptr;
    SetError(rv);
  } else {
    mListener = aCallback;
    mIsDirty = false;
  }

  return rv;
}

void
CacheFileChunk::WaitForUpdate(CacheFileChunkListener *aCallback)
{
  AssertOwnsLock();

  LOG(("CacheFileChunk::WaitForUpdate() [this=%p, listener=%p]",
       this, aCallback));

  MOZ_ASSERT(mFile->mOutput);
  MOZ_ASSERT(IsReady());

#ifdef DEBUG
  for (uint32_t i = 0 ; i < mUpdateListeners.Length() ; i++) {
    MOZ_ASSERT(mUpdateListeners[i]->mCallback != aCallback);
  }
#endif

  ChunkListenerItem *item = new ChunkListenerItem();
  item->mTarget = CacheFileIOManager::IOTarget();
  if (!item->mTarget) {
    LOG(("CacheFileChunk::WaitForUpdate() - Cannot get Cache I/O thread! Using "
         "main thread for callback."));
    item->mTarget = do_GetMainThread();
  }
  item->mCallback = aCallback;
  MOZ_ASSERT(item->mTarget);
  item->mCallback = aCallback;

  mUpdateListeners.AppendElement(item);
}

nsresult
CacheFileChunk::CancelWait(CacheFileChunkListener *aCallback)
{
  AssertOwnsLock();

  LOG(("CacheFileChunk::CancelWait() [this=%p, listener=%p]", this, aCallback));

  MOZ_ASSERT(IsReady());

  uint32_t i;
  for (i = 0 ; i < mUpdateListeners.Length() ; i++) {
    ChunkListenerItem *item = mUpdateListeners[i];

    if (item->mCallback == aCallback) {
      mUpdateListeners.RemoveElementAt(i);
      delete item;
      break;
    }
  }

#ifdef DEBUG
  for ( ; i < mUpdateListeners.Length() ; i++) {
    MOZ_ASSERT(mUpdateListeners[i]->mCallback != aCallback);
  }
#endif

  return NS_OK;
}

nsresult
CacheFileChunk::NotifyUpdateListeners()
{
  AssertOwnsLock();

  LOG(("CacheFileChunk::NotifyUpdateListeners() [this=%p]", this));

  MOZ_ASSERT(IsReady());

  nsresult rv, rv2;

  rv = NS_OK;
  for (uint32_t i = 0 ; i < mUpdateListeners.Length() ; i++) {
    ChunkListenerItem *item = mUpdateListeners[i];

    LOG(("CacheFileChunk::NotifyUpdateListeners() - Notifying listener %p "
         "[this=%p]", item->mCallback.get(), this));

    RefPtr<NotifyUpdateListenerEvent> ev;
    ev = new NotifyUpdateListenerEvent(item->mCallback, this);
    rv2 = item->mTarget->Dispatch(ev, NS_DISPATCH_NORMAL);
    if (NS_FAILED(rv2) && NS_SUCCEEDED(rv))
      rv = rv2;
    delete item;
  }

  mUpdateListeners.Clear();

  return rv;
}

uint32_t
CacheFileChunk::Index() const
{
  return mIndex;
}

CacheHash::Hash16_t
CacheFileChunk::Hash() const
{
  AssertOwnsLock();

  MOZ_ASSERT(!mListener);
  MOZ_ASSERT(IsReady());

  return CacheHash::Hash16(mBuf->Buf(), mBuf->DataSize());
}

uint32_t
CacheFileChunk::DataSize() const
{
  return mBuf->DataSize();
}

void
CacheFileChunk::UpdateDataSize(uint32_t aOffset, uint32_t aLen)
{
  AssertOwnsLock();

  // UpdateDataSize() is called only when we've written some data to the chunk
  // and we never write data anymore once some error occurs.
  MOZ_ASSERT(NS_SUCCEEDED(mStatus));

  LOG(("CacheFileChunk::UpdateDataSize() [this=%p, offset=%d, len=%d]",
       this, aOffset, aLen));

  mIsDirty = true;

  int64_t fileSize = static_cast<int64_t>(kChunkSize) * mIndex + aOffset + aLen;
  bool notify = false;

  if (fileSize > mFile->mDataSize) {
    mFile->mDataSize = fileSize;
    notify = true;
  }

  if (mState == READY || mState == WRITING) {
    MOZ_ASSERT(mValidityMap.Length() == 0);

    if (notify) {
      NotifyUpdateListeners();
    }

    return;
  }

  // We're still waiting for data from the disk. This chunk cannot be used by
  // input stream, so there must be no update listener. We also need to keep
  // track of where the data is written so that we can correctly merge the new
  // data with the old one.

  MOZ_ASSERT(mUpdateListeners.Length() == 0);
  MOZ_ASSERT(mState == READING);

  mValidityMap.AddPair(aOffset, aLen);
  mValidityMap.Log();
}

nsresult
CacheFileChunk::Truncate(uint32_t aOffset)
{
  mBuf->SetDataSize(aOffset);
  return NS_OK;
}

nsresult
CacheFileChunk::OnFileOpened(CacheFileHandle *aHandle, nsresult aResult)
{
  MOZ_CRASH("CacheFileChunk::OnFileOpened should not be called!");
  return NS_ERROR_UNEXPECTED;
}

nsresult
CacheFileChunk::OnDataWritten(CacheFileHandle *aHandle, const char *aBuf,
                              nsresult aResult)
{
  LOG(("CacheFileChunk::OnDataWritten() [this=%p, handle=%p, result=0x%08x]",
       this, aHandle, aResult));

  nsCOMPtr<CacheFileChunkListener> listener;

  {
    CacheFileAutoLock lock(mFile);

    MOZ_ASSERT(mState == WRITING);
    MOZ_ASSERT(mListener);

    mWritingStateHandle = nullptr;

    if (NS_WARN_IF(NS_FAILED(aResult))) {
      SetError(aResult);
    }

    mState = READY;
    mListener.swap(listener);
  }

  listener->OnChunkWritten(aResult, this);

  return NS_OK;
}

nsresult
CacheFileChunk::OnDataRead(CacheFileHandle *aHandle, char *aBuf,
                           nsresult aResult)
{
  LOG(("CacheFileChunk::OnDataRead() [this=%p, handle=%p, result=0x%08x]",
       this, aHandle, aResult));

  nsCOMPtr<CacheFileChunkListener> listener;

  {
    CacheFileAutoLock lock(mFile);

    MOZ_ASSERT(mState == READING);
    MOZ_ASSERT(mListener);
    MOZ_ASSERT(mReadingStateBuf);
    MOZ_RELEASE_ASSERT(mBuf->ReadHandlesCount() == 0);
    MOZ_RELEASE_ASSERT(!mBuf->WriteHandleExists());

    RefPtr<CacheFileChunkBuffer> tmpBuf;
    tmpBuf.swap(mReadingStateBuf);

    if (NS_SUCCEEDED(aResult)) {
      CacheHash::Hash16_t hash = CacheHash::Hash16(tmpBuf->Buf(),
                                                   tmpBuf->DataSize());
      if (hash != mExpectedHash) {
        LOG(("CacheFileChunk::OnDataRead() - Hash mismatch! Hash of the data is"
             " %hx, hash in metadata is %hx. [this=%p, idx=%d]",
             hash, mExpectedHash, this, mIndex));
        aResult = NS_ERROR_FILE_CORRUPTED;
      } else {
        if (!mBuf->Buf()) {
          // Just swap the buffers if mBuf is still empty
          mBuf.swap(tmpBuf);
        } else {
          LOG(("CacheFileChunk::OnDataRead() - Merging buffers. [this=%p]",
               this));

          mValidityMap.Log();
          aResult = mBuf->FillInvalidRanges(tmpBuf, &mValidityMap);
          mValidityMap.Clear();
        }
      }
    }

    if (NS_FAILED(aResult)) {
      aResult = mIndex ? NS_ERROR_FILE_CORRUPTED : NS_ERROR_FILE_NOT_FOUND;
      SetError(aResult);
      mBuf->SetDataSize(0);
    }

    mState = READY;
    mListener.swap(listener);
  }

  listener->OnChunkRead(aResult, this);

  return NS_OK;
}

nsresult
CacheFileChunk::OnFileDoomed(CacheFileHandle *aHandle, nsresult aResult)
{
  MOZ_CRASH("CacheFileChunk::OnFileDoomed should not be called!");
  return NS_ERROR_UNEXPECTED;
}

nsresult
CacheFileChunk::OnEOFSet(CacheFileHandle *aHandle, nsresult aResult)
{
  MOZ_CRASH("CacheFileChunk::OnEOFSet should not be called!");
  return NS_ERROR_UNEXPECTED;
}

nsresult
CacheFileChunk::OnFileRenamed(CacheFileHandle *aHandle, nsresult aResult)
{
  MOZ_CRASH("CacheFileChunk::OnFileRenamed should not be called!");
  return NS_ERROR_UNEXPECTED;
}

bool
CacheFileChunk::IsKilled()
{
  return mFile->IsKilled();
}

bool
CacheFileChunk::IsReady() const
{
  AssertOwnsLock();

  return (NS_SUCCEEDED(mStatus) && (mState == READY || mState == WRITING));
}

bool
CacheFileChunk::IsDirty() const
{
  AssertOwnsLock();

  return mIsDirty;
}

nsresult
CacheFileChunk::GetStatus()
{
  AssertOwnsLock();

  return mStatus;
}

void
CacheFileChunk::SetError(nsresult aStatus)
{
  LOG(("CacheFileChunk::SetError() [this=%p, status=0x%08x]", this, aStatus));

  MOZ_ASSERT(NS_FAILED(aStatus));

  if (NS_FAILED(mStatus)) {
    // Remember only the first error code.
    return;
  }

  mStatus = aStatus;
}

CacheFileChunkReadHandle
CacheFileChunk::GetReadHandle()
{
  LOG(("CacheFileChunk::GetReadHandle() [this=%p]", this));

  AssertOwnsLock();

  MOZ_RELEASE_ASSERT(mState == READY || mState == WRITING);
  // We don't release the lock when writing the data and CacheFileOutputStream
  // doesn't get the read handle, so there cannot be a write handle when read
  // handle is obtained.
  MOZ_RELEASE_ASSERT(!mBuf->WriteHandleExists());

  return CacheFileChunkReadHandle(mBuf);
}

CacheFileChunkWriteHandle
CacheFileChunk::GetWriteHandle(uint32_t aEnsuredBufSize)
{
  LOG(("CacheFileChunk::GetWriteHandle() [this=%p, ensuredBufSize=%u]",
       this, aEnsuredBufSize));

  AssertOwnsLock();

  if (NS_FAILED(mStatus)) {
    return CacheFileChunkWriteHandle(nullptr); // dummy handle
  }

  nsresult rv;

  // We don't support multiple write handles
  MOZ_RELEASE_ASSERT(!mBuf->WriteHandleExists());

  if (mBuf->ReadHandlesCount()) {
    LOG(("CacheFileChunk::GetWriteHandle() - cloning buffer because of existing"
         " read handle"));

    MOZ_RELEASE_ASSERT(mState != READING);
    RefPtr<CacheFileChunkBuffer> newBuf = new CacheFileChunkBuffer(this);
    rv = newBuf->EnsureBufSize(std::max(aEnsuredBufSize, mBuf->DataSize()));
    if (NS_SUCCEEDED(rv)) {
      newBuf->CopyFrom(mBuf);
      mOldBufs.AppendElement(mBuf);
      mBuf = newBuf;
    }
  } else {
    rv = mBuf->EnsureBufSize(aEnsuredBufSize);
  }

  if (NS_FAILED(rv)) {
    SetError(NS_ERROR_OUT_OF_MEMORY);
    return CacheFileChunkWriteHandle(nullptr); // dummy handle
  }

  return CacheFileChunkWriteHandle(mBuf);
}

// Memory reporting

size_t
CacheFileChunk::SizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const
{
  size_t n = mBuf->SizeOfIncludingThis(mallocSizeOf);

  if (mReadingStateBuf) {
    n += mReadingStateBuf->SizeOfIncludingThis(mallocSizeOf);
  }

  for (uint32_t i = 0; i < mOldBufs.Length(); ++i) {
    n += mOldBufs[i]->SizeOfIncludingThis(mallocSizeOf);
  }

  n += mValidityMap.SizeOfExcludingThis(mallocSizeOf);

  return n;
}

size_t
CacheFileChunk::SizeOfIncludingThis(mozilla::MallocSizeOf mallocSizeOf) const
{
  return mallocSizeOf(this) + SizeOfExcludingThis(mallocSizeOf);
}

bool
CacheFileChunk::CanAllocate(uint32_t aSize) const
{
  if (!mLimitAllocation) {
    return true;
  }

  LOG(("CacheFileChunk::CanAllocate() [this=%p, size=%u]", this, aSize));

  uint32_t limit = CacheObserver::MaxDiskChunksMemoryUsage(mIsPriority);
  if (limit == 0) {
    return true;
  }

  uint32_t usage = ChunksMemoryUsage();
  if (usage + aSize > limit) {
    LOG(("CacheFileChunk::CanAllocate() - Returning false. [this=%p]", this));
    return false;
  }

  return true;
}

void
CacheFileChunk::BuffersAllocationChanged(uint32_t aFreed, uint32_t aAllocated)
{
  uint32_t oldBuffersSize = mBuffersSize;
  mBuffersSize += aAllocated;
  mBuffersSize -= aFreed;

  DoMemoryReport(sizeof(CacheFileChunk) + mBuffersSize);

  if (!mLimitAllocation) {
    return;
  }

  ChunksMemoryUsage() -= oldBuffersSize;
  ChunksMemoryUsage() += mBuffersSize;
  LOG(("CacheFileChunk::BuffersAllocationChanged() - %s chunks usage %u "
       "[this=%p]", mIsPriority ? "Priority" : "Normal",
       static_cast<uint32_t>(ChunksMemoryUsage()), this));
}

mozilla::Atomic<uint32_t, ReleaseAcquire>& CacheFileChunk::ChunksMemoryUsage() const
{
  static mozilla::Atomic<uint32_t, ReleaseAcquire> chunksMemoryUsage(0);
  static mozilla::Atomic<uint32_t, ReleaseAcquire> prioChunksMemoryUsage(0);
  return mIsPriority ? prioChunksMemoryUsage : chunksMemoryUsage;
}

} // namespace net
} // namespace mozilla