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

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

Issue 2857283002: Add memory pressure listener to Blob storage (Closed)
Patch Set: set limit in constants. Created 3 years, 7 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
1 // Copyright 2016 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "storage/browser/blob/blob_memory_controller.h" 5 #include "storage/browser/blob/blob_memory_controller.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <numeric> 8 #include <numeric>
9 9
10 #include "base/bind.h" 10 #include "base/bind.h"
(...skipping 23 matching lines...) Expand all
34 #include "storage/browser/blob/shareable_file_reference.h" 34 #include "storage/browser/blob/shareable_file_reference.h"
35 #include "storage/common/data_element.h" 35 #include "storage/common/data_element.h"
36 36
37 using base::File; 37 using base::File;
38 using base::FilePath; 38 using base::FilePath;
39 39
40 namespace storage { 40 namespace storage {
41 namespace { 41 namespace {
42 constexpr int64_t kUnknownDiskAvailability = -1ll; 42 constexpr int64_t kUnknownDiskAvailability = -1ll;
43 constexpr uint64_t kMegabyte = 1024ull * 1024; 43 constexpr uint64_t kMegabyte = 1024ull * 1024;
44 const int64_t kMinSecondsForPressureEvictions = 30;
44 45
45 using FileCreationInfo = BlobMemoryController::FileCreationInfo; 46 using FileCreationInfo = BlobMemoryController::FileCreationInfo;
46 using MemoryAllocation = BlobMemoryController::MemoryAllocation; 47 using MemoryAllocation = BlobMemoryController::MemoryAllocation;
47 using QuotaAllocationTask = BlobMemoryController::QuotaAllocationTask; 48 using QuotaAllocationTask = BlobMemoryController::QuotaAllocationTask;
48 using DiskSpaceFuncPtr = BlobMemoryController::DiskSpaceFuncPtr; 49 using DiskSpaceFuncPtr = BlobMemoryController::DiskSpaceFuncPtr;
49 50
50 // CrOS: 51 // CrOS:
51 // * Ram - 20% 52 // * Ram - 20%
52 // * Disk - 50% 53 // * Disk - 50%
53 // Note: The disk is the user partition, so the operating system can still 54 // Note: The disk is the user partition, so the operating system can still
(...skipping 444 matching lines...) Expand 10 before | Expand all | Expand 10 after
498 499
499 BlobMemoryController::BlobMemoryController( 500 BlobMemoryController::BlobMemoryController(
500 const base::FilePath& storage_directory, 501 const base::FilePath& storage_directory,
501 scoped_refptr<base::TaskRunner> file_runner) 502 scoped_refptr<base::TaskRunner> file_runner)
502 : file_paging_enabled_(file_runner.get() != nullptr), 503 : file_paging_enabled_(file_runner.get() != nullptr),
503 blob_storage_dir_(storage_directory), 504 blob_storage_dir_(storage_directory),
504 file_runner_(std::move(file_runner)), 505 file_runner_(std::move(file_runner)),
505 disk_space_function_(&base::SysInfo::AmountOfFreeDiskSpace), 506 disk_space_function_(&base::SysInfo::AmountOfFreeDiskSpace),
506 populated_memory_items_( 507 populated_memory_items_(
507 base::MRUCache<uint64_t, ShareableBlobDataItem*>::NO_AUTO_EVICT), 508 base::MRUCache<uint64_t, ShareableBlobDataItem*>::NO_AUTO_EVICT),
509 memory_pressure_listener_(
510 base::Bind(&BlobMemoryController::OnMemoryPressure,
511 base::Unretained(this))),
dmurph 2017/05/09 21:57:33 Unretained? How is this being registered? Can we u
ssid 2017/05/10 00:21:38 The unregistration is safe because the callback is
dmurph 2017/05/10 19:13:34 If you think that it won't get called after-free,
508 weak_factory_(this) {} 512 weak_factory_(this) {}
509 513
510 BlobMemoryController::~BlobMemoryController() {} 514 BlobMemoryController::~BlobMemoryController() {}
511 515
512 void BlobMemoryController::DisableFilePaging(base::File::Error reason) { 516 void BlobMemoryController::DisableFilePaging(base::File::Error reason) {
513 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingDisabled", -reason, 517 UMA_HISTOGRAM_ENUMERATION("Storage.Blob.PagingDisabled", -reason,
514 -File::FILE_ERROR_MAX); 518 -File::FILE_ERROR_MAX);
515 DLOG(ERROR) << "Blob storage paging disabled, reason: " << reason; 519 DLOG(ERROR) << "Blob storage paging disabled, reason: " << reason;
516 file_paging_enabled_ = false; 520 file_paging_enabled_ = false;
517 in_flight_memory_used_ = 0; 521 in_flight_memory_used_ = 0;
(...skipping 79 matching lines...) Expand 10 before | Expand all | Expand 10 after
597 // more paging for any more pending blobs. 601 // more paging for any more pending blobs.
598 if (!pending_memory_quota_tasks_.empty()) { 602 if (!pending_memory_quota_tasks_.empty()) {
599 return AppendMemoryTask(total_bytes_needed, 603 return AppendMemoryTask(total_bytes_needed,
600 std::move(unreserved_memory_items), done_callback); 604 std::move(unreserved_memory_items), done_callback);
601 } 605 }
602 606
603 // Store right away if we can. 607 // Store right away if we can.
604 if (total_bytes_needed <= GetAvailableMemoryForBlobs()) { 608 if (total_bytes_needed <= GetAvailableMemoryForBlobs()) {
605 GrantMemoryAllocations(&unreserved_memory_items, 609 GrantMemoryAllocations(&unreserved_memory_items,
606 static_cast<size_t>(total_bytes_needed)); 610 static_cast<size_t>(total_bytes_needed));
607 MaybeScheduleEvictionUntilSystemHealthy(); 611 MaybeScheduleEvictionUntilSystemHealthy(false /* on_memory_pressue */);
608 done_callback.Run(true); 612 done_callback.Run(true);
609 return base::WeakPtr<QuotaAllocationTask>(); 613 return base::WeakPtr<QuotaAllocationTask>();
610 } 614 }
611 615
612 // Size is larger than available memory. 616 // Size is larger than available memory.
613 DCHECK(pending_memory_quota_tasks_.empty()); 617 DCHECK(pending_memory_quota_tasks_.empty());
614 DCHECK_EQ(0u, pending_memory_quota_total_size_); 618 DCHECK_EQ(0u, pending_memory_quota_total_size_);
615 619
616 auto weak_ptr = AppendMemoryTask( 620 auto weak_ptr = AppendMemoryTask(
617 total_bytes_needed, std::move(unreserved_memory_items), done_callback); 621 total_bytes_needed, std::move(unreserved_memory_items), done_callback);
618 MaybeScheduleEvictionUntilSystemHealthy(); 622 MaybeScheduleEvictionUntilSystemHealthy(false /* on_memory_pressue */);
619 return weak_ptr; 623 return weak_ptr;
620 } 624 }
621 625
622 base::WeakPtr<QuotaAllocationTask> BlobMemoryController::ReserveFileQuota( 626 base::WeakPtr<QuotaAllocationTask> BlobMemoryController::ReserveFileQuota(
623 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_file_items, 627 std::vector<scoped_refptr<ShareableBlobDataItem>> unreserved_file_items,
624 const FileQuotaRequestCallback& done_callback) { 628 const FileQuotaRequestCallback& done_callback) {
625 pending_file_quota_tasks_.push_back(base::MakeUnique<FileQuotaAllocationTask>( 629 pending_file_quota_tasks_.push_back(base::MakeUnique<FileQuotaAllocationTask>(
626 this, disk_space_function_, std::move(unreserved_file_items), 630 this, disk_space_function_, std::move(unreserved_file_items),
627 done_callback)); 631 done_callback));
628 pending_file_quota_tasks_.back()->set_my_list_position( 632 pending_file_quota_tasks_.back()->set_my_list_position(
(...skipping 13 matching lines...) Expand all
642 items_paging_to_file_.end()) { 646 items_paging_to_file_.end()) {
643 return; 647 return;
644 } 648 }
645 auto iterator = populated_memory_items_.Get(item->item_id()); 649 auto iterator = populated_memory_items_.Get(item->item_id());
646 if (iterator == populated_memory_items_.end()) { 650 if (iterator == populated_memory_items_.end()) {
647 populated_memory_items_bytes_ += 651 populated_memory_items_bytes_ +=
648 static_cast<size_t>(item->item()->length()); 652 static_cast<size_t>(item->item()->length());
649 populated_memory_items_.Put(item->item_id(), item.get()); 653 populated_memory_items_.Put(item->item_id(), item.get());
650 } 654 }
651 } 655 }
652 MaybeScheduleEvictionUntilSystemHealthy(); 656 MaybeScheduleEvictionUntilSystemHealthy(false /* on_memory_pressue */);
653 } 657 }
654 658
655 void BlobMemoryController::CalculateBlobStorageLimits() { 659 void BlobMemoryController::CalculateBlobStorageLimits() {
656 if (file_runner_) { 660 if (file_runner_) {
657 PostTaskAndReplyWithResult( 661 PostTaskAndReplyWithResult(
658 file_runner_.get(), FROM_HERE, 662 file_runner_.get(), FROM_HERE,
659 base::Bind(&CalculateBlobStorageLimitsImpl, blob_storage_dir_, true), 663 base::Bind(&CalculateBlobStorageLimitsImpl, blob_storage_dir_, true),
660 base::Bind(&BlobMemoryController::OnStorageLimitsCalculated, 664 base::Bind(&BlobMemoryController::OnStorageLimitsCalculated,
661 weak_factory_.GetWeakPtr())); 665 weak_factory_.GetWeakPtr()));
662 } else { 666 } else {
(...skipping 101 matching lines...) Expand 10 before | Expand all | Expand 10 after
764 std::unique_ptr<MemoryQuotaAllocationTask> memory_task = 768 std::unique_ptr<MemoryQuotaAllocationTask> memory_task =
765 std::move(pending_memory_quota_tasks_.front()); 769 std::move(pending_memory_quota_tasks_.front());
766 pending_memory_quota_tasks_.pop_front(); 770 pending_memory_quota_tasks_.pop_front();
767 pending_memory_quota_total_size_ -= memory_task->allocation_size(); 771 pending_memory_quota_total_size_ -= memory_task->allocation_size();
768 memory_task->RunDoneCallback(true); 772 memory_task->RunDoneCallback(true);
769 } 773 }
770 RecordTracingCounters(); 774 RecordTracingCounters();
771 } 775 }
772 776
773 size_t BlobMemoryController::CollectItemsForEviction( 777 size_t BlobMemoryController::CollectItemsForEviction(
774 std::vector<scoped_refptr<ShareableBlobDataItem>>* output) { 778 std::vector<scoped_refptr<ShareableBlobDataItem>>* output,
779 uint64_t min_page_file_size) {
775 base::CheckedNumeric<size_t> total_items_size = 0; 780 base::CheckedNumeric<size_t> total_items_size = 0;
776 // Process the recent item list and remove items until we have at least a 781 // Process the recent item list and remove items until we have at least a
777 // minimum file size or we're at the end of our items to page to disk. 782 // minimum file size or we're at the end of our items to page to disk.
778 while (total_items_size.ValueOrDie() < limits_.min_page_file_size && 783 while (total_items_size.ValueOrDie() < min_page_file_size &&
779 !populated_memory_items_.empty()) { 784 !populated_memory_items_.empty()) {
780 auto iterator = --populated_memory_items_.end(); 785 auto iterator = --populated_memory_items_.end();
781 ShareableBlobDataItem* item = iterator->second; 786 ShareableBlobDataItem* item = iterator->second;
782 DCHECK_EQ(item->item()->type(), DataElement::TYPE_BYTES); 787 DCHECK_EQ(item->item()->type(), DataElement::TYPE_BYTES);
783 populated_memory_items_.Erase(iterator); 788 populated_memory_items_.Erase(iterator);
784 size_t size = base::checked_cast<size_t>(item->item()->length()); 789 size_t size = base::checked_cast<size_t>(item->item()->length());
785 populated_memory_items_bytes_ -= size; 790 populated_memory_items_bytes_ -= size;
786 total_items_size += size; 791 total_items_size += size;
787 output->push_back(make_scoped_refptr(item)); 792 output->push_back(make_scoped_refptr(item));
788 } 793 }
789 return total_items_size.ValueOrDie(); 794 return total_items_size.ValueOrDie();
790 } 795 }
791 796
792 void BlobMemoryController::MaybeScheduleEvictionUntilSystemHealthy() { 797 void BlobMemoryController::MaybeScheduleEvictionUntilSystemHealthy(
798 bool on_memory_pressure) {
793 // Don't do eviction when others are happening, as we don't change our 799 // Don't do eviction when others are happening, as we don't change our
794 // pending_memory_quota_total_size_ value until after the paging files have 800 // pending_memory_quota_total_size_ value until after the paging files have
795 // been written. 801 // been written.
796 if (pending_evictions_ != 0 || !file_paging_enabled_) 802 if (pending_evictions_ != 0 || !file_paging_enabled_)
797 return; 803 return;
798 804
799 uint64_t total_memory_usage = 805 uint64_t total_memory_usage =
800 static_cast<uint64_t>(pending_memory_quota_total_size_) + 806 static_cast<uint64_t>(pending_memory_quota_total_size_) +
801 blob_memory_used_; 807 blob_memory_used_;
802 808
809 size_t in_memory_limit = limits_.memory_limit_before_paging();
810 uint64_t min_page_file_size = limits_.min_page_file_size;
811 if (on_memory_pressure) {
812 in_memory_limit = 0;
dmurph 2017/05/09 21:57:33 Do we want to flush everything?
ssid 2017/05/10 00:21:38 Actually we would still not flush anything less th
813 // Use lower page file size to reduce using more memory for writing under
814 // pressure.
815 min_page_file_size = limits_.min_page_file_size_under_pressure;
816 }
817
803 // We try to page items to disk until our current system size + requested 818 // We try to page items to disk until our current system size + requested
804 // memory is below our size limit. 819 // memory is below our size limit.
805 // Size limit is a lower |memory_limit_before_paging()| if we have disk space. 820 // Size limit is a lower |memory_limit_before_paging()| if we have disk space.
806 while (total_memory_usage > limits_.effective_max_disk_space || 821 while (total_memory_usage > limits_.effective_max_disk_space ||
807 (disk_used_ < limits_.effective_max_disk_space && 822 (disk_used_ < limits_.effective_max_disk_space &&
808 total_memory_usage > limits_.memory_limit_before_paging())) { 823 total_memory_usage > in_memory_limit)) {
824 const char* reason = nullptr;
825 if (on_memory_pressure) {
826 reason = "OnMemoryPressure";
827 } else if (total_memory_usage > limits_.effective_max_disk_space) {
828 reason = "SizeExceededMaxDiskSpace";
829 } else {
830 reason = "SizeExceededInMemoryLimit";
831 }
832
809 // We only page when we have enough items to fill a whole page file. 833 // We only page when we have enough items to fill a whole page file.
810 if (populated_memory_items_bytes_ < limits_.min_page_file_size) 834 if (populated_memory_items_bytes_ < min_page_file_size)
811 break; 835 break;
812 DCHECK_LE(limits_.min_page_file_size, 836 DCHECK_LE(min_page_file_size, static_cast<uint64_t>(blob_memory_used_));
813 static_cast<uint64_t>(blob_memory_used_));
814 837
815 std::vector<scoped_refptr<ShareableBlobDataItem>> items_to_swap; 838 std::vector<scoped_refptr<ShareableBlobDataItem>> items_to_swap;
816 size_t total_items_size = CollectItemsForEviction(&items_to_swap); 839
840 size_t total_items_size =
841 CollectItemsForEviction(&items_to_swap, min_page_file_size);
817 if (total_items_size == 0) 842 if (total_items_size == 0)
818 break; 843 break;
819 844
820 std::vector<DataElement*> items_for_paging; 845 std::vector<DataElement*> items_for_paging;
821 for (auto& shared_blob_item : items_to_swap) { 846 for (auto& shared_blob_item : items_to_swap) {
822 items_paging_to_file_.insert(shared_blob_item->item_id()); 847 items_paging_to_file_.insert(shared_blob_item->item_id());
823 items_for_paging.push_back(shared_blob_item->item()->data_element_ptr()); 848 items_for_paging.push_back(shared_blob_item->item()->data_element_ptr());
824 } 849 }
825 850
826 // Update our bookkeeping. 851 // Update our bookkeeping.
(...skipping 15 matching lines...) Expand all
842 867
843 // Post the file writing task. 868 // Post the file writing task.
844 base::PostTaskAndReplyWithResult( 869 base::PostTaskAndReplyWithResult(
845 file_runner_.get(), FROM_HERE, 870 file_runner_.get(), FROM_HERE,
846 base::Bind(&CreateFileAndWriteItems, blob_storage_dir_, 871 base::Bind(&CreateFileAndWriteItems, blob_storage_dir_,
847 disk_space_function_, base::Passed(&page_file_path), 872 disk_space_function_, base::Passed(&page_file_path),
848 file_runner_, base::Passed(&items_for_paging), 873 file_runner_, base::Passed(&items_for_paging),
849 total_items_size), 874 total_items_size),
850 base::Bind(&BlobMemoryController::OnEvictionComplete, 875 base::Bind(&BlobMemoryController::OnEvictionComplete,
851 weak_factory_.GetWeakPtr(), base::Passed(&file_reference), 876 weak_factory_.GetWeakPtr(), base::Passed(&file_reference),
852 base::Passed(&items_to_swap), total_items_size)); 877 base::Passed(&items_to_swap), total_items_size, reason,
878 total_memory_usage));
879
880 last_eviction_time_ = base::TimeTicks::Now();
853 } 881 }
882
854 RecordTracingCounters(); 883 RecordTracingCounters();
855 } 884 }
856 885
857 void BlobMemoryController::OnEvictionComplete( 886 void BlobMemoryController::OnEvictionComplete(
858 scoped_refptr<ShareableFileReference> file_reference, 887 scoped_refptr<ShareableFileReference> file_reference,
859 std::vector<scoped_refptr<ShareableBlobDataItem>> items, 888 std::vector<scoped_refptr<ShareableBlobDataItem>> items,
860 size_t total_items_size, 889 size_t total_items_size,
890 const char* evict_reason,
891 size_t memory_usage_before_eviction,
861 std::pair<FileCreationInfo, int64_t /* avail_disk */> result) { 892 std::pair<FileCreationInfo, int64_t /* avail_disk */> result) {
862 if (!file_paging_enabled_) 893 if (!file_paging_enabled_)
863 return; 894 return;
864 895
865 FileCreationInfo& file_info = std::get<0>(result); 896 FileCreationInfo& file_info = std::get<0>(result);
866 int64_t avail_disk_space = std::get<1>(result); 897 int64_t avail_disk_space = std::get<1>(result);
867 898
868 if (file_info.error != File::FILE_OK) { 899 if (file_info.error != File::FILE_OK) {
869 DisableFilePaging(file_info.error); 900 DisableFilePaging(file_info.error);
870 return; 901 return;
(...skipping 15 matching lines...) Expand all
886 file_reference->path(), offset, shareable_item->item()->length(), 917 file_reference->path(), offset, shareable_item->item()->length(),
887 file_info.last_modified); 918 file_info.last_modified);
888 DCHECK(shareable_item->memory_allocation_); 919 DCHECK(shareable_item->memory_allocation_);
889 shareable_item->set_memory_allocation(nullptr); 920 shareable_item->set_memory_allocation(nullptr);
890 shareable_item->set_item(new_item); 921 shareable_item->set_item(new_item);
891 items_paging_to_file_.erase(shareable_item->item_id()); 922 items_paging_to_file_.erase(shareable_item->item_id());
892 offset += shareable_item->item()->length(); 923 offset += shareable_item->item()->length();
893 } 924 }
894 in_flight_memory_used_ -= total_items_size; 925 in_flight_memory_used_ -= total_items_size;
895 926
927 // Record change in memory usage at the last eviction reply.
928 size_t total_usage = blob_memory_used_ + pending_memory_quota_total_size_;
929 if (!pending_evictions_ && memory_usage_before_eviction >= total_usage) {
930 std::string full_histogram_name =
931 std::string("Storage.Blob.SizeEvictedToDiskInKB.") + evict_reason;
932 base::HistogramBase* histogram = base::Histogram::FactoryGet(
933 full_histogram_name, 1, 100000, 50,
934 base::HistogramBase::kUmaTargetedHistogramFlag);
935 if (histogram)
936 histogram->Add((memory_usage_before_eviction - total_usage) / 1024);
937 }
938
896 // We want callback on blobs up to the amount we've freed. 939 // We want callback on blobs up to the amount we've freed.
897 MaybeGrantPendingMemoryRequests(); 940 MaybeGrantPendingMemoryRequests();
898 941
899 // If we still have more blobs waiting and we're not waiting on more paging 942 // If we still have more blobs waiting and we're not waiting on more paging
900 // operations, schedule more. 943 // operations, schedule more.
901 MaybeScheduleEvictionUntilSystemHealthy(); 944 MaybeScheduleEvictionUntilSystemHealthy(false /* on_memory_pressue */);
945 }
946
947 void BlobMemoryController::OnMemoryPressure(
948 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
949 auto time_from_last_evicion = base::TimeTicks::Now() - last_eviction_time_;
950 if (time_from_last_evicion.InSeconds() < kMinSecondsForPressureEvictions)
951 return;
952
953 MaybeScheduleEvictionUntilSystemHealthy(true /* on_memory_pressure */);
902 } 954 }
903 955
904 FilePath BlobMemoryController::GenerateNextPageFileName() { 956 FilePath BlobMemoryController::GenerateNextPageFileName() {
905 std::string file_name = base::Uint64ToString(current_file_num_++); 957 std::string file_name = base::Uint64ToString(current_file_num_++);
906 return blob_storage_dir_.Append(FilePath::FromUTF8Unsafe(file_name)); 958 return blob_storage_dir_.Append(FilePath::FromUTF8Unsafe(file_name));
907 } 959 }
908 960
909 void BlobMemoryController::RecordTracingCounters() const { 961 void BlobMemoryController::RecordTracingCounters() const {
910 TRACE_COUNTER2("Blob", "MemoryUsage", "TotalStorage", blob_memory_used_, 962 TRACE_COUNTER2("Blob", "MemoryUsage", "TotalStorage", blob_memory_used_,
911 "InFlightToDisk", in_flight_memory_used_); 963 "InFlightToDisk", in_flight_memory_used_);
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
977 MaybeGrantPendingMemoryRequests(); 1029 MaybeGrantPendingMemoryRequests();
978 } 1030 }
979 1031
980 void BlobMemoryController::OnBlobFileDelete(uint64_t size, 1032 void BlobMemoryController::OnBlobFileDelete(uint64_t size,
981 const FilePath& path) { 1033 const FilePath& path) {
982 DCHECK_LE(size, disk_used_); 1034 DCHECK_LE(size, disk_used_);
983 disk_used_ -= size; 1035 disk_used_ -= size;
984 } 1036 }
985 1037
986 } // namespace storage 1038 } // namespace storage
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698