Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(153)

Side by Side Diff: storage/browser/blob/blob_memory_controller.cc

Issue 2055053003: [BlobAsync] Disk support for blob storage (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Fixed layout tests, cleaned up test visibility Created 4 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2016 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 "storage/browser/blob/blob_memory_controller.h"
6
7 #include <algorithm>
8
9 #include "base/callback.h"
10 #include "base/callback_helpers.h"
11 #include "base/files/file_util.h"
12 #include "base/location.h"
13 #include "base/memory/ptr_util.h"
14 #include "base/metrics/histogram_macros.h"
15 #include "base/numerics/safe_conversions.h"
16 #include "base/numerics/safe_math.h"
17 #include "base/single_thread_task_runner.h"
18 #include "base/single_thread_task_runner.h"
19 #include "base/strings/string_number_conversions.h"
20 #include "base/task_runner.h"
21 #include "base/task_runner_util.h"
22 #include "base/time/time.h"
23 #include "base/trace_event/trace_event.h"
24 #include "base/tuple.h"
25 #include "storage/browser/blob/blob_data_item.h"
26 #include "storage/browser/blob/shareable_blob_data_item.h"
27 #include "storage/browser/blob/shareable_file_reference.h"
28 #include "storage/common/data_element.h"
29
30 using base::File;
31 using base::FilePath;
32 using FileCreationInfo = storage::BlobMemoryController::FileCreationInfo;
33
34 namespace storage {
35 namespace {
36
37 bool CalculateBlobMemorySize(const std::vector<DataElement>& elements,
38 size_t* shortcut_bytes,
39 uint64_t* total_bytes) {
40 DCHECK(shortcut_bytes);
41 DCHECK(total_bytes);
42
43 base::CheckedNumeric<uint64_t> total_size_checked = 0;
44 base::CheckedNumeric<size_t> shortcut_size_checked = 0;
45 for (const auto& e : elements) {
46 if (e.type() == DataElement::TYPE_BYTES) {
47 total_size_checked += e.length();
48 shortcut_size_checked += e.length();
49 } else if (e.type() == DataElement::TYPE_BYTES_DESCRIPTION) {
50 total_size_checked += e.length();
51 } else {
52 continue;
53 }
54 if (!total_size_checked.IsValid() || !shortcut_size_checked.IsValid())
55 return false;
56 }
57 *shortcut_bytes = shortcut_size_checked.ValueOrDie();
58 *total_bytes = total_size_checked.ValueOrDie();
59 return true;
60 }
61
62 // Creates a file in the given directory w/ the given filename and size.
63 BlobMemoryController::FileCreationInfo CreateFile(
64 scoped_refptr<ShareableFileReference> file_reference,
65 size_t size_bytes) {
66 LOG(ERROR) << "creating file for renderer";
67 DCHECK_NE(0u, size_bytes);
68 BlobMemoryController::FileCreationInfo creation_info;
69
70 // Try to open our file.
71 File file(file_reference->path(),
72 File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE);
73 creation_info.file_reference = std::move(file_reference);
74 creation_info.error = file.error_details();
75 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.TransportFileCreate",
76 -creation_info.error, -File::FILE_ERROR_MAX);
77 if (creation_info.error != File::FILE_OK)
78 return creation_info;
79
80 // Grab the file info to get the "last modified" time and store the file.
81 File::Info file_info;
82 bool success = file.GetInfo(&file_info);
83 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.TransportFileInfoSuccess", success);
84 creation_info.error = success ? File::FILE_OK : File::FILE_ERROR_FAILED;
85 creation_info.last_modified = file_info.last_modified;
86 if (success)
87 creation_info.file = std::move(file);
88 return creation_info;
89 }
90
91 BlobMemoryController::FileCreationInfo WriteItemsToFile(
92 std::vector<scoped_refptr<ShareableBlobDataItem>>* items,
93 size_t total_size_bytes,
94 scoped_refptr<ShareableFileReference> file_reference) {
95 DCHECK_NE(0u, total_size_bytes);
96 LOG(ERROR) << "writing to file!";
97 UMA_HISTOGRAM_MEMORY_KB("Storage.Blob.PageFileSize", total_size_bytes / 1024);
98
99 // Create our file.
100 BlobMemoryController::FileCreationInfo creation_info;
101 File file(file_reference->path(),
102 File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE);
103 creation_info.file_reference = std::move(file_reference);
104 creation_info.error = file.error_details();
105 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PageFileCreate", -creation_info.error,
106 -File::FILE_ERROR_MAX);
107 if (creation_info.error != File::FILE_OK)
108 return creation_info;
109
110 // Write data.
111 file.SetLength(total_size_bytes);
112 int bytes_written = 0;
113 for (const auto& refptr : *items) {
114 const DataElement& element = refptr->item()->data_element();
115 DCHECK_EQ(DataElement::TYPE_BYTES, element.type());
116 size_t length = base::checked_cast<size_t>(element.length());
117 size_t bytes_left = length;
118 while (bytes_left > 0) {
119 bytes_written =
120 file.WriteAtCurrentPos(element.bytes() + (length - bytes_left),
121 base::saturated_cast<int>(bytes_left));
122 if (bytes_written < 0)
123 break;
124 DCHECK_LE(static_cast<size_t>(bytes_written), bytes_left);
125 bytes_left -= bytes_written;
126 }
127 if (bytes_written < 0)
128 break;
129 }
130 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.PageFileWriteSuccess", bytes_written > 0);
131
132 // Grab our modification time and create our SharedFileReference to manage the
133 // lifetime of the file.
134 File::Info info;
135 bool success = file.GetInfo(&info);
136 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.PageFileInfoSuccess", success);
137 creation_info.error =
138 bytes_written < 0 || !success ? File::FILE_ERROR_FAILED : File::FILE_OK;
139 creation_info.last_modified = info.last_modified;
140 return creation_info;
141 }
142
143 } // namespace
144
145 BlobMemoryController::FileCreationInfo::FileCreationInfo() {}
146
147 BlobMemoryController::FileCreationInfo::~FileCreationInfo() {}
148
149 FileCreationInfo::FileCreationInfo(FileCreationInfo&&) = default;
150 FileCreationInfo& FileCreationInfo::operator=(FileCreationInfo&&) = default;
151
152 BlobMemoryController::BlobMemoryController()
153 : recent_item_cache_(
154 base::MRUCache<uint64_t, ShareableBlobDataItem*>::NO_AUTO_EVICT),
155 ptr_factory_(this) {}
156
157 BlobMemoryController::~BlobMemoryController() {}
158
159 void BlobMemoryController::EnableDisk(
160 const base::FilePath& storage_directory,
161 scoped_refptr<base::TaskRunner> file_runner) {
162 LOG(ERROR) << "enbling disk";
163 file_runner_ = std::move(file_runner);
164 blob_storage_dir_ = storage_directory;
165 disk_enabled_ = true;
166 }
167
168 void BlobMemoryController::DisableDisk() {
169 disk_enabled_ = false;
170 blob_memory_used_ += in_flight_memory_used_;
171 in_flight_memory_used_ = 0;
172 for (const auto& size_callback_pair : blobs_waiting_for_paging_)
173 size_callback_pair.second.Run(false);
174 pending_pagings_ = 0;
175 blobs_waiting_for_paging_.clear();
176 blobs_waiting_for_paging_size_ = 0;
177 recent_item_cache_.Clear();
178 recent_item_cache_bytes_ = 0;
179 RecordTracingCounters();
180 }
181
182 bool BlobMemoryController::DecideBlobTransportationMemoryStrategy(
183 const std::vector<DataElement>& descriptions,
184 uint64_t* total_bytes,
185 BlobMemoryController::MemoryStrategyResult* result) const {
186 DCHECK(total_bytes);
187 DCHECK(result);
188
189 // Step 1: Get the sizes.
190 size_t shortcut_memory_size_bytes;
191 uint64_t total_memory_size_bytes;
192 if (!CalculateBlobMemorySize(descriptions, &shortcut_memory_size_bytes,
193 &total_memory_size_bytes)) {
194 return false;
195 }
196 *total_bytes = total_memory_size_bytes;
197
198 // Step 2: Handle case where we have no memory to transport.
199 if (total_memory_size_bytes == 0) {
200 *result = MemoryStrategyResult::NONE_NEEDED;
201 return true;
202 }
203
204 // Step 3: Check if we have enough memory to store the blob.
205 if (total_memory_size_bytes >
206 GetAvailableMemoryForBlobs() + GetAvailableDiskSpaceForBlobs()) {
207 *result = MemoryStrategyResult::TOO_LARGE;
208 return true;
209 }
210
211 // From here on, we know we can fit the blob in memory or on disk.
212 // Step 4: Decide if we're using the shortcut method.
213 if (shortcut_memory_size_bytes == total_memory_size_bytes &&
214 blobs_waiting_for_paging_.empty() &&
215 shortcut_memory_size_bytes < GetAvailableMemoryForBlobs()) {
216 *result = MemoryStrategyResult::NONE_NEEDED;
217 return true;
218 }
219
220 // Step 5: Decide if we're going straight to disk.
221 if (disk_enabled_ && (total_memory_size_bytes > max_blob_in_memory_size_)) {
222 *result = MemoryStrategyResult::FILE;
223 return true;
224 }
225 // From here on, we know the blob's size is less than:
226 // * max_blob_in_memory_size_ if enable_disk_ is true
227 // * max_blob_memory_space_ if enable_disk_ is false
228 // So we know we're < max(size_t).
229 // Step 6: Decide if we're using shared memory.
230 if (total_memory_size_bytes > max_ipc_memory_size_) {
231 *result = MemoryStrategyResult::SHARED_MEMORY;
232 return true;
233 }
234 // Step 7: We can fit in IPC.
235 *result = MemoryStrategyResult::IPC;
236 return true;
237 }
238
239 void BlobMemoryController::CreateTemporaryFile(
240 uint64_t size_bytes,
241 const base::Callback<void(FileCreationInfo)>& file_callback) {
242 if (!disk_enabled_) {
243 BlobMemoryController::FileCreationInfo creation_info;
244 file_callback.Run(std::move(creation_info));
245 return;
246 }
247
248 disk_used_ += size_bytes;
249 std::string file_name = base::Uint64ToString(current_file_num_++);
250 scoped_refptr<ShareableFileReference> file_ref =
251 ShareableFileReference::GetOrCreate(
252 blob_storage_dir_.Append(file_name),
253 ShareableFileReference::DELETE_ON_FINAL_RELEASE, file_runner_.get());
254 base::PostTaskAndReplyWithResult(
255 file_runner_.get(), FROM_HERE,
256 base::Bind(&CreateFile, std::move(file_ref), size_bytes),
257 base::Bind(&BlobMemoryController::OnCreateFile, ptr_factory_.GetWeakPtr(),
258 size_bytes, file_callback));
259
260 RecordTracingCounters();
261 }
262
263 void BlobMemoryController::FreeMemory(size_t memory_size_bytes) {
264 DCHECK_GE(blob_memory_used_, memory_size_bytes);
265 blob_memory_used_ -= memory_size_bytes;
266 if (memory_size_bytes != 0) {
267 LOG(ERROR) << "Freeing memory " << memory_size_bytes;
268 MaybeScheduleWaitingBlobs();
269 }
270 }
271
272 bool BlobMemoryController::CanFitInSystem(uint64_t size) const {
273 return size < GetAvailableMemoryForBlobs() + GetAvailableDiskSpaceForBlobs();
274 }
275
276 base::Optional<BlobMemoryController::PendingConstructionEntry>
277 BlobMemoryController::NotifyWhenMemoryCanPopulated(
278 size_t memory_size,
279 const base::Callback<void(bool)>& can_request_callback) {
280 DCHECK(memory_size <=
281 GetAvailableMemoryForBlobs() + GetAvailableDiskSpaceForBlobs());
282
283 if (!disk_enabled_) {
284 LOG(ERROR) << "Yes, " << memory_size << " can fit in memory now.";
285 blob_memory_used_ += memory_size;
286 return base::nullopt;
287 }
288
289 // If we're currently waiting for blobs to page already, then we add
290 // ourselves to the end of the queue. Once paging is complete, we'll schedule
291 // more paging for any more pending blobs.
292 if (!blobs_waiting_for_paging_.empty()) {
293 LOG(ERROR) << "putting memory request " << memory_size << " in queue.";
294 blobs_waiting_for_paging_.push_back(
295 std::make_pair(memory_size, can_request_callback));
296 blobs_waiting_for_paging_size_ += memory_size;
297 base::Optional<BlobMemoryController::PendingConstructionEntry> entry =
298 --blobs_waiting_for_paging_.end();
299 return entry;
300 }
301
302 // Store right away if we can.
303 if (memory_size <= GetAvailableMemoryForBlobs()) {
304 // If we're past our blob memory limit, then schedule our paging.
305 LOG(ERROR) << "Yes, " << memory_size << " can fit in memory now.";
306 blob_memory_used_ += memory_size;
307 MaybeSchedulePagingUntilSystemHealthy();
308 return base::nullopt;
309 }
310
311 // This means we're too big for memory.
312 LOG(ERROR) << "waiting until " << memory_size << " can fit.";
313 DCHECK(blobs_waiting_for_paging_.empty());
314 DCHECK_EQ(0u, blobs_waiting_for_paging_size_);
315 blobs_waiting_for_paging_.push_back(
316 std::make_pair(memory_size, can_request_callback));
317 blobs_waiting_for_paging_size_ = memory_size;
318 base::Optional<BlobMemoryController::PendingConstructionEntry> entry =
319 --blobs_waiting_for_paging_.end();
320 LOG(ERROR) << "Scheduling paging on first item too big";
321 MaybeSchedulePagingUntilSystemHealthy();
322 return entry;
323 }
324
325 void BlobMemoryController::RemovePendingConstructionEntry(
326 const BlobMemoryController::PendingConstructionEntry& entry) {
327 if (entry == blobs_waiting_for_paging_.end())
328 return;
329 const std::pair<size_t, base::Callback<void(bool)>> pair = *entry;
330 blobs_waiting_for_paging_size_ -= pair.first;
331 blobs_waiting_for_paging_.erase(entry);
332 }
333
334 void BlobMemoryController::UpdateBlobItemInRecents(
335 ShareableBlobDataItem* item) {
336 auto iterator = recent_item_cache_.Get(item->item_id());
337 if (iterator == recent_item_cache_.end()) {
338 DCHECK_EQ(DataElement::TYPE_BYTES, item->item()->type());
339 recent_item_cache_bytes_ += static_cast<size_t>(item->item()->length());
340 recent_item_cache_.Put(item->item_id(), item);
341 MaybeSchedulePagingUntilSystemHealthy();
342 }
343 }
344
345 void BlobMemoryController::RemoveBlobItemInRecents(
346 const ShareableBlobDataItem& item) {
347 auto iterator = recent_item_cache_.Get(item.item_id());
348 if (iterator != recent_item_cache_.end()) {
349 size_t size = static_cast<size_t>(item.item()->length());
350 DCHECK_GE(recent_item_cache_bytes_, size);
351 recent_item_cache_bytes_ -= size;
352 recent_item_cache_.Erase(iterator);
353 }
354 }
355
356 void BlobMemoryController::OnCreateFile(
357 uint64_t file_size,
358 const base::Callback<void(FileCreationInfo)>& file_callback,
359 FileCreationInfo result) {
360 if (result.error == File::FILE_OK) {
361 result.file_reference->AddFinalReleaseCallback(
362 base::Bind(&BlobMemoryController::OnBlobFileDelete,
363 ptr_factory_.GetWeakPtr(), file_size));
364 } else {
365 disk_used_ -= file_size;
366 }
367 LOG(ERROR) << "Created file!";
368 file_callback.Run(std::move(result));
369 }
370
371 void BlobMemoryController::MaybeScheduleWaitingBlobs() {
372 size_t space_available = max_blob_in_memory_size_ - blob_memory_used_;
373 while (!blobs_waiting_for_paging_.empty() &&
374 max_blob_in_memory_size_ - blob_memory_used_ >=
375 blobs_waiting_for_paging_.front().first) {
376 auto size_callback_pair = blobs_waiting_for_paging_.front();
377 blobs_waiting_for_paging_.pop_front();
378 space_available -= size_callback_pair.first;
379 blobs_waiting_for_paging_size_ -= size_callback_pair.first;
380 blob_memory_used_ += size_callback_pair.first;
381 size_callback_pair.second.Run(true);
382 }
383 RecordTracingCounters();
384 }
385
386 void BlobMemoryController::MaybeSchedulePagingUntilSystemHealthy() {
387 // Don't do paging when others are happening, as we don't change our
388 // blobs_waiting_for_paging_size_ value until after the paging files have
389 // been writen.
390 if (pending_pagings_ != 0 || !disk_enabled_)
391 return;
392
393 // We try to page items to disk until our current system size + requested
394 // memory is below our size limit.
395 while (blobs_waiting_for_paging_size_ + blob_memory_used_ >
396 max_blob_in_memory_size_) {
397 if (!HasEnoughMemoryToPage())
398 break;
399 DCHECK_LT(min_page_file_size_, static_cast<uint64_t>(blob_memory_used_));
400 size_t total_items_size = 0;
401 std::unique_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>>
402 items_for_disk(new std::vector<scoped_refptr<ShareableBlobDataItem>>());
403 // Collect our items.
404 while (total_items_size < min_page_file_size_ &&
405 !recent_item_cache_.empty()) {
406 auto iterator = --recent_item_cache_.end();
407 ShareableBlobDataItem* item = iterator->second;
408 DCHECK(item);
409 recent_item_cache_.Erase(iterator);
410 recent_item_cache_bytes_ -= static_cast<size_t>(item->item()->length());
411 size_t size = base::checked_cast<size_t>(item->item()->length());
412 total_items_size += size;
413 items_for_disk->push_back(make_scoped_refptr(item));
414 }
415 if (total_items_size == 0)
416 break;
417
418 // Update our bookkeeping.
419 pending_pagings_++;
420 disk_used_ += total_items_size;
421 DCHECK_GE(blob_memory_used_, total_items_size);
422 LOG(ERROR) << "saving " << total_items_size << " to disk.";
423 blob_memory_used_ -= total_items_size;
424 in_flight_memory_used_ += total_items_size;
425 std::string file_name = base::Uint64ToString(current_file_num_++);
426 // Create our file reference.
427 scoped_refptr<ShareableFileReference> file_ref =
428 ShareableFileReference::GetOrCreate(
429 blob_storage_dir_.Append(file_name),
430 ShareableFileReference::DELETE_ON_FINAL_RELEASE,
431 file_runner_.get());
432 // Add the release callback so we decrement our disk usage on file deletion.
433 file_ref->AddFinalReleaseCallback(
434 base::Bind(&BlobMemoryController::OnBlobFileDelete,
435 ptr_factory_.GetWeakPtr(), total_items_size));
436 // Post the file writing task.
437 base::PostTaskAndReplyWithResult(
438 file_runner_.get(), FROM_HERE,
439 base::Bind(&WriteItemsToFile, items_for_disk.get(), total_items_size,
440 std::move(file_ref)),
441 base::Bind(&BlobMemoryController::OnPagingComplete,
442 ptr_factory_.GetWeakPtr(), base::Passed(&items_for_disk),
443 total_items_size));
444 }
445 RecordTracingCounters();
446 }
447
448 void BlobMemoryController::OnPagingComplete(
449 std::unique_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>> items,
450 size_t total_items_size,
451 FileCreationInfo result) {
452 if (!disk_enabled_)
453 return;
454 if (result.error != File::FILE_OK) {
455 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingError", -result.error,
456 -File::FILE_ERROR_MAX);
457 disk_used_ -= total_items_size;
458 DisableDisk();
459 return;
460 }
461 DCHECK_LT(0u, pending_pagings_);
462 pending_pagings_--;
463
464 // Switch from the data backing item to a new file backing item.
465 uint64_t offset = 0;
466 for (const scoped_refptr<ShareableBlobDataItem>& shareable_item :
467 *items.get()) {
468 scoped_refptr<BlobDataItem> new_item(new BlobDataItem(
469 base::WrapUnique(new DataElement()), result.file_reference));
470 new_item->data_element_ptr()->SetToFilePathRange(
471 result.file_reference->path(), offset, shareable_item->item()->length(),
472 result.last_modified);
473 shareable_item->item_ = new_item;
474 offset += shareable_item->item()->length();
475 }
476 in_flight_memory_used_ -= total_items_size;
477
478 // We want callback on blobs up to the amount we've freed.
479 MaybeScheduleWaitingBlobs();
480
481 // If we still have more blobs waiting and we're not waiting on more paging
482 // operations, schedule more.
483 MaybeSchedulePagingUntilSystemHealthy();
484
485 RecordTracingCounters();
486 }
487
488 void BlobMemoryController::RecordTracingCounters() {
489 TRACE_COUNTER2("Blob", "MemoryUsage", "RegularStorage", blob_memory_used_,
490 "InFlightToDisk", in_flight_memory_used_);
491 TRACE_COUNTER1("Blob", "DiskUsage", disk_used_);
492 TRACE_COUNTER1("Blob", "TranfersPendingOnDisk",
493 blobs_waiting_for_paging_.size());
494 TRACE_COUNTER1("Blob", "TranfersBytesPendingOnDisk",
495 blobs_waiting_for_paging_size_);
496 }
497
498 size_t BlobMemoryController::GetAvailableMemoryForBlobs() const {
499 // If disk is enabled, then we include |in_flight_memory_used_|. Otherwise we
500 // combine the in memory and in flight quotas.
501 if (disk_enabled_) {
502 if (max_blob_in_memory_size_ + in_flight_space_ < memory_usage())
503 return 0;
504 return max_blob_in_memory_size_ + in_flight_space_ - memory_usage();
505 }
506 if (max_blob_in_memory_size_ + in_flight_space_ < memory_usage())
507 return 0;
508 return max_blob_in_memory_size_ + in_flight_space_ - memory_usage();
509 }
510
511 uint64_t BlobMemoryController::GetAvailableDiskSpaceForBlobs() const {
512 return disk_enabled_ ? max_blob_disk_space_ - disk_used_ : 0;
513 }
514
515 void BlobMemoryController::OnBlobFileDelete(uint64_t size,
516 const base::FilePath& path) {
517 DCHECK_LE(size, disk_used_);
518 LOG(ERROR) << "File deleted " << size;
519 disk_used_ -= size;
520 }
521
522 } // namespace storage
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698