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

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

Powered by Google App Engine
This is Rietveld 408576698