1 /*
2  * Copyright (C) 2016 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 #include "chre/platform/memory.h"
18 #include "chre/platform/slpi/memory.h"
19 
20 #ifdef CHRE_SLPI_SEE
21 #include "chre/platform/slpi/see/island_vote_client.h"
22 #endif
23 
24 #include <cstdlib>
25 
26 extern "C" {
27 
28 #include "sns_island_util.h"
29 #include "sns_memmgr.h"
30 
31 }  // extern "C"
32 
33 namespace chre {
34 
35 void *memoryAlloc(size_t size) {
36 #ifdef CHRE_SLPI_UIMG_ENABLED
37   void *ptr = sns_malloc(SNS_HEAP_CHRE_ISLAND, size);
38 
39   // Fall back to big image memory when uimg memory is exhausted.
40   // Must exclude size 0 as clients may not explicitly free memory of size 0,
41   // which may mistakenly hold the system in big image.
42   if (ptr == nullptr && size != 0) {
43     // Increment big image ref count to prevent system from entering uimg
44     // while big image memory is in use.
45     IslandVoteClientSingleton::get()->incrementBigImageRefCount();
46     ptr = memoryAllocBigImage(size);
47 
48     // Big image allocation failed too.
49     if (ptr == nullptr) {
50       IslandVoteClientSingleton::get()->decrementBigImageRefCount();
51     }
52   }
53 
54   return ptr;
55 #else
56   return malloc(size);
57 #endif  // CHRE_SLPI_UIMG_ENABLED
58 }
59 
60 void *memoryAllocBigImage(size_t size) {
61   return malloc(size);
62 }
63 
64 void *palSystemApiMemoryAlloc(size_t size) {
65   return malloc(size);
66 }
67 
68 void memoryFree(void *pointer) {
69 #ifdef CHRE_SLPI_UIMG_ENABLED
70   if (sns_island_is_island_ptr(reinterpret_cast<intptr_t>(pointer))) {
71     sns_free(pointer);
72   } else {
73     memoryFreeBigImage(pointer);
74 
75     // Must exclude nullptr as it's excluded in memoryAlloc() as well.
76     // Note currently sns_island_is_island_ptr returns true for nullptr,
77     // so this mainly serves as a protection in case the implementation of
78     // sns_island_is_island_ptr changes in the future.
79     if (pointer != nullptr) {
80       IslandVoteClientSingleton::get()->decrementBigImageRefCount();
81     }
82   }
83 #else
84   free(pointer);
85 #endif  // CHRE_SLPI_UIMG_ENABLED
86 }
87 
88 void memoryFreeBigImage(void *pointer) {
89   free(pointer);
90 }
91 
92 void palSystemApiMemoryFree(void *pointer) {
93   free(pointer);
94 }
95 
96 }  // namespace chre
97