OLD | NEW |
---|---|
(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/location.h" | |
14 #include "base/memory/ptr_util.h" | |
15 #include "base/metrics/histogram_macros.h" | |
16 #include "base/numerics/safe_conversions.h" | |
17 #include "base/numerics/safe_math.h" | |
18 #include "base/single_thread_task_runner.h" | |
19 #include "base/single_thread_task_runner.h" | |
20 #include "base/strings/string_number_conversions.h" | |
21 #include "base/task_runner.h" | |
22 #include "base/task_runner_util.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_builder.h" | |
27 #include "storage/browser/blob/blob_data_item.h" | |
28 #include "storage/browser/blob/shareable_blob_data_item.h" | |
29 #include "storage/browser/blob/shareable_file_reference.h" | |
30 #include "storage/common/data_element.h" | |
31 | |
32 using base::File; | |
33 using base::FilePath; | |
34 using FileCreationInfo = storage::BlobMemoryController::FileCreationInfo; | |
35 | |
36 namespace storage { | |
37 namespace { | |
38 | |
39 // Creates a file in the given directory w/ the given filename and size. | |
40 std::vector<BlobMemoryController::FileCreationInfo> CreateFiles( | |
41 std::vector<scoped_refptr<ShareableFileReference>> file_references) { | |
42 LOG(ERROR) << "creating files for renderer"; | |
43 std::vector<BlobMemoryController::FileCreationInfo> result; | |
44 | |
45 for (scoped_refptr<ShareableFileReference>& file_ref : file_references) { | |
46 result.push_back(BlobMemoryController::FileCreationInfo()); | |
47 BlobMemoryController::FileCreationInfo& creation_info = result.back(); | |
48 // Try to open our file. | |
49 File file(file_ref->path(), File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE); | |
50 creation_info.file_reference = std::move(file_ref); | |
51 creation_info.error = file.error_details(); | |
52 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.TransportFileCreate", | |
53 -creation_info.error, -File::FILE_ERROR_MAX); | |
54 if (creation_info.error != File::FILE_OK) | |
55 return std::vector<BlobMemoryController::FileCreationInfo>(); | |
56 | |
57 // Grab the file info to get the "last modified" time and store the file. | |
58 File::Info file_info; | |
59 bool success = file.GetInfo(&file_info); | |
60 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.TransportFileInfoSuccess", success); | |
61 creation_info.error = success ? File::FILE_OK : File::FILE_ERROR_FAILED; | |
62 if (!success) | |
63 return std::vector<BlobMemoryController::FileCreationInfo>(); | |
64 creation_info.file = std::move(file); | |
65 } | |
66 LOG(ERROR) << "Done! Returning " << result.size() << " files."; | |
67 return result; | |
68 } | |
69 | |
70 BlobMemoryController::FileCreationInfo WriteItemsToFile( | |
71 std::vector<scoped_refptr<ShareableBlobDataItem>>* items, | |
72 size_t total_size_bytes, | |
73 scoped_refptr<ShareableFileReference> file_reference) { | |
michaeln
2016/08/23 01:31:54
ShareableFileRefs are not thread-safe so this has
| |
74 DCHECK_NE(0u, total_size_bytes); | |
75 LOG(ERROR) << "writing to file!"; | |
76 UMA_HISTOGRAM_MEMORY_KB("Storage.Blob.PageFileSize", total_size_bytes / 1024); | |
77 | |
78 // Create our file. | |
79 BlobMemoryController::FileCreationInfo creation_info; | |
80 File file(file_reference->path(), | |
81 File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE); | |
82 creation_info.file_reference = std::move(file_reference); | |
83 creation_info.error = file.error_details(); | |
84 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PageFileCreate", -creation_info.error, | |
85 -File::FILE_ERROR_MAX); | |
86 if (creation_info.error != File::FILE_OK) | |
87 return creation_info; | |
88 | |
89 // Write data. | |
90 file.SetLength(total_size_bytes); | |
91 int bytes_written = 0; | |
92 for (const auto& refptr : *items) { | |
93 const DataElement& element = refptr->item()->data_element(); | |
94 DCHECK_EQ(DataElement::TYPE_BYTES, element.type()); | |
95 size_t length = base::checked_cast<size_t>(element.length()); | |
96 size_t bytes_left = length; | |
97 while (bytes_left > 0) { | |
98 bytes_written = | |
99 file.WriteAtCurrentPos(element.bytes() + (length - bytes_left), | |
100 base::saturated_cast<int>(bytes_left)); | |
101 if (bytes_written < 0) | |
102 break; | |
103 DCHECK_LE(static_cast<size_t>(bytes_written), bytes_left); | |
104 bytes_left -= bytes_written; | |
105 } | |
106 if (bytes_written < 0) | |
107 break; | |
108 } | |
109 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.PageFileWriteSuccess", bytes_written > 0); | |
110 | |
111 // Grab our modification time and create our SharedFileReference to manage the | |
112 // lifetime of the file. | |
113 File::Info info; | |
114 bool success = file.GetInfo(&info); | |
115 UMA_HISTOGRAM_BOOLEAN("Storage.Blob.PageFileInfoSuccess", success); | |
116 creation_info.error = | |
117 bytes_written < 0 || !success ? File::FILE_ERROR_FAILED : File::FILE_OK; | |
118 creation_info.last_modified = info.last_modified; | |
119 return creation_info; | |
120 } | |
121 | |
122 // Here so we can destruct files on the correct thread if the user cancels. | |
123 void DestructFiles(std::vector<BlobMemoryController::FileCreationInfo> files) {} | |
124 | |
125 } // namespace | |
126 | |
127 BlobMemoryController::FileCreationInfo::FileCreationInfo() {} | |
128 | |
129 BlobMemoryController::FileCreationInfo::~FileCreationInfo() {} | |
130 | |
131 FileCreationInfo::FileCreationInfo(FileCreationInfo&&) = default; | |
132 FileCreationInfo& FileCreationInfo::operator=(FileCreationInfo&&) = default; | |
133 | |
134 BlobMemoryController::PendingQuotaEntry::PendingQuotaEntry( | |
135 uint64_t disk_quota_entry) | |
136 : disk_quota_entry(disk_quota_entry) {} | |
137 BlobMemoryController::PendingQuotaEntry::PendingQuotaEntry( | |
138 PendingBlobConstructionList::iterator memory_quota_entry) | |
139 : memory_quota_entry(memory_quota_entry) {} | |
140 BlobMemoryController::PendingQuotaEntry::PendingQuotaEntry( | |
141 const PendingQuotaEntry& other) = default; | |
142 | |
143 BlobMemoryController::PendingQuotaEntry::~PendingQuotaEntry() {} | |
144 | |
145 BlobMemoryController::BlobMemoryController() | |
146 : recent_item_cache_( | |
147 base::MRUCache<uint64_t, ShareableBlobDataItem*>::NO_AUTO_EVICT), | |
148 ptr_factory_(this) {} | |
149 | |
150 BlobMemoryController::~BlobMemoryController() {} | |
151 | |
152 void BlobMemoryController::EnableDisk( | |
153 const base::FilePath& storage_directory, | |
154 scoped_refptr<base::TaskRunner> file_runner) { | |
155 LOG(ERROR) << "enabling disk"; | |
156 DCHECK(!storage_directory.empty()); | |
157 file_runner_ = std::move(file_runner); | |
158 blob_storage_dir_ = storage_directory; | |
159 disk_enabled_ = true; | |
160 } | |
161 | |
162 void BlobMemoryController::DisableDisk() { | |
163 disk_enabled_ = false; | |
164 blob_memory_used_ += in_flight_memory_used_; | |
165 in_flight_memory_used_ = 0; | |
166 pending_file_opens_.clear(); | |
167 items_saving_to_disk_.clear(); | |
168 for (const auto& size_callback_pair : blobs_waiting_for_paging_) | |
169 size_callback_pair.second.Run(false, std::vector<FileCreationInfo>()); | |
170 pending_pagings_ = 0; | |
171 blobs_waiting_for_paging_.clear(); | |
172 blobs_waiting_for_paging_size_ = 0; | |
173 recent_item_cache_.Clear(); | |
174 recent_item_cache_bytes_ = 0; | |
175 RecordTracingCounters(); | |
176 } | |
177 | |
178 BlobMemoryController::MemoryStrategyResult | |
179 BlobMemoryController::DecideBlobTransportationMemoryStrategy( | |
180 size_t shortcut_bytes, | |
181 uint64_t total_transportation_bytes) const { | |
182 // Step 1: Handle case where we have no memory to transport. | |
michaeln
2016/08/23 01:31:54
seems like the the step n comments in this method
| |
183 if (total_transportation_bytes == 0) { | |
184 return MemoryStrategyResult::NONE_NEEDED; | |
185 } | |
186 // Step 2: Check if we have enough memory to store the blob. | |
187 // We check both individually, as when something is stored straight to disk | |
Marijn Kruisselbrink
2016/08/05 23:23:54
Not sure what "both" refers to here? You only chec
dmurph
2016/08/19 00:18:33
Done.
| |
188 // we only use disk. So it must fit in the available disk space by itself. | |
189 if (!CanFitInSystem(total_transportation_bytes)) { | |
190 return MemoryStrategyResult::TOO_LARGE; | |
191 } | |
192 // From here on, we know we can fit the blob in memory or on disk. | |
193 // Step 3: Decide if we're using the shortcut method. | |
194 if (shortcut_bytes == total_transportation_bytes && | |
195 blobs_waiting_for_paging_.empty() && | |
196 shortcut_bytes < GetAvailableMemoryForBlobs()) { | |
197 return MemoryStrategyResult::NONE_NEEDED; | |
198 } | |
199 // Step 4: Decide if we're going straight to disk. | |
200 if (disk_enabled_ && | |
201 (total_transportation_bytes > max_blob_in_memory_size_)) { | |
michaeln
2016/08/23 01:31:54
should this take shortcut_bytes into account? tota
| |
202 return MemoryStrategyResult::FILE; | |
203 } | |
204 // Step 5: Decide if we're using shared memory. | |
205 if (total_transportation_bytes > max_ipc_memory_size_) { | |
206 return MemoryStrategyResult::SHARED_MEMORY; | |
207 } | |
208 // Step 6: We can fit in IPC. | |
209 return MemoryStrategyResult::IPC; | |
210 } | |
211 | |
212 bool BlobMemoryController::CanFitInSystem(uint64_t size) const { | |
213 // We check each size independently as a blob can't be constructed in both | |
214 // disk and memory. | |
215 return size <= GetAvailableMemoryForBlobs() || | |
216 size <= GetAvailableDiskSpaceForBlobs(); | |
217 } | |
218 | |
219 base::Optional<BlobMemoryController::PendingQuotaEntry> | |
220 BlobMemoryController::ReserveQuotaForItems( | |
221 std::vector<ShareableBlobDataItem*> items, | |
222 const QuotaRequestCallback& success_callback) { | |
223 bool files = false; | |
Marijn Kruisselbrink
2016/08/05 23:23:55
What is this |files| thing, and what is it used fo
dmurph
2016/08/19 00:18:33
Removed.
| |
224 uint64_t total_files_size_needed = 0; | |
225 uint64_t total_bytes_needed = 0; | |
226 base::SmallMap<std::map<std::string, uint64_t>> file_sizes; | |
227 std::vector<scoped_refptr<ShareableBlobDataItem>> pending_items; | |
228 for (ShareableBlobDataItem* item : items) { | |
229 if (item->state() != ShareableBlobDataItem::QUOTA_NEEDED) | |
230 continue; | |
231 const DataElement& element = item->item()->data_element(); | |
232 switch (item->item()->type()) { | |
233 case DataElement::TYPE_BYTES_DESCRIPTION: | |
234 case DataElement::TYPE_BYTES: { | |
235 DCHECK_EQ(0ull, total_files_size_needed) | |
236 << "You cannot reserve quota for both files and data"; | |
237 total_bytes_needed += element.length(); | |
238 break; | |
239 } | |
240 case DataElement::TYPE_FILE: { | |
241 DCHECK_EQ(0ull, total_bytes_needed) | |
242 << "You cannot reserve quota for both files and data"; | |
243 DCHECK(BlobDataBuilder::IsTemporaryFileItem(element)); | |
244 files = true; | |
245 std::string file_id = BlobDataBuilder::GetTemporaryFileID(element); | |
246 auto it = file_sizes.find(file_id); | |
247 if (it != file_sizes.end()) { | |
248 it->second = | |
249 std::max(it->second, element.offset() + element.length()); | |
250 } else { | |
251 file_sizes[file_id] = element.offset() + element.length(); | |
252 } | |
253 total_files_size_needed += element.length(); | |
254 break; | |
255 } | |
256 case DataElement::TYPE_FILE_FILESYSTEM: | |
257 case DataElement::TYPE_BLOB: | |
258 case DataElement::TYPE_UNKNOWN: | |
259 case DataElement::TYPE_DISK_CACHE_ENTRY: | |
260 NOTREACHED() << "We only need quota for temporary file and data items"; | |
261 break; | |
262 } | |
263 pending_items.push_back(make_scoped_refptr(item)); | |
264 item->state_ = ShareableBlobDataItem::QUOTA_REQUESTED; | |
265 } | |
266 | |
267 if (total_files_size_needed > 0) { | |
268 DCHECK_LE(total_files_size_needed, GetAvailableDiskSpaceForBlobs()); | |
269 disk_used_ += total_files_size_needed; | |
270 std::vector<scoped_refptr<ShareableFileReference>> file_refs; | |
271 std::vector<uint64_t> sizes; | |
272 for (const auto& size_pair : file_sizes) { | |
273 std::string file_name = base::Uint64ToString(current_file_num_++); | |
274 file_refs.push_back(ShareableFileReference::GetOrCreate( | |
275 blob_storage_dir_.Append(file_name), | |
276 ShareableFileReference::DELETE_ON_FINAL_RELEASE, file_runner_.get())); | |
277 sizes.push_back(size_pair.second); | |
278 } | |
279 | |
280 uint64_t disk_quota_entry = ++curr_disk_save_entry_; | |
281 if (disk_quota_entry == kInvalidDiskQuotaEntry) { | |
282 disk_quota_entry = ++curr_disk_save_entry_; | |
283 } | |
284 pending_file_opens_.insert(disk_quota_entry); | |
285 base::PostTaskAndReplyWithResult( | |
286 file_runner_.get(), FROM_HERE, | |
287 base::Bind(&CreateFiles, base::Passed(&file_refs)), | |
288 base::Bind(&BlobMemoryController::OnCreateFiles, | |
289 ptr_factory_.GetWeakPtr(), base::Passed(&sizes), | |
290 base::Passed(&pending_items), disk_quota_entry, | |
291 success_callback)); | |
292 RecordTracingCounters(); | |
293 return PendingQuotaEntry(disk_quota_entry); | |
294 } | |
295 | |
296 if (total_bytes_needed == 0) { | |
297 LOG(ERROR) << "Dont' need bytes"; | |
298 success_callback.Run(true, | |
299 std::vector<BlobMemoryController::FileCreationInfo>()); | |
300 return base::nullopt; | |
301 } | |
302 | |
303 if (!disk_enabled_) { | |
304 LOG(ERROR) << "Yes, " << total_bytes_needed << " can fit in memory now."; | |
305 blob_memory_used_ += total_bytes_needed; | |
306 for (ShareableBlobDataItem* item : items) { | |
307 item->state_ = ShareableBlobDataItem::QUOTA_GRANTED; | |
308 } | |
309 success_callback.Run(true, | |
310 std::vector<BlobMemoryController::FileCreationInfo>()); | |
311 return base::nullopt; | |
312 } | |
313 | |
314 // If we're currently waiting for blobs to page already, then we add | |
315 // ourselves to the end of the queue. Once paging is complete, we'll schedule | |
316 // more paging for any more pending blobs. | |
317 if (!blobs_waiting_for_paging_.empty()) { | |
318 LOG(ERROR) << "putting memory request " << total_bytes_needed | |
319 << " in queue."; | |
320 blobs_waiting_for_paging_.push_back(std::make_pair( | |
321 total_bytes_needed, | |
322 base::Bind(&BlobMemoryController::SetStateQuotaGrantedAndCallback, | |
323 ptr_factory_.GetWeakPtr(), base::Passed(&pending_items), | |
324 success_callback))); | |
325 blobs_waiting_for_paging_size_ += total_bytes_needed; | |
326 base::Optional<BlobMemoryController::PendingQuotaEntry> entry = | |
327 PendingQuotaEntry(--blobs_waiting_for_paging_.end()); | |
328 return entry; | |
329 } | |
330 | |
331 // Store right away if we can. | |
332 if (total_bytes_needed <= GetAvailableMemoryForBlobs()) { | |
333 // If we're past our blob memory limit, then schedule our paging. | |
334 LOG(ERROR) << "Yes, " << total_bytes_needed << " can fit in memory now."; | |
335 blob_memory_used_ += total_bytes_needed; | |
336 for (ShareableBlobDataItem* item : items) { | |
337 item->state_ = ShareableBlobDataItem::QUOTA_GRANTED; | |
338 } | |
339 MaybeSchedulePagingUntilSystemHealthy(); | |
340 success_callback.Run(true, | |
341 std::vector<BlobMemoryController::FileCreationInfo>()); | |
342 return base::nullopt; | |
343 } | |
344 | |
345 // This means we're too big for memory. | |
346 LOG(ERROR) << "waiting until " << total_bytes_needed << " can fit."; | |
347 DCHECK(blobs_waiting_for_paging_.empty()); | |
348 DCHECK_EQ(0u, blobs_waiting_for_paging_size_); | |
349 blobs_waiting_for_paging_.push_back(std::make_pair( | |
350 total_bytes_needed, | |
351 base::Bind(&BlobMemoryController::SetStateQuotaGrantedAndCallback, | |
352 ptr_factory_.GetWeakPtr(), base::Passed(&pending_items), | |
353 success_callback))); | |
354 blobs_waiting_for_paging_size_ = total_bytes_needed; | |
355 base::Optional<BlobMemoryController::PendingQuotaEntry> entry = | |
356 PendingQuotaEntry(--blobs_waiting_for_paging_.end()); | |
357 LOG(ERROR) << "Scheduling paging on first item too big"; | |
358 MaybeSchedulePagingUntilSystemHealthy(); | |
359 return entry; | |
360 } | |
361 | |
362 void BlobMemoryController::CancelQuotaReservation( | |
363 const BlobMemoryController::PendingQuotaEntry& entry) { | |
364 if (entry.disk_quota_entry == kInvalidDiskQuotaEntry) { | |
365 if (entry.memory_quota_entry == blobs_waiting_for_paging_.end()) | |
Marijn Kruisselbrink
2016/08/05 23:23:54
Under what circumstances would this comparison be
dmurph
2016/08/19 00:18:33
Simplified this by separating out memory and file
| |
366 return; | |
367 const std::pair<size_t, QuotaRequestCallback> pair = | |
Marijn Kruisselbrink
2016/08/05 23:23:54
Not sure if this two-line variable declaration gai
dmurph
2016/08/19 00:18:33
Done.
| |
368 *entry.memory_quota_entry; | |
369 blobs_waiting_for_paging_size_ -= pair.first; | |
370 blobs_waiting_for_paging_.erase(entry.memory_quota_entry); | |
371 return; | |
372 } | |
373 pending_file_opens_.erase(entry.disk_quota_entry); | |
374 } | |
375 | |
376 void BlobMemoryController::MaybeFreeQuotaForItems( | |
377 const std::vector<scoped_refptr<ShareableBlobDataItem>>& items) { | |
378 uint64_t total_memory_freeing = 0; | |
379 base::hash_set<uint64_t> visited_items; | |
Marijn Kruisselbrink
2016/08/05 23:23:54
base::hash_set is deprecated (and is just an alias
dmurph
2016/08/19 00:18:33
Done.
| |
380 for (const scoped_refptr<ShareableBlobDataItem>& item : items) { | |
381 switch (item->state()) { | |
Marijn Kruisselbrink
2016/08/05 23:23:54
It might help make it more immediately obvious wha
dmurph
2016/08/19 00:18:33
Simplified by requiring that the items are all QUO
| |
382 case ShareableBlobDataItem::QUOTA_NEEDED: | |
383 case ShareableBlobDataItem::QUOTA_REQUESTED: | |
384 case ShareableBlobDataItem::POPULATED_WITHOUT_QUOTA: | |
385 continue; | |
386 case ShareableBlobDataItem::QUOTA_GRANTED: | |
387 case ShareableBlobDataItem::POPULATED_WITH_QUOTA: | |
388 break; | |
389 } | |
390 // We only care about bytes items that don't have blobs referencing them, | |
391 // and we remove duplicates. | |
392 DataElement::Type type = item->item()->type(); | |
393 if (!item->referencing_blobs().empty() || | |
394 (type != DataElement::TYPE_BYTES && | |
395 type != DataElement::TYPE_BYTES_DESCRIPTION) || | |
396 visited_items.find(item->item_id()) != visited_items.end()) | |
Marijn Kruisselbrink
2016/08/05 23:23:54
nit: there is a ContainsKey method in base/stl_uti
dmurph
2016/08/19 00:18:33
Done.
| |
397 continue; | |
398 visited_items.insert(item->item_id()); | |
399 total_memory_freeing += item->item()->length(); | |
400 } | |
401 if (total_memory_freeing != 0) { | |
402 DCHECK_GE(blob_memory_used_, total_memory_freeing); | |
403 LOG(ERROR) << "Freeing memory " << total_memory_freeing; | |
404 blob_memory_used_ -= total_memory_freeing; | |
405 MaybeGrantPendingQuotaRequests(); | |
406 } | |
407 } | |
408 | |
409 void BlobMemoryController::FreeQuotaForPagedItemReference( | |
410 const scoped_refptr<ShareableBlobDataItem>& item) { | |
411 CHECK_EQ(item->state(), ShareableBlobDataItem::QUOTA_GRANTED); | |
412 CHECK_EQ(item->item()->type(), DataElement::TYPE_BYTES_DESCRIPTION); | |
413 LOG(ERROR) << "Freeing memory " << item->item()->length(); | |
414 blob_memory_used_ -= item->item()->length(); | |
415 MaybeGrantPendingQuotaRequests(); | |
416 } | |
417 | |
418 void BlobMemoryController::UpdateBlobItemInRecents( | |
419 ShareableBlobDataItem* item) { | |
420 DCHECK_EQ(DataElement::TYPE_BYTES, item->item()->type()); | |
421 DCHECK_EQ(ShareableBlobDataItem::POPULATED_WITH_QUOTA, item->state()); | |
422 // We don't want to re-add the item if we're currently paging it to disk. | |
423 if (items_saving_to_disk_.find(item->item_id()) != | |
424 items_saving_to_disk_.end()) | |
425 return; | |
426 auto iterator = recent_item_cache_.Get(item->item_id()); | |
427 if (iterator == recent_item_cache_.end()) { | |
428 recent_item_cache_bytes_ += static_cast<size_t>(item->item()->length()); | |
429 recent_item_cache_.Put(item->item_id(), item); | |
430 MaybeSchedulePagingUntilSystemHealthy(); | |
431 } | |
432 } | |
433 | |
434 void BlobMemoryController::RemoveBlobItemInRecents( | |
435 const ShareableBlobDataItem& item) { | |
436 auto iterator = recent_item_cache_.Get(item.item_id()); | |
437 if (iterator != recent_item_cache_.end()) { | |
438 size_t size = static_cast<size_t>(item.item()->length()); | |
439 DCHECK_GE(recent_item_cache_bytes_, size); | |
440 recent_item_cache_bytes_ -= size; | |
441 recent_item_cache_.Erase(iterator); | |
442 } | |
443 } | |
444 | |
445 void BlobMemoryController::SetStateQuotaGrantedAndCallback( | |
446 std::vector<scoped_refptr<ShareableBlobDataItem>> items, | |
447 const BlobMemoryController::QuotaRequestCallback& final_callback, | |
448 bool success, | |
449 std::vector<FileCreationInfo> files) { | |
450 if (!success) { | |
451 final_callback.Run(false, std::move(files)); | |
452 return; | |
453 } | |
454 for (const auto& item : items) { | |
455 item->state_ = ShareableBlobDataItem::QUOTA_GRANTED; | |
456 } | |
457 final_callback.Run(true, std::move(files)); | |
458 return; | |
459 } | |
460 | |
461 void BlobMemoryController::OnCreateFiles( | |
462 std::vector<uint64_t> file_sizes, | |
463 std::vector<scoped_refptr<ShareableBlobDataItem>> pending_items, | |
464 uint64_t disk_quota_entry, | |
465 const QuotaRequestCallback& file_callback, | |
466 std::vector<FileCreationInfo> result) { | |
467 if (result.empty()) { | |
468 LOG(ERROR) << "Error creating files"; | |
469 for (uint64_t size : file_sizes) { | |
470 disk_used_ -= size; | |
471 } | |
472 file_callback.Run(false, std::vector<FileCreationInfo>()); | |
473 DisableDisk(); | |
474 return; | |
475 } | |
476 if (pending_file_opens_.find(disk_quota_entry) == pending_file_opens_.end()) { | |
Marijn Kruisselbrink
2016/08/05 23:23:54
nit: rather than first checking if the value exist
dmurph
2016/08/19 00:18:33
Done.
| |
477 // The user cancelled this operation. | |
478 LOG(ERROR) << "user cancelled file write."; | |
479 file_runner_->PostTask(FROM_HERE, | |
480 base::Bind(&DestructFiles, base::Passed(&result))); | |
481 } | |
482 pending_file_opens_.erase(disk_quota_entry); | |
483 DCHECK_EQ(file_sizes.size(), result.size()); | |
484 for (size_t i = 0; i < result.size(); i++) { | |
485 result[i].file_reference->AddFinalReleaseCallback( | |
486 base::Bind(&BlobMemoryController::OnBlobFileDelete, | |
487 ptr_factory_.GetWeakPtr(), file_sizes[i])); | |
488 } | |
489 for (const auto& item : pending_items) { | |
490 item->state_ = ShareableBlobDataItem::QUOTA_GRANTED; | |
491 } | |
492 LOG(ERROR) << "Created " << result.size() << " files!"; | |
493 file_callback.Run(true, std::move(result)); | |
494 } | |
495 | |
496 void BlobMemoryController::MaybeGrantPendingQuotaRequests() { | |
497 size_t space_available = max_blob_in_memory_size_ - blob_memory_used_; | |
498 while (!blobs_waiting_for_paging_.empty() && | |
499 max_blob_in_memory_size_ - blob_memory_used_ >= | |
500 blobs_waiting_for_paging_.front().first) { | |
501 auto size_callback_pair = blobs_waiting_for_paging_.front(); | |
502 blobs_waiting_for_paging_.pop_front(); | |
503 space_available -= size_callback_pair.first; | |
504 blobs_waiting_for_paging_size_ -= size_callback_pair.first; | |
505 blob_memory_used_ += size_callback_pair.first; | |
506 size_callback_pair.second.Run(true, std::vector<FileCreationInfo>()); | |
507 } | |
508 RecordTracingCounters(); | |
509 } | |
510 | |
511 void BlobMemoryController::MaybeSchedulePagingUntilSystemHealthy() { | |
512 // Don't do paging when others are happening, as we don't change our | |
513 // blobs_waiting_for_paging_size_ value until after the paging files have | |
514 // been written. | |
515 if (pending_pagings_ != 0 || !disk_enabled_) | |
516 return; | |
517 | |
518 // We try to page items to disk until our current system size + requested | |
519 // memory is below our size limit. | |
520 while (blobs_waiting_for_paging_size_ + blob_memory_used_ > | |
521 max_blob_in_memory_size_) { | |
522 // We only page when we have enough items to fill a while page file. | |
523 if (recent_item_cache_bytes_ < min_page_file_size_) | |
524 break; | |
525 DCHECK_LE(min_page_file_size_, static_cast<uint64_t>(blob_memory_used_)); | |
526 size_t total_items_size = 0; | |
527 std::unique_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>> | |
528 items_for_disk(new std::vector<scoped_refptr<ShareableBlobDataItem>>()); | |
529 // Collect our items. | |
530 while (total_items_size < min_page_file_size_ && | |
531 !recent_item_cache_.empty()) { | |
532 auto iterator = --recent_item_cache_.end(); | |
533 ShareableBlobDataItem* item = iterator->second; | |
534 DCHECK(item); | |
535 DCHECK_EQ(item->item()->type(), DataElement::TYPE_BYTES); | |
536 recent_item_cache_.Erase(iterator); | |
537 recent_item_cache_bytes_ -= static_cast<size_t>(item->item()->length()); | |
538 items_saving_to_disk_.insert(item->item_id()); | |
539 size_t size = base::checked_cast<size_t>(item->item()->length()); | |
540 total_items_size += size; | |
541 items_for_disk->push_back(make_scoped_refptr(item)); | |
542 } | |
543 if (total_items_size == 0) | |
544 break; | |
545 | |
546 // Update our bookkeeping. | |
547 pending_pagings_++; | |
548 disk_used_ += total_items_size; | |
549 DCHECK_GE(blob_memory_used_, total_items_size); | |
550 LOG(ERROR) << "saving " << total_items_size << " to disk."; | |
551 blob_memory_used_ -= total_items_size; | |
552 in_flight_memory_used_ += total_items_size; | |
553 std::string file_name = base::Uint64ToString(current_file_num_++); | |
554 // Create our file reference. | |
555 scoped_refptr<ShareableFileReference> file_ref = | |
556 ShareableFileReference::GetOrCreate( | |
557 blob_storage_dir_.Append(file_name), | |
558 ShareableFileReference::DELETE_ON_FINAL_RELEASE, | |
559 file_runner_.get()); | |
560 // Add the release callback so we decrement our disk usage on file deletion. | |
561 file_ref->AddFinalReleaseCallback( | |
562 base::Bind(&BlobMemoryController::OnBlobFileDelete, | |
563 ptr_factory_.GetWeakPtr(), total_items_size)); | |
564 // Post the file writing task. | |
565 base::PostTaskAndReplyWithResult( | |
566 file_runner_.get(), FROM_HERE, | |
567 base::Bind(&WriteItemsToFile, items_for_disk.get(), total_items_size, | |
568 base::Passed(&file_ref)), | |
569 base::Bind(&BlobMemoryController::OnPagingComplete, | |
570 ptr_factory_.GetWeakPtr(), base::Passed(&items_for_disk), | |
571 total_items_size)); | |
572 } | |
573 RecordTracingCounters(); | |
574 } | |
575 | |
576 void BlobMemoryController::OnPagingComplete( | |
577 std::unique_ptr<std::vector<scoped_refptr<ShareableBlobDataItem>>> items, | |
578 size_t total_items_size, | |
579 FileCreationInfo result) { | |
580 if (!disk_enabled_) | |
581 return; | |
582 if (result.error != File::FILE_OK) { | |
583 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingError", -result.error, | |
584 -File::FILE_ERROR_MAX); | |
585 disk_used_ -= total_items_size; | |
586 DisableDisk(); | |
587 return; | |
588 } | |
589 DCHECK_LT(0u, pending_pagings_); | |
590 pending_pagings_--; | |
591 | |
592 // Switch from the data backing item to a new file backing item. | |
593 uint64_t offset = 0; | |
594 for (const scoped_refptr<ShareableBlobDataItem>& shareable_item : | |
595 *items.get()) { | |
596 scoped_refptr<BlobDataItem> new_item(new BlobDataItem( | |
597 base::WrapUnique(new DataElement()), result.file_reference)); | |
598 new_item->data_element_ptr()->SetToFilePathRange( | |
599 result.file_reference->path(), offset, shareable_item->item()->length(), | |
600 result.last_modified); | |
601 shareable_item->item_ = new_item; | |
602 items_saving_to_disk_.erase(shareable_item->item_id()); | |
603 offset += shareable_item->item()->length(); | |
604 } | |
605 in_flight_memory_used_ -= total_items_size; | |
606 | |
607 // We want callback on blobs up to the amount we've freed. | |
608 MaybeGrantPendingQuotaRequests(); | |
609 | |
610 // If we still have more blobs waiting and we're not waiting on more paging | |
611 // operations, schedule more. | |
612 MaybeSchedulePagingUntilSystemHealthy(); | |
613 } | |
614 | |
615 void BlobMemoryController::RecordTracingCounters() { | |
616 TRACE_COUNTER2("Blob", "MemoryUsage", "RegularStorage", blob_memory_used_, | |
617 "InFlightToDisk", in_flight_memory_used_); | |
618 TRACE_COUNTER1("Blob", "DiskUsage", disk_used_); | |
619 TRACE_COUNTER1("Blob", "TranfersPendingOnDisk", | |
620 blobs_waiting_for_paging_.size()); | |
621 TRACE_COUNTER1("Blob", "TranfersBytesPendingOnDisk", | |
622 blobs_waiting_for_paging_size_); | |
623 } | |
624 | |
625 size_t BlobMemoryController::GetAvailableMemoryForBlobs() const { | |
626 // If disk is enabled, then we include |in_flight_memory_used_|. Otherwise we | |
627 // combine the in memory and in flight quotas. | |
628 if (disk_enabled_) { | |
629 if (max_blob_in_memory_size_ + in_flight_space_ < memory_usage()) | |
630 return 0; | |
631 return max_blob_in_memory_size_ + in_flight_space_ - memory_usage(); | |
632 } | |
633 if (max_blob_in_memory_size_ + in_flight_space_ < memory_usage()) | |
634 return 0; | |
635 return max_blob_in_memory_size_ + in_flight_space_ - memory_usage(); | |
636 } | |
637 | |
638 uint64_t BlobMemoryController::GetAvailableDiskSpaceForBlobs() const { | |
639 return disk_enabled_ | |
640 ? max_blob_disk_space_ - disk_used_ - | |
641 blobs_waiting_for_paging_size_ | |
642 : 0; | |
643 } | |
644 | |
645 void BlobMemoryController::OnBlobFileDelete(uint64_t size, | |
646 const base::FilePath& path) { | |
647 DCHECK_LE(size, disk_used_); | |
648 LOG(ERROR) << "File deleted " << size; | |
649 disk_used_ -= size; | |
650 } | |
651 | |
652 } // namespace storage | |
OLD | NEW |