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

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: rebase 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_(RecentItemsCache::NO_AUTO_EVICT), ptr_factory_(this) {}
154
155 BlobMemoryController::~BlobMemoryController() {}
156
157 void BlobMemoryController::EnableDisk(
158 const base::FilePath& storage_directory,
159 scoped_refptr<base::TaskRunner> file_runner) {
160 LOG(ERROR) << "enbling disk";
161 file_runner_ = std::move(file_runner);
162 blob_storage_dir_ = storage_directory;
163 enable_disk_ = true;
164 }
165
166 void BlobMemoryController::DisableDisk() {
167 enable_disk_ = false;
168 blob_memory_used_ += in_flight_memory_used_;
169 in_flight_memory_used_ = 0;
170 for (const auto& size_callback_pair : blobs_waiting_for_paging_) {
171 size_callback_pair.second.Run(false);
172 }
173 pending_pagings_ = 0;
174 blobs_waiting_for_paging_.clear();
175 blobs_waiting_for_paging_size_ = 0;
176 recent_item_cache_.Clear();
177 recent_item_cache_bytes_ = 0;
178 RecordTracingCounters();
179 }
180
181 bool BlobMemoryController::DecideBlobTransportationMemoryStrategy(
182 const std::vector<DataElement>& descriptions,
183 uint64_t* total_bytes,
184 BlobMemoryController::MemoryStrategyResult* result) const {
185 DCHECK(total_bytes);
186 DCHECK(result);
187
188 // Step 1: Get the sizes.
189 size_t shortcut_memory_size_bytes;
190 uint64_t total_memory_size_bytes;
191 if (!CalculateBlobMemorySize(descriptions, &shortcut_memory_size_bytes,
192 &total_memory_size_bytes)) {
193 return false;
194 }
195 *total_bytes = total_memory_size_bytes;
196
197 // Step 2: Handle case where we have no memory to transport.
198 if (total_memory_size_bytes == 0) {
199 *result = MemoryStrategyResult::NONE_NEEDED;
200 return true;
201 }
202
203 // Step 3: Check if we have enough memory to store the blob.
204 if (total_memory_size_bytes > GetAvailableMemoryForBlobs() &&
205 total_memory_size_bytes > GetAvailableDiskSpaceForBlobs()) {
206 *result = MemoryStrategyResult::TOO_LARGE;
207 return true;
208 }
209
210 // From here on, we know we can fit the blob in memory or on disk.
211 // Step 4: Decide if we're using the shortcut method.
212 if (shortcut_memory_size_bytes == total_memory_size_bytes &&
213 blobs_waiting_for_paging_.empty() &&
214 shortcut_memory_size_bytes < GetAvailableMemoryForBlobs()) {
215 *result = MemoryStrategyResult::NONE_NEEDED;
216 return true;
217 }
218
219 // Step 5: Decide if we're going straight to disk.
220 if (enable_disk_ && (total_memory_size_bytes > max_blob_in_memory_size_)) {
221 *result = MemoryStrategyResult::FILE;
222 return true;
223 }
224 // From here on, we know the blob's size is less than:
225 // * max_blob_in_memory_size_ if enable_disk_ is true
226 // * max_blob_memory_space_ if enable_disk_ is false
227 // So we know we're < max(size_t).
228 // Step 6: Decide if we're using shared memory.
229 if (total_memory_size_bytes > max_ipc_memory_size_) {
230 *result = MemoryStrategyResult::SHARED_MEMORY;
231 return true;
232 }
233 // Step 7: We can fit in IPC.
234 *result = MemoryStrategyResult::IPC;
235 return true;
236 }
237
238 void BlobMemoryController::CreateTemporaryFileForRenderer(
239 uint64_t size_bytes,
240 const base::Callback<void(FileCreationInfo)>& file_callback) {
241 if (!enable_disk_) {
242 BlobMemoryController::FileCreationInfo creation_info;
243 file_callback.Run(std::move(creation_info));
244 return;
245 }
246
247 disk_used_ += size_bytes;
248 std::string file_name = base::Uint64ToString(current_file_num_++);
249 scoped_refptr<ShareableFileReference> file_ref =
250 ShareableFileReference::GetOrCreate(
251 blob_storage_dir_.Append(file_name),
252 ShareableFileReference::DELETE_ON_FINAL_RELEASE, file_runner_.get());
253 base::PostTaskAndReplyWithResult(
254 file_runner_.get(), FROM_HERE,
255 base::Bind(&CreateFile, std::move(file_ref), size_bytes),
256 base::Bind(&BlobMemoryController::OnCreateFile, ptr_factory_.GetWeakPtr(),
257 size_bytes, file_callback));
258
259 RecordTracingCounters();
260 }
261
262 void BlobMemoryController::FreeMemory(size_t memory_size_bytes) {
263 DCHECK_GE(blob_memory_used_, memory_size_bytes);
264 blob_memory_used_ -= memory_size_bytes;
265 if (memory_size_bytes != 0) {
266 LOG(ERROR) << "Freeing memory " << memory_size_bytes;
267 MaybeScheduleWaitingBlobs();
268 }
269 }
270
271 bool BlobMemoryController::CanFitInSystem(uint64_t size) const {
272 return size < GetAvailableMemoryForBlobs() + GetAvailableDiskSpaceForBlobs();
273 }
274
275 base::Optional<BlobMemoryController::PendingConstructionEntry>
276 BlobMemoryController::NotifyWhenMemoryCanPopulated(
277 size_t memory_size,
278 const base::Callback<void(bool)>& can_request_callback) {
279 DCHECK(memory_size <=
280 GetAvailableMemoryForBlobs() + GetAvailableDiskSpaceForBlobs());
281
282 if (!enable_disk_) {
283 LOG(ERROR) << "Yes, " << memory_size << " can fit in memory now.";
284 blob_memory_used_ += memory_size;
285 return base::nullopt;
286 }
287
288 // If we're currently waiting for blobs to page already, then we add
289 // ourselves to the end of the queue. Once paging is complete, we'll schedule
290 // more paging for any more pending blobs.
291 if (!blobs_waiting_for_paging_.empty()) {
292 LOG(ERROR) << "putting memory request " << memory_size << " in queue.";
293 blobs_waiting_for_paging_.push_back(
294 std::make_pair(memory_size, can_request_callback));
295 blobs_waiting_for_paging_size_ += memory_size;
296 base::Optional<BlobMemoryController::PendingConstructionEntry> entry =
297 --blobs_waiting_for_paging_.end();
298 return entry;
299 }
300
301 // Store right away if we can.
302 if (memory_size <= GetAvailableMemoryForBlobs()) {
303 // If we're past our blob memory limit, then schedule our paging.
304 LOG(ERROR) << "Yes, " << memory_size << " can fit in memory now.";
305 blob_memory_used_ += memory_size;
306 MaybeSchedulePagingUntilSystemHealthy();
307 return base::nullopt;
308 }
309
310 // This means we're too big for memory.
311 LOG(ERROR) << "waiting until " << memory_size << " can fit.";
312 DCHECK(blobs_waiting_for_paging_.empty());
313 DCHECK_EQ(0u, blobs_waiting_for_paging_size_);
314 blobs_waiting_for_paging_.push_back(
315 std::make_pair(memory_size, can_request_callback));
316 blobs_waiting_for_paging_size_ = memory_size;
317 base::Optional<BlobMemoryController::PendingConstructionEntry> entry =
318 --blobs_waiting_for_paging_.end();
319 LOG(ERROR) << "Scheduling paging on first item too big";
320 MaybeSchedulePagingUntilSystemHealthy();
321 return entry;
322 }
323
324 void BlobMemoryController::RemovePendingConstructionEntry(
325 const BlobMemoryController::PendingConstructionEntry& entry) {
326 const std::pair<size_t, base::Callback<void(bool)>> pair = *entry;
327 blobs_waiting_for_paging_size_ -= pair.first;
328 blobs_waiting_for_paging_.erase(entry);
329 }
330
331 void BlobMemoryController::UpdateBlobItemInRecents(
332 ShareableBlobDataItem* item) {
333 auto iterator = recent_item_cache_.Get(item->item_id());
334 if (iterator == recent_item_cache_.end()) {
335 DCHECK_EQ(DataElement::TYPE_BYTES, item->item()->type());
336 recent_item_cache_bytes_ += static_cast<size_t>(item->item()->length());
337 recent_item_cache_.Put(item->item_id(), item);
338 MaybeSchedulePagingUntilSystemHealthy();
339 }
340 }
341
342 void BlobMemoryController::RemoveBlobItemInRecents(
343 const ShareableBlobDataItem& item) {
344 auto iterator = recent_item_cache_.Get(item.item_id());
345 if (iterator != recent_item_cache_.end()) {
346 size_t size = static_cast<size_t>(item.item()->length());
347 DCHECK_GE(recent_item_cache_bytes_, size);
348 recent_item_cache_bytes_ -= size;
349 recent_item_cache_.Erase(iterator);
350 }
351 }
352
353 void BlobMemoryController::OnCreateFile(
354 uint64_t file_size,
355 const base::Callback<void(FileCreationInfo)>& file_callback,
356 FileCreationInfo result) {
357 if (result.error == File::FILE_OK) {
358 result.file_reference->AddFinalReleaseCallback(
359 base::Bind(&BlobMemoryController::OnBlobFileDelete,
360 ptr_factory_.GetWeakPtr(), file_size));
361 } else {
362 disk_used_ -= file_size;
363 }
364 LOG(ERROR) << "Created file!";
365 file_callback.Run(std::move(result));
366 }
367
368 void BlobMemoryController::MaybeScheduleWaitingBlobs() {
369 size_t space_available = max_blob_in_memory_size_ - blob_memory_used_;
370 while (!blobs_waiting_for_paging_.empty() &&
371 max_blob_in_memory_size_ - blob_memory_used_ >=
372 blobs_waiting_for_paging_.front().first) {
373 auto size_callback_pair = blobs_waiting_for_paging_.front();
374 blobs_waiting_for_paging_.pop_front();
375 space_available -= size_callback_pair.first;
376 blobs_waiting_for_paging_size_ -= size_callback_pair.first;
377 blob_memory_used_ += size_callback_pair.first;
378 size_callback_pair.second.Run(true);
379 }
380 RecordTracingCounters();
381 }
382
383 void BlobMemoryController::MaybeSchedulePagingUntilSystemHealthy() {
384 // Don't do paging when others are happening, as we don't change our
385 // blobs_waiting_for_paging_size_ value until after the paging files have
386 // been writen.
387 if (pending_pagings_ != 0 || !enable_disk_)
388 return;
389
390 // We try to page items to disk until our current system size + requested
391 // memory is below our size limit.
392 while (blobs_waiting_for_paging_size_ + blob_memory_used_ >
393 max_blob_in_memory_size_) {
394 if (!HasEnoughMemoryToPage()) {
395 break;
396 }
397 DCHECK_LT(min_page_file_size_, static_cast<uint64_t>(blob_memory_used_));
398 size_t total_items_size = 0;
399 std::unique_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>>
400 items_for_disk(new std::vector<scoped_refptr<ShareableBlobDataItem>>());
401 // Collect our items.
402 while (total_items_size < min_page_file_size_ &&
403 !recent_item_cache_.empty()) {
404 auto iterator = --recent_item_cache_.end();
405 ShareableBlobDataItem* item = iterator->second;
406 DCHECK(item);
407 recent_item_cache_.Erase(iterator);
408 recent_item_cache_bytes_ -= static_cast<size_t>(item->item()->length());
409 size_t size = base::checked_cast<size_t>(item->item()->length());
410 total_items_size += size;
411 items_for_disk->push_back(make_scoped_refptr(item));
412 }
413 if (total_items_size == 0)
414 break;
415
416 // Update our bookkeeping.
417 pending_pagings_++;
418 disk_used_ += total_items_size;
419 DCHECK_GE(blob_memory_used_, total_items_size);
420 LOG(ERROR) << "saving " << total_items_size << " to disk.";
421 blob_memory_used_ -= total_items_size;
422 in_flight_memory_used_ += total_items_size;
423 std::string file_name = base::Uint64ToString(current_file_num_++);
424 // Create our file reference.
425 scoped_refptr<ShareableFileReference> file_ref =
426 ShareableFileReference::GetOrCreate(
427 blob_storage_dir_.Append(file_name),
428 ShareableFileReference::DELETE_ON_FINAL_RELEASE,
429 file_runner_.get());
430 // Add the release callback so we decrement our disk usage on file deletion.
431 file_ref->AddFinalReleaseCallback(
432 base::Bind(&BlobMemoryController::OnBlobFileDelete,
433 ptr_factory_.GetWeakPtr(), total_items_size));
434 // Post the file writing task.
435 base::PostTaskAndReplyWithResult(
436 file_runner_.get(), FROM_HERE,
437 base::Bind(&WriteItemsToFile, items_for_disk.get(), total_items_size,
438 std::move(file_ref)),
439 base::Bind(&BlobMemoryController::OnPagingComplete,
440 ptr_factory_.GetWeakPtr(), base::Passed(&items_for_disk),
441 total_items_size));
442 }
443 RecordTracingCounters();
444 }
445
446 void BlobMemoryController::OnPagingComplete(
447 std::unique_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>> items,
448 size_t total_items_size,
449 FileCreationInfo result) {
450 if (!enable_disk_)
451 return;
452 if (result.error != File::FILE_OK) {
453 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingError", -result.error,
454 -File::FILE_ERROR_MAX);
455 disk_used_ -= total_items_size;
456 DisableDisk();
457 return;
458 }
459 DCHECK_LT(0u, pending_pagings_);
460 pending_pagings_--;
461
462 // Switch from the data backing item to a new file backing item.
463 uint64_t offset = 0;
464 for (const scoped_refptr<ShareableBlobDataItem>& shareable_item :
465 *items.get()) {
466 scoped_refptr<BlobDataItem> new_item(new BlobDataItem(
467 base::WrapUnique(new DataElement()), result.file_reference));
468 new_item->data_element_ptr()->SetToFilePathRange(
469 result.file_reference->path(), offset, shareable_item->item()->length(),
470 result.last_modified);
471 shareable_item->item_ = new_item;
472 offset += shareable_item->item()->length();
473 }
474 in_flight_memory_used_ -= total_items_size;
475
476 // We want callback on blobs up to the amount we've freed.
477 MaybeScheduleWaitingBlobs();
478
479 // If we still have more blobs waiting and we're not waiting on more paging
480 // operations, schedule more.
481 MaybeSchedulePagingUntilSystemHealthy();
482
483 RecordTracingCounters();
484 }
485
486 void BlobMemoryController::RecordTracingCounters() {
487 TRACE_COUNTER2("Blob", "MemoryUsage", "RegularStorage", blob_memory_used_,
488 "InFlightToDisk", in_flight_memory_used_);
489 TRACE_COUNTER1("Blob", "DiskUsage", disk_used_);
490 TRACE_COUNTER1("Blob", "TranfersPendingOnDisk",
491 blobs_waiting_for_paging_.size());
492 TRACE_COUNTER1("Blob", "TranfersBytesPendingOnDisk",
493 blobs_waiting_for_paging_size_);
494 }
495
496 size_t BlobMemoryController::GetAvailableMemoryForBlobs() const {
497 if (blob_memory_used_ >= max_blob_in_memory_size_)
498 return 0;
499 if (enable_disk_) {
500 if (max_blob_in_memory_size_ + in_flight_space_ <
501 blob_memory_used_ + in_flight_memory_used_) {
502 return 0;
503 }
504 return max_blob_in_memory_size_ + in_flight_space_ - blob_memory_used_ -
505 in_flight_memory_used_;
506 }
507 return max_blob_memory_space_ - blob_memory_used_;
508 }
509
510 uint64_t BlobMemoryController::GetAvailableDiskSpaceForBlobs() const {
511 return enable_disk_ ? max_blob_disk_space_ - disk_used_ : 0;
512 }
513
514 void BlobMemoryController::OnBlobFileDelete(uint64_t size,
515 const base::FilePath& path) {
516 DCHECK_LE(size, disk_used_);
517 LOG(ERROR) << "File deleted " << size;
518 disk_used_ -= size;
519 }
520
521 } // namespace storage
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698