This source file includes following definitions.
- AlignToNextPage
- CreateAshmemRegion
- CloseAshmemRegion
- LockAshmemRegion
- UnlockAshmemRegion
- locked_
- Unlock
- Memory
- Create
- AshmemRegion
- Allocate_Locked
- OnChunkDeletion
- offset_
- ReuseFreeChunk_Locked
- MergeAndAddFreeChunk_Locked
- AddFreeChunk_Locked
- RemoveFreeChunk_Locked
- RemoveFreeChunkFromIterator_Locked
- last_ashmem_region_size_
- Allocate
- last_ashmem_region_size
- DeleteAshmemRegion_Locked
#include "base/memory/discardable_memory_allocator_android.h"
#include <sys/mman.h>
#include <unistd.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <set>
#include <utility>
#include "base/basictypes.h"
#include "base/containers/hash_tables.h"
#include "base/file_util.h"
#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/memory/discardable_memory.h"
#include "base/memory/scoped_vector.h"
#include "base/synchronization/lock.h"
#include "base/threading/thread_checker.h"
#include "third_party/ashmem/ashmem.h"
namespace base {
namespace {
const size_t kMaxChunkFragmentationBytes = 4096 - 1;
const size_t kMinAshmemRegionSize = 32 * 1024 * 1024;
size_t AlignToNextPage(size_t size) {
const size_t kPageSize = 4096;
DCHECK_EQ(static_cast<int>(kPageSize), getpagesize());
if (size > std::numeric_limits<size_t>::max() - kPageSize + 1)
return 0;
const size_t mask = ~(kPageSize - 1);
return (size + kPageSize - 1) & mask;
}
bool CreateAshmemRegion(const char* name,
size_t size,
int* out_fd,
void** out_address) {
base::ScopedFD fd(ashmem_create_region(name, size));
if (!fd.is_valid()) {
DLOG(ERROR) << "ashmem_create_region() failed";
return false;
}
const int err = ashmem_set_prot_region(fd.get(), PROT_READ | PROT_WRITE);
if (err < 0) {
DLOG(ERROR) << "Error " << err << " when setting protection of ashmem";
return false;
}
void* const address = mmap(
NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd.get(), 0);
if (address == MAP_FAILED) {
DPLOG(ERROR) << "Failed to map memory.";
return false;
}
*out_fd = fd.release();
*out_address = address;
return true;
}
bool CloseAshmemRegion(int fd, size_t size, void* address) {
if (munmap(address, size) == -1) {
DPLOG(ERROR) << "Failed to unmap memory.";
close(fd);
return false;
}
return close(fd) == 0;
}
DiscardableMemoryLockStatus LockAshmemRegion(int fd, size_t off, size_t size) {
const int result = ashmem_pin_region(fd, off, size);
return result == ASHMEM_WAS_PURGED ? DISCARDABLE_MEMORY_LOCK_STATUS_PURGED
: DISCARDABLE_MEMORY_LOCK_STATUS_SUCCESS;
}
bool UnlockAshmemRegion(int fd, size_t off, size_t size) {
const int failed = ashmem_unpin_region(fd, off, size);
if (failed)
DLOG(ERROR) << "Failed to unpin memory.";
return !failed;
}
}
namespace internal {
class DiscardableMemoryAllocator::DiscardableAshmemChunk
: public DiscardableMemory {
public:
DiscardableAshmemChunk(AshmemRegion* ashmem_region,
int fd,
void* address,
size_t offset,
size_t size)
: ashmem_region_(ashmem_region),
fd_(fd),
address_(address),
offset_(offset),
size_(size),
locked_(true) {
}
virtual ~DiscardableAshmemChunk();
virtual DiscardableMemoryLockStatus Lock() OVERRIDE {
DCHECK(!locked_);
locked_ = true;
return LockAshmemRegion(fd_, offset_, size_);
}
virtual void Unlock() OVERRIDE {
DCHECK(locked_);
locked_ = false;
UnlockAshmemRegion(fd_, offset_, size_);
}
virtual void* Memory() const OVERRIDE {
return address_;
}
private:
AshmemRegion* const ashmem_region_;
const int fd_;
void* const address_;
const size_t offset_;
const size_t size_;
bool locked_;
DISALLOW_COPY_AND_ASSIGN(DiscardableAshmemChunk);
};
class DiscardableMemoryAllocator::AshmemRegion {
public:
static scoped_ptr<AshmemRegion> Create(
size_t size,
const std::string& name,
DiscardableMemoryAllocator* allocator) {
DCHECK_EQ(size, AlignToNextPage(size));
int fd;
void* base;
if (!CreateAshmemRegion(name.c_str(), size, &fd, &base))
return scoped_ptr<AshmemRegion>();
return make_scoped_ptr(new AshmemRegion(fd, size, base, allocator));
}
~AshmemRegion() {
const bool result = CloseAshmemRegion(fd_, size_, base_);
DCHECK(result);
DCHECK(!highest_allocated_chunk_);
}
scoped_ptr<DiscardableMemory> Allocate_Locked(size_t client_requested_size,
size_t actual_size) {
DCHECK_LE(client_requested_size, actual_size);
allocator_->lock_.AssertAcquired();
DCHECK(!highest_allocated_chunk_ ||
address_to_free_chunk_map_.find(highest_allocated_chunk_) !=
address_to_free_chunk_map_.end() ||
used_to_previous_chunk_map_.find(highest_allocated_chunk_) !=
used_to_previous_chunk_map_.end());
scoped_ptr<DiscardableMemory> memory = ReuseFreeChunk_Locked(
client_requested_size, actual_size);
if (memory)
return memory.Pass();
if (size_ - offset_ < actual_size) {
return scoped_ptr<DiscardableMemory>();
}
void* const address = static_cast<char*>(base_) + offset_;
memory.reset(
new DiscardableAshmemChunk(this, fd_, address, offset_, actual_size));
used_to_previous_chunk_map_.insert(
std::make_pair(address, highest_allocated_chunk_));
highest_allocated_chunk_ = address;
offset_ += actual_size;
DCHECK_LE(offset_, size_);
return memory.Pass();
}
void OnChunkDeletion(void* chunk, size_t size) {
AutoLock auto_lock(allocator_->lock_);
MergeAndAddFreeChunk_Locked(chunk, size);
}
private:
struct FreeChunk {
FreeChunk() : previous_chunk(NULL), start(NULL), size(0) {}
explicit FreeChunk(size_t size)
: previous_chunk(NULL),
start(NULL),
size(size) {
}
FreeChunk(void* previous_chunk, void* start, size_t size)
: previous_chunk(previous_chunk),
start(start),
size(size) {
DCHECK_LT(previous_chunk, start);
}
void* const previous_chunk;
void* const start;
const size_t size;
bool is_null() const { return !start; }
bool operator<(const FreeChunk& other) const {
return size < other.size;
}
};
AshmemRegion(int fd,
size_t size,
void* base,
DiscardableMemoryAllocator* allocator)
: fd_(fd),
size_(size),
base_(base),
allocator_(allocator),
highest_allocated_chunk_(NULL),
offset_(0) {
DCHECK_GE(fd_, 0);
DCHECK_GE(size, kMinAshmemRegionSize);
DCHECK(base);
DCHECK(allocator);
}
scoped_ptr<DiscardableMemory> ReuseFreeChunk_Locked(
size_t client_requested_size,
size_t actual_size) {
allocator_->lock_.AssertAcquired();
const FreeChunk reused_chunk = RemoveFreeChunkFromIterator_Locked(
free_chunks_.lower_bound(FreeChunk(actual_size)));
if (reused_chunk.is_null())
return scoped_ptr<DiscardableMemory>();
used_to_previous_chunk_map_.insert(
std::make_pair(reused_chunk.start, reused_chunk.previous_chunk));
size_t reused_chunk_size = reused_chunk.size;
DCHECK_GE(reused_chunk.size, client_requested_size);
const size_t fragmentation_bytes =
reused_chunk.size - client_requested_size;
if (fragmentation_bytes > kMaxChunkFragmentationBytes) {
reused_chunk_size = actual_size;
void* const new_chunk_start =
static_cast<char*>(reused_chunk.start) + actual_size;
if (reused_chunk.start == highest_allocated_chunk_) {
highest_allocated_chunk_ = new_chunk_start;
}
DCHECK_GT(reused_chunk.size, actual_size);
const size_t new_chunk_size = reused_chunk.size - actual_size;
AddFreeChunk_Locked(
FreeChunk(reused_chunk.start, new_chunk_start, new_chunk_size));
}
const size_t offset =
static_cast<char*>(reused_chunk.start) - static_cast<char*>(base_);
LockAshmemRegion(fd_, offset, reused_chunk_size);
scoped_ptr<DiscardableMemory> memory(
new DiscardableAshmemChunk(this, fd_, reused_chunk.start, offset,
reused_chunk_size));
return memory.Pass();
}
void MergeAndAddFreeChunk_Locked(void* chunk, size_t size) {
allocator_->lock_.AssertAcquired();
size_t new_free_chunk_size = size;
void* first_free_chunk = chunk;
DCHECK(!used_to_previous_chunk_map_.empty());
const hash_map<void*, void*>::iterator previous_chunk_it =
used_to_previous_chunk_map_.find(chunk);
DCHECK(previous_chunk_it != used_to_previous_chunk_map_.end());
void* previous_chunk = previous_chunk_it->second;
used_to_previous_chunk_map_.erase(previous_chunk_it);
if (previous_chunk) {
const FreeChunk free_chunk = RemoveFreeChunk_Locked(previous_chunk);
if (!free_chunk.is_null()) {
new_free_chunk_size += free_chunk.size;
first_free_chunk = previous_chunk;
if (chunk == highest_allocated_chunk_)
highest_allocated_chunk_ = previous_chunk;
previous_chunk = free_chunk.previous_chunk;
DCHECK(!address_to_free_chunk_map_.count(previous_chunk));
}
}
void* next_chunk = static_cast<char*>(chunk) + size;
const FreeChunk next_free_chunk = RemoveFreeChunk_Locked(next_chunk);
if (!next_free_chunk.is_null()) {
new_free_chunk_size += next_free_chunk.size;
if (next_free_chunk.start == highest_allocated_chunk_)
highest_allocated_chunk_ = first_free_chunk;
DCHECK(!address_to_free_chunk_map_.count(static_cast<char*>(next_chunk) +
next_free_chunk.size));
}
const bool whole_ashmem_region_is_free =
used_to_previous_chunk_map_.empty();
if (!whole_ashmem_region_is_free) {
AddFreeChunk_Locked(
FreeChunk(previous_chunk, first_free_chunk, new_free_chunk_size));
return;
}
DCHECK_EQ(base_, first_free_chunk);
DCHECK_EQ(base_, highest_allocated_chunk_);
DCHECK(free_chunks_.empty());
DCHECK(address_to_free_chunk_map_.empty());
DCHECK(used_to_previous_chunk_map_.empty());
highest_allocated_chunk_ = NULL;
allocator_->DeleteAshmemRegion_Locked(this);
}
void AddFreeChunk_Locked(const FreeChunk& free_chunk) {
allocator_->lock_.AssertAcquired();
const std::multiset<FreeChunk>::iterator it = free_chunks_.insert(
free_chunk);
address_to_free_chunk_map_.insert(std::make_pair(free_chunk.start, it));
void* const next_used_contiguous_chunk =
static_cast<char*>(free_chunk.start) + free_chunk.size;
hash_map<void*, void*>::iterator previous_it =
used_to_previous_chunk_map_.find(next_used_contiguous_chunk);
if (previous_it != used_to_previous_chunk_map_.end())
previous_it->second = free_chunk.start;
}
FreeChunk RemoveFreeChunk_Locked(void* chunk_start) {
allocator_->lock_.AssertAcquired();
const hash_map<
void*, std::multiset<FreeChunk>::iterator>::iterator it =
address_to_free_chunk_map_.find(chunk_start);
if (it == address_to_free_chunk_map_.end())
return FreeChunk();
return RemoveFreeChunkFromIterator_Locked(it->second);
}
FreeChunk RemoveFreeChunkFromIterator_Locked(
std::multiset<FreeChunk>::iterator free_chunk_it) {
allocator_->lock_.AssertAcquired();
if (free_chunk_it == free_chunks_.end())
return FreeChunk();
DCHECK(free_chunk_it != free_chunks_.end());
const FreeChunk free_chunk(*free_chunk_it);
address_to_free_chunk_map_.erase(free_chunk_it->start);
free_chunks_.erase(free_chunk_it);
return free_chunk;
}
const int fd_;
const size_t size_;
void* const base_;
DiscardableMemoryAllocator* const allocator_;
void* highest_allocated_chunk_;
size_t offset_;
std::multiset<FreeChunk> free_chunks_;
hash_map<
void*, std::multiset<FreeChunk>::iterator> address_to_free_chunk_map_;
hash_map<void*, void*> used_to_previous_chunk_map_;
DISALLOW_COPY_AND_ASSIGN(AshmemRegion);
};
DiscardableMemoryAllocator::DiscardableAshmemChunk::~DiscardableAshmemChunk() {
if (locked_)
UnlockAshmemRegion(fd_, offset_, size_);
ashmem_region_->OnChunkDeletion(address_, size_);
}
DiscardableMemoryAllocator::DiscardableMemoryAllocator(
const std::string& name,
size_t ashmem_region_size)
: name_(name),
ashmem_region_size_(
std::max(kMinAshmemRegionSize, AlignToNextPage(ashmem_region_size))),
last_ashmem_region_size_(0) {
DCHECK_GE(ashmem_region_size_, kMinAshmemRegionSize);
}
DiscardableMemoryAllocator::~DiscardableMemoryAllocator() {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(ashmem_regions_.empty());
}
scoped_ptr<DiscardableMemory> DiscardableMemoryAllocator::Allocate(
size_t size) {
const size_t aligned_size = AlignToNextPage(size);
if (!aligned_size)
return scoped_ptr<DiscardableMemory>();
AutoLock auto_lock(lock_);
DCHECK_LE(ashmem_regions_.size(), 5U);
for (ScopedVector<AshmemRegion>::iterator it = ashmem_regions_.begin();
it != ashmem_regions_.end(); ++it) {
scoped_ptr<DiscardableMemory> memory(
(*it)->Allocate_Locked(size, aligned_size));
if (memory)
return memory.Pass();
}
const size_t min_region_size = std::max(kMinAshmemRegionSize, aligned_size);
for (size_t region_size = std::max(ashmem_region_size_, aligned_size);
region_size >= min_region_size;
region_size = AlignToNextPage(region_size / 2)) {
scoped_ptr<AshmemRegion> new_region(
AshmemRegion::Create(region_size, name_.c_str(), this));
if (!new_region)
continue;
last_ashmem_region_size_ = region_size;
ashmem_regions_.push_back(new_region.release());
return ashmem_regions_.back()->Allocate_Locked(size, aligned_size);
}
return scoped_ptr<DiscardableMemory>();
}
size_t DiscardableMemoryAllocator::last_ashmem_region_size() const {
AutoLock auto_lock(lock_);
return last_ashmem_region_size_;
}
void DiscardableMemoryAllocator::DeleteAshmemRegion_Locked(
AshmemRegion* region) {
lock_.AssertAcquired();
DCHECK_LE(ashmem_regions_.size(), 5U);
const ScopedVector<AshmemRegion>::iterator it = std::find(
ashmem_regions_.begin(), ashmem_regions_.end(), region);
DCHECK_NE(ashmem_regions_.end(), it);
std::swap(*it, ashmem_regions_.back());
ashmem_regions_.pop_back();
}
}
}