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

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

Issue 2339933004: [BlobStorage] BlobMemoryController & tests (Closed)
Patch Set: Fix android & windows build errors Created 4 years, 2 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/containers/small_map.h"
12 #include "base/files/file_util.h"
13 #include "base/guid.h"
14 #include "base/location.h"
15 #include "base/memory/ptr_util.h"
16 #include "base/metrics/histogram_macros.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/numerics/safe_math.h"
19 #include "base/single_thread_task_runner.h"
20 #include "base/stl_util.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/task_runner.h"
23 #include "base/task_runner_util.h"
24 #include "base/threading/thread_restrictions.h"
25 #include "base/time/time.h"
26 #include "base/trace_event/trace_event.h"
27 #include "base/tuple.h"
28 #include "storage/browser/blob/blob_data_builder.h"
29 #include "storage/browser/blob/blob_data_item.h"
30 #include "storage/browser/blob/shareable_blob_data_item.h"
31 #include "storage/browser/blob/shareable_file_reference.h"
32 #include "storage/common/data_element.h"
33
34 using base::File;
35 using base::FilePath;
36 using FileCreationInfo = storage::BlobMemoryController::FileCreationInfo;
37
38 namespace storage {
39 namespace {
40 using QuotaAllocationTask = BlobMemoryController::QuotaAllocationTask;
41
42 File::Error CreateBlobDirectory(const FilePath& blob_storage_dir) {
43 File::Error error;
44 bool success = base::CreateDirectoryAndGetError(blob_storage_dir, &error);
45 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.DirectorySuccess", success);
46 if (!success) {
47 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.DirectorySuccess.Error", -error,
michaeln 2016/10/11 20:55:24 i think you could merge these two stats into one,
dmurph 2016/10/13 00:39:30 Done.
48 -File::FILE_ERROR_MAX);
49 return error;
50 }
51 return File::FILE_OK;
52 }
53
54 void DestructFile(File infos_without_references) {}
55
56 // Used for new unpopulated file items. Caller must populate file reference in
57 // returned FileCreationInfos.
58 std::vector<FileCreationInfo> CreateEmptyFiles(
59 const FilePath& blob_storage_dir,
60 scoped_refptr<base::TaskRunner> file_task_runner,
61 std::vector<base::FilePath> file_paths) {
kinuko 2016/10/12 15:26:41 nit: const ref
dmurph 2016/10/13 00:39:30 We do a value here as we std::move our vector (bas
62 base::ThreadRestrictions::AssertIOAllowed();
kinuko 2016/10/12 15:26:41 I think these are automatically checked in File's
dmurph 2016/10/13 00:39:31 Just to clarify to the reader that we expect to be
63
64 if (CreateBlobDirectory(blob_storage_dir) != File::FILE_OK)
65 return std::vector<FileCreationInfo>();
66
67 std::vector<FileCreationInfo> result;
68 for (const base::FilePath& file_path : file_paths) {
69 FileCreationInfo creation_info;
70 // Try to open our file.
71 File file(file_path, File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE);
72 creation_info.path = std::move(file_path);
73 creation_info.file_deletion_runner = file_task_runner;
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 std::vector<FileCreationInfo>();
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 if (!success)
86 return std::vector<FileCreationInfo>();
87 creation_info.file = std::move(file);
88
89 result.push_back(std::move(creation_info));
90 }
91 return result;
92 }
93
94 // Used to evict multiple memory items out to a single file. Caller must
95 // populate file reference in returned FileCreationInfo.
96 FileCreationInfo CreateFileAndWriteItems(
97 const FilePath& blob_storage_dir,
98 const FilePath& file_path,
99 scoped_refptr<base::TaskRunner> file_task_runner,
100 std::vector<DataElement*> items,
kinuko 2016/10/12 15:26:41 const ref
dmurph 2016/10/13 00:39:30 Same as above, we std::move our vector into this c
101 size_t total_size_bytes) {
102 DCHECK_NE(0u, total_size_bytes);
103 UMA_HISTOGRAM_MEMORY_KB("Storage.Blob.PageFileSize", total_size_bytes / 1024);
michaeln 2016/10/11 20:55:23 this stat looks interesting
dmurph 2016/10/13 00:39:30 Acknowledged.
104 base::ThreadRestrictions::AssertIOAllowed();
kinuko 2016/10/12 15:26:42 ditto
dmurph 2016/10/13 00:39:30 Same answer as above. Let me know if you feel stro
105
106 FileCreationInfo creation_info;
107 creation_info.file_deletion_runner = std::move(file_task_runner);
108 creation_info.error = CreateBlobDirectory(blob_storage_dir);
109 if (creation_info.error != File::FILE_OK)
110 return creation_info;
111
112 // Create the page file.
113 File file(file_path, File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE);
114 creation_info.path = file_path;
115 creation_info.error = file.error_details();
116 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PageFileCreate", -creation_info.error,
117 -File::FILE_ERROR_MAX);
118 if (creation_info.error != File::FILE_OK)
119 return creation_info;
120
121 // Write data.
122 file.SetLength(total_size_bytes);
123 int bytes_written = 0;
124 for (DataElement* element : items) {
125 DCHECK_EQ(DataElement::TYPE_BYTES, element->type());
126 size_t length = base::checked_cast<size_t>(element->length());
127 size_t bytes_left = length;
128 while (bytes_left > 0) {
129 bytes_written =
130 file.WriteAtCurrentPos(element->bytes() + (length - bytes_left),
131 base::saturated_cast<int>(bytes_left));
132 if (bytes_written < 0)
133 break;
134 DCHECK_LE(static_cast<size_t>(bytes_written), bytes_left);
135 bytes_left -= bytes_written;
136 }
137 if (bytes_written < 0)
138 break;
139 }
140 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.PageFileWriteSuccess", bytes_written > 0);
141
142 File::Info info;
143 bool success = file.GetInfo(&info);
144 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.PageFileInfoSuccess", success);
michaeln 2016/10/11 20:55:23 I'm not sure these functions warrant 8 many uma st
dmurph 2016/10/13 00:39:31 Done.
145 creation_info.error =
146 bytes_written < 0 || !success ? File::FILE_ERROR_FAILED : File::FILE_OK;
147 creation_info.last_modified = info.last_modified;
148 return creation_info;
149 }
150
151 uint64_t GetTotalSizeAndFileSizes(
152 const std::vector<scoped_refptr<ShareableBlobDataItem>>&
153 unreserved_file_items,
154 std::vector<uint64_t>* file_sizes_output) {
155 uint64_t total_size_output = 0;
156 base::SmallMap<std::map<uint64_t, uint64_t>> file_sizes;
kinuko 2016/10/12 15:26:41 nit: maybe file_sizes -> file_id_to_sizes for bett
dmurph 2016/10/13 00:39:30 Done.
157 for (const auto& item : unreserved_file_items) {
158 const DataElement& element = item->item()->data_element();
159 uint64_t file_id = BlobDataBuilder::GetFutureFileID(element);
160 auto it = file_sizes.find(file_id);
161 if (it != file_sizes.end()) {
162 it->second = std::max(it->second, element.offset() + element.length());
163 } else {
164 file_sizes[file_id] = element.offset() + element.length();
165 }
166 total_size_output += element.length();
167 }
168 for (const auto& size_pair : file_sizes) {
169 file_sizes_output->push_back(size_pair.second);
170 }
171 return total_size_output;
172 }
173
174 } // namespace
175
176 BlobMemoryController::QuotaAllocationTask::~QuotaAllocationTask() {}
177
178 // The my_list_position_ iterator is stored so that we can remove ourself from
179 // the task list when it is cancelled.
180 template <typename T>
kinuko 2016/10/12 15:26:41 nit: T -> TaskList or TASK_LIST for better readabi
dmurph 2016/10/13 00:39:31 Done.
181 class BlobMemoryController::BaseQuotaAllocationTask
182 : public BlobMemoryController::QuotaAllocationTask {
183 public:
184 BaseQuotaAllocationTask() : allocation_size_(0) {}
185 explicit BaseQuotaAllocationTask(uint64_t allocation_size)
186 : allocation_size_(allocation_size) {}
187
188 ~BaseQuotaAllocationTask() override {}
189
190 void set_my_list_position(typename T::iterator my_list_position) {
191 my_list_position_ = my_list_position;
192 }
193 typename T::iterator my_list_position() const { return my_list_position_; }
194
195 uint64_t allocation_size() { return allocation_size_; }
196 void set_allocation_size(uint64_t allocation_size) {
197 allocation_size_ = allocation_size;
198 }
199
200 private:
201 uint64_t allocation_size_;
202 typename T::iterator my_list_position_;
203 };
204
205 class BlobMemoryController::MemoryQuotaAllocationTask
206 : public BlobMemoryController::BaseQuotaAllocationTask<
207 PendingMemoryQuotaTaskList> {
208 public:
209 MemoryQuotaAllocationTask(
210 BlobMemoryController* controller,
211 uint64_t quota_request_size,
212 std::vector<scoped_refptr<ShareableBlobDataItem>> pending_items,
213 MemoryQuotaRequestCallback done_callback)
kinuko 2016/10/12 15:26:41 nit: some of params can be probably const ref's
dmurph 2016/10/13 00:39:31 I'm doing std::moves here, so I don't want the con
214 : BaseQuotaAllocationTask(quota_request_size),
215 controller_(controller),
216 pending_items_(std::move(pending_items)),
217 done_callback_(done_callback),
218 weak_factory_(this) {}
219
220 ~MemoryQuotaAllocationTask() override = default;
221
222 void RunDoneCallback(bool success) const {
223 if (success) {
224 for (const auto& item : pending_items_) {
225 item->set_state(ShareableBlobDataItem::QUOTA_GRANTED);
kinuko 2016/10/12 15:26:41 nit: getting an item with const ref and calling se
dmurph 2016/10/13 00:39:30 I can remove the const.
226 }
227 }
228 done_callback_.Run(success);
229 }
230
231 void Cancel() override {
232 controller_->pending_memory_quota_total_size_ -= allocation_size();
233 // This call destroys this object.
234 controller_->pending_memory_quota_tasks_.erase(my_list_position());
235 }
236
michaeln 2016/10/11 20:55:24 can these be private?
dmurph 2016/10/13 00:39:30 Done.
237 BlobMemoryController* controller_;
238 std::vector<scoped_refptr<ShareableBlobDataItem>> pending_items_;
239 MemoryQuotaRequestCallback done_callback_;
240
241 base::WeakPtrFactory<MemoryQuotaAllocationTask> weak_factory_;
242 DISALLOW_COPY_AND_ASSIGN(MemoryQuotaAllocationTask);
243 };
244
245 class BlobMemoryController::FileQuotaAllocationTask
246 : public BlobMemoryController::BaseQuotaAllocationTask<
247 PendingFileQuotaTaskList> {
248 public:
249 FileQuotaAllocationTask(
250 BlobMemoryController* memory_controller,
251 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_file_items,
252 const FileQuotaRequestCallback& done_callback)
253 : controller_(memory_controller),
254 done_callback_(done_callback),
255 weak_factory_(this) {
256 // Get the file sizes and total size.
257 std::vector<uint64_t> file_sizes;
258 uint64_t total_size =
259 GetTotalSizeAndFileSizes(unreserved_file_items, &file_sizes);
260 DCHECK_LE(total_size, controller_->GetAvailableFileSpaceForBlobs());
261 set_allocation_size(total_size);
262
263 // Check & set our item states.
264 for (const auto& shareable_item : unreserved_file_items) {
265 DCHECK_EQ(ShareableBlobDataItem::QUOTA_NEEDED, shareable_item->state());
266 DCHECK_EQ(DataElement::TYPE_FILE, shareable_item->item()->type());
267 shareable_item->set_state(ShareableBlobDataItem::QUOTA_REQUESTED);
268 }
269 pending_items_ = std::move(unreserved_file_items);
270
271 // Increment disk usage and create our file references.
272 controller_->disk_used_ += allocation_size();
273 std::vector<base::FilePath> file_paths;
274 std::vector<scoped_refptr<ShareableFileReference>> references;
275 for (size_t i = 0; i < file_sizes.size(); i++) {
276 file_paths.push_back(controller_->GenerateNextPageFileName());
277 references.push_back(ShareableFileReference::GetOrCreate(
278 file_paths.back(), ShareableFileReference::DELETE_ON_FINAL_RELEASE,
279 controller_->file_runner_.get()));
280 references.back()->AddFinalReleaseCallback(base::Bind(
281 &BlobMemoryController::OnBlobFileDelete,
282 controller_->file_destruction_factory_.GetWeakPtr(), file_sizes[i]));
283 }
284
285 // Send file creation task to file thread.
286 base::PostTaskAndReplyWithResult(
287 controller_->file_runner_.get(), FROM_HERE,
288 base::Bind(&CreateEmptyFiles, controller_->blob_storage_dir_,
289 controller_->file_runner_, base::Passed(&file_paths)),
290 base::Bind(&FileQuotaAllocationTask::OnCreateEmptyFiles,
291 weak_factory_.GetWeakPtr(), base::Passed(&references)));
292 controller_->RecordTracingCounters();
293 }
294 ~FileQuotaAllocationTask() override {}
295
296 void RunDoneCallback(bool success,
297 bool delete_object,
298 std::vector<FileCreationInfo> file_info) const {
299 if (success) {
300 for (const auto& item : pending_items_) {
301 item->set_state(ShareableBlobDataItem::QUOTA_GRANTED);
302 }
303 }
304 std::unique_ptr<FileQuotaAllocationTask> this_object;
305 if (delete_object) {
306 // Grab the unique pointer to this object. We will destruct ourselves on
307 // method return.
308 this_object = std::move(*my_list_position());
309 controller_->pending_file_quota_tasks_.erase(my_list_position());
310 }
311
312 done_callback_.Run(success, std::move(file_info));
313 }
314
315 void Cancel() override {
316 // This call destroys this object. We rely on ShareableFileReference's
317 // final release callback for disk_usage_ accounting.
318 controller_->pending_file_quota_tasks_.erase(my_list_position());
319 }
320
321 void OnCreateEmptyFiles(
322 std::vector<scoped_refptr<ShareableFileReference>> references,
323 std::vector<FileCreationInfo> files) {
324 if (files.empty()) {
325 controller_->disk_used_ -= allocation_size();
326 // This will call call our callback and delete the object correctly.
327 controller_->DisableFilePaging();
328 return;
329 }
330 DCHECK_EQ(files.size(), references.size());
331 for (size_t i = 0; i < files.size(); i++) {
332 files[i].file_reference = std::move(references[i]);
333 }
334 RunDoneCallback(true, true, std::move(files));
kinuko 2016/10/12 15:26:41 nit: can we comment bool params? true /* success
dmurph 2016/10/13 00:39:30 Done.
335 }
336
337 BlobMemoryController* controller_;
338 std::vector<scoped_refptr<ShareableBlobDataItem>> pending_items_;
339 scoped_refptr<base::TaskRunner> file_runner_;
340 FileQuotaRequestCallback done_callback_;
341
342 base::WeakPtrFactory<FileQuotaAllocationTask> weak_factory_;
343 DISALLOW_COPY_AND_ASSIGN(FileQuotaAllocationTask);
344 };
345
346 FileCreationInfo::FileCreationInfo() {}
347 FileCreationInfo::~FileCreationInfo() {
348 if (file.IsValid()) {
349 DCHECK(file_deletion_runner);
350 file_deletion_runner->PostTask(
351 FROM_HERE, base::Bind(&DestructFile, base::Passed(&file)));
352 }
353 }
354 FileCreationInfo::FileCreationInfo(FileCreationInfo&&) = default;
355 FileCreationInfo& FileCreationInfo::operator=(FileCreationInfo&&) = default;
356
357 BlobMemoryController::BlobMemoryController(
358 const base::FilePath& storage_directory,
359 scoped_refptr<base::TaskRunner> file_runner)
360 : file_paging_enabled_(file_runner.get() != nullptr),
361 blob_storage_dir_(storage_directory),
362 file_runner_(std::move(file_runner)),
363 recent_item_cache_(
364 base::MRUCache<uint64_t, ShareableBlobDataItem*>::NO_AUTO_EVICT),
365 file_task_factory_(this),
366 file_destruction_factory_(this) {}
367
368 BlobMemoryController::~BlobMemoryController() {}
369
370 void BlobMemoryController::DisableFilePaging() {
371 file_paging_enabled_ = false;
372 blob_memory_used_ += in_flight_memory_used_;
373 in_flight_memory_used_ = 0;
374 items_saving_to_disk_.clear();
375 pending_evictions_ = 0;
376 pending_memory_quota_total_size_ = 0;
377 recent_item_cache_.Clear();
378 recent_item_cache_bytes_ = 0;
379 file_runner_ = nullptr;
380
381 PendingMemoryQuotaTaskList old_memory_tasks;
382 PendingFileQuotaTaskList old_file_tasks;
383 std::swap(old_memory_tasks, pending_memory_quota_tasks_);
384 std::swap(old_file_tasks, pending_file_quota_tasks_);
385 // Kill all disk operation callbacks.
386 file_task_factory_.InvalidateWeakPtrs();
387
388 // Don't call the callbacks until we have a consistant state.
kinuko 2016/10/12 15:26:42 consistant -> consistent
dmurph 2016/10/13 00:39:30 Done.
389 for (const auto& memory_request : old_memory_tasks) {
390 memory_request->RunDoneCallback(false);
391 }
392 for (const auto& file_request : old_file_tasks) {
393 file_request->RunDoneCallback(false, false,
394 std::vector<FileCreationInfo>());
395 }
396 }
397
398 BlobMemoryController::Strategy BlobMemoryController::DetermineStrategy(
399 size_t preemptive_transported_bytes,
400 uint64_t total_transportation_bytes) const {
401 if (total_transportation_bytes == 0) {
402 return Strategy::NONE_NEEDED;
403 }
404 if (!CanReserveQuota(total_transportation_bytes)) {
405 return Strategy::TOO_LARGE;
406 }
407 // Handle the case where we have all the bytes preemptively transported, and
408 // we can also fit them.
409 if (preemptive_transported_bytes == total_transportation_bytes &&
410 pending_memory_quota_tasks_.empty() &&
411 preemptive_transported_bytes < GetAvailableMemoryForBlobs()) {
412 return Strategy::NONE_NEEDED;
413 }
414 if (file_paging_enabled_ &&
415 (total_transportation_bytes > limits_.max_blob_in_memory_space)) {
416 return Strategy::FILE;
417 }
418 if (total_transportation_bytes > limits_.max_ipc_memory_size) {
kinuko 2016/10/12 15:26:41 should this be total_transportation_bytes - preemp
dmurph 2016/10/13 00:39:31 No, we're doing all or nothing here. It's a more c
419 return Strategy::SHARED_MEMORY;
420 }
421 return Strategy::IPC;
422 }
423
424 bool BlobMemoryController::CanReserveQuota(uint64_t size) const {
425 // We check each size independently as a blob can't be constructed in both
426 // disk and memory.
427 return size <= GetAvailableMemoryForBlobs() ||
428 size <= GetAvailableFileSpaceForBlobs();
429 }
430
431 base::WeakPtr<QuotaAllocationTask> BlobMemoryController::ReserveMemoryQuota(
432 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_memory_items,
433 const MemoryQuotaRequestCallback& done_callback) {
434 base::CheckedNumeric<uint64_t> unsafe_total_bytes_needed = 0;
435 for (const scoped_refptr<ShareableBlobDataItem>& item :
michaeln 2016/10/11 20:55:23 could use const auto& here, might be rid of a line
dmurph 2016/10/13 00:39:30 Done.
436 unreserved_memory_items) {
437 DCHECK_EQ(ShareableBlobDataItem::QUOTA_NEEDED, item->state());
438 DCHECK(item->item()->type() == DataElement::TYPE_BYTES_DESCRIPTION ||
439 item->item()->type() == DataElement::TYPE_BYTES);
440 DCHECK(item->item()->length() > 0);
441 unsafe_total_bytes_needed += item->item()->length();
442 item->set_state(ShareableBlobDataItem::QUOTA_REQUESTED);
443 }
444
445 uint64_t total_bytes_needed = unsafe_total_bytes_needed.ValueOrDie();
446 if (total_bytes_needed == 0) {
447 done_callback.Run(true);
448 return base::WeakPtr<QuotaAllocationTask>();
kinuko 2016/10/12 15:26:41 nit: if memory_items is not empty we might be leav
dmurph 2016/10/13 00:39:30 We can't, as this would only hit if we don't have
michaeln 2016/10/14 01:53:26 i had noticed this too and it made me look closer,
dmurph 2016/10/14 23:31:46 Done.
449 }
450
451 // If we're currently waiting for blobs to page already, then we add
452 // ourselves to the end of the queue. Once paging is complete, we'll schedule
453 // more paging for any more pending blobs.
454 if (!pending_memory_quota_tasks_.empty()) {
455 return AppendMemoryTask(total_bytes_needed,
456 std::move(unreserved_memory_items), done_callback);
457 }
458
459 // Store right away if we can.
460 if (total_bytes_needed <= GetAvailableMemoryForBlobs()) {
461 // If we're past our blob memory limit, then schedule our paging.
michaeln 2016/10/11 20:55:24 this comment seems out of place, looks like it bel
dmurph 2016/10/13 00:39:30 Done.
462 blob_memory_used_ += total_bytes_needed;
463 for (const scoped_refptr<ShareableBlobDataItem>& item :
michaeln 2016/10/11 20:55:23 ditto const auto&
dmurph 2016/10/13 00:39:30 Done.
464 unreserved_memory_items) {
465 item->set_state(ShareableBlobDataItem::QUOTA_GRANTED);
466 }
467 if (file_paging_enabled_)
kinuko 2016/10/12 15:26:41 this check's not necessary (we're not doing it at
dmurph 2016/10/13 00:39:30 Done.
468 MaybeScheduleEvictionUntilSystemHealthy();
469 done_callback.Run(true);
470 return base::WeakPtr<QuotaAllocationTask>();
471 }
472
473 // Size is larger than available memory.
474 DCHECK(pending_memory_quota_tasks_.empty());
475 DCHECK_EQ(0u, pending_memory_quota_total_size_);
476
477 auto weak_ptr = AppendMemoryTask(
478 total_bytes_needed, std::move(unreserved_memory_items), done_callback);
479 MaybeScheduleEvictionUntilSystemHealthy();
480 return weak_ptr;
481 }
482
483 base::WeakPtr<QuotaAllocationTask> BlobMemoryController::ReserveFileQuota(
484 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_file_items,
485 const FileQuotaRequestCallback& done_callback) {
486 pending_file_quota_tasks_.push_back(base::MakeUnique<FileQuotaAllocationTask>(
487 this, std::move(unreserved_file_items), done_callback));
488 pending_file_quota_tasks_.back()->set_my_list_position(
489 --pending_file_quota_tasks_.end());
490 return pending_file_quota_tasks_.back()->weak_factory_.GetWeakPtr();
491 }
492
493 void BlobMemoryController::MaybeFreeMemoryQuotaForItems(
494 const std::vector<scoped_refptr<ShareableBlobDataItem>>& items) {
495 base::CheckedNumeric<size_t> memory_to_be_freed = 0;
496 std::unordered_set<uint64_t> visited_items;
497 for (const scoped_refptr<ShareableBlobDataItem>& item : items) {
498 if (!item->HasGrantedQuota())
499 continue;
500 // We only care about bytes items that don't have blobs referencing them,
501 // and we remove duplicates.
502 DataElement::Type type = item->item()->type();
503 if (!item->referencing_blobs().empty() ||
504 (type != DataElement::TYPE_BYTES &&
505 type != DataElement::TYPE_BYTES_DESCRIPTION) ||
506 base::ContainsKey(visited_items, item->item_id()))
507 continue;
508 visited_items.insert(item->item_id());
509 memory_to_be_freed += base::checked_cast<size_t>(item->item()->length());
510 RemoveItemInRecents(*item);
511 }
512 size_t checked_memory = memory_to_be_freed.ValueOrDie();
513 if (checked_memory != 0) {
514 DCHECK_GE(blob_memory_used_, checked_memory);
515 blob_memory_used_ -= checked_memory;
516 MaybeGrantPendingQuotaRequests();
517 }
518 }
519
520 void BlobMemoryController::ForceFreeMemoryQuotaForItem(
521 const scoped_refptr<ShareableBlobDataItem>& item) {
522 CHECK(item->HasGrantedQuota());
523 size_t size = base::checked_cast<size_t>(item->item()->length());
524 DCHECK_GE(blob_memory_used_, size);
525 blob_memory_used_ -= size;
526 RemoveItemInRecents(*item);
527 MaybeGrantPendingQuotaRequests();
528 }
529
530 void BlobMemoryController::NotifyMemoryItemUsed(ShareableBlobDataItem* item) {
531 DCHECK_EQ(DataElement::TYPE_BYTES, item->item()->type());
532 DCHECK_EQ(ShareableBlobDataItem::POPULATED_WITH_QUOTA, item->state());
533 // We don't want to re-add the item if we're currently paging it to disk.
534 if (items_saving_to_disk_.find(item->item_id()) !=
535 items_saving_to_disk_.end())
536 return;
537 auto iterator = recent_item_cache_.Get(item->item_id());
538 if (iterator == recent_item_cache_.end()) {
539 recent_item_cache_bytes_ += static_cast<size_t>(item->item()->length());
michaeln 2016/10/11 20:55:24 nit: i think the name of the "recent_item" data me
dmurph 2016/10/13 00:39:30 Done.
540 recent_item_cache_.Put(item->item_id(), item);
541 MaybeScheduleEvictionUntilSystemHealthy();
542 }
543 }
544
545 base::WeakPtr<QuotaAllocationTask> BlobMemoryController::AppendMemoryTask(
546 uint64_t total_bytes_needed,
547 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_memory_items,
548 const MemoryQuotaRequestCallback& done_callback) {
549 DCHECK(file_paging_enabled_)
550 << "Caller tried to reserve memory when CanReserveQuota("
551 << total_bytes_needed << ") would have returned false.";
552
553 pending_memory_quota_total_size_ += total_bytes_needed;
554 pending_memory_quota_tasks_.push_back(
555 base::MakeUnique<MemoryQuotaAllocationTask>(
556 this, total_bytes_needed, std::move(unreserved_memory_items),
557 done_callback));
558 pending_memory_quota_tasks_.back()->set_my_list_position(
559 --pending_memory_quota_tasks_.end());
560
561 return pending_memory_quota_tasks_.back()->weak_factory_.GetWeakPtr();
562 }
563
564 void BlobMemoryController::RemoveItemInRecents(
565 const ShareableBlobDataItem& item) {
566 auto iterator = recent_item_cache_.Get(item.item_id());
567 if (iterator == recent_item_cache_.end())
568 return;
569 size_t size = base::checked_cast<size_t>(item.item()->length());
570 DCHECK_GE(recent_item_cache_bytes_, size);
571 recent_item_cache_bytes_ -= size;
572 recent_item_cache_.Erase(iterator);
573 }
574
575 void BlobMemoryController::MaybeGrantPendingQuotaRequests() {
michaeln 2016/10/11 20:55:24 since it only deals with memory requests, MaybeGra
dmurph 2016/10/13 00:39:30 Done.
576 while (!pending_memory_quota_tasks_.empty() &&
577 limits_.max_blob_in_memory_space - blob_memory_used_ >=
578 pending_memory_quota_tasks_.front()->allocation_size()) {
579 std::unique_ptr<MemoryQuotaAllocationTask> memory_task =
580 std::move(pending_memory_quota_tasks_.front());
581 pending_memory_quota_tasks_.pop_front();
582 size_t request_size = memory_task->allocation_size();
583 pending_memory_quota_total_size_ -= request_size;
584 blob_memory_used_ += request_size;
585 memory_task->RunDoneCallback(true);
586 }
587 RecordTracingCounters();
588 }
589
590 size_t BlobMemoryController::CollectItemsForEviction(
591 std::vector<scoped_refptr<ShareableBlobDataItem>>* output) {
592 base::CheckedNumeric<size_t> total_items_size = 0;
593 // Process the recent item list and remove items until we have at least
kinuko 2016/10/12 15:26:41 the comment isn't finishing
dmurph 2016/10/13 00:39:30 Done.
594 while (total_items_size.ValueOrDie() < limits_.min_page_file_size &&
595 !recent_item_cache_.empty()) {
596 auto iterator = --recent_item_cache_.end();
597 ShareableBlobDataItem* item = iterator->second;
598 DCHECK(item);
599 DCHECK_EQ(item->item()->type(), DataElement::TYPE_BYTES);
600 recent_item_cache_.Erase(iterator);
601 size_t size = base::checked_cast<size_t>(item->item()->length());
602 recent_item_cache_bytes_ -= size;
603 total_items_size += size;
604 output->push_back(make_scoped_refptr(item));
605 }
606 return total_items_size.ValueOrDie();
607 }
608
609 void BlobMemoryController::MaybeScheduleEvictionUntilSystemHealthy() {
610 // Don't do eviction when others are happening, as we don't change our
611 // pending_memory_quota_total_size_ value until after the paging files have
612 // been written.
613 if (pending_evictions_ != 0 || !file_paging_enabled_)
614 return;
615
616 // We try to page items to disk until our current system size + requested
617 // memory is below our size limit.
618 while (pending_memory_quota_total_size_ + blob_memory_used_ >
619 limits_.max_blob_in_memory_space) {
620 // We only page when we have enough items to fill a whole page file.
621 if (recent_item_cache_bytes_ < limits_.min_page_file_size)
622 break;
623 DCHECK_LE(limits_.min_page_file_size,
624 static_cast<uint64_t>(blob_memory_used_));
625
626 std::vector<scoped_refptr<ShareableBlobDataItem>> items_to_swap;
627 size_t total_items_size = CollectItemsForEviction(&items_to_swap);
628 if (total_items_size == 0)
629 break;
630
631 std::vector<DataElement*> items_for_disk;
kinuko 2016/10/12 15:26:41 nit: items_for_disk -> items_for_paging ?
dmurph 2016/10/13 00:39:30 Done.
632 for (const auto& shared_blob_item : items_to_swap) {
633 items_saving_to_disk_.insert(shared_blob_item->item_id());
634 items_for_disk.push_back(shared_blob_item->item()->data_element_ptr());
635 }
636
637 // Update our bookkeeping.
638 pending_evictions_++;
639 disk_used_ += total_items_size;
640 DCHECK_GE(blob_memory_used_, total_items_size);
641 blob_memory_used_ -= total_items_size;
642 in_flight_memory_used_ += total_items_size;
643
644 // Create our file reference.
645 scoped_refptr<ShareableFileReference> file_reference =
646 ShareableFileReference::GetOrCreate(
647 GenerateNextPageFileName(),
648 ShareableFileReference::DELETE_ON_FINAL_RELEASE,
649 file_runner_.get());
650 // Add the release callback so we decrement our disk usage on file deletion.
651 file_reference->AddFinalReleaseCallback(
652 base::Bind(&BlobMemoryController::OnBlobFileDelete,
653 file_destruction_factory_.GetWeakPtr(), total_items_size));
654
655 // Post the file writing task.
656 base::PostTaskAndReplyWithResult(
657 file_runner_.get(), FROM_HERE,
658 base::Bind(&CreateFileAndWriteItems, blob_storage_dir_,
659 file_reference->path(), file_runner_,
660 base::Passed(&items_for_disk), total_items_size),
661 base::Bind(&BlobMemoryController::OnEvictionComplete,
662 file_task_factory_.GetWeakPtr(),
663 base::Passed(&file_reference), base::Passed(&items_to_swap),
664 total_items_size));
665 }
666 RecordTracingCounters();
667 }
668
669 void BlobMemoryController::OnEvictionComplete(
670 scoped_refptr<ShareableFileReference> file_reference,
671 std::vector<scoped_refptr<ShareableBlobDataItem>> items,
672 size_t total_items_size,
673 FileCreationInfo result) {
674 if (!file_paging_enabled_)
675 return;
676
677 if (result.error != File::FILE_OK) {
678 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingError", -result.error,
679 -File::FILE_ERROR_MAX);
680 DisableFilePaging();
681 return;
682 }
683 result.file_reference = std::move(file_reference);
kinuko 2016/10/12 15:26:42 do we need this line?
dmurph 2016/10/13 00:39:30 Ah, yeah I guess not.
684
685 DCHECK_LT(0u, pending_evictions_);
686 pending_evictions_--;
687
688 // Switch item from memory to the new file.
689 uint64_t offset = 0;
690 for (const scoped_refptr<ShareableBlobDataItem>& shareable_item : items) {
691 scoped_refptr<BlobDataItem> new_item(new BlobDataItem(
692 base::WrapUnique(new DataElement()), result.file_reference));
693 new_item->data_element_ptr()->SetToFilePathRange(
694 result.file_reference->path(), offset, shareable_item->item()->length(),
695 result.last_modified);
696 shareable_item->set_item(new_item);
697 items_saving_to_disk_.erase(shareable_item->item_id());
698 offset += shareable_item->item()->length();
699 }
700 in_flight_memory_used_ -= total_items_size;
701
702 // We want callback on blobs up to the amount we've freed.
703 MaybeGrantPendingQuotaRequests();
704
705 // If we still have more blobs waiting and we're not waiting on more paging
706 // operations, schedule more.
707 MaybeScheduleEvictionUntilSystemHealthy();
708 }
709
710 FilePath BlobMemoryController::GenerateNextPageFileName() {
711 std::string file_name = base::Uint64ToString(current_file_num_++);
712 return blob_storage_dir_.Append(file_name);
713 }
714
715 void BlobMemoryController::RecordTracingCounters() const {
716 TRACE_COUNTER2("Blob", "MemoryUsage", "RegularStorage", blob_memory_used_,
717 "InFlightToDisk", in_flight_memory_used_);
718 TRACE_COUNTER1("Blob", "DiskUsage", disk_used_);
719 TRACE_COUNTER1("Blob", "TranfersPendingOnDisk",
720 pending_memory_quota_tasks_.size());
721 TRACE_COUNTER1("Blob", "TranfersBytesPendingOnDisk",
722 pending_memory_quota_total_size_);
723 }
724
725 size_t BlobMemoryController::GetAvailableMemoryForBlobs() const {
726 if (limits_.total_memory_space() < memory_usage())
727 return 0;
728 return limits_.total_memory_space() - memory_usage();
729 }
730
731 uint64_t BlobMemoryController::GetAvailableFileSpaceForBlobs() const {
732 if (!file_paging_enabled_)
733 return 0;
734 // Sometimes we're only paging part of what we need for the new blob, so add
735 // the rest of the size we need into our disk usage if this is the case.
736 uint64_t total_disk_used = disk_used_;
737 if (in_flight_memory_used_ < pending_memory_quota_total_size_) {
738 total_disk_used +=
739 pending_memory_quota_total_size_ - in_flight_memory_used_;
740 }
741 if (limits_.max_blob_disk_space < total_disk_used)
742 return 0;
743 return limits_.max_blob_disk_space - total_disk_used;
744 }
745
746 void BlobMemoryController::OnBlobFileDelete(uint64_t size,
747 const FilePath& path) {
748 DCHECK_LE(size, disk_used_);
749 disk_used_ -= size;
750 }
751
752 } // namespace storage
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698