1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef PANDA_RUNTIME_INCLUDE_MEM_ALLOCATOR_INL_H_
17 #define PANDA_RUNTIME_INCLUDE_MEM_ALLOCATOR_INL_H_
18
19 #include "runtime/include/mem/allocator.h"
20 namespace panda::mem {
21
22 template <typename AllocT>
AllocateSafe(size_t size,Alignment align,AllocT * object_allocator,size_t pool_size,SpaceType space_type)23 inline void *ObjectAllocatorBase::AllocateSafe(size_t size, Alignment align, AllocT *object_allocator, size_t pool_size,
24 SpaceType space_type)
25 {
26 void *mem = object_allocator->Alloc(size, align);
27 if (UNLIKELY(mem == nullptr)) {
28 return AddPoolsAndAlloc(size, align, object_allocator, pool_size, space_type);
29 }
30 return mem;
31 }
32
33 template <typename AllocT>
AddPoolsAndAlloc(size_t size,Alignment align,AllocT * object_allocator,size_t pool_size,SpaceType space_type)34 inline void *ObjectAllocatorBase::AddPoolsAndAlloc(size_t size, Alignment align, AllocT *object_allocator,
35 size_t pool_size, SpaceType space_type)
36 {
37 void *mem = nullptr;
38 static os::memory::Mutex pool_lock;
39 os::memory::LockHolder lock(pool_lock);
40 while (true) {
41 auto pool = PoolManager::GetMmapMemPool()->AllocPool(pool_size, space_type, AllocT::GetAllocatorType(),
42 object_allocator);
43 if (UNLIKELY(pool.GetMem() == nullptr)) {
44 return nullptr;
45 }
46 bool added_memory_pool = object_allocator->AddMemoryPool(pool.GetMem(), pool.GetSize());
47 if (!added_memory_pool) {
48 LOG(FATAL, ALLOC) << "ObjectAllocator: couldn't add memory pool to object allocator";
49 }
50 mem = object_allocator->Alloc(size, align);
51 if (mem != nullptr) {
52 break;
53 }
54 }
55 return mem;
56 }
57
58 } // namespace panda::mem
59
60 #endif // PANDA_RUNTIME_INCLUDE_MEM_ALLOCATOR_INL_H_
61