• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/disk_cache/entry_impl.h"
6 
7 #include "base/message_loop.h"
8 #include "base/metrics/histogram.h"
9 #include "base/string_util.h"
10 #include "net/base/io_buffer.h"
11 #include "net/base/net_errors.h"
12 #include "net/disk_cache/backend_impl.h"
13 #include "net/disk_cache/bitmap.h"
14 #include "net/disk_cache/cache_util.h"
15 #include "net/disk_cache/hash.h"
16 #include "net/disk_cache/histogram_macros.h"
17 #include "net/disk_cache/net_log_parameters.h"
18 #include "net/disk_cache/sparse_control.h"
19 
20 using base::Time;
21 using base::TimeDelta;
22 using base::TimeTicks;
23 
24 namespace {
25 
26 // Index for the file used to store the key, if any (files_[kKeyFileIndex]).
27 const int kKeyFileIndex = 3;
28 
29 // This class implements FileIOCallback to buffer the callback from a file IO
30 // operation from the actual net class.
31 class SyncCallback: public disk_cache::FileIOCallback {
32  public:
33   // |end_event_type| is the event type to log on completion.  Logs nothing on
34   // discard, or when the NetLog is not set to log all events.
SyncCallback(disk_cache::EntryImpl * entry,net::IOBuffer * buffer,net::CompletionCallback * callback,net::NetLog::EventType end_event_type)35   SyncCallback(disk_cache::EntryImpl* entry, net::IOBuffer* buffer,
36                net::CompletionCallback* callback,
37                net::NetLog::EventType end_event_type)
38       : entry_(entry), callback_(callback), buf_(buffer),
39         start_(TimeTicks::Now()), end_event_type_(end_event_type) {
40     entry->AddRef();
41     entry->IncrementIoCount();
42   }
~SyncCallback()43   ~SyncCallback() {}
44 
45   virtual void OnFileIOComplete(int bytes_copied);
46   void Discard();
47 
48  private:
49   disk_cache::EntryImpl* entry_;
50   net::CompletionCallback* callback_;
51   scoped_refptr<net::IOBuffer> buf_;
52   TimeTicks start_;
53   const net::NetLog::EventType end_event_type_;
54 
55   DISALLOW_COPY_AND_ASSIGN(SyncCallback);
56 };
57 
OnFileIOComplete(int bytes_copied)58 void SyncCallback::OnFileIOComplete(int bytes_copied) {
59   entry_->DecrementIoCount();
60   if (callback_) {
61     if (entry_->net_log().IsLoggingAllEvents()) {
62       entry_->net_log().EndEvent(
63           end_event_type_,
64           make_scoped_refptr(
65               new disk_cache::ReadWriteCompleteParameters(bytes_copied)));
66     }
67     entry_->ReportIOTime(disk_cache::EntryImpl::kAsyncIO, start_);
68     callback_->Run(bytes_copied);
69   }
70   entry_->Release();
71   delete this;
72 }
73 
Discard()74 void SyncCallback::Discard() {
75   callback_ = NULL;
76   buf_ = NULL;
77   OnFileIOComplete(0);
78 }
79 
80 const int kMaxBufferSize = 1024 * 1024;  // 1 MB.
81 
82 }  // namespace
83 
84 namespace disk_cache {
85 
86 // This class handles individual memory buffers that store data before it is
87 // sent to disk. The buffer can start at any offset, but if we try to write to
88 // anywhere in the first 16KB of the file (kMaxBlockSize), we set the offset to
89 // zero. The buffer grows up to a size determined by the backend, to keep the
90 // total memory used under control.
91 class EntryImpl::UserBuffer {
92  public:
UserBuffer(BackendImpl * backend)93   explicit UserBuffer(BackendImpl* backend)
94       : backend_(backend->GetWeakPtr()), offset_(0), grow_allowed_(true) {
95     buffer_.reserve(kMaxBlockSize);
96   }
~UserBuffer()97   ~UserBuffer() {
98     if (backend_)
99       backend_->BufferDeleted(capacity() - kMaxBlockSize);
100   }
101 
102   // Returns true if we can handle writing |len| bytes to |offset|.
103   bool PreWrite(int offset, int len);
104 
105   // Truncates the buffer to |offset| bytes.
106   void Truncate(int offset);
107 
108   // Writes |len| bytes from |buf| at the given |offset|.
109   void Write(int offset, net::IOBuffer* buf, int len);
110 
111   // Returns true if we can read |len| bytes from |offset|, given that the
112   // actual file has |eof| bytes stored. Note that the number of bytes to read
113   // may be modified by this method even though it returns false: that means we
114   // should do a smaller read from disk.
115   bool PreRead(int eof, int offset, int* len);
116 
117   // Read |len| bytes from |buf| at the given |offset|.
118   int Read(int offset, net::IOBuffer* buf, int len);
119 
120   // Prepare this buffer for reuse.
121   void Reset();
122 
Data()123   char* Data() { return buffer_.size() ? &buffer_[0] : NULL; }
Size()124   int Size() { return static_cast<int>(buffer_.size()); }
Start()125   int Start() { return offset_; }
End()126   int End() { return offset_ + Size(); }
127 
128  private:
capacity()129   int capacity() { return static_cast<int>(buffer_.capacity()); }
130   bool GrowBuffer(int required, int limit);
131 
132   base::WeakPtr<BackendImpl> backend_;
133   int offset_;
134   std::vector<char> buffer_;
135   bool grow_allowed_;
136   DISALLOW_COPY_AND_ASSIGN(UserBuffer);
137 };
138 
PreWrite(int offset,int len)139 bool EntryImpl::UserBuffer::PreWrite(int offset, int len) {
140   DCHECK_GE(offset, 0);
141   DCHECK_GE(len, 0);
142   DCHECK_GE(offset + len, 0);
143 
144   // We don't want to write before our current start.
145   if (offset < offset_)
146     return false;
147 
148   // Lets get the common case out of the way.
149   if (offset + len <= capacity())
150     return true;
151 
152   // If we are writing to the first 16K (kMaxBlockSize), we want to keep the
153   // buffer offset_ at 0.
154   if (!Size() && offset > kMaxBlockSize)
155     return GrowBuffer(len, kMaxBufferSize);
156 
157   int required = offset - offset_ + len;
158   return GrowBuffer(required, kMaxBufferSize * 6 / 5);
159 }
160 
Truncate(int offset)161 void EntryImpl::UserBuffer::Truncate(int offset) {
162   DCHECK_GE(offset, 0);
163   DCHECK_GE(offset, offset_);
164   DVLOG(3) << "Buffer truncate at " << offset << " current " << offset_;
165 
166   offset -= offset_;
167   if (Size() >= offset)
168     buffer_.resize(offset);
169 }
170 
Write(int offset,net::IOBuffer * buf,int len)171 void EntryImpl::UserBuffer::Write(int offset, net::IOBuffer* buf, int len) {
172   DCHECK_GE(offset, 0);
173   DCHECK_GE(len, 0);
174   DCHECK_GE(offset + len, 0);
175   DCHECK_GE(offset, offset_);
176   DVLOG(3) << "Buffer write at " << offset << " current " << offset_;
177 
178   if (!Size() && offset > kMaxBlockSize)
179     offset_ = offset;
180 
181   offset -= offset_;
182 
183   if (offset > Size())
184     buffer_.resize(offset);
185 
186   if (!len)
187     return;
188 
189   char* buffer = buf->data();
190   int valid_len = Size() - offset;
191   int copy_len = std::min(valid_len, len);
192   if (copy_len) {
193     memcpy(&buffer_[offset], buffer, copy_len);
194     len -= copy_len;
195     buffer += copy_len;
196   }
197   if (!len)
198     return;
199 
200   buffer_.insert(buffer_.end(), buffer, buffer + len);
201 }
202 
PreRead(int eof,int offset,int * len)203 bool EntryImpl::UserBuffer::PreRead(int eof, int offset, int* len) {
204   DCHECK_GE(offset, 0);
205   DCHECK_GT(*len, 0);
206 
207   if (offset < offset_) {
208     // We are reading before this buffer.
209     if (offset >= eof)
210       return true;
211 
212     // If the read overlaps with the buffer, change its length so that there is
213     // no overlap.
214     *len = std::min(*len, offset_ - offset);
215     *len = std::min(*len, eof - offset);
216 
217     // We should read from disk.
218     return false;
219   }
220 
221   if (!Size())
222     return false;
223 
224   // See if we can fulfill the first part of the operation.
225   return (offset - offset_ < Size());
226 }
227 
Read(int offset,net::IOBuffer * buf,int len)228 int EntryImpl::UserBuffer::Read(int offset, net::IOBuffer* buf, int len) {
229   DCHECK_GE(offset, 0);
230   DCHECK_GT(len, 0);
231   DCHECK(Size() || offset < offset_);
232 
233   int clean_bytes = 0;
234   if (offset < offset_) {
235     // We don't have a file so lets fill the first part with 0.
236     clean_bytes = std::min(offset_ - offset, len);
237     memset(buf->data(), 0, clean_bytes);
238     if (len == clean_bytes)
239       return len;
240     offset = offset_;
241     len -= clean_bytes;
242   }
243 
244   int start = offset - offset_;
245   int available = Size() - start;
246   DCHECK_GE(start, 0);
247   DCHECK_GE(available, 0);
248   len = std::min(len, available);
249   memcpy(buf->data() + clean_bytes, &buffer_[start], len);
250   return len + clean_bytes;
251 }
252 
Reset()253 void EntryImpl::UserBuffer::Reset() {
254   if (!grow_allowed_) {
255     if (backend_)
256       backend_->BufferDeleted(capacity() - kMaxBlockSize);
257     grow_allowed_ = true;
258     std::vector<char> tmp;
259     buffer_.swap(tmp);
260     buffer_.reserve(kMaxBlockSize);
261   }
262   offset_ = 0;
263   buffer_.clear();
264 }
265 
GrowBuffer(int required,int limit)266 bool EntryImpl::UserBuffer::GrowBuffer(int required, int limit) {
267   DCHECK_GE(required, 0);
268   int current_size = capacity();
269   if (required <= current_size)
270     return true;
271 
272   if (required > limit)
273     return false;
274 
275   if (!backend_)
276     return false;
277 
278   int to_add = std::max(required - current_size, kMaxBlockSize * 4);
279   to_add = std::max(current_size, to_add);
280   required = std::min(current_size + to_add, limit);
281 
282   grow_allowed_ = backend_->IsAllocAllowed(current_size, required);
283   if (!grow_allowed_)
284     return false;
285 
286   DVLOG(3) << "Buffer grow to " << required;
287 
288   buffer_.reserve(required);
289   return true;
290 }
291 
292 // ------------------------------------------------------------------------
293 
EntryImpl(BackendImpl * backend,Addr address,bool read_only)294 EntryImpl::EntryImpl(BackendImpl* backend, Addr address, bool read_only)
295     : entry_(NULL, Addr(0)), node_(NULL, Addr(0)), backend_(backend),
296       doomed_(false), read_only_(read_only), dirty_(false) {
297   entry_.LazyInit(backend->File(address), address);
298   for (int i = 0; i < kNumStreams; i++) {
299     unreported_size_[i] = 0;
300   }
301 }
302 
DoomImpl()303 void EntryImpl::DoomImpl() {
304   if (doomed_)
305     return;
306 
307   SetPointerForInvalidEntry(backend_->GetCurrentEntryId());
308   backend_->InternalDoomEntry(this);
309 }
310 
ReadDataImpl(int index,int offset,net::IOBuffer * buf,int buf_len,CompletionCallback * callback)311 int EntryImpl::ReadDataImpl(int index, int offset, net::IOBuffer* buf,
312                             int buf_len, CompletionCallback* callback) {
313   if (net_log_.IsLoggingAllEvents()) {
314     net_log_.BeginEvent(
315         net::NetLog::TYPE_ENTRY_READ_DATA,
316         make_scoped_refptr(
317             new ReadWriteDataParameters(index, offset, buf_len, false)));
318   }
319 
320   int result = InternalReadData(index, offset, buf, buf_len, callback);
321 
322   if (result != net::ERR_IO_PENDING && net_log_.IsLoggingAllEvents()) {
323     net_log_.EndEvent(
324         net::NetLog::TYPE_ENTRY_READ_DATA,
325         make_scoped_refptr(new ReadWriteCompleteParameters(result)));
326   }
327   return result;
328 }
329 
WriteDataImpl(int index,int offset,net::IOBuffer * buf,int buf_len,CompletionCallback * callback,bool truncate)330 int EntryImpl::WriteDataImpl(int index, int offset, net::IOBuffer* buf,
331                              int buf_len, CompletionCallback* callback,
332                              bool truncate) {
333   if (net_log_.IsLoggingAllEvents()) {
334     net_log_.BeginEvent(
335         net::NetLog::TYPE_ENTRY_WRITE_DATA,
336         make_scoped_refptr(
337             new ReadWriteDataParameters(index, offset, buf_len, truncate)));
338   }
339 
340   int result = InternalWriteData(index, offset, buf, buf_len, callback,
341                                  truncate);
342 
343   if (result != net::ERR_IO_PENDING && net_log_.IsLoggingAllEvents()) {
344     net_log_.EndEvent(
345         net::NetLog::TYPE_ENTRY_WRITE_DATA,
346         make_scoped_refptr(new ReadWriteCompleteParameters(result)));
347   }
348   return result;
349 }
350 
ReadSparseDataImpl(int64 offset,net::IOBuffer * buf,int buf_len,CompletionCallback * callback)351 int EntryImpl::ReadSparseDataImpl(int64 offset, net::IOBuffer* buf, int buf_len,
352                                   CompletionCallback* callback) {
353   DCHECK(node_.Data()->dirty || read_only_);
354   int result = InitSparseData();
355   if (net::OK != result)
356     return result;
357 
358   TimeTicks start = TimeTicks::Now();
359   result = sparse_->StartIO(SparseControl::kReadOperation, offset, buf, buf_len,
360                             callback);
361   ReportIOTime(kSparseRead, start);
362   return result;
363 }
364 
WriteSparseDataImpl(int64 offset,net::IOBuffer * buf,int buf_len,CompletionCallback * callback)365 int EntryImpl::WriteSparseDataImpl(int64 offset, net::IOBuffer* buf,
366                                    int buf_len, CompletionCallback* callback) {
367   DCHECK(node_.Data()->dirty || read_only_);
368   int result = InitSparseData();
369   if (net::OK != result)
370     return result;
371 
372   TimeTicks start = TimeTicks::Now();
373   result = sparse_->StartIO(SparseControl::kWriteOperation, offset, buf,
374                             buf_len, callback);
375   ReportIOTime(kSparseWrite, start);
376   return result;
377 }
378 
GetAvailableRangeImpl(int64 offset,int len,int64 * start)379 int EntryImpl::GetAvailableRangeImpl(int64 offset, int len, int64* start) {
380   int result = InitSparseData();
381   if (net::OK != result)
382     return result;
383 
384   return sparse_->GetAvailableRange(offset, len, start);
385 }
386 
CancelSparseIOImpl()387 void EntryImpl::CancelSparseIOImpl() {
388   if (!sparse_.get())
389     return;
390 
391   sparse_->CancelIO();
392 }
393 
ReadyForSparseIOImpl(CompletionCallback * callback)394 int EntryImpl::ReadyForSparseIOImpl(CompletionCallback* callback) {
395   DCHECK(sparse_.get());
396   return sparse_->ReadyToUse(callback);
397 }
398 
GetHash()399 uint32 EntryImpl::GetHash() {
400   return entry_.Data()->hash;
401 }
402 
CreateEntry(Addr node_address,const std::string & key,uint32 hash)403 bool EntryImpl::CreateEntry(Addr node_address, const std::string& key,
404                             uint32 hash) {
405   Trace("Create entry In");
406   EntryStore* entry_store = entry_.Data();
407   RankingsNode* node = node_.Data();
408   memset(entry_store, 0, sizeof(EntryStore) * entry_.address().num_blocks());
409   memset(node, 0, sizeof(RankingsNode));
410   if (!node_.LazyInit(backend_->File(node_address), node_address))
411     return false;
412 
413   entry_store->rankings_node = node_address.value();
414   node->contents = entry_.address().value();
415 
416   entry_store->hash = hash;
417   entry_store->creation_time = Time::Now().ToInternalValue();
418   entry_store->key_len = static_cast<int32>(key.size());
419   if (entry_store->key_len > kMaxInternalKeyLength) {
420     Addr address(0);
421     if (!CreateBlock(entry_store->key_len + 1, &address))
422       return false;
423 
424     entry_store->long_key = address.value();
425     File* key_file = GetBackingFile(address, kKeyFileIndex);
426     key_ = key;
427 
428     size_t offset = 0;
429     if (address.is_block_file())
430       offset = address.start_block() * address.BlockSize() + kBlockHeaderSize;
431 
432     if (!key_file || !key_file->Write(key.data(), key.size(), offset)) {
433       DeleteData(address, kKeyFileIndex);
434       return false;
435     }
436 
437     if (address.is_separate_file())
438       key_file->SetLength(key.size() + 1);
439   } else {
440     memcpy(entry_store->key, key.data(), key.size());
441     entry_store->key[key.size()] = '\0';
442   }
443   backend_->ModifyStorageSize(0, static_cast<int32>(key.size()));
444   CACHE_UMA(COUNTS, "KeySize", 0, static_cast<int32>(key.size()));
445   node->dirty = backend_->GetCurrentEntryId();
446   Log("Create Entry ");
447   return true;
448 }
449 
IsSameEntry(const std::string & key,uint32 hash)450 bool EntryImpl::IsSameEntry(const std::string& key, uint32 hash) {
451   if (entry_.Data()->hash != hash ||
452       static_cast<size_t>(entry_.Data()->key_len) != key.size())
453     return false;
454 
455   std::string my_key = GetKey();
456   return key.compare(my_key) ? false : true;
457 }
458 
InternalDoom()459 void EntryImpl::InternalDoom() {
460   net_log_.AddEvent(net::NetLog::TYPE_ENTRY_DOOM, NULL);
461   DCHECK(node_.HasData());
462   if (!node_.Data()->dirty) {
463     node_.Data()->dirty = backend_->GetCurrentEntryId();
464     node_.Store();
465   }
466   doomed_ = true;
467 }
468 
DeleteEntryData(bool everything)469 void EntryImpl::DeleteEntryData(bool everything) {
470   DCHECK(doomed_ || !everything);
471 
472   if (GetEntryFlags() & PARENT_ENTRY) {
473     // We have some child entries that must go away.
474     SparseControl::DeleteChildren(this);
475   }
476 
477   if (GetDataSize(0))
478     CACHE_UMA(COUNTS, "DeleteHeader", 0, GetDataSize(0));
479   if (GetDataSize(1))
480     CACHE_UMA(COUNTS, "DeleteData", 0, GetDataSize(1));
481   for (int index = 0; index < kNumStreams; index++) {
482     Addr address(entry_.Data()->data_addr[index]);
483     if (address.is_initialized()) {
484       backend_->ModifyStorageSize(entry_.Data()->data_size[index] -
485                                       unreported_size_[index], 0);
486       entry_.Data()->data_addr[index] = 0;
487       entry_.Data()->data_size[index] = 0;
488       entry_.Store();
489       DeleteData(address, index);
490     }
491   }
492 
493   if (!everything)
494     return;
495 
496   // Remove all traces of this entry.
497   backend_->RemoveEntry(this);
498 
499   Addr address(entry_.Data()->long_key);
500   DeleteData(address, kKeyFileIndex);
501   backend_->ModifyStorageSize(entry_.Data()->key_len, 0);
502 
503   memset(node_.buffer(), 0, node_.size());
504   memset(entry_.buffer(), 0, entry_.size());
505   node_.Store();
506   entry_.Store();
507 
508   backend_->DeleteBlock(node_.address(), false);
509   backend_->DeleteBlock(entry_.address(), false);
510 }
511 
GetNextAddress()512 CacheAddr EntryImpl::GetNextAddress() {
513   return entry_.Data()->next;
514 }
515 
SetNextAddress(Addr address)516 void EntryImpl::SetNextAddress(Addr address) {
517   DCHECK_NE(address.value(), entry_.address().value());
518   entry_.Data()->next = address.value();
519   bool success = entry_.Store();
520   DCHECK(success);
521 }
522 
LoadNodeAddress()523 bool EntryImpl::LoadNodeAddress() {
524   Addr address(entry_.Data()->rankings_node);
525   if (!node_.LazyInit(backend_->File(address), address))
526     return false;
527   return node_.Load();
528 }
529 
Update()530 bool EntryImpl::Update() {
531   DCHECK(node_.HasData());
532 
533   if (read_only_)
534     return true;
535 
536   RankingsNode* rankings = node_.Data();
537   if (!rankings->dirty) {
538     rankings->dirty = backend_->GetCurrentEntryId();
539     if (!node_.Store())
540       return false;
541   }
542   return true;
543 }
544 
SetDirtyFlag(int32 current_id)545 void EntryImpl::SetDirtyFlag(int32 current_id) {
546   DCHECK(node_.HasData());
547   // We are checking if the entry is valid or not. If there is a pointer here,
548   // we should not be checking the entry.
549   if (node_.Data()->dummy)
550     dirty_ = true;
551 
552   if (node_.Data()->dirty && current_id != node_.Data()->dirty)
553     dirty_ = true;
554 }
555 
SetPointerForInvalidEntry(int32 new_id)556 void EntryImpl::SetPointerForInvalidEntry(int32 new_id) {
557   node_.Data()->dirty = new_id;
558   node_.Data()->dummy = 0;
559   node_.Store();
560 }
561 
SanityCheck()562 bool EntryImpl::SanityCheck() {
563   EntryStore* stored = entry_.Data();
564   if (!stored->rankings_node || stored->key_len <= 0)
565     return false;
566 
567   if (stored->reuse_count < 0 || stored->refetch_count < 0)
568     return false;
569 
570   Addr rankings_addr(stored->rankings_node);
571   if (!rankings_addr.is_initialized() || rankings_addr.is_separate_file() ||
572       rankings_addr.file_type() != RANKINGS)
573     return false;
574 
575   Addr next_addr(stored->next);
576   if (next_addr.is_initialized() &&
577       (next_addr.is_separate_file() || next_addr.file_type() != BLOCK_256))
578     return false;
579 
580   if (!rankings_addr.SanityCheck() || !next_addr.SanityCheck())
581     return false;
582 
583   if (stored->state > ENTRY_DOOMED || stored->state < ENTRY_NORMAL)
584     return false;
585 
586   Addr key_addr(stored->long_key);
587   if (stored->key_len <= kMaxInternalKeyLength && key_addr.is_initialized())
588     return false;
589 
590   if (!key_addr.SanityCheck())
591     return false;
592 
593   if (stored->hash != Hash(GetKey()))
594     return false;
595 
596   for (int i = 0; i < kNumStreams; i++) {
597     Addr data_addr(stored->data_addr[i]);
598     int data_size = stored->data_size[i];
599     if (data_size < 0)
600       return false;
601     if (!data_size && data_addr.is_initialized())
602       return false;
603     if (!data_addr.SanityCheck())
604       return false;
605     if (!data_size)
606       continue;
607     if (data_size <= kMaxBlockSize && data_addr.is_separate_file())
608       return false;
609     if (data_size > kMaxBlockSize && data_addr.is_block_file())
610       return false;
611   }
612 
613   return true;
614 }
615 
IncrementIoCount()616 void EntryImpl::IncrementIoCount() {
617   backend_->IncrementIoCount();
618 }
619 
DecrementIoCount()620 void EntryImpl::DecrementIoCount() {
621   backend_->DecrementIoCount();
622 }
623 
SetTimes(base::Time last_used,base::Time last_modified)624 void EntryImpl::SetTimes(base::Time last_used, base::Time last_modified) {
625   node_.Data()->last_used = last_used.ToInternalValue();
626   node_.Data()->last_modified = last_modified.ToInternalValue();
627   node_.set_modified();
628 }
629 
ReportIOTime(Operation op,const base::TimeTicks & start)630 void EntryImpl::ReportIOTime(Operation op, const base::TimeTicks& start) {
631   int group = backend_->GetSizeGroup();
632   switch (op) {
633     case kRead:
634       CACHE_UMA(AGE_MS, "ReadTime", group, start);
635       break;
636     case kWrite:
637       CACHE_UMA(AGE_MS, "WriteTime", group, start);
638       break;
639     case kSparseRead:
640       CACHE_UMA(AGE_MS, "SparseReadTime", 0, start);
641       break;
642     case kSparseWrite:
643       CACHE_UMA(AGE_MS, "SparseWriteTime", 0, start);
644       break;
645     case kAsyncIO:
646       CACHE_UMA(AGE_MS, "AsyncIOTime", group, start);
647       break;
648     default:
649       NOTREACHED();
650   }
651 }
652 
BeginLogging(net::NetLog * net_log,bool created)653 void EntryImpl::BeginLogging(net::NetLog* net_log, bool created) {
654   DCHECK(!net_log_.net_log());
655   net_log_ = net::BoundNetLog::Make(
656       net_log, net::NetLog::SOURCE_DISK_CACHE_ENTRY);
657   net_log_.BeginEvent(
658       net::NetLog::TYPE_DISK_CACHE_ENTRY_IMPL,
659       make_scoped_refptr(new EntryCreationParameters(GetKey(), created)));
660 }
661 
net_log() const662 const net::BoundNetLog& EntryImpl::net_log() const {
663   return net_log_;
664 }
665 
Doom()666 void EntryImpl::Doom() {
667   backend_->background_queue()->DoomEntryImpl(this);
668 }
669 
Close()670 void EntryImpl::Close() {
671   backend_->background_queue()->CloseEntryImpl(this);
672 }
673 
GetKey() const674 std::string EntryImpl::GetKey() const {
675   CacheEntryBlock* entry = const_cast<CacheEntryBlock*>(&entry_);
676   if (entry->Data()->key_len <= kMaxInternalKeyLength)
677     return std::string(entry->Data()->key);
678 
679   // We keep a copy of the key so that we can always return it, even if the
680   // backend is disabled.
681   if (!key_.empty())
682     return key_;
683 
684   Addr address(entry->Data()->long_key);
685   DCHECK(address.is_initialized());
686   size_t offset = 0;
687   if (address.is_block_file())
688     offset = address.start_block() * address.BlockSize() + kBlockHeaderSize;
689 
690   COMPILE_ASSERT(kNumStreams == kKeyFileIndex, invalid_key_index);
691   File* key_file = const_cast<EntryImpl*>(this)->GetBackingFile(address,
692                                                                 kKeyFileIndex);
693 
694   if (!key_file ||
695       !key_file->Read(WriteInto(&key_, entry->Data()->key_len + 1),
696                       entry->Data()->key_len + 1, offset))
697     key_.clear();
698   return key_;
699 }
700 
GetLastUsed() const701 Time EntryImpl::GetLastUsed() const {
702   CacheRankingsBlock* node = const_cast<CacheRankingsBlock*>(&node_);
703   return Time::FromInternalValue(node->Data()->last_used);
704 }
705 
GetLastModified() const706 Time EntryImpl::GetLastModified() const {
707   CacheRankingsBlock* node = const_cast<CacheRankingsBlock*>(&node_);
708   return Time::FromInternalValue(node->Data()->last_modified);
709 }
710 
GetDataSize(int index) const711 int32 EntryImpl::GetDataSize(int index) const {
712   if (index < 0 || index >= kNumStreams)
713     return 0;
714 
715   CacheEntryBlock* entry = const_cast<CacheEntryBlock*>(&entry_);
716   return entry->Data()->data_size[index];
717 }
718 
ReadData(int index,int offset,net::IOBuffer * buf,int buf_len,net::CompletionCallback * callback)719 int EntryImpl::ReadData(int index, int offset, net::IOBuffer* buf, int buf_len,
720                         net::CompletionCallback* callback) {
721   if (!callback)
722     return ReadDataImpl(index, offset, buf, buf_len, callback);
723 
724   DCHECK(node_.Data()->dirty || read_only_);
725   if (index < 0 || index >= kNumStreams)
726     return net::ERR_INVALID_ARGUMENT;
727 
728   int entry_size = entry_.Data()->data_size[index];
729   if (offset >= entry_size || offset < 0 || !buf_len)
730     return 0;
731 
732   if (buf_len < 0)
733     return net::ERR_INVALID_ARGUMENT;
734 
735   backend_->background_queue()->ReadData(this, index, offset, buf, buf_len,
736                                          callback);
737   return net::ERR_IO_PENDING;
738 }
739 
WriteData(int index,int offset,net::IOBuffer * buf,int buf_len,CompletionCallback * callback,bool truncate)740 int EntryImpl::WriteData(int index, int offset, net::IOBuffer* buf, int buf_len,
741                          CompletionCallback* callback, bool truncate) {
742   if (!callback)
743     return WriteDataImpl(index, offset, buf, buf_len, callback, truncate);
744 
745   DCHECK(node_.Data()->dirty || read_only_);
746   if (index < 0 || index >= kNumStreams)
747     return net::ERR_INVALID_ARGUMENT;
748 
749   if (offset < 0 || buf_len < 0)
750     return net::ERR_INVALID_ARGUMENT;
751 
752   backend_->background_queue()->WriteData(this, index, offset, buf, buf_len,
753                                           truncate, callback);
754   return net::ERR_IO_PENDING;
755 }
756 
ReadSparseData(int64 offset,net::IOBuffer * buf,int buf_len,net::CompletionCallback * callback)757 int EntryImpl::ReadSparseData(int64 offset, net::IOBuffer* buf, int buf_len,
758                               net::CompletionCallback* callback) {
759   if (!callback)
760     return ReadSparseDataImpl(offset, buf, buf_len, callback);
761 
762   backend_->background_queue()->ReadSparseData(this, offset, buf, buf_len,
763                                                callback);
764   return net::ERR_IO_PENDING;
765 }
766 
WriteSparseData(int64 offset,net::IOBuffer * buf,int buf_len,net::CompletionCallback * callback)767 int EntryImpl::WriteSparseData(int64 offset, net::IOBuffer* buf, int buf_len,
768                                net::CompletionCallback* callback) {
769   if (!callback)
770     return WriteSparseDataImpl(offset, buf, buf_len, callback);
771 
772   backend_->background_queue()->WriteSparseData(this, offset, buf, buf_len,
773                                                 callback);
774   return net::ERR_IO_PENDING;
775 }
776 
GetAvailableRange(int64 offset,int len,int64 * start,CompletionCallback * callback)777 int EntryImpl::GetAvailableRange(int64 offset, int len, int64* start,
778                                  CompletionCallback* callback) {
779   backend_->background_queue()->GetAvailableRange(this, offset, len, start,
780                                                   callback);
781   return net::ERR_IO_PENDING;
782 }
783 
CouldBeSparse() const784 bool EntryImpl::CouldBeSparse() const {
785   if (sparse_.get())
786     return true;
787 
788   scoped_ptr<SparseControl> sparse;
789   sparse.reset(new SparseControl(const_cast<EntryImpl*>(this)));
790   return sparse->CouldBeSparse();
791 }
792 
CancelSparseIO()793 void EntryImpl::CancelSparseIO() {
794   backend_->background_queue()->CancelSparseIO(this);
795 }
796 
ReadyForSparseIO(net::CompletionCallback * callback)797 int EntryImpl::ReadyForSparseIO(net::CompletionCallback* callback) {
798   if (!sparse_.get())
799     return net::OK;
800 
801   backend_->background_queue()->ReadyForSparseIO(this, callback);
802   return net::ERR_IO_PENDING;
803 }
804 
805 // When an entry is deleted from the cache, we clean up all the data associated
806 // with it for two reasons: to simplify the reuse of the block (we know that any
807 // unused block is filled with zeros), and to simplify the handling of write /
808 // read partial information from an entry (don't have to worry about returning
809 // data related to a previous cache entry because the range was not fully
810 // written before).
~EntryImpl()811 EntryImpl::~EntryImpl() {
812   Log("~EntryImpl in");
813 
814   // Save the sparse info to disk. This will generate IO for this entry and
815   // maybe for a child entry, so it is important to do it before deleting this
816   // entry.
817   sparse_.reset();
818 
819   // Remove this entry from the list of open entries.
820   backend_->OnEntryDestroyBegin(entry_.address());
821 
822   if (doomed_) {
823     DeleteEntryData(true);
824   } else {
825     net_log_.AddEvent(net::NetLog::TYPE_ENTRY_CLOSE, NULL);
826     bool ret = true;
827     for (int index = 0; index < kNumStreams; index++) {
828       if (user_buffers_[index].get()) {
829         if (!(ret = Flush(index, 0)))
830           LOG(ERROR) << "Failed to save user data";
831       }
832       if (unreported_size_[index]) {
833         backend_->ModifyStorageSize(
834             entry_.Data()->data_size[index] - unreported_size_[index],
835             entry_.Data()->data_size[index]);
836       }
837     }
838 
839     if (!ret) {
840       // There was a failure writing the actual data. Mark the entry as dirty.
841       int current_id = backend_->GetCurrentEntryId();
842       node_.Data()->dirty = current_id == 1 ? -1 : current_id - 1;
843       node_.Store();
844     } else if (node_.HasData() && !dirty_) {
845       node_.Data()->dirty = 0;
846       node_.Store();
847     }
848   }
849 
850   Trace("~EntryImpl out 0x%p", reinterpret_cast<void*>(this));
851   net_log_.EndEvent(net::NetLog::TYPE_DISK_CACHE_ENTRY_IMPL, NULL);
852   backend_->OnEntryDestroyEnd();
853 }
854 
855 // ------------------------------------------------------------------------
856 
InternalReadData(int index,int offset,net::IOBuffer * buf,int buf_len,CompletionCallback * callback)857 int EntryImpl::InternalReadData(int index, int offset, net::IOBuffer* buf,
858                                 int buf_len, CompletionCallback* callback) {
859   DCHECK(node_.Data()->dirty || read_only_);
860   DVLOG(2) << "Read from " << index << " at " << offset << " : " << buf_len;
861   if (index < 0 || index >= kNumStreams)
862     return net::ERR_INVALID_ARGUMENT;
863 
864   int entry_size = entry_.Data()->data_size[index];
865   if (offset >= entry_size || offset < 0 || !buf_len)
866     return 0;
867 
868   if (buf_len < 0)
869     return net::ERR_INVALID_ARGUMENT;
870 
871   TimeTicks start = TimeTicks::Now();
872 
873   if (offset + buf_len > entry_size)
874     buf_len = entry_size - offset;
875 
876   UpdateRank(false);
877 
878   backend_->OnEvent(Stats::READ_DATA);
879   backend_->OnRead(buf_len);
880 
881   Addr address(entry_.Data()->data_addr[index]);
882   int eof = address.is_initialized() ? entry_size : 0;
883   if (user_buffers_[index].get() &&
884       user_buffers_[index]->PreRead(eof, offset, &buf_len)) {
885     // Complete the operation locally.
886     buf_len = user_buffers_[index]->Read(offset, buf, buf_len);
887     ReportIOTime(kRead, start);
888     return buf_len;
889   }
890 
891   address.set_value(entry_.Data()->data_addr[index]);
892   DCHECK(address.is_initialized());
893   if (!address.is_initialized())
894     return net::ERR_FAILED;
895 
896   File* file = GetBackingFile(address, index);
897   if (!file)
898     return net::ERR_FAILED;
899 
900   size_t file_offset = offset;
901   if (address.is_block_file()) {
902     DCHECK_LE(offset + buf_len, kMaxBlockSize);
903     file_offset += address.start_block() * address.BlockSize() +
904                    kBlockHeaderSize;
905   }
906 
907   SyncCallback* io_callback = NULL;
908   if (callback) {
909     io_callback = new SyncCallback(this, buf, callback,
910                                    net::NetLog::TYPE_ENTRY_READ_DATA);
911   }
912 
913   bool completed;
914   if (!file->Read(buf->data(), buf_len, file_offset, io_callback, &completed)) {
915     if (io_callback)
916       io_callback->Discard();
917     return net::ERR_FAILED;
918   }
919 
920   if (io_callback && completed)
921     io_callback->Discard();
922 
923   ReportIOTime(kRead, start);
924   return (completed || !callback) ? buf_len : net::ERR_IO_PENDING;
925 }
926 
InternalWriteData(int index,int offset,net::IOBuffer * buf,int buf_len,CompletionCallback * callback,bool truncate)927 int EntryImpl::InternalWriteData(int index, int offset, net::IOBuffer* buf,
928                                  int buf_len, CompletionCallback* callback,
929                                  bool truncate) {
930   DCHECK(node_.Data()->dirty || read_only_);
931   DVLOG(2) << "Write to " << index << " at " << offset << " : " << buf_len;
932   if (index < 0 || index >= kNumStreams)
933     return net::ERR_INVALID_ARGUMENT;
934 
935   if (offset < 0 || buf_len < 0)
936     return net::ERR_INVALID_ARGUMENT;
937 
938   int max_file_size = backend_->MaxFileSize();
939 
940   // offset or buf_len could be negative numbers.
941   if (offset > max_file_size || buf_len > max_file_size ||
942       offset + buf_len > max_file_size) {
943     int size = offset + buf_len;
944     if (size <= max_file_size)
945       size = kint32max;
946     backend_->TooMuchStorageRequested(size);
947     return net::ERR_FAILED;
948   }
949 
950   TimeTicks start = TimeTicks::Now();
951 
952   // Read the size at this point (it may change inside prepare).
953   int entry_size = entry_.Data()->data_size[index];
954   bool extending = entry_size < offset + buf_len;
955   truncate = truncate && entry_size > offset + buf_len;
956   Trace("To PrepareTarget 0x%x", entry_.address().value());
957   if (!PrepareTarget(index, offset, buf_len, truncate))
958     return net::ERR_FAILED;
959 
960   Trace("From PrepareTarget 0x%x", entry_.address().value());
961   if (extending || truncate)
962     UpdateSize(index, entry_size, offset + buf_len);
963 
964   UpdateRank(true);
965 
966   backend_->OnEvent(Stats::WRITE_DATA);
967   backend_->OnWrite(buf_len);
968 
969   if (user_buffers_[index].get()) {
970     // Complete the operation locally.
971     user_buffers_[index]->Write(offset, buf, buf_len);
972     ReportIOTime(kWrite, start);
973     return buf_len;
974   }
975 
976   Addr address(entry_.Data()->data_addr[index]);
977   if (offset + buf_len == 0) {
978     if (truncate) {
979       DCHECK(!address.is_initialized());
980     }
981     return 0;
982   }
983 
984   File* file = GetBackingFile(address, index);
985   if (!file)
986     return net::ERR_FAILED;
987 
988   size_t file_offset = offset;
989   if (address.is_block_file()) {
990     DCHECK_LE(offset + buf_len, kMaxBlockSize);
991     file_offset += address.start_block() * address.BlockSize() +
992                    kBlockHeaderSize;
993   } else if (truncate || (extending && !buf_len)) {
994     if (!file->SetLength(offset + buf_len))
995       return net::ERR_FAILED;
996   }
997 
998   if (!buf_len)
999     return 0;
1000 
1001   SyncCallback* io_callback = NULL;
1002   if (callback) {
1003     io_callback = new SyncCallback(this, buf, callback,
1004                                    net::NetLog::TYPE_ENTRY_WRITE_DATA);
1005   }
1006 
1007   bool completed;
1008   if (!file->Write(buf->data(), buf_len, file_offset, io_callback,
1009                    &completed)) {
1010     if (io_callback)
1011       io_callback->Discard();
1012     return net::ERR_FAILED;
1013   }
1014 
1015   if (io_callback && completed)
1016     io_callback->Discard();
1017 
1018   ReportIOTime(kWrite, start);
1019   return (completed || !callback) ? buf_len : net::ERR_IO_PENDING;
1020 }
1021 
1022 // ------------------------------------------------------------------------
1023 
CreateDataBlock(int index,int size)1024 bool EntryImpl::CreateDataBlock(int index, int size) {
1025   DCHECK(index >= 0 && index < kNumStreams);
1026 
1027   Addr address(entry_.Data()->data_addr[index]);
1028   if (!CreateBlock(size, &address))
1029     return false;
1030 
1031   entry_.Data()->data_addr[index] = address.value();
1032   entry_.Store();
1033   return true;
1034 }
1035 
CreateBlock(int size,Addr * address)1036 bool EntryImpl::CreateBlock(int size, Addr* address) {
1037   DCHECK(!address->is_initialized());
1038 
1039   FileType file_type = Addr::RequiredFileType(size);
1040   if (EXTERNAL == file_type) {
1041     if (size > backend_->MaxFileSize())
1042       return false;
1043     if (!backend_->CreateExternalFile(address))
1044       return false;
1045   } else {
1046     int num_blocks = (size + Addr::BlockSizeForFileType(file_type) - 1) /
1047                      Addr::BlockSizeForFileType(file_type);
1048 
1049     if (!backend_->CreateBlock(file_type, num_blocks, address))
1050       return false;
1051   }
1052   return true;
1053 }
1054 
1055 // Note that this method may end up modifying a block file so upon return the
1056 // involved block will be free, and could be reused for something else. If there
1057 // is a crash after that point (and maybe before returning to the caller), the
1058 // entry will be left dirty... and at some point it will be discarded; it is
1059 // important that the entry doesn't keep a reference to this address, or we'll
1060 // end up deleting the contents of |address| once again.
DeleteData(Addr address,int index)1061 void EntryImpl::DeleteData(Addr address, int index) {
1062   if (!address.is_initialized())
1063     return;
1064   if (address.is_separate_file()) {
1065     int failure = !DeleteCacheFile(backend_->GetFileName(address));
1066     CACHE_UMA(COUNTS, "DeleteFailed", 0, failure);
1067     if (failure) {
1068       LOG(ERROR) << "Failed to delete " <<
1069           backend_->GetFileName(address).value() << " from the cache.";
1070     }
1071     if (files_[index])
1072       files_[index] = NULL;  // Releases the object.
1073   } else {
1074     backend_->DeleteBlock(address, true);
1075   }
1076 }
1077 
UpdateRank(bool modified)1078 void EntryImpl::UpdateRank(bool modified) {
1079   if (!doomed_) {
1080     // Everything is handled by the backend.
1081     backend_->UpdateRank(this, modified);
1082     return;
1083   }
1084 
1085   Time current = Time::Now();
1086   node_.Data()->last_used = current.ToInternalValue();
1087 
1088   if (modified)
1089     node_.Data()->last_modified = current.ToInternalValue();
1090 }
1091 
GetBackingFile(Addr address,int index)1092 File* EntryImpl::GetBackingFile(Addr address, int index) {
1093   File* file;
1094   if (address.is_separate_file())
1095     file = GetExternalFile(address, index);
1096   else
1097     file = backend_->File(address);
1098   return file;
1099 }
1100 
GetExternalFile(Addr address,int index)1101 File* EntryImpl::GetExternalFile(Addr address, int index) {
1102   DCHECK(index >= 0 && index <= kKeyFileIndex);
1103   if (!files_[index].get()) {
1104     // For a key file, use mixed mode IO.
1105     scoped_refptr<File> file(new File(kKeyFileIndex == index));
1106     if (file->Init(backend_->GetFileName(address)))
1107       files_[index].swap(file);
1108   }
1109   return files_[index].get();
1110 }
1111 
1112 // We keep a memory buffer for everything that ends up stored on a block file
1113 // (because we don't know yet the final data size), and for some of the data
1114 // that end up on external files. This function will initialize that memory
1115 // buffer and / or the files needed to store the data.
1116 //
1117 // In general, a buffer may overlap data already stored on disk, and in that
1118 // case, the contents of the buffer are the most accurate. It may also extend
1119 // the file, but we don't want to read from disk just to keep the buffer up to
1120 // date. This means that as soon as there is a chance to get confused about what
1121 // is the most recent version of some part of a file, we'll flush the buffer and
1122 // reuse it for the new data. Keep in mind that the normal use pattern is quite
1123 // simple (write sequentially from the beginning), so we optimize for handling
1124 // that case.
PrepareTarget(int index,int offset,int buf_len,bool truncate)1125 bool EntryImpl::PrepareTarget(int index, int offset, int buf_len,
1126                               bool truncate) {
1127   if (truncate)
1128     return HandleTruncation(index, offset, buf_len);
1129 
1130   if (!offset && !buf_len)
1131     return true;
1132 
1133   Addr address(entry_.Data()->data_addr[index]);
1134   if (address.is_initialized()) {
1135     if (address.is_block_file() && !MoveToLocalBuffer(index))
1136       return false;
1137 
1138     if (!user_buffers_[index].get() && offset < kMaxBlockSize) {
1139       // We are about to create a buffer for the first 16KB, make sure that we
1140       // preserve existing data.
1141       if (!CopyToLocalBuffer(index))
1142         return false;
1143     }
1144   }
1145 
1146   if (!user_buffers_[index].get())
1147     user_buffers_[index].reset(new UserBuffer(backend_));
1148 
1149   return PrepareBuffer(index, offset, buf_len);
1150 }
1151 
1152 // We get to this function with some data already stored. If there is a
1153 // truncation that results on data stored internally, we'll explicitly
1154 // handle the case here.
HandleTruncation(int index,int offset,int buf_len)1155 bool EntryImpl::HandleTruncation(int index, int offset, int buf_len) {
1156   Addr address(entry_.Data()->data_addr[index]);
1157 
1158   int current_size = entry_.Data()->data_size[index];
1159   int new_size = offset + buf_len;
1160 
1161   if (!new_size) {
1162     // This is by far the most common scenario.
1163     backend_->ModifyStorageSize(current_size - unreported_size_[index], 0);
1164     entry_.Data()->data_addr[index] = 0;
1165     entry_.Data()->data_size[index] = 0;
1166     unreported_size_[index] = 0;
1167     entry_.Store();
1168     DeleteData(address, index);
1169 
1170     user_buffers_[index].reset();
1171     return true;
1172   }
1173 
1174   // We never postpone truncating a file, if there is one, but we may postpone
1175   // telling the backend about the size reduction.
1176   if (user_buffers_[index].get()) {
1177     DCHECK_GE(current_size, user_buffers_[index]->Start());
1178     if (!address.is_initialized()) {
1179       // There is no overlap between the buffer and disk.
1180       if (new_size > user_buffers_[index]->Start()) {
1181         // Just truncate our buffer.
1182         DCHECK_LT(new_size, user_buffers_[index]->End());
1183         user_buffers_[index]->Truncate(new_size);
1184         return true;
1185       }
1186 
1187       // Just discard our buffer.
1188       user_buffers_[index]->Reset();
1189       return PrepareBuffer(index, offset, buf_len);
1190     }
1191 
1192     // There is some overlap or we need to extend the file before the
1193     // truncation.
1194     if (offset > user_buffers_[index]->Start())
1195       user_buffers_[index]->Truncate(new_size);
1196     UpdateSize(index, current_size, new_size);
1197     if (!Flush(index, 0))
1198       return false;
1199     user_buffers_[index].reset();
1200   }
1201 
1202   // We have data somewhere, and it is not in a buffer.
1203   DCHECK(!user_buffers_[index].get());
1204   DCHECK(address.is_initialized());
1205 
1206   if (new_size > kMaxBlockSize)
1207     return true;  // Let the operation go directly to disk.
1208 
1209   return ImportSeparateFile(index, offset + buf_len);
1210 }
1211 
CopyToLocalBuffer(int index)1212 bool EntryImpl::CopyToLocalBuffer(int index) {
1213   Addr address(entry_.Data()->data_addr[index]);
1214   DCHECK(!user_buffers_[index].get());
1215   DCHECK(address.is_initialized());
1216 
1217   int len = std::min(entry_.Data()->data_size[index], kMaxBlockSize);
1218   user_buffers_[index].reset(new UserBuffer(backend_));
1219   user_buffers_[index]->Write(len, NULL, 0);
1220 
1221   File* file = GetBackingFile(address, index);
1222   int offset = 0;
1223 
1224   if (address.is_block_file())
1225     offset = address.start_block() * address.BlockSize() + kBlockHeaderSize;
1226 
1227   if (!file ||
1228       !file->Read(user_buffers_[index]->Data(), len, offset, NULL, NULL)) {
1229     user_buffers_[index].reset();
1230     return false;
1231   }
1232   return true;
1233 }
1234 
MoveToLocalBuffer(int index)1235 bool EntryImpl::MoveToLocalBuffer(int index) {
1236   if (!CopyToLocalBuffer(index))
1237     return false;
1238 
1239   Addr address(entry_.Data()->data_addr[index]);
1240   entry_.Data()->data_addr[index] = 0;
1241   entry_.Store();
1242   DeleteData(address, index);
1243 
1244   // If we lose this entry we'll see it as zero sized.
1245   int len = entry_.Data()->data_size[index];
1246   backend_->ModifyStorageSize(len - unreported_size_[index], 0);
1247   unreported_size_[index] = len;
1248   return true;
1249 }
1250 
ImportSeparateFile(int index,int new_size)1251 bool EntryImpl::ImportSeparateFile(int index, int new_size) {
1252   if (entry_.Data()->data_size[index] > new_size)
1253     UpdateSize(index, entry_.Data()->data_size[index], new_size);
1254 
1255   return MoveToLocalBuffer(index);
1256 }
1257 
PrepareBuffer(int index,int offset,int buf_len)1258 bool EntryImpl::PrepareBuffer(int index, int offset, int buf_len) {
1259   DCHECK(user_buffers_[index].get());
1260   if ((user_buffers_[index]->End() && offset > user_buffers_[index]->End()) ||
1261       offset > entry_.Data()->data_size[index]) {
1262     // We are about to extend the buffer or the file (with zeros), so make sure
1263     // that we are not overwriting anything.
1264     Addr address(entry_.Data()->data_addr[index]);
1265     if (address.is_initialized() && address.is_separate_file()) {
1266       if (!Flush(index, 0))
1267         return false;
1268       // There is an actual file already, and we don't want to keep track of
1269       // its length so we let this operation go straight to disk.
1270       // The only case when a buffer is allowed to extend the file (as in fill
1271       // with zeros before the start) is when there is no file yet to extend.
1272       user_buffers_[index].reset();
1273       return true;
1274     }
1275   }
1276 
1277   if (!user_buffers_[index]->PreWrite(offset, buf_len)) {
1278     if (!Flush(index, offset + buf_len))
1279       return false;
1280 
1281     // Lets try again.
1282     if (offset > user_buffers_[index]->End() ||
1283         !user_buffers_[index]->PreWrite(offset, buf_len)) {
1284       // We cannot complete the operation with a buffer.
1285       DCHECK(!user_buffers_[index]->Size());
1286       DCHECK(!user_buffers_[index]->Start());
1287       user_buffers_[index].reset();
1288     }
1289   }
1290   return true;
1291 }
1292 
Flush(int index,int min_len)1293 bool EntryImpl::Flush(int index, int min_len) {
1294   Addr address(entry_.Data()->data_addr[index]);
1295   DCHECK(user_buffers_[index].get());
1296   DCHECK(!address.is_initialized() || address.is_separate_file());
1297   DVLOG(3) << "Flush";
1298 
1299   int size = std::max(entry_.Data()->data_size[index], min_len);
1300   if (size && !address.is_initialized() && !CreateDataBlock(index, size))
1301     return false;
1302 
1303   if (!entry_.Data()->data_size[index]) {
1304     DCHECK(!user_buffers_[index]->Size());
1305     return true;
1306   }
1307 
1308   address.set_value(entry_.Data()->data_addr[index]);
1309 
1310   int len = user_buffers_[index]->Size();
1311   int offset = user_buffers_[index]->Start();
1312   if (!len && !offset)
1313     return true;
1314 
1315   if (address.is_block_file()) {
1316     DCHECK_EQ(len, entry_.Data()->data_size[index]);
1317     DCHECK(!offset);
1318     offset = address.start_block() * address.BlockSize() + kBlockHeaderSize;
1319   }
1320 
1321   File* file = GetBackingFile(address, index);
1322   if (!file)
1323     return false;
1324 
1325   if (!file->Write(user_buffers_[index]->Data(), len, offset, NULL, NULL))
1326     return false;
1327   user_buffers_[index]->Reset();
1328 
1329   return true;
1330 }
1331 
UpdateSize(int index,int old_size,int new_size)1332 void EntryImpl::UpdateSize(int index, int old_size, int new_size) {
1333   if (entry_.Data()->data_size[index] == new_size)
1334     return;
1335 
1336   unreported_size_[index] += new_size - old_size;
1337   entry_.Data()->data_size[index] = new_size;
1338   entry_.set_modified();
1339 }
1340 
InitSparseData()1341 int EntryImpl::InitSparseData() {
1342   if (sparse_.get())
1343     return net::OK;
1344 
1345   // Use a local variable so that sparse_ never goes from 'valid' to NULL.
1346   scoped_ptr<SparseControl> sparse(new SparseControl(this));
1347   int result = sparse->Init();
1348   if (net::OK == result)
1349     sparse_.swap(sparse);
1350 
1351   return result;
1352 }
1353 
SetEntryFlags(uint32 flags)1354 void EntryImpl::SetEntryFlags(uint32 flags) {
1355   entry_.Data()->flags |= flags;
1356   entry_.set_modified();
1357 }
1358 
GetEntryFlags()1359 uint32 EntryImpl::GetEntryFlags() {
1360   return entry_.Data()->flags;
1361 }
1362 
GetData(int index,char ** buffer,Addr * address)1363 void EntryImpl::GetData(int index, char** buffer, Addr* address) {
1364   if (user_buffers_[index].get() && user_buffers_[index]->Size() &&
1365       !user_buffers_[index]->Start()) {
1366     // The data is already in memory, just copy it and we're done.
1367     int data_len = entry_.Data()->data_size[index];
1368     if (data_len <= user_buffers_[index]->Size()) {
1369       DCHECK(!user_buffers_[index]->Start());
1370       *buffer = new char[data_len];
1371       memcpy(*buffer, user_buffers_[index]->Data(), data_len);
1372       return;
1373     }
1374   }
1375 
1376   // Bad news: we'd have to read the info from disk so instead we'll just tell
1377   // the caller where to read from.
1378   *buffer = NULL;
1379   address->set_value(entry_.Data()->data_addr[index]);
1380   if (address->is_initialized()) {
1381     // Prevent us from deleting the block from the backing store.
1382     backend_->ModifyStorageSize(entry_.Data()->data_size[index] -
1383                                     unreported_size_[index], 0);
1384     entry_.Data()->data_addr[index] = 0;
1385     entry_.Data()->data_size[index] = 0;
1386   }
1387 }
1388 
Log(const char * msg)1389 void EntryImpl::Log(const char* msg) {
1390   int dirty = 0;
1391   if (node_.HasData()) {
1392     dirty = node_.Data()->dirty;
1393   }
1394 
1395   Trace("%s 0x%p 0x%x 0x%x", msg, reinterpret_cast<void*>(this),
1396         entry_.address().value(), node_.address().value());
1397 
1398   Trace("  data: 0x%x 0x%x 0x%x", entry_.Data()->data_addr[0],
1399         entry_.Data()->data_addr[1], entry_.Data()->long_key);
1400 
1401   Trace("  doomed: %d 0x%x", doomed_, dirty);
1402 }
1403 
1404 }  // namespace disk_cache
1405