1 
2 /*
3  * Copyright (C) 2013 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #include "rosalloc_space-inl.h"
19 
20 #include "base/logging.h"  // For VLOG.
21 #include "base/time_utils.h"
22 #include "base/utils.h"
23 #include "gc/accounting/card_table.h"
24 #include "gc/accounting/space_bitmap-inl.h"
25 #include "gc/heap.h"
26 #include "memory_tool_malloc_space-inl.h"
27 #include "mirror/class-inl.h"
28 #include "mirror/object-inl.h"
29 #include "runtime.h"
30 #include "scoped_thread_state_change-inl.h"
31 #include "thread.h"
32 #include "thread_list.h"
33 
34 namespace art {
35 namespace gc {
36 namespace space {
37 
38 static constexpr bool kPrefetchDuringRosAllocFreeList = false;
39 static constexpr size_t kPrefetchLookAhead = 8;
40 // Use this only for verification, it is not safe to use since the class of the object may have
41 // been freed.
42 static constexpr bool kVerifyFreedBytes = false;
43 
44 // TODO: Fix
45 // template class MemoryToolMallocSpace<RosAllocSpace, allocator::RosAlloc*>;
46 
RosAllocSpace(MemMap && mem_map,size_t initial_size,const std::string & name,art::gc::allocator::RosAlloc * rosalloc,uint8_t * begin,uint8_t * end,uint8_t * limit,size_t growth_limit,bool can_move_objects,size_t starting_size,bool low_memory_mode)47 RosAllocSpace::RosAllocSpace(MemMap&& mem_map,
48                              size_t initial_size,
49                              const std::string& name,
50                              art::gc::allocator::RosAlloc* rosalloc,
51                              uint8_t* begin,
52                              uint8_t* end,
53                              uint8_t* limit,
54                              size_t growth_limit,
55                              bool can_move_objects,
56                              size_t starting_size,
57                              bool low_memory_mode)
58     : MallocSpace(name,
59                   std::move(mem_map),
60                   begin,
61                   end,
62                   limit,
63                   growth_limit,
64                   true,
65                   can_move_objects,
66                   starting_size, initial_size),
67       rosalloc_(rosalloc), low_memory_mode_(low_memory_mode) {
68   CHECK(rosalloc != nullptr);
69 }
70 
CreateFromMemMap(MemMap && mem_map,const std::string & name,size_t starting_size,size_t initial_size,size_t growth_limit,size_t capacity,bool low_memory_mode,bool can_move_objects)71 RosAllocSpace* RosAllocSpace::CreateFromMemMap(MemMap&& mem_map,
72                                                const std::string& name,
73                                                size_t starting_size,
74                                                size_t initial_size,
75                                                size_t growth_limit,
76                                                size_t capacity,
77                                                bool low_memory_mode,
78                                                bool can_move_objects) {
79   DCHECK(mem_map.IsValid());
80 
81   bool running_on_memory_tool = Runtime::Current()->IsRunningOnMemoryTool();
82 
83   allocator::RosAlloc* rosalloc = CreateRosAlloc(mem_map.Begin(),
84                                                  starting_size,
85                                                  initial_size,
86                                                  capacity,
87                                                  low_memory_mode,
88                                                  running_on_memory_tool);
89   if (rosalloc == nullptr) {
90     LOG(ERROR) << "Failed to initialize rosalloc for alloc space (" << name << ")";
91     return nullptr;
92   }
93 
94   // Protect memory beyond the starting size. MoreCore will add r/w permissions when necessory
95   uint8_t* end = mem_map.Begin() + starting_size;
96   if (capacity - starting_size > 0) {
97     CheckedCall(mprotect, name.c_str(), end, capacity - starting_size, PROT_NONE);
98   }
99 
100   // Everything is set so record in immutable structure and leave
101   uint8_t* begin = mem_map.Begin();
102   // TODO: Fix RosAllocSpace to support ASan. There is currently some issues with
103   // AllocationSize caused by redzones. b/12944686
104   if (running_on_memory_tool) {
105     return new MemoryToolMallocSpace<RosAllocSpace, kDefaultMemoryToolRedZoneBytes, false, true>(
106         std::move(mem_map),
107         initial_size,
108         name,
109         rosalloc,
110         begin,
111         end,
112         begin + capacity,
113         growth_limit,
114         can_move_objects,
115         starting_size,
116         low_memory_mode);
117   } else {
118     return new RosAllocSpace(std::move(mem_map),
119                              initial_size,
120                              name,
121                              rosalloc,
122                              begin,
123                              end,
124                              begin + capacity,
125                              growth_limit,
126                              can_move_objects,
127                              starting_size,
128                              low_memory_mode);
129   }
130 }
131 
~RosAllocSpace()132 RosAllocSpace::~RosAllocSpace() {
133   delete rosalloc_;
134 }
135 
Create(const std::string & name,size_t initial_size,size_t growth_limit,size_t capacity,bool low_memory_mode,bool can_move_objects)136 RosAllocSpace* RosAllocSpace::Create(const std::string& name,
137                                      size_t initial_size,
138                                      size_t growth_limit,
139                                      size_t capacity,
140                                      bool low_memory_mode,
141                                      bool can_move_objects) {
142   uint64_t start_time = 0;
143   if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
144     start_time = NanoTime();
145     VLOG(startup) << "RosAllocSpace::Create entering " << name
146                   << " initial_size=" << PrettySize(initial_size)
147                   << " growth_limit=" << PrettySize(growth_limit)
148                   << " capacity=" << PrettySize(capacity);
149   }
150 
151   // Memory we promise to rosalloc before it asks for morecore.
152   // Note: making this value large means that large allocations are unlikely to succeed as rosalloc
153   // will ask for this memory from sys_alloc which will fail as the footprint (this value plus the
154   // size of the large allocation) will be greater than the footprint limit.
155   size_t starting_size = Heap::kDefaultStartingSize;
156   MemMap mem_map = CreateMemMap(name, starting_size, &initial_size, &growth_limit, &capacity);
157   if (!mem_map.IsValid()) {
158     LOG(ERROR) << "Failed to create mem map for alloc space (" << name << ") of size "
159                << PrettySize(capacity);
160     return nullptr;
161   }
162 
163   RosAllocSpace* space = CreateFromMemMap(std::move(mem_map),
164                                           name,
165                                           starting_size,
166                                           initial_size,
167                                           growth_limit,
168                                           capacity,
169                                           low_memory_mode,
170                                           can_move_objects);
171   // We start out with only the initial size possibly containing objects.
172   if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
173     LOG(INFO) << "RosAllocSpace::Create exiting (" << PrettyDuration(NanoTime() - start_time)
174         << " ) " << *space;
175   }
176   return space;
177 }
178 
CreateRosAlloc(void * begin,size_t morecore_start,size_t initial_size,size_t maximum_size,bool low_memory_mode,bool running_on_memory_tool)179 allocator::RosAlloc* RosAllocSpace::CreateRosAlloc(void* begin, size_t morecore_start,
180                                                    size_t initial_size,
181                                                    size_t maximum_size, bool low_memory_mode,
182                                                    bool running_on_memory_tool) {
183   // clear errno to allow PLOG on error
184   errno = 0;
185   // create rosalloc using our backing storage starting at begin and
186   // with a footprint of morecore_start. When morecore_start bytes of
187   // memory is exhaused morecore will be called.
188   allocator::RosAlloc* rosalloc = new art::gc::allocator::RosAlloc(
189       begin, morecore_start, maximum_size,
190       low_memory_mode ?
191           art::gc::allocator::RosAlloc::kPageReleaseModeAll :
192           art::gc::allocator::RosAlloc::kPageReleaseModeSizeAndEnd,
193       running_on_memory_tool);
194   if (rosalloc != nullptr) {
195     rosalloc->SetFootprintLimit(initial_size);
196   } else {
197     PLOG(ERROR) << "RosAlloc::Create failed";
198   }
199   return rosalloc;
200 }
201 
AllocWithGrowth(Thread * self,size_t num_bytes,size_t * bytes_allocated,size_t * usable_size,size_t * bytes_tl_bulk_allocated)202 mirror::Object* RosAllocSpace::AllocWithGrowth(Thread* self, size_t num_bytes,
203                                                size_t* bytes_allocated, size_t* usable_size,
204                                                size_t* bytes_tl_bulk_allocated) {
205   mirror::Object* result;
206   {
207     MutexLock mu(self, lock_);
208     // Grow as much as possible within the space.
209     size_t max_allowed = Capacity();
210     rosalloc_->SetFootprintLimit(max_allowed);
211     // Try the allocation.
212     result = AllocCommon(self, num_bytes, bytes_allocated, usable_size,
213                          bytes_tl_bulk_allocated);
214     // Shrink back down as small as possible.
215     size_t footprint = rosalloc_->Footprint();
216     rosalloc_->SetFootprintLimit(footprint);
217   }
218   // Note RosAlloc zeroes memory internally.
219   // Return the new allocation or null.
220   CHECK(!kDebugSpaces || result == nullptr || Contains(result));
221   return result;
222 }
223 
CreateInstance(MemMap && mem_map,const std::string & name,void * allocator,uint8_t * begin,uint8_t * end,uint8_t * limit,size_t growth_limit,bool can_move_objects)224 MallocSpace* RosAllocSpace::CreateInstance(MemMap&& mem_map,
225                                            const std::string& name,
226                                            void* allocator,
227                                            uint8_t* begin,
228                                            uint8_t* end,
229                                            uint8_t* limit,
230                                            size_t growth_limit,
231                                            bool can_move_objects) {
232   if (Runtime::Current()->IsRunningOnMemoryTool()) {
233     return new MemoryToolMallocSpace<RosAllocSpace, kDefaultMemoryToolRedZoneBytes, false, true>(
234         std::move(mem_map),
235         initial_size_,
236         name,
237         reinterpret_cast<allocator::RosAlloc*>(allocator),
238         begin,
239         end,
240         limit,
241         growth_limit,
242         can_move_objects,
243         starting_size_,
244         low_memory_mode_);
245   } else {
246     return new RosAllocSpace(std::move(mem_map),
247                              initial_size_,
248                              name,
249                              reinterpret_cast<allocator::RosAlloc*>(allocator),
250                              begin,
251                              end,
252                              limit,
253                              growth_limit,
254                              can_move_objects,
255                              starting_size_,
256                              low_memory_mode_);
257   }
258 }
259 
Free(Thread * self,mirror::Object * ptr)260 size_t RosAllocSpace::Free(Thread* self, mirror::Object* ptr) {
261   if (kDebugSpaces) {
262     CHECK(ptr != nullptr);
263     CHECK(Contains(ptr)) << "Free (" << ptr << ") not in bounds of heap " << *this;
264   }
265   if (kRecentFreeCount > 0) {
266     MutexLock mu(self, lock_);
267     RegisterRecentFree(ptr);
268   }
269   return rosalloc_->Free(self, ptr);
270 }
271 
FreeList(Thread * self,size_t num_ptrs,mirror::Object ** ptrs)272 size_t RosAllocSpace::FreeList(Thread* self, size_t num_ptrs, mirror::Object** ptrs) {
273   DCHECK(ptrs != nullptr);
274 
275   size_t verify_bytes = 0;
276   for (size_t i = 0; i < num_ptrs; i++) {
277     if (kPrefetchDuringRosAllocFreeList && i + kPrefetchLookAhead < num_ptrs) {
278       __builtin_prefetch(reinterpret_cast<char*>(ptrs[i + kPrefetchLookAhead]));
279     }
280     if (kVerifyFreedBytes) {
281       verify_bytes += AllocationSizeNonvirtual<true>(ptrs[i], nullptr);
282     }
283   }
284 
285   if (kRecentFreeCount > 0) {
286     MutexLock mu(self, lock_);
287     for (size_t i = 0; i < num_ptrs; i++) {
288       RegisterRecentFree(ptrs[i]);
289     }
290   }
291 
292   if (kDebugSpaces) {
293     size_t num_broken_ptrs = 0;
294     for (size_t i = 0; i < num_ptrs; i++) {
295       if (!Contains(ptrs[i])) {
296         num_broken_ptrs++;
297         LOG(ERROR) << "FreeList[" << i << "] (" << ptrs[i] << ") not in bounds of heap " << *this;
298       } else {
299         size_t size = rosalloc_->UsableSize(ptrs[i]);
300         memset(ptrs[i], 0xEF, size);
301       }
302     }
303     CHECK_EQ(num_broken_ptrs, 0u);
304   }
305 
306   const size_t bytes_freed = rosalloc_->BulkFree(self, reinterpret_cast<void**>(ptrs), num_ptrs);
307   if (kVerifyFreedBytes) {
308     CHECK_EQ(verify_bytes, bytes_freed);
309   }
310   return bytes_freed;
311 }
312 
Trim()313 size_t RosAllocSpace::Trim() {
314   VLOG(heap) << "RosAllocSpace::Trim() ";
315   {
316     Thread* const self = Thread::Current();
317     // SOA required for Rosalloc::Trim() -> ArtRosAllocMoreCore() -> Heap::GetRosAllocSpace.
318     ScopedObjectAccess soa(self);
319     MutexLock mu(self, lock_);
320     // Trim to release memory at the end of the space.
321     rosalloc_->Trim();
322   }
323   // Attempt to release pages if it does not release all empty pages.
324   if (!rosalloc_->DoesReleaseAllPages()) {
325     return rosalloc_->ReleasePages();
326   }
327   return 0;
328 }
329 
Walk(void (* callback)(void * start,void * end,size_t num_bytes,void * callback_arg),void * arg)330 void RosAllocSpace::Walk(void(*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
331                          void* arg) {
332   InspectAllRosAlloc(callback, arg, true);
333 }
334 
GetFootprint()335 size_t RosAllocSpace::GetFootprint() {
336   MutexLock mu(Thread::Current(), lock_);
337   return rosalloc_->Footprint();
338 }
339 
GetFootprintLimit()340 size_t RosAllocSpace::GetFootprintLimit() {
341   MutexLock mu(Thread::Current(), lock_);
342   return rosalloc_->FootprintLimit();
343 }
344 
SetFootprintLimit(size_t new_size)345 void RosAllocSpace::SetFootprintLimit(size_t new_size) {
346   MutexLock mu(Thread::Current(), lock_);
347   VLOG(heap) << "RosAllocSpace::SetFootprintLimit " << PrettySize(new_size);
348   // Compare against the actual footprint, rather than the Size(), because the heap may not have
349   // grown all the way to the allowed size yet.
350   size_t current_space_size = rosalloc_->Footprint();
351   if (new_size < current_space_size) {
352     // Don't let the space grow any more.
353     new_size = current_space_size;
354   }
355   rosalloc_->SetFootprintLimit(new_size);
356 }
357 
GetBytesAllocated()358 uint64_t RosAllocSpace::GetBytesAllocated() {
359   size_t bytes_allocated = 0;
360   InspectAllRosAlloc(art::gc::allocator::RosAlloc::BytesAllocatedCallback, &bytes_allocated, false);
361   return bytes_allocated;
362 }
363 
GetObjectsAllocated()364 uint64_t RosAllocSpace::GetObjectsAllocated() {
365   size_t objects_allocated = 0;
366   InspectAllRosAlloc(art::gc::allocator::RosAlloc::ObjectsAllocatedCallback, &objects_allocated, false);
367   return objects_allocated;
368 }
369 
InspectAllRosAllocWithSuspendAll(void (* callback)(void * start,void * end,size_t num_bytes,void * callback_arg),void * arg,bool do_null_callback_at_end)370 void RosAllocSpace::InspectAllRosAllocWithSuspendAll(
371     void (*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
372     void* arg, bool do_null_callback_at_end) NO_THREAD_SAFETY_ANALYSIS {
373   // TODO: NO_THREAD_SAFETY_ANALYSIS.
374   Thread* self = Thread::Current();
375   ScopedSuspendAll ssa(__FUNCTION__);
376   MutexLock mu(self, *Locks::runtime_shutdown_lock_);
377   MutexLock mu2(self, *Locks::thread_list_lock_);
378   rosalloc_->InspectAll(callback, arg);
379   if (do_null_callback_at_end) {
380     callback(nullptr, nullptr, 0, arg);  // Indicate end of a space.
381   }
382 }
383 
InspectAllRosAlloc(void (* callback)(void * start,void * end,size_t num_bytes,void * callback_arg),void * arg,bool do_null_callback_at_end)384 void RosAllocSpace::InspectAllRosAlloc(void (*callback)(void *start, void *end, size_t num_bytes, void* callback_arg),
385                                        void* arg, bool do_null_callback_at_end) NO_THREAD_SAFETY_ANALYSIS {
386   // TODO: NO_THREAD_SAFETY_ANALYSIS.
387   Thread* self = Thread::Current();
388   if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
389     // The mutators are already suspended. For example, a call path
390     // from SignalCatcher::HandleSigQuit().
391     rosalloc_->InspectAll(callback, arg);
392     if (do_null_callback_at_end) {
393       callback(nullptr, nullptr, 0, arg);  // Indicate end of a space.
394     }
395   } else if (Locks::mutator_lock_->IsSharedHeld(self)) {
396     // The mutators are not suspended yet and we have a shared access
397     // to the mutator lock. Temporarily release the shared access by
398     // transitioning to the suspend state, and suspend the mutators.
399     ScopedThreadSuspension sts(self, kSuspended);
400     InspectAllRosAllocWithSuspendAll(callback, arg, do_null_callback_at_end);
401   } else {
402     // The mutators are not suspended yet. Suspend the mutators.
403     InspectAllRosAllocWithSuspendAll(callback, arg, do_null_callback_at_end);
404   }
405 }
406 
RevokeThreadLocalBuffers(Thread * thread)407 size_t RosAllocSpace::RevokeThreadLocalBuffers(Thread* thread) {
408   return rosalloc_->RevokeThreadLocalRuns(thread);
409 }
410 
RevokeAllThreadLocalBuffers()411 size_t RosAllocSpace::RevokeAllThreadLocalBuffers() {
412   return rosalloc_->RevokeAllThreadLocalRuns();
413 }
414 
AssertThreadLocalBuffersAreRevoked(Thread * thread)415 void RosAllocSpace::AssertThreadLocalBuffersAreRevoked(Thread* thread) {
416   if (kIsDebugBuild) {
417     rosalloc_->AssertThreadLocalRunsAreRevoked(thread);
418   }
419 }
420 
AssertAllThreadLocalBuffersAreRevoked()421 void RosAllocSpace::AssertAllThreadLocalBuffersAreRevoked() {
422   if (kIsDebugBuild) {
423     rosalloc_->AssertAllThreadLocalRunsAreRevoked();
424   }
425 }
426 
Clear()427 void RosAllocSpace::Clear() {
428   size_t footprint_limit = GetFootprintLimit();
429   madvise(GetMemMap()->Begin(), GetMemMap()->Size(), MADV_DONTNEED);
430   live_bitmap_.Clear();
431   mark_bitmap_.Clear();
432   SetEnd(begin_ + starting_size_);
433   delete rosalloc_;
434   rosalloc_ = CreateRosAlloc(mem_map_.Begin(),
435                              starting_size_,
436                              initial_size_,
437                              NonGrowthLimitCapacity(),
438                              low_memory_mode_,
439                              Runtime::Current()->IsRunningOnMemoryTool());
440   SetFootprintLimit(footprint_limit);
441 }
442 
DumpStats(std::ostream & os)443 void RosAllocSpace::DumpStats(std::ostream& os) {
444   ScopedSuspendAll ssa(__FUNCTION__);
445   rosalloc_->DumpStats(os);
446 }
447 
448 template<bool kMaybeIsRunningOnMemoryTool>
AllocationSizeNonvirtual(mirror::Object * obj,size_t * usable_size)449 size_t RosAllocSpace::AllocationSizeNonvirtual(mirror::Object* obj, size_t* usable_size) {
450   // obj is a valid object. Use its class in the header to get the size.
451   // Don't use verification since the object may be dead if we are sweeping.
452   size_t size = obj->SizeOf<kVerifyNone>();
453   bool add_redzones = false;
454   if (kMaybeIsRunningOnMemoryTool) {
455     add_redzones = kRunningOnMemoryTool && kMemoryToolAddsRedzones;
456     if (add_redzones) {
457       size += 2 * kDefaultMemoryToolRedZoneBytes;
458     }
459   } else {
460     DCHECK(!kRunningOnMemoryTool);
461   }
462   size_t size_by_size = rosalloc_->UsableSize(size);
463   if (kIsDebugBuild) {
464     // On memory tool, the red zone has an impact...
465     const uint8_t* obj_ptr = reinterpret_cast<const uint8_t*>(obj);
466     size_t size_by_ptr = rosalloc_->UsableSize(
467         obj_ptr - (add_redzones ? kDefaultMemoryToolRedZoneBytes : 0));
468     if (size_by_size != size_by_ptr) {
469       LOG(INFO) << "Found a bad sized obj of size " << size
470                 << " at " << std::hex << reinterpret_cast<intptr_t>(obj_ptr) << std::dec
471                 << " size_by_size=" << size_by_size << " size_by_ptr=" << size_by_ptr;
472     }
473     DCHECK_EQ(size_by_size, size_by_ptr);
474   }
475   if (usable_size != nullptr) {
476     *usable_size = size_by_size;
477   }
478   return size_by_size;
479 }
480 
481 }  // namespace space
482 
483 namespace allocator {
484 
485 // Callback from rosalloc when it needs to increase the footprint.
ArtRosAllocMoreCore(allocator::RosAlloc * rosalloc,intptr_t increment)486 void* ArtRosAllocMoreCore(allocator::RosAlloc* rosalloc, intptr_t increment)
487     REQUIRES_SHARED(Locks::mutator_lock_) {
488   Heap* heap = Runtime::Current()->GetHeap();
489   art::gc::space::RosAllocSpace* rosalloc_space = heap->GetRosAllocSpace(rosalloc);
490   DCHECK(rosalloc_space != nullptr);
491   DCHECK_EQ(rosalloc_space->GetRosAlloc(), rosalloc);
492   return rosalloc_space->MoreCore(increment);
493 }
494 
495 }  // namespace allocator
496 
497 }  // namespace gc
498 }  // namespace art
499