1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifdef UNSAFE_BUFFERS_BUILD
6 // TODO(crbug.com/40284755): Remove this and spanify to fix the errors.
7 #pragma allow_unsafe_buffers
8 #endif
9
10 #include "net/disk_cache/blockfile/sparse_control.h"
11
12 #include <stdint.h>
13
14 #include "base/format_macros.h"
15 #include "base/functional/bind.h"
16 #include "base/location.h"
17 #include "base/logging.h"
18 #include "base/numerics/checked_math.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/task/single_thread_task_runner.h"
22 #include "base/time/time.h"
23 #include "net/base/interval.h"
24 #include "net/base/io_buffer.h"
25 #include "net/base/net_errors.h"
26 #include "net/disk_cache/blockfile/backend_impl.h"
27 #include "net/disk_cache/blockfile/entry_impl.h"
28 #include "net/disk_cache/blockfile/file.h"
29 #include "net/disk_cache/net_log_parameters.h"
30 #include "net/log/net_log.h"
31 #include "net/log/net_log_event_type.h"
32 #include "net/log/net_log_with_source.h"
33
34 using base::Time;
35
36 namespace {
37
38 // Stream of the sparse data index.
39 const int kSparseIndex = 2;
40
41 // Stream of the sparse data.
42 const int kSparseData = 1;
43
44 // We can have up to 64k children.
45 const int kMaxMapSize = 8 * 1024;
46
47 // The maximum number of bytes that a child can store.
48 const int kMaxEntrySize = 0x100000;
49
50 // How much we can address. 8 KiB bitmap (kMaxMapSize above) gives us offsets
51 // up to 64 GiB.
52 const int64_t kMaxEndOffset = 8ll * kMaxMapSize * kMaxEntrySize;
53
54 // The size of each data block (tracked by the child allocation bitmap).
55 const int kBlockSize = 1024;
56
57 // Returns the name of a child entry given the base_name and signature of the
58 // parent and the child_id.
59 // If the entry is called entry_name, child entries will be named something
60 // like Range_entry_name:XXX:YYY where XXX is the entry signature and YYY is the
61 // number of the particular child.
GenerateChildName(const std::string & base_name,int64_t signature,int64_t child_id)62 std::string GenerateChildName(const std::string& base_name,
63 int64_t signature,
64 int64_t child_id) {
65 return base::StringPrintf("Range_%s:%" PRIx64 ":%" PRIx64, base_name.c_str(),
66 signature, child_id);
67 }
68
69 // This class deletes the children of a sparse entry.
70 class ChildrenDeleter
71 : public base::RefCounted<ChildrenDeleter>,
72 public disk_cache::FileIOCallback {
73 public:
ChildrenDeleter(disk_cache::BackendImpl * backend,const std::string & name)74 ChildrenDeleter(disk_cache::BackendImpl* backend, const std::string& name)
75 : backend_(backend->GetWeakPtr()), name_(name) {}
76
77 ChildrenDeleter(const ChildrenDeleter&) = delete;
78 ChildrenDeleter& operator=(const ChildrenDeleter&) = delete;
79
80 void OnFileIOComplete(int bytes_copied) override;
81
82 // Two ways of deleting the children: if we have the children map, use Start()
83 // directly, otherwise pass the data address to ReadData().
84 void Start(std::unique_ptr<char[]> buffer, int len);
85 void ReadData(disk_cache::Addr address, int len);
86
87 private:
88 friend class base::RefCounted<ChildrenDeleter>;
89 ~ChildrenDeleter() override = default;
90
91 void DeleteChildren();
92
93 base::WeakPtr<disk_cache::BackendImpl> backend_;
94 std::string name_;
95 disk_cache::Bitmap children_map_;
96 int64_t signature_ = 0;
97 std::unique_ptr<char[]> buffer_;
98 };
99
100 // This is the callback of the file operation.
OnFileIOComplete(int bytes_copied)101 void ChildrenDeleter::OnFileIOComplete(int bytes_copied) {
102 Start(std::move(buffer_), bytes_copied);
103 }
104
Start(std::unique_ptr<char[]> buffer,int len)105 void ChildrenDeleter::Start(std::unique_ptr<char[]> buffer, int len) {
106 buffer_ = std::move(buffer);
107 if (len < static_cast<int>(sizeof(disk_cache::SparseData)))
108 return Release();
109
110 // Just copy the information from |buffer|, delete |buffer| and start deleting
111 // the child entries.
112 disk_cache::SparseData* data =
113 reinterpret_cast<disk_cache::SparseData*>(buffer_.get());
114 signature_ = data->header.signature;
115
116 int num_bits = (len - sizeof(disk_cache::SparseHeader)) * 8;
117 children_map_.Resize(num_bits, false);
118 children_map_.SetMap(data->bitmap, num_bits / 32);
119 buffer_.reset();
120
121 DeleteChildren();
122 }
123
ReadData(disk_cache::Addr address,int len)124 void ChildrenDeleter::ReadData(disk_cache::Addr address, int len) {
125 DCHECK(address.is_block_file());
126 if (!backend_.get())
127 return Release();
128
129 disk_cache::File* file(backend_->File(address));
130 if (!file)
131 return Release();
132
133 size_t file_offset = address.start_block() * address.BlockSize() +
134 disk_cache::kBlockHeaderSize;
135
136 buffer_ = std::make_unique<char[]>(len);
137 bool completed;
138 if (!file->Read(buffer_.get(), len, file_offset, this, &completed))
139 return Release();
140
141 if (completed)
142 OnFileIOComplete(len);
143
144 // And wait until OnFileIOComplete gets called.
145 }
146
DeleteChildren()147 void ChildrenDeleter::DeleteChildren() {
148 int child_id = 0;
149 if (!children_map_.FindNextSetBit(&child_id) || !backend_.get()) {
150 // We are done. Just delete this object.
151 return Release();
152 }
153 std::string child_name = GenerateChildName(name_, signature_, child_id);
154 backend_->SyncDoomEntry(child_name);
155 children_map_.Set(child_id, false);
156
157 // Post a task to delete the next child.
158 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
159 FROM_HERE, base::BindOnce(&ChildrenDeleter::DeleteChildren, this));
160 }
161
162 // Returns the NetLog event type corresponding to a SparseOperation.
GetSparseEventType(disk_cache::SparseControl::SparseOperation operation)163 net::NetLogEventType GetSparseEventType(
164 disk_cache::SparseControl::SparseOperation operation) {
165 switch (operation) {
166 case disk_cache::SparseControl::kReadOperation:
167 return net::NetLogEventType::SPARSE_READ;
168 case disk_cache::SparseControl::kWriteOperation:
169 return net::NetLogEventType::SPARSE_WRITE;
170 case disk_cache::SparseControl::kGetRangeOperation:
171 return net::NetLogEventType::SPARSE_GET_RANGE;
172 default:
173 NOTREACHED();
174 }
175 }
176
177 // Logs the end event for |operation| on a child entry. Range operations log
178 // no events for each child they search through.
LogChildOperationEnd(const net::NetLogWithSource & net_log,disk_cache::SparseControl::SparseOperation operation,int result)179 void LogChildOperationEnd(const net::NetLogWithSource& net_log,
180 disk_cache::SparseControl::SparseOperation operation,
181 int result) {
182 if (net_log.IsCapturing()) {
183 net::NetLogEventType event_type;
184 switch (operation) {
185 case disk_cache::SparseControl::kReadOperation:
186 event_type = net::NetLogEventType::SPARSE_READ_CHILD_DATA;
187 break;
188 case disk_cache::SparseControl::kWriteOperation:
189 event_type = net::NetLogEventType::SPARSE_WRITE_CHILD_DATA;
190 break;
191 case disk_cache::SparseControl::kGetRangeOperation:
192 return;
193 default:
194 NOTREACHED();
195 }
196 net_log.EndEventWithNetErrorCode(event_type, result);
197 }
198 }
199
200 } // namespace.
201
202 namespace disk_cache {
203
SparseControl(EntryImpl * entry)204 SparseControl::SparseControl(EntryImpl* entry)
205 : entry_(entry),
206 child_map_(child_data_.bitmap, kNumSparseBits, kNumSparseBits / 32) {
207 memset(&sparse_header_, 0, sizeof(sparse_header_));
208 memset(&child_data_, 0, sizeof(child_data_));
209 }
210
~SparseControl()211 SparseControl::~SparseControl() {
212 if (child_)
213 CloseChild();
214 if (init_)
215 WriteSparseData();
216 }
217
Init()218 int SparseControl::Init() {
219 DCHECK(!init_);
220
221 // We should not have sparse data for the exposed entry.
222 if (entry_->GetDataSize(kSparseData))
223 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
224
225 // Now see if there is something where we store our data.
226 int rv = net::OK;
227 int data_len = entry_->GetDataSize(kSparseIndex);
228 if (!data_len) {
229 rv = CreateSparseEntry();
230 } else {
231 rv = OpenSparseEntry(data_len);
232 }
233
234 if (rv == net::OK)
235 init_ = true;
236 return rv;
237 }
238
CouldBeSparse() const239 bool SparseControl::CouldBeSparse() const {
240 DCHECK(!init_);
241
242 if (entry_->GetDataSize(kSparseData))
243 return false;
244
245 // We don't verify the data, just see if it could be there.
246 return (entry_->GetDataSize(kSparseIndex) != 0);
247 }
248
StartIO(SparseOperation op,int64_t offset,net::IOBuffer * buf,int buf_len,CompletionOnceCallback callback)249 int SparseControl::StartIO(SparseOperation op,
250 int64_t offset,
251 net::IOBuffer* buf,
252 int buf_len,
253 CompletionOnceCallback callback) {
254 DCHECK(init_);
255 // We don't support simultaneous IO for sparse data.
256 if (operation_ != kNoOperation)
257 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
258
259 if (offset < 0 || buf_len < 0)
260 return net::ERR_INVALID_ARGUMENT;
261
262 int64_t end_offset = 0; // non-inclusive.
263 if (!base::CheckAdd(offset, buf_len).AssignIfValid(&end_offset)) {
264 // Writes aren't permitted to try to cross the end of address space;
265 // read/GetAvailableRange clip.
266 if (op == kWriteOperation)
267 return net::ERR_INVALID_ARGUMENT;
268 else
269 end_offset = std::numeric_limits<int64_t>::max();
270 }
271
272 if (offset >= kMaxEndOffset) {
273 // Interval is within valid offset space, but completely outside backend
274 // supported range. Permit GetAvailableRange to say "nothing here", actual
275 // I/O fails.
276 if (op == kGetRangeOperation)
277 return 0;
278 else
279 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
280 }
281
282 if (end_offset > kMaxEndOffset) {
283 // Interval is partially what the backend can handle. Fail writes, clip
284 // reads.
285 if (op == kWriteOperation)
286 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
287 else
288 end_offset = kMaxEndOffset;
289 }
290
291 DCHECK_GE(end_offset, offset);
292 buf_len = end_offset - offset;
293
294 DCHECK(!user_buf_.get());
295 DCHECK(user_callback_.is_null());
296
297 if (!buf && (op == kReadOperation || op == kWriteOperation))
298 return 0;
299
300 // Copy the operation parameters.
301 operation_ = op;
302 offset_ = offset;
303 user_buf_ = buf ? base::MakeRefCounted<net::DrainableIOBuffer>(buf, buf_len)
304 : nullptr;
305 buf_len_ = buf_len;
306 user_callback_ = std::move(callback);
307
308 result_ = 0;
309 pending_ = false;
310 finished_ = false;
311 abort_ = false;
312
313 if (entry_->net_log().IsCapturing()) {
314 NetLogSparseOperation(entry_->net_log(), GetSparseEventType(operation_),
315 net::NetLogEventPhase::BEGIN, offset_, buf_len_);
316 }
317 DoChildrenIO();
318
319 if (!pending_) {
320 // Everything was done synchronously.
321 operation_ = kNoOperation;
322 user_buf_ = nullptr;
323 user_callback_.Reset();
324 return result_;
325 }
326
327 return net::ERR_IO_PENDING;
328 }
329
GetAvailableRange(int64_t offset,int len)330 RangeResult SparseControl::GetAvailableRange(int64_t offset, int len) {
331 DCHECK(init_);
332 // We don't support simultaneous IO for sparse data.
333 if (operation_ != kNoOperation)
334 return RangeResult(net::ERR_CACHE_OPERATION_NOT_SUPPORTED);
335
336 range_found_ = false;
337 int result = StartIO(kGetRangeOperation, offset, nullptr, len,
338 CompletionOnceCallback());
339 if (range_found_)
340 return RangeResult(offset_, result);
341
342 // This is a failure. We want to return a valid start value if it's just an
343 // empty range, though.
344 if (result < 0)
345 return RangeResult(static_cast<net::Error>(result));
346 return RangeResult(offset, 0);
347 }
348
CancelIO()349 void SparseControl::CancelIO() {
350 if (operation_ == kNoOperation)
351 return;
352 abort_ = true;
353 }
354
ReadyToUse(CompletionOnceCallback callback)355 int SparseControl::ReadyToUse(CompletionOnceCallback callback) {
356 if (!abort_)
357 return net::OK;
358
359 // We'll grab another reference to keep this object alive because we just have
360 // one extra reference due to the pending IO operation itself, but we'll
361 // release that one before invoking user_callback_.
362 entry_->AddRef(); // Balanced in DoAbortCallbacks.
363 abort_callbacks_.push_back(std::move(callback));
364 return net::ERR_IO_PENDING;
365 }
366
367 // Static
DeleteChildren(EntryImpl * entry)368 void SparseControl::DeleteChildren(EntryImpl* entry) {
369 DCHECK(entry->GetEntryFlags() & PARENT_ENTRY);
370 int data_len = entry->GetDataSize(kSparseIndex);
371 if (data_len < static_cast<int>(sizeof(SparseData)) ||
372 entry->GetDataSize(kSparseData))
373 return;
374
375 int map_len = data_len - sizeof(SparseHeader);
376 if (map_len > kMaxMapSize || map_len % 4)
377 return;
378
379 std::unique_ptr<char[]> buffer;
380 Addr address;
381 entry->GetData(kSparseIndex, &buffer, &address);
382 if (!buffer && !address.is_initialized())
383 return;
384
385 entry->net_log().AddEvent(net::NetLogEventType::SPARSE_DELETE_CHILDREN);
386
387 DCHECK(entry->backend_.get());
388 ChildrenDeleter* deleter = new ChildrenDeleter(entry->backend_.get(),
389 entry->GetKey());
390 // The object will self destruct when finished.
391 deleter->AddRef();
392
393 if (buffer) {
394 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
395 FROM_HERE, base::BindOnce(&ChildrenDeleter::Start, deleter,
396 std::move(buffer), data_len));
397 } else {
398 base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
399 FROM_HERE,
400 base::BindOnce(&ChildrenDeleter::ReadData, deleter, address, data_len));
401 }
402 }
403
404 // We are going to start using this entry to store sparse data, so we have to
405 // initialize our control info.
CreateSparseEntry()406 int SparseControl::CreateSparseEntry() {
407 if (CHILD_ENTRY & entry_->GetEntryFlags())
408 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
409
410 memset(&sparse_header_, 0, sizeof(sparse_header_));
411 sparse_header_.signature = Time::Now().ToInternalValue();
412 sparse_header_.magic = kIndexMagic;
413 sparse_header_.parent_key_len = entry_->GetKey().size();
414 children_map_.Resize(kNumSparseBits, true);
415
416 // Save the header. The bitmap is saved in the destructor.
417 scoped_refptr<net::IOBuffer> buf = base::MakeRefCounted<net::WrappedIOBuffer>(
418 base::as_chars(base::span_from_ref(sparse_header_)));
419
420 int rv = entry_->WriteData(kSparseIndex, 0, buf.get(), sizeof(sparse_header_),
421 CompletionOnceCallback(), false);
422 if (rv != sizeof(sparse_header_)) {
423 DLOG(ERROR) << "Unable to save sparse_header_";
424 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
425 }
426
427 entry_->SetEntryFlags(PARENT_ENTRY);
428 return net::OK;
429 }
430
431 // We are opening an entry from disk. Make sure that our control data is there.
OpenSparseEntry(int data_len)432 int SparseControl::OpenSparseEntry(int data_len) {
433 if (data_len < static_cast<int>(sizeof(SparseData)))
434 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
435
436 if (entry_->GetDataSize(kSparseData))
437 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
438
439 if (!(PARENT_ENTRY & entry_->GetEntryFlags()))
440 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
441
442 // Don't go over board with the bitmap.
443 int map_len = data_len - sizeof(sparse_header_);
444 if (map_len > kMaxMapSize || map_len % 4)
445 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
446
447 scoped_refptr<net::IOBuffer> buf = base::MakeRefCounted<net::WrappedIOBuffer>(
448 base::as_chars(base::span_from_ref(sparse_header_)));
449
450 // Read header.
451 int rv = entry_->ReadData(kSparseIndex, 0, buf.get(), sizeof(sparse_header_),
452 CompletionOnceCallback());
453 if (rv != static_cast<int>(sizeof(sparse_header_)))
454 return net::ERR_CACHE_READ_FAILURE;
455
456 // The real validation should be performed by the caller. This is just to
457 // double check.
458 if (sparse_header_.magic != kIndexMagic ||
459 sparse_header_.parent_key_len !=
460 static_cast<int>(entry_->GetKey().size()))
461 return net::ERR_CACHE_OPERATION_NOT_SUPPORTED;
462
463 // Read the actual bitmap.
464 buf = base::MakeRefCounted<net::IOBufferWithSize>(map_len);
465 rv = entry_->ReadData(kSparseIndex, sizeof(sparse_header_), buf.get(),
466 map_len, CompletionOnceCallback());
467 if (rv != map_len)
468 return net::ERR_CACHE_READ_FAILURE;
469
470 // Grow the bitmap to the current size and copy the bits.
471 children_map_.Resize(map_len * 8, false);
472 children_map_.SetMap(reinterpret_cast<uint32_t*>(buf->data()), map_len);
473 return net::OK;
474 }
475
OpenChild()476 bool SparseControl::OpenChild() {
477 DCHECK_GE(result_, 0);
478
479 std::string key = GenerateChildKey();
480 if (child_) {
481 // Keep using the same child or open another one?.
482 if (key == child_->GetKey())
483 return true;
484 CloseChild();
485 }
486
487 // See if we are tracking this child.
488 if (!ChildPresent())
489 return ContinueWithoutChild(key);
490
491 if (!entry_->backend_.get())
492 return false;
493
494 child_ = entry_->backend_->OpenEntryImpl(key);
495 if (!child_)
496 return ContinueWithoutChild(key);
497
498 if (!(CHILD_ENTRY & child_->GetEntryFlags()) ||
499 child_->GetDataSize(kSparseIndex) < static_cast<int>(sizeof(child_data_)))
500 return KillChildAndContinue(key, false);
501
502 auto buf = base::MakeRefCounted<net::WrappedIOBuffer>(
503 base::as_chars(base::span_from_ref(child_data_)));
504
505 // Read signature.
506 int rv = child_->ReadData(kSparseIndex, 0, buf.get(), sizeof(child_data_),
507 CompletionOnceCallback());
508 if (rv != sizeof(child_data_))
509 return KillChildAndContinue(key, true); // This is a fatal failure.
510
511 if (child_data_.header.signature != sparse_header_.signature ||
512 child_data_.header.magic != kIndexMagic)
513 return KillChildAndContinue(key, false);
514
515 if (child_data_.header.last_block_len < 0 ||
516 child_data_.header.last_block_len >= kBlockSize) {
517 // Make sure these values are always within range.
518 child_data_.header.last_block_len = 0;
519 child_data_.header.last_block = -1;
520 }
521
522 return true;
523 }
524
CloseChild()525 void SparseControl::CloseChild() {
526 auto buf = base::MakeRefCounted<net::WrappedIOBuffer>(
527 base::as_chars(base::span_from_ref(child_data_)));
528
529 // Save the allocation bitmap before closing the child entry.
530 int rv = child_->WriteData(kSparseIndex, 0, buf.get(), sizeof(child_data_),
531 CompletionOnceCallback(), false);
532 if (rv != sizeof(child_data_))
533 DLOG(ERROR) << "Failed to save child data";
534 child_ = nullptr;
535 }
536
GenerateChildKey()537 std::string SparseControl::GenerateChildKey() {
538 return GenerateChildName(entry_->GetKey(), sparse_header_.signature,
539 offset_ >> 20);
540 }
541
542 // We are deleting the child because something went wrong.
KillChildAndContinue(const std::string & key,bool fatal)543 bool SparseControl::KillChildAndContinue(const std::string& key, bool fatal) {
544 SetChildBit(false);
545 child_->DoomImpl();
546 child_ = nullptr;
547 if (fatal) {
548 result_ = net::ERR_CACHE_READ_FAILURE;
549 return false;
550 }
551 return ContinueWithoutChild(key);
552 }
553
554 // We were not able to open this child; see what we can do.
ContinueWithoutChild(const std::string & key)555 bool SparseControl::ContinueWithoutChild(const std::string& key) {
556 if (kReadOperation == operation_)
557 return false;
558 if (kGetRangeOperation == operation_)
559 return true;
560
561 if (!entry_->backend_.get())
562 return false;
563
564 child_ = entry_->backend_->CreateEntryImpl(key);
565 if (!child_) {
566 child_ = nullptr;
567 result_ = net::ERR_CACHE_READ_FAILURE;
568 return false;
569 }
570 // Write signature.
571 InitChildData();
572 return true;
573 }
574
ChildPresent()575 bool SparseControl::ChildPresent() {
576 int child_bit = static_cast<int>(offset_ >> 20);
577 if (children_map_.Size() <= child_bit)
578 return false;
579
580 return children_map_.Get(child_bit);
581 }
582
SetChildBit(bool value)583 void SparseControl::SetChildBit(bool value) {
584 int child_bit = static_cast<int>(offset_ >> 20);
585
586 // We may have to increase the bitmap of child entries.
587 if (children_map_.Size() <= child_bit)
588 children_map_.Resize(Bitmap::RequiredArraySize(child_bit + 1) * 32, true);
589
590 children_map_.Set(child_bit, value);
591 }
592
WriteSparseData()593 void SparseControl::WriteSparseData() {
594 auto buf = base::MakeRefCounted<net::WrappedIOBuffer>(
595 base::as_chars(children_map_.GetSpan()));
596
597 int rv = entry_->WriteData(kSparseIndex, sizeof(sparse_header_), buf.get(),
598 buf->size(), CompletionOnceCallback(), false);
599 if (rv != buf->size()) {
600 DLOG(ERROR) << "Unable to save sparse map";
601 }
602 }
603
VerifyRange()604 bool SparseControl::VerifyRange() {
605 DCHECK_GE(result_, 0);
606
607 child_offset_ = static_cast<int>(offset_) & (kMaxEntrySize - 1);
608 child_len_ = std::min(buf_len_, kMaxEntrySize - child_offset_);
609
610 // We can write to (or get info from) anywhere in this child.
611 if (operation_ != kReadOperation)
612 return true;
613
614 // Check that there are no holes in this range.
615 int last_bit = (child_offset_ + child_len_ + 1023) >> 10;
616 int start = child_offset_ >> 10;
617 if (child_map_.FindNextBit(&start, last_bit, false)) {
618 // Something is not here.
619 DCHECK_GE(child_data_.header.last_block_len, 0);
620 DCHECK_LT(child_data_.header.last_block_len, kBlockSize);
621 int partial_block_len = PartialBlockLength(start);
622 if (start == child_offset_ >> 10) {
623 // It looks like we don't have anything.
624 if (partial_block_len <= (child_offset_ & (kBlockSize - 1)))
625 return false;
626 }
627
628 // We have the first part.
629 child_len_ = (start << 10) - child_offset_;
630 if (partial_block_len) {
631 // We may have a few extra bytes.
632 child_len_ = std::min(child_len_ + partial_block_len, buf_len_);
633 }
634 // There is no need to read more after this one.
635 buf_len_ = child_len_;
636 }
637 return true;
638 }
639
UpdateRange(int result)640 void SparseControl::UpdateRange(int result) {
641 if (result <= 0 || operation_ != kWriteOperation)
642 return;
643
644 DCHECK_GE(child_data_.header.last_block_len, 0);
645 DCHECK_LT(child_data_.header.last_block_len, kBlockSize);
646
647 // Write the bitmap.
648 int first_bit = child_offset_ >> 10;
649 int block_offset = child_offset_ & (kBlockSize - 1);
650 if (block_offset && (child_data_.header.last_block != first_bit ||
651 child_data_.header.last_block_len < block_offset)) {
652 // The first block is not completely filled; ignore it.
653 first_bit++;
654 }
655
656 int last_bit = (child_offset_ + result) >> 10;
657 block_offset = (child_offset_ + result) & (kBlockSize - 1);
658
659 // This condition will hit with the following criteria:
660 // 1. The first byte doesn't follow the last write.
661 // 2. The first byte is in the middle of a block.
662 // 3. The first byte and the last byte are in the same block.
663 if (first_bit > last_bit)
664 return;
665
666 if (block_offset && !child_map_.Get(last_bit)) {
667 // The last block is not completely filled; save it for later.
668 child_data_.header.last_block = last_bit;
669 child_data_.header.last_block_len = block_offset;
670 } else {
671 child_data_.header.last_block = -1;
672 }
673
674 child_map_.SetRange(first_bit, last_bit, true);
675 }
676
PartialBlockLength(int block_index) const677 int SparseControl::PartialBlockLength(int block_index) const {
678 if (block_index == child_data_.header.last_block)
679 return child_data_.header.last_block_len;
680
681 // This is really empty.
682 return 0;
683 }
684
InitChildData()685 void SparseControl::InitChildData() {
686 child_->SetEntryFlags(CHILD_ENTRY);
687
688 memset(&child_data_, 0, sizeof(child_data_));
689 child_data_.header = sparse_header_;
690
691 auto buf = base::MakeRefCounted<net::WrappedIOBuffer>(
692 base::as_chars(base::span_from_ref(child_data_)));
693
694 int rv = child_->WriteData(kSparseIndex, 0, buf.get(), sizeof(child_data_),
695 CompletionOnceCallback(), false);
696 if (rv != sizeof(child_data_))
697 DLOG(ERROR) << "Failed to save child data";
698 SetChildBit(true);
699 }
700
DoChildrenIO()701 void SparseControl::DoChildrenIO() {
702 while (DoChildIO()) continue;
703
704 // Range operations are finished synchronously, often without setting
705 // |finished_| to true.
706 if (kGetRangeOperation == operation_ && entry_->net_log().IsCapturing()) {
707 entry_->net_log().EndEvent(net::NetLogEventType::SPARSE_GET_RANGE, [&] {
708 return CreateNetLogGetAvailableRangeResultParams(
709 RangeResult(offset_, result_));
710 });
711 }
712 if (finished_) {
713 if (kGetRangeOperation != operation_ && entry_->net_log().IsCapturing()) {
714 entry_->net_log().EndEvent(GetSparseEventType(operation_));
715 }
716 if (pending_)
717 DoUserCallback(); // Don't touch this object after this point.
718 }
719 }
720
DoChildIO()721 bool SparseControl::DoChildIO() {
722 finished_ = true;
723 if (!buf_len_ || result_ < 0)
724 return false;
725
726 if (!OpenChild())
727 return false;
728
729 if (!VerifyRange())
730 return false;
731
732 // We have more work to do. Let's not trigger a callback to the caller.
733 finished_ = false;
734 CompletionOnceCallback callback;
735 if (!user_callback_.is_null()) {
736 callback = base::BindOnce(&SparseControl::OnChildIOCompleted,
737 base::Unretained(this));
738 }
739
740 int rv = 0;
741 switch (operation_) {
742 case kReadOperation:
743 if (entry_->net_log().IsCapturing()) {
744 NetLogSparseReadWrite(entry_->net_log(),
745 net::NetLogEventType::SPARSE_READ_CHILD_DATA,
746 net::NetLogEventPhase::BEGIN,
747 child_->net_log().source(), child_len_);
748 }
749 rv = child_->ReadDataImpl(kSparseData, child_offset_, user_buf_.get(),
750 child_len_, std::move(callback));
751 break;
752 case kWriteOperation:
753 if (entry_->net_log().IsCapturing()) {
754 NetLogSparseReadWrite(entry_->net_log(),
755 net::NetLogEventType::SPARSE_WRITE_CHILD_DATA,
756 net::NetLogEventPhase::BEGIN,
757 child_->net_log().source(), child_len_);
758 }
759 rv = child_->WriteDataImpl(kSparseData, child_offset_, user_buf_.get(),
760 child_len_, std::move(callback), false);
761 break;
762 case kGetRangeOperation:
763 rv = DoGetAvailableRange();
764 break;
765 default:
766 NOTREACHED();
767 }
768
769 if (rv == net::ERR_IO_PENDING) {
770 if (!pending_) {
771 pending_ = true;
772 // The child will protect himself against closing the entry while IO is in
773 // progress. However, this entry can still be closed, and that would not
774 // be a good thing for us, so we increase the refcount until we're
775 // finished doing sparse stuff.
776 entry_->AddRef(); // Balanced in DoUserCallback.
777 }
778 return false;
779 }
780 if (!rv)
781 return false;
782
783 DoChildIOCompleted(rv);
784 return true;
785 }
786
DoGetAvailableRange()787 int SparseControl::DoGetAvailableRange() {
788 if (!child_)
789 return child_len_; // Move on to the next child.
790
791 // Blockfile splits sparse files into multiple child entries, each responsible
792 // for managing 1MiB of address space. This method is responsible for
793 // implementing GetAvailableRange within a single child.
794 //
795 // Input:
796 // |child_offset_|, |child_len_|:
797 // describe range in current child's address space the client requested.
798 // |offset_| is equivalent to |child_offset_| but in global address space.
799 //
800 // For example if this were child [2] and the original call was for
801 // [0x200005, 0x200007) then |offset_| would be 0x200005, |child_offset_|
802 // would be 5, and |child_len| would be 2.
803 //
804 // Output:
805 // If nothing found:
806 // return |child_len_|
807 //
808 // If something found:
809 // |result_| gets the length of the available range.
810 // |offset_| gets the global address of beginning of the available range.
811 // |range_found_| get true to signal SparseControl::GetAvailableRange().
812 // return 0 to exit loop.
813 net::Interval<int> to_find(child_offset_, child_offset_ + child_len_);
814
815 // Within each child, valid portions are mostly tracked via the |child_map_|
816 // bitmap which marks which 1KiB 'blocks' have valid data. Scan the bitmap
817 // for the first contiguous range of set bits that's relevant to the range
818 // [child_offset_, child_offset_ + len)
819 int first_bit = child_offset_ >> 10;
820 int last_bit = (child_offset_ + child_len_ + kBlockSize - 1) >> 10;
821 int found = first_bit;
822 int bits_found = child_map_.FindBits(&found, last_bit, true);
823 net::Interval<int> bitmap_range(found * kBlockSize,
824 found * kBlockSize + bits_found * kBlockSize);
825
826 // Bits on the bitmap should only be set when the corresponding block was
827 // fully written (it's really being used). If a block is partially used, it
828 // has to start with valid data, the length of the valid data is saved in
829 // |header.last_block_len| and the block number saved in |header.last_block|.
830 // This is updated after every write; with |header.last_block| set to -1
831 // if no sub-KiB range is being tracked.
832 net::Interval<int> last_write_range;
833 if (child_data_.header.last_block >= 0) {
834 last_write_range =
835 net::Interval<int>(child_data_.header.last_block * kBlockSize,
836 child_data_.header.last_block * kBlockSize +
837 child_data_.header.last_block_len);
838 }
839
840 // Often |last_write_range| is contiguously after |bitmap_range|, but not
841 // always. See if they can be combined.
842 if (!last_write_range.Empty() && !bitmap_range.Empty() &&
843 bitmap_range.max() == last_write_range.min()) {
844 bitmap_range.SetMax(last_write_range.max());
845 last_write_range.Clear();
846 }
847
848 // Do any of them have anything relevant?
849 bitmap_range.IntersectWith(to_find);
850 last_write_range.IntersectWith(to_find);
851
852 // Now return the earliest non-empty interval, if any.
853 net::Interval<int> result_range = bitmap_range;
854 if (bitmap_range.Empty() || (!last_write_range.Empty() &&
855 last_write_range.min() < bitmap_range.min()))
856 result_range = last_write_range;
857
858 if (result_range.Empty()) {
859 // Nothing found, so we just skip over this child.
860 return child_len_;
861 }
862
863 // Package up our results.
864 range_found_ = true;
865 offset_ += result_range.min() - child_offset_;
866 result_ = result_range.max() - result_range.min();
867 return 0;
868 }
869
DoChildIOCompleted(int result)870 void SparseControl::DoChildIOCompleted(int result) {
871 LogChildOperationEnd(entry_->net_log(), operation_, result);
872 if (result < 0) {
873 // We fail the whole operation if we encounter an error.
874 result_ = result;
875 return;
876 }
877
878 UpdateRange(result);
879
880 result_ += result;
881 offset_ += result;
882 buf_len_ -= result;
883
884 // We'll be reusing the user provided buffer for the next chunk.
885 if (buf_len_ && user_buf_.get())
886 user_buf_->DidConsume(result);
887 }
888
OnChildIOCompleted(int result)889 void SparseControl::OnChildIOCompleted(int result) {
890 DCHECK_NE(net::ERR_IO_PENDING, result);
891 DoChildIOCompleted(result);
892
893 if (abort_) {
894 // We'll return the current result of the operation, which may be less than
895 // the bytes to read or write, but the user cancelled the operation.
896 abort_ = false;
897 if (entry_->net_log().IsCapturing()) {
898 entry_->net_log().AddEvent(net::NetLogEventType::CANCELLED);
899 entry_->net_log().EndEvent(GetSparseEventType(operation_));
900 }
901 // We have an indirect reference to this object for every callback so if
902 // there is only one callback, we may delete this object before reaching
903 // DoAbortCallbacks.
904 bool has_abort_callbacks = !abort_callbacks_.empty();
905 DoUserCallback();
906 if (has_abort_callbacks)
907 DoAbortCallbacks();
908 return;
909 }
910
911 // We are running a callback from the message loop. It's time to restart what
912 // we were doing before.
913 DoChildrenIO();
914 }
915
DoUserCallback()916 void SparseControl::DoUserCallback() {
917 DCHECK(!user_callback_.is_null());
918 CompletionOnceCallback cb = std::move(user_callback_);
919 user_buf_ = nullptr;
920 pending_ = false;
921 operation_ = kNoOperation;
922 int rv = result_;
923 entry_->Release(); // Don't touch object after this line.
924 std::move(cb).Run(rv);
925 }
926
DoAbortCallbacks()927 void SparseControl::DoAbortCallbacks() {
928 std::vector<CompletionOnceCallback> abort_callbacks;
929 abort_callbacks.swap(abort_callbacks_);
930
931 for (CompletionOnceCallback& callback : abort_callbacks) {
932 // Releasing all references to entry_ may result in the destruction of this
933 // object so we should not be touching it after the last Release().
934 entry_->Release();
935 std::move(callback).Run(net::OK);
936 }
937 }
938
939 } // namespace disk_cache
940