mark_sweep.cc revision 8118781ebc9659f806716c451bdb3fe9b77ae32b
1/*
2 * Copyright (C) 2011 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 "mark_sweep.h"
18
19#include <atomic>
20#include <functional>
21#include <numeric>
22#include <climits>
23#include <vector>
24
25#define ATRACE_TAG ATRACE_TAG_DALVIK
26#include "cutils/trace.h"
27
28#include "base/bounded_fifo.h"
29#include "base/logging.h"
30#include "base/macros.h"
31#include "base/mutex-inl.h"
32#include "base/time_utils.h"
33#include "base/timing_logger.h"
34#include "gc/accounting/card_table-inl.h"
35#include "gc/accounting/heap_bitmap-inl.h"
36#include "gc/accounting/mod_union_table.h"
37#include "gc/accounting/space_bitmap-inl.h"
38#include "gc/heap.h"
39#include "gc/reference_processor.h"
40#include "gc/space/large_object_space.h"
41#include "gc/space/space-inl.h"
42#include "mark_sweep-inl.h"
43#include "mirror/object-inl.h"
44#include "runtime.h"
45#include "scoped_thread_state_change.h"
46#include "thread-inl.h"
47#include "thread_list.h"
48
49namespace art {
50namespace gc {
51namespace collector {
52
53// Performance options.
54static constexpr bool kUseRecursiveMark = false;
55static constexpr bool kUseMarkStackPrefetch = true;
56static constexpr size_t kSweepArrayChunkFreeSize = 1024;
57static constexpr bool kPreCleanCards = true;
58
59// Parallelism options.
60static constexpr bool kParallelCardScan = true;
61static constexpr bool kParallelRecursiveMark = true;
62// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
63// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
64// having this can add overhead in ProcessReferences since we may end up doing many calls of
65// ProcessMarkStack with very small mark stacks.
66static constexpr size_t kMinimumParallelMarkStackSize = 128;
67static constexpr bool kParallelProcessMarkStack = true;
68
69// Profiling and information flags.
70static constexpr bool kProfileLargeObjects = false;
71static constexpr bool kMeasureOverhead = false;
72static constexpr bool kCountTasks = false;
73static constexpr bool kCountJavaLangRefs = false;
74static constexpr bool kCountMarkedObjects = false;
75
76// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
77static constexpr bool kCheckLocks = kDebugLocking;
78static constexpr bool kVerifyRootsMarked = kIsDebugBuild;
79
80// If true, revoke the rosalloc thread-local buffers at the
81// checkpoint, as opposed to during the pause.
82static constexpr bool kRevokeRosAllocThreadLocalBuffersAtCheckpoint = true;
83
84void MarkSweep::BindBitmaps() {
85  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
86  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
87  // Mark all of the spaces we never collect as immune.
88  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
89    if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
90      CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
91    }
92  }
93}
94
95MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
96    : GarbageCollector(heap,
97                       name_prefix +
98                       (is_concurrent ? "concurrent mark sweep": "mark sweep")),
99      current_space_bitmap_(nullptr), mark_bitmap_(nullptr), mark_stack_(nullptr),
100      gc_barrier_(new Barrier(0)),
101      mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
102      is_concurrent_(is_concurrent), live_stack_freeze_size_(0) {
103  std::string error_msg;
104  MemMap* mem_map = MemMap::MapAnonymous(
105      "mark sweep sweep array free buffer", nullptr,
106      RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
107      PROT_READ | PROT_WRITE, false, false, &error_msg);
108  CHECK(mem_map != nullptr) << "Couldn't allocate sweep array free buffer: " << error_msg;
109  sweep_array_free_buffer_mem_map_.reset(mem_map);
110}
111
112void MarkSweep::InitializePhase() {
113  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
114  mark_stack_ = heap_->GetMarkStack();
115  DCHECK(mark_stack_ != nullptr);
116  immune_region_.Reset();
117  class_count_.StoreRelaxed(0);
118  array_count_.StoreRelaxed(0);
119  other_count_.StoreRelaxed(0);
120  large_object_test_.StoreRelaxed(0);
121  large_object_mark_.StoreRelaxed(0);
122  overhead_time_ .StoreRelaxed(0);
123  work_chunks_created_.StoreRelaxed(0);
124  work_chunks_deleted_.StoreRelaxed(0);
125  reference_count_.StoreRelaxed(0);
126  mark_null_count_.StoreRelaxed(0);
127  mark_immune_count_.StoreRelaxed(0);
128  mark_fastpath_count_.StoreRelaxed(0);
129  mark_slowpath_count_.StoreRelaxed(0);
130  {
131    // TODO: I don't think we should need heap bitmap lock to Get the mark bitmap.
132    ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
133    mark_bitmap_ = heap_->GetMarkBitmap();
134  }
135  if (!GetCurrentIteration()->GetClearSoftReferences()) {
136    // Always clear soft references if a non-sticky collection.
137    GetCurrentIteration()->SetClearSoftReferences(GetGcType() != collector::kGcTypeSticky);
138  }
139}
140
141void MarkSweep::RunPhases() {
142  Thread* self = Thread::Current();
143  InitializePhase();
144  Locks::mutator_lock_->AssertNotHeld(self);
145  if (IsConcurrent()) {
146    GetHeap()->PreGcVerification(this);
147    {
148      ReaderMutexLock mu(self, *Locks::mutator_lock_);
149      MarkingPhase();
150    }
151    ScopedPause pause(this);
152    GetHeap()->PrePauseRosAllocVerification(this);
153    PausePhase();
154    RevokeAllThreadLocalBuffers();
155  } else {
156    ScopedPause pause(this);
157    GetHeap()->PreGcVerificationPaused(this);
158    MarkingPhase();
159    GetHeap()->PrePauseRosAllocVerification(this);
160    PausePhase();
161    RevokeAllThreadLocalBuffers();
162  }
163  {
164    // Sweeping always done concurrently, even for non concurrent mark sweep.
165    ReaderMutexLock mu(self, *Locks::mutator_lock_);
166    ReclaimPhase();
167  }
168  GetHeap()->PostGcVerification(this);
169  FinishPhase();
170}
171
172void MarkSweep::ProcessReferences(Thread* self) {
173  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
174  GetHeap()->GetReferenceProcessor()->ProcessReferences(
175      true, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
176}
177
178void MarkSweep::PausePhase() {
179  TimingLogger::ScopedTiming t("(Paused)PausePhase", GetTimings());
180  Thread* self = Thread::Current();
181  Locks::mutator_lock_->AssertExclusiveHeld(self);
182  if (IsConcurrent()) {
183    // Handle the dirty objects if we are a concurrent GC.
184    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
185    // Re-mark root set.
186    ReMarkRoots();
187    // Scan dirty objects, this is only required if we are not doing concurrent GC.
188    RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
189  }
190  {
191    TimingLogger::ScopedTiming t2("SwapStacks", GetTimings());
192    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
193    heap_->SwapStacks(self);
194    live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
195    // Need to revoke all the thread local allocation stacks since we just swapped the allocation
196    // stacks and don't want anybody to allocate into the live stack.
197    RevokeAllThreadLocalAllocationStacks(self);
198  }
199  heap_->PreSweepingGcVerification(this);
200  // Disallow new system weaks to prevent a race which occurs when someone adds a new system
201  // weak before we sweep them. Since this new system weak may not be marked, the GC may
202  // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
203  // reference to a string that is about to be swept.
204  Runtime::Current()->DisallowNewSystemWeaks();
205  // Enable the reference processing slow path, needs to be done with mutators paused since there
206  // is no lock in the GetReferent fast path.
207  GetHeap()->GetReferenceProcessor()->EnableSlowPath();
208}
209
210void MarkSweep::PreCleanCards() {
211  // Don't do this for non concurrent GCs since they don't have any dirty cards.
212  if (kPreCleanCards && IsConcurrent()) {
213    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
214    Thread* self = Thread::Current();
215    CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
216    // Process dirty cards and add dirty cards to mod union tables, also ages cards.
217    heap_->ProcessCards(GetTimings(), false, true, false);
218    // The checkpoint root marking is required to avoid a race condition which occurs if the
219    // following happens during a reference write:
220    // 1. mutator dirties the card (write barrier)
221    // 2. GC ages the card (the above ProcessCards call)
222    // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
223    // 4. mutator writes the value (corresponding to the write barrier in 1.)
224    // This causes the GC to age the card but not necessarily mark the reference which the mutator
225    // wrote into the object stored in the card.
226    // Having the checkpoint fixes this issue since it ensures that the card mark and the
227    // reference write are visible to the GC before the card is scanned (this is due to locks being
228    // acquired / released in the checkpoint code).
229    // The other roots are also marked to help reduce the pause.
230    MarkRootsCheckpoint(self, false);
231    MarkNonThreadRoots();
232    MarkConcurrentRoots(
233        static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
234    // Process the newly aged cards.
235    RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
236    // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
237    // in the next GC.
238  }
239}
240
241void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
242  if (kUseThreadLocalAllocationStack) {
243    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
244    Locks::mutator_lock_->AssertExclusiveHeld(self);
245    heap_->RevokeAllThreadLocalAllocationStacks(self);
246  }
247}
248
249void MarkSweep::MarkingPhase() {
250  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
251  Thread* self = Thread::Current();
252  BindBitmaps();
253  FindDefaultSpaceBitmap();
254  // Process dirty cards and add dirty cards to mod union tables.
255  // If the GC type is non sticky, then we just clear the cards instead of ageing them.
256  heap_->ProcessCards(GetTimings(), false, true, GetGcType() != kGcTypeSticky);
257  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
258  MarkRoots(self);
259  MarkReachableObjects();
260  // Pre-clean dirtied cards to reduce pauses.
261  PreCleanCards();
262}
263
264void MarkSweep::UpdateAndMarkModUnion() {
265  for (const auto& space : heap_->GetContinuousSpaces()) {
266    if (immune_region_.ContainsSpace(space)) {
267      const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
268          "UpdateAndMarkImageModUnionTable";
269      TimingLogger::ScopedTiming t(name, GetTimings());
270      accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
271      CHECK(mod_union_table != nullptr);
272      mod_union_table->UpdateAndMarkReferences(this);
273    }
274  }
275}
276
277void MarkSweep::MarkReachableObjects() {
278  UpdateAndMarkModUnion();
279  // Recursively mark all the non-image bits set in the mark bitmap.
280  RecursiveMark();
281}
282
283void MarkSweep::ReclaimPhase() {
284  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
285  Thread* self = Thread::Current();
286  // Process the references concurrently.
287  ProcessReferences(self);
288  SweepSystemWeaks(self);
289  Runtime::Current()->AllowNewSystemWeaks();
290  {
291    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
292    GetHeap()->RecordFreeRevoke();
293    // Reclaim unmarked objects.
294    Sweep(false);
295    // Swap the live and mark bitmaps for each space which we modified space. This is an
296    // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
297    // bitmaps.
298    SwapBitmaps();
299    // Unbind the live and mark bitmaps.
300    GetHeap()->UnBindBitmaps();
301  }
302}
303
304void MarkSweep::FindDefaultSpaceBitmap() {
305  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
306  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
307    accounting::ContinuousSpaceBitmap* bitmap = space->GetMarkBitmap();
308    // We want to have the main space instead of non moving if possible.
309    if (bitmap != nullptr &&
310        space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
311      current_space_bitmap_ = bitmap;
312      // If we are not the non moving space exit the loop early since this will be good enough.
313      if (space != heap_->GetNonMovingSpace()) {
314        break;
315      }
316    }
317  }
318  CHECK(current_space_bitmap_ != nullptr) << "Could not find a default mark bitmap\n"
319      << heap_->DumpSpaces();
320}
321
322void MarkSweep::ExpandMarkStack() {
323  ResizeMarkStack(mark_stack_->Capacity() * 2);
324}
325
326void MarkSweep::ResizeMarkStack(size_t new_size) {
327  // Rare case, no need to have Thread::Current be a parameter.
328  if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
329    // Someone else acquired the lock and expanded the mark stack before us.
330    return;
331  }
332  std::vector<StackReference<mirror::Object>> temp(mark_stack_->Begin(), mark_stack_->End());
333  CHECK_LE(mark_stack_->Size(), new_size);
334  mark_stack_->Resize(new_size);
335  for (auto& obj : temp) {
336    mark_stack_->PushBack(obj.AsMirrorPtr());
337  }
338}
339
340inline void MarkSweep::MarkObjectNonNullParallel(mirror::Object* obj) {
341  DCHECK(obj != nullptr);
342  if (MarkObjectParallel(obj)) {
343    MutexLock mu(Thread::Current(), mark_stack_lock_);
344    if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
345      ExpandMarkStack();
346    }
347    // The object must be pushed on to the mark stack.
348    mark_stack_->PushBack(obj);
349  }
350}
351
352bool MarkSweep::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* ref) {
353  return IsMarked(ref->AsMirrorPtr());
354}
355
356class MarkSweepMarkObjectSlowPath {
357 public:
358  explicit MarkSweepMarkObjectSlowPath(MarkSweep* mark_sweep, mirror::Object* holder = nullptr,
359                                       MemberOffset offset = MemberOffset(0))
360      : mark_sweep_(mark_sweep), holder_(holder), offset_(offset) {
361  }
362
363  void operator()(const mirror::Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
364    if (kProfileLargeObjects) {
365      // TODO: Differentiate between marking and testing somehow.
366      ++mark_sweep_->large_object_test_;
367      ++mark_sweep_->large_object_mark_;
368    }
369    space::LargeObjectSpace* large_object_space = mark_sweep_->GetHeap()->GetLargeObjectsSpace();
370    if (UNLIKELY(obj == nullptr || !IsAligned<kPageSize>(obj) ||
371                 (kIsDebugBuild && large_object_space != nullptr &&
372                     !large_object_space->Contains(obj)))) {
373      LOG(INTERNAL_FATAL) << "Tried to mark " << obj << " not contained by any spaces";
374      if (holder_ != nullptr) {
375        size_t holder_size = holder_->SizeOf();
376        ArtField* field = holder_->FindFieldByOffset(offset_);
377        LOG(INTERNAL_FATAL) << "Field info: "
378                            << " holder=" << holder_
379                            << " holder is "
380                            << (mark_sweep_->GetHeap()->IsLiveObjectLocked(holder_)
381                                ? "alive" : "dead")
382                            << " holder_size=" << holder_size
383                            << " holder_type=" << PrettyTypeOf(holder_)
384                            << " offset=" << offset_.Uint32Value()
385                            << " field=" << (field != nullptr ? field->GetName() : "nullptr")
386                            << " field_type="
387                            << (field != nullptr ? field->GetTypeDescriptor() : "")
388                            << " first_ref_field_offset="
389                            << (holder_->IsClass()
390                                ? holder_->AsClass()->GetFirstReferenceStaticFieldOffset(
391                                    sizeof(void*))
392                                : holder_->GetClass()->GetFirstReferenceInstanceFieldOffset())
393                            << " num_of_ref_fields="
394                            << (holder_->IsClass()
395                                ? holder_->AsClass()->NumReferenceStaticFields()
396                                : holder_->GetClass()->NumReferenceInstanceFields())
397                            << "\n";
398        // Print the memory content of the holder.
399        for (size_t i = 0; i < holder_size / sizeof(uint32_t); ++i) {
400          uint32_t* p = reinterpret_cast<uint32_t*>(holder_);
401          LOG(INTERNAL_FATAL) << &p[i] << ": " << "holder+" << (i * sizeof(uint32_t)) << " = "
402                              << std::hex << p[i];
403        }
404      }
405      PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
406      MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
407      {
408        LOG(INTERNAL_FATAL) << "Attempting see if it's a bad root";
409        Thread* self = Thread::Current();
410        if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
411          mark_sweep_->VerifyRoots();
412        } else {
413          const bool heap_bitmap_exclusive_locked =
414              Locks::heap_bitmap_lock_->IsExclusiveHeld(self);
415          if (heap_bitmap_exclusive_locked) {
416            Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
417          }
418          Locks::mutator_lock_->SharedUnlock(self);
419          ThreadList* tl = Runtime::Current()->GetThreadList();
420          tl->SuspendAll(__FUNCTION__);
421          mark_sweep_->VerifyRoots();
422          tl->ResumeAll();
423          Locks::mutator_lock_->SharedLock(self);
424          if (heap_bitmap_exclusive_locked) {
425            Locks::heap_bitmap_lock_->ExclusiveLock(self);
426          }
427        }
428      }
429      LOG(FATAL) << "Can't mark invalid object";
430    }
431  }
432
433 private:
434  MarkSweep* const mark_sweep_;
435  mirror::Object* const holder_;
436  MemberOffset offset_;
437};
438
439inline void MarkSweep::MarkObjectNonNull(mirror::Object* obj, mirror::Object* holder,
440                                         MemberOffset offset) {
441  DCHECK(obj != nullptr);
442  if (kUseBakerOrBrooksReadBarrier) {
443    // Verify all the objects have the correct pointer installed.
444    obj->AssertReadBarrierPointer();
445  }
446  if (immune_region_.ContainsObject(obj)) {
447    if (kCountMarkedObjects) {
448      ++mark_immune_count_;
449    }
450    DCHECK(mark_bitmap_->Test(obj));
451  } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
452    if (kCountMarkedObjects) {
453      ++mark_fastpath_count_;
454    }
455    if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
456      PushOnMarkStack(obj);  // This object was not previously marked.
457    }
458  } else {
459    if (kCountMarkedObjects) {
460      ++mark_slowpath_count_;
461    }
462    MarkSweepMarkObjectSlowPath visitor(this, holder, offset);
463    // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
464    // will check again.
465    if (!mark_bitmap_->Set(obj, visitor)) {
466      PushOnMarkStack(obj);  // Was not already marked, push.
467    }
468  }
469}
470
471inline void MarkSweep::PushOnMarkStack(mirror::Object* obj) {
472  if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
473    // Lock is not needed but is here anyways to please annotalysis.
474    MutexLock mu(Thread::Current(), mark_stack_lock_);
475    ExpandMarkStack();
476  }
477  // The object must be pushed on to the mark stack.
478  mark_stack_->PushBack(obj);
479}
480
481inline bool MarkSweep::MarkObjectParallel(mirror::Object* obj) {
482  DCHECK(obj != nullptr);
483  if (kUseBakerOrBrooksReadBarrier) {
484    // Verify all the objects have the correct pointer installed.
485    obj->AssertReadBarrierPointer();
486  }
487  if (immune_region_.ContainsObject(obj)) {
488    DCHECK(IsMarked(obj) != nullptr);
489    return false;
490  }
491  // Try to take advantage of locality of references within a space, failing this find the space
492  // the hard way.
493  accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
494  if (LIKELY(object_bitmap->HasAddress(obj))) {
495    return !object_bitmap->AtomicTestAndSet(obj);
496  }
497  MarkSweepMarkObjectSlowPath visitor(this);
498  return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
499}
500
501void MarkSweep::MarkHeapReference(mirror::HeapReference<mirror::Object>* ref) {
502  MarkObject(ref->AsMirrorPtr(), nullptr, MemberOffset(0));
503}
504
505// Used to mark objects when processing the mark stack. If an object is null, it is not marked.
506inline void MarkSweep::MarkObject(mirror::Object* obj, mirror::Object* holder,
507                                  MemberOffset offset) {
508  if (obj != nullptr) {
509    MarkObjectNonNull(obj, holder, offset);
510  } else if (kCountMarkedObjects) {
511    ++mark_null_count_;
512  }
513}
514
515class VerifyRootMarkedVisitor : public SingleRootVisitor {
516 public:
517  explicit VerifyRootMarkedVisitor(MarkSweep* collector) : collector_(collector) { }
518
519  void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
520      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
521    CHECK(collector_->IsMarked(root) != nullptr) << info.ToString();
522  }
523
524 private:
525  MarkSweep* const collector_;
526};
527
528void MarkSweep::VisitRoots(mirror::Object*** roots, size_t count,
529                           const RootInfo& info ATTRIBUTE_UNUSED) {
530  for (size_t i = 0; i < count; ++i) {
531    MarkObjectNonNull(*roots[i]);
532  }
533}
534
535void MarkSweep::VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
536                           const RootInfo& info ATTRIBUTE_UNUSED) {
537  for (size_t i = 0; i < count; ++i) {
538    MarkObjectNonNull(roots[i]->AsMirrorPtr());
539  }
540}
541
542class VerifyRootVisitor : public SingleRootVisitor {
543 public:
544  void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
545      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
546    // See if the root is on any space bitmap.
547    auto* heap = Runtime::Current()->GetHeap();
548    if (heap->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
549      space::LargeObjectSpace* large_object_space = heap->GetLargeObjectsSpace();
550      if (large_object_space != nullptr && !large_object_space->Contains(root)) {
551        LOG(INTERNAL_FATAL) << "Found invalid root: " << root << " " << info;
552      }
553    }
554  }
555};
556
557void MarkSweep::VerifyRoots() {
558  VerifyRootVisitor visitor;
559  Runtime::Current()->GetThreadList()->VisitRoots(&visitor);
560}
561
562void MarkSweep::MarkRoots(Thread* self) {
563  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
564  if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
565    // If we exclusively hold the mutator lock, all threads must be suspended.
566    Runtime::Current()->VisitRoots(this);
567    RevokeAllThreadLocalAllocationStacks(self);
568  } else {
569    MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
570    // At this point the live stack should no longer have any mutators which push into it.
571    MarkNonThreadRoots();
572    MarkConcurrentRoots(
573        static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
574  }
575}
576
577void MarkSweep::MarkNonThreadRoots() {
578  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
579  Runtime::Current()->VisitNonThreadRoots(this);
580}
581
582void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
583  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
584  // Visit all runtime roots and clear dirty flags.
585  Runtime::Current()->VisitConcurrentRoots(
586      this, static_cast<VisitRootFlags>(flags | kVisitRootFlagNonMoving));
587}
588
589class ScanObjectVisitor {
590 public:
591  explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
592      : mark_sweep_(mark_sweep) {}
593
594  void operator()(mirror::Object* obj) const ALWAYS_INLINE
595      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
596      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
597    if (kCheckLocks) {
598      Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
599      Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
600    }
601    mark_sweep_->ScanObject(obj);
602  }
603
604 private:
605  MarkSweep* const mark_sweep_;
606};
607
608class DelayReferenceReferentVisitor {
609 public:
610  explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {
611  }
612
613  void operator()(mirror::Class* klass, mirror::Reference* ref) const
614      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
615      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
616    collector_->DelayReferenceReferent(klass, ref);
617  }
618
619 private:
620  MarkSweep* const collector_;
621};
622
623template <bool kUseFinger = false>
624class MarkStackTask : public Task {
625 public:
626  MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
627                StackReference<mirror::Object>* mark_stack)
628      : mark_sweep_(mark_sweep),
629        thread_pool_(thread_pool),
630        mark_stack_pos_(mark_stack_size) {
631    // We may have to copy part of an existing mark stack when another mark stack overflows.
632    if (mark_stack_size != 0) {
633      DCHECK(mark_stack != nullptr);
634      // TODO: Check performance?
635      std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
636    }
637    if (kCountTasks) {
638      ++mark_sweep_->work_chunks_created_;
639    }
640  }
641
642  static const size_t kMaxSize = 1 * KB;
643
644 protected:
645  class MarkObjectParallelVisitor {
646   public:
647    explicit MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
648                                       MarkSweep* mark_sweep) ALWAYS_INLINE
649            : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
650
651    void operator()(mirror::Object* obj, MemberOffset offset, bool /* static */) const ALWAYS_INLINE
652        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
653      mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
654      if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
655        if (kUseFinger) {
656          std::atomic_thread_fence(std::memory_order_seq_cst);
657          if (reinterpret_cast<uintptr_t>(ref) >=
658              static_cast<uintptr_t>(mark_sweep_->atomic_finger_.LoadRelaxed())) {
659            return;
660          }
661        }
662        chunk_task_->MarkStackPush(ref);
663      }
664    }
665
666   private:
667    MarkStackTask<kUseFinger>* const chunk_task_;
668    MarkSweep* const mark_sweep_;
669  };
670
671  class ScanObjectParallelVisitor {
672   public:
673    explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
674        : chunk_task_(chunk_task) {}
675
676    // No thread safety analysis since multiple threads will use this visitor.
677    void operator()(mirror::Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
678        EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
679      MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
680      MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
681      DelayReferenceReferentVisitor ref_visitor(mark_sweep);
682      mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
683    }
684
685   private:
686    MarkStackTask<kUseFinger>* const chunk_task_;
687  };
688
689  virtual ~MarkStackTask() {
690    // Make sure that we have cleared our mark stack.
691    DCHECK_EQ(mark_stack_pos_, 0U);
692    if (kCountTasks) {
693      ++mark_sweep_->work_chunks_deleted_;
694    }
695  }
696
697  MarkSweep* const mark_sweep_;
698  ThreadPool* const thread_pool_;
699  // Thread local mark stack for this task.
700  StackReference<mirror::Object> mark_stack_[kMaxSize];
701  // Mark stack position.
702  size_t mark_stack_pos_;
703
704  ALWAYS_INLINE void MarkStackPush(mirror::Object* obj)
705      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
706    if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
707      // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
708      mark_stack_pos_ /= 2;
709      auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
710                                     mark_stack_ + mark_stack_pos_);
711      thread_pool_->AddTask(Thread::Current(), task);
712    }
713    DCHECK(obj != nullptr);
714    DCHECK_LT(mark_stack_pos_, kMaxSize);
715    mark_stack_[mark_stack_pos_++].Assign(obj);
716  }
717
718  virtual void Finalize() {
719    delete this;
720  }
721
722  // Scans all of the objects
723  virtual void Run(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
724      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
725    UNUSED(self);
726    ScanObjectParallelVisitor visitor(this);
727    // TODO: Tune this.
728    static const size_t kFifoSize = 4;
729    BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
730    for (;;) {
731      mirror::Object* obj = nullptr;
732      if (kUseMarkStackPrefetch) {
733        while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
734          mirror::Object* const mark_stack_obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
735          DCHECK(mark_stack_obj != nullptr);
736          __builtin_prefetch(mark_stack_obj);
737          prefetch_fifo.push_back(mark_stack_obj);
738        }
739        if (UNLIKELY(prefetch_fifo.empty())) {
740          break;
741        }
742        obj = prefetch_fifo.front();
743        prefetch_fifo.pop_front();
744      } else {
745        if (UNLIKELY(mark_stack_pos_ == 0)) {
746          break;
747        }
748        obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
749      }
750      DCHECK(obj != nullptr);
751      visitor(obj);
752    }
753  }
754};
755
756class CardScanTask : public MarkStackTask<false> {
757 public:
758  CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
759               accounting::ContinuousSpaceBitmap* bitmap,
760               uint8_t* begin, uint8_t* end, uint8_t minimum_age, size_t mark_stack_size,
761               StackReference<mirror::Object>* mark_stack_obj, bool clear_card)
762      : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
763        bitmap_(bitmap),
764        begin_(begin),
765        end_(end),
766        minimum_age_(minimum_age), clear_card_(clear_card) {
767  }
768
769 protected:
770  accounting::ContinuousSpaceBitmap* const bitmap_;
771  uint8_t* const begin_;
772  uint8_t* const end_;
773  const uint8_t minimum_age_;
774  const bool clear_card_;
775
776  virtual void Finalize() {
777    delete this;
778  }
779
780  virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
781    ScanObjectParallelVisitor visitor(this);
782    accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
783    size_t cards_scanned = clear_card_ ?
784                           card_table->Scan<true>(bitmap_, begin_, end_, visitor, minimum_age_) :
785                           card_table->Scan<false>(bitmap_, begin_, end_, visitor, minimum_age_);
786    VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
787        << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
788    // Finish by emptying our local mark stack.
789    MarkStackTask::Run(self);
790  }
791};
792
793size_t MarkSweep::GetThreadCount(bool paused) const {
794  if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
795    return 1;
796  }
797  return (paused ? heap_->GetParallelGCThreadCount() : heap_->GetConcGCThreadCount()) + 1;
798}
799
800void MarkSweep::ScanGrayObjects(bool paused, uint8_t minimum_age) {
801  accounting::CardTable* card_table = GetHeap()->GetCardTable();
802  ThreadPool* thread_pool = GetHeap()->GetThreadPool();
803  size_t thread_count = GetThreadCount(paused);
804  // The parallel version with only one thread is faster for card scanning, TODO: fix.
805  if (kParallelCardScan && thread_count > 1) {
806    Thread* self = Thread::Current();
807    // Can't have a different split for each space since multiple spaces can have their cards being
808    // scanned at the same time.
809    TimingLogger::ScopedTiming t(paused ? "(Paused)ScanGrayObjects" : __FUNCTION__,
810        GetTimings());
811    // Try to take some of the mark stack since we can pass this off to the worker tasks.
812    StackReference<mirror::Object>* mark_stack_begin = mark_stack_->Begin();
813    StackReference<mirror::Object>* mark_stack_end = mark_stack_->End();
814    const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
815    // Estimated number of work tasks we will create.
816    const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
817    DCHECK_NE(mark_stack_tasks, 0U);
818    const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
819                                             mark_stack_size / mark_stack_tasks + 1);
820    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
821      if (space->GetMarkBitmap() == nullptr) {
822        continue;
823      }
824      uint8_t* card_begin = space->Begin();
825      uint8_t* card_end = space->End();
826      // Align up the end address. For example, the image space's end
827      // may not be card-size-aligned.
828      card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
829      DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin));
830      DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end));
831      // Calculate how many bytes of heap we will scan,
832      const size_t address_range = card_end - card_begin;
833      // Calculate how much address range each task gets.
834      const size_t card_delta = RoundUp(address_range / thread_count + 1,
835                                        accounting::CardTable::kCardSize);
836      // If paused and the space is neither zygote nor image space, we could clear the dirty
837      // cards to avoid accumulating them to increase card scanning load in the following GC
838      // cycles. We need to keep dirty cards of image space and zygote space in order to track
839      // references to the other spaces.
840      bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
841      // Create the worker tasks for this space.
842      while (card_begin != card_end) {
843        // Add a range of cards.
844        size_t addr_remaining = card_end - card_begin;
845        size_t card_increment = std::min(card_delta, addr_remaining);
846        // Take from the back of the mark stack.
847        size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
848        size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
849        mark_stack_end -= mark_stack_increment;
850        mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
851        DCHECK_EQ(mark_stack_end, mark_stack_->End());
852        // Add the new task to the thread pool.
853        auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
854                                      card_begin + card_increment, minimum_age,
855                                      mark_stack_increment, mark_stack_end, clear_card);
856        thread_pool->AddTask(self, task);
857        card_begin += card_increment;
858      }
859    }
860
861    // Note: the card scan below may dirty new cards (and scan them)
862    // as a side effect when a Reference object is encountered and
863    // queued during the marking. See b/11465268.
864    thread_pool->SetMaxActiveWorkers(thread_count - 1);
865    thread_pool->StartWorkers(self);
866    thread_pool->Wait(self, true, true);
867    thread_pool->StopWorkers(self);
868  } else {
869    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
870      if (space->GetMarkBitmap() != nullptr) {
871        // Image spaces are handled properly since live == marked for them.
872        const char* name = nullptr;
873        switch (space->GetGcRetentionPolicy()) {
874        case space::kGcRetentionPolicyNeverCollect:
875          name = paused ? "(Paused)ScanGrayImageSpaceObjects" : "ScanGrayImageSpaceObjects";
876          break;
877        case space::kGcRetentionPolicyFullCollect:
878          name = paused ? "(Paused)ScanGrayZygoteSpaceObjects" : "ScanGrayZygoteSpaceObjects";
879          break;
880        case space::kGcRetentionPolicyAlwaysCollect:
881          name = paused ? "(Paused)ScanGrayAllocSpaceObjects" : "ScanGrayAllocSpaceObjects";
882          break;
883        default:
884          LOG(FATAL) << "Unreachable";
885          UNREACHABLE();
886        }
887        TimingLogger::ScopedTiming t(name, GetTimings());
888        ScanObjectVisitor visitor(this);
889        bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
890        if (clear_card) {
891          card_table->Scan<true>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor,
892                                 minimum_age);
893        } else {
894          card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor,
895                                  minimum_age);
896        }
897      }
898    }
899  }
900}
901
902class RecursiveMarkTask : public MarkStackTask<false> {
903 public:
904  RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
905                    accounting::ContinuousSpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
906      : MarkStackTask<false>(thread_pool, mark_sweep, 0, nullptr), bitmap_(bitmap), begin_(begin),
907        end_(end) {
908  }
909
910 protected:
911  accounting::ContinuousSpaceBitmap* const bitmap_;
912  const uintptr_t begin_;
913  const uintptr_t end_;
914
915  virtual void Finalize() {
916    delete this;
917  }
918
919  // Scans all of the objects
920  virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
921    ScanObjectParallelVisitor visitor(this);
922    bitmap_->VisitMarkedRange(begin_, end_, visitor);
923    // Finish by emptying our local mark stack.
924    MarkStackTask::Run(self);
925  }
926};
927
928// Populates the mark stack based on the set of marked objects and
929// recursively marks until the mark stack is emptied.
930void MarkSweep::RecursiveMark() {
931  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
932  // RecursiveMark will build the lists of known instances of the Reference classes. See
933  // DelayReferenceReferent for details.
934  if (kUseRecursiveMark) {
935    const bool partial = GetGcType() == kGcTypePartial;
936    ScanObjectVisitor scan_visitor(this);
937    auto* self = Thread::Current();
938    ThreadPool* thread_pool = heap_->GetThreadPool();
939    size_t thread_count = GetThreadCount(false);
940    const bool parallel = kParallelRecursiveMark && thread_count > 1;
941    mark_stack_->Reset();
942    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
943      if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
944          (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
945        current_space_bitmap_ = space->GetMarkBitmap();
946        if (current_space_bitmap_ == nullptr) {
947          continue;
948        }
949        if (parallel) {
950          // We will use the mark stack the future.
951          // CHECK(mark_stack_->IsEmpty());
952          // This function does not handle heap end increasing, so we must use the space end.
953          uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
954          uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
955          atomic_finger_.StoreRelaxed(AtomicInteger::MaxValue());
956
957          // Create a few worker tasks.
958          const size_t n = thread_count * 2;
959          while (begin != end) {
960            uintptr_t start = begin;
961            uintptr_t delta = (end - begin) / n;
962            delta = RoundUp(delta, KB);
963            if (delta < 16 * KB) delta = end - begin;
964            begin += delta;
965            auto* task = new RecursiveMarkTask(thread_pool, this, current_space_bitmap_, start,
966                                               begin);
967            thread_pool->AddTask(self, task);
968          }
969          thread_pool->SetMaxActiveWorkers(thread_count - 1);
970          thread_pool->StartWorkers(self);
971          thread_pool->Wait(self, true, true);
972          thread_pool->StopWorkers(self);
973        } else {
974          // This function does not handle heap end increasing, so we must use the space end.
975          uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
976          uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
977          current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
978        }
979      }
980    }
981  }
982  ProcessMarkStack(false);
983}
984
985void MarkSweep::RecursiveMarkDirtyObjects(bool paused, uint8_t minimum_age) {
986  ScanGrayObjects(paused, minimum_age);
987  ProcessMarkStack(paused);
988}
989
990void MarkSweep::ReMarkRoots() {
991  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
992  Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
993  Runtime::Current()->VisitRoots(this, static_cast<VisitRootFlags>(
994      kVisitRootFlagNewRoots | kVisitRootFlagStopLoggingNewRoots | kVisitRootFlagClearRootLog));
995  if (kVerifyRootsMarked) {
996    TimingLogger::ScopedTiming t2("(Paused)VerifyRoots", GetTimings());
997    VerifyRootMarkedVisitor visitor(this);
998    Runtime::Current()->VisitRoots(&visitor);
999  }
1000}
1001
1002void MarkSweep::SweepSystemWeaks(Thread* self) {
1003  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1004  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1005  Runtime::Current()->SweepSystemWeaks(this);
1006}
1007
1008class VerifySystemWeakVisitor : public IsMarkedVisitor {
1009 public:
1010  explicit VerifySystemWeakVisitor(MarkSweep* mark_sweep) : mark_sweep_(mark_sweep) {}
1011
1012  virtual mirror::Object* IsMarked(mirror::Object* obj) OVERRIDE
1013      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1014    mark_sweep_->VerifyIsLive(obj);
1015    return obj;
1016  }
1017
1018  MarkSweep* const mark_sweep_;
1019};
1020
1021void MarkSweep::VerifyIsLive(const mirror::Object* obj) {
1022  if (!heap_->GetLiveBitmap()->Test(obj)) {
1023    // TODO: Consider live stack? Has this code bitrotted?
1024    CHECK(!heap_->allocation_stack_->Contains(obj))
1025        << "Found dead object " << obj << "\n" << heap_->DumpSpaces();
1026  }
1027}
1028
1029void MarkSweep::VerifySystemWeaks() {
1030  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1031  // Verify system weaks, uses a special object visitor which returns the input object.
1032  VerifySystemWeakVisitor visitor(this);
1033  Runtime::Current()->SweepSystemWeaks(&visitor);
1034}
1035
1036class CheckpointMarkThreadRoots : public Closure, public RootVisitor {
1037 public:
1038  explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
1039                                     bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
1040      : mark_sweep_(mark_sweep),
1041        revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
1042            revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1043  }
1044
1045  void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
1046      OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1047      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1048    for (size_t i = 0; i < count; ++i) {
1049      mark_sweep_->MarkObjectNonNullParallel(*roots[i]);
1050    }
1051  }
1052
1053  void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1054                  const RootInfo& info ATTRIBUTE_UNUSED)
1055      OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1056      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1057    for (size_t i = 0; i < count; ++i) {
1058      mark_sweep_->MarkObjectNonNullParallel(roots[i]->AsMirrorPtr());
1059    }
1060  }
1061
1062  virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
1063    ATRACE_BEGIN("Marking thread roots");
1064    // Note: self is not necessarily equal to thread since thread may be suspended.
1065    Thread* const self = Thread::Current();
1066    CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1067        << thread->GetState() << " thread " << thread << " self " << self;
1068    thread->VisitRoots(this);
1069    ATRACE_END();
1070    if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
1071      ATRACE_BEGIN("RevokeRosAllocThreadLocalBuffers");
1072      mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
1073      ATRACE_END();
1074    }
1075    // If thread is a running mutator, then act on behalf of the garbage collector.
1076    // See the code in ThreadList::RunCheckpoint.
1077    if (thread->GetState() == kRunnable) {
1078      mark_sweep_->GetBarrier().Pass(self);
1079    }
1080  }
1081
1082 private:
1083  MarkSweep* const mark_sweep_;
1084  const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
1085};
1086
1087void MarkSweep::MarkRootsCheckpoint(Thread* self,
1088                                    bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1089  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1090  CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
1091  ThreadList* thread_list = Runtime::Current()->GetThreadList();
1092  // Request the check point is run on all threads returning a count of the threads that must
1093  // run through the barrier including self.
1094  size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1095  // Release locks then wait for all mutator threads to pass the barrier.
1096  // If there are no threads to wait which implys that all the checkpoint functions are finished,
1097  // then no need to release locks.
1098  if (barrier_count == 0) {
1099    return;
1100  }
1101  Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1102  Locks::mutator_lock_->SharedUnlock(self);
1103  {
1104    ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1105    gc_barrier_->Increment(self, barrier_count);
1106  }
1107  Locks::mutator_lock_->SharedLock(self);
1108  Locks::heap_bitmap_lock_->ExclusiveLock(self);
1109}
1110
1111void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
1112  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1113  Thread* self = Thread::Current();
1114  mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1115      sweep_array_free_buffer_mem_map_->BaseBegin());
1116  size_t chunk_free_pos = 0;
1117  ObjectBytePair freed;
1118  ObjectBytePair freed_los;
1119  // How many objects are left in the array, modified after each space is swept.
1120  StackReference<mirror::Object>* objects = allocations->Begin();
1121  size_t count = allocations->Size();
1122  // Change the order to ensure that the non-moving space last swept as an optimization.
1123  std::vector<space::ContinuousSpace*> sweep_spaces;
1124  space::ContinuousSpace* non_moving_space = nullptr;
1125  for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
1126    if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) &&
1127        space->GetLiveBitmap() != nullptr) {
1128      if (space == heap_->GetNonMovingSpace()) {
1129        non_moving_space = space;
1130      } else {
1131        sweep_spaces.push_back(space);
1132      }
1133    }
1134  }
1135  // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1136  // the other alloc spaces as an optimization.
1137  if (non_moving_space != nullptr) {
1138    sweep_spaces.push_back(non_moving_space);
1139  }
1140  // Start by sweeping the continuous spaces.
1141  for (space::ContinuousSpace* space : sweep_spaces) {
1142    space::AllocSpace* alloc_space = space->AsAllocSpace();
1143    accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1144    accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1145    if (swap_bitmaps) {
1146      std::swap(live_bitmap, mark_bitmap);
1147    }
1148    StackReference<mirror::Object>* out = objects;
1149    for (size_t i = 0; i < count; ++i) {
1150      mirror::Object* const obj = objects[i].AsMirrorPtr();
1151      if (kUseThreadLocalAllocationStack && obj == nullptr) {
1152        continue;
1153      }
1154      if (space->HasAddress(obj)) {
1155        // This object is in the space, remove it from the array and add it to the sweep buffer
1156        // if needed.
1157        if (!mark_bitmap->Test(obj)) {
1158          if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1159            TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1160            freed.objects += chunk_free_pos;
1161            freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1162            chunk_free_pos = 0;
1163          }
1164          chunk_free_buffer[chunk_free_pos++] = obj;
1165        }
1166      } else {
1167        (out++)->Assign(obj);
1168      }
1169    }
1170    if (chunk_free_pos > 0) {
1171      TimingLogger::ScopedTiming t2("FreeList", GetTimings());
1172      freed.objects += chunk_free_pos;
1173      freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1174      chunk_free_pos = 0;
1175    }
1176    // All of the references which space contained are no longer in the allocation stack, update
1177    // the count.
1178    count = out - objects;
1179  }
1180  // Handle the large object space.
1181  space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
1182  if (large_object_space != nullptr) {
1183    accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1184    accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1185    if (swap_bitmaps) {
1186      std::swap(large_live_objects, large_mark_objects);
1187    }
1188    for (size_t i = 0; i < count; ++i) {
1189      mirror::Object* const obj = objects[i].AsMirrorPtr();
1190      // Handle large objects.
1191      if (kUseThreadLocalAllocationStack && obj == nullptr) {
1192        continue;
1193      }
1194      if (!large_mark_objects->Test(obj)) {
1195        ++freed_los.objects;
1196        freed_los.bytes += large_object_space->Free(self, obj);
1197      }
1198    }
1199  }
1200  {
1201    TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
1202    RecordFree(freed);
1203    RecordFreeLOS(freed_los);
1204    t2.NewTiming("ResetStack");
1205    allocations->Reset();
1206  }
1207  sweep_array_free_buffer_mem_map_->MadviseDontNeedAndZero();
1208}
1209
1210void MarkSweep::Sweep(bool swap_bitmaps) {
1211  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1212  // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1213  CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
1214  {
1215    TimingLogger::ScopedTiming t2("MarkAllocStackAsLive", GetTimings());
1216    // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1217    // knowing that new allocations won't be marked as live.
1218    accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1219    heap_->MarkAllocStackAsLive(live_stack);
1220    live_stack->Reset();
1221    DCHECK(mark_stack_->IsEmpty());
1222  }
1223  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1224    if (space->IsContinuousMemMapAllocSpace()) {
1225      space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1226      TimingLogger::ScopedTiming split(
1227          alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", GetTimings());
1228      RecordFree(alloc_space->Sweep(swap_bitmaps));
1229    }
1230  }
1231  SweepLargeObjects(swap_bitmaps);
1232}
1233
1234void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
1235  space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
1236  if (los != nullptr) {
1237    TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1238    RecordFreeLOS(los->Sweep(swap_bitmaps));
1239  }
1240}
1241
1242// Process the "referent" field in a java.lang.ref.Reference.  If the referent has not yet been
1243// marked, put it on the appropriate list in the heap for later processing.
1244void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
1245  if (kCountJavaLangRefs) {
1246    ++reference_count_;
1247  }
1248  heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, ref, this);
1249}
1250
1251class MarkVisitor {
1252 public:
1253  explicit MarkVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {
1254  }
1255
1256  void operator()(mirror::Object* obj, MemberOffset offset, bool /* is_static */) const
1257      ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1258      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1259    if (kCheckLocks) {
1260      Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1261      Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1262    }
1263    mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset), obj, offset);
1264  }
1265
1266 private:
1267  MarkSweep* const mark_sweep_;
1268};
1269
1270// Scans an object reference.  Determines the type of the reference
1271// and dispatches to a specialized scanning routine.
1272void MarkSweep::ScanObject(mirror::Object* obj) {
1273  MarkVisitor mark_visitor(this);
1274  DelayReferenceReferentVisitor ref_visitor(this);
1275  ScanObjectVisit(obj, mark_visitor, ref_visitor);
1276}
1277
1278void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
1279  Thread* self = Thread::Current();
1280  ThreadPool* thread_pool = GetHeap()->GetThreadPool();
1281  const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1282                                     static_cast<size_t>(MarkStackTask<false>::kMaxSize));
1283  CHECK_GT(chunk_size, 0U);
1284  // Split the current mark stack up into work tasks.
1285  for (auto* it = mark_stack_->Begin(), *end = mark_stack_->End(); it < end; ) {
1286    const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
1287    thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
1288    it += delta;
1289  }
1290  thread_pool->SetMaxActiveWorkers(thread_count - 1);
1291  thread_pool->StartWorkers(self);
1292  thread_pool->Wait(self, true, true);
1293  thread_pool->StopWorkers(self);
1294  mark_stack_->Reset();
1295  CHECK_EQ(work_chunks_created_.LoadSequentiallyConsistent(),
1296           work_chunks_deleted_.LoadSequentiallyConsistent())
1297      << " some of the work chunks were leaked";
1298}
1299
1300// Scan anything that's on the mark stack.
1301void MarkSweep::ProcessMarkStack(bool paused) {
1302  TimingLogger::ScopedTiming t(paused ? "(Paused)ProcessMarkStack" : __FUNCTION__, GetTimings());
1303  size_t thread_count = GetThreadCount(paused);
1304  if (kParallelProcessMarkStack && thread_count > 1 &&
1305      mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1306    ProcessMarkStackParallel(thread_count);
1307  } else {
1308    // TODO: Tune this.
1309    static const size_t kFifoSize = 4;
1310    BoundedFifoPowerOfTwo<mirror::Object*, kFifoSize> prefetch_fifo;
1311    for (;;) {
1312      mirror::Object* obj = nullptr;
1313      if (kUseMarkStackPrefetch) {
1314        while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
1315          mirror::Object* mark_stack_obj = mark_stack_->PopBack();
1316          DCHECK(mark_stack_obj != nullptr);
1317          __builtin_prefetch(mark_stack_obj);
1318          prefetch_fifo.push_back(mark_stack_obj);
1319        }
1320        if (prefetch_fifo.empty()) {
1321          break;
1322        }
1323        obj = prefetch_fifo.front();
1324        prefetch_fifo.pop_front();
1325      } else {
1326        if (mark_stack_->IsEmpty()) {
1327          break;
1328        }
1329        obj = mark_stack_->PopBack();
1330      }
1331      DCHECK(obj != nullptr);
1332      ScanObject(obj);
1333    }
1334  }
1335}
1336
1337inline mirror::Object* MarkSweep::IsMarked(mirror::Object* object) {
1338  if (immune_region_.ContainsObject(object)) {
1339    return object;
1340  }
1341  if (current_space_bitmap_->HasAddress(object)) {
1342    return current_space_bitmap_->Test(object) ? object : nullptr;
1343  }
1344  return mark_bitmap_->Test(object) ? object : nullptr;
1345}
1346
1347void MarkSweep::FinishPhase() {
1348  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1349  if (kCountScannedTypes) {
1350    VLOG(gc) << "MarkSweep scanned classes=" << class_count_.LoadRelaxed()
1351        << " arrays=" << array_count_.LoadRelaxed() << " other=" << other_count_.LoadRelaxed();
1352  }
1353  if (kCountTasks) {
1354    VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_.LoadRelaxed();
1355  }
1356  if (kMeasureOverhead) {
1357    VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_.LoadRelaxed());
1358  }
1359  if (kProfileLargeObjects) {
1360    VLOG(gc) << "Large objects tested " << large_object_test_.LoadRelaxed()
1361        << " marked " << large_object_mark_.LoadRelaxed();
1362  }
1363  if (kCountJavaLangRefs) {
1364    VLOG(gc) << "References scanned " << reference_count_.LoadRelaxed();
1365  }
1366  if (kCountMarkedObjects) {
1367    VLOG(gc) << "Marked: null=" << mark_null_count_.LoadRelaxed()
1368        << " immune=" <<  mark_immune_count_.LoadRelaxed()
1369        << " fastpath=" << mark_fastpath_count_.LoadRelaxed()
1370        << " slowpath=" << mark_slowpath_count_.LoadRelaxed();
1371  }
1372  CHECK(mark_stack_->IsEmpty());  // Ensure that the mark stack is empty.
1373  mark_stack_->Reset();
1374  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1375  heap_->ClearMarkedObjects();
1376}
1377
1378void MarkSweep::RevokeAllThreadLocalBuffers() {
1379  if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1380    // If concurrent, rosalloc thread-local buffers are revoked at the
1381    // thread checkpoint. Bump pointer space thread-local buffers must
1382    // not be in use.
1383    GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1384  } else {
1385    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1386    GetHeap()->RevokeAllThreadLocalBuffers();
1387  }
1388}
1389
1390}  // namespace collector
1391}  // namespace gc
1392}  // namespace art
1393