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