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

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: comments 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/threading/sequenced_worker_pool.h"
23 #include "base/time/time.h"
24 #include "base/trace_event/trace_event.h"
25 #include "base/tuple.h"
26 #include "storage/browser/blob/blob_data_item.h"
27 #include "storage/browser/blob/shareable_blob_data_item.h"
28 #include "storage/browser/blob/shareable_file_reference.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 -= static_cast<size_t>(bytes_written);
Marijn Kruisselbrink 2016/07/12 21:33:06 I don't think you need the static_cast here.
dmurph 2016/07/14 01:04:31 Done.
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::SequencedWorkerPool> file_worker_pool) {
160 LOG(ERROR) << "enbling disk";
161 file_worker_pool_ = std::move(file_worker_pool);
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 RecordTracingCounters();
178 }
179
180 bool BlobMemoryController::DecideBlobTransportationMemoryStrategy(
181 const std::vector<DataElement>& descriptions,
182 uint64_t* total_bytes,
183 BlobMemoryController::MemoryStrategyResult* result) const {
184 DCHECK(total_bytes);
185 DCHECK(result);
186
187 // Step 1: Get the sizes.
188 size_t shortcut_memory_size_bytes;
189 uint64_t total_memory_size_bytes;
190 if (!CalculateBlobMemorySize(descriptions, &shortcut_memory_size_bytes,
191 &total_memory_size_bytes)) {
192 return false;
193 }
194 *total_bytes = total_memory_size_bytes;
195
196 // Step 2: Handle case where we have no memory to transport.
197 if (total_memory_size_bytes == 0) {
198 *result = MemoryStrategyResult::NONE_NEEDED;
199 return true;
200 }
201
202 // Step 3: Check if we have enough memory to store the blob.
203 if (total_memory_size_bytes > GetAvailableMemoryForBlobs() &&
204 total_memory_size_bytes > GetAvailableDiskSpaceForBlobs()) {
205 *result = MemoryStrategyResult::TOO_LARGE;
206 return true;
207 }
208
209 // From here on, we know we can fit the blob in memory or on disk.
210 // Step 4: Decide if we're using the shortcut method.
211 if (shortcut_memory_size_bytes == total_memory_size_bytes &&
212 blobs_waiting_for_paging_.empty() &&
213 shortcut_memory_size_bytes < GetAvailableMemoryForBlobs()) {
214 *result = MemoryStrategyResult::SHORTCUT;
215 return true;
216 }
217
218 // Step 5: Decide if we're going straight to disk.
219 if (enable_disk_ && (total_memory_size_bytes > max_blob_in_memory_size_)) {
220 *result = MemoryStrategyResult::FILE;
221 return true;
222 }
223 // From here on, we know the blob's size is less than:
224 // * max_blob_in_memory_size_ if enable_disk_ is true
225 // * max_blob_memory_space_ if enable_disk_ is false
226 // So we know we're < max(size_t).
227 // Step 6: Decide if we're using shared memory.
228 if (total_memory_size_bytes > max_ipc_memory_size_) {
229 *result = MemoryStrategyResult::SHARED_MEMORY;
230 return true;
231 }
232 // Step 7: We can fit in IPC.
233 *result = MemoryStrategyResult::IPC;
234 return true;
235 }
236
237 void BlobMemoryController::CreateTemporaryFileForRenderer(
238 uint64_t size_bytes,
239 const base::Callback<void(FileCreationInfo)>& file_callback) {
240 if (!enable_disk_) {
241 BlobMemoryController::FileCreationInfo creation_info;
242 file_callback.Run(std::move(creation_info));
243 return;
244 }
245
246 disk_used_ += size_bytes;
michaeln 2016/07/14 01:44:43 and this "allocates" memory on disk
dmurph 2016/07/15 02:45:27 Added more documentation.
247 std::string file_name = base::Uint64ToString(current_file_num_++);
248 scoped_refptr<base::TaskRunner> file_runner =
249 file_worker_pool_->GetTaskRunnerWithShutdownBehavior(
250 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
251 scoped_refptr<ShareableFileReference> file_ref =
252 ShareableFileReference::GetOrCreate(
253 blob_storage_dir_.Append(file_name),
254 ShareableFileReference::DELETE_ON_FINAL_RELEASE, file_runner.get());
255 base::PostTaskAndReplyWithResult(
256 file_runner.get(), FROM_HERE,
257 base::Bind(&CreateFile, std::move(file_ref), size_bytes),
258 base::Bind(&BlobMemoryController::OnCreateFile, ptr_factory_.GetWeakPtr(),
259 size_bytes, file_callback));
260 }
261
262 void BlobMemoryController::FreeMemory(size_t memory_size_bytes) {
263 DCHECK_GE(blob_memory_used_, memory_size_bytes);
264 LOG(ERROR) << "Freeing memory " << memory_size_bytes;
265 blob_memory_used_ -= memory_size_bytes;
266 MaybeScheduleWaitingBlobs();
267 }
268
269 base::Optional<BlobMemoryController::PendingConstructionEntry>
270 BlobMemoryController::NotifyWhenMemoryCanPopulated(
271 size_t memory_size,
272 const base::Callback<void(bool)>& can_request_callback) {
273 DCHECK(memory_size <=
274 GetAvailableMemoryForBlobs() + GetAvailableDiskSpaceForBlobs());
275
276 if (!enable_disk_) {
277 LOG(ERROR) << "Yes, " << memory_size << " can fit in memory now.";
278 blob_memory_used_ += memory_size;
michaeln 2016/07/14 01:44:43 ok, this method "allocates" the memory
dmurph 2016/07/15 02:45:27 Added more documentation.
279 return base::nullopt;
280 }
281
282 // If we're currently waiting for blobs to page already, then we add
283 // ourselves to the end of the queue. Once paging is complete, we'll schedule
284 // more paging for any more pending blobs.
285 if (!blobs_waiting_for_paging_.empty()) {
286 LOG(ERROR) << "putting memory request " << memory_size << " in queue.";
287 blobs_waiting_for_paging_.push_back(
288 std::make_pair(memory_size, can_request_callback));
289 blobs_waiting_for_paging_size_ += memory_size;
290 return base::make_optional(--blobs_waiting_for_paging_.end());
291 }
292
293 // Store right away if we can.
294 if (memory_size <= GetAvailableMemoryForBlobs()) {
295 // If we're past our blob memory limit, then schedule our paging.
296 if (ShouldSchedulePagingForSize(memory_size)) {
297 LOG(ERROR) << "Scheduling premptive paging";
298 ScheduleBlobPaging();
299 }
300 LOG(ERROR) << "Yes, " << memory_size << " can fit in memory now.";
301 blob_memory_used_ += memory_size;
302 return base::nullopt;
303 }
304
305 // This means we're too big for memory.
306 LOG(ERROR) << "waiting until " << memory_size << " can fit.";
307 DCHECK(blobs_waiting_for_paging_.empty());
308 DCHECK_EQ(0u, blobs_waiting_for_paging_size_);
309 blobs_waiting_for_paging_.push_back(
310 std::make_pair(memory_size, can_request_callback));
311 blobs_waiting_for_paging_size_ = memory_size;
312 LOG(ERROR) << "Scheduling paging on first item too big";
313 SchedulePagingUntilWeCanFit(memory_size);
314 return base::make_optional(--blobs_waiting_for_paging_.end());
315 }
316
317 void BlobMemoryController::RemovePendingConstructionEntry(
318 const BlobMemoryController::PendingConstructionEntry& entry) {
319 const std::pair<size_t, base::Callback<void(bool)>> pair = *entry;
Marijn Kruisselbrink 2016/07/12 21:33:06 I'm not sure I quite get why you're making of a co
dmurph 2016/07/14 01:04:31 I forgot to remove the entry from the list.
320 blobs_waiting_for_paging_size_ -= pair.first;
321 }
322
323 void BlobMemoryController::UpdateBlobItemInRecents(
324 ShareableBlobDataItem* item) {
325 recent_item_cache_.Put(item->item_id(), item);
326 }
327
328 void BlobMemoryController::RemoveBlobItemInRecents(
329 const ShareableBlobDataItem& item) {
330 auto iterator = recent_item_cache_.Get(item.item_id());
331 if (iterator != recent_item_cache_.end())
332 recent_item_cache_.Erase(iterator);
333 }
334
335 void BlobMemoryController::OnCreateFile(
336 uint64_t file_size,
337 const base::Callback<void(FileCreationInfo)>& file_callback,
338 FileCreationInfo result) {
339 if (result.error == File::FILE_OK) {
340 result.file_reference->AddFinalReleaseCallback(
341 base::Bind(&BlobMemoryController::OnBlobFileDelete,
342 ptr_factory_.GetWeakPtr(), file_size));
343 } else {
344 disk_used_ -= file_size;
345 }
346 LOG(ERROR) << "Created file!";
347 file_callback.Run(std::move(result));
348 }
349
350 void BlobMemoryController::MaybeScheduleWaitingBlobs() {
351 size_t space_available = max_blob_in_memory_size_ - blob_memory_used_;
352 while (!blobs_waiting_for_paging_.empty() &&
353 space_available >= blobs_waiting_for_paging_.front().first) {
354 auto size_callback_pair = blobs_waiting_for_paging_.front();
355 blobs_waiting_for_paging_.pop_front();
356 space_available -= size_callback_pair.first;
357 blobs_waiting_for_paging_size_ -= size_callback_pair.first;
358 blob_memory_used_ += size_callback_pair.first;
359 size_callback_pair.second.Run(true);
360 }
361 }
362
363 size_t BlobMemoryController::ScheduleBlobPaging() {
364 DCHECK(enable_disk_);
365 DCHECK_LT(min_page_file_size_, static_cast<uint64_t>(blob_memory_used_));
366 LOG(ERROR) << "scheduling paging";
367
368 size_t total_items_size = 0;
369 std::unique_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>>
370 items_for_disk(new std::vector<scoped_refptr<ShareableBlobDataItem>>());
371 // Collect our items.
372 while (total_items_size < min_page_file_size_ &&
373 !recent_item_cache_.empty()) {
374 auto iterator = --recent_item_cache_.end();
375 ShareableBlobDataItem* item = iterator->second;
376 DCHECK(item);
377 recent_item_cache_.Erase(iterator);
378 size_t size = base::checked_cast<size_t>(item->item()->length());
379 total_items_size += size;
380 items_for_disk->push_back(make_scoped_refptr(item));
381 }
382 if (total_items_size == 0)
383 return 0;
384
385 // Update our bookkeeping.
386 pending_pagings_++;
387 disk_used_ += total_items_size;
388 DCHECK_GE(blob_memory_used_, total_items_size);
389 LOG(ERROR) << "saving " << total_items_size << " to disk.";
390 blob_memory_used_ -= total_items_size;
391 in_flight_memory_used_ += total_items_size;
392 std::string file_name = base::Uint64ToString(current_file_num_++);
393 scoped_refptr<base::TaskRunner> file_runner =
394 file_worker_pool_->GetTaskRunnerWithShutdownBehavior(
395 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN);
396 scoped_refptr<ShareableFileReference> file_ref =
397 ShareableFileReference::GetOrCreate(
398 blob_storage_dir_.Append(file_name),
399 ShareableFileReference::DELETE_ON_FINAL_RELEASE, file_runner.get());
400 base::PostTaskAndReplyWithResult(
401 file_runner.get(), FROM_HERE,
402 base::Bind(&WriteItemsToFile, items_for_disk.get(), total_items_size,
403 std::move(file_ref)),
404 base::Bind(&BlobMemoryController::OnPagingComplete,
405 ptr_factory_.GetWeakPtr(), base::Passed(&items_for_disk),
406 total_items_size));
407 return total_items_size;
408 }
409
410 void BlobMemoryController::SchedulePagingUntilWeCanFit(
411 size_t total_memory_needed) {
412 DCHECK_LT(total_memory_needed, max_blob_in_memory_size_);
413 while (total_memory_needed + blob_memory_used_ > max_blob_in_memory_size_) {
414 // schedule another page.
415 size_t memory_freeing = ScheduleBlobPaging();
416 DCHECK_GE(blob_memory_used_, memory_freeing);
417 if (memory_freeing == 0)
418 return;
419 }
420 }
421
422 void BlobMemoryController::OnPagingComplete(
423 std::unique_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>> items,
424 size_t total_items_size,
425 FileCreationInfo result) {
426 if (!enable_disk_)
427 return;
428 if (result.error != File::FILE_OK) {
429 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingError", -result.error,
430 -File::FILE_ERROR_MAX);
431 disk_used_ -= total_items_size;
432 DisableDisk();
433 return;
434 }
435 DCHECK_LT(0u, pending_pagings_);
436 pending_pagings_--;
437
438 // Switch from the data backing item to a new file backing item.
439 uint64_t offset = 0;
440 for (const scoped_refptr<ShareableBlobDataItem>& shareable_item :
441 *items.get()) {
442 scoped_refptr<BlobDataItem> new_item(new BlobDataItem(
443 base::WrapUnique(new DataElement()), result.file_reference));
444 new_item->data_element_ptr()->SetToFilePathRange(
445 result.file_reference->path(), offset, shareable_item->item()->length(),
446 result.last_modified);
447 shareable_item->item_ = new_item;
448 offset += shareable_item->item()->length();
449 }
450 in_flight_memory_used_ -= total_items_size;
451
452 // We want callback on blobs up to the amount we've freed.
453 MaybeScheduleWaitingBlobs();
454
455 // If we still have more blobs waiting and we're not waiting on more paging
456 // operations, schedule more.
457 if (!blobs_waiting_for_paging_.empty() && pending_pagings_ == 0) {
458 SchedulePagingUntilWeCanFit(blobs_waiting_for_paging_size_);
459 }
460 }
461
462 void BlobMemoryController::RecordTracingCounters() {
463 TRACE_COUNTER2("Blob", "MemoryUsage", "RegularStorage", blob_memory_used_,
464 "InFlightToDisk", in_flight_memory_used_);
465 TRACE_COUNTER1("Blob", "TranfersPendingOnDisk",
466 blobs_waiting_for_paging_.size());
467 TRACE_COUNTER1("Blob", "TranfersBytesPendingOnDisk",
468 blobs_waiting_for_paging_size_);
469 }
470
471 bool BlobMemoryController::ShouldSchedulePagingForSize(size_t size) const {
472 return blob_memory_used_ + size - in_flight_memory_used_ >
473 max_blob_in_memory_size_;
474 }
475
476 bool BlobMemoryController::CanFitInSystem(uint64_t size) const {
477 return size < GetAvailableMemoryForBlobs() + GetAvailableDiskSpaceForBlobs();
478 }
479
480 size_t BlobMemoryController::GetAvailableMemoryForBlobs() const {
481 if (blob_memory_used_ >= max_blob_in_memory_size_)
482 return 0;
483 if (enable_disk_) {
484 if (max_blob_in_memory_size_ + in_flight_space_ <
485 blob_memory_used_ + in_flight_memory_used_) {
486 return 0;
487 }
488 return max_blob_in_memory_size_ + in_flight_space_ - blob_memory_used_ -
489 in_flight_memory_used_;
490 }
491 return max_blob_memory_space_ - blob_memory_used_;
492 }
493
494 uint64_t BlobMemoryController::GetAvailableDiskSpaceForBlobs() const {
495 return enable_disk_ ? kBlobStorageMaxDiskSpace - disk_used_ : 0;
496 }
497
498 void BlobMemoryController::OnBlobFileDelete(uint64_t size,
499 const base::FilePath& path) {
500 DCHECK_LE(size, disk_used_);
501 LOG(ERROR) << "deleting file " << path.value();
502 disk_used_ -= size;
503 }
504
505 } // namespace storage
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698