1 // Copyright (c) 2013 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.h"
7 #include "base/android/sys_utils.h"
8 #include "base/basictypes.h"
9 #include "base/compiler_specific.h"
10 #include "base/lazy_instance.h"
11 #include "base/logging.h"
12 #include "base/memory/discardable_memory_allocator_android.h"
13 #include "base/memory/discardable_memory_emulated.h"
14 #include "base/memory/discardable_memory_malloc.h"
19 const char kAshmemAllocatorName
[] = "DiscardableMemoryAllocator";
21 struct DiscardableMemoryAllocatorWrapper
{
22 DiscardableMemoryAllocatorWrapper()
23 : allocator(kAshmemAllocatorName
,
24 GetOptimalAshmemRegionSizeForAllocator()) {
27 internal::DiscardableMemoryAllocator allocator
;
30 // Returns 64 MBytes for a 512 MBytes device, 128 MBytes for 1024 MBytes...
31 static size_t GetOptimalAshmemRegionSizeForAllocator() {
32 // Note that this may do some I/O (without hitting the disk though) so it
33 // should not be called on the critical path.
34 return base::android::SysUtils::AmountOfPhysicalMemoryKB() * 1024 / 8;
38 LazyInstance
<DiscardableMemoryAllocatorWrapper
>::Leaky g_context
=
39 LAZY_INSTANCE_INITIALIZER
;
44 void DiscardableMemory::RegisterMemoryPressureListeners() {
45 internal::DiscardableMemoryEmulated::RegisterMemoryPressureListeners();
49 void DiscardableMemory::UnregisterMemoryPressureListeners() {
50 internal::DiscardableMemoryEmulated::UnregisterMemoryPressureListeners();
54 void DiscardableMemory::GetSupportedTypes(
55 std::vector
<DiscardableMemoryType
>* types
) {
56 const DiscardableMemoryType supported_types
[] = {
57 DISCARDABLE_MEMORY_TYPE_ANDROID
,
58 DISCARDABLE_MEMORY_TYPE_EMULATED
,
59 DISCARDABLE_MEMORY_TYPE_MALLOC
61 types
->assign(supported_types
, supported_types
+ arraysize(supported_types
));
65 scoped_ptr
<DiscardableMemory
> DiscardableMemory::CreateLockedMemoryWithType(
66 DiscardableMemoryType type
, size_t size
) {
68 case DISCARDABLE_MEMORY_TYPE_NONE
:
69 case DISCARDABLE_MEMORY_TYPE_MAC
:
70 return scoped_ptr
<DiscardableMemory
>();
71 case DISCARDABLE_MEMORY_TYPE_ANDROID
: {
72 return g_context
.Pointer()->allocator
.Allocate(size
);
74 case DISCARDABLE_MEMORY_TYPE_EMULATED
: {
75 scoped_ptr
<internal::DiscardableMemoryEmulated
> memory(
76 new internal::DiscardableMemoryEmulated(size
));
77 if (!memory
->Initialize())
78 return scoped_ptr
<DiscardableMemory
>();
80 return memory
.PassAs
<DiscardableMemory
>();
82 case DISCARDABLE_MEMORY_TYPE_MALLOC
: {
83 scoped_ptr
<internal::DiscardableMemoryMalloc
> memory(
84 new internal::DiscardableMemoryMalloc(size
));
85 if (!memory
->Initialize())
86 return scoped_ptr
<DiscardableMemory
>();
88 return memory
.PassAs
<DiscardableMemory
>();
93 return scoped_ptr
<DiscardableMemory
>();
97 bool DiscardableMemory::PurgeForTestingSupported() {
102 void DiscardableMemory::PurgeForTesting() {