Bumping manifests a=b2g-bump
[gecko.git] / memory / volatile / VolatileBufferAshmem.cpp
blob09904d6efe017aa2d32e8fefbe609bdc6e52dfad
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 #include "VolatileBuffer.h"
6 #include "mozilla/Assertions.h"
7 #include "mozilla/mozalloc.h"
9 #include <fcntl.h>
10 #include <linux/ashmem.h>
11 #include <sys/mman.h>
12 #include <sys/stat.h>
13 #include <sys/types.h>
14 #include <unistd.h>
16 #ifdef MOZ_MEMORY
17 extern "C" int posix_memalign(void** memptr, size_t alignment, size_t size);
18 #endif
20 #define MIN_VOLATILE_ALLOC_SIZE 8192
22 namespace mozilla {
24 VolatileBuffer::VolatileBuffer()
25 : mMutex("VolatileBuffer")
26 , mBuf(nullptr)
27 , mSize(0)
28 , mLockCount(0)
29 , mFd(-1)
33 bool
34 VolatileBuffer::Init(size_t aSize, size_t aAlignment)
36 MOZ_ASSERT(!mSize && !mBuf, "Init called twice");
37 MOZ_ASSERT(!(aAlignment % sizeof(void *)),
38 "Alignment must be multiple of pointer size");
40 mSize = aSize;
41 if (aSize < MIN_VOLATILE_ALLOC_SIZE) {
42 goto heap_alloc;
45 mFd = open("/" ASHMEM_NAME_DEF, O_RDWR);
46 if (mFd < 0) {
47 goto heap_alloc;
50 if (ioctl(mFd, ASHMEM_SET_SIZE, mSize) < 0) {
51 goto heap_alloc;
54 mBuf = mmap(nullptr, mSize, PROT_READ | PROT_WRITE, MAP_SHARED, mFd, 0);
55 if (mBuf != MAP_FAILED) {
56 return true;
59 heap_alloc:
60 mBuf = nullptr;
61 if (mFd >= 0) {
62 close(mFd);
63 mFd = -1;
66 #ifdef MOZ_MEMORY
67 posix_memalign(&mBuf, aAlignment, aSize);
68 #else
69 mBuf = memalign(aAlignment, aSize);
70 #endif
71 return !!mBuf;
74 VolatileBuffer::~VolatileBuffer()
76 MOZ_ASSERT(mLockCount == 0, "Being destroyed with non-zero lock count?");
78 if (OnHeap()) {
79 free(mBuf);
80 } else {
81 munmap(mBuf, mSize);
82 close(mFd);
86 bool
87 VolatileBuffer::Lock(void** aBuf)
89 MutexAutoLock lock(mMutex);
91 MOZ_ASSERT(mBuf, "Attempting to lock an uninitialized VolatileBuffer");
93 *aBuf = mBuf;
94 if (++mLockCount > 1 || OnHeap()) {
95 return true;
98 // Zero offset and zero length means we want to pin/unpin the entire thing.
99 struct ashmem_pin pin = { 0, 0 };
100 return ioctl(mFd, ASHMEM_PIN, &pin) == ASHMEM_NOT_PURGED;
103 void
104 VolatileBuffer::Unlock()
106 MutexAutoLock lock(mMutex);
108 MOZ_ASSERT(mLockCount > 0, "VolatileBuffer unlocked too many times!");
109 if (--mLockCount || OnHeap()) {
110 return;
113 struct ashmem_pin pin = { 0, 0 };
114 ioctl(mFd, ASHMEM_UNPIN, &pin);
117 bool
118 VolatileBuffer::OnHeap() const
120 return mFd < 0;
123 size_t
124 VolatileBuffer::HeapSizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
126 return OnHeap() ? aMallocSizeOf(mBuf) : 0;
129 size_t
130 VolatileBuffer::NonHeapSizeOfExcludingThis() const
132 if (OnHeap()) {
133 return 0;
136 return (mSize + (PAGE_SIZE - 1)) & PAGE_MASK;
139 } // namespace mozilla