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

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

Issue 1528233004: [Blob] Blob paging to disk patch. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@blob-disk1
Patch Set: Created 5 years 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 2015 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/metrics/histogram_macros.h"
14 #include "base/numerics/safe_conversions.h"
15 #include "base/numerics/safe_math.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/task_runner.h"
19 #include "base/task_runner_util.h"
20 #include "base/thread_task_runner_handle.h"
21 #include "base/time/time.h"
22 #include "base/trace_event/trace_event.h"
23 #include "base/tuple.h"
24 #include "storage/browser/blob/blob_data_item.h"
25 #include "storage/browser/blob/shareable_blob_data_item.h"
26 #include "storage/browser/blob/shareable_file_reference.h"
27
28 using base::File;
29 using base::FilePath;
30
31 namespace storage {
32
33 BlobMemoryController::FileCreationInfo::FileCreationInfo() {}
34 BlobMemoryController::FileCreationInfo::~FileCreationInfo() {}
35
36 BlobMemoryController::BlobMemoryController()
37 : recent_item_cache_(RecentItemsCache::NO_AUTO_EVICT) {}
38
39 BlobMemoryController::BlobMemoryController(
40 bool enable_disk,
41 const FilePath& blob_storage_dir,
42 scoped_refptr<base::TaskRunner> file_runner)
43 : file_runner_(file_runner),
44 enable_disk_(enable_disk),
45 blob_storage_dir_(blob_storage_dir),
46 recent_item_cache_(RecentItemsCache::NO_AUTO_EVICT) {}
47
48 BlobMemoryController::~BlobMemoryController() {}
49
50 bool BlobMemoryController::DecideBlobTransportationMemoryStrategy(
51 const std::vector<DataElement>& descriptions,
52 uint64_t* total_bytes,
53 BlobMemoryController::BlobTrasportationMemoryStrategyResult* result) {
54 DCHECK(total_bytes);
55 DCHECK(result);
56 // Step 1: Get the sizes.
57 size_t shortcut_memory_size_bytes;
58 uint64_t total_memory_size_bytes;
59 if (!CalculateBlobMemorySize(descriptions, &shortcut_memory_size_bytes,
60 &total_memory_size_bytes)) {
61 return false;
62 }
63 *total_bytes = total_memory_size_bytes;
64
65 // Step 2: Handle case where we have no memory to transport.
66 if (total_memory_size_bytes == 0) {
67 *result = BlobTrasportationMemoryStrategyResult::NONE_NEEDED;
68 return true;
69 }
70
71 // Step 3: Check if we have enough memory to store the blob.
72 if (total_memory_size_bytes > GetAvailableMemoryForBlobs() &&
73 total_memory_size_bytes > GetAvailableDiskSpaceForBlobs()) {
74 *result = BlobTrasportationMemoryStrategyResult::TOO_LARGE;
75 return true;
76 }
77 // From here on, we know we can fit the blob in memory or on disk.
78
79 // Step 4: Decide if we're using the shortcut method.
80 if (shortcut_memory_size_bytes == total_memory_size_bytes &&
81 blobs_waiting_for_paging_.empty() &&
82 shortcut_memory_size_bytes < GetAvailableMemoryForBlobs()) {
83 *result = BlobTrasportationMemoryStrategyResult::SHORTCUT;
84 return true;
85 }
86
87 // Step 5: Decide if we're going straight to disk.
88 if (enable_disk_ && (total_memory_size_bytes > max_blob_in_memory_size_)) {
89 *result = BlobTrasportationMemoryStrategyResult::FILE;
90 return true;
91 }
92 // From here on, we know the blob's size is less than:
93 // * max_blob_in_memory_size_ if enable_disk_ is true
94 // * max_blob_memory_space_ if enable_disk_ is false
95 // So we know we're < max(size_t).
96
97 // Step 6: Decide if we're using shared memory.
98 if (total_memory_size_bytes > max_ipc_memory_size_) {
99 *result = BlobTrasportationMemoryStrategyResult::SHARED_MEMORY;
100 return true;
101 }
102
103 // Step 7: We can fit in IPC.
104 *result = BlobTrasportationMemoryStrategyResult::IPC;
105 return true;
106 }
107
108 void BlobMemoryController::CreateTemporaryFileForRenderer(
109 uint64_t size_bytes,
110 base::Callback<void(const FileCreationInfo&)> done) {
111 if (!enable_disk_) {
112 BlobMemoryController::FileCreationInfo creation_info;
113 creation_info.error = File::FILE_ERROR_FAILED;
114 done.Run(creation_info);
115 return;
116 }
117 disk_used_ += size_bytes;
118 std::string file_name = base::Uint64ToString(current_file_num_++);
119 base::PostTaskAndReplyWithResult(
120 file_runner_.get(), FROM_HERE,
121 base::Bind(&BlobMemoryController::CreateFile, blob_storage_dir_,
122 file_name, size_bytes),
123 base::Bind(&BlobMemoryController::OnCreateFile, this->AsWeakPtr(),
124 size_bytes, done));
125 }
126
127 void BlobMemoryController::NotifyWhenBlobCanBeRequested(
128 uint64_t memory_size,
129 base::Callback<void(bool)> can_request) {
130 if (!enable_disk_) {
131 blob_memory_used_ += memory_size;
132 can_request.Run(true);
133 return;
134 }
135 if (!blobs_waiting_for_paging_.empty()) {
136 blobs_waiting_for_paging_.push_back(
137 std::make_pair(memory_size, can_request));
138 blobs_waiting_for_paging_size_ += memory_size;
139 SchedulePagingUntilWeCanFit(blobs_waiting_for_paging_size_);
140 return;
141 }
142 DCHECK_EQ(0u, blobs_waiting_for_paging_size_);
143 SchedulePagingUntilWeCanFit(memory_size);
144 if (memory_size < GetAvailableMemoryForBlobs()) {
145 blob_memory_used_ += memory_size;
146 can_request.Run(true);
147 return;
148 }
149 blobs_waiting_for_paging_.push_back(std::make_pair(memory_size, can_request));
150 blobs_waiting_for_paging_size_ += memory_size;
151 SchedulePagingUntilWeCanFit(blobs_waiting_for_paging_size_);
152 }
153
154 void BlobMemoryController::UpdateBlobItemInRecents(
155 ShareableBlobDataItem* item) {
156 if (!enable_disk_)
157 return;
158 auto iterator = recent_item_cache_.Get(item->item_id());
159 if (iterator != recent_item_cache_.end())
160 recent_item_cache_.Erase(iterator);
161 recent_item_cache_.Put(item->item_id(), item);
162 }
163
164 void BlobMemoryController::RemoveBlobItemInRecents(uint64_t id) {
165 if (!enable_disk_)
166 return;
167 auto iterator = recent_item_cache_.Get(id);
168 if (iterator != recent_item_cache_.end())
169 recent_item_cache_.Erase(iterator);
170 }
171
172 /* static */
173 bool BlobMemoryController::CalculateBlobMemorySize(
174 const std::vector<DataElement>& descriptions,
175 size_t* shortcut_bytes,
176 uint64_t* total_bytes) {
177 DCHECK(shortcut_bytes);
178 DCHECK(total_bytes);
179 base::CheckedNumeric<uint64_t> total_size_checked = 0;
180 base::CheckedNumeric<size_t> shortcut_size_checked = 0;
181 for (const auto& info : descriptions) {
182 if (info.type() == DataElement::TYPE_BYTES) {
183 total_size_checked += info.length();
184 shortcut_size_checked += info.length();
185 } else if (info.type() == DataElement::TYPE_BYTES_DESCRIPTION) {
186 total_size_checked += info.length();
187 } else {
188 continue;
189 }
190
191 if (!total_size_checked.IsValid() || !shortcut_size_checked.IsValid()) {
192 return false;
193 }
194 }
195 *shortcut_bytes = shortcut_size_checked.ValueOrDie();
196 *total_bytes = total_size_checked.ValueOrDie();
197 return true;
198 }
199
200 /* static */
201 BlobMemoryController::FileCreationInfo BlobMemoryController::CreateFile(
202 const FilePath& directory_path,
203 const std::string& file_name,
204 size_t size_bytes) {
205 DCHECK_NE(0u, size_bytes);
206 BlobMemoryController::FileCreationInfo creation_info;
207 UMA_HISTOGRAM_MEMORY_KB("Storage.Blob.RendererFileSize", size_bytes / 1024);
208 creation_info.error = File::FILE_OK;
209 base::CreateDirectoryAndGetError(directory_path, &creation_info.error);
210 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.EnsureBlobStorageDirectory",
211 -creation_info.error, -File::FILE_ERROR_MAX);
212 if (creation_info.error != File::FILE_OK)
213 return creation_info;
214 base::FilePath path = directory_path.Append(file_name);
215 File file(path, File::FLAG_CREATE_ALWAYS);
216 creation_info.error = file.error_details();
217 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.RendererFileCreate",
218 -creation_info.error, -File::FILE_ERROR_MAX);
219 if (creation_info.error != File::FILE_OK)
220 return creation_info;
221 File::Info file_info;
222 bool success = file.GetInfo(&file_info);
223 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.RendererFileInfoSuccess", success);
224 creation_info.error = success ? File::FILE_OK : File::FILE_ERROR_FAILED;
225 creation_info.last_modified = file_info.last_modified;
226 if (success) {
227 creation_info.file_reference = ShareableFileReference::GetOrCreate(
228 path, ShareableFileReference::DELETE_ON_FINAL_RELEASE,
229 base::ThreadTaskRunnerHandle::Get().get());
230 }
231 return creation_info;
232 }
233
234 /* static */
235 BlobMemoryController::FileCreationInfo BlobMemoryController::WriteItemsToFile(
236 std::vector<scoped_refptr<ShareableBlobDataItem>>* items,
237 size_t total_size_bytes,
238 const FilePath& directory_path,
239 const std::string& file_name) {
240 DCHECK_NE(0u, total_size_bytes);
241 UMA_HISTOGRAM_MEMORY_KB("Storage.Blob.PageFileSize", total_size_bytes / 1024);
242 BlobMemoryController::FileCreationInfo creation_info;
243 creation_info.error = File::FILE_OK;
244 base::CreateDirectoryAndGetError(directory_path, &creation_info.error);
245 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.EnsureBlobStorageDirectory",
246 -creation_info.error, -File::FILE_ERROR_MAX);
247 if (creation_info.error != File::FILE_OK)
248 return creation_info;
249
250 base::FilePath path = directory_path.Append(file_name);
251 File file(path, File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE);
252 creation_info.error = file.error_details();
253 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PageFileCreate", -creation_info.error,
254 -File::FILE_ERROR_MAX);
255 if (creation_info.error != File::FILE_OK)
256 return creation_info;
257
258 file.SetLength(total_size_bytes);
259 int bytes_written = 0;
260 for (const auto& refptr : *items) {
261 const DataElement& element = refptr->item()->data_element();
262 DCHECK_EQ(DataElement::TYPE_BYTES, element.type());
263 int length = base::checked_cast<int, uint64>(element.length());
264 bytes_written = file.WriteAtCurrentPos(element.bytes(), length);
265 DCHECK_EQ(length, bytes_written);
266 if (bytes_written < 0) {
267 break;
268 }
269 }
270 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.PageFileWriteSuccess", bytes_written > 0);
271 File::Info info;
272 bool success = file.GetInfo(&info);
273 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.PageFileInfoSuccess", success);
274 creation_info.error =
275 bytes_written < 0 || !success ? File::FILE_ERROR_FAILED : File::FILE_OK;
276 if (creation_info.error == File::FILE_OK) {
277 creation_info.file_reference = ShareableFileReference::GetOrCreate(
278 path, ShareableFileReference::DELETE_ON_FINAL_RELEASE,
279 base::ThreadTaskRunnerHandle::Get().get());
280 }
281 return creation_info;
282 }
283
284 void BlobMemoryController::OnCreateFile(
285 uint64_t file_size,
286 base::Callback<void(const FileCreationInfo&)> done,
287 FileCreationInfo result) {
288 if (result.error == File::FILE_OK) {
289 result.file_reference->AddFinalReleaseCallback(base::Bind(
290 &BlobMemoryController::OnBlobFileDelete, this->AsWeakPtr(), file_size));
291 } else {
292 disk_used_ -= file_size;
293 }
294 done.Run(result);
295 }
296
297 size_t BlobMemoryController::ScheduleBlobPaging() {
298 DCHECK(enable_disk_);
299 DCHECK_LT(min_page_file_size_, static_cast<uint64_t>(blob_memory_used_));
300 size_t total_items_size = 0;
301 scoped_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>> items_for_disk(
302 new std::vector<scoped_refptr<ShareableBlobDataItem>>());
303 while (total_items_size < min_page_file_size_) {
304 DCHECK(!recent_item_cache_.empty());
305 auto iterator = --recent_item_cache_.end();
306 ShareableBlobDataItem* item = iterator->second;
307 recent_item_cache_.Erase(iterator);
308 size_t size = base::checked_cast<size_t, uint64_t>(item->item()->length());
309 total_items_size += size;
310 items_for_disk->push_back(make_scoped_refptr(item));
311 }
312 disk_used_ += total_items_size;
313 std::string file_name = base::Uint64ToString(current_file_num_++);
314 FilePath path = blob_storage_dir_.Append(file_name);
315 base::PostTaskAndReplyWithResult(
316 file_runner_.get(), FROM_HERE,
317 base::Bind(&BlobMemoryController::WriteItemsToFile, items_for_disk.get(),
318 total_items_size, blob_storage_dir_, file_name),
319 base::Bind(&BlobMemoryController::OnPagingComplete, this->AsWeakPtr(),
320 base::Passed(items_for_disk.Pass()), total_items_size));
321
322 return total_items_size;
323 }
324
325 void BlobMemoryController::SchedulePagingUntilWeCanFit(
326 size_t total_memory_needed) {
327 DCHECK_LT(total_memory_needed, max_blob_memory_space_);
328 while (total_memory_needed + blob_memory_used_ > max_blob_memory_space_) {
329 // schedule another page.
330 size_t memory_freeing = ScheduleBlobPaging();
331 DCHECK_GE(blob_memory_used_, memory_freeing);
332 blob_memory_used_ -= memory_freeing;
333 in_flight_memory_used_ += memory_freeing;
334 }
335 }
336
337 void BlobMemoryController::OnPagingComplete(
338 scoped_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>> items,
339 size_t total_items_size,
340 FileCreationInfo result) {
341 if (!enable_disk_) {
342 return;
343 }
344 if (result.error != File::FILE_OK) {
345 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingError", -result.error,
346 -File::FILE_ERROR_MAX);
347 disk_used_ -= total_items_size;
348 DisableDisk();
349 return;
350 }
351 // Switch from the data backing item to a new file backing item.
352 uint64_t offset = 0;
353 for (const scoped_refptr<ShareableBlobDataItem>& shareable_item :
354 *items.get()) {
355 scoped_refptr<BlobDataItem> new_item(new BlobDataItem(
356 make_scoped_ptr(new DataElement()), result.file_reference));
357 new_item->data_element_ptr()->SetToFilePathRange(
358 result.file_reference->path(), offset, shareable_item->item()->length(),
359 result.last_modified);
360 shareable_item->item_.swap(new_item);
361 offset += shareable_item->item()->length();
362 }
363 in_flight_memory_used_ -= total_items_size;
364
365 // We want callback on blobs up to the amount we've freed.
366 size_t space_available = GetAvailableMemoryForBlobs();
367 while (!blobs_waiting_for_paging_.empty() &&
368 space_available > blobs_waiting_for_paging_.front().first) {
369 auto size_callback_pair = blobs_waiting_for_paging_.front();
370 blobs_waiting_for_paging_.pop_front();
371 space_available -= size_callback_pair.first;
372 blob_memory_used_ += size_callback_pair.first;
373 size_callback_pair.second.Run(true);
374 }
375 }
376
377 void BlobMemoryController::DisableDisk() {
378 enable_disk_ = false;
379 blob_memory_used_ += in_flight_memory_used_;
380 in_flight_memory_used_ = 0;
381 for (const auto& size_callback_pair : blobs_waiting_for_paging_) {
382 size_callback_pair.second.Run(false);
383 }
384 blobs_waiting_for_paging_.clear();
385 blobs_waiting_for_paging_size_ = 0;
386 recent_item_cache_.Clear();
387 RecordTracingCounters();
388 }
389
390 void BlobMemoryController::RecordTracingCounters() {
391 TRACE_COUNTER2("Blob", "MemoryUsage", "RegularStorage", blob_memory_used_,
392 "InFlightToDisk", in_flight_memory_used_);
393 TRACE_COUNTER1("Blob", "TranfersPendingOnDisk",
394 blobs_waiting_for_paging_.size());
395 TRACE_COUNTER1("Blob", "TranfersBytesPendingOnDisk",
396 blobs_waiting_for_paging_size_);
397 }
398
399 size_t BlobMemoryController::GetAvailableMemoryForBlobs() {
400 if (max_blob_memory_space_ < blob_memory_used_)
401 return 0;
402 if (enable_disk_)
403 return std::min<size_t>(0u, in_flight_space_ - in_flight_memory_used_) +
404 (max_blob_memory_space_ - blob_memory_used_);
405 return max_blob_memory_space_ - blob_memory_used_;
406 }
407
408 uint64_t BlobMemoryController::GetAvailableDiskSpaceForBlobs() {
409 return enable_disk_ ? kBlobStorageMaxDiskSpace - disk_used_ : 0;
410 }
411
412 void BlobMemoryController::OnBlobFileDelete(uint64_t size,
413 const base::FilePath& path) {
414 if (enable_disk_) {
415 DCHECK_GT(size, disk_used_);
416 disk_used_ -= size;
417 }
418 }
419
420 } // namespace storage
OLDNEW
« no previous file with comments | « storage/browser/blob/blob_memory_controller.h ('k') | storage/browser/blob/blob_storage_context.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698