1 /*
2  * Copyright (C) 2013 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 "malloc_space.h"
18 
19 #include "android-base/stringprintf.h"
20 
21 #include "base/logging.h"  // For VLOG
22 #include "base/utils.h"
23 #include "gc/accounting/card_table-inl.h"
24 #include "gc/accounting/space_bitmap-inl.h"
25 #include "gc/heap.h"
26 #include "gc/space/space-inl.h"
27 #include "gc/space/zygote_space.h"
28 #include "handle_scope-inl.h"
29 #include "mirror/class-inl.h"
30 #include "mirror/object-inl.h"
31 #include "runtime.h"
32 #include "thread.h"
33 #include "thread_list.h"
34 
35 namespace art {
36 namespace gc {
37 namespace space {
38 
39 using android::base::StringPrintf;
40 
41 size_t MallocSpace::bitmap_index_ = 0;
42 
MallocSpace(const std::string & name,MemMap * mem_map,uint8_t * begin,uint8_t * end,uint8_t * limit,size_t growth_limit,bool create_bitmaps,bool can_move_objects,size_t starting_size,size_t initial_size)43 MallocSpace::MallocSpace(const std::string& name, MemMap* mem_map,
44                          uint8_t* begin, uint8_t* end, uint8_t* limit, size_t growth_limit,
45                          bool create_bitmaps, bool can_move_objects, size_t starting_size,
46                          size_t initial_size)
47     : ContinuousMemMapAllocSpace(name, mem_map, begin, end, limit, kGcRetentionPolicyAlwaysCollect),
48       recent_free_pos_(0), lock_("allocation space lock", kAllocSpaceLock),
49       growth_limit_(growth_limit), can_move_objects_(can_move_objects),
50       starting_size_(starting_size), initial_size_(initial_size) {
51   if (create_bitmaps) {
52     size_t bitmap_index = bitmap_index_++;
53     static const uintptr_t kGcCardSize = static_cast<uintptr_t>(accounting::CardTable::kCardSize);
54     CHECK_ALIGNED(reinterpret_cast<uintptr_t>(mem_map->Begin()), kGcCardSize);
55     CHECK_ALIGNED(reinterpret_cast<uintptr_t>(mem_map->End()), kGcCardSize);
56     live_bitmap_.reset(accounting::ContinuousSpaceBitmap::Create(
57         StringPrintf("allocspace %s live-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)),
58         Begin(), NonGrowthLimitCapacity()));
59     CHECK(live_bitmap_.get() != nullptr) << "could not create allocspace live bitmap #"
60         << bitmap_index;
61     mark_bitmap_.reset(accounting::ContinuousSpaceBitmap::Create(
62         StringPrintf("allocspace %s mark-bitmap %d", name.c_str(), static_cast<int>(bitmap_index)),
63         Begin(), NonGrowthLimitCapacity()));
64     CHECK(mark_bitmap_.get() != nullptr) << "could not create allocspace mark bitmap #"
65         << bitmap_index;
66   }
67   for (auto& freed : recent_freed_objects_) {
68     freed.first = nullptr;
69     freed.second = nullptr;
70   }
71 }
72 
CreateMemMap(const std::string & name,size_t starting_size,size_t * initial_size,size_t * growth_limit,size_t * capacity,uint8_t * requested_begin)73 MemMap* MallocSpace::CreateMemMap(const std::string& name, size_t starting_size, size_t* initial_size,
74                                   size_t* growth_limit, size_t* capacity, uint8_t* requested_begin) {
75   // Sanity check arguments
76   if (starting_size > *initial_size) {
77     *initial_size = starting_size;
78   }
79   if (*initial_size > *growth_limit) {
80     LOG(ERROR) << "Failed to create alloc space (" << name << ") where the initial size ("
81         << PrettySize(*initial_size) << ") is larger than its capacity ("
82         << PrettySize(*growth_limit) << ")";
83     return nullptr;
84   }
85   if (*growth_limit > *capacity) {
86     LOG(ERROR) << "Failed to create alloc space (" << name << ") where the growth limit capacity ("
87         << PrettySize(*growth_limit) << ") is larger than the capacity ("
88         << PrettySize(*capacity) << ")";
89     return nullptr;
90   }
91 
92   // Page align growth limit and capacity which will be used to manage mmapped storage
93   *growth_limit = RoundUp(*growth_limit, kPageSize);
94   *capacity = RoundUp(*capacity, kPageSize);
95 
96   std::string error_msg;
97   MemMap* mem_map = MemMap::MapAnonymous(name.c_str(), requested_begin, *capacity,
98                                          PROT_READ | PROT_WRITE, true, false, &error_msg);
99   if (mem_map == nullptr) {
100     LOG(ERROR) << "Failed to allocate pages for alloc space (" << name << ") of size "
101                << PrettySize(*capacity) << ": " << error_msg;
102   }
103   return mem_map;
104 }
105 
FindRecentFreedObject(const mirror::Object * obj)106 mirror::Class* MallocSpace::FindRecentFreedObject(const mirror::Object* obj) {
107   size_t pos = recent_free_pos_;
108   // Start at the most recently freed object and work our way back since there may be duplicates
109   // caused by dlmalloc reusing memory.
110   if (kRecentFreeCount > 0) {
111     for (size_t i = 0; i + 1 < kRecentFreeCount + 1; ++i) {
112       pos = pos != 0 ? pos - 1 : kRecentFreeMask;
113       if (recent_freed_objects_[pos].first == obj) {
114         return recent_freed_objects_[pos].second;
115       }
116     }
117   }
118   return nullptr;
119 }
120 
RegisterRecentFree(mirror::Object * ptr)121 void MallocSpace::RegisterRecentFree(mirror::Object* ptr) {
122   // No verification since the object is dead.
123   recent_freed_objects_[recent_free_pos_] = std::make_pair(ptr, ptr->GetClass<kVerifyNone>());
124   recent_free_pos_ = (recent_free_pos_ + 1) & kRecentFreeMask;
125 }
126 
SetGrowthLimit(size_t growth_limit)127 void MallocSpace::SetGrowthLimit(size_t growth_limit) {
128   growth_limit = RoundUp(growth_limit, kPageSize);
129   growth_limit_ = growth_limit;
130   if (Size() > growth_limit_) {
131     SetEnd(begin_ + growth_limit);
132   }
133 }
134 
MoreCore(intptr_t increment)135 void* MallocSpace::MoreCore(intptr_t increment) {
136   CheckMoreCoreForPrecondition();
137   uint8_t* original_end = End();
138   if (increment != 0) {
139     VLOG(heap) << "MallocSpace::MoreCore " << PrettySize(increment);
140     uint8_t* new_end = original_end + increment;
141     if (increment > 0) {
142       // Should never be asked to increase the allocation beyond the capacity of the space. Enforced
143       // by mspace_set_footprint_limit.
144       CHECK_LE(new_end, Begin() + Capacity());
145       CheckedCall(mprotect, GetName(), original_end, increment, PROT_READ | PROT_WRITE);
146     } else {
147       // Should never be asked for negative footprint (ie before begin). Zero footprint is ok.
148       CHECK_GE(original_end + increment, Begin());
149       // Advise we don't need the pages and protect them
150       // TODO: by removing permissions to the pages we may be causing TLB shoot-down which can be
151       // expensive (note the same isn't true for giving permissions to a page as the protected
152       // page shouldn't be in a TLB). We should investigate performance impact of just
153       // removing ignoring the memory protection change here and in Space::CreateAllocSpace. It's
154       // likely just a useful debug feature.
155       size_t size = -increment;
156       CheckedCall(madvise, GetName(), new_end, size, MADV_DONTNEED);
157       CheckedCall(mprotect, GetName(), new_end, size, PROT_NONE);
158     }
159     // Update end_.
160     SetEnd(new_end);
161   }
162   return original_end;
163 }
164 
CreateZygoteSpace(const char * alloc_space_name,bool low_memory_mode,MallocSpace ** out_malloc_space)165 ZygoteSpace* MallocSpace::CreateZygoteSpace(const char* alloc_space_name, bool low_memory_mode,
166                                             MallocSpace** out_malloc_space) {
167   // For RosAlloc, revoke thread local runs before creating a new
168   // alloc space so that we won't mix thread local runs from different
169   // alloc spaces.
170   RevokeAllThreadLocalBuffers();
171   SetEnd(reinterpret_cast<uint8_t*>(RoundUp(reinterpret_cast<uintptr_t>(End()), kPageSize)));
172   DCHECK_ALIGNED(begin_, accounting::CardTable::kCardSize);
173   DCHECK_ALIGNED(End(), accounting::CardTable::kCardSize);
174   DCHECK_ALIGNED(begin_, kPageSize);
175   DCHECK_ALIGNED(End(), kPageSize);
176   size_t size = RoundUp(Size(), kPageSize);
177   // Trimming the heap should be done by the caller since we may have invalidated the accounting
178   // stored in between objects.
179   // Remaining size is for the new alloc space.
180   const size_t growth_limit = growth_limit_ - size;
181   // Use mem map limit in case error for clear growth limit.
182   const size_t capacity = NonGrowthLimitCapacity() - size;
183   VLOG(heap) << "Begin " << reinterpret_cast<const void*>(begin_) << "\n"
184              << "End " << reinterpret_cast<const void*>(End()) << "\n"
185              << "Size " << size << "\n"
186              << "GrowthLimit " << growth_limit_ << "\n"
187              << "Capacity " << Capacity();
188   SetGrowthLimit(RoundUp(size, kPageSize));
189   // FIXME: Do we need reference counted pointers here?
190   // Make the two spaces share the same mark bitmaps since the bitmaps span both of the spaces.
191   VLOG(heap) << "Creating new AllocSpace: ";
192   VLOG(heap) << "Size " << GetMemMap()->Size();
193   VLOG(heap) << "GrowthLimit " << PrettySize(growth_limit);
194   VLOG(heap) << "Capacity " << PrettySize(capacity);
195   // Remap the tail.
196   std::string error_msg;
197   std::unique_ptr<MemMap> mem_map(GetMemMap()->RemapAtEnd(End(), alloc_space_name,
198                                                           PROT_READ | PROT_WRITE, &error_msg));
199   CHECK(mem_map.get() != nullptr) << error_msg;
200   void* allocator = CreateAllocator(End(), starting_size_, initial_size_, capacity,
201                                     low_memory_mode);
202   // Protect memory beyond the initial size.
203   uint8_t* end = mem_map->Begin() + starting_size_;
204   if (capacity > initial_size_) {
205     CheckedCall(mprotect, alloc_space_name, end, capacity - initial_size_, PROT_NONE);
206   }
207   *out_malloc_space = CreateInstance(mem_map.release(), alloc_space_name, allocator, End(), end,
208                                      limit_, growth_limit, CanMoveObjects());
209   SetLimit(End());
210   live_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
211   CHECK_EQ(live_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
212   mark_bitmap_->SetHeapLimit(reinterpret_cast<uintptr_t>(End()));
213   CHECK_EQ(mark_bitmap_->HeapLimit(), reinterpret_cast<uintptr_t>(End()));
214 
215   // Create the actual zygote space.
216   ZygoteSpace* zygote_space = ZygoteSpace::Create("Zygote space", ReleaseMemMap(),
217                                                   live_bitmap_.release(), mark_bitmap_.release());
218   if (UNLIKELY(zygote_space == nullptr)) {
219     VLOG(heap) << "Failed creating zygote space from space " << GetName();
220   } else {
221     VLOG(heap) << "zygote space creation done";
222   }
223   return zygote_space;
224 }
225 
Dump(std::ostream & os) const226 void MallocSpace::Dump(std::ostream& os) const {
227   os << GetType()
228      << " begin=" << reinterpret_cast<void*>(Begin())
229      << ",end=" << reinterpret_cast<void*>(End())
230      << ",limit=" << reinterpret_cast<void*>(Limit())
231      << ",size=" << PrettySize(Size()) << ",capacity=" << PrettySize(Capacity())
232      << ",non_growth_limit_capacity=" << PrettySize(NonGrowthLimitCapacity())
233      << ",name=\"" << GetName() << "\"]";
234 }
235 
SweepCallback(size_t num_ptrs,mirror::Object ** ptrs,void * arg)236 void MallocSpace::SweepCallback(size_t num_ptrs, mirror::Object** ptrs, void* arg) {
237   SweepCallbackContext* context = static_cast<SweepCallbackContext*>(arg);
238   space::MallocSpace* space = context->space->AsMallocSpace();
239   Thread* self = context->self;
240   Locks::heap_bitmap_lock_->AssertExclusiveHeld(self);
241   // If the bitmaps aren't swapped we need to clear the bits since the GC isn't going to re-swap
242   // the bitmaps as an optimization.
243   if (!context->swap_bitmaps) {
244     accounting::ContinuousSpaceBitmap* bitmap = space->GetLiveBitmap();
245     for (size_t i = 0; i < num_ptrs; ++i) {
246       bitmap->Clear(ptrs[i]);
247     }
248   }
249   // Use a bulk free, that merges consecutive objects before freeing or free per object?
250   // Documentation suggests better free performance with merging, but this may be at the expensive
251   // of allocation.
252   context->freed.objects += num_ptrs;
253   context->freed.bytes += space->FreeList(self, num_ptrs, ptrs);
254 }
255 
ClampGrowthLimit()256 void MallocSpace::ClampGrowthLimit() {
257   size_t new_capacity = Capacity();
258   CHECK_LE(new_capacity, NonGrowthLimitCapacity());
259   GetLiveBitmap()->SetHeapSize(new_capacity);
260   GetMarkBitmap()->SetHeapSize(new_capacity);
261   if (temp_bitmap_.get() != nullptr) {
262     // If the bitmaps are clamped, then the temp bitmap is actually the mark bitmap.
263     temp_bitmap_->SetHeapSize(new_capacity);
264   }
265   GetMemMap()->SetSize(new_capacity);
266   limit_ = Begin() + new_capacity;
267 }
268 
269 }  // namespace space
270 }  // namespace gc
271 }  // namespace art
272