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
3 // found in the LICENSE file.
5 #include "content/child/child_discardable_shared_memory_manager.h"
7 #include "base/atomic_sequence_num.h"
9 #include "base/debug/crash_logging.h"
10 #include "base/memory/discardable_memory.h"
11 #include "base/memory/discardable_shared_memory.h"
12 #include "base/metrics/histogram.h"
13 #include "base/process/memory.h"
14 #include "base/process/process_metrics.h"
15 #include "base/strings/string_number_conversions.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/trace_event/memory_dump_manager.h"
18 #include "base/trace_event/trace_event.h"
19 #include "content/common/child_process_messages.h"
24 // Default allocation size.
25 const size_t kAllocationSize
= 4 * 1024 * 1024;
27 // Global atomic to generate unique discardable shared memory IDs.
28 base::StaticAtomicSequenceNumber g_next_discardable_shared_memory_id
;
30 class DiscardableMemoryImpl
: public base::DiscardableMemory
{
32 DiscardableMemoryImpl(ChildDiscardableSharedMemoryManager
* manager
,
33 scoped_ptr
<DiscardableSharedMemoryHeap::Span
> span
)
34 : manager_(manager
), span_(span
.Pass()), is_locked_(true) {}
36 ~DiscardableMemoryImpl() override
{
38 manager_
->UnlockSpan(span_
.get());
40 manager_
->ReleaseSpan(span_
.Pass());
43 // Overridden from base::DiscardableMemory:
44 bool Lock() override
{
47 if (!manager_
->LockSpan(span_
.get()))
53 void Unlock() override
{
56 manager_
->UnlockSpan(span_
.get());
59 void* data() const override
{
61 return reinterpret_cast<void*>(span_
->start() * base::GetPageSize());
65 ChildDiscardableSharedMemoryManager
* const manager_
;
66 scoped_ptr
<DiscardableSharedMemoryHeap::Span
> span_
;
69 DISALLOW_COPY_AND_ASSIGN(DiscardableMemoryImpl
);
72 void SendDeletedDiscardableSharedMemoryMessage(
73 scoped_refptr
<ThreadSafeSender
> sender
,
74 DiscardableSharedMemoryId id
) {
75 sender
->Send(new ChildProcessHostMsg_DeletedDiscardableSharedMemory(id
));
80 ChildDiscardableSharedMemoryManager::ChildDiscardableSharedMemoryManager(
81 ThreadSafeSender
* sender
)
82 : heap_(base::GetPageSize()), sender_(sender
) {
83 base::trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider(
84 this, base::ThreadTaskRunnerHandle::Get());
87 ChildDiscardableSharedMemoryManager::~ChildDiscardableSharedMemoryManager() {
88 base::trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(
90 // TODO(reveman): Determine if this DCHECK can be enabled. crbug.com/430533
91 // DCHECK_EQ(heap_.GetSize(), heap_.GetSizeOfFreeLists());
93 MemoryUsageChanged(0, 0);
96 scoped_ptr
<base::DiscardableMemory
>
97 ChildDiscardableSharedMemoryManager::AllocateLockedDiscardableMemory(
99 base::AutoLock
lock(lock_
);
103 UMA_HISTOGRAM_CUSTOM_COUNTS("Memory.DiscardableAllocationSize",
104 size
/ 1024, // In KB
106 4 * 1024 * 1024, // 4 GB
109 // Round up to multiple of page size.
110 size_t pages
= (size
+ base::GetPageSize() - 1) / base::GetPageSize();
112 // Default allocation size in pages.
113 size_t allocation_pages
= kAllocationSize
/ base::GetPageSize();
116 // When searching the free lists, allow a slack between required size and
117 // free span size that is less or equal to kAllocationSize. This is to
118 // avoid segments larger then kAllocationSize unless they are a perfect
119 // fit. The result is that large allocations can be reused without reducing
120 // the ability to discard memory.
121 if (pages
< allocation_pages
)
122 slack
= allocation_pages
- pages
;
124 size_t heap_size_prior_to_releasing_purged_memory
= heap_
.GetSize();
126 // Search free lists for suitable span.
127 scoped_ptr
<DiscardableSharedMemoryHeap::Span
> free_span
=
128 heap_
.SearchFreeLists(pages
, slack
);
129 if (!free_span
.get())
132 // Attempt to lock |free_span|. Delete span and search free lists again
133 // if locking failed.
134 if (free_span
->shared_memory()->Lock(
135 free_span
->start() * base::GetPageSize() -
136 reinterpret_cast<size_t>(free_span
->shared_memory()->memory()),
137 free_span
->length() * base::GetPageSize()) ==
138 base::DiscardableSharedMemory::FAILED
) {
139 DCHECK(!free_span
->shared_memory()->IsMemoryResident());
140 // We have to release purged memory before |free_span| can be destroyed.
141 heap_
.ReleasePurgedMemory();
142 DCHECK(!free_span
->shared_memory());
146 // Memory usage is guaranteed to have changed after having removed
147 // at least one span from the free lists.
148 MemoryUsageChanged(heap_
.GetSize(), heap_
.GetSizeOfFreeLists());
150 return make_scoped_ptr(new DiscardableMemoryImpl(this, free_span
.Pass()));
153 // Release purged memory to free up the address space before we attempt to
154 // allocate more memory.
155 heap_
.ReleasePurgedMemory();
157 // Make sure crash keys are up to date in case allocation fails.
158 if (heap_
.GetSize() != heap_size_prior_to_releasing_purged_memory
)
159 MemoryUsageChanged(heap_
.GetSize(), heap_
.GetSizeOfFreeLists());
161 size_t pages_to_allocate
=
162 std::max(kAllocationSize
/ base::GetPageSize(), pages
);
163 size_t allocation_size_in_bytes
= pages_to_allocate
* base::GetPageSize();
165 DiscardableSharedMemoryId new_id
=
166 g_next_discardable_shared_memory_id
.GetNext();
168 // Ask parent process to allocate a new discardable shared memory segment.
169 scoped_ptr
<base::DiscardableSharedMemory
> shared_memory(
170 AllocateLockedDiscardableSharedMemory(allocation_size_in_bytes
, new_id
));
172 // Create span for allocated memory.
173 scoped_ptr
<DiscardableSharedMemoryHeap::Span
> new_span(heap_
.Grow(
174 shared_memory
.Pass(), allocation_size_in_bytes
, new_id
,
175 base::Bind(&SendDeletedDiscardableSharedMemoryMessage
, sender_
, new_id
)));
177 // Unlock and insert any left over memory into free lists.
178 if (pages
< pages_to_allocate
) {
179 scoped_ptr
<DiscardableSharedMemoryHeap::Span
> leftover
=
180 heap_
.Split(new_span
.get(), pages
);
181 leftover
->shared_memory()->Unlock(
182 leftover
->start() * base::GetPageSize() -
183 reinterpret_cast<size_t>(leftover
->shared_memory()->memory()),
184 leftover
->length() * base::GetPageSize());
185 heap_
.MergeIntoFreeLists(leftover
.Pass());
188 MemoryUsageChanged(heap_
.GetSize(), heap_
.GetSizeOfFreeLists());
190 return make_scoped_ptr(new DiscardableMemoryImpl(this, new_span
.Pass()));
193 bool ChildDiscardableSharedMemoryManager::OnMemoryDump(
194 base::trace_event::ProcessMemoryDump
* pmd
) {
195 base::AutoLock
lock(lock_
);
196 return heap_
.OnMemoryDump(pmd
);
199 void ChildDiscardableSharedMemoryManager::ReleaseFreeMemory() {
200 base::AutoLock
lock(lock_
);
202 size_t heap_size_prior_to_releasing_memory
= heap_
.GetSize();
204 // Release both purged and free memory.
205 heap_
.ReleasePurgedMemory();
206 heap_
.ReleaseFreeMemory();
208 if (heap_
.GetSize() != heap_size_prior_to_releasing_memory
)
209 MemoryUsageChanged(heap_
.GetSize(), heap_
.GetSizeOfFreeLists());
212 bool ChildDiscardableSharedMemoryManager::LockSpan(
213 DiscardableSharedMemoryHeap::Span
* span
) {
214 base::AutoLock
lock(lock_
);
216 if (!span
->shared_memory())
219 size_t offset
= span
->start() * base::GetPageSize() -
220 reinterpret_cast<size_t>(span
->shared_memory()->memory());
221 size_t length
= span
->length() * base::GetPageSize();
223 switch (span
->shared_memory()->Lock(offset
, length
)) {
224 case base::DiscardableSharedMemory::SUCCESS
:
226 case base::DiscardableSharedMemory::PURGED
:
227 span
->shared_memory()->Unlock(offset
, length
);
229 case base::DiscardableSharedMemory::FAILED
:
237 void ChildDiscardableSharedMemoryManager::UnlockSpan(
238 DiscardableSharedMemoryHeap::Span
* span
) {
239 base::AutoLock
lock(lock_
);
241 DCHECK(span
->shared_memory());
242 size_t offset
= span
->start() * base::GetPageSize() -
243 reinterpret_cast<size_t>(span
->shared_memory()->memory());
244 size_t length
= span
->length() * base::GetPageSize();
246 return span
->shared_memory()->Unlock(offset
, length
);
249 void ChildDiscardableSharedMemoryManager::ReleaseSpan(
250 scoped_ptr
<DiscardableSharedMemoryHeap::Span
> span
) {
251 base::AutoLock
lock(lock_
);
253 // Delete span instead of merging it into free lists if memory is gone.
254 if (!span
->shared_memory())
257 heap_
.MergeIntoFreeLists(span
.Pass());
259 // Bytes of free memory changed.
260 MemoryUsageChanged(heap_
.GetSize(), heap_
.GetSizeOfFreeLists());
263 scoped_ptr
<base::DiscardableSharedMemory
>
264 ChildDiscardableSharedMemoryManager::AllocateLockedDiscardableSharedMemory(
266 DiscardableSharedMemoryId id
) {
267 TRACE_EVENT2("renderer",
268 "ChildDiscardableSharedMemoryManager::"
269 "AllocateLockedDiscardableSharedMemory",
270 "size", size
, "id", id
);
272 base::SharedMemoryHandle handle
= base::SharedMemory::NULLHandle();
274 new ChildProcessHostMsg_SyncAllocateLockedDiscardableSharedMemory(
276 scoped_ptr
<base::DiscardableSharedMemory
> memory(
277 new base::DiscardableSharedMemory(handle
));
278 if (!memory
->Map(size
))
279 base::TerminateBecauseOutOfMemory(size
);
280 return memory
.Pass();
283 void ChildDiscardableSharedMemoryManager::MemoryUsageChanged(
284 size_t new_bytes_total
,
285 size_t new_bytes_free
) const {
286 TRACE_COUNTER2("renderer", "DiscardableMemoryUsage", "allocated",
287 new_bytes_total
- new_bytes_free
, "free", new_bytes_free
);
289 static const char kDiscardableMemoryAllocatedKey
[] =
290 "discardable-memory-allocated";
291 base::debug::SetCrashKeyValue(kDiscardableMemoryAllocatedKey
,
292 base::Uint64ToString(new_bytes_total
));
294 static const char kDiscardableMemoryFreeKey
[] = "discardable-memory-free";
295 base::debug::SetCrashKeyValue(kDiscardableMemoryFreeKey
,
296 base::Uint64ToString(new_bytes_free
));
299 } // namespace content