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