mark_sweep.cc revision e401d146407d61eeb99f8d6176b2ac13c4df1e33
12faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes/*
22faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * Copyright (C) 2011 The Android Open Source Project
32faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes *
42faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * Licensed under the Apache License, Version 2.0 (the "License");
52faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * you may not use this file except in compliance with the License.
62faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * You may obtain a copy of the License at
72faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes *
82faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes *      http://www.apache.org/licenses/LICENSE-2.0
92faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes *
102faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * Unless required by applicable law or agreed to in writing, software
112faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * distributed under the License is distributed on an "AS IS" BASIS,
122faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
132faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * See the License for the specific language governing permissions and
142faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes * limitations under the License.
152faa5f1271587cda765f26bcf2951065300a01ffElliott Hughes */
1669759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
17578bbdc684db8ed68e9fedbc678669d27fa68b6eBrian Carlstrom#include "mark_sweep.h"
1869759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
19c7df66e2cb124d261cf3b0691a09a3b6e357b6f1Yabin Cui#include <atomic>
202b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier#include <functional>
212b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier#include <numeric>
2258551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro#include <climits>
2358551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro#include <vector>
2458551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro
25cf7f19135f0e273f7b0136315633c2abfc715343Ian Rogers#define ATRACE_TAG ATRACE_TAG_DALVIK
26cf7f19135f0e273f7b0136315633c2abfc715343Ian Rogers#include "cutils/trace.h"
27cf7f19135f0e273f7b0136315633c2abfc715343Ian Rogers
2894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier#include "base/bounded_fifo.h"
2907ed66b5ae659c452cbe1ab20c3dbf1d6f546461Elliott Hughes#include "base/logging.h"
30761600567d73b23324ae0251e871c15d6849ffd8Elliott Hughes#include "base/macros.h"
31693ff61274cd2c9b8eb7e68c370f84a911b8ca52Ian Rogers#include "base/mutex-inl.h"
3280afd02024d20e60b197d3adfbb43cc303cf29e0Vladimir Marko#include "base/time_utils.h"
33a84395489098e4531619b1cffd1afc282b14510eSameer Abu Asal#include "base/timing_logger.h"
341d54e73444e017d3a65234e0f193846f3e27472bIan Rogers#include "gc/accounting/card_table-inl.h"
354aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier#include "gc/accounting/heap_bitmap-inl.h"
3611409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier#include "gc/accounting/mod_union_table.h"
371d54e73444e017d3a65234e0f193846f3e27472bIan Rogers#include "gc/accounting/space_bitmap-inl.h"
381d54e73444e017d3a65234e0f193846f3e27472bIan Rogers#include "gc/heap.h"
3978f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartier#include "gc/reference_processor.h"
401d54e73444e017d3a65234e0f193846f3e27472bIan Rogers#include "gc/space/image_space.h"
411d54e73444e017d3a65234e0f193846f3e27472bIan Rogers#include "gc/space/large_object_space.h"
421d54e73444e017d3a65234e0f193846f3e27472bIan Rogers#include "gc/space/space-inl.h"
432dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers#include "mark_sweep-inl.h"
442dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers#include "mirror/object-inl.h"
451f87008b165d26541d832ff805250afdc89c253dBrian Carlstrom#include "runtime.h"
464aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier#include "scoped_thread_state_change.h"
471d54e73444e017d3a65234e0f193846f3e27472bIan Rogers#include "thread-inl.h"
486f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartier#include "thread_list.h"
4969759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
503e3d591f781b771de89f3b989830da2b6ac6fac8Brian Carlstromusing ::art::mirror::Object;
512dd0e2cea360bc9206eb88ecc40d259e796c239dIan Rogers
5269759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapironamespace art {
531d54e73444e017d3a65234e0f193846f3e27472bIan Rogersnamespace gc {
541d54e73444e017d3a65234e0f193846f3e27472bIan Rogersnamespace collector {
5569759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
5602b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier// Performance options.
57eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kUseRecursiveMark = false;
58eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kUseMarkStackPrefetch = true;
59eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr size_t kSweepArrayChunkFreeSize = 1024;
60eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kPreCleanCards = true;
6194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
6294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier// Parallelism options.
63eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kParallelCardScan = true;
64eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kParallelRecursiveMark = true;
6594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
6694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
6794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier// having this can add overhead in ProcessReferences since we may end up doing many calls of
6894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier// ProcessMarkStack with very small mark stacks.
69eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr size_t kMinimumParallelMarkStackSize = 128;
70eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kParallelProcessMarkStack = true;
71858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier
7202b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier// Profiling and information flags.
73eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kProfileLargeObjects = false;
74eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kMeasureOverhead = false;
75eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kCountTasks = false;
76eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kCountJavaLangRefs = false;
770e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartierstatic constexpr bool kCountMarkedObjects = false;
7894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
7994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
80eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartierstatic constexpr bool kCheckLocks = kDebugLocking;
817bf9f190cd33a7e2f8584299eb889e9df66e0323Mathieu Chartierstatic constexpr bool kVerifyRootsMarked = kIsDebugBuild;
8202b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier
83c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi// If true, revoke the rosalloc thread-local buffers at the
84c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi// checkpoint, as opposed to during the pause.
85c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchistatic constexpr bool kRevokeRosAllocThreadLocalBuffersAtCheckpoint = true;
86c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi
872b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartiervoid MarkSweep::BindBitmaps() {
88f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
892b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
902b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  // Mark all of the spaces we never collect as immune.
9194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
921d54e73444e017d3a65234e0f193846f3e27472bIan Rogers    if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
938d562103c3a3452fb15ef4b1c64df767b70507a4Mathieu Chartier      CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
942b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    }
952b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  }
962b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier}
972b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier
981d54e73444e017d3a65234e0f193846f3e27472bIan RogersMarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
991d54e73444e017d3a65234e0f193846f3e27472bIan Rogers    : GarbageCollector(heap,
100590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier                       name_prefix +
1011d54e73444e017d3a65234e0f193846f3e27472bIan Rogers                       (is_concurrent ? "concurrent mark sweep": "mark sweep")),
1023e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers      current_space_bitmap_(nullptr), mark_bitmap_(nullptr), mark_stack_(nullptr),
10335883cc623fdf475a4ead1dafcba9e9becc1ed11Mathieu Chartier      gc_barrier_(new Barrier(0)),
104958291c7afe723d846a39539fd00410c102485f3Mathieu Chartier      mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
1053e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers      is_concurrent_(is_concurrent), live_stack_freeze_size_(0) {
106bbdc5bc5fd5141711879a6c85d80ac45b7aad5d0Hiroshi Yamauchi  std::string error_msg;
107bbdc5bc5fd5141711879a6c85d80ac45b7aad5d0Hiroshi Yamauchi  MemMap* mem_map = MemMap::MapAnonymous(
108bbdc5bc5fd5141711879a6c85d80ac45b7aad5d0Hiroshi Yamauchi      "mark sweep sweep array free buffer", nullptr,
109bbdc5bc5fd5141711879a6c85d80ac45b7aad5d0Hiroshi Yamauchi      RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
1105c42c29b89286e5efa4a4613132b09051ce5945bVladimir Marko      PROT_READ | PROT_WRITE, false, false, &error_msg);
111bbdc5bc5fd5141711879a6c85d80ac45b7aad5d0Hiroshi Yamauchi  CHECK(mem_map != nullptr) << "Couldn't allocate sweep array free buffer: " << error_msg;
112bbdc5bc5fd5141711879a6c85d80ac45b7aad5d0Hiroshi Yamauchi  sweep_array_free_buffer_mem_map_.reset(mem_map);
1135301cd241b4d8afbfc1211e107c41f1b15c6bd48Mathieu Chartier}
114b3bd5f07884f5a1f2b84224363b1372d7c28d447Elliott Hughes
1152b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartiervoid MarkSweep::InitializePhase() {
116f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
117eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier  mark_stack_ = heap_->GetMarkStack();
118e53225c7b8c98f8fc3855fc70f718e7f8abab307Mathieu Chartier  DCHECK(mark_stack_ != nullptr);
1198d562103c3a3452fb15ef4b1c64df767b70507a4Mathieu Chartier  immune_region_.Reset();
1203e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  class_count_.StoreRelaxed(0);
1213e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  array_count_.StoreRelaxed(0);
1223e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  other_count_.StoreRelaxed(0);
1233e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  large_object_test_.StoreRelaxed(0);
1243e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  large_object_mark_.StoreRelaxed(0);
1253e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  overhead_time_ .StoreRelaxed(0);
1263e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  work_chunks_created_.StoreRelaxed(0);
1273e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  work_chunks_deleted_.StoreRelaxed(0);
1283e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  reference_count_.StoreRelaxed(0);
1293e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  mark_null_count_.StoreRelaxed(0);
1303e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  mark_immune_count_.StoreRelaxed(0);
1313e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  mark_fastpath_count_.StoreRelaxed(0);
1323e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  mark_slowpath_count_.StoreRelaxed(0);
1330e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  {
134eb8167a4f4d27fce0530f6724ab8032610cd146bMathieu Chartier    // TODO: I don't think we should need heap bitmap lock to Get the mark bitmap.
1350e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1360e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    mark_bitmap_ = heap_->GetMarkBitmap();
1370e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  }
13810fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier  if (!GetCurrentIteration()->GetClearSoftReferences()) {
139df386c551405ce9668e827584f744c6f098761faHiroshi Yamauchi    // Always clear soft references if a non-sticky collection.
14010fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier    GetCurrentIteration()->SetClearSoftReferences(GetGcType() != collector::kGcTypeSticky);
141df386c551405ce9668e827584f744c6f098761faHiroshi Yamauchi  }
1426f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier}
1436f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier
1446f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartiervoid MarkSweep::RunPhases() {
1456f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  Thread* self = Thread::Current();
1466f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  InitializePhase();
1476f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  Locks::mutator_lock_->AssertNotHeld(self);
1486f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  if (IsConcurrent()) {
1496f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    GetHeap()->PreGcVerification(this);
1506f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    {
1516f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier      ReaderMutexLock mu(self, *Locks::mutator_lock_);
1526f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier      MarkingPhase();
1536f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    }
1546f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    ScopedPause pause(this);
1556f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    GetHeap()->PrePauseRosAllocVerification(this);
1566f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    PausePhase();
1576f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    RevokeAllThreadLocalBuffers();
1586f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  } else {
1596f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    ScopedPause pause(this);
1606f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    GetHeap()->PreGcVerificationPaused(this);
1616f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    MarkingPhase();
1626f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    GetHeap()->PrePauseRosAllocVerification(this);
1636f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    PausePhase();
1646f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    RevokeAllThreadLocalBuffers();
1656f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  }
1666f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  {
1676f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    // Sweeping always done concurrently, even for non concurrent mark sweep.
1686f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    ReaderMutexLock mu(self, *Locks::mutator_lock_);
1696f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier    ReclaimPhase();
1706f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  }
1716f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  GetHeap()->PostGcVerification(this);
1726f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  FinishPhase();
1732b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier}
1742b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier
1752b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartiervoid MarkSweep::ProcessReferences(Thread* self) {
1768e56c7e41cb37e2eaf553503968a01ff893b135bMathieu Chartier  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
17778f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartier  GetHeap()->GetReferenceProcessor()->ProcessReferences(
17810fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier      true, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(),
17910fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier      &HeapReferenceMarkedCallback, &MarkObjectCallback, &ProcessMarkStackCallback, this);
1801ad2784ad9f311ebf9fe0677d33818648f423f9cMathieu Chartier}
1811ad2784ad9f311ebf9fe0677d33818648f423f9cMathieu Chartier
1820f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartiervoid MarkSweep::PausePhase() {
183f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t("(Paused)PausePhase", GetTimings());
1842b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  Thread* self = Thread::Current();
1852b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  Locks::mutator_lock_->AssertExclusiveHeld(self);
1860f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  if (IsConcurrent()) {
1870f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier    // Handle the dirty objects if we are a concurrent GC.
1882b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1892b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    // Re-mark root set.
1902b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    ReMarkRoots();
1912b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    // Scan dirty objects, this is only required if we are not doing concurrent GC.
19294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
1932b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  }
1940f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  {
195f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    TimingLogger::ScopedTiming t2("SwapStacks", GetTimings());
1962b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
1970f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier    heap_->SwapStacks(self);
1980f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier    live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
1990f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier    // Need to revoke all the thread local allocation stacks since we just swapped the allocation
2000f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier    // stacks and don't want anybody to allocate into the live stack.
201c22c59ef8513b4cbbfd25073d1afbf58196b522aMathieu Chartier    RevokeAllThreadLocalAllocationStacks(self);
2022b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  }
2030f72e4136aecaf6976fdb55916bbd7b6d5c9c77bMathieu Chartier  heap_->PreSweepingGcVerification(this);
2046f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  // Disallow new system weaks to prevent a race which occurs when someone adds a new system
2056f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  // weak before we sweep them. Since this new system weak may not be marked, the GC may
2066f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
2076f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  // reference to a string that is about to be swept.
2086f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  Runtime::Current()->DisallowNewSystemWeaks();
20978f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartier  // Enable the reference processing slow path, needs to be done with mutators paused since there
21078f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartier  // is no lock in the GetReferent fast path.
21178f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartier  GetHeap()->GetReferenceProcessor()->EnableSlowPath();
2122b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier}
2132b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier
214dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartiervoid MarkSweep::PreCleanCards() {
215dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier  // Don't do this for non concurrent GCs since they don't have any dirty cards.
216dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier  if (kPreCleanCards && IsConcurrent()) {
217f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
218dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier    Thread* self = Thread::Current();
219dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier    CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
220dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier    // Process dirty cards and add dirty cards to mod union tables, also ages cards.
2214add3b4fa38ec42bb3c71d01cf70bce8e9a9fb4eLei Li    heap_->ProcessCards(GetTimings(), false, true, false);
222eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // The checkpoint root marking is required to avoid a race condition which occurs if the
223eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // following happens during a reference write:
224eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // 1. mutator dirties the card (write barrier)
225eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // 2. GC ages the card (the above ProcessCards call)
226eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
227eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // 4. mutator writes the value (corresponding to the write barrier in 1.)
228eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // This causes the GC to age the card but not necessarily mark the reference which the mutator
229eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // wrote into the object stored in the card.
230eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // Having the checkpoint fixes this issue since it ensures that the card mark and the
231eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // reference write are visible to the GC before the card is scanned (this is due to locks being
232eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // acquired / released in the checkpoint code).
233eb7bbad163ce7a2c60bba6e0d3d7488e5cfb2c05Mathieu Chartier    // The other roots are also marked to help reduce the pause.
2340f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier    MarkRootsCheckpoint(self, false);
235dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier    MarkNonThreadRoots();
236893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier    MarkConcurrentRoots(
237893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier        static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
238dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier    // Process the newly aged cards.
239dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier    RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
240dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier    // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
241dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier    // in the next GC.
242dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier  }
243dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier}
244dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier
245c22c59ef8513b4cbbfd25073d1afbf58196b522aMathieu Chartiervoid MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
246c22c59ef8513b4cbbfd25073d1afbf58196b522aMathieu Chartier  if (kUseThreadLocalAllocationStack) {
247f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
248c22c59ef8513b4cbbfd25073d1afbf58196b522aMathieu Chartier    Locks::mutator_lock_->AssertExclusiveHeld(self);
249c22c59ef8513b4cbbfd25073d1afbf58196b522aMathieu Chartier    heap_->RevokeAllThreadLocalAllocationStacks(self);
250c22c59ef8513b4cbbfd25073d1afbf58196b522aMathieu Chartier  }
251c22c59ef8513b4cbbfd25073d1afbf58196b522aMathieu Chartier}
252c22c59ef8513b4cbbfd25073d1afbf58196b522aMathieu Chartier
2532b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartiervoid MarkSweep::MarkingPhase() {
254f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
2552b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  Thread* self = Thread::Current();
2562b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  BindBitmaps();
2570e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  FindDefaultSpaceBitmap();
2582b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  // Process dirty cards and add dirty cards to mod union tables.
2594add3b4fa38ec42bb3c71d01cf70bce8e9a9fb4eLei Li  // If the GC type is non sticky, then we just clear the cards instead of ageing them.
2604add3b4fa38ec42bb3c71d01cf70bce8e9a9fb4eLei Li  heap_->ProcessCards(GetTimings(), false, true, GetGcType() != kGcTypeSticky);
2612b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
262893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier  MarkRoots(self);
2632b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  MarkReachableObjects();
264dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier  // Pre-clean dirtied cards to reduce pauses.
265dda54f59271464b5a72bf4cde6d9010e8dc1f337Mathieu Chartier  PreCleanCards();
2662b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier}
2672b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier
26811409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartiervoid MarkSweep::UpdateAndMarkModUnion() {
26911409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier  for (const auto& space : heap_->GetContinuousSpaces()) {
2708d562103c3a3452fb15ef4b1c64df767b70507a4Mathieu Chartier    if (immune_region_.ContainsSpace(space)) {
27111409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier      const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
27211409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier          "UpdateAndMarkImageModUnionTable";
273f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier      TimingLogger::ScopedTiming t(name, GetTimings());
27411409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier      accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
27511409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier      CHECK(mod_union_table != nullptr);
276407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      mod_union_table->UpdateAndMarkReferences(MarkHeapReferenceCallback, this);
27711409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier    }
27811409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier  }
27911409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier}
28011409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier
2812b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartiervoid MarkSweep::MarkReachableObjects() {
2824aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  UpdateAndMarkModUnion();
2832b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  // Recursively mark all the non-image bits set in the mark bitmap.
2842b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  RecursiveMark();
2852b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier}
2862b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier
2872b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartiervoid MarkSweep::ReclaimPhase() {
288f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
289720ef7680573c1afd12f99f02eee3045daee5168Mathieu Chartier  Thread* self = Thread::Current();
29078f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartier  // Process the references concurrently.
29178f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartier  ProcessReferences(self);
2920f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  SweepSystemWeaks(self);
2936f365cc033654a5a3b45eaa1379d4b5f156b0ceeMathieu Chartier  Runtime::Current()->AllowNewSystemWeaks();
2942b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  {
2952b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
2964460a84be92b5a94ecfb5c650aef4945ab849c93Hiroshi Yamauchi    GetHeap()->RecordFreeRevoke();
2972b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    // Reclaim unmarked objects.
2981d54e73444e017d3a65234e0f193846f3e27472bIan Rogers    Sweep(false);
2992b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    // Swap the live and mark bitmaps for each space which we modified space. This is an
3002b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
3012b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    // bitmaps.
3022b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    SwapBitmaps();
3032b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    // Unbind the live and mark bitmaps.
304a1602f28c0e3127ad511712d4b08db89737ae901Mathieu Chartier    GetHeap()->UnBindBitmaps();
3052b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  }
3062b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier}
3072b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier
3080e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartiervoid MarkSweep::FindDefaultSpaceBitmap() {
309f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
31002e25119b15a6f619f17db99f5d05124a5807ff3Mathieu Chartier  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
311a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier    accounting::ContinuousSpaceBitmap* bitmap = space->GetMarkBitmap();
312bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    // We want to have the main space instead of non moving if possible.
313590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    if (bitmap != nullptr &&
314590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
3150e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier      current_space_bitmap_ = bitmap;
316bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      // If we are not the non moving space exit the loop early since this will be good enough.
317bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      if (space != heap_->GetNonMovingSpace()) {
318bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier        break;
319bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      }
320b062fdd4cb097fbae69b4bcb479c34d83ecab8caMathieu Chartier    }
321b062fdd4cb097fbae69b4bcb479c34d83ecab8caMathieu Chartier  }
3224c13a3ff475f206c4d0a86ee2595c45392fd942fMathieu Chartier  CHECK(current_space_bitmap_ != nullptr) << "Could not find a default mark bitmap\n"
3234c13a3ff475f206c4d0a86ee2595c45392fd942fMathieu Chartier      << heap_->DumpSpaces();
32458551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro}
32558551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro
326ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartiervoid MarkSweep::ExpandMarkStack() {
327ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartier  ResizeMarkStack(mark_stack_->Capacity() * 2);
328ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartier}
329ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartier
330ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartiervoid MarkSweep::ResizeMarkStack(size_t new_size) {
331ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier  // Rare case, no need to have Thread::Current be a parameter.
332ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier  if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
333ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier    // Someone else acquired the lock and expanded the mark stack before us.
334ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier    return;
335ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier  }
336cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier  std::vector<StackReference<Object>> temp(mark_stack_->Begin(), mark_stack_->End());
337ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartier  CHECK_LE(mark_stack_->Size(), new_size);
338ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartier  mark_stack_->Resize(new_size);
339cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier  for (auto& obj : temp) {
340cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier    mark_stack_->PushBack(obj.AsMirrorPtr());
341ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier  }
342ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier}
343ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier
3440e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartierinline void MarkSweep::MarkObjectNonNullParallel(Object* obj) {
345bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  DCHECK(obj != nullptr);
346ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier  if (MarkObjectParallel(obj)) {
347ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartier    MutexLock mu(Thread::Current(), mark_stack_lock_);
348ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartier    if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
349184e322fe8ddd75c844a1eb2eb1ca32bc02f2d45Mathieu Chartier      ExpandMarkStack();
350ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier    }
351ba311b4385fa3f382f01312a8cc97b52011232e3Mathieu Chartier    // The object must be pushed on to the mark stack.
3520e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    mark_stack_->PushBack(obj);
353ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier  }
354ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier}
355ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier
3563bb57c7b41bf5419fe895e7aa664d8d430205ba8Mathieu Chartiermirror::Object* MarkSweep::MarkObjectCallback(mirror::Object* obj, void* arg) {
35739e3261168e7761fea6d873494d7c5d191285791Mathieu Chartier  MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
35839e3261168e7761fea6d873494d7c5d191285791Mathieu Chartier  mark_sweep->MarkObject(obj);
35939e3261168e7761fea6d873494d7c5d191285791Mathieu Chartier  return obj;
36039e3261168e7761fea6d873494d7c5d191285791Mathieu Chartier}
36139e3261168e7761fea6d873494d7c5d191285791Mathieu Chartier
362407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartiervoid MarkSweep::MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) {
363407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  reinterpret_cast<MarkSweep*>(arg)->MarkObject(ref->AsMirrorPtr());
364407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier}
365407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier
366308351ada0008b0cbe1a5afc31c302c975554ee4Mathieu Chartierbool MarkSweep::HeapReferenceMarkedCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) {
367308351ada0008b0cbe1a5afc31c302c975554ee4Mathieu Chartier  return reinterpret_cast<MarkSweep*>(arg)->IsMarked(ref->AsMirrorPtr());
368308351ada0008b0cbe1a5afc31c302c975554ee4Mathieu Chartier}
369308351ada0008b0cbe1a5afc31c302c975554ee4Mathieu Chartier
370bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartierclass MarkSweepMarkObjectSlowPath {
371bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier public:
372eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi  explicit MarkSweepMarkObjectSlowPath(MarkSweep* mark_sweep, Object* holder = nullptr,
373eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi                                       MemberOffset offset = MemberOffset(0))
374eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi      : mark_sweep_(mark_sweep), holder_(holder), offset_(offset) {
375bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  }
376bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier
377d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi  void operator()(const Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
378bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    if (kProfileLargeObjects) {
379bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      // TODO: Differentiate between marking and testing somehow.
380bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      ++mark_sweep_->large_object_test_;
381bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      ++mark_sweep_->large_object_mark_;
382bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    }
383bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    space::LargeObjectSpace* large_object_space = mark_sweep_->GetHeap()->GetLargeObjectsSpace();
384a17288e3b9dd6751005fed3386251d2d0949be74Mathieu Chartier    if (UNLIKELY(obj == nullptr || !IsAligned<kPageSize>(obj) ||
3852dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier                 (kIsDebugBuild && large_object_space != nullptr &&
3862dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier                     !large_object_space->Contains(obj)))) {
387175746ac9039e9b741d3521420dcaa9c59341738Mathieu Chartier      LOG(INTERNAL_FATAL) << "Tried to mark " << obj << " not contained by any spaces";
388eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi      if (holder_ != nullptr) {
389d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi        size_t holder_size = holder_->SizeOf();
390eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi        ArtField* field = holder_->FindFieldByOffset(offset_);
391d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi        LOG(INTERNAL_FATAL) << "Field info: "
392d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << " holder=" << holder_
393679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi                            << " holder is "
394679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi                            << (mark_sweep_->GetHeap()->IsLiveObjectLocked(holder_)
395679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi                                ? "alive" : "dead")
396d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << " holder_size=" << holder_size
397eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi                            << " holder_type=" << PrettyTypeOf(holder_)
398eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi                            << " offset=" << offset_.Uint32Value()
399d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << " field=" << (field != nullptr ? field->GetName() : "nullptr")
400d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << " field_type="
401d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << (field != nullptr ? field->GetTypeDescriptor() : "")
402d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << " first_ref_field_offset="
403d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << (holder_->IsClass()
404e401d146407d61eeb99f8d6176b2ac13c4df1e33Mathieu Chartier                                ? holder_->AsClass()->GetFirstReferenceStaticFieldOffset(
405e401d146407d61eeb99f8d6176b2ac13c4df1e33Mathieu Chartier                                    sizeof(void*))
406d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                                : holder_->GetClass()->GetFirstReferenceInstanceFieldOffset())
407d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << " num_of_ref_fields="
408d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << (holder_->IsClass()
409d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                                ? holder_->AsClass()->NumReferenceStaticFields()
410d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                                : holder_->GetClass()->NumReferenceInstanceFields())
411d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi                            << "\n";
412679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi        // Print the memory content of the holder.
413679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi        for (size_t i = 0; i < holder_size / sizeof(uint32_t); ++i) {
414679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi          uint32_t* p = reinterpret_cast<uint32_t*>(holder_);
415679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi          LOG(INTERNAL_FATAL) << &p[i] << ": " << "holder+" << (i * sizeof(uint32_t)) << " = "
416679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi                              << std::hex << p[i];
417679b1cf291f364dcc3a142f53a07b0ad15c01e9aHiroshi Yamauchi        }
418eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi      }
419d38ec80b163af1639fbaae382a319c73be67c560Hiroshi Yamauchi      PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
42017a924abde2b0f1f37f6008b451a0a75190c71ffVladimir Marko      MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
421d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi      {
422d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi        LOG(INTERNAL_FATAL) << "Attempting see if it's a bad root";
423d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi        Thread* self = Thread::Current();
424d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi        if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
425d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          mark_sweep_->VerifyRoots();
426d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi        } else {
427d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          const bool heap_bitmap_exclusive_locked =
428d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi              Locks::heap_bitmap_lock_->IsExclusiveHeld(self);
429d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          if (heap_bitmap_exclusive_locked) {
430d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi            Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
431d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          }
432d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          Locks::mutator_lock_->SharedUnlock(self);
433d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          ThreadList* tl = Runtime::Current()->GetThreadList();
434d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          tl->SuspendAll(__FUNCTION__);
435d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          mark_sweep_->VerifyRoots();
436d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          tl->ResumeAll();
437d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          Locks::mutator_lock_->SharedLock(self);
438d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          if (heap_bitmap_exclusive_locked) {
439d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi            Locks::heap_bitmap_lock_->ExclusiveLock(self);
440d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi          }
441d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi        }
442d0c8412c3b87317074e8e809198207cd75ee73c4Hiroshi Yamauchi      }
443bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      LOG(FATAL) << "Can't mark invalid object";
444bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    }
445bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  }
446bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier
447bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier private:
448bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  MarkSweep* const mark_sweep_;
449eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi  mirror::Object* const holder_;
450eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi  MemberOffset offset_;
451bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier};
452bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier
453eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchiinline void MarkSweep::MarkObjectNonNull(Object* obj, Object* holder, MemberOffset offset) {
4540e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  DCHECK(obj != nullptr);
455624468cd401cc1ac0dd70c746301e0788a597759Hiroshi Yamauchi  if (kUseBakerOrBrooksReadBarrier) {
456624468cd401cc1ac0dd70c746301e0788a597759Hiroshi Yamauchi    // Verify all the objects have the correct pointer installed.
457624468cd401cc1ac0dd70c746301e0788a597759Hiroshi Yamauchi    obj->AssertReadBarrierPointer();
4589d04a20bde1b1855cefc64aebc1a44e253b1a13bHiroshi Yamauchi  }
4598d562103c3a3452fb15ef4b1c64df767b70507a4Mathieu Chartier  if (immune_region_.ContainsObject(obj)) {
4600e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    if (kCountMarkedObjects) {
4610e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier      ++mark_immune_count_;
4620e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    }
463bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    DCHECK(mark_bitmap_->Test(obj));
464bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
465bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    if (kCountMarkedObjects) {
466bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      ++mark_fastpath_count_;
467bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    }
468bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
469bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      PushOnMarkStack(obj);  // This object was not previously marked.
470bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    }
471bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  } else {
4720e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    if (kCountMarkedObjects) {
4730e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier      ++mark_slowpath_count_;
4740e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    }
475eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi    MarkSweepMarkObjectSlowPath visitor(this, holder, offset);
476bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
477bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    // will check again.
478bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    if (!mark_bitmap_->Set(obj, visitor)) {
479bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier      PushOnMarkStack(obj);  // Was not already marked, push.
480357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier    }
4810e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  }
4820e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier}
4830e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier
4840e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartierinline void MarkSweep::PushOnMarkStack(Object* obj) {
4850e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
4860e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    // Lock is not needed but is here anyways to please annotalysis.
4870e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    MutexLock mu(Thread::Current(), mark_stack_lock_);
4880e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    ExpandMarkStack();
48969759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro  }
4900e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  // The object must be pushed on to the mark stack.
4910e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  mark_stack_->PushBack(obj);
49269759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}
49369759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
49402b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartierinline bool MarkSweep::MarkObjectParallel(const Object* obj) {
4950e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  DCHECK(obj != nullptr);
496624468cd401cc1ac0dd70c746301e0788a597759Hiroshi Yamauchi  if (kUseBakerOrBrooksReadBarrier) {
497624468cd401cc1ac0dd70c746301e0788a597759Hiroshi Yamauchi    // Verify all the objects have the correct pointer installed.
498624468cd401cc1ac0dd70c746301e0788a597759Hiroshi Yamauchi    obj->AssertReadBarrierPointer();
4999d04a20bde1b1855cefc64aebc1a44e253b1a13bHiroshi Yamauchi  }
5008d562103c3a3452fb15ef4b1c64df767b70507a4Mathieu Chartier  if (immune_region_.ContainsObject(obj)) {
50102b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier    DCHECK(IsMarked(obj));
50202b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier    return false;
50302b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
50402b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  // Try to take advantage of locality of references within a space, failing this find the space
50502b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  // the hard way.
506a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier  accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
507bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  if (LIKELY(object_bitmap->HasAddress(obj))) {
508bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    return !object_bitmap->AtomicTestAndSet(obj);
50902b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
510bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  MarkSweepMarkObjectSlowPath visitor(this);
511bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
51202b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier}
51302b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier
5140e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier// Used to mark objects when processing the mark stack. If an object is null, it is not marked.
515eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchiinline void MarkSweep::MarkObject(Object* obj, Object* holder, MemberOffset offset) {
5160e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  if (obj != nullptr) {
517eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi    MarkObjectNonNull(obj, holder, offset);
5180e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  } else if (kCountMarkedObjects) {
5190e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    ++mark_null_count_;
52069759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro  }
52169759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}
52269759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
523bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartierclass VerifyRootMarkedVisitor : public SingleRootVisitor {
524bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier public:
525bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  explicit VerifyRootMarkedVisitor(MarkSweep* collector) : collector_(collector) { }
526ac86a7cad60c20a131011338057887bb64cbfd38Mathieu Chartier
527bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
528bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
529bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    CHECK(collector_->IsMarked(root)) << info.ToString();
530bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  }
531bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier
532bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier private:
533bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  MarkSweep* const collector_;
534bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier};
535893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier
536bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartiervoid MarkSweep::VisitRoots(mirror::Object*** roots, size_t count,
537bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier                           const RootInfo& info ATTRIBUTE_UNUSED) {
538bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  for (size_t i = 0; i < count; ++i) {
539bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    MarkObjectNonNull(*roots[i]);
540bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  }
541815873ecc312b1d231acce71e1a16f42cdaf09f2Mathieu Chartier}
542815873ecc312b1d231acce71e1a16f42cdaf09f2Mathieu Chartier
543bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartiervoid MarkSweep::VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
544bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier                           const RootInfo& info ATTRIBUTE_UNUSED) {
545bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  for (size_t i = 0; i < count; ++i) {
546bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    MarkObjectNonNull(roots[i]->AsMirrorPtr());
547bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  }
5486f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartier}
5496f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartier
550bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartierclass VerifyRootVisitor : public SingleRootVisitor {
551bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier public:
552bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
553bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
5549086b65b2ad35dd39a8afc62d535be8217208d08Mathieu Chartier    // See if the root is on any space bitmap.
5559086b65b2ad35dd39a8afc62d535be8217208d08Mathieu Chartier    auto* heap = Runtime::Current()->GetHeap();
5569086b65b2ad35dd39a8afc62d535be8217208d08Mathieu Chartier    if (heap->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
5579086b65b2ad35dd39a8afc62d535be8217208d08Mathieu Chartier      space::LargeObjectSpace* large_object_space = heap->GetLargeObjectsSpace();
5589086b65b2ad35dd39a8afc62d535be8217208d08Mathieu Chartier      if (large_object_space != nullptr && !large_object_space->Contains(root)) {
559175746ac9039e9b741d3521420dcaa9c59341738Mathieu Chartier        LOG(INTERNAL_FATAL) << "Found invalid root: " << root << " " << info;
5609086b65b2ad35dd39a8afc62d535be8217208d08Mathieu Chartier      }
5616f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartier    }
5626f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartier  }
5639086b65b2ad35dd39a8afc62d535be8217208d08Mathieu Chartier};
5646f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartier
5656f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartiervoid MarkSweep::VerifyRoots() {
5669086b65b2ad35dd39a8afc62d535be8217208d08Mathieu Chartier  VerifyRootVisitor visitor;
567bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  Runtime::Current()->GetThreadList()->VisitRoots(&visitor);
5686f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartier}
5696f1c94968ada57da433debf8e2d1b38a80ceb510Mathieu Chartier
570893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartiervoid MarkSweep::MarkRoots(Thread* self) {
571f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
572893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier  if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
573893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier    // If we exclusively hold the mutator lock, all threads must be suspended.
574bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    Runtime::Current()->VisitRoots(this);
575893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier    RevokeAllThreadLocalAllocationStacks(self);
576893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier  } else {
5770f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier    MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
578893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier    // At this point the live stack should no longer have any mutators which push into it.
579893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier    MarkNonThreadRoots();
580893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier    MarkConcurrentRoots(
581893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier        static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
582893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier  }
5839ebae1f30b84dfd8dab4144f80eebec4f8fc8851Mathieu Chartier}
5849ebae1f30b84dfd8dab4144f80eebec4f8fc8851Mathieu Chartier
585858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartiervoid MarkSweep::MarkNonThreadRoots() {
586f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
587bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  Runtime::Current()->VisitNonThreadRoots(this);
588858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier}
589858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier
590893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartiervoid MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
591f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
5921d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  // Visit all runtime roots and clear dirty flags.
593bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  Runtime::Current()->VisitConcurrentRoots(this, flags);
59469759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}
59569759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
59602b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartierclass ScanObjectVisitor {
597cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier public:
59894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
59994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      : mark_sweep_(mark_sweep) {}
600cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier
601407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  void operator()(Object* obj) const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
602407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
60394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    if (kCheckLocks) {
6042b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier      Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
6052b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier      Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
6062b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    }
60702b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier    mark_sweep_->ScanObject(obj);
608cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier  }
609cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier
610cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier private:
611cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier  MarkSweep* const mark_sweep_;
612cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier};
613cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier
614407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartierclass DelayReferenceReferentVisitor {
615407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier public:
616407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {
617407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  }
618407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier
619407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  void operator()(mirror::Class* klass, mirror::Reference* ref) const
620407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
621407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
622407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier    collector_->DelayReferenceReferent(klass, ref);
623407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  }
624407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier
625407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier private:
626407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  MarkSweep* const collector_;
627407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier};
628407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier
62994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartiertemplate <bool kUseFinger = false>
63094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartierclass MarkStackTask : public Task {
63194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier public:
63294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
633cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier                StackReference<Object>* mark_stack)
63494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      : mark_sweep_(mark_sweep),
63594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        thread_pool_(thread_pool),
63694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        mark_stack_pos_(mark_stack_size) {
63794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // We may have to copy part of an existing mark stack when another mark stack overflows.
63894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    if (mark_stack_size != 0) {
6392cebb24bfc3247d3e9be138a3350106737455918Mathieu Chartier      DCHECK(mark_stack != nullptr);
64094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      // TODO: Check performance?
64194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
64294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    }
64394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    if (kCountTasks) {
64494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      ++mark_sweep_->work_chunks_created_;
6451d54e73444e017d3a65234e0f193846f3e27472bIan Rogers    }
646262e5ffa1d4b23f23af3dea762a71a0af4bfd4a9Mathieu Chartier  }
647262e5ffa1d4b23f23af3dea762a71a0af4bfd4a9Mathieu Chartier
64894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  static const size_t kMaxSize = 1 * KB;
649cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier
65094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier protected:
651407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  class MarkObjectParallelVisitor {
652407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier   public:
653407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier    explicit MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
654407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier                                       MarkSweep* mark_sweep) ALWAYS_INLINE
655407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier            : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
656407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier
657407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier    void operator()(Object* obj, MemberOffset offset, bool /* static */) const ALWAYS_INLINE
658407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier        SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
659b0fa5dc7769c1e054032f39de0a3f6d6dd06f8cfIan Rogers      mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
660407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
661407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier        if (kUseFinger) {
662c7df66e2cb124d261cf3b0691a09a3b6e357b6f1Yabin Cui          std::atomic_thread_fence(std::memory_order_seq_cst);
663407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier          if (reinterpret_cast<uintptr_t>(ref) >=
6643e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers              static_cast<uintptr_t>(mark_sweep_->atomic_finger_.LoadRelaxed())) {
665407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier            return;
666407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier          }
667407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier        }
668407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier        chunk_task_->MarkStackPush(ref);
669407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      }
670407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier    }
671407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier
672407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier   private:
673407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier    MarkStackTask<kUseFinger>* const chunk_task_;
674407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier    MarkSweep* const mark_sweep_;
675407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  };
676407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier
67794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  class ScanObjectParallelVisitor {
67894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier   public:
67994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
68094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        : chunk_task_(chunk_task) {}
68194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
682407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier    // No thread safety analysis since multiple threads will use this visitor.
683407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier    void operator()(Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
684407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier        EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
685407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
686407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
687407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      DelayReferenceReferentVisitor ref_visitor(mark_sweep);
688407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
68994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    }
69094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
69194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier   private:
69294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    MarkStackTask<kUseFinger>* const chunk_task_;
69394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  };
69494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
69594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  virtual ~MarkStackTask() {
69694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // Make sure that we have cleared our mark stack.
69794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    DCHECK_EQ(mark_stack_pos_, 0U);
69894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    if (kCountTasks) {
69994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      ++mark_sweep_->work_chunks_deleted_;
7002b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    }
701cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier  }
702cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier
70394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  MarkSweep* const mark_sweep_;
70494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  ThreadPool* const thread_pool_;
70594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  // Thread local mark stack for this task.
706cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier  StackReference<Object> mark_stack_[kMaxSize];
70794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  // Mark stack position.
70894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  size_t mark_stack_pos_;
70994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
710cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier  ALWAYS_INLINE void MarkStackPush(Object* obj) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
71194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
71294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
71394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      mark_stack_pos_ /= 2;
71494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
71594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier                                     mark_stack_ + mark_stack_pos_);
71694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      thread_pool_->AddTask(Thread::Current(), task);
71794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    }
71894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    DCHECK(obj != nullptr);
7190e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    DCHECK_LT(mark_stack_pos_, kMaxSize);
720cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier    mark_stack_[mark_stack_pos_++].Assign(obj);
72194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
72294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
72394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  virtual void Finalize() {
72494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    delete this;
72594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
72694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
72794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  // Scans all of the objects
728407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  virtual void Run(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
729407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
7306a3c1fcb4ba42ad4d5d142c17a3712a6ddd3866fIan Rogers    UNUSED(self);
73194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    ScanObjectParallelVisitor visitor(this);
73294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // TODO: Tune this.
73394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    static const size_t kFifoSize = 4;
7340e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
73594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    for (;;) {
7360e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier      Object* obj = nullptr;
73794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      if (kUseMarkStackPrefetch) {
73894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
739cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier          Object* const mark_stack_obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
740277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe          DCHECK(mark_stack_obj != nullptr);
741277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe          __builtin_prefetch(mark_stack_obj);
742277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe          prefetch_fifo.push_back(mark_stack_obj);
74394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        }
74494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        if (UNLIKELY(prefetch_fifo.empty())) {
74594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          break;
74694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        }
74794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        obj = prefetch_fifo.front();
74894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        prefetch_fifo.pop_front();
74994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      } else {
75094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        if (UNLIKELY(mark_stack_pos_ == 0)) {
75194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          break;
75294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        }
753cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier        obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
75494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      }
75511409ae81a3eaf84d7fd2b3c85b8b06d2bae27f0Mathieu Chartier      DCHECK(obj != nullptr);
7560e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier      visitor(obj);
75794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    }
75894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
75994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier};
76094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
76194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartierclass CardScanTask : public MarkStackTask<false> {
76294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier public:
763a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier  CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
764a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier               accounting::ContinuousSpaceBitmap* bitmap,
76513735955f39b3b304c37d2b2840663c131262c18Ian Rogers               uint8_t* begin, uint8_t* end, uint8_t minimum_age, size_t mark_stack_size,
766cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier               StackReference<Object>* mark_stack_obj, bool clear_card)
76794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
76894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        bitmap_(bitmap),
76994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        begin_(begin),
77094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        end_(end),
771727b294b4091cf3cc2f8137cd654552f477fe46aLei Li        minimum_age_(minimum_age), clear_card_(clear_card) {
77294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
77394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
77494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier protected:
775a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier  accounting::ContinuousSpaceBitmap* const bitmap_;
77613735955f39b3b304c37d2b2840663c131262c18Ian Rogers  uint8_t* const begin_;
77713735955f39b3b304c37d2b2840663c131262c18Ian Rogers  uint8_t* const end_;
77813735955f39b3b304c37d2b2840663c131262c18Ian Rogers  const uint8_t minimum_age_;
779727b294b4091cf3cc2f8137cd654552f477fe46aLei Li  const bool clear_card_;
78094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
78194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  virtual void Finalize() {
78294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    delete this;
78394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
78494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
78594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
78694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    ScanObjectParallelVisitor visitor(this);
78794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
788727b294b4091cf3cc2f8137cd654552f477fe46aLei Li    size_t cards_scanned = clear_card_ ?
789727b294b4091cf3cc2f8137cd654552f477fe46aLei Li                           card_table->Scan<true>(bitmap_, begin_, end_, visitor, minimum_age_) :
790727b294b4091cf3cc2f8137cd654552f477fe46aLei Li                           card_table->Scan<false>(bitmap_, begin_, end_, visitor, minimum_age_);
7910f72e4136aecaf6976fdb55916bbd7b6d5c9c77bMathieu Chartier    VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
7920f72e4136aecaf6976fdb55916bbd7b6d5c9c77bMathieu Chartier        << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
79394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // Finish by emptying our local mark stack.
79494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    MarkStackTask::Run(self);
79594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
796cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier};
797cc236d74772dda5a4161d9bc5f497fd3d956eb87Mathieu Chartier
7982775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartiersize_t MarkSweep::GetThreadCount(bool paused) const {
7992775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
800bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier    return 1;
8012775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  }
80210d6886c9ce3ed87431cf10d376a69c23950fa61Mathieu Chartier  return (paused ? heap_->GetParallelGCThreadCount() : heap_->GetConcGCThreadCount()) + 1;
8032775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier}
8042775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier
80513735955f39b3b304c37d2b2840663c131262c18Ian Rogersvoid MarkSweep::ScanGrayObjects(bool paused, uint8_t minimum_age) {
80694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  accounting::CardTable* card_table = GetHeap()->GetCardTable();
80794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  ThreadPool* thread_pool = GetHeap()->GetThreadPool();
8082775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  size_t thread_count = GetThreadCount(paused);
8092775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  // The parallel version with only one thread is faster for card scanning, TODO: fix.
810bbd695c71e0bf518f582e84524e1cdeb3de3896cMathieu Chartier  if (kParallelCardScan && thread_count > 1) {
811720ef7680573c1afd12f99f02eee3045daee5168Mathieu Chartier    Thread* self = Thread::Current();
81294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // Can't have a different split for each space since multiple spaces can have their cards being
81394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // scanned at the same time.
814f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    TimingLogger::ScopedTiming t(paused ? "(Paused)ScanGrayObjects" : __FUNCTION__,
815f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier        GetTimings());
81694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // Try to take some of the mark stack since we can pass this off to the worker tasks.
817cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier    StackReference<Object>* mark_stack_begin = mark_stack_->Begin();
818cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier    StackReference<Object>* mark_stack_end = mark_stack_->End();
819720ef7680573c1afd12f99f02eee3045daee5168Mathieu Chartier    const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
82094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // Estimated number of work tasks we will create.
82194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
82294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    DCHECK_NE(mark_stack_tasks, 0U);
82394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
82494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier                                             mark_stack_size / mark_stack_tasks + 1);
82594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
826590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      if (space->GetMarkBitmap() == nullptr) {
827590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        continue;
828590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
82913735955f39b3b304c37d2b2840663c131262c18Ian Rogers      uint8_t* card_begin = space->Begin();
83013735955f39b3b304c37d2b2840663c131262c18Ian Rogers      uint8_t* card_end = space->End();
8310941b0423537a6a5d7c1df6dd23e9864ea8f319cHiroshi Yamauchi      // Align up the end address. For example, the image space's end
8320941b0423537a6a5d7c1df6dd23e9864ea8f319cHiroshi Yamauchi      // may not be card-size-aligned.
8330941b0423537a6a5d7c1df6dd23e9864ea8f319cHiroshi Yamauchi      card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
8340941b0423537a6a5d7c1df6dd23e9864ea8f319cHiroshi Yamauchi      DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin));
8350941b0423537a6a5d7c1df6dd23e9864ea8f319cHiroshi Yamauchi      DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end));
83694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      // Calculate how many bytes of heap we will scan,
83794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      const size_t address_range = card_end - card_begin;
83894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      // Calculate how much address range each task gets.
83994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      const size_t card_delta = RoundUp(address_range / thread_count + 1,
84094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier                                        accounting::CardTable::kCardSize);
841727b294b4091cf3cc2f8137cd654552f477fe46aLei Li      // If paused and the space is neither zygote nor image space, we could clear the dirty
842727b294b4091cf3cc2f8137cd654552f477fe46aLei Li      // cards to avoid accumulating them to increase card scanning load in the following GC
843727b294b4091cf3cc2f8137cd654552f477fe46aLei Li      // cycles. We need to keep dirty cards of image space and zygote space in order to track
844727b294b4091cf3cc2f8137cd654552f477fe46aLei Li      // references to the other spaces.
845727b294b4091cf3cc2f8137cd654552f477fe46aLei Li      bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
84694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      // Create the worker tasks for this space.
84794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      while (card_begin != card_end) {
84894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        // Add a range of cards.
84994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        size_t addr_remaining = card_end - card_begin;
85094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        size_t card_increment = std::min(card_delta, addr_remaining);
85194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        // Take from the back of the mark stack.
85294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
85394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
85494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        mark_stack_end -= mark_stack_increment;
85594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
8560e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier        DCHECK_EQ(mark_stack_end, mark_stack_->End());
85794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        // Add the new task to the thread pool.
85894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
85994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier                                      card_begin + card_increment, minimum_age,
860727b294b4091cf3cc2f8137cd654552f477fe46aLei Li                                      mark_stack_increment, mark_stack_end, clear_card);
86194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        thread_pool->AddTask(self, task);
86294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        card_begin += card_increment;
86394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      }
86494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    }
8650f72e4136aecaf6976fdb55916bbd7b6d5c9c77bMathieu Chartier
8660941b0423537a6a5d7c1df6dd23e9864ea8f319cHiroshi Yamauchi    // Note: the card scan below may dirty new cards (and scan them)
8670941b0423537a6a5d7c1df6dd23e9864ea8f319cHiroshi Yamauchi    // as a side effect when a Reference object is encountered and
8680941b0423537a6a5d7c1df6dd23e9864ea8f319cHiroshi Yamauchi    // queued during the marking. See b/11465268.
8692775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier    thread_pool->SetMaxActiveWorkers(thread_count - 1);
87094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    thread_pool->StartWorkers(self);
8712775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier    thread_pool->Wait(self, true, true);
87294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    thread_pool->StopWorkers(self);
87394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  } else {
87494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
875590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      if (space->GetMarkBitmap() != nullptr) {
876590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        // Image spaces are handled properly since live == marked for them.
877f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier        const char* name = nullptr;
878590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        switch (space->GetGcRetentionPolicy()) {
879f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier        case space::kGcRetentionPolicyNeverCollect:
880f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier          name = paused ? "(Paused)ScanGrayImageSpaceObjects" : "ScanGrayImageSpaceObjects";
881f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier          break;
882f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier        case space::kGcRetentionPolicyFullCollect:
883f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier          name = paused ? "(Paused)ScanGrayZygoteSpaceObjects" : "ScanGrayZygoteSpaceObjects";
884f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier          break;
885f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier        case space::kGcRetentionPolicyAlwaysCollect:
886f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier          name = paused ? "(Paused)ScanGrayAllocSpaceObjects" : "ScanGrayAllocSpaceObjects";
887f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier          break;
888f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier        default:
889f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier          LOG(FATAL) << "Unreachable";
8902c4257be8191c5eefde744e8965fcefc80a0a97dIan Rogers          UNREACHABLE();
891f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier        }
892f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier        TimingLogger::ScopedTiming t(name, GetTimings());
893590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier        ScanObjectVisitor visitor(this);
894727b294b4091cf3cc2f8137cd654552f477fe46aLei Li        bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
895727b294b4091cf3cc2f8137cd654552f477fe46aLei Li        if (clear_card) {
896727b294b4091cf3cc2f8137cd654552f477fe46aLei Li          card_table->Scan<true>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor,
897727b294b4091cf3cc2f8137cd654552f477fe46aLei Li                                 minimum_age);
898727b294b4091cf3cc2f8137cd654552f477fe46aLei Li        } else {
899727b294b4091cf3cc2f8137cd654552f477fe46aLei Li          card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor,
900727b294b4091cf3cc2f8137cd654552f477fe46aLei Li                                  minimum_age);
901727b294b4091cf3cc2f8137cd654552f477fe46aLei Li        }
902590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier      }
90394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    }
90494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
90594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier}
90694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
90794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartierclass RecursiveMarkTask : public MarkStackTask<false> {
90894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier public:
90994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
910a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier                    accounting::ContinuousSpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
9112cebb24bfc3247d3e9be138a3350106737455918Mathieu Chartier      : MarkStackTask<false>(thread_pool, mark_sweep, 0, nullptr), bitmap_(bitmap), begin_(begin),
91294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        end_(end) {
91394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
91494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
91594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier protected:
916a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier  accounting::ContinuousSpaceBitmap* const bitmap_;
91794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  const uintptr_t begin_;
91894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  const uintptr_t end_;
91994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
92094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  virtual void Finalize() {
92194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    delete this;
92294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
92394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
92494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  // Scans all of the objects
92594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
92694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    ScanObjectParallelVisitor visitor(this);
92794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    bitmap_->VisitMarkedRange(begin_, end_, visitor);
92894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // Finish by emptying our local mark stack.
92994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    MarkStackTask::Run(self);
93094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  }
93194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier};
93294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
93358551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro// Populates the mark stack based on the set of marked objects and
93458551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro// recursively marks until the mark stack is emptied.
9352b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartiervoid MarkSweep::RecursiveMark() {
936f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
937a1602f28c0e3127ad511712d4b08db89737ae901Mathieu Chartier  // RecursiveMark will build the lists of known instances of the Reference classes. See
938a1602f28c0e3127ad511712d4b08db89737ae901Mathieu Chartier  // DelayReferenceReferent for details.
93994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  if (kUseRecursiveMark) {
94094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    const bool partial = GetGcType() == kGcTypePartial;
94194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    ScanObjectVisitor scan_visitor(this);
94294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    auto* self = Thread::Current();
94394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    ThreadPool* thread_pool = heap_->GetThreadPool();
9442775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier    size_t thread_count = GetThreadCount(false);
9452775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier    const bool parallel = kParallelRecursiveMark && thread_count > 1;
94694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    mark_stack_->Reset();
94702e25119b15a6f619f17db99f5d05124a5807ff3Mathieu Chartier    for (const auto& space : GetHeap()->GetContinuousSpaces()) {
9481d54e73444e017d3a65234e0f193846f3e27472bIan Rogers      if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
9491d54e73444e017d3a65234e0f193846f3e27472bIan Rogers          (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
9500e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier        current_space_bitmap_ = space->GetMarkBitmap();
9510e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier        if (current_space_bitmap_ == nullptr) {
952590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier          continue;
9532b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier        }
95494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        if (parallel) {
95594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          // We will use the mark stack the future.
95694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          // CHECK(mark_stack_->IsEmpty());
95794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          // This function does not handle heap end increasing, so we must use the space end.
95894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
95994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
9603e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers          atomic_finger_.StoreRelaxed(AtomicInteger::MaxValue());
96194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier
96294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          // Create a few worker tasks.
9632775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier          const size_t n = thread_count * 2;
96494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          while (begin != end) {
96594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier            uintptr_t start = begin;
96694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier            uintptr_t delta = (end - begin) / n;
96794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier            delta = RoundUp(delta, KB);
96894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier            if (delta < 16 * KB) delta = end - begin;
96994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier            begin += delta;
9700e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier            auto* task = new RecursiveMarkTask(thread_pool, this, current_space_bitmap_, start,
97194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier                                               begin);
97294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier            thread_pool->AddTask(self, task);
97394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          }
9742775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier          thread_pool->SetMaxActiveWorkers(thread_count - 1);
97594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          thread_pool->StartWorkers(self);
9762775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier          thread_pool->Wait(self, true, true);
97794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          thread_pool->StopWorkers(self);
97894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        } else {
97994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          // This function does not handle heap end increasing, so we must use the space end.
98094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
98194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
9820e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier          current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
98394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        }
984357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier      }
985357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier    }
986357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier  }
98794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  ProcessMarkStack(false);
98858551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro}
98958551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro
99083c8ee000d525017ead8753fce6bc1020249b96aMathieu Chartiermirror::Object* MarkSweep::IsMarkedCallback(mirror::Object* object, void* arg) {
9915712d5d04640925970db9c98938ffaf806b3962cMathieu Chartier  if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
9926aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier    return object;
9936aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier  }
9946aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier  return nullptr;
995357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier}
996357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier
99713735955f39b3b304c37d2b2840663c131262c18Ian Rogersvoid MarkSweep::RecursiveMarkDirtyObjects(bool paused, uint8_t minimum_age) {
99894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  ScanGrayObjects(paused, minimum_age);
99994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  ProcessMarkStack(paused);
1000262e5ffa1d4b23f23af3dea762a71a0af4bfd4a9Mathieu Chartier}
1001262e5ffa1d4b23f23af3dea762a71a0af4bfd4a9Mathieu Chartier
100258551df3c2646ed507feec9e9eb3768085a76059Carl Shapirovoid MarkSweep::ReMarkRoots() {
1003f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1004893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier  Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
1005bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  Runtime::Current()->VisitRoots(this, static_cast<VisitRootFlags>(
1006bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      kVisitRootFlagNewRoots | kVisitRootFlagStopLoggingNewRoots | kVisitRootFlagClearRootLog));
10077bf9f190cd33a7e2f8584299eb889e9df66e0323Mathieu Chartier  if (kVerifyRootsMarked) {
1008277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe    TimingLogger::ScopedTiming t2("(Paused)VerifyRoots", GetTimings());
1009bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    VerifyRootMarkedVisitor visitor(this);
1010bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    Runtime::Current()->VisitRoots(&visitor);
1011893263b7d5bc2ca43a91ecb8071867f5134fc60aMathieu Chartier  }
101258551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro}
101358551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro
10140f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartiervoid MarkSweep::SweepSystemWeaks(Thread* self) {
1015f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
10160f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
10170f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this);
101869759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}
101969759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
10206aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartiermirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
1021c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier  reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
1022c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier  // We don't actually want to sweep the object, so lets return "marked"
10236aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier  return obj;
1024c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier}
1025c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier
1026c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartiervoid MarkSweep::VerifyIsLive(const Object* obj) {
10274aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  if (!heap_->GetLiveBitmap()->Test(obj)) {
1028cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier    // TODO: Consider live stack? Has this code bitrotted?
1029cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier    CHECK(!heap_->allocation_stack_->Contains(obj))
1030cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier        << "Found dead object " << obj << "\n" << heap_->DumpSpaces();
1031c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier  }
1032c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier}
1033c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier
1034c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartiervoid MarkSweep::VerifySystemWeaks() {
1035f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
10366aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier  // Verify system weaks, uses a special object visitor which returns the input object.
10376aa3df965395566ed6a4fec4af37c2b7577992e9Mathieu Chartier  Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
1038c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier}
1039c7b83a0d8ac73bdfff751619ae2a34948e3534b7Mathieu Chartier
1040bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartierclass CheckpointMarkThreadRoots : public Closure, public RootVisitor {
1041858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier public:
10420f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
10430f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier                                     bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
10440f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier      : mark_sweep_(mark_sweep),
10450f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier        revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
10460f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier            revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
10470f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  }
1048858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier
1049bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
1050bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1051bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1052bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    for (size_t i = 0; i < count; ++i) {
1053bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      mark_sweep_->MarkObjectNonNullParallel(*roots[i]);
1054bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    }
1055bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  }
1056bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier
1057bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1058bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier                  const RootInfo& info ATTRIBUTE_UNUSED)
1059bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1060bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1061bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    for (size_t i = 0; i < count; ++i) {
1062bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier      mark_sweep_->MarkObjectNonNullParallel(roots[i]->AsMirrorPtr());
1063bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    }
1064bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier  }
1065bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier
10664aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
10673f9667022788ba1effcd1e47fc9e3decc4db569dMathieu Chartier    ATRACE_BEGIN("Marking thread roots");
1068858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier    // Note: self is not necessarily equal to thread since thread may be suspended.
1069bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    Thread* const self = Thread::Current();
1070d22d54849c96760aa1efa259d6dcfbace54da2afMathieu Chartier    CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1071d22d54849c96760aa1efa259d6dcfbace54da2afMathieu Chartier        << thread->GetState() << " thread " << thread << " self " << self;
1072bb87e0f1a52de656bc77cb01cb887e51a0e5198bMathieu Chartier    thread->VisitRoots(this);
10733f9667022788ba1effcd1e47fc9e3decc4db569dMathieu Chartier    ATRACE_END();
10740f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier    if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
10750f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier      ATRACE_BEGIN("RevokeRosAllocThreadLocalBuffers");
1076c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi      mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
10770f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier      ATRACE_END();
1078c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi    }
1079dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li    // If thread is a running mutator, then act on behalf of the garbage collector.
1080dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li    // See the code in ThreadList::RunCheckpoint.
1081dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li    if (thread->GetState() == kRunnable) {
1082dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li      mark_sweep_->GetBarrier().Pass(self);
1083dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li    }
1084858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier  }
1085858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier
1086858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier private:
10874aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  MarkSweep* const mark_sweep_;
10880f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
1089858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier};
1090858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier
10910f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartiervoid MarkSweep::MarkRootsCheckpoint(Thread* self,
10920f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier                                    bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1093f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
10940f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
1095858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier  ThreadList* thread_list = Runtime::Current()->GetThreadList();
10961d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  // Request the check point is run on all threads returning a count of the threads that must
10971d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  // run through the barrier including self.
10981d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  size_t barrier_count = thread_list->RunCheckpoint(&check_point);
10991d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  // Release locks then wait for all mutator threads to pass the barrier.
1100dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li  // If there are no threads to wait which implys that all the checkpoint functions are finished,
1101dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li  // then no need to release locks.
1102dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li  if (barrier_count == 0) {
1103dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li    return;
1104dd9943d4466b052ef6c5ee5b32187adb48cbce74Lei Li  }
11051d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
11061d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  Locks::mutator_lock_->SharedUnlock(self);
11074aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  {
11084aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier    ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
11094aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier    gc_barrier_->Increment(self, barrier_count);
11104aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  }
11111d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  Locks::mutator_lock_->SharedLock(self);
11121d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  Locks::heap_bitmap_lock_->ExclusiveLock(self);
1113858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier}
1114858f1c5fd5e528d0b16040ced74d4636046a42d8Mathieu Chartier
11151d54e73444e017d3a65234e0f193846f3e27472bIan Rogersvoid MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
1116f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1117e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  Thread* self = Thread::Current();
1118bbdc5bc5fd5141711879a6c85d80ac45b7aad5d0Hiroshi Yamauchi  mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1119bbdc5bc5fd5141711879a6c85d80ac45b7aad5d0Hiroshi Yamauchi      sweep_array_free_buffer_mem_map_->BaseBegin());
1120e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  size_t chunk_free_pos = 0;
112110fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier  ObjectBytePair freed;
112210fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier  ObjectBytePair freed_los;
1123e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  // How many objects are left in the array, modified after each space is swept.
1124cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier  StackReference<Object>* objects = allocations->Begin();
1125e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  size_t count = allocations->Size();
1126e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  // Change the order to ensure that the non-moving space last swept as an optimization.
1127e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  std::vector<space::ContinuousSpace*> sweep_spaces;
1128e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  space::ContinuousSpace* non_moving_space = nullptr;
1129e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
11308d562103c3a3452fb15ef4b1c64df767b70507a4Mathieu Chartier    if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) &&
11318d562103c3a3452fb15ef4b1c64df767b70507a4Mathieu Chartier        space->GetLiveBitmap() != nullptr) {
1132e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier      if (space == heap_->GetNonMovingSpace()) {
1133e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier        non_moving_space = space;
1134e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier      } else {
1135e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier        sweep_spaces.push_back(space);
1136e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier      }
1137e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    }
1138e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  }
1139e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1140e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  // the other alloc spaces as an optimization.
1141e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  if (non_moving_space != nullptr) {
1142e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    sweep_spaces.push_back(non_moving_space);
1143e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  }
1144e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  // Start by sweeping the continuous spaces.
1145e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  for (space::ContinuousSpace* space : sweep_spaces) {
1146e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    space::AllocSpace* alloc_space = space->AsAllocSpace();
1147a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier    accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1148a8e8f9c0a8e259a807d7b99a148d14104c24209dMathieu Chartier    accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
1149e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    if (swap_bitmaps) {
1150e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier      std::swap(live_bitmap, mark_bitmap);
1151e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    }
1152cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier    StackReference<Object>* out = objects;
1153e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    for (size_t i = 0; i < count; ++i) {
1154cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier      Object* const obj = objects[i].AsMirrorPtr();
1155f5b0e20b5b31f5f5465784adcf2a204dcd69c7fdHiroshi Yamauchi      if (kUseThreadLocalAllocationStack && obj == nullptr) {
1156f5b0e20b5b31f5f5465784adcf2a204dcd69c7fdHiroshi Yamauchi        continue;
1157f5b0e20b5b31f5f5465784adcf2a204dcd69c7fdHiroshi Yamauchi      }
1158e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier      if (space->HasAddress(obj)) {
1159e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier        // This object is in the space, remove it from the array and add it to the sweep buffer
1160e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier        // if needed.
1161e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier        if (!mark_bitmap->Test(obj)) {
1162e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier          if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
1163277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe            TimingLogger::ScopedTiming t2("FreeList", GetTimings());
116410fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier            freed.objects += chunk_free_pos;
116510fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier            freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1166e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier            chunk_free_pos = 0;
1167e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier          }
1168e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier          chunk_free_buffer[chunk_free_pos++] = obj;
1169e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier        }
1170e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier      } else {
1171cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier        (out++)->Assign(obj);
1172e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier      }
1173e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    }
1174e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    if (chunk_free_pos > 0) {
1175277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe      TimingLogger::ScopedTiming t2("FreeList", GetTimings());
117610fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier      freed.objects += chunk_free_pos;
117710fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier      freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
1178e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier      chunk_free_pos = 0;
1179e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    }
1180e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    // All of the references which space contained are no longer in the allocation stack, update
1181e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    // the count.
1182e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier    count = out - objects;
1183e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  }
1184e6da9af8dfe0a3e3fbc2be700554f6478380e7b9Mathieu Chartier  // Handle the large object space.
11851d54e73444e017d3a65234e0f193846f3e27472bIan Rogers  space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
11862dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier  if (large_object_space != nullptr) {
11872dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier    accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
11882dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier    accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
11892dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier    if (swap_bitmaps) {
11902dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier      std::swap(large_live_objects, large_mark_objects);
1191f5b0e20b5b31f5f5465784adcf2a204dcd69c7fdHiroshi Yamauchi    }
11922dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier    for (size_t i = 0; i < count; ++i) {
1193cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier      Object* const obj = objects[i].AsMirrorPtr();
11942dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier      // Handle large objects.
11952dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier      if (kUseThreadLocalAllocationStack && obj == nullptr) {
11962dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier        continue;
11972dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier      }
11982dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier      if (!large_mark_objects->Test(obj)) {
11992dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier        ++freed_los.objects;
12002dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier        freed_los.bytes += large_object_space->Free(self, obj);
12012dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier      }
1202357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier    }
1203357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier  }
1204f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  {
1205277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe    TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
1206f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    RecordFree(freed);
1207f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    RecordFreeLOS(freed_los);
1208277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe    t2.NewTiming("ResetStack");
1209f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    allocations->Reset();
1210f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  }
1211c5f17732d8144491c642776b6b48c85dfadf4b52Ian Rogers  sweep_array_free_buffer_mem_map_->MadviseDontNeedAndZero();
1212357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier}
1213357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier
12141d54e73444e017d3a65234e0f193846f3e27472bIan Rogersvoid MarkSweep::Sweep(bool swap_bitmaps) {
1215f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
12160f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  // Ensure that nobody inserted items in the live stack after we swapped the stacks.
12170f7bf6a3ad1798fde328a2bff48a4bf2d750a36bMathieu Chartier  CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
1218f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  {
1219f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    TimingLogger::ScopedTiming t2("MarkAllocStackAsLive", GetTimings());
1220f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1221f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    // knowing that new allocations won't be marked as live.
1222f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1223f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    heap_->MarkAllocStackAsLive(live_stack);
1224f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    live_stack->Reset();
1225f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    DCHECK(mark_stack_->IsEmpty());
1226f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  }
122702e25119b15a6f619f17db99f5d05124a5807ff3Mathieu Chartier  for (const auto& space : GetHeap()->GetContinuousSpaces()) {
1228a1602f28c0e3127ad511712d4b08db89737ae901Mathieu Chartier    if (space->IsContinuousMemMapAllocSpace()) {
1229a1602f28c0e3127ad511712d4b08db89737ae901Mathieu Chartier      space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
1230f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier      TimingLogger::ScopedTiming split(
123110fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier          alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", GetTimings());
123210fb83ad7442c8cf3356a89ec918e0786f110981Mathieu Chartier      RecordFree(alloc_space->Sweep(swap_bitmaps));
123358551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro    }
123458551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro  }
12352b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier  SweepLargeObjects(swap_bitmaps);
123658551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro}
123758551df3c2646ed507feec9e9eb3768085a76059Carl Shapiro
1238e0f0cb3d855cb5e926452b5e1ec8457adc4e454eMathieu Chartiervoid MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
12392dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier  space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
12402dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier  if (los != nullptr) {
12412dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier    TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
12422dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier    RecordFreeLOS(los->Sweep(swap_bitmaps));
12432dbe627954fd78a3659ab3cd42d2ead5b4529441Mathieu Chartier  }
1244e0f0cb3d855cb5e926452b5e1ec8457adc4e454eMathieu Chartier}
1245e0f0cb3d855cb5e926452b5e1ec8457adc4e454eMathieu Chartier
1246407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier// Process the "referent" field in a java.lang.ref.Reference.  If the referent has not yet been
1247407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier// marked, put it on the appropriate list in the heap for later processing.
1248407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartiervoid MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
12490e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  if (kCountJavaLangRefs) {
12500e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    ++reference_count_;
12510e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  }
1252308351ada0008b0cbe1a5afc31c302c975554ee4Mathieu Chartier  heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, ref, &HeapReferenceMarkedCallback,
1253308351ada0008b0cbe1a5afc31c302c975554ee4Mathieu Chartier                                                         this);
125469759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}
125569759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
125602b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartierclass MarkObjectVisitor {
125702b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier public:
1258407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {
1259407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  }
126002b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier
1261407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const
1262407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1263407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
126494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    if (kCheckLocks) {
12652b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier      Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
12662b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier      Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
12672b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartier    }
1268eb2baaf20d9059c0fc38141780ec05bea0486c40Hiroshi Yamauchi    mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset), obj, offset);
126902b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
127002b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier
127102b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier private:
127202b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  MarkSweep* const mark_sweep_;
127302b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier};
127402b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier
127569759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro// Scans an object reference.  Determines the type of the reference
127669759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro// and dispatches to a specialized scanning routine.
1277590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartiervoid MarkSweep::ScanObject(Object* obj) {
1278407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  MarkObjectVisitor mark_visitor(this);
1279407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  DelayReferenceReferentVisitor ref_visitor(this);
1280407f702da4f867c074fc3c8c688b8f8c32279effMathieu Chartier  ScanObjectVisit(obj, mark_visitor, ref_visitor);
128102b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier}
128202b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier
128378f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartiervoid MarkSweep::ProcessMarkStackCallback(void* arg) {
128478f7b4c04ab6e8b5581921bc95b67a9beee1c246Mathieu Chartier  reinterpret_cast<MarkSweep*>(arg)->ProcessMarkStack(false);
12853bb57c7b41bf5419fe895e7aa664d8d430205ba8Mathieu Chartier}
12863bb57c7b41bf5419fe895e7aa664d8d430205ba8Mathieu Chartier
12872775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartiervoid MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
128802b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  Thread* self = Thread::Current();
128902b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  ThreadPool* thread_pool = GetHeap()->GetThreadPool();
12902775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
12912775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier                                     static_cast<size_t>(MarkStackTask<false>::kMaxSize));
129294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  CHECK_GT(chunk_size, 0U);
129394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  // Split the current mark stack up into work tasks.
1294cb535da36915f9d10bec3880b46f1de1f7a69f22Mathieu Chartier  for (auto* it = mark_stack_->Begin(), *end = mark_stack_->End(); it < end; ) {
129594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
12960e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
129794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    it += delta;
129802b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
12992775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  thread_pool->SetMaxActiveWorkers(thread_count - 1);
130002b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  thread_pool->StartWorkers(self);
13012775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  thread_pool->Wait(self, true, true);
130294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  thread_pool->StopWorkers(self);
130302b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  mark_stack_->Reset();
13043e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers  CHECK_EQ(work_chunks_created_.LoadSequentiallyConsistent(),
13053e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers           work_chunks_deleted_.LoadSequentiallyConsistent())
13063e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers      << " some of the work chunks were leaked";
130769759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}
130869759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
13095d76c435082332ef79a22962386fa92a0870e378Ian Rogers// Scan anything that's on the mark stack.
131094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartiervoid MarkSweep::ProcessMarkStack(bool paused) {
1311f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(paused ? "(Paused)ProcessMarkStack" : __FUNCTION__, GetTimings());
13122775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  size_t thread_count = GetThreadCount(paused);
13132775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier  if (kParallelProcessMarkStack && thread_count > 1 &&
13142775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier      mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
13152775ee4f82dff260663ca16adddc0b15327aaa42Mathieu Chartier    ProcessMarkStackParallel(thread_count);
131694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier  } else {
131794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    // TODO: Tune this.
131894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier    static const size_t kFifoSize = 4;
1319590fee9e8972f872301c2d16a575d579ee564beeMathieu Chartier    BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
1320d8195f19840911a73b1491dfc8e7c18139753731Mathieu Chartier    for (;;) {
13212cebb24bfc3247d3e9be138a3350106737455918Mathieu Chartier      Object* obj = nullptr;
132294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      if (kUseMarkStackPrefetch) {
132394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
1324277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe          Object* mark_stack_obj = mark_stack_->PopBack();
13252cebb24bfc3247d3e9be138a3350106737455918Mathieu Chartier          DCHECK(mark_stack_obj != nullptr);
1326277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe          __builtin_prefetch(mark_stack_obj);
1327277ccbd200ea43590dfc06a93ae184a765327ad0Andreas Gampe          prefetch_fifo.push_back(mark_stack_obj);
132894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        }
132994c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        if (prefetch_fifo.empty()) {
133094c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          break;
133194c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        }
133294c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        obj = prefetch_fifo.front();
133394c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        prefetch_fifo.pop_front();
133494c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier      } else {
133594c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        if (mark_stack_->IsEmpty()) {
133694c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier          break;
133794c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        }
133894c32c5f01c7d44781317bf23933ed0a5bc4b796Mathieu Chartier        obj = mark_stack_->PopBack();
1339d8195f19840911a73b1491dfc8e7c18139753731Mathieu Chartier      }
13404aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier      DCHECK(obj != nullptr);
1341d8195f19840911a73b1491dfc8e7c18139753731Mathieu Chartier      ScanObject(obj);
1342357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier    }
1343357e9be24c17a6bc2ae9fb53f25c73503116101dMathieu Chartier  }
134469759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}
134569759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
134652e4b43d62896b56f8c2bd041e528472bb4a0d8dMathieu Chartierinline bool MarkSweep::IsMarked(const Object* object) const {
13478d562103c3a3452fb15ef4b1c64df767b70507a4Mathieu Chartier  if (immune_region_.ContainsObject(object)) {
13487469ebf3888b8037421cb6834f37f946646265ecMathieu Chartier    return true;
13497469ebf3888b8037421cb6834f37f946646265ecMathieu Chartier  }
13500e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  if (current_space_bitmap_->HasAddress(object)) {
13510e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier    return current_space_bitmap_->Test(object);
13527469ebf3888b8037421cb6834f37f946646265ecMathieu Chartier  }
13530e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  return mark_bitmap_->Test(object);
13547469ebf3888b8037421cb6834f37f946646265ecMathieu Chartier}
13557469ebf3888b8037421cb6834f37f946646265ecMathieu Chartier
13562b82db45c09450022199376c3a5420eacf2aa81eMathieu Chartiervoid MarkSweep::FinishPhase() {
1357f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier  TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1358d22d54849c96760aa1efa259d6dcfbace54da2afMathieu Chartier  if (kCountScannedTypes) {
13593e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers    VLOG(gc) << "MarkSweep scanned classes=" << class_count_.LoadRelaxed()
13603e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers        << " arrays=" << array_count_.LoadRelaxed() << " other=" << other_count_.LoadRelaxed();
136102b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
136202b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  if (kCountTasks) {
13633e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers    VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_.LoadRelaxed();
136402b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
136502b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  if (kMeasureOverhead) {
13663e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers    VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_.LoadRelaxed());
136702b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
136802b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  if (kProfileLargeObjects) {
13693e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers    VLOG(gc) << "Large objects tested " << large_object_test_.LoadRelaxed()
13703e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers        << " marked " << large_object_mark_.LoadRelaxed();
137102b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
1372d22d54849c96760aa1efa259d6dcfbace54da2afMathieu Chartier  if (kCountJavaLangRefs) {
13733e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers    VLOG(gc) << "References scanned " << reference_count_.LoadRelaxed();
137402b6a78038f12c109f95eb31713cfc747f5512f1Mathieu Chartier  }
13750e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  if (kCountMarkedObjects) {
13763e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers    VLOG(gc) << "Marked: null=" << mark_null_count_.LoadRelaxed()
13773e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers        << " immune=" <<  mark_immune_count_.LoadRelaxed()
13783e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers        << " fastpath=" << mark_fastpath_count_.LoadRelaxed()
13793e5cf305db800b2989ad57b7cde8fb3cc9fa1b9eIan Rogers        << " slowpath=" << mark_slowpath_count_.LoadRelaxed();
13800e54cd0d8fc635d3dc8bf88a465fdade151a098fMathieu Chartier  }
13814aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  CHECK(mark_stack_->IsEmpty());  // Ensure that the mark stack is empty.
13825301cd241b4d8afbfc1211e107c41f1b15c6bd48Mathieu Chartier  mark_stack_->Reset();
13834aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
13844aeec176eaf11fe03f342aadcbb79142230270edMathieu Chartier  heap_->ClearMarkedObjects();
138569759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}
138669759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro
1387c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchivoid MarkSweep::RevokeAllThreadLocalBuffers() {
1388c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi  if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1389c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi    // If concurrent, rosalloc thread-local buffers are revoked at the
1390c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi    // thread checkpoint. Bump pointer space thread-local buffers must
1391c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi    // not be in use.
1392c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi    GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1393c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi  } else {
1394f5997b4d3f889569d5a2b724d83d764bfbb8d106Mathieu Chartier    TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
1395c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi    GetHeap()->RevokeAllThreadLocalBuffers();
1396c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi  }
1397c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi}
1398c93c530efc175954160c3834c93961a1a946a35aHiroshi Yamauchi
13991d54e73444e017d3a65234e0f193846f3e27472bIan Rogers}  // namespace collector
14001d54e73444e017d3a65234e0f193846f3e27472bIan Rogers}  // namespace gc
140169759eaa6fd4386f1e6d8748052ad221087b3476Carl Shapiro}  // namespace art
1402