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/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 |
| 37 namespace storage { |
| 38 namespace { |
| 39 using FileCreationInfo = BlobMemoryController::FileCreationInfo; |
| 40 using MemoryAllocation = BlobMemoryController::MemoryAllocation; |
| 41 using QuotaAllocationTask = BlobMemoryController::QuotaAllocationTask; |
| 42 |
| 43 File::Error CreateBlobDirectory(const FilePath& blob_storage_dir) { |
| 44 File::Error error = File::FILE_OK; |
| 45 base::CreateDirectoryAndGetError(blob_storage_dir, &error); |
| 46 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.CreateDirectoryResult", -error, |
| 47 -File::FILE_ERROR_MAX); |
| 48 return error; |
| 49 } |
| 50 |
| 51 void DestructFile(File infos_without_references) {} |
| 52 |
| 53 // Used for new unpopulated file items. Caller must populate file reference in |
| 54 // returned FileCreationInfos. |
| 55 std::pair<std::vector<FileCreationInfo>, File::Error> CreateEmptyFiles( |
| 56 const FilePath& blob_storage_dir, |
| 57 scoped_refptr<base::TaskRunner> file_task_runner, |
| 58 std::vector<base::FilePath> file_paths) { |
| 59 base::ThreadRestrictions::AssertIOAllowed(); |
| 60 |
| 61 File::Error dir_create_status = CreateBlobDirectory(blob_storage_dir); |
| 62 if (dir_create_status != File::FILE_OK) |
| 63 return std::make_pair(std::vector<FileCreationInfo>(), dir_create_status); |
| 64 |
| 65 std::vector<FileCreationInfo> result; |
| 66 for (const base::FilePath& file_path : file_paths) { |
| 67 FileCreationInfo creation_info; |
| 68 // Try to open our file. |
| 69 File file(file_path, File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE); |
| 70 creation_info.path = std::move(file_path); |
| 71 creation_info.file_deletion_runner = file_task_runner; |
| 72 creation_info.error = file.error_details(); |
| 73 if (creation_info.error != File::FILE_OK) { |
| 74 return std::make_pair(std::vector<FileCreationInfo>(), |
| 75 creation_info.error); |
| 76 } |
| 77 |
| 78 // Grab the file info to get the "last modified" time and store the file. |
| 79 File::Info file_info; |
| 80 bool success = file.GetInfo(&file_info); |
| 81 creation_info.error = success ? File::FILE_OK : File::FILE_ERROR_FAILED; |
| 82 if (!success) { |
| 83 return std::make_pair(std::vector<FileCreationInfo>(), |
| 84 creation_info.error); |
| 85 } |
| 86 creation_info.file = std::move(file); |
| 87 |
| 88 result.push_back(std::move(creation_info)); |
| 89 } |
| 90 return std::make_pair(std::move(result), File::FILE_OK); |
| 91 } |
| 92 |
| 93 // Used to evict multiple memory items out to a single file. Caller must |
| 94 // populate file reference in returned FileCreationInfo. |
| 95 FileCreationInfo CreateFileAndWriteItems( |
| 96 const FilePath& blob_storage_dir, |
| 97 const FilePath& file_path, |
| 98 scoped_refptr<base::TaskRunner> file_task_runner, |
| 99 std::vector<DataElement*> items, |
| 100 size_t total_size_bytes) { |
| 101 DCHECK_NE(0u, total_size_bytes); |
| 102 UMA_HISTOGRAM_MEMORY_KB("Storage.Blob.PageFileSize", total_size_bytes / 1024); |
| 103 base::ThreadRestrictions::AssertIOAllowed(); |
| 104 |
| 105 FileCreationInfo creation_info; |
| 106 creation_info.file_deletion_runner = std::move(file_task_runner); |
| 107 creation_info.error = CreateBlobDirectory(blob_storage_dir); |
| 108 if (creation_info.error != File::FILE_OK) |
| 109 return creation_info; |
| 110 |
| 111 // Create the page file. |
| 112 File file(file_path, File::FLAG_CREATE_ALWAYS | File::FLAG_WRITE); |
| 113 creation_info.path = file_path; |
| 114 creation_info.error = file.error_details(); |
| 115 if (creation_info.error != File::FILE_OK) |
| 116 return creation_info; |
| 117 |
| 118 // Write data. |
| 119 file.SetLength(total_size_bytes); |
| 120 int bytes_written = 0; |
| 121 for (DataElement* element : items) { |
| 122 DCHECK_EQ(DataElement::TYPE_BYTES, element->type()); |
| 123 size_t length = base::checked_cast<size_t>(element->length()); |
| 124 size_t bytes_left = length; |
| 125 while (bytes_left > 0) { |
| 126 bytes_written = |
| 127 file.WriteAtCurrentPos(element->bytes() + (length - bytes_left), |
| 128 base::saturated_cast<int>(bytes_left)); |
| 129 if (bytes_written < 0) |
| 130 break; |
| 131 DCHECK_LE(static_cast<size_t>(bytes_written), bytes_left); |
| 132 bytes_left -= bytes_written; |
| 133 } |
| 134 if (bytes_written < 0) |
| 135 break; |
| 136 } |
| 137 |
| 138 File::Info info; |
| 139 bool success = file.GetInfo(&info); |
| 140 creation_info.error = |
| 141 bytes_written < 0 || !success ? File::FILE_ERROR_FAILED : File::FILE_OK; |
| 142 creation_info.last_modified = info.last_modified; |
| 143 return creation_info; |
| 144 } |
| 145 |
| 146 uint64_t GetTotalSizeAndFileSizes( |
| 147 const std::vector<scoped_refptr<ShareableBlobDataItem>>& |
| 148 unreserved_file_items, |
| 149 std::vector<uint64_t>* file_sizes_output) { |
| 150 uint64_t total_size_output = 0; |
| 151 base::SmallMap<std::map<uint64_t, uint64_t>> file_id_to_sizes; |
| 152 for (const auto& item : unreserved_file_items) { |
| 153 const DataElement& element = item->item()->data_element(); |
| 154 uint64_t file_id = BlobDataBuilder::GetFutureFileID(element); |
| 155 auto it = file_id_to_sizes.find(file_id); |
| 156 if (it != file_id_to_sizes.end()) |
| 157 it->second = std::max(it->second, element.offset() + element.length()); |
| 158 else |
| 159 file_id_to_sizes[file_id] = element.offset() + element.length(); |
| 160 total_size_output += element.length(); |
| 161 } |
| 162 for (const auto& size_pair : file_id_to_sizes) { |
| 163 file_sizes_output->push_back(size_pair.second); |
| 164 } |
| 165 return total_size_output; |
| 166 } |
| 167 |
| 168 } // namespace |
| 169 |
| 170 FileCreationInfo::FileCreationInfo() {} |
| 171 FileCreationInfo::~FileCreationInfo() { |
| 172 if (file.IsValid()) { |
| 173 DCHECK(file_deletion_runner); |
| 174 file_deletion_runner->PostTask( |
| 175 FROM_HERE, base::Bind(&DestructFile, base::Passed(&file))); |
| 176 } |
| 177 } |
| 178 FileCreationInfo::FileCreationInfo(FileCreationInfo&&) = default; |
| 179 FileCreationInfo& FileCreationInfo::operator=(FileCreationInfo&&) = default; |
| 180 |
| 181 MemoryAllocation::MemoryAllocation( |
| 182 base::WeakPtr<BlobMemoryController> controller, |
| 183 uint64_t item_id, |
| 184 size_t length) |
| 185 : controller(controller), item_id(item_id), length(length) {} |
| 186 |
| 187 MemoryAllocation::~MemoryAllocation() { |
| 188 if (controller) |
| 189 controller->RevokeMemoryAllocation(item_id, length); |
| 190 } |
| 191 |
| 192 BlobMemoryController::QuotaAllocationTask::~QuotaAllocationTask() {} |
| 193 |
| 194 class BlobMemoryController::MemoryQuotaAllocationTask |
| 195 : public BlobMemoryController::QuotaAllocationTask { |
| 196 public: |
| 197 MemoryQuotaAllocationTask( |
| 198 BlobMemoryController* controller, |
| 199 size_t quota_request_size, |
| 200 std::vector<scoped_refptr<ShareableBlobDataItem>> pending_items, |
| 201 MemoryQuotaRequestCallback done_callback) |
| 202 : controller_(controller), |
| 203 pending_items_(std::move(pending_items)), |
| 204 done_callback_(std::move(done_callback)), |
| 205 allocation_size_(quota_request_size), |
| 206 weak_factory_(this) {} |
| 207 |
| 208 ~MemoryQuotaAllocationTask() override = default; |
| 209 |
| 210 void RunDoneCallback(bool success) { |
| 211 // Make sure we clear the weak pointers we gave to the caller beforehand. |
| 212 weak_factory_.InvalidateWeakPtrs(); |
| 213 if (success) |
| 214 controller_->GrantMemoryAllocations(&pending_items_, allocation_size_); |
| 215 done_callback_.Run(success); |
| 216 } |
| 217 |
| 218 base::WeakPtr<QuotaAllocationTask> GetWeakPtr() { |
| 219 return weak_factory_.GetWeakPtr(); |
| 220 } |
| 221 |
| 222 void Cancel() override { |
| 223 DCHECK_GE(controller_->pending_memory_quota_total_size_, allocation_size_); |
| 224 controller_->pending_memory_quota_total_size_ -= allocation_size_; |
| 225 // This call destroys this object. |
| 226 controller_->pending_memory_quota_tasks_.erase(my_list_position_); |
| 227 } |
| 228 |
| 229 // The my_list_position_ iterator is stored so that we can remove ourself |
| 230 // from the task list when we are cancelled. |
| 231 void set_my_list_position( |
| 232 PendingMemoryQuotaTaskList::iterator my_list_position) { |
| 233 my_list_position_ = my_list_position; |
| 234 } |
| 235 |
| 236 size_t allocation_size() const { return allocation_size_; } |
| 237 |
| 238 private: |
| 239 BlobMemoryController* controller_; |
| 240 std::vector<scoped_refptr<ShareableBlobDataItem>> pending_items_; |
| 241 MemoryQuotaRequestCallback done_callback_; |
| 242 |
| 243 size_t allocation_size_; |
| 244 PendingMemoryQuotaTaskList::iterator my_list_position_; |
| 245 |
| 246 base::WeakPtrFactory<MemoryQuotaAllocationTask> weak_factory_; |
| 247 DISALLOW_COPY_AND_ASSIGN(MemoryQuotaAllocationTask); |
| 248 }; |
| 249 |
| 250 class BlobMemoryController::FileQuotaAllocationTask |
| 251 : public BlobMemoryController::QuotaAllocationTask { |
| 252 public: |
| 253 // We post a task to create the file for the items right away. |
| 254 FileQuotaAllocationTask( |
| 255 BlobMemoryController* memory_controller, |
| 256 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_file_items, |
| 257 const FileQuotaRequestCallback& done_callback) |
| 258 : controller_(memory_controller), |
| 259 done_callback_(done_callback), |
| 260 weak_factory_(this) { |
| 261 // Get the file sizes and total size. |
| 262 std::vector<uint64_t> file_sizes; |
| 263 uint64_t total_size = |
| 264 GetTotalSizeAndFileSizes(unreserved_file_items, &file_sizes); |
| 265 DCHECK_LE(total_size, controller_->GetAvailableFileSpaceForBlobs()); |
| 266 allocation_size_ = total_size; |
| 267 |
| 268 // Check & set our item states. |
| 269 for (auto& shareable_item : unreserved_file_items) { |
| 270 DCHECK_EQ(ShareableBlobDataItem::QUOTA_NEEDED, shareable_item->state()); |
| 271 DCHECK_EQ(DataElement::TYPE_FILE, shareable_item->item()->type()); |
| 272 shareable_item->set_state(ShareableBlobDataItem::QUOTA_REQUESTED); |
| 273 } |
| 274 pending_items_ = std::move(unreserved_file_items); |
| 275 |
| 276 // Increment disk usage and create our file references. |
| 277 controller_->disk_used_ += allocation_size_; |
| 278 std::vector<base::FilePath> file_paths; |
| 279 std::vector<scoped_refptr<ShareableFileReference>> references; |
| 280 for (size_t i = 0; i < file_sizes.size(); i++) { |
| 281 file_paths.push_back(controller_->GenerateNextPageFileName()); |
| 282 references.push_back(ShareableFileReference::GetOrCreate( |
| 283 file_paths.back(), ShareableFileReference::DELETE_ON_FINAL_RELEASE, |
| 284 controller_->file_runner_.get())); |
| 285 references.back()->AddFinalReleaseCallback( |
| 286 base::Bind(&BlobMemoryController::OnBlobFileDelete, |
| 287 controller_->weak_factory_.GetWeakPtr(), file_sizes[i])); |
| 288 } |
| 289 |
| 290 // Send file creation task to file thread. |
| 291 base::PostTaskAndReplyWithResult( |
| 292 controller_->file_runner_.get(), FROM_HERE, |
| 293 base::Bind(&CreateEmptyFiles, controller_->blob_storage_dir_, |
| 294 controller_->file_runner_, base::Passed(&file_paths)), |
| 295 base::Bind(&FileQuotaAllocationTask::OnCreateEmptyFiles, |
| 296 weak_factory_.GetWeakPtr(), base::Passed(&references))); |
| 297 controller_->RecordTracingCounters(); |
| 298 } |
| 299 ~FileQuotaAllocationTask() override {} |
| 300 |
| 301 void RunDoneCallback(bool success, std::vector<FileCreationInfo> file_info) { |
| 302 // Make sure we clear the weak pointers we gave to the caller beforehand. |
| 303 weak_factory_.InvalidateWeakPtrs(); |
| 304 |
| 305 // We want to destroy this object on the exit of this method if we were |
| 306 // successful. |
| 307 std::unique_ptr<FileQuotaAllocationTask> this_object; |
| 308 if (success) { |
| 309 for (auto& item : pending_items_) { |
| 310 item->set_state(ShareableBlobDataItem::QUOTA_GRANTED); |
| 311 } |
| 312 this_object = std::move(*my_list_position_); |
| 313 controller_->pending_file_quota_tasks_.erase(my_list_position_); |
| 314 } |
| 315 |
| 316 done_callback_.Run(success, std::move(file_info)); |
| 317 } |
| 318 |
| 319 base::WeakPtr<QuotaAllocationTask> GetWeakPtr() { |
| 320 return weak_factory_.GetWeakPtr(); |
| 321 } |
| 322 |
| 323 void Cancel() override { |
| 324 // This call destroys this object. We rely on ShareableFileReference's |
| 325 // final release callback for disk_usage_ accounting. |
| 326 controller_->pending_file_quota_tasks_.erase(my_list_position_); |
| 327 } |
| 328 |
| 329 void OnCreateEmptyFiles( |
| 330 std::vector<scoped_refptr<ShareableFileReference>> references, |
| 331 std::pair<std::vector<FileCreationInfo>, File::Error> files_and_error) { |
| 332 auto& files = files_and_error.first; |
| 333 if (files.empty()) { |
| 334 DCHECK_GE(controller_->disk_used_, allocation_size_); |
| 335 controller_->disk_used_ -= allocation_size_; |
| 336 // This will call our callback and delete the object correctly. |
| 337 controller_->DisableFilePaging(files_and_error.second); |
| 338 return; |
| 339 } |
| 340 DCHECK_EQ(files.size(), references.size()); |
| 341 for (size_t i = 0; i < files.size(); i++) { |
| 342 files[i].file_reference = std::move(references[i]); |
| 343 } |
| 344 RunDoneCallback(true, std::move(files)); |
| 345 } |
| 346 |
| 347 // The my_list_position_ iterator is stored so that we can remove ourself |
| 348 // from the task list when we are cancelled. |
| 349 void set_my_list_position( |
| 350 PendingFileQuotaTaskList::iterator my_list_position) { |
| 351 my_list_position_ = my_list_position; |
| 352 } |
| 353 |
| 354 private: |
| 355 BlobMemoryController* controller_; |
| 356 std::vector<scoped_refptr<ShareableBlobDataItem>> pending_items_; |
| 357 scoped_refptr<base::TaskRunner> file_runner_; |
| 358 FileQuotaRequestCallback done_callback_; |
| 359 |
| 360 uint64_t allocation_size_; |
| 361 PendingFileQuotaTaskList::iterator my_list_position_; |
| 362 |
| 363 base::WeakPtrFactory<FileQuotaAllocationTask> weak_factory_; |
| 364 DISALLOW_COPY_AND_ASSIGN(FileQuotaAllocationTask); |
| 365 }; |
| 366 |
| 367 BlobMemoryController::BlobMemoryController( |
| 368 const base::FilePath& storage_directory, |
| 369 scoped_refptr<base::TaskRunner> file_runner) |
| 370 : file_paging_enabled_(file_runner.get() != nullptr), |
| 371 blob_storage_dir_(storage_directory), |
| 372 file_runner_(std::move(file_runner)), |
| 373 populated_memory_items_( |
| 374 base::MRUCache<uint64_t, ShareableBlobDataItem*>::NO_AUTO_EVICT), |
| 375 weak_factory_(this) {} |
| 376 |
| 377 BlobMemoryController::~BlobMemoryController() {} |
| 378 |
| 379 void BlobMemoryController::DisableFilePaging(base::File::Error reason) { |
| 380 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingDisabled", -reason, |
| 381 -File::FILE_ERROR_MAX); |
| 382 file_paging_enabled_ = false; |
| 383 in_flight_memory_used_ = 0; |
| 384 items_paging_to_file_.clear(); |
| 385 pending_evictions_ = 0; |
| 386 pending_memory_quota_total_size_ = 0; |
| 387 populated_memory_items_.Clear(); |
| 388 populated_memory_items_bytes_ = 0; |
| 389 file_runner_ = nullptr; |
| 390 |
| 391 PendingMemoryQuotaTaskList old_memory_tasks; |
| 392 PendingFileQuotaTaskList old_file_tasks; |
| 393 std::swap(old_memory_tasks, pending_memory_quota_tasks_); |
| 394 std::swap(old_file_tasks, pending_file_quota_tasks_); |
| 395 |
| 396 // Don't call the callbacks until we have a consistent state. |
| 397 for (auto& memory_request : old_memory_tasks) { |
| 398 memory_request->RunDoneCallback(false); |
| 399 } |
| 400 for (auto& file_request : old_file_tasks) { |
| 401 file_request->RunDoneCallback(false, std::vector<FileCreationInfo>()); |
| 402 } |
| 403 } |
| 404 |
| 405 BlobMemoryController::Strategy BlobMemoryController::DetermineStrategy( |
| 406 size_t preemptive_transported_bytes, |
| 407 uint64_t total_transportation_bytes) const { |
| 408 if (total_transportation_bytes == 0) |
| 409 return Strategy::NONE_NEEDED; |
| 410 if (!CanReserveQuota(total_transportation_bytes)) |
| 411 return Strategy::TOO_LARGE; |
| 412 |
| 413 // Handle the case where we have all the bytes preemptively transported, and |
| 414 // we can also fit them. |
| 415 if (preemptive_transported_bytes == total_transportation_bytes && |
| 416 pending_memory_quota_tasks_.empty() && |
| 417 preemptive_transported_bytes < GetAvailableMemoryForBlobs()) { |
| 418 return Strategy::NONE_NEEDED; |
| 419 } |
| 420 if (file_paging_enabled_ && |
| 421 (total_transportation_bytes > limits_.memory_limit_before_paging())) { |
| 422 return Strategy::FILE; |
| 423 } |
| 424 if (total_transportation_bytes > limits_.max_ipc_memory_size) |
| 425 return Strategy::SHARED_MEMORY; |
| 426 return Strategy::IPC; |
| 427 } |
| 428 |
| 429 bool BlobMemoryController::CanReserveQuota(uint64_t size) const { |
| 430 // We check each size independently as a blob can't be constructed in both |
| 431 // disk and memory. |
| 432 return size <= GetAvailableMemoryForBlobs() || |
| 433 size <= GetAvailableFileSpaceForBlobs(); |
| 434 } |
| 435 |
| 436 base::WeakPtr<QuotaAllocationTask> BlobMemoryController::ReserveMemoryQuota( |
| 437 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_memory_items, |
| 438 const MemoryQuotaRequestCallback& done_callback) { |
| 439 if (unreserved_memory_items.empty()) { |
| 440 done_callback.Run(true); |
| 441 return base::WeakPtr<QuotaAllocationTask>(); |
| 442 } |
| 443 |
| 444 base::CheckedNumeric<uint64_t> unsafe_total_bytes_needed = 0; |
| 445 for (auto& item : unreserved_memory_items) { |
| 446 DCHECK_EQ(ShareableBlobDataItem::QUOTA_NEEDED, item->state()); |
| 447 DCHECK(item->item()->type() == DataElement::TYPE_BYTES_DESCRIPTION || |
| 448 item->item()->type() == DataElement::TYPE_BYTES); |
| 449 DCHECK(item->item()->length() > 0); |
| 450 unsafe_total_bytes_needed += item->item()->length(); |
| 451 item->set_state(ShareableBlobDataItem::QUOTA_REQUESTED); |
| 452 } |
| 453 |
| 454 uint64_t total_bytes_needed = unsafe_total_bytes_needed.ValueOrDie(); |
| 455 DCHECK_GT(total_bytes_needed, 0ull); |
| 456 |
| 457 // If we're currently waiting for blobs to page already, then we add |
| 458 // ourselves to the end of the queue. Once paging is complete, we'll schedule |
| 459 // more paging for any more pending blobs. |
| 460 if (!pending_memory_quota_tasks_.empty()) { |
| 461 return AppendMemoryTask(total_bytes_needed, |
| 462 std::move(unreserved_memory_items), done_callback); |
| 463 } |
| 464 |
| 465 // Store right away if we can. |
| 466 if (total_bytes_needed <= GetAvailableMemoryForBlobs()) { |
| 467 GrantMemoryAllocations(&unreserved_memory_items, |
| 468 static_cast<size_t>(total_bytes_needed)); |
| 469 MaybeScheduleEvictionUntilSystemHealthy(); |
| 470 done_callback.Run(true); |
| 471 return base::WeakPtr<QuotaAllocationTask>(); |
| 472 } |
| 473 |
| 474 // Size is larger than available memory. |
| 475 DCHECK(pending_memory_quota_tasks_.empty()); |
| 476 DCHECK_EQ(0u, pending_memory_quota_total_size_); |
| 477 |
| 478 auto weak_ptr = AppendMemoryTask( |
| 479 total_bytes_needed, std::move(unreserved_memory_items), done_callback); |
| 480 MaybeScheduleEvictionUntilSystemHealthy(); |
| 481 return weak_ptr; |
| 482 } |
| 483 |
| 484 base::WeakPtr<QuotaAllocationTask> BlobMemoryController::ReserveFileQuota( |
| 485 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_file_items, |
| 486 const FileQuotaRequestCallback& done_callback) { |
| 487 pending_file_quota_tasks_.push_back(base::MakeUnique<FileQuotaAllocationTask>( |
| 488 this, std::move(unreserved_file_items), done_callback)); |
| 489 pending_file_quota_tasks_.back()->set_my_list_position( |
| 490 --pending_file_quota_tasks_.end()); |
| 491 return pending_file_quota_tasks_.back()->GetWeakPtr(); |
| 492 } |
| 493 |
| 494 void BlobMemoryController::NotifyMemoryItemsUsed( |
| 495 std::vector<scoped_refptr<ShareableBlobDataItem>>& items) { |
| 496 for (const auto& item : items) { |
| 497 DCHECK_EQ(DataElement::TYPE_BYTES, item->item()->type()); |
| 498 DCHECK_EQ(ShareableBlobDataItem::POPULATED_WITH_QUOTA, item->state()); |
| 499 // We don't want to re-add the item if we're currently paging it to disk. |
| 500 if (items_paging_to_file_.find(item->item_id()) != |
| 501 items_paging_to_file_.end()) { |
| 502 return; |
| 503 } |
| 504 auto iterator = populated_memory_items_.Get(item->item_id()); |
| 505 if (iterator == populated_memory_items_.end()) { |
| 506 populated_memory_items_bytes_ += |
| 507 static_cast<size_t>(item->item()->length()); |
| 508 populated_memory_items_.Put(item->item_id(), item.get()); |
| 509 } |
| 510 } |
| 511 MaybeScheduleEvictionUntilSystemHealthy(); |
| 512 } |
| 513 |
| 514 base::WeakPtr<QuotaAllocationTask> BlobMemoryController::AppendMemoryTask( |
| 515 uint64_t total_bytes_needed, |
| 516 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_memory_items, |
| 517 const MemoryQuotaRequestCallback& done_callback) { |
| 518 DCHECK(file_paging_enabled_) |
| 519 << "Caller tried to reserve memory when CanReserveQuota(" |
| 520 << total_bytes_needed << ") would have returned false."; |
| 521 |
| 522 pending_memory_quota_total_size_ += total_bytes_needed; |
| 523 pending_memory_quota_tasks_.push_back( |
| 524 base::MakeUnique<MemoryQuotaAllocationTask>( |
| 525 this, total_bytes_needed, std::move(unreserved_memory_items), |
| 526 std::move(done_callback))); |
| 527 pending_memory_quota_tasks_.back()->set_my_list_position( |
| 528 --pending_memory_quota_tasks_.end()); |
| 529 |
| 530 return pending_memory_quota_tasks_.back()->GetWeakPtr(); |
| 531 } |
| 532 |
| 533 void BlobMemoryController::MaybeGrantPendingMemoryRequests() { |
| 534 while (!pending_memory_quota_tasks_.empty() && |
| 535 limits_.max_blob_in_memory_space - blob_memory_used_ >= |
| 536 pending_memory_quota_tasks_.front()->allocation_size()) { |
| 537 std::unique_ptr<MemoryQuotaAllocationTask> memory_task = |
| 538 std::move(pending_memory_quota_tasks_.front()); |
| 539 pending_memory_quota_tasks_.pop_front(); |
| 540 pending_memory_quota_total_size_ -= memory_task->allocation_size(); |
| 541 memory_task->RunDoneCallback(true); |
| 542 } |
| 543 RecordTracingCounters(); |
| 544 } |
| 545 |
| 546 size_t BlobMemoryController::CollectItemsForEviction( |
| 547 std::vector<scoped_refptr<ShareableBlobDataItem>>* output) { |
| 548 base::CheckedNumeric<size_t> total_items_size = 0; |
| 549 // Process the recent item list and remove items until we have at least a |
| 550 // minimum file size or we're at the end of our items to page to disk. |
| 551 while (total_items_size.ValueOrDie() < limits_.min_page_file_size && |
| 552 !populated_memory_items_.empty()) { |
| 553 auto iterator = --populated_memory_items_.end(); |
| 554 ShareableBlobDataItem* item = iterator->second; |
| 555 DCHECK_EQ(item->item()->type(), DataElement::TYPE_BYTES); |
| 556 populated_memory_items_.Erase(iterator); |
| 557 size_t size = base::checked_cast<size_t>(item->item()->length()); |
| 558 populated_memory_items_bytes_ -= size; |
| 559 total_items_size += size; |
| 560 output->push_back(make_scoped_refptr(item)); |
| 561 } |
| 562 return total_items_size.ValueOrDie(); |
| 563 } |
| 564 |
| 565 void BlobMemoryController::MaybeScheduleEvictionUntilSystemHealthy() { |
| 566 // Don't do eviction when others are happening, as we don't change our |
| 567 // pending_memory_quota_total_size_ value until after the paging files have |
| 568 // been written. |
| 569 if (pending_evictions_ != 0 || !file_paging_enabled_) |
| 570 return; |
| 571 |
| 572 // We try to page items to disk until our current system size + requested |
| 573 // memory is below our size limit. |
| 574 while (pending_memory_quota_total_size_ + blob_memory_used_ > |
| 575 limits_.memory_limit_before_paging()) { |
| 576 // We only page when we have enough items to fill a whole page file. |
| 577 if (populated_memory_items_bytes_ < limits_.min_page_file_size) |
| 578 break; |
| 579 DCHECK_LE(limits_.min_page_file_size, |
| 580 static_cast<uint64_t>(blob_memory_used_)); |
| 581 |
| 582 std::vector<scoped_refptr<ShareableBlobDataItem>> items_to_swap; |
| 583 size_t total_items_size = CollectItemsForEviction(&items_to_swap); |
| 584 if (total_items_size == 0) |
| 585 break; |
| 586 |
| 587 std::vector<DataElement*> items_for_paging; |
| 588 for (auto& shared_blob_item : items_to_swap) { |
| 589 items_paging_to_file_.insert(shared_blob_item->item_id()); |
| 590 items_for_paging.push_back(shared_blob_item->item()->data_element_ptr()); |
| 591 } |
| 592 |
| 593 // Update our bookkeeping. |
| 594 pending_evictions_++; |
| 595 disk_used_ += total_items_size; |
| 596 in_flight_memory_used_ += total_items_size; |
| 597 |
| 598 // Create our file reference. |
| 599 FilePath page_file_path = GenerateNextPageFileName(); |
| 600 scoped_refptr<ShareableFileReference> file_reference = |
| 601 ShareableFileReference::GetOrCreate( |
| 602 page_file_path, |
| 603 ShareableFileReference::DELETE_ON_FINAL_RELEASE, |
| 604 file_runner_.get()); |
| 605 // Add the release callback so we decrement our disk usage on file deletion. |
| 606 file_reference->AddFinalReleaseCallback( |
| 607 base::Bind(&BlobMemoryController::OnBlobFileDelete, |
| 608 weak_factory_.GetWeakPtr(), total_items_size)); |
| 609 |
| 610 // Post the file writing task. |
| 611 base::PostTaskAndReplyWithResult( |
| 612 file_runner_.get(), FROM_HERE, |
| 613 base::Bind(&CreateFileAndWriteItems, blob_storage_dir_, |
| 614 base::Passed(&page_file_path), file_runner_, |
| 615 base::Passed(&items_for_paging), total_items_size), |
| 616 base::Bind(&BlobMemoryController::OnEvictionComplete, |
| 617 weak_factory_.GetWeakPtr(), base::Passed(&file_reference), |
| 618 base::Passed(&items_to_swap), total_items_size)); |
| 619 } |
| 620 RecordTracingCounters(); |
| 621 } |
| 622 |
| 623 void BlobMemoryController::OnEvictionComplete( |
| 624 scoped_refptr<ShareableFileReference> file_reference, |
| 625 std::vector<scoped_refptr<ShareableBlobDataItem>> items, |
| 626 size_t total_items_size, |
| 627 FileCreationInfo result) { |
| 628 if (!file_paging_enabled_) |
| 629 return; |
| 630 |
| 631 if (result.error != File::FILE_OK) { |
| 632 DisableFilePaging(result.error); |
| 633 return; |
| 634 } |
| 635 |
| 636 DCHECK_LT(0, pending_evictions_); |
| 637 pending_evictions_--; |
| 638 |
| 639 // Switch item from memory to the new file. |
| 640 uint64_t offset = 0; |
| 641 for (const scoped_refptr<ShareableBlobDataItem>& shareable_item : items) { |
| 642 scoped_refptr<BlobDataItem> new_item( |
| 643 new BlobDataItem(base::WrapUnique(new DataElement()), file_reference)); |
| 644 new_item->data_element_ptr()->SetToFilePathRange( |
| 645 file_reference->path(), offset, shareable_item->item()->length(), |
| 646 result.last_modified); |
| 647 DCHECK(shareable_item->memory_allocation_); |
| 648 shareable_item->set_memory_allocation(nullptr); |
| 649 shareable_item->set_item(new_item); |
| 650 items_paging_to_file_.erase(shareable_item->item_id()); |
| 651 offset += shareable_item->item()->length(); |
| 652 } |
| 653 in_flight_memory_used_ -= total_items_size; |
| 654 |
| 655 // We want callback on blobs up to the amount we've freed. |
| 656 MaybeGrantPendingMemoryRequests(); |
| 657 |
| 658 // If we still have more blobs waiting and we're not waiting on more paging |
| 659 // operations, schedule more. |
| 660 MaybeScheduleEvictionUntilSystemHealthy(); |
| 661 } |
| 662 |
| 663 FilePath BlobMemoryController::GenerateNextPageFileName() { |
| 664 std::string file_name = base::Uint64ToString(current_file_num_++); |
| 665 return blob_storage_dir_.Append(FilePath::FromUTF8Unsafe(file_name)); |
| 666 } |
| 667 |
| 668 void BlobMemoryController::RecordTracingCounters() const { |
| 669 TRACE_COUNTER2("Blob", "MemoryUsage", "TotalStorage", blob_memory_used_, |
| 670 "InFlightToDisk", in_flight_memory_used_); |
| 671 TRACE_COUNTER1("Blob", "DiskUsage", disk_used_); |
| 672 TRACE_COUNTER1("Blob", "TranfersPendingOnDisk", |
| 673 pending_memory_quota_tasks_.size()); |
| 674 TRACE_COUNTER1("Blob", "TranfersBytesPendingOnDisk", |
| 675 pending_memory_quota_total_size_); |
| 676 } |
| 677 |
| 678 size_t BlobMemoryController::GetAvailableMemoryForBlobs() const { |
| 679 if (limits_.max_blob_in_memory_space < memory_usage()) |
| 680 return 0; |
| 681 return limits_.max_blob_in_memory_space - memory_usage(); |
| 682 } |
| 683 |
| 684 uint64_t BlobMemoryController::GetAvailableFileSpaceForBlobs() const { |
| 685 if (!file_paging_enabled_) |
| 686 return 0; |
| 687 // Sometimes we're only paging part of what we need for the new blob, so add |
| 688 // the rest of the size we need into our disk usage if this is the case. |
| 689 uint64_t total_disk_used = disk_used_; |
| 690 if (in_flight_memory_used_ < pending_memory_quota_total_size_) { |
| 691 total_disk_used += |
| 692 pending_memory_quota_total_size_ - in_flight_memory_used_; |
| 693 } |
| 694 if (limits_.max_blob_disk_space < total_disk_used) |
| 695 return 0; |
| 696 return limits_.max_blob_disk_space - total_disk_used; |
| 697 } |
| 698 |
| 699 void BlobMemoryController::GrantMemoryAllocations( |
| 700 std::vector<scoped_refptr<ShareableBlobDataItem>>* items, |
| 701 size_t total_bytes) { |
| 702 blob_memory_used_ += total_bytes; |
| 703 for (auto& item : *items) { |
| 704 item->set_state(ShareableBlobDataItem::QUOTA_GRANTED); |
| 705 item->set_memory_allocation(base::MakeUnique<MemoryAllocation>( |
| 706 weak_factory_.GetWeakPtr(), item->item_id(), |
| 707 base::checked_cast<size_t>(item->item()->length()))); |
| 708 } |
| 709 } |
| 710 |
| 711 void BlobMemoryController::RevokeMemoryAllocation(uint64_t item_id, |
| 712 size_t length) { |
| 713 DCHECK_LE(length, blob_memory_used_); |
| 714 blob_memory_used_ -= length; |
| 715 auto iterator = populated_memory_items_.Get(item_id); |
| 716 if (iterator != populated_memory_items_.end()) { |
| 717 DCHECK_GE(populated_memory_items_bytes_, length); |
| 718 populated_memory_items_bytes_ -= length; |
| 719 populated_memory_items_.Erase(iterator); |
| 720 } |
| 721 MaybeGrantPendingMemoryRequests(); |
| 722 } |
| 723 |
| 724 void BlobMemoryController::OnBlobFileDelete(uint64_t size, |
| 725 const FilePath& path) { |
| 726 DCHECK_LE(size, disk_used_); |
| 727 disk_used_ -= size; |
| 728 } |
| 729 |
| 730 } // namespace storage |
OLD | NEW |