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

Side by Side Diff: components/discardable_memory/service/discardable_shared_memory_manager.cc

Issue 2459733002: Move discardable memory to //components from //content (Closed)
Patch Set: Fix build error Created 4 years, 1 month 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 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 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 "content/common/host_discardable_shared_memory_manager.h" 5 #include "components/discardable_memory/service/discardable_shared_memory_manage r.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <utility> 8 #include <utility>
9 9
10 #include "base/atomic_sequence_num.h" 10 #include "base/atomic_sequence_num.h"
11 #include "base/bind.h" 11 #include "base/bind.h"
12 #include "base/callback.h" 12 #include "base/callback.h"
13 #include "base/command_line.h"
13 #include "base/debug/crash_logging.h" 14 #include "base/debug/crash_logging.h"
14 #include "base/lazy_instance.h" 15 #include "base/lazy_instance.h"
15 #include "base/macros.h" 16 #include "base/macros.h"
16 #include "base/memory/discardable_memory.h" 17 #include "base/memory/discardable_memory.h"
17 #include "base/memory/memory_coordinator_client_registry.h" 18 #include "base/memory/memory_coordinator_client_registry.h"
18 #include "base/memory/ptr_util.h" 19 #include "base/memory/ptr_util.h"
19 #include "base/numerics/safe_math.h" 20 #include "base/numerics/safe_math.h"
20 #include "base/process/memory.h" 21 #include "base/process/memory.h"
21 #include "base/strings/string_number_conversions.h" 22 #include "base/strings/string_number_conversions.h"
22 #include "base/strings/stringprintf.h" 23 #include "base/strings/stringprintf.h"
23 #include "base/sys_info.h" 24 #include "base/sys_info.h"
24 #include "base/threading/thread_task_runner_handle.h" 25 #include "base/threading/thread_task_runner_handle.h"
25 #include "base/trace_event/memory_allocator_dump.h" 26 #include "base/trace_event/memory_allocator_dump.h"
26 #include "base/trace_event/memory_dump_manager.h" 27 #include "base/trace_event/memory_dump_manager.h"
27 #include "base/trace_event/process_memory_dump.h" 28 #include "base/trace_event/process_memory_dump.h"
28 #include "base/trace_event/trace_event.h" 29 #include "base/trace_event/trace_event.h"
29 #include "build/build_config.h" 30 #include "build/build_config.h"
30 #include "content/common/child_process_host_impl.h" 31 #include "components/discardable_memory/common/discardable_shared_memory_heap.h"
31 #include "content/common/discardable_shared_memory_heap.h"
32 #include "content/public/common/child_process_host.h"
33 32
34 #if defined(OS_LINUX) 33 #if defined(OS_LINUX)
35 #include "base/files/file_path.h" 34 #include "base/files/file_path.h"
36 #include "base/files/file_util.h" 35 #include "base/files/file_util.h"
37 #include "base/metrics/histogram_macros.h" 36 #include "base/metrics/histogram_macros.h"
38 #endif 37 #endif
39 38
40 namespace content { 39 namespace discardable_memory {
41 namespace { 40 namespace {
42 41
42 const char kSingleProcess[] = "single-process";
43
44 const int kInvalidUniqueClientID = -1;
45
46 const uint64_t kBrowserTracingProcessId = std::numeric_limits<uint64_t>::max();
47
48 uint64_t ClientProcessUniqueIdToTracingProcessId(int client_id) {
49 // TODO(penghuang): Move this function to right place.
50 // https://crbug.com/661257
51 if (base::CommandLine::ForCurrentProcess()->HasSwitch(kSingleProcess))
52 return kBrowserTracingProcessId;
53 // The hash value is incremented so that the tracing id is never equal to
54 // MemoryDumpManager::kInvalidTracingProcessId.
55 return static_cast<uint64_t>(base::Hash(
56 reinterpret_cast<const char*>(&client_id), sizeof(client_id))) +
57 1;
58 }
59
43 class DiscardableMemoryImpl : public base::DiscardableMemory { 60 class DiscardableMemoryImpl : public base::DiscardableMemory {
44 public: 61 public:
45 DiscardableMemoryImpl( 62 DiscardableMemoryImpl(
46 std::unique_ptr<base::DiscardableSharedMemory> shared_memory, 63 std::unique_ptr<base::DiscardableSharedMemory> shared_memory,
47 const base::Closure& deleted_callback) 64 const base::Closure& deleted_callback)
48 : shared_memory_(std::move(shared_memory)), 65 : shared_memory_(std::move(shared_memory)),
49 deleted_callback_(deleted_callback), 66 deleted_callback_(deleted_callback),
50 is_locked_(true) {} 67 is_locked_(true) {}
51 68
52 ~DiscardableMemoryImpl() override { 69 ~DiscardableMemoryImpl() override {
(...skipping 86 matching lines...) Expand 10 before | Expand all | Expand 10 after
139 max_default_memory_limit = 156 max_default_memory_limit =
140 std::min(max_default_memory_limit, shmem_dir_amount_of_free_space / 2); 157 std::min(max_default_memory_limit, shmem_dir_amount_of_free_space / 2);
141 } 158 }
142 #endif 159 #endif
143 160
144 // Allow 25% of physical memory to be used for discardable memory. 161 // Allow 25% of physical memory to be used for discardable memory.
145 return std::min(max_default_memory_limit, 162 return std::min(max_default_memory_limit,
146 base::SysInfo::AmountOfPhysicalMemory() / 4); 163 base::SysInfo::AmountOfPhysicalMemory() / 4);
147 } 164 }
148 165
149 base::LazyInstance<HostDiscardableSharedMemoryManager> 166 base::LazyInstance<DiscardableSharedMemoryManager>
150 g_discardable_shared_memory_manager = LAZY_INSTANCE_INITIALIZER; 167 g_discardable_shared_memory_manager = LAZY_INSTANCE_INITIALIZER;
151 168
152 const int kEnforceMemoryPolicyDelayMs = 1000; 169 const int kEnforceMemoryPolicyDelayMs = 1000;
153 170
154 // Global atomic to generate unique discardable shared memory IDs. 171 // Global atomic to generate unique discardable shared memory IDs.
155 base::StaticAtomicSequenceNumber g_next_discardable_shared_memory_id; 172 base::StaticAtomicSequenceNumber g_next_discardable_shared_memory_id;
156 173
157 } // namespace 174 } // namespace
158 175
159 HostDiscardableSharedMemoryManager::MemorySegment::MemorySegment( 176 DiscardableSharedMemoryManager::MemorySegment::MemorySegment(
160 std::unique_ptr<base::DiscardableSharedMemory> memory) 177 std::unique_ptr<base::DiscardableSharedMemory> memory)
161 : memory_(std::move(memory)) {} 178 : memory_(std::move(memory)) {}
162 179
163 HostDiscardableSharedMemoryManager::MemorySegment::~MemorySegment() { 180 DiscardableSharedMemoryManager::MemorySegment::~MemorySegment() {}
164 }
165 181
166 HostDiscardableSharedMemoryManager::HostDiscardableSharedMemoryManager() 182 DiscardableSharedMemoryManager::DiscardableSharedMemoryManager()
167 : default_memory_limit_(GetDefaultMemoryLimit()), 183 : default_memory_limit_(GetDefaultMemoryLimit()),
168 memory_limit_(default_memory_limit_), 184 memory_limit_(default_memory_limit_),
169 bytes_allocated_(0), 185 bytes_allocated_(0),
170 memory_pressure_listener_(new base::MemoryPressureListener( 186 memory_pressure_listener_(new base::MemoryPressureListener(
171 base::Bind(&HostDiscardableSharedMemoryManager::OnMemoryPressure, 187 base::Bind(&DiscardableSharedMemoryManager::OnMemoryPressure,
172 base::Unretained(this)))), 188 base::Unretained(this)))),
173 // Current thread might not have a task runner in tests. 189 // Current thread might not have a task runner in tests.
174 enforce_memory_policy_task_runner_(base::ThreadTaskRunnerHandle::Get()), 190 enforce_memory_policy_task_runner_(base::ThreadTaskRunnerHandle::Get()),
175 enforce_memory_policy_pending_(false), 191 enforce_memory_policy_pending_(false),
176 weak_ptr_factory_(this) { 192 weak_ptr_factory_(this) {
177 DCHECK_NE(memory_limit_, 0u); 193 DCHECK_NE(memory_limit_, 0u);
178 enforce_memory_policy_callback_ = 194 enforce_memory_policy_callback_ =
179 base::Bind(&HostDiscardableSharedMemoryManager::EnforceMemoryPolicy, 195 base::Bind(&DiscardableSharedMemoryManager::EnforceMemoryPolicy,
180 weak_ptr_factory_.GetWeakPtr()); 196 weak_ptr_factory_.GetWeakPtr());
181 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( 197 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
182 this, "HostDiscardableSharedMemoryManager", 198 this, "DiscardableSharedMemoryManager",
183 base::ThreadTaskRunnerHandle::Get()); 199 base::ThreadTaskRunnerHandle::Get());
184 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this); 200 base::MemoryCoordinatorClientRegistry::GetInstance()->Register(this);
185 } 201 }
186 202
187 HostDiscardableSharedMemoryManager::~HostDiscardableSharedMemoryManager() { 203 DiscardableSharedMemoryManager::~DiscardableSharedMemoryManager() {
188 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider( 204 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
189 this); 205 this);
190 } 206 }
191 207
192 HostDiscardableSharedMemoryManager* 208 DiscardableSharedMemoryManager* DiscardableSharedMemoryManager::current() {
193 HostDiscardableSharedMemoryManager::current() {
194 return g_discardable_shared_memory_manager.Pointer(); 209 return g_discardable_shared_memory_manager.Pointer();
195 } 210 }
196 211
197 std::unique_ptr<base::DiscardableMemory> 212 std::unique_ptr<base::DiscardableMemory>
198 HostDiscardableSharedMemoryManager::AllocateLockedDiscardableMemory( 213 DiscardableSharedMemoryManager::AllocateLockedDiscardableMemory(size_t size) {
199 size_t size) {
200 DCHECK_NE(size, 0u); 214 DCHECK_NE(size, 0u);
201 215
202 DiscardableSharedMemoryId new_id = 216 DiscardableSharedMemoryId new_id =
203 g_next_discardable_shared_memory_id.GetNext(); 217 g_next_discardable_shared_memory_id.GetNext();
204 base::ProcessHandle current_process_handle = base::GetCurrentProcessHandle(); 218 base::ProcessHandle current_process_handle = base::GetCurrentProcessHandle();
205 219
206 // Note: Use DiscardableSharedMemoryHeap for in-process allocation 220 // Note: Use DiscardableSharedMemoryHeap for in-process allocation
207 // of discardable memory if the cost of each allocation is too high. 221 // of discardable memory if the cost of each allocation is too high.
208 base::SharedMemoryHandle handle; 222 base::SharedMemoryHandle handle;
209 AllocateLockedDiscardableSharedMemory(current_process_handle, 223 AllocateLockedDiscardableSharedMemory(
210 ChildProcessHost::kInvalidUniqueID, 224 current_process_handle, kInvalidUniqueClientID, size, new_id, &handle);
211 size, new_id, &handle);
212 std::unique_ptr<base::DiscardableSharedMemory> memory( 225 std::unique_ptr<base::DiscardableSharedMemory> memory(
213 new base::DiscardableSharedMemory(handle)); 226 new base::DiscardableSharedMemory(handle));
214 if (!memory->Map(size)) 227 if (!memory->Map(size))
215 base::TerminateBecauseOutOfMemory(size); 228 base::TerminateBecauseOutOfMemory(size);
216 // Close file descriptor to avoid running out. 229 // Close file descriptor to avoid running out.
217 memory->Close(); 230 memory->Close();
218 return base::MakeUnique<DiscardableMemoryImpl>( 231 return base::MakeUnique<DiscardableMemoryImpl>(
219 std::move(memory), 232 std::move(memory),
220 base::Bind( 233 base::Bind(
221 &HostDiscardableSharedMemoryManager::DeletedDiscardableSharedMemory, 234 &DiscardableSharedMemoryManager::DeletedDiscardableSharedMemory,
222 base::Unretained(this), new_id, ChildProcessHost::kInvalidUniqueID)); 235 base::Unretained(this), new_id, kInvalidUniqueClientID));
223 } 236 }
224 237
225 bool HostDiscardableSharedMemoryManager::OnMemoryDump( 238 bool DiscardableSharedMemoryManager::OnMemoryDump(
226 const base::trace_event::MemoryDumpArgs& args, 239 const base::trace_event::MemoryDumpArgs& args,
227 base::trace_event::ProcessMemoryDump* pmd) { 240 base::trace_event::ProcessMemoryDump* pmd) {
228 if (args.level_of_detail == 241 if (args.level_of_detail ==
229 base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND) { 242 base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND) {
230 base::trace_event::MemoryAllocatorDump* total_dump = 243 base::trace_event::MemoryAllocatorDump* total_dump =
231 pmd->CreateAllocatorDump("discardable"); 244 pmd->CreateAllocatorDump("discardable");
232 total_dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize, 245 total_dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize,
233 base::trace_event::MemoryAllocatorDump::kUnitsBytes, 246 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
234 GetBytesAllocated()); 247 GetBytesAllocated());
235 return true; 248 return true;
236 } 249 }
237 250
238 base::AutoLock lock(lock_); 251 base::AutoLock lock(lock_);
239 for (const auto& process_entry : processes_) { 252 for (const auto& client_entry : clients_) {
240 const int child_process_id = process_entry.first; 253 const int client_id = client_entry.first;
241 const MemorySegmentMap& process_segments = process_entry.second; 254 const MemorySegmentMap& client_segments = client_entry.second;
242 for (const auto& segment_entry : process_segments) { 255 for (const auto& segment_entry : client_segments) {
243 const int segment_id = segment_entry.first; 256 const int segment_id = segment_entry.first;
244 const MemorySegment* segment = segment_entry.second.get(); 257 const MemorySegment* segment = segment_entry.second.get();
245 if (!segment->memory()->mapped_size()) 258 if (!segment->memory()->mapped_size())
246 continue; 259 continue;
247 260
248 // The "size" will be inherited form the shared global dump. 261 // The "size" will be inherited form the shared global dump.
249 std::string dump_name = base::StringPrintf( 262 std::string dump_name = base::StringPrintf(
250 "discardable/process_%x/segment_%d", child_process_id, segment_id); 263 "discardable/process_%x/segment_%d", client_id, segment_id);
251 base::trace_event::MemoryAllocatorDump* dump = 264 base::trace_event::MemoryAllocatorDump* dump =
252 pmd->CreateAllocatorDump(dump_name); 265 pmd->CreateAllocatorDump(dump_name);
253 266
254 dump->AddScalar("virtual_size", 267 dump->AddScalar("virtual_size",
255 base::trace_event::MemoryAllocatorDump::kUnitsBytes, 268 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
256 segment->memory()->mapped_size()); 269 segment->memory()->mapped_size());
257 270
258 // Host can only tell if whole segment is locked or not. 271 // Host can only tell if whole segment is locked or not.
259 dump->AddScalar( 272 dump->AddScalar(
260 "locked_size", base::trace_event::MemoryAllocatorDump::kUnitsBytes, 273 "locked_size", base::trace_event::MemoryAllocatorDump::kUnitsBytes,
261 segment->memory()->IsMemoryLocked() ? segment->memory()->mapped_size() 274 segment->memory()->IsMemoryLocked() ? segment->memory()->mapped_size()
262 : 0u); 275 : 0u);
263 276
264 // Create the cross-process ownership edge. If the child creates a 277 // Create the cross-process ownership edge. If the client creates a
265 // corresponding dump for the same segment, this will avoid to 278 // corresponding dump for the same segment, this will avoid to
266 // double-count them in tracing. If, instead, no other process will emit a 279 // double-count them in tracing. If, instead, no other process will emit a
267 // dump with the same guid, the segment will be accounted to the browser. 280 // dump with the same guid, the segment will be accounted to the browser.
268 const uint64_t child_tracing_process_id = 281 const uint64_t client_tracing_id =
269 ChildProcessHostImpl::ChildProcessUniqueIdToTracingProcessId( 282 ClientProcessUniqueIdToTracingProcessId(client_id);
270 child_process_id);
271 base::trace_event::MemoryAllocatorDumpGuid shared_segment_guid = 283 base::trace_event::MemoryAllocatorDumpGuid shared_segment_guid =
272 DiscardableSharedMemoryHeap::GetSegmentGUIDForTracing( 284 DiscardableSharedMemoryHeap::GetSegmentGUIDForTracing(
273 child_tracing_process_id, segment_id); 285 client_tracing_id, segment_id);
274 pmd->CreateSharedGlobalAllocatorDump(shared_segment_guid); 286 pmd->CreateSharedGlobalAllocatorDump(shared_segment_guid);
275 pmd->AddOwnershipEdge(dump->guid(), shared_segment_guid); 287 pmd->AddOwnershipEdge(dump->guid(), shared_segment_guid);
276 288
277 #if defined(COUNT_RESIDENT_BYTES_SUPPORTED) 289 #if defined(COUNT_RESIDENT_BYTES_SUPPORTED)
278 if (args.level_of_detail == 290 if (args.level_of_detail ==
279 base::trace_event::MemoryDumpLevelOfDetail::DETAILED) { 291 base::trace_event::MemoryDumpLevelOfDetail::DETAILED) {
280 size_t resident_size = 292 size_t resident_size =
281 base::trace_event::ProcessMemoryDump::CountResidentBytes( 293 base::trace_event::ProcessMemoryDump::CountResidentBytes(
282 segment->memory()->memory(), segment->memory()->mapped_size()); 294 segment->memory()->memory(), segment->memory()->mapped_size());
283 295
284 // This is added to the global dump since it has to be attributed to 296 // This is added to the global dump since it has to be attributed to
285 // both the allocator dumps involved. 297 // both the allocator dumps involved.
286 pmd->GetSharedGlobalAllocatorDump(shared_segment_guid) 298 pmd->GetSharedGlobalAllocatorDump(shared_segment_guid)
287 ->AddScalar("resident_size", 299 ->AddScalar("resident_size",
288 base::trace_event::MemoryAllocatorDump::kUnitsBytes, 300 base::trace_event::MemoryAllocatorDump::kUnitsBytes,
289 static_cast<uint64_t>(resident_size)); 301 static_cast<uint64_t>(resident_size));
290 } 302 }
291 #endif // defined(COUNT_RESIDENT_BYTES_SUPPORTED) 303 #endif // defined(COUNT_RESIDENT_BYTES_SUPPORTED)
292 } 304 }
293 } 305 }
294 return true; 306 return true;
295 } 307 }
296 308
297 void HostDiscardableSharedMemoryManager:: 309 void DiscardableSharedMemoryManager::
298 AllocateLockedDiscardableSharedMemoryForChild( 310 AllocateLockedDiscardableSharedMemoryForClient(
299 base::ProcessHandle process_handle, 311 base::ProcessHandle process_handle,
300 int child_process_id, 312 int client_id,
301 size_t size, 313 size_t size,
302 DiscardableSharedMemoryId id, 314 DiscardableSharedMemoryId id,
303 base::SharedMemoryHandle* shared_memory_handle) { 315 base::SharedMemoryHandle* shared_memory_handle) {
304 AllocateLockedDiscardableSharedMemory(process_handle, child_process_id, size, 316 AllocateLockedDiscardableSharedMemory(process_handle, client_id, size, id,
305 id, shared_memory_handle); 317 shared_memory_handle);
306 } 318 }
307 319
308 void HostDiscardableSharedMemoryManager::ChildDeletedDiscardableSharedMemory( 320 void DiscardableSharedMemoryManager::ClientDeletedDiscardableSharedMemory(
309 DiscardableSharedMemoryId id, 321 DiscardableSharedMemoryId id,
310 int child_process_id) { 322 int client_id) {
311 DeletedDiscardableSharedMemory(id, child_process_id); 323 DeletedDiscardableSharedMemory(id, client_id);
312 } 324 }
313 325
314 void HostDiscardableSharedMemoryManager::ProcessRemoved(int child_process_id) { 326 void DiscardableSharedMemoryManager::ClientRemoved(int client_id) {
315 base::AutoLock lock(lock_); 327 base::AutoLock lock(lock_);
316 328
317 ProcessMap::iterator process_it = processes_.find(child_process_id); 329 auto it = clients_.find(client_id);
318 if (process_it == processes_.end()) 330 if (it == clients_.end())
319 return; 331 return;
320 332
321 size_t bytes_allocated_before_releasing_memory = bytes_allocated_; 333 size_t bytes_allocated_before_releasing_memory = bytes_allocated_;
322 334
323 for (auto& segment_it : process_it->second) 335 for (auto& segment_it : it->second)
324 ReleaseMemory(segment_it.second->memory()); 336 ReleaseMemory(segment_it.second->memory());
325 337
326 processes_.erase(process_it); 338 clients_.erase(it);
327 339
328 if (bytes_allocated_ != bytes_allocated_before_releasing_memory) 340 if (bytes_allocated_ != bytes_allocated_before_releasing_memory)
329 BytesAllocatedChanged(bytes_allocated_); 341 BytesAllocatedChanged(bytes_allocated_);
330 } 342 }
331 343
332 void HostDiscardableSharedMemoryManager::SetMemoryLimit(size_t limit) { 344 void DiscardableSharedMemoryManager::SetMemoryLimit(size_t limit) {
333 base::AutoLock lock(lock_); 345 base::AutoLock lock(lock_);
334 346
335 memory_limit_ = limit; 347 memory_limit_ = limit;
336 ReduceMemoryUsageUntilWithinMemoryLimit(); 348 ReduceMemoryUsageUntilWithinMemoryLimit();
337 } 349 }
338 350
339 void HostDiscardableSharedMemoryManager::EnforceMemoryPolicy() { 351 void DiscardableSharedMemoryManager::EnforceMemoryPolicy() {
340 base::AutoLock lock(lock_); 352 base::AutoLock lock(lock_);
341 353
342 enforce_memory_policy_pending_ = false; 354 enforce_memory_policy_pending_ = false;
343 ReduceMemoryUsageUntilWithinMemoryLimit(); 355 ReduceMemoryUsageUntilWithinMemoryLimit();
344 } 356 }
345 357
346 size_t HostDiscardableSharedMemoryManager::GetBytesAllocated() { 358 size_t DiscardableSharedMemoryManager::GetBytesAllocated() {
347 base::AutoLock lock(lock_); 359 base::AutoLock lock(lock_);
348 360
349 return bytes_allocated_; 361 return bytes_allocated_;
350 } 362 }
351 363
352 void HostDiscardableSharedMemoryManager::OnMemoryStateChange( 364 void DiscardableSharedMemoryManager::OnMemoryStateChange(
353 base::MemoryState state) { 365 base::MemoryState state) {
354 switch (state) { 366 switch (state) {
355 case base::MemoryState::NORMAL: 367 case base::MemoryState::NORMAL:
356 SetMemoryLimit(default_memory_limit_); 368 SetMemoryLimit(default_memory_limit_);
357 break; 369 break;
358 case base::MemoryState::THROTTLED: 370 case base::MemoryState::THROTTLED:
359 SetMemoryLimit(0); 371 SetMemoryLimit(0);
360 break; 372 break;
361 case base::MemoryState::SUSPENDED: 373 case base::MemoryState::SUSPENDED:
362 // Note that SUSPENDED never occurs in the main browser process so far. 374 // Note that SUSPENDED never occurs in the main browser process so far.
363 // Fall through. 375 // Fall through.
364 case base::MemoryState::UNKNOWN: 376 case base::MemoryState::UNKNOWN:
365 NOTREACHED(); 377 NOTREACHED();
366 break; 378 break;
367 } 379 }
368 } 380 }
369 381
370 void HostDiscardableSharedMemoryManager::AllocateLockedDiscardableSharedMemory( 382 void DiscardableSharedMemoryManager::AllocateLockedDiscardableSharedMemory(
371 base::ProcessHandle process_handle, 383 base::ProcessHandle process_handle,
372 int client_process_id, 384 int client_id,
373 size_t size, 385 size_t size,
374 DiscardableSharedMemoryId id, 386 DiscardableSharedMemoryId id,
375 base::SharedMemoryHandle* shared_memory_handle) { 387 base::SharedMemoryHandle* shared_memory_handle) {
376 base::AutoLock lock(lock_); 388 base::AutoLock lock(lock_);
377 389
378 // Make sure |id| is not already in use. 390 // Make sure |id| is not already in use.
379 MemorySegmentMap& process_segments = processes_[client_process_id]; 391 MemorySegmentMap& client_segments = clients_[client_id];
380 if (process_segments.find(id) != process_segments.end()) { 392 if (client_segments.find(id) != client_segments.end()) {
381 LOG(ERROR) << "Invalid discardable shared memory ID"; 393 LOG(ERROR) << "Invalid discardable shared memory ID";
382 *shared_memory_handle = base::SharedMemory::NULLHandle(); 394 *shared_memory_handle = base::SharedMemory::NULLHandle();
383 return; 395 return;
384 } 396 }
385 397
386 // Memory usage must be reduced to prevent the addition of |size| from 398 // Memory usage must be reduced to prevent the addition of |size| from
387 // taking usage above the limit. Usage should be reduced to 0 in cases 399 // taking usage above the limit. Usage should be reduced to 0 in cases
388 // where |size| is greater than the limit. 400 // where |size| is greater than the limit.
389 size_t limit = 0; 401 size_t limit = 0;
390 // Note: the actual mapped size can be larger than requested and cause 402 // Note: the actual mapped size can be larger than requested and cause
(...skipping 26 matching lines...) Expand all
417 checked_bytes_allocated += memory->mapped_size(); 429 checked_bytes_allocated += memory->mapped_size();
418 if (!checked_bytes_allocated.IsValid()) { 430 if (!checked_bytes_allocated.IsValid()) {
419 *shared_memory_handle = base::SharedMemory::NULLHandle(); 431 *shared_memory_handle = base::SharedMemory::NULLHandle();
420 return; 432 return;
421 } 433 }
422 434
423 bytes_allocated_ = checked_bytes_allocated.ValueOrDie(); 435 bytes_allocated_ = checked_bytes_allocated.ValueOrDie();
424 BytesAllocatedChanged(bytes_allocated_); 436 BytesAllocatedChanged(bytes_allocated_);
425 437
426 scoped_refptr<MemorySegment> segment(new MemorySegment(std::move(memory))); 438 scoped_refptr<MemorySegment> segment(new MemorySegment(std::move(memory)));
427 process_segments[id] = segment.get(); 439 client_segments[id] = segment.get();
428 segments_.push_back(segment.get()); 440 segments_.push_back(segment.get());
429 std::push_heap(segments_.begin(), segments_.end(), CompareMemoryUsageTime); 441 std::push_heap(segments_.begin(), segments_.end(), CompareMemoryUsageTime);
430 442
431 if (bytes_allocated_ > memory_limit_) 443 if (bytes_allocated_ > memory_limit_)
432 ScheduleEnforceMemoryPolicy(); 444 ScheduleEnforceMemoryPolicy();
433 } 445 }
434 446
435 void HostDiscardableSharedMemoryManager::DeletedDiscardableSharedMemory( 447 void DiscardableSharedMemoryManager::DeletedDiscardableSharedMemory(
436 DiscardableSharedMemoryId id, 448 DiscardableSharedMemoryId id,
437 int client_process_id) { 449 int client_id) {
438 base::AutoLock lock(lock_); 450 base::AutoLock lock(lock_);
439 451
440 MemorySegmentMap& process_segments = processes_[client_process_id]; 452 MemorySegmentMap& client_segments = clients_[client_id];
441 453
442 MemorySegmentMap::iterator segment_it = process_segments.find(id); 454 MemorySegmentMap::iterator segment_it = client_segments.find(id);
443 if (segment_it == process_segments.end()) { 455 if (segment_it == client_segments.end()) {
444 LOG(ERROR) << "Invalid discardable shared memory ID"; 456 LOG(ERROR) << "Invalid discardable shared memory ID";
445 return; 457 return;
446 } 458 }
447 459
448 size_t bytes_allocated_before_releasing_memory = bytes_allocated_; 460 size_t bytes_allocated_before_releasing_memory = bytes_allocated_;
449 461
450 ReleaseMemory(segment_it->second->memory()); 462 ReleaseMemory(segment_it->second->memory());
451 463
452 process_segments.erase(segment_it); 464 client_segments.erase(segment_it);
453 465
454 if (bytes_allocated_ != bytes_allocated_before_releasing_memory) 466 if (bytes_allocated_ != bytes_allocated_before_releasing_memory)
455 BytesAllocatedChanged(bytes_allocated_); 467 BytesAllocatedChanged(bytes_allocated_);
456 } 468 }
457 469
458 void HostDiscardableSharedMemoryManager::OnMemoryPressure( 470 void DiscardableSharedMemoryManager::OnMemoryPressure(
459 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) { 471 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
460 base::AutoLock lock(lock_); 472 base::AutoLock lock(lock_);
461 473
462 switch (memory_pressure_level) { 474 switch (memory_pressure_level) {
463 case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE: 475 case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE:
464 break; 476 break;
465 case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE: 477 case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE:
466 // Purge memory until usage is within half of |memory_limit_|. 478 // Purge memory until usage is within half of |memory_limit_|.
467 ReduceMemoryUsageUntilWithinLimit(memory_limit_ / 2); 479 ReduceMemoryUsageUntilWithinLimit(memory_limit_ / 2);
468 break; 480 break;
469 case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL: 481 case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL:
470 // Purge everything possible when pressure is critical. 482 // Purge everything possible when pressure is critical.
471 ReduceMemoryUsageUntilWithinLimit(0); 483 ReduceMemoryUsageUntilWithinLimit(0);
472 break; 484 break;
473 } 485 }
474 } 486 }
475 487
476 void 488 void DiscardableSharedMemoryManager::ReduceMemoryUsageUntilWithinMemoryLimit() {
477 HostDiscardableSharedMemoryManager::ReduceMemoryUsageUntilWithinMemoryLimit() {
478 lock_.AssertAcquired(); 489 lock_.AssertAcquired();
479 490
480 if (bytes_allocated_ <= memory_limit_) 491 if (bytes_allocated_ <= memory_limit_)
481 return; 492 return;
482 493
483 ReduceMemoryUsageUntilWithinLimit(memory_limit_); 494 ReduceMemoryUsageUntilWithinLimit(memory_limit_);
484 if (bytes_allocated_ > memory_limit_) 495 if (bytes_allocated_ > memory_limit_)
485 ScheduleEnforceMemoryPolicy(); 496 ScheduleEnforceMemoryPolicy();
486 } 497 }
487 498
488 void HostDiscardableSharedMemoryManager::ReduceMemoryUsageUntilWithinLimit( 499 void DiscardableSharedMemoryManager::ReduceMemoryUsageUntilWithinLimit(
489 size_t limit) { 500 size_t limit) {
490 TRACE_EVENT1("renderer_host", 501 TRACE_EVENT1("renderer_host",
491 "HostDiscardableSharedMemoryManager::" 502 "DiscardableSharedMemoryManager::"
492 "ReduceMemoryUsageUntilWithinLimit", 503 "ReduceMemoryUsageUntilWithinLimit",
493 "bytes_allocated", 504 "bytes_allocated", bytes_allocated_);
494 bytes_allocated_);
495 505
496 // Usage time of currently locked segments are updated to this time and 506 // Usage time of currently locked segments are updated to this time and
497 // we stop eviction attempts as soon as we come across a segment that we've 507 // we stop eviction attempts as soon as we come across a segment that we've
498 // previously tried to evict but was locked. 508 // previously tried to evict but was locked.
499 base::Time current_time = Now(); 509 base::Time current_time = Now();
500 510
501 lock_.AssertAcquired(); 511 lock_.AssertAcquired();
502 size_t bytes_allocated_before_purging = bytes_allocated_; 512 size_t bytes_allocated_before_purging = bytes_allocated_;
503 while (!segments_.empty()) { 513 while (!segments_.empty()) {
504 if (bytes_allocated_ <= limit) 514 if (bytes_allocated_ <= limit)
(...skipping 22 matching lines...) Expand all
527 // Add memory segment (with updated usage timestamp) back on heap after 537 // Add memory segment (with updated usage timestamp) back on heap after
528 // failed attempt to purge it. 538 // failed attempt to purge it.
529 segments_.push_back(segment.get()); 539 segments_.push_back(segment.get());
530 std::push_heap(segments_.begin(), segments_.end(), CompareMemoryUsageTime); 540 std::push_heap(segments_.begin(), segments_.end(), CompareMemoryUsageTime);
531 } 541 }
532 542
533 if (bytes_allocated_ != bytes_allocated_before_purging) 543 if (bytes_allocated_ != bytes_allocated_before_purging)
534 BytesAllocatedChanged(bytes_allocated_); 544 BytesAllocatedChanged(bytes_allocated_);
535 } 545 }
536 546
537 void HostDiscardableSharedMemoryManager::ReleaseMemory( 547 void DiscardableSharedMemoryManager::ReleaseMemory(
538 base::DiscardableSharedMemory* memory) { 548 base::DiscardableSharedMemory* memory) {
539 lock_.AssertAcquired(); 549 lock_.AssertAcquired();
540 550
541 size_t size = memory->mapped_size(); 551 size_t size = memory->mapped_size();
542 DCHECK_GE(bytes_allocated_, size); 552 DCHECK_GE(bytes_allocated_, size);
543 bytes_allocated_ -= size; 553 bytes_allocated_ -= size;
544 554
545 // This will unmap the memory segment and drop our reference. The result 555 // This will unmap the memory segment and drop our reference. The result
546 // is that the memory will be released to the OS if the child process is 556 // is that the memory will be released to the OS if the client is no longer
547 // no longer referencing it. 557 // referencing it.
548 // Note: We intentionally leave the segment in the |segments| vector to 558 // Note: We intentionally leave the segment in the |segments| vector to
549 // avoid reconstructing the heap. The element will be removed from the heap 559 // avoid reconstructing the heap. The element will be removed from the heap
550 // when its last usage time is older than all other segments. 560 // when its last usage time is older than all other segments.
551 memory->Unmap(); 561 memory->Unmap();
552 memory->Close(); 562 memory->Close();
553 } 563 }
554 564
555 void HostDiscardableSharedMemoryManager::BytesAllocatedChanged( 565 void DiscardableSharedMemoryManager::BytesAllocatedChanged(
556 size_t new_bytes_allocated) const { 566 size_t new_bytes_allocated) const {
557 static const char kTotalDiscardableMemoryAllocatedKey[] = 567 static const char kTotalDiscardableMemoryAllocatedKey[] =
558 "total-discardable-memory-allocated"; 568 "total-discardable-memory-allocated";
559 base::debug::SetCrashKeyValue(kTotalDiscardableMemoryAllocatedKey, 569 base::debug::SetCrashKeyValue(kTotalDiscardableMemoryAllocatedKey,
560 base::Uint64ToString(new_bytes_allocated)); 570 base::Uint64ToString(new_bytes_allocated));
561 } 571 }
562 572
563 base::Time HostDiscardableSharedMemoryManager::Now() const { 573 base::Time DiscardableSharedMemoryManager::Now() const {
564 return base::Time::Now(); 574 return base::Time::Now();
565 } 575 }
566 576
567 void HostDiscardableSharedMemoryManager::ScheduleEnforceMemoryPolicy() { 577 void DiscardableSharedMemoryManager::ScheduleEnforceMemoryPolicy() {
568 lock_.AssertAcquired(); 578 lock_.AssertAcquired();
569 579
570 if (enforce_memory_policy_pending_) 580 if (enforce_memory_policy_pending_)
571 return; 581 return;
572 582
573 enforce_memory_policy_pending_ = true; 583 enforce_memory_policy_pending_ = true;
574 DCHECK(enforce_memory_policy_task_runner_); 584 DCHECK(enforce_memory_policy_task_runner_);
575 enforce_memory_policy_task_runner_->PostDelayedTask( 585 enforce_memory_policy_task_runner_->PostDelayedTask(
576 FROM_HERE, enforce_memory_policy_callback_, 586 FROM_HERE, enforce_memory_policy_callback_,
577 base::TimeDelta::FromMilliseconds(kEnforceMemoryPolicyDelayMs)); 587 base::TimeDelta::FromMilliseconds(kEnforceMemoryPolicyDelayMs));
578 } 588 }
579 589
580 } // namespace content 590 } // namespace discardable_memory
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698