1 /*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "MemoryDealer"
18
19 #include <binder/MemoryDealer.h>
20 #include <binder/IPCThreadState.h>
21 #include <binder/MemoryBase.h>
22
23 #include <utils/Log.h>
24 #include <utils/SortedVector.h>
25 #include <utils/String8.h>
26
27 #include <stdint.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <errno.h>
33 #include <string.h>
34
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/mman.h>
38 #include <sys/file.h>
39
40 namespace android {
41 // ----------------------------------------------------------------------------
42
43 /*
44 * A simple templatized doubly linked-list implementation
45 */
46
47 template <typename NODE>
48 class LinkedList
49 {
50 NODE* mFirst;
51 NODE* mLast;
52
53 public:
LinkedList()54 LinkedList() : mFirst(nullptr), mLast(nullptr) { }
isEmpty() const55 bool isEmpty() const { return mFirst == nullptr; }
head() const56 NODE const* head() const { return mFirst; }
head()57 NODE* head() { return mFirst; }
tail() const58 NODE const* tail() const { return mLast; }
tail()59 NODE* tail() { return mLast; }
60
insertAfter(NODE * node,NODE * newNode)61 void insertAfter(NODE* node, NODE* newNode) {
62 newNode->prev = node;
63 newNode->next = node->next;
64 if (node->next == nullptr) mLast = newNode;
65 else node->next->prev = newNode;
66 node->next = newNode;
67 }
68
insertBefore(NODE * node,NODE * newNode)69 void insertBefore(NODE* node, NODE* newNode) {
70 newNode->prev = node->prev;
71 newNode->next = node;
72 if (node->prev == nullptr) mFirst = newNode;
73 else node->prev->next = newNode;
74 node->prev = newNode;
75 }
76
insertHead(NODE * newNode)77 void insertHead(NODE* newNode) {
78 if (mFirst == nullptr) {
79 mFirst = mLast = newNode;
80 newNode->prev = newNode->next = nullptr;
81 } else {
82 newNode->prev = nullptr;
83 newNode->next = mFirst;
84 mFirst->prev = newNode;
85 mFirst = newNode;
86 }
87 }
88
insertTail(NODE * newNode)89 void insertTail(NODE* newNode) {
90 if (mLast == 0) {
91 insertHead(newNode);
92 } else {
93 newNode->prev = mLast;
94 newNode->next = 0;
95 mLast->next = newNode;
96 mLast = newNode;
97 }
98 }
99
remove(NODE * node)100 NODE* remove(NODE* node) {
101 if (node->prev == nullptr) mFirst = node->next;
102 else node->prev->next = node->next;
103 if (node->next == nullptr) mLast = node->prev;
104 else node->next->prev = node->prev;
105 return node;
106 }
107 };
108
109 // ----------------------------------------------------------------------------
110
111 class Allocation : public MemoryBase {
112 public:
113 Allocation(const sp<MemoryDealer>& dealer,
114 const sp<IMemoryHeap>& heap, ssize_t offset, size_t size);
115 virtual ~Allocation();
116 private:
117 sp<MemoryDealer> mDealer;
118 };
119
120 // ----------------------------------------------------------------------------
121
122 class SimpleBestFitAllocator
123 {
124 enum {
125 PAGE_ALIGNED = 0x00000001
126 };
127 public:
128 explicit SimpleBestFitAllocator(size_t size);
129 ~SimpleBestFitAllocator();
130
131 size_t allocate(size_t size, uint32_t flags = 0);
132 status_t deallocate(size_t offset);
133 size_t size() const;
134 void dump(const char* what) const;
135 void dump(String8& res, const char* what) const;
136
getAllocationAlignment()137 static size_t getAllocationAlignment() { return kMemoryAlign; }
138
139 private:
140
141 struct chunk_t {
chunk_tandroid::SimpleBestFitAllocator::chunk_t142 chunk_t(size_t start, size_t size)
143 : start(start), size(size), free(1), prev(nullptr), next(nullptr) {
144 }
145 size_t start;
146 size_t size : 28;
147 int free : 4;
148 mutable chunk_t* prev;
149 mutable chunk_t* next;
150 };
151
152 ssize_t alloc(size_t size, uint32_t flags);
153 chunk_t* dealloc(size_t start);
154 void dump_l(const char* what) const;
155 void dump_l(String8& res, const char* what) const;
156
157 static const int kMemoryAlign;
158 mutable Mutex mLock;
159 LinkedList<chunk_t> mList;
160 size_t mHeapSize;
161 };
162
163 // ----------------------------------------------------------------------------
164
Allocation(const sp<MemoryDealer> & dealer,const sp<IMemoryHeap> & heap,ssize_t offset,size_t size)165 Allocation::Allocation(
166 const sp<MemoryDealer>& dealer,
167 const sp<IMemoryHeap>& heap, ssize_t offset, size_t size)
168 : MemoryBase(heap, offset, size), mDealer(dealer)
169 {
170 #ifndef NDEBUG
171 void* const start_ptr = (void*)(intptr_t(heap->base()) + offset);
172 memset(start_ptr, 0xda, size);
173 #endif
174 }
175
~Allocation()176 Allocation::~Allocation()
177 {
178 size_t freedOffset = getOffset();
179 size_t freedSize = getSize();
180 if (freedSize) {
181 /* NOTE: it's VERY important to not free allocations of size 0 because
182 * they're special as they don't have any record in the allocator
183 * and could alias some real allocation (their offset is zero). */
184
185 // keep the size to unmap in excess
186 size_t pagesize = getpagesize();
187 size_t start = freedOffset;
188 size_t end = start + freedSize;
189 start &= ~(pagesize-1);
190 end = (end + pagesize-1) & ~(pagesize-1);
191
192 // give back to the kernel the pages we don't need
193 size_t free_start = freedOffset;
194 size_t free_end = free_start + freedSize;
195 if (start < free_start)
196 start = free_start;
197 if (end > free_end)
198 end = free_end;
199 start = (start + pagesize-1) & ~(pagesize-1);
200 end &= ~(pagesize-1);
201
202 if (start < end) {
203 void* const start_ptr = (void*)(intptr_t(getHeap()->base()) + start);
204 size_t size = end-start;
205
206 #ifndef NDEBUG
207 memset(start_ptr, 0xdf, size);
208 #endif
209
210 // MADV_REMOVE is not defined on Dapper based Goobuntu
211 #ifdef MADV_REMOVE
212 if (size) {
213 int err = madvise(start_ptr, size, MADV_REMOVE);
214 ALOGW_IF(err, "madvise(%p, %zu, MADV_REMOVE) returned %s",
215 start_ptr, size, err<0 ? strerror(errno) : "Ok");
216 }
217 #endif
218 }
219
220 // This should be done after madvise(MADV_REMOVE), otherwise madvise()
221 // might kick out the memory region that's allocated and/or written
222 // right after the deallocation.
223 mDealer->deallocate(freedOffset);
224 }
225 }
226
227 // ----------------------------------------------------------------------------
228
MemoryDealer(size_t size,const char * name,uint32_t flags)229 MemoryDealer::MemoryDealer(size_t size, const char* name, uint32_t flags)
230 : mHeap(sp<MemoryHeapBase>::make(size, flags, name)),
231 mAllocator(new SimpleBestFitAllocator(size)) {}
232
~MemoryDealer()233 MemoryDealer::~MemoryDealer()
234 {
235 delete mAllocator;
236 }
237
allocate(size_t size)238 sp<IMemory> MemoryDealer::allocate(size_t size)
239 {
240 sp<IMemory> memory;
241 const ssize_t offset = allocator()->allocate(size);
242 if (offset >= 0) {
243 memory = sp<Allocation>::make(sp<MemoryDealer>::fromExisting(this), heap(), offset, size);
244 }
245 return memory;
246 }
247
deallocate(size_t offset)248 void MemoryDealer::deallocate(size_t offset)
249 {
250 allocator()->deallocate(offset);
251 }
252
dump(const char * what) const253 void MemoryDealer::dump(const char* what) const
254 {
255 allocator()->dump(what);
256 }
257
heap() const258 const sp<IMemoryHeap>& MemoryDealer::heap() const {
259 return mHeap;
260 }
261
allocator() const262 SimpleBestFitAllocator* MemoryDealer::allocator() const {
263 return mAllocator;
264 }
265
266 // static
getAllocationAlignment()267 size_t MemoryDealer::getAllocationAlignment()
268 {
269 return SimpleBestFitAllocator::getAllocationAlignment();
270 }
271
272 // ----------------------------------------------------------------------------
273
274 // align all the memory blocks on a cache-line boundary
275 const int SimpleBestFitAllocator::kMemoryAlign = 32;
276
SimpleBestFitAllocator(size_t size)277 SimpleBestFitAllocator::SimpleBestFitAllocator(size_t size)
278 {
279 size_t pagesize = getpagesize();
280 mHeapSize = ((size + pagesize-1) & ~(pagesize-1));
281
282 chunk_t* node = new chunk_t(0, mHeapSize / kMemoryAlign);
283 mList.insertHead(node);
284 }
285
~SimpleBestFitAllocator()286 SimpleBestFitAllocator::~SimpleBestFitAllocator()
287 {
288 while(!mList.isEmpty()) {
289 chunk_t* removed = mList.remove(mList.head());
290 #ifdef __clang_analyzer__
291 // Clang static analyzer gets confused in this loop
292 // and generates a false positive warning about accessing
293 // memory that is already freed.
294 // Add an "assert" to avoid the confusion.
295 LOG_ALWAYS_FATAL_IF(mList.head() == removed);
296 #endif
297 delete removed;
298 }
299 }
300
size() const301 size_t SimpleBestFitAllocator::size() const
302 {
303 return mHeapSize;
304 }
305
allocate(size_t size,uint32_t flags)306 size_t SimpleBestFitAllocator::allocate(size_t size, uint32_t flags)
307 {
308 Mutex::Autolock _l(mLock);
309 ssize_t offset = alloc(size, flags);
310 return offset;
311 }
312
deallocate(size_t offset)313 status_t SimpleBestFitAllocator::deallocate(size_t offset)
314 {
315 Mutex::Autolock _l(mLock);
316 chunk_t const * const freed = dealloc(offset);
317 if (freed) {
318 return NO_ERROR;
319 }
320 return NAME_NOT_FOUND;
321 }
322
alloc(size_t size,uint32_t flags)323 ssize_t SimpleBestFitAllocator::alloc(size_t size, uint32_t flags)
324 {
325 if (size == 0) {
326 return 0;
327 }
328 size = (size + kMemoryAlign-1) / kMemoryAlign;
329 chunk_t* free_chunk = nullptr;
330 chunk_t* cur = mList.head();
331
332 size_t pagesize = getpagesize();
333 while (cur) {
334 int extra = 0;
335 if (flags & PAGE_ALIGNED)
336 extra = ( -cur->start & ((pagesize/kMemoryAlign)-1) ) ;
337
338 // best fit
339 if (cur->free && (cur->size >= (size+extra))) {
340 if ((!free_chunk) || (cur->size < free_chunk->size)) {
341 free_chunk = cur;
342 }
343 if (cur->size == size) {
344 break;
345 }
346 }
347 cur = cur->next;
348 }
349
350 if (free_chunk) {
351 const size_t free_size = free_chunk->size;
352 free_chunk->free = 0;
353 free_chunk->size = size;
354 if (free_size > size) {
355 int extra = 0;
356 if (flags & PAGE_ALIGNED)
357 extra = ( -free_chunk->start & ((pagesize/kMemoryAlign)-1) ) ;
358 if (extra) {
359 chunk_t* split = new chunk_t(free_chunk->start, extra);
360 free_chunk->start += extra;
361 mList.insertBefore(free_chunk, split);
362 }
363
364 ALOGE_IF((flags&PAGE_ALIGNED) &&
365 ((free_chunk->start*kMemoryAlign)&(pagesize-1)),
366 "PAGE_ALIGNED requested, but page is not aligned!!!");
367
368 const ssize_t tail_free = free_size - (size+extra);
369 if (tail_free > 0) {
370 chunk_t* split = new chunk_t(
371 free_chunk->start + free_chunk->size, tail_free);
372 mList.insertAfter(free_chunk, split);
373 }
374 }
375 return (free_chunk->start)*kMemoryAlign;
376 }
377 return NO_MEMORY;
378 }
379
dealloc(size_t start)380 SimpleBestFitAllocator::chunk_t* SimpleBestFitAllocator::dealloc(size_t start)
381 {
382 start = start / kMemoryAlign;
383 chunk_t* cur = mList.head();
384 while (cur) {
385 if (cur->start == start) {
386 LOG_FATAL_IF(cur->free,
387 "block at offset 0x%08lX of size 0x%08X already freed",
388 cur->start*kMemoryAlign, cur->size*kMemoryAlign);
389
390 // merge freed blocks together
391 chunk_t* freed = cur;
392 cur->free = 1;
393 do {
394 chunk_t* const p = cur->prev;
395 chunk_t* const n = cur->next;
396 if (p && (p->free || !cur->size)) {
397 freed = p;
398 p->size += cur->size;
399 mList.remove(cur);
400 delete cur;
401 }
402 cur = n;
403 } while (cur && cur->free);
404
405 #ifndef NDEBUG
406 if (!freed->free) {
407 dump_l("dealloc (!freed->free)");
408 }
409 #endif
410 LOG_FATAL_IF(!freed->free,
411 "freed block at offset 0x%08lX of size 0x%08X is not free!",
412 freed->start * kMemoryAlign, freed->size * kMemoryAlign);
413
414 return freed;
415 }
416 cur = cur->next;
417 }
418 return nullptr;
419 }
420
dump(const char * what) const421 void SimpleBestFitAllocator::dump(const char* what) const
422 {
423 Mutex::Autolock _l(mLock);
424 dump_l(what);
425 }
426
dump_l(const char * what) const427 void SimpleBestFitAllocator::dump_l(const char* what) const
428 {
429 String8 result;
430 dump_l(result, what);
431 ALOGD("%s", result.string());
432 }
433
dump(String8 & result,const char * what) const434 void SimpleBestFitAllocator::dump(String8& result,
435 const char* what) const
436 {
437 Mutex::Autolock _l(mLock);
438 dump_l(result, what);
439 }
440
dump_l(String8 & result,const char * what) const441 void SimpleBestFitAllocator::dump_l(String8& result,
442 const char* what) const
443 {
444 size_t size = 0;
445 int32_t i = 0;
446 chunk_t const* cur = mList.head();
447
448 const size_t SIZE = 256;
449 char buffer[SIZE];
450 snprintf(buffer, SIZE, " %s (%p, size=%u)\n",
451 what, this, (unsigned int)mHeapSize);
452
453 result.append(buffer);
454
455 while (cur) {
456 const char* errs[] = {"", "| link bogus NP",
457 "| link bogus PN", "| link bogus NP+PN" };
458 int np = ((cur->next) && cur->next->prev != cur) ? 1 : 0;
459 int pn = ((cur->prev) && cur->prev->next != cur) ? 2 : 0;
460
461 snprintf(buffer, SIZE, " %3u: %p | 0x%08X | 0x%08X | %s %s\n",
462 i, cur, int(cur->start*kMemoryAlign),
463 int(cur->size*kMemoryAlign),
464 int(cur->free) ? "F" : "A",
465 errs[np|pn]);
466
467 result.append(buffer);
468
469 if (!cur->free)
470 size += cur->size*kMemoryAlign;
471
472 i++;
473 cur = cur->next;
474 }
475 snprintf(buffer, SIZE,
476 " size allocated: %u (%u KB)\n", int(size), int(size/1024));
477 result.append(buffer);
478 }
479
480
481 } // namespace android
482