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 return heap_
.OnMemoryDump(pmd
);
198 void ChildDiscardableSharedMemoryManager::ReleaseFreeMemory() {
199 base::AutoLock
lock(lock_
);
201 size_t heap_size_prior_to_releasing_memory
= heap_
.GetSize();
203 // Release both purged and free memory.
204 heap_
.ReleasePurgedMemory();
205 heap_
.ReleaseFreeMemory();
207 if (heap_
.GetSize() != heap_size_prior_to_releasing_memory
)
208 MemoryUsageChanged(heap_
.GetSize(), heap_
.GetSizeOfFreeLists());
211 bool ChildDiscardableSharedMemoryManager::LockSpan(
212 DiscardableSharedMemoryHeap::Span
* span
) {
213 base::AutoLock
lock(lock_
);
215 if (!span
->shared_memory())
218 size_t offset
= span
->start() * base::GetPageSize() -
219 reinterpret_cast<size_t>(span
->shared_memory()->memory());
220 size_t length
= span
->length() * base::GetPageSize();
222 switch (span
->shared_memory()->Lock(offset
, length
)) {
223 case base::DiscardableSharedMemory::SUCCESS
:
225 case base::DiscardableSharedMemory::PURGED
:
226 span
->shared_memory()->Unlock(offset
, length
);
228 case base::DiscardableSharedMemory::FAILED
:
236 void ChildDiscardableSharedMemoryManager::UnlockSpan(
237 DiscardableSharedMemoryHeap::Span
* span
) {
238 base::AutoLock
lock(lock_
);
240 DCHECK(span
->shared_memory());
241 size_t offset
= span
->start() * base::GetPageSize() -
242 reinterpret_cast<size_t>(span
->shared_memory()->memory());
243 size_t length
= span
->length() * base::GetPageSize();
245 return span
->shared_memory()->Unlock(offset
, length
);
248 void ChildDiscardableSharedMemoryManager::ReleaseSpan(
249 scoped_ptr
<DiscardableSharedMemoryHeap::Span
> span
) {
250 base::AutoLock
lock(lock_
);
252 // Delete span instead of merging it into free lists if memory is gone.
253 if (!span
->shared_memory())
256 heap_
.MergeIntoFreeLists(span
.Pass());
258 // Bytes of free memory changed.
259 MemoryUsageChanged(heap_
.GetSize(), heap_
.GetSizeOfFreeLists());
262 scoped_ptr
<base::DiscardableSharedMemory
>
263 ChildDiscardableSharedMemoryManager::AllocateLockedDiscardableSharedMemory(
265 DiscardableSharedMemoryId id
) {
266 TRACE_EVENT2("renderer",
267 "ChildDiscardableSharedMemoryManager::"
268 "AllocateLockedDiscardableSharedMemory",
269 "size", size
, "id", id
);
271 base::SharedMemoryHandle handle
= base::SharedMemory::NULLHandle();
273 new ChildProcessHostMsg_SyncAllocateLockedDiscardableSharedMemory(
275 scoped_ptr
<base::DiscardableSharedMemory
> memory(
276 new base::DiscardableSharedMemory(handle
));
277 if (!memory
->Map(size
))
278 base::TerminateBecauseOutOfMemory(size
);
279 return memory
.Pass();
282 void ChildDiscardableSharedMemoryManager::MemoryUsageChanged(
283 size_t new_bytes_total
,
284 size_t new_bytes_free
) const {
285 TRACE_COUNTER2("renderer", "DiscardableMemoryUsage", "allocated",
286 new_bytes_total
- new_bytes_free
, "free", new_bytes_free
);
288 static const char kDiscardableMemoryAllocatedKey
[] =
289 "discardable-memory-allocated";
290 base::debug::SetCrashKeyValue(kDiscardableMemoryAllocatedKey
,
291 base::Uint64ToString(new_bytes_total
));
293 static const char kDiscardableMemoryFreeKey
[] = "discardable-memory-free";
294 base::debug::SetCrashKeyValue(kDiscardableMemoryFreeKey
,
295 base::Uint64ToString(new_bytes_free
));
298 } // namespace content