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 "semi_space-inl.h"
18 
19 #include <climits>
20 #include <functional>
21 #include <numeric>
22 #include <sstream>
23 #include <vector>
24 
25 #include "base/logging.h"
26 #include "base/macros.h"
27 #include "base/mutex-inl.h"
28 #include "base/timing_logger.h"
29 #include "gc/accounting/heap_bitmap-inl.h"
30 #include "gc/accounting/mod_union_table.h"
31 #include "gc/accounting/remembered_set.h"
32 #include "gc/accounting/space_bitmap-inl.h"
33 #include "gc/heap.h"
34 #include "gc/reference_processor.h"
35 #include "gc/space/bump_pointer_space.h"
36 #include "gc/space/bump_pointer_space-inl.h"
37 #include "gc/space/image_space.h"
38 #include "gc/space/large_object_space.h"
39 #include "gc/space/space-inl.h"
40 #include "indirect_reference_table.h"
41 #include "intern_table.h"
42 #include "jni_internal.h"
43 #include "mark_sweep-inl.h"
44 #include "monitor.h"
45 #include "mirror/reference-inl.h"
46 #include "mirror/object-inl.h"
47 #include "runtime.h"
48 #include "thread-inl.h"
49 #include "thread_list.h"
50 
51 using ::art::mirror::Object;
52 
53 namespace art {
54 namespace gc {
55 namespace collector {
56 
57 static constexpr bool kProtectFromSpace = true;
58 static constexpr bool kStoreStackTraces = false;
59 static constexpr size_t kBytesPromotedThreshold = 4 * MB;
60 static constexpr size_t kLargeObjectBytesAllocatedThreshold = 16 * MB;
61 
BindBitmaps()62 void SemiSpace::BindBitmaps() {
63   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
64   WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
65   // Mark all of the spaces we never collect as immune.
66   for (const auto& space : GetHeap()->GetContinuousSpaces()) {
67     if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
68         space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
69       CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
70     } else if (space->GetLiveBitmap() != nullptr) {
71       if (space == to_space_ || collect_from_space_only_) {
72         if (collect_from_space_only_) {
73           // Bind the bitmaps of the main free list space and the non-moving space we are doing a
74           // bump pointer space only collection.
75           CHECK(space == GetHeap()->GetPrimaryFreeListSpace() ||
76                 space == GetHeap()->GetNonMovingSpace());
77         }
78         CHECK(space->IsContinuousMemMapAllocSpace());
79         space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
80       }
81     }
82   }
83   if (collect_from_space_only_) {
84     // We won't collect the large object space if a bump pointer space only collection.
85     is_large_object_space_immune_ = true;
86   }
87 }
88 
SemiSpace(Heap * heap,bool generational,const std::string & name_prefix)89 SemiSpace::SemiSpace(Heap* heap, bool generational, const std::string& name_prefix)
90     : GarbageCollector(heap,
91                        name_prefix + (name_prefix.empty() ? "" : " ") + "marksweep + semispace"),
92       to_space_(nullptr),
93       from_space_(nullptr),
94       generational_(generational),
95       last_gc_to_space_end_(nullptr),
96       bytes_promoted_(0),
97       bytes_promoted_since_last_whole_heap_collection_(0),
98       large_object_bytes_allocated_at_last_whole_heap_collection_(0),
99       collect_from_space_only_(generational),
100       collector_name_(name_),
101       swap_semi_spaces_(true) {
102 }
103 
RunPhases()104 void SemiSpace::RunPhases() {
105   Thread* self = Thread::Current();
106   InitializePhase();
107   // Semi-space collector is special since it is sometimes called with the mutators suspended
108   // during the zygote creation and collector transitions. If we already exclusively hold the
109   // mutator lock, then we can't lock it again since it will cause a deadlock.
110   if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
111     GetHeap()->PreGcVerificationPaused(this);
112     GetHeap()->PrePauseRosAllocVerification(this);
113     MarkingPhase();
114     ReclaimPhase();
115     GetHeap()->PostGcVerificationPaused(this);
116   } else {
117     Locks::mutator_lock_->AssertNotHeld(self);
118     {
119       ScopedPause pause(this);
120       GetHeap()->PreGcVerificationPaused(this);
121       GetHeap()->PrePauseRosAllocVerification(this);
122       MarkingPhase();
123     }
124     {
125       ReaderMutexLock mu(self, *Locks::mutator_lock_);
126       ReclaimPhase();
127     }
128     GetHeap()->PostGcVerification(this);
129   }
130   FinishPhase();
131 }
132 
InitializePhase()133 void SemiSpace::InitializePhase() {
134   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
135   mark_stack_ = heap_->GetMarkStack();
136   DCHECK(mark_stack_ != nullptr);
137   immune_region_.Reset();
138   is_large_object_space_immune_ = false;
139   saved_bytes_ = 0;
140   bytes_moved_ = 0;
141   objects_moved_ = 0;
142   self_ = Thread::Current();
143   CHECK(from_space_->CanMoveObjects()) << "Attempting to move from " << *from_space_;
144   // Set the initial bitmap.
145   to_space_live_bitmap_ = to_space_->GetLiveBitmap();
146   {
147     // TODO: I don't think we should need heap bitmap lock to Get the mark bitmap.
148     ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
149     mark_bitmap_ = heap_->GetMarkBitmap();
150   }
151   if (generational_) {
152     promo_dest_space_ = GetHeap()->GetPrimaryFreeListSpace();
153   }
154   fallback_space_ = GetHeap()->GetNonMovingSpace();
155 }
156 
ProcessReferences(Thread * self)157 void SemiSpace::ProcessReferences(Thread* self) {
158   WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
159   GetHeap()->GetReferenceProcessor()->ProcessReferences(
160       false, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(),
161       &HeapReferenceMarkedCallback, &MarkObjectCallback, &ProcessMarkStackCallback, this);
162 }
163 
MarkingPhase()164 void SemiSpace::MarkingPhase() {
165   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
166   CHECK(Locks::mutator_lock_->IsExclusiveHeld(self_));
167   if (kStoreStackTraces) {
168     Locks::mutator_lock_->AssertExclusiveHeld(self_);
169     // Store the stack traces into the runtime fault string in case we Get a heap corruption
170     // related crash later.
171     ThreadState old_state = self_->SetStateUnsafe(kRunnable);
172     std::ostringstream oss;
173     Runtime* runtime = Runtime::Current();
174     runtime->GetThreadList()->DumpForSigQuit(oss);
175     runtime->GetThreadList()->DumpNativeStacks(oss);
176     runtime->SetFaultMessage(oss.str());
177     CHECK_EQ(self_->SetStateUnsafe(old_state), kRunnable);
178   }
179   // Revoke the thread local buffers since the GC may allocate into a RosAllocSpace and this helps
180   // to prevent fragmentation.
181   RevokeAllThreadLocalBuffers();
182   if (generational_) {
183     if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
184         GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
185         GetCurrentIteration()->GetClearSoftReferences()) {
186       // If an explicit, native allocation-triggered, or last attempt
187       // collection, collect the whole heap.
188       collect_from_space_only_ = false;
189     }
190     if (!collect_from_space_only_) {
191       VLOG(heap) << "Whole heap collection";
192       name_ = collector_name_ + " whole";
193     } else {
194       VLOG(heap) << "Bump pointer space only collection";
195       name_ = collector_name_ + " bps";
196     }
197   }
198 
199   if (!collect_from_space_only_) {
200     // If non-generational, always clear soft references.
201     // If generational, clear soft references if a whole heap collection.
202     GetCurrentIteration()->SetClearSoftReferences(true);
203   }
204   Locks::mutator_lock_->AssertExclusiveHeld(self_);
205   if (generational_) {
206     // If last_gc_to_space_end_ is out of the bounds of the from-space
207     // (the to-space from last GC), then point it to the beginning of
208     // the from-space. For example, the very first GC or the
209     // pre-zygote compaction.
210     if (!from_space_->HasAddress(reinterpret_cast<mirror::Object*>(last_gc_to_space_end_))) {
211       last_gc_to_space_end_ = from_space_->Begin();
212     }
213     // Reset this before the marking starts below.
214     bytes_promoted_ = 0;
215   }
216   // Assume the cleared space is already empty.
217   BindBitmaps();
218   // Process dirty cards and add dirty cards to mod-union tables.
219   heap_->ProcessCards(GetTimings(), kUseRememberedSet && generational_, false, true);
220   // Clear the whole card table since we can not Get any additional dirty cards during the
221   // paused GC. This saves memory but only works for pause the world collectors.
222   t.NewTiming("ClearCardTable");
223   heap_->GetCardTable()->ClearCardTable();
224   // Need to do this before the checkpoint since we don't want any threads to add references to
225   // the live stack during the recursive mark.
226   if (kUseThreadLocalAllocationStack) {
227     TimingLogger::ScopedTiming t2("RevokeAllThreadLocalAllocationStacks", GetTimings());
228     heap_->RevokeAllThreadLocalAllocationStacks(self_);
229   }
230   heap_->SwapStacks(self_);
231   {
232     WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
233     MarkRoots();
234     // Recursively mark remaining objects.
235     MarkReachableObjects();
236   }
237   ProcessReferences(self_);
238   {
239     ReaderMutexLock mu(self_, *Locks::heap_bitmap_lock_);
240     SweepSystemWeaks();
241   }
242   // Revoke buffers before measuring how many objects were moved since the TLABs need to be revoked
243   // before they are properly counted.
244   RevokeAllThreadLocalBuffers();
245   GetHeap()->RecordFreeRevoke();  // this is for the non-moving rosalloc space used by GSS.
246   // Record freed memory.
247   const int64_t from_bytes = from_space_->GetBytesAllocated();
248   const int64_t to_bytes = bytes_moved_;
249   const uint64_t from_objects = from_space_->GetObjectsAllocated();
250   const uint64_t to_objects = objects_moved_;
251   CHECK_LE(to_objects, from_objects);
252   // Note: Freed bytes can be negative if we copy form a compacted space to a free-list backed
253   // space.
254   RecordFree(ObjectBytePair(from_objects - to_objects, from_bytes - to_bytes));
255   // Clear and protect the from space.
256   from_space_->Clear();
257   if (kProtectFromSpace && !from_space_->IsRosAllocSpace()) {
258     // Protect with PROT_NONE.
259     VLOG(heap) << "Protecting from_space_ : " << *from_space_;
260     from_space_->GetMemMap()->Protect(PROT_NONE);
261   } else {
262     // If RosAllocSpace, we'll leave it as PROT_READ here so the
263     // rosaloc verification can read the metadata magic number and
264     // protect it with PROT_NONE later in FinishPhase().
265     VLOG(heap) << "Protecting from_space_ with PROT_READ : " << *from_space_;
266     from_space_->GetMemMap()->Protect(PROT_READ);
267   }
268   heap_->PreSweepingGcVerification(this);
269   if (swap_semi_spaces_) {
270     heap_->SwapSemiSpaces();
271   }
272 }
273 
274 class SemiSpaceScanObjectVisitor {
275  public:
SemiSpaceScanObjectVisitor(SemiSpace * ss)276   explicit SemiSpaceScanObjectVisitor(SemiSpace* ss) : semi_space_(ss) {}
operator ()(Object * obj) const277   void operator()(Object* obj) const EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_,
278                                                               Locks::heap_bitmap_lock_) {
279     DCHECK(obj != nullptr);
280     semi_space_->ScanObject(obj);
281   }
282  private:
283   SemiSpace* const semi_space_;
284 };
285 
286 // Used to verify that there's no references to the from-space.
287 class SemiSpaceVerifyNoFromSpaceReferencesVisitor {
288  public:
SemiSpaceVerifyNoFromSpaceReferencesVisitor(space::ContinuousMemMapAllocSpace * from_space)289   explicit SemiSpaceVerifyNoFromSpaceReferencesVisitor(space::ContinuousMemMapAllocSpace* from_space) :
290       from_space_(from_space) {}
291 
operator ()(Object * obj,MemberOffset offset,bool) const292   void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const
293       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) ALWAYS_INLINE {
294     mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
295     if (from_space_->HasAddress(ref)) {
296       Runtime::Current()->GetHeap()->DumpObject(LOG(INFO), obj);
297       LOG(FATAL) << ref << " found in from space";
298     }
299   }
300  private:
301   space::ContinuousMemMapAllocSpace* from_space_;
302 };
303 
VerifyNoFromSpaceReferences(Object * obj)304 void SemiSpace::VerifyNoFromSpaceReferences(Object* obj) {
305   DCHECK(!from_space_->HasAddress(obj)) << "Scanning object " << obj << " in from space";
306   SemiSpaceVerifyNoFromSpaceReferencesVisitor visitor(from_space_);
307   obj->VisitReferences<kMovingClasses>(visitor, VoidFunctor());
308 }
309 
310 class SemiSpaceVerifyNoFromSpaceReferencesObjectVisitor {
311  public:
SemiSpaceVerifyNoFromSpaceReferencesObjectVisitor(SemiSpace * ss)312   explicit SemiSpaceVerifyNoFromSpaceReferencesObjectVisitor(SemiSpace* ss) : semi_space_(ss) {}
operator ()(Object * obj) const313   void operator()(Object* obj) const
314       SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
315     DCHECK(obj != nullptr);
316     semi_space_->VerifyNoFromSpaceReferences(obj);
317   }
318  private:
319   SemiSpace* const semi_space_;
320 };
321 
MarkReachableObjects()322 void SemiSpace::MarkReachableObjects() {
323   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
324   {
325     TimingLogger::ScopedTiming t2("MarkStackAsLive", GetTimings());
326     accounting::ObjectStack* live_stack = heap_->GetLiveStack();
327     heap_->MarkAllocStackAsLive(live_stack);
328     live_stack->Reset();
329   }
330   for (auto& space : heap_->GetContinuousSpaces()) {
331     // If the space is immune then we need to mark the references to other spaces.
332     accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
333     if (table != nullptr) {
334       // TODO: Improve naming.
335       TimingLogger::ScopedTiming t2(
336           space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
337                                    "UpdateAndMarkImageModUnionTable",
338                                    GetTimings());
339       table->UpdateAndMarkReferences(MarkHeapReferenceCallback, this);
340       DCHECK(GetHeap()->FindRememberedSetFromSpace(space) == nullptr);
341     } else if (collect_from_space_only_ && space->GetLiveBitmap() != nullptr) {
342       // If the space has no mod union table (the non-moving space and main spaces when the bump
343       // pointer space only collection is enabled,) then we need to scan its live bitmap or dirty
344       // cards as roots (including the objects on the live stack which have just marked in the live
345       // bitmap above in MarkAllocStackAsLive().)
346       DCHECK(space == heap_->GetNonMovingSpace() || space == heap_->GetPrimaryFreeListSpace())
347           << "Space " << space->GetName() << " "
348           << "generational_=" << generational_ << " "
349           << "collect_from_space_only_=" << collect_from_space_only_;
350       accounting::RememberedSet* rem_set = GetHeap()->FindRememberedSetFromSpace(space);
351       CHECK_EQ(rem_set != nullptr, kUseRememberedSet);
352       if (rem_set != nullptr) {
353         TimingLogger::ScopedTiming t2("UpdateAndMarkRememberedSet", GetTimings());
354         rem_set->UpdateAndMarkReferences(MarkHeapReferenceCallback, DelayReferenceReferentCallback,
355                                          from_space_, this);
356         if (kIsDebugBuild) {
357           // Verify that there are no from-space references that
358           // remain in the space, that is, the remembered set (and the
359           // card table) didn't miss any from-space references in the
360           // space.
361           accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
362           SemiSpaceVerifyNoFromSpaceReferencesObjectVisitor visitor(this);
363           live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
364                                         reinterpret_cast<uintptr_t>(space->End()),
365                                         visitor);
366         }
367       } else {
368         TimingLogger::ScopedTiming t2("VisitLiveBits", GetTimings());
369         accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
370         SemiSpaceScanObjectVisitor visitor(this);
371         live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
372                                       reinterpret_cast<uintptr_t>(space->End()),
373                                       visitor);
374       }
375     }
376   }
377 
378   CHECK_EQ(is_large_object_space_immune_, collect_from_space_only_);
379   space::LargeObjectSpace* los = GetHeap()->GetLargeObjectsSpace();
380   if (is_large_object_space_immune_ && los != nullptr) {
381     TimingLogger::ScopedTiming t2("VisitLargeObjects", GetTimings());
382     DCHECK(collect_from_space_only_);
383     // Delay copying the live set to the marked set until here from
384     // BindBitmaps() as the large objects on the allocation stack may
385     // be newly added to the live set above in MarkAllocStackAsLive().
386     los->CopyLiveToMarked();
387 
388     // When the large object space is immune, we need to scan the
389     // large object space as roots as they contain references to their
390     // classes (primitive array classes) that could move though they
391     // don't contain any other references.
392     accounting::LargeObjectBitmap* large_live_bitmap = los->GetLiveBitmap();
393     SemiSpaceScanObjectVisitor visitor(this);
394     large_live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(los->Begin()),
395                                         reinterpret_cast<uintptr_t>(los->End()),
396                                         visitor);
397   }
398   // Recursively process the mark stack.
399   ProcessMarkStack();
400 }
401 
ReclaimPhase()402 void SemiSpace::ReclaimPhase() {
403   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
404   WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
405   // Reclaim unmarked objects.
406   Sweep(false);
407   // Swap the live and mark bitmaps for each space which we modified space. This is an
408   // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
409   // bitmaps.
410   SwapBitmaps();
411   // Unbind the live and mark bitmaps.
412   GetHeap()->UnBindBitmaps();
413   if (saved_bytes_ > 0) {
414     VLOG(heap) << "Avoided dirtying " << PrettySize(saved_bytes_);
415   }
416   if (generational_) {
417     // Record the end (top) of the to space so we can distinguish
418     // between objects that were allocated since the last GC and the
419     // older objects.
420     last_gc_to_space_end_ = to_space_->End();
421   }
422 }
423 
ResizeMarkStack(size_t new_size)424 void SemiSpace::ResizeMarkStack(size_t new_size) {
425   std::vector<StackReference<Object>> temp(mark_stack_->Begin(), mark_stack_->End());
426   CHECK_LE(mark_stack_->Size(), new_size);
427   mark_stack_->Resize(new_size);
428   for (auto& obj : temp) {
429     mark_stack_->PushBack(obj.AsMirrorPtr());
430   }
431 }
432 
MarkStackPush(Object * obj)433 inline void SemiSpace::MarkStackPush(Object* obj) {
434   if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
435     ResizeMarkStack(mark_stack_->Capacity() * 2);
436   }
437   // The object must be pushed on to the mark stack.
438   mark_stack_->PushBack(obj);
439 }
440 
CopyAvoidingDirtyingPages(void * dest,const void * src,size_t size)441 static inline size_t CopyAvoidingDirtyingPages(void* dest, const void* src, size_t size) {
442   if (LIKELY(size <= static_cast<size_t>(kPageSize))) {
443     // We will dirty the current page and somewhere in the middle of the next page. This means
444     // that the next object copied will also dirty that page.
445     // TODO: Worth considering the last object copied? We may end up dirtying one page which is
446     // not necessary per GC.
447     memcpy(dest, src, size);
448     return 0;
449   }
450   size_t saved_bytes = 0;
451   uint8_t* byte_dest = reinterpret_cast<uint8_t*>(dest);
452   if (kIsDebugBuild) {
453     for (size_t i = 0; i < size; ++i) {
454       CHECK_EQ(byte_dest[i], 0U);
455     }
456   }
457   // Process the start of the page. The page must already be dirty, don't bother with checking.
458   const uint8_t* byte_src = reinterpret_cast<const uint8_t*>(src);
459   const uint8_t* limit = byte_src + size;
460   size_t page_remain = AlignUp(byte_dest, kPageSize) - byte_dest;
461   // Copy the bytes until the start of the next page.
462   memcpy(dest, src, page_remain);
463   byte_src += page_remain;
464   byte_dest += page_remain;
465   DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(byte_dest), kPageSize);
466   DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(byte_dest), sizeof(uintptr_t));
467   DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(byte_src), sizeof(uintptr_t));
468   while (byte_src + kPageSize < limit) {
469     bool all_zero = true;
470     uintptr_t* word_dest = reinterpret_cast<uintptr_t*>(byte_dest);
471     const uintptr_t* word_src = reinterpret_cast<const uintptr_t*>(byte_src);
472     for (size_t i = 0; i < kPageSize / sizeof(*word_src); ++i) {
473       // Assumes the destination of the copy is all zeros.
474       if (word_src[i] != 0) {
475         all_zero = false;
476         word_dest[i] = word_src[i];
477       }
478     }
479     if (all_zero) {
480       // Avoided copying into the page since it was all zeros.
481       saved_bytes += kPageSize;
482     }
483     byte_src += kPageSize;
484     byte_dest += kPageSize;
485   }
486   // Handle the part of the page at the end.
487   memcpy(byte_dest, byte_src, limit - byte_src);
488   return saved_bytes;
489 }
490 
MarkNonForwardedObject(mirror::Object * obj)491 mirror::Object* SemiSpace::MarkNonForwardedObject(mirror::Object* obj) {
492   const size_t object_size = obj->SizeOf();
493   size_t bytes_allocated, dummy;
494   mirror::Object* forward_address = nullptr;
495   if (generational_ && reinterpret_cast<uint8_t*>(obj) < last_gc_to_space_end_) {
496     // If it's allocated before the last GC (older), move
497     // (pseudo-promote) it to the main free list space (as sort
498     // of an old generation.)
499     forward_address = promo_dest_space_->AllocThreadUnsafe(self_, object_size, &bytes_allocated,
500                                                            nullptr, &dummy);
501     if (UNLIKELY(forward_address == nullptr)) {
502       // If out of space, fall back to the to-space.
503       forward_address = to_space_->AllocThreadUnsafe(self_, object_size, &bytes_allocated, nullptr,
504                                                      &dummy);
505       // No logic for marking the bitmap, so it must be null.
506       DCHECK(to_space_live_bitmap_ == nullptr);
507     } else {
508       bytes_promoted_ += bytes_allocated;
509       // Dirty the card at the destionation as it may contain
510       // references (including the class pointer) to the bump pointer
511       // space.
512       GetHeap()->WriteBarrierEveryFieldOf(forward_address);
513       // Handle the bitmaps marking.
514       accounting::ContinuousSpaceBitmap* live_bitmap = promo_dest_space_->GetLiveBitmap();
515       DCHECK(live_bitmap != nullptr);
516       accounting::ContinuousSpaceBitmap* mark_bitmap = promo_dest_space_->GetMarkBitmap();
517       DCHECK(mark_bitmap != nullptr);
518       DCHECK(!live_bitmap->Test(forward_address));
519       if (collect_from_space_only_) {
520         // If collecting the bump pointer spaces only, live_bitmap == mark_bitmap.
521         DCHECK_EQ(live_bitmap, mark_bitmap);
522 
523         // If a bump pointer space only collection, delay the live
524         // bitmap marking of the promoted object until it's popped off
525         // the mark stack (ProcessMarkStack()). The rationale: we may
526         // be in the middle of scanning the objects in the promo
527         // destination space for
528         // non-moving-space-to-bump-pointer-space references by
529         // iterating over the marked bits of the live bitmap
530         // (MarkReachableObjects()). If we don't delay it (and instead
531         // mark the promoted object here), the above promo destination
532         // space scan could encounter the just-promoted object and
533         // forward the references in the promoted object's fields even
534         // through it is pushed onto the mark stack. If this happens,
535         // the promoted object would be in an inconsistent state, that
536         // is, it's on the mark stack (gray) but its fields are
537         // already forwarded (black), which would cause a
538         // DCHECK(!to_space_->HasAddress(obj)) failure below.
539       } else {
540         // Mark forward_address on the live bit map.
541         live_bitmap->Set(forward_address);
542         // Mark forward_address on the mark bit map.
543         DCHECK(!mark_bitmap->Test(forward_address));
544         mark_bitmap->Set(forward_address);
545       }
546     }
547   } else {
548     // If it's allocated after the last GC (younger), copy it to the to-space.
549     forward_address = to_space_->AllocThreadUnsafe(self_, object_size, &bytes_allocated, nullptr,
550                                                    &dummy);
551     if (forward_address != nullptr && to_space_live_bitmap_ != nullptr) {
552       to_space_live_bitmap_->Set(forward_address);
553     }
554   }
555   // If it's still null, attempt to use the fallback space.
556   if (UNLIKELY(forward_address == nullptr)) {
557     forward_address = fallback_space_->AllocThreadUnsafe(self_, object_size, &bytes_allocated,
558                                                          nullptr, &dummy);
559     CHECK(forward_address != nullptr) << "Out of memory in the to-space and fallback space.";
560     accounting::ContinuousSpaceBitmap* bitmap = fallback_space_->GetLiveBitmap();
561     if (bitmap != nullptr) {
562       bitmap->Set(forward_address);
563     }
564   }
565   ++objects_moved_;
566   bytes_moved_ += bytes_allocated;
567   // Copy over the object and add it to the mark stack since we still need to update its
568   // references.
569   saved_bytes_ +=
570       CopyAvoidingDirtyingPages(reinterpret_cast<void*>(forward_address), obj, object_size);
571   if (kUseBakerOrBrooksReadBarrier) {
572     obj->AssertReadBarrierPointer();
573     if (kUseBrooksReadBarrier) {
574       DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
575       forward_address->SetReadBarrierPointer(forward_address);
576     }
577     forward_address->AssertReadBarrierPointer();
578   }
579   DCHECK(to_space_->HasAddress(forward_address) ||
580          fallback_space_->HasAddress(forward_address) ||
581          (generational_ && promo_dest_space_->HasAddress(forward_address)))
582       << forward_address << "\n" << GetHeap()->DumpSpaces();
583   return forward_address;
584 }
585 
ProcessMarkStackCallback(void * arg)586 void SemiSpace::ProcessMarkStackCallback(void* arg) {
587   reinterpret_cast<SemiSpace*>(arg)->ProcessMarkStack();
588 }
589 
MarkObjectCallback(mirror::Object * root,void * arg)590 mirror::Object* SemiSpace::MarkObjectCallback(mirror::Object* root, void* arg) {
591   auto ref = StackReference<mirror::Object>::FromMirrorPtr(root);
592   reinterpret_cast<SemiSpace*>(arg)->MarkObject(&ref);
593   return ref.AsMirrorPtr();
594 }
595 
MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object> * obj_ptr,void * arg)596 void SemiSpace::MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>* obj_ptr,
597                                           void* arg) {
598   reinterpret_cast<SemiSpace*>(arg)->MarkObject(obj_ptr);
599 }
600 
DelayReferenceReferentCallback(mirror::Class * klass,mirror::Reference * ref,void * arg)601 void SemiSpace::DelayReferenceReferentCallback(mirror::Class* klass, mirror::Reference* ref,
602                                                void* arg) {
603   reinterpret_cast<SemiSpace*>(arg)->DelayReferenceReferent(klass, ref);
604 }
605 
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)606 void SemiSpace::VisitRoots(mirror::Object*** roots, size_t count,
607                            const RootInfo& info ATTRIBUTE_UNUSED) {
608   for (size_t i = 0; i < count; ++i) {
609     auto* root = roots[i];
610     auto ref = StackReference<mirror::Object>::FromMirrorPtr(*root);
611     MarkObject(&ref);
612     if (*root != ref.AsMirrorPtr()) {
613       *root = ref.AsMirrorPtr();
614     }
615   }
616 }
617 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)618 void SemiSpace::VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
619                            const RootInfo& info ATTRIBUTE_UNUSED) {
620   for (size_t i = 0; i < count; ++i) {
621     MarkObject(roots[i]);
622   }
623 }
624 
625 // Marks all objects in the root set.
MarkRoots()626 void SemiSpace::MarkRoots() {
627   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
628   Runtime::Current()->VisitRoots(this);
629 }
630 
HeapReferenceMarkedCallback(mirror::HeapReference<mirror::Object> * object,void * arg)631 bool SemiSpace::HeapReferenceMarkedCallback(mirror::HeapReference<mirror::Object>* object,
632                                             void* arg) {
633   mirror::Object* obj = object->AsMirrorPtr();
634   mirror::Object* new_obj =
635       reinterpret_cast<SemiSpace*>(arg)->GetMarkedForwardAddress(obj);
636   if (new_obj == nullptr) {
637     return false;
638   }
639   if (new_obj != obj) {
640     // Write barrier is not necessary since it still points to the same object, just at a different
641     // address.
642     object->Assign(new_obj);
643   }
644   return true;
645 }
646 
MarkedForwardingAddressCallback(mirror::Object * object,void * arg)647 mirror::Object* SemiSpace::MarkedForwardingAddressCallback(mirror::Object* object, void* arg) {
648   return reinterpret_cast<SemiSpace*>(arg)->GetMarkedForwardAddress(object);
649 }
650 
SweepSystemWeaks()651 void SemiSpace::SweepSystemWeaks() {
652   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
653   Runtime::Current()->SweepSystemWeaks(MarkedForwardingAddressCallback, this);
654 }
655 
ShouldSweepSpace(space::ContinuousSpace * space) const656 bool SemiSpace::ShouldSweepSpace(space::ContinuousSpace* space) const {
657   return space != from_space_ && space != to_space_;
658 }
659 
Sweep(bool swap_bitmaps)660 void SemiSpace::Sweep(bool swap_bitmaps) {
661   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
662   DCHECK(mark_stack_->IsEmpty());
663   for (const auto& space : GetHeap()->GetContinuousSpaces()) {
664     if (space->IsContinuousMemMapAllocSpace()) {
665       space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
666       if (!ShouldSweepSpace(alloc_space)) {
667         continue;
668       }
669       TimingLogger::ScopedTiming split(
670           alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
671       RecordFree(alloc_space->Sweep(swap_bitmaps));
672     }
673   }
674   if (!is_large_object_space_immune_) {
675     SweepLargeObjects(swap_bitmaps);
676   }
677 }
678 
SweepLargeObjects(bool swap_bitmaps)679 void SemiSpace::SweepLargeObjects(bool swap_bitmaps) {
680   DCHECK(!is_large_object_space_immune_);
681   space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
682   if (los != nullptr) {
683     TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
684     RecordFreeLOS(los->Sweep(swap_bitmaps));
685   }
686 }
687 
688 // Process the "referent" field in a java.lang.ref.Reference.  If the referent has not yet been
689 // marked, put it on the appropriate list in the heap for later processing.
DelayReferenceReferent(mirror::Class * klass,mirror::Reference * reference)690 void SemiSpace::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* reference) {
691   heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference,
692                                                          &HeapReferenceMarkedCallback, this);
693 }
694 
695 class SemiSpaceMarkObjectVisitor {
696  public:
SemiSpaceMarkObjectVisitor(SemiSpace * collector)697   explicit SemiSpaceMarkObjectVisitor(SemiSpace* collector) : collector_(collector) {
698   }
699 
operator ()(Object * obj,MemberOffset offset,bool) const700   void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const ALWAYS_INLINE
701       EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
702     // Object was already verified when we scanned it.
703     collector_->MarkObject(obj->GetFieldObjectReferenceAddr<kVerifyNone>(offset));
704   }
705 
operator ()(mirror::Class * klass,mirror::Reference * ref) const706   void operator()(mirror::Class* klass, mirror::Reference* ref) const
707       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
708       EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
709     collector_->DelayReferenceReferent(klass, ref);
710   }
711 
712  private:
713   SemiSpace* const collector_;
714 };
715 
716 // Visit all of the references of an object and update.
ScanObject(Object * obj)717 void SemiSpace::ScanObject(Object* obj) {
718   DCHECK(!from_space_->HasAddress(obj)) << "Scanning object " << obj << " in from space";
719   SemiSpaceMarkObjectVisitor visitor(this);
720   obj->VisitReferences<kMovingClasses>(visitor, visitor);
721 }
722 
723 // Scan anything that's on the mark stack.
ProcessMarkStack()724 void SemiSpace::ProcessMarkStack() {
725   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
726   accounting::ContinuousSpaceBitmap* live_bitmap = nullptr;
727   if (collect_from_space_only_) {
728     // If a bump pointer space only collection (and the promotion is
729     // enabled,) we delay the live-bitmap marking of promoted objects
730     // from MarkObject() until this function.
731     live_bitmap = promo_dest_space_->GetLiveBitmap();
732     DCHECK(live_bitmap != nullptr);
733     accounting::ContinuousSpaceBitmap* mark_bitmap = promo_dest_space_->GetMarkBitmap();
734     DCHECK(mark_bitmap != nullptr);
735     DCHECK_EQ(live_bitmap, mark_bitmap);
736   }
737   while (!mark_stack_->IsEmpty()) {
738     Object* obj = mark_stack_->PopBack();
739     if (collect_from_space_only_ && promo_dest_space_->HasAddress(obj)) {
740       // obj has just been promoted. Mark the live bitmap for it,
741       // which is delayed from MarkObject().
742       DCHECK(!live_bitmap->Test(obj));
743       live_bitmap->Set(obj);
744     }
745     ScanObject(obj);
746   }
747 }
748 
GetMarkedForwardAddress(mirror::Object * obj) const749 inline Object* SemiSpace::GetMarkedForwardAddress(mirror::Object* obj) const
750     SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
751   // All immune objects are assumed marked.
752   if (from_space_->HasAddress(obj)) {
753     // Returns either the forwarding address or null.
754     return GetForwardingAddressInFromSpace(obj);
755   } else if (collect_from_space_only_ || immune_region_.ContainsObject(obj) ||
756              to_space_->HasAddress(obj)) {
757     return obj;  // Already forwarded, must be marked.
758   }
759   return mark_bitmap_->Test(obj) ? obj : nullptr;
760 }
761 
SetToSpace(space::ContinuousMemMapAllocSpace * to_space)762 void SemiSpace::SetToSpace(space::ContinuousMemMapAllocSpace* to_space) {
763   DCHECK(to_space != nullptr);
764   to_space_ = to_space;
765 }
766 
SetFromSpace(space::ContinuousMemMapAllocSpace * from_space)767 void SemiSpace::SetFromSpace(space::ContinuousMemMapAllocSpace* from_space) {
768   DCHECK(from_space != nullptr);
769   from_space_ = from_space;
770 }
771 
FinishPhase()772 void SemiSpace::FinishPhase() {
773   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
774   if (kProtectFromSpace && from_space_->IsRosAllocSpace()) {
775     VLOG(heap) << "Protecting from_space_ with PROT_NONE : " << *from_space_;
776     from_space_->GetMemMap()->Protect(PROT_NONE);
777   }
778   // Null the "to" and "from" spaces since compacting from one to the other isn't valid until
779   // further action is done by the heap.
780   to_space_ = nullptr;
781   from_space_ = nullptr;
782   CHECK(mark_stack_->IsEmpty());
783   mark_stack_->Reset();
784   space::LargeObjectSpace* los = GetHeap()->GetLargeObjectsSpace();
785   if (generational_) {
786     // Decide whether to do a whole heap collection or a bump pointer
787     // only space collection at the next collection by updating
788     // collect_from_space_only_.
789     if (collect_from_space_only_) {
790       // Disable collect_from_space_only_ if the bytes promoted since the
791       // last whole heap collection or the large object bytes
792       // allocated exceeds a threshold.
793       bytes_promoted_since_last_whole_heap_collection_ += bytes_promoted_;
794       bool bytes_promoted_threshold_exceeded =
795           bytes_promoted_since_last_whole_heap_collection_ >= kBytesPromotedThreshold;
796       uint64_t current_los_bytes_allocated = los != nullptr ? los->GetBytesAllocated() : 0U;
797       uint64_t last_los_bytes_allocated =
798           large_object_bytes_allocated_at_last_whole_heap_collection_;
799       bool large_object_bytes_threshold_exceeded =
800           current_los_bytes_allocated >=
801           last_los_bytes_allocated + kLargeObjectBytesAllocatedThreshold;
802       if (bytes_promoted_threshold_exceeded || large_object_bytes_threshold_exceeded) {
803         collect_from_space_only_ = false;
804       }
805     } else {
806       // Reset the counters.
807       bytes_promoted_since_last_whole_heap_collection_ = bytes_promoted_;
808       large_object_bytes_allocated_at_last_whole_heap_collection_ =
809           los != nullptr ? los->GetBytesAllocated() : 0U;
810       collect_from_space_only_ = true;
811     }
812   }
813   // Clear all of the spaces' mark bitmaps.
814   WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
815   heap_->ClearMarkedObjects();
816 }
817 
RevokeAllThreadLocalBuffers()818 void SemiSpace::RevokeAllThreadLocalBuffers() {
819   TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
820   GetHeap()->RevokeAllThreadLocalBuffers();
821 }
822 
823 }  // namespace collector
824 }  // namespace gc
825 }  // namespace art
826