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