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