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 "base/memory/discardable_memory_shmem.h"
7 #include "base/lazy_instance.h"
8 #include "base/memory/discardable_memory_shmem_allocator.h"
9 #include "base/memory/discardable_shared_memory.h"
14 // Have the DiscardableMemoryManager trigger in-process eviction
15 // when address space usage gets too high (e.g. 512 MBytes).
16 const size_t kMemoryLimit
= 512 * 1024 * 1024;
18 // internal::DiscardableMemoryManager has an explicit constructor that takes
19 // a number of memory limit parameters. The LeakyLazyInstanceTraits doesn't
20 // handle the case. Thus, we need our own class here.
21 struct DiscardableMemoryManagerLazyInstanceTraits
{
22 // Leaky as discardable memory clients can use this after the exit handler
24 static const bool kRegisterOnExit
= false;
26 static const bool kAllowedToAccessOnNonjoinableThread
= true;
29 static internal::DiscardableMemoryManager
* New(void* instance
) {
30 return new (instance
) internal::DiscardableMemoryManager(
31 kMemoryLimit
, kMemoryLimit
, TimeDelta::Max());
33 static void Delete(internal::DiscardableMemoryManager
* instance
) {
34 instance
->~DiscardableMemoryManager();
38 LazyInstance
<internal::DiscardableMemoryManager
,
39 DiscardableMemoryManagerLazyInstanceTraits
> g_manager
=
40 LAZY_INSTANCE_INITIALIZER
;
46 DiscardableMemoryShmem::DiscardableMemoryShmem(size_t bytes
)
47 : bytes_(bytes
), is_locked_(false) {
48 g_manager
.Pointer()->Register(this, bytes
);
51 DiscardableMemoryShmem::~DiscardableMemoryShmem() {
54 g_manager
.Pointer()->Unregister(this);
58 void DiscardableMemoryShmem::ReleaseFreeMemory() {
59 g_manager
.Pointer()->ReleaseFreeMemory();
63 void DiscardableMemoryShmem::PurgeForTesting() {
64 g_manager
.Pointer()->PurgeAll();
67 bool DiscardableMemoryShmem::Initialize() {
68 return Lock() != DISCARDABLE_MEMORY_LOCK_STATUS_FAILED
;
71 DiscardableMemoryLockStatus
DiscardableMemoryShmem::Lock() {
75 if (!g_manager
.Pointer()->AcquireLock(this, &purged
))
76 return DISCARDABLE_MEMORY_LOCK_STATUS_FAILED
;
79 return purged
? DISCARDABLE_MEMORY_LOCK_STATUS_PURGED
80 : DISCARDABLE_MEMORY_LOCK_STATUS_SUCCESS
;
83 void DiscardableMemoryShmem::Unlock() {
85 g_manager
.Pointer()->ReleaseLock(this);
89 void* DiscardableMemoryShmem::Memory() const {
92 return chunk_
->Memory();
95 bool DiscardableMemoryShmem::AllocateAndAcquireLock() {
96 if (chunk_
&& chunk_
->Lock())
99 chunk_
= DiscardableMemoryShmemAllocator::GetInstance()
100 ->AllocateLockedDiscardableMemory(bytes_
);
105 void DiscardableMemoryShmem::ReleaseLock() {
109 void DiscardableMemoryShmem::Purge() {
114 bool DiscardableMemoryShmem::IsMemoryResident() const {
115 return chunk_
->IsMemoryResident();
118 } // namespace internal