blob: 5401b56449677a002db41fd2a759e494e68d72ff [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro69759ea2011-07-21 18:13:35 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "mark_sweep.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070018
Yabin Cuic7df66e2015-04-15 15:40:18 -070019#include <atomic>
Mathieu Chartier2b82db42012-11-14 17:29:05 -080020#include <functional>
21#include <numeric>
Carl Shapiro58551df2011-07-24 03:09:51 -070022#include <climits>
23#include <vector>
24
Ian Rogerscf7f1912014-10-22 22:06:39 -070025#define ATRACE_TAG ATRACE_TAG_DALVIK
26#include "cutils/trace.h"
27
Mathieu Chartier94c32c52013-08-09 11:14:04 -070028#include "base/bounded_fifo.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080029#include "base/logging.h"
Elliott Hughes76160052012-12-12 16:31:20 -080030#include "base/macros.h"
Ian Rogers693ff612013-02-01 10:56:12 -080031#include "base/mutex-inl.h"
Sameer Abu Asala8439542013-02-14 16:06:42 -080032#include "base/timing_logger.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070033#include "gc/accounting/card_table-inl.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070034#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier11409ae2013-09-23 11:49:36 -070035#include "gc/accounting/mod_union_table.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070036#include "gc/accounting/space_bitmap-inl.h"
37#include "gc/heap.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070038#include "gc/reference_processor.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "gc/space/image_space.h"
40#include "gc/space/large_object_space.h"
41#include "gc/space/space-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080042#include "mark_sweep-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/object-inl.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070044#include "runtime.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070045#include "scoped_thread_state_change.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070046#include "thread-inl.h"
Mathieu Chartier6f1c9492012-10-15 12:08:41 -070047#include "thread_list.h"
Carl Shapiro69759ea2011-07-21 18:13:35 -070048
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070049using ::art::mirror::Object;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050
Carl Shapiro69759ea2011-07-21 18:13:35 -070051namespace art {
Ian Rogers1d54e732013-05-02 21:10:01 -070052namespace gc {
53namespace collector {
Carl Shapiro69759ea2011-07-21 18:13:35 -070054
Mathieu Chartier02b6a782012-10-26 13:51:26 -070055// Performance options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080056static constexpr bool kUseRecursiveMark = false;
57static constexpr bool kUseMarkStackPrefetch = true;
58static constexpr size_t kSweepArrayChunkFreeSize = 1024;
59static constexpr bool kPreCleanCards = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070060
61// Parallelism options.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080062static constexpr bool kParallelCardScan = true;
63static constexpr bool kParallelRecursiveMark = true;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070064// Don't attempt to parallelize mark stack processing unless the mark stack is at least n
65// elements. This is temporary until we reduce the overhead caused by allocating tasks, etc.. Not
66// having this can add overhead in ProcessReferences since we may end up doing many calls of
67// ProcessMarkStack with very small mark stacks.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080068static constexpr size_t kMinimumParallelMarkStackSize = 128;
69static constexpr bool kParallelProcessMarkStack = true;
Mathieu Chartier858f1c52012-10-17 17:45:55 -070070
Mathieu Chartier02b6a782012-10-26 13:51:26 -070071// Profiling and information flags.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080072static constexpr bool kProfileLargeObjects = false;
73static constexpr bool kMeasureOverhead = false;
74static constexpr bool kCountTasks = false;
75static constexpr bool kCountJavaLangRefs = false;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -070076static constexpr bool kCountMarkedObjects = false;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070077
78// Turn off kCheckLocks when profiling the GC since it slows the GC down by up to 40%.
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -080079static constexpr bool kCheckLocks = kDebugLocking;
Mathieu Chartier7bf9f192014-04-04 11:09:41 -070080static constexpr bool kVerifyRootsMarked = kIsDebugBuild;
Mathieu Chartier02b6a782012-10-26 13:51:26 -070081
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -070082// If true, revoke the rosalloc thread-local buffers at the
83// checkpoint, as opposed to during the pause.
84static constexpr bool kRevokeRosAllocThreadLocalBuffersAtCheckpoint = true;
85
Mathieu Chartier2b82db42012-11-14 17:29:05 -080086void MarkSweep::BindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -070087 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -080088 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -080089 // Mark all of the spaces we never collect as immune.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070090 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -070091 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect) {
Mathieu Chartier8d562102014-03-12 17:42:10 -070092 CHECK(immune_region_.AddContinuousSpace(space)) << "Failed to add space " << *space;
Mathieu Chartier2b82db42012-11-14 17:29:05 -080093 }
94 }
95}
96
Ian Rogers1d54e732013-05-02 21:10:01 -070097MarkSweep::MarkSweep(Heap* heap, bool is_concurrent, const std::string& name_prefix)
98 : GarbageCollector(heap,
Mathieu Chartier590fee92013-09-13 13:46:47 -070099 name_prefix +
Ian Rogers1d54e732013-05-02 21:10:01 -0700100 (is_concurrent ? "concurrent mark sweep": "mark sweep")),
Ian Rogers3e5cf302014-05-20 16:40:37 -0700101 current_space_bitmap_(nullptr), mark_bitmap_(nullptr), mark_stack_(nullptr),
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800102 gc_barrier_(new Barrier(0)),
Mathieu Chartier958291c2013-08-27 18:14:55 -0700103 mark_stack_lock_("mark sweep mark stack lock", kMarkSweepMarkStackLock),
Ian Rogers3e5cf302014-05-20 16:40:37 -0700104 is_concurrent_(is_concurrent), live_stack_freeze_size_(0) {
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -0700105 std::string error_msg;
106 MemMap* mem_map = MemMap::MapAnonymous(
107 "mark sweep sweep array free buffer", nullptr,
108 RoundUp(kSweepArrayChunkFreeSize * sizeof(mirror::Object*), kPageSize),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000109 PROT_READ | PROT_WRITE, false, false, &error_msg);
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -0700110 CHECK(mem_map != nullptr) << "Couldn't allocate sweep array free buffer: " << error_msg;
111 sweep_array_free_buffer_mem_map_.reset(mem_map);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800112}
113
114void MarkSweep::InitializePhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700115 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700116 mark_stack_ = heap_->GetMarkStack();
Mathieu Chartiere53225c2013-08-19 10:59:11 -0700117 DCHECK(mark_stack_ != nullptr);
Mathieu Chartier8d562102014-03-12 17:42:10 -0700118 immune_region_.Reset();
Ian Rogers3e5cf302014-05-20 16:40:37 -0700119 class_count_.StoreRelaxed(0);
120 array_count_.StoreRelaxed(0);
121 other_count_.StoreRelaxed(0);
122 large_object_test_.StoreRelaxed(0);
123 large_object_mark_.StoreRelaxed(0);
124 overhead_time_ .StoreRelaxed(0);
125 work_chunks_created_.StoreRelaxed(0);
126 work_chunks_deleted_.StoreRelaxed(0);
127 reference_count_.StoreRelaxed(0);
128 mark_null_count_.StoreRelaxed(0);
129 mark_immune_count_.StoreRelaxed(0);
130 mark_fastpath_count_.StoreRelaxed(0);
131 mark_slowpath_count_.StoreRelaxed(0);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700132 {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700133 // TODO: I don't think we should need heap bitmap lock to Get the mark bitmap.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700134 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
135 mark_bitmap_ = heap_->GetMarkBitmap();
136 }
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700137 if (!GetCurrentIteration()->GetClearSoftReferences()) {
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700138 // Always clear soft references if a non-sticky collection.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700139 GetCurrentIteration()->SetClearSoftReferences(GetGcType() != collector::kGcTypeSticky);
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700140 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700141}
142
143void MarkSweep::RunPhases() {
144 Thread* self = Thread::Current();
145 InitializePhase();
146 Locks::mutator_lock_->AssertNotHeld(self);
147 if (IsConcurrent()) {
148 GetHeap()->PreGcVerification(this);
149 {
150 ReaderMutexLock mu(self, *Locks::mutator_lock_);
151 MarkingPhase();
152 }
153 ScopedPause pause(this);
154 GetHeap()->PrePauseRosAllocVerification(this);
155 PausePhase();
156 RevokeAllThreadLocalBuffers();
157 } else {
158 ScopedPause pause(this);
159 GetHeap()->PreGcVerificationPaused(this);
160 MarkingPhase();
161 GetHeap()->PrePauseRosAllocVerification(this);
162 PausePhase();
163 RevokeAllThreadLocalBuffers();
164 }
165 {
166 // Sweeping always done concurrently, even for non concurrent mark sweep.
167 ReaderMutexLock mu(self, *Locks::mutator_lock_);
168 ReclaimPhase();
169 }
170 GetHeap()->PostGcVerification(this);
171 FinishPhase();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800172}
173
174void MarkSweep::ProcessReferences(Thread* self) {
Mathieu Chartier8e56c7e2012-11-20 13:25:50 -0800175 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700176 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700177 true, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(),
178 &HeapReferenceMarkedCallback, &MarkObjectCallback, &ProcessMarkStackCallback, this);
Mathieu Chartier1ad27842014-03-19 17:08:17 -0700179}
180
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700181void MarkSweep::PausePhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700182 TimingLogger::ScopedTiming t("(Paused)PausePhase", GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800183 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800184 Locks::mutator_lock_->AssertExclusiveHeld(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700185 if (IsConcurrent()) {
186 // Handle the dirty objects if we are a concurrent GC.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800187 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800188 // Re-mark root set.
189 ReMarkRoots();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800190 // Scan dirty objects, this is only required if we are not doing concurrent GC.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700191 RecursiveMarkDirtyObjects(true, accounting::CardTable::kCardDirty);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800192 }
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700193 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700194 TimingLogger::ScopedTiming t2("SwapStacks", GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800195 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700196 heap_->SwapStacks(self);
197 live_stack_freeze_size_ = heap_->GetLiveStack()->Size();
198 // Need to revoke all the thread local allocation stacks since we just swapped the allocation
199 // stacks and don't want anybody to allocate into the live stack.
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800200 RevokeAllThreadLocalAllocationStacks(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800201 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700202 heap_->PreSweepingGcVerification(this);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700203 // Disallow new system weaks to prevent a race which occurs when someone adds a new system
204 // weak before we sweep them. Since this new system weak may not be marked, the GC may
205 // incorrectly sweep it. This also fixes a race where interning may attempt to return a strong
206 // reference to a string that is about to be swept.
207 Runtime::Current()->DisallowNewSystemWeaks();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700208 // Enable the reference processing slow path, needs to be done with mutators paused since there
209 // is no lock in the GetReferent fast path.
210 GetHeap()->GetReferenceProcessor()->EnableSlowPath();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800211}
212
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800213void MarkSweep::PreCleanCards() {
214 // Don't do this for non concurrent GCs since they don't have any dirty cards.
215 if (kPreCleanCards && IsConcurrent()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700216 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800217 Thread* self = Thread::Current();
218 CHECK(!Locks::mutator_lock_->IsExclusiveHeld(self));
219 // Process dirty cards and add dirty cards to mod union tables, also ages cards.
Lei Li4add3b42015-01-15 11:55:26 +0800220 heap_->ProcessCards(GetTimings(), false, true, false);
Mathieu Chartiereb7bbad2014-02-25 15:52:46 -0800221 // The checkpoint root marking is required to avoid a race condition which occurs if the
222 // following happens during a reference write:
223 // 1. mutator dirties the card (write barrier)
224 // 2. GC ages the card (the above ProcessCards call)
225 // 3. GC scans the object (the RecursiveMarkDirtyObjects call below)
226 // 4. mutator writes the value (corresponding to the write barrier in 1.)
227 // This causes the GC to age the card but not necessarily mark the reference which the mutator
228 // wrote into the object stored in the card.
229 // Having the checkpoint fixes this issue since it ensures that the card mark and the
230 // reference write are visible to the GC before the card is scanned (this is due to locks being
231 // acquired / released in the checkpoint code).
232 // The other roots are also marked to help reduce the pause.
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700233 MarkRootsCheckpoint(self, false);
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800234 MarkNonThreadRoots();
Mathieu Chartier893263b2014-03-04 11:07:42 -0800235 MarkConcurrentRoots(
236 static_cast<VisitRootFlags>(kVisitRootFlagClearRootLog | kVisitRootFlagNewRoots));
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800237 // Process the newly aged cards.
238 RecursiveMarkDirtyObjects(false, accounting::CardTable::kCardDirty - 1);
239 // TODO: Empty allocation stack to reduce the number of objects we need to test / mark as live
240 // in the next GC.
241 }
242}
243
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800244void MarkSweep::RevokeAllThreadLocalAllocationStacks(Thread* self) {
245 if (kUseThreadLocalAllocationStack) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700246 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierc22c59e2014-02-24 15:16:06 -0800247 Locks::mutator_lock_->AssertExclusiveHeld(self);
248 heap_->RevokeAllThreadLocalAllocationStacks(self);
249 }
250}
251
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800252void MarkSweep::MarkingPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700253 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800254 Thread* self = Thread::Current();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800255 BindBitmaps();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700256 FindDefaultSpaceBitmap();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800257 // Process dirty cards and add dirty cards to mod union tables.
Lei Li4add3b42015-01-15 11:55:26 +0800258 // If the GC type is non sticky, then we just clear the cards instead of ageing them.
259 heap_->ProcessCards(GetTimings(), false, true, GetGcType() != kGcTypeSticky);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800260 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800261 MarkRoots(self);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800262 MarkReachableObjects();
Mathieu Chartierdda54f52014-02-24 09:58:40 -0800263 // Pre-clean dirtied cards to reduce pauses.
264 PreCleanCards();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800265}
266
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700267void MarkSweep::UpdateAndMarkModUnion() {
268 for (const auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier8d562102014-03-12 17:42:10 -0700269 if (immune_region_.ContainsSpace(space)) {
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700270 const char* name = space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
271 "UpdateAndMarkImageModUnionTable";
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700272 TimingLogger::ScopedTiming t(name, GetTimings());
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700273 accounting::ModUnionTable* mod_union_table = heap_->FindModUnionTableFromSpace(space);
274 CHECK(mod_union_table != nullptr);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800275 mod_union_table->UpdateAndMarkReferences(MarkHeapReferenceCallback, this);
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700276 }
277 }
278}
279
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800280void MarkSweep::MarkReachableObjects() {
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700281 UpdateAndMarkModUnion();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800282 // Recursively mark all the non-image bits set in the mark bitmap.
283 RecursiveMark();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800284}
285
286void MarkSweep::ReclaimPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700287 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier720ef762013-08-17 14:46:54 -0700288 Thread* self = Thread::Current();
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700289 // Process the references concurrently.
290 ProcessReferences(self);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700291 SweepSystemWeaks(self);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700292 Runtime::Current()->AllowNewSystemWeaks();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800293 {
294 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700295 GetHeap()->RecordFreeRevoke();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800296 // Reclaim unmarked objects.
Ian Rogers1d54e732013-05-02 21:10:01 -0700297 Sweep(false);
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800298 // Swap the live and mark bitmaps for each space which we modified space. This is an
299 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
300 // bitmaps.
301 SwapBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800302 // Unbind the live and mark bitmaps.
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800303 GetHeap()->UnBindBitmaps();
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800304 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800305}
306
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700307void MarkSweep::FindDefaultSpaceBitmap() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700308 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier02e25112013-08-14 16:14:24 -0700309 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700310 accounting::ContinuousSpaceBitmap* bitmap = space->GetMarkBitmap();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700311 // We want to have the main space instead of non moving if possible.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700312 if (bitmap != nullptr &&
313 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700314 current_space_bitmap_ = bitmap;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700315 // If we are not the non moving space exit the loop early since this will be good enough.
316 if (space != heap_->GetNonMovingSpace()) {
317 break;
318 }
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700319 }
320 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700321 CHECK(current_space_bitmap_ != nullptr) << "Could not find a default mark bitmap\n"
322 << heap_->DumpSpaces();
Mathieu Chartier7469ebf2012-09-24 16:28:36 -0700323}
324
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800325void MarkSweep::ExpandMarkStack() {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700326 ResizeMarkStack(mark_stack_->Capacity() * 2);
327}
328
329void MarkSweep::ResizeMarkStack(size_t new_size) {
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800330 // Rare case, no need to have Thread::Current be a parameter.
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800331 if (UNLIKELY(mark_stack_->Size() < mark_stack_->Capacity())) {
332 // Someone else acquired the lock and expanded the mark stack before us.
333 return;
334 }
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800335 std::vector<StackReference<Object>> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartierba311b42013-08-27 13:02:30 -0700336 CHECK_LE(mark_stack_->Size(), new_size);
337 mark_stack_->Resize(new_size);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800338 for (auto& obj : temp) {
339 mark_stack_->PushBack(obj.AsMirrorPtr());
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800340 }
341}
342
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700343inline void MarkSweep::MarkObjectNonNullParallel(Object* obj) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700344 DCHECK(obj != nullptr);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800345 if (MarkObjectParallel(obj)) {
Mathieu Chartierba311b42013-08-27 13:02:30 -0700346 MutexLock mu(Thread::Current(), mark_stack_lock_);
347 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
Mathieu Chartier184e3222013-08-03 14:02:57 -0700348 ExpandMarkStack();
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800349 }
Mathieu Chartierba311b42013-08-27 13:02:30 -0700350 // The object must be pushed on to the mark stack.
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700351 mark_stack_->PushBack(obj);
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800352 }
353}
354
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800355mirror::Object* MarkSweep::MarkObjectCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800356 MarkSweep* mark_sweep = reinterpret_cast<MarkSweep*>(arg);
357 mark_sweep->MarkObject(obj);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800358 return obj;
359}
360
Mathieu Chartier407f7022014-02-18 14:37:05 -0800361void MarkSweep::MarkHeapReferenceCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) {
362 reinterpret_cast<MarkSweep*>(arg)->MarkObject(ref->AsMirrorPtr());
363}
364
Mathieu Chartier308351a2014-06-15 12:39:02 -0700365bool MarkSweep::HeapReferenceMarkedCallback(mirror::HeapReference<mirror::Object>* ref, void* arg) {
366 return reinterpret_cast<MarkSweep*>(arg)->IsMarked(ref->AsMirrorPtr());
367}
368
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700369class MarkSweepMarkObjectSlowPath {
370 public:
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700371 explicit MarkSweepMarkObjectSlowPath(MarkSweep* mark_sweep, Object* holder = nullptr,
372 MemberOffset offset = MemberOffset(0))
373 : mark_sweep_(mark_sweep), holder_(holder), offset_(offset) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700374 }
375
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700376 void operator()(const Object* obj) const ALWAYS_INLINE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700377 if (kProfileLargeObjects) {
378 // TODO: Differentiate between marking and testing somehow.
379 ++mark_sweep_->large_object_test_;
380 ++mark_sweep_->large_object_mark_;
381 }
382 space::LargeObjectSpace* large_object_space = mark_sweep_->GetHeap()->GetLargeObjectsSpace();
Mathieu Chartiera17288e2014-05-08 17:53:19 -0700383 if (UNLIKELY(obj == nullptr || !IsAligned<kPageSize>(obj) ||
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700384 (kIsDebugBuild && large_object_space != nullptr &&
385 !large_object_space->Contains(obj)))) {
Mathieu Chartier175746a2015-05-01 13:00:23 -0700386 LOG(INTERNAL_FATAL) << "Tried to mark " << obj << " not contained by any spaces";
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700387 if (holder_ != nullptr) {
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700388 size_t holder_size = holder_->SizeOf();
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700389 ArtField* field = holder_->FindFieldByOffset(offset_);
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700390 LOG(INTERNAL_FATAL) << "Field info: "
391 << " holder=" << holder_
392 << " holder_size=" << holder_size
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700393 << " holder_type=" << PrettyTypeOf(holder_)
394 << " offset=" << offset_.Uint32Value()
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700395 << " field=" << (field != nullptr ? field->GetName() : "nullptr")
396 << " field_type="
397 << (field != nullptr ? field->GetTypeDescriptor() : "")
398 << " first_ref_field_offset="
399 << (holder_->IsClass()
400 ? holder_->AsClass()->GetFirstReferenceStaticFieldOffset()
401 : holder_->GetClass()->GetFirstReferenceInstanceFieldOffset())
402 << " num_of_ref_fields="
403 << (holder_->IsClass()
404 ? holder_->AsClass()->NumReferenceStaticFields()
405 : holder_->GetClass()->NumReferenceInstanceFields())
406 << "\n";
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700407 }
Hiroshi Yamauchid38ec802015-05-01 11:50:24 -0700408 PrintFileToLog("/proc/self/maps", LogSeverity::INTERNAL_FATAL);
Vladimir Marko17a924a2015-05-08 15:17:32 +0100409 MemMap::DumpMaps(LOG(INTERNAL_FATAL), true);
Hiroshi Yamauchid0c84122015-05-15 15:23:30 -0700410 {
411 LOG(INTERNAL_FATAL) << "Attempting see if it's a bad root";
412 Thread* self = Thread::Current();
413 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
414 mark_sweep_->VerifyRoots();
415 } else {
416 const bool heap_bitmap_exclusive_locked =
417 Locks::heap_bitmap_lock_->IsExclusiveHeld(self);
418 if (heap_bitmap_exclusive_locked) {
419 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
420 }
421 Locks::mutator_lock_->SharedUnlock(self);
422 ThreadList* tl = Runtime::Current()->GetThreadList();
423 tl->SuspendAll(__FUNCTION__);
424 mark_sweep_->VerifyRoots();
425 tl->ResumeAll();
426 Locks::mutator_lock_->SharedLock(self);
427 if (heap_bitmap_exclusive_locked) {
428 Locks::heap_bitmap_lock_->ExclusiveLock(self);
429 }
430 }
431 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700432 LOG(FATAL) << "Can't mark invalid object";
433 }
434 }
435
436 private:
437 MarkSweep* const mark_sweep_;
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700438 mirror::Object* const holder_;
439 MemberOffset offset_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700440};
441
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700442inline void MarkSweep::MarkObjectNonNull(Object* obj, Object* holder, MemberOffset offset) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700443 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700444 if (kUseBakerOrBrooksReadBarrier) {
445 // Verify all the objects have the correct pointer installed.
446 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800447 }
Mathieu Chartier8d562102014-03-12 17:42:10 -0700448 if (immune_region_.ContainsObject(obj)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700449 if (kCountMarkedObjects) {
450 ++mark_immune_count_;
451 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700452 DCHECK(mark_bitmap_->Test(obj));
453 } else if (LIKELY(current_space_bitmap_->HasAddress(obj))) {
454 if (kCountMarkedObjects) {
455 ++mark_fastpath_count_;
456 }
457 if (UNLIKELY(!current_space_bitmap_->Set(obj))) {
458 PushOnMarkStack(obj); // This object was not previously marked.
459 }
460 } else {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700461 if (kCountMarkedObjects) {
462 ++mark_slowpath_count_;
463 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700464 MarkSweepMarkObjectSlowPath visitor(this, holder, offset);
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700465 // TODO: We already know that the object is not in the current_space_bitmap_ but MarkBitmap::Set
466 // will check again.
467 if (!mark_bitmap_->Set(obj, visitor)) {
468 PushOnMarkStack(obj); // Was not already marked, push.
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700469 }
Carl Shapiro69759ea2011-07-21 18:13:35 -0700470 }
471}
472
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700473inline void MarkSweep::PushOnMarkStack(Object* obj) {
474 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
475 // Lock is not needed but is here anyways to please annotalysis.
476 MutexLock mu(Thread::Current(), mark_stack_lock_);
477 ExpandMarkStack();
478 }
479 // The object must be pushed on to the mark stack.
480 mark_stack_->PushBack(obj);
481}
482
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700483inline bool MarkSweep::MarkObjectParallel(const Object* obj) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700484 DCHECK(obj != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700485 if (kUseBakerOrBrooksReadBarrier) {
486 // Verify all the objects have the correct pointer installed.
487 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800488 }
Mathieu Chartier8d562102014-03-12 17:42:10 -0700489 if (immune_region_.ContainsObject(obj)) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700490 DCHECK(IsMarked(obj));
491 return false;
492 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700493 // Try to take advantage of locality of references within a space, failing this find the space
494 // the hard way.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700495 accounting::ContinuousSpaceBitmap* object_bitmap = current_space_bitmap_;
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700496 if (LIKELY(object_bitmap->HasAddress(obj))) {
497 return !object_bitmap->AtomicTestAndSet(obj);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700498 }
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700499 MarkSweepMarkObjectSlowPath visitor(this);
500 return !mark_bitmap_->AtomicTestAndSet(obj, visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700501}
502
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700503// Used to mark objects when processing the mark stack. If an object is null, it is not marked.
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700504inline void MarkSweep::MarkObject(Object* obj, Object* holder, MemberOffset offset) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700505 if (obj != nullptr) {
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -0700506 MarkObjectNonNull(obj, holder, offset);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700507 } else if (kCountMarkedObjects) {
508 ++mark_null_count_;
Carl Shapiro69759ea2011-07-21 18:13:35 -0700509 }
510}
511
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700512class VerifyRootMarkedVisitor : public SingleRootVisitor {
513 public:
514 explicit VerifyRootMarkedVisitor(MarkSweep* collector) : collector_(collector) { }
515
516 void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
517 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
518 CHECK(collector_->IsMarked(root)) << info.ToString();
519 }
520
521 private:
522 MarkSweep* const collector_;
523};
524
525void MarkSweep::VisitRoots(mirror::Object*** roots, size_t count,
526 const RootInfo& info ATTRIBUTE_UNUSED) {
527 for (size_t i = 0; i < count; ++i) {
528 MarkObjectNonNull(*roots[i]);
529 }
Mathieu Chartierac86a7c2012-11-12 15:03:16 -0800530}
531
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700532void MarkSweep::VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
533 const RootInfo& info ATTRIBUTE_UNUSED) {
534 for (size_t i = 0; i < count; ++i) {
535 MarkObjectNonNull(roots[i]->AsMirrorPtr());
536 }
Mathieu Chartier893263b2014-03-04 11:07:42 -0800537}
538
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700539class VerifyRootVisitor : public SingleRootVisitor {
540 public:
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700541 void VisitRoot(mirror::Object* root, const RootInfo& info) OVERRIDE
542 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700543 // See if the root is on any space bitmap.
544 auto* heap = Runtime::Current()->GetHeap();
545 if (heap->GetLiveBitmap()->GetContinuousSpaceBitmap(root) == nullptr) {
546 space::LargeObjectSpace* large_object_space = heap->GetLargeObjectsSpace();
547 if (large_object_space != nullptr && !large_object_space->Contains(root)) {
Mathieu Chartier175746a2015-05-01 13:00:23 -0700548 LOG(INTERNAL_FATAL) << "Found invalid root: " << root << " " << info;
Mathieu Chartier9086b652015-04-14 09:35:18 -0700549 }
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700550 }
551 }
Mathieu Chartier9086b652015-04-14 09:35:18 -0700552};
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700553
554void MarkSweep::VerifyRoots() {
Mathieu Chartier9086b652015-04-14 09:35:18 -0700555 VerifyRootVisitor visitor;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700556 Runtime::Current()->GetThreadList()->VisitRoots(&visitor);
Mathieu Chartier6f1c9492012-10-15 12:08:41 -0700557}
558
Mathieu Chartier893263b2014-03-04 11:07:42 -0800559void MarkSweep::MarkRoots(Thread* self) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700560 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier893263b2014-03-04 11:07:42 -0800561 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
562 // If we exclusively hold the mutator lock, all threads must be suspended.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700563 Runtime::Current()->VisitRoots(this);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800564 RevokeAllThreadLocalAllocationStacks(self);
565 } else {
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -0700566 MarkRootsCheckpoint(self, kRevokeRosAllocThreadLocalBuffersAtCheckpoint);
Mathieu Chartier893263b2014-03-04 11:07:42 -0800567 // At this point the live stack should no longer have any mutators which push into it.
568 MarkNonThreadRoots();
569 MarkConcurrentRoots(
570 static_cast<VisitRootFlags>(kVisitRootFlagAllRoots | kVisitRootFlagStartLoggingNewRoots));
571 }
Mathieu Chartier9ebae1f2012-10-15 17:38:16 -0700572}
573
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700574void MarkSweep::MarkNonThreadRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700575 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700576 Runtime::Current()->VisitNonThreadRoots(this);
Mathieu Chartier858f1c52012-10-17 17:45:55 -0700577}
578
Mathieu Chartier893263b2014-03-04 11:07:42 -0800579void MarkSweep::MarkConcurrentRoots(VisitRootFlags flags) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700580 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Ian Rogers1d54e732013-05-02 21:10:01 -0700581 // Visit all runtime roots and clear dirty flags.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700582 Runtime::Current()->VisitConcurrentRoots(this, flags);
Carl Shapiro69759ea2011-07-21 18:13:35 -0700583}
584
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700585class ScanObjectVisitor {
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700586 public:
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700587 explicit ScanObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE
588 : mark_sweep_(mark_sweep) {}
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700589
Mathieu Chartier407f7022014-02-18 14:37:05 -0800590 void operator()(Object* obj) const ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
591 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700592 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800593 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
594 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
595 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -0700596 mark_sweep_->ScanObject(obj);
Mathieu Chartiercc236d72012-07-20 10:29:05 -0700597 }
598
599 private:
600 MarkSweep* const mark_sweep_;
601};
602
Mathieu Chartier407f7022014-02-18 14:37:05 -0800603class DelayReferenceReferentVisitor {
604 public:
605 explicit DelayReferenceReferentVisitor(MarkSweep* collector) : collector_(collector) {
606 }
607
608 void operator()(mirror::Class* klass, mirror::Reference* ref) const
609 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
610 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
611 collector_->DelayReferenceReferent(klass, ref);
612 }
613
614 private:
615 MarkSweep* const collector_;
616};
617
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700618template <bool kUseFinger = false>
619class MarkStackTask : public Task {
620 public:
621 MarkStackTask(ThreadPool* thread_pool, MarkSweep* mark_sweep, size_t mark_stack_size,
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800622 StackReference<Object>* mark_stack)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700623 : mark_sweep_(mark_sweep),
624 thread_pool_(thread_pool),
625 mark_stack_pos_(mark_stack_size) {
626 // We may have to copy part of an existing mark stack when another mark stack overflows.
627 if (mark_stack_size != 0) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700628 DCHECK(mark_stack != nullptr);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700629 // TODO: Check performance?
630 std::copy(mark_stack, mark_stack + mark_stack_size, mark_stack_);
Ian Rogers1d54e732013-05-02 21:10:01 -0700631 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700632 if (kCountTasks) {
633 ++mark_sweep_->work_chunks_created_;
634 }
635 }
636
637 static const size_t kMaxSize = 1 * KB;
638
639 protected:
Mathieu Chartier407f7022014-02-18 14:37:05 -0800640 class MarkObjectParallelVisitor {
641 public:
642 explicit MarkObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task,
643 MarkSweep* mark_sweep) ALWAYS_INLINE
644 : chunk_task_(chunk_task), mark_sweep_(mark_sweep) {}
645
646 void operator()(Object* obj, MemberOffset offset, bool /* static */) const ALWAYS_INLINE
647 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700648 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800649 if (ref != nullptr && mark_sweep_->MarkObjectParallel(ref)) {
650 if (kUseFinger) {
Yabin Cuic7df66e2015-04-15 15:40:18 -0700651 std::atomic_thread_fence(std::memory_order_seq_cst);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800652 if (reinterpret_cast<uintptr_t>(ref) >=
Ian Rogers3e5cf302014-05-20 16:40:37 -0700653 static_cast<uintptr_t>(mark_sweep_->atomic_finger_.LoadRelaxed())) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800654 return;
655 }
656 }
657 chunk_task_->MarkStackPush(ref);
658 }
659 }
660
661 private:
662 MarkStackTask<kUseFinger>* const chunk_task_;
663 MarkSweep* const mark_sweep_;
664 };
665
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700666 class ScanObjectParallelVisitor {
667 public:
668 explicit ScanObjectParallelVisitor(MarkStackTask<kUseFinger>* chunk_task) ALWAYS_INLINE
669 : chunk_task_(chunk_task) {}
670
Mathieu Chartier407f7022014-02-18 14:37:05 -0800671 // No thread safety analysis since multiple threads will use this visitor.
672 void operator()(Object* obj) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
673 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
674 MarkSweep* const mark_sweep = chunk_task_->mark_sweep_;
675 MarkObjectParallelVisitor mark_visitor(chunk_task_, mark_sweep);
676 DelayReferenceReferentVisitor ref_visitor(mark_sweep);
677 mark_sweep->ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700678 }
679
680 private:
681 MarkStackTask<kUseFinger>* const chunk_task_;
682 };
683
684 virtual ~MarkStackTask() {
685 // Make sure that we have cleared our mark stack.
686 DCHECK_EQ(mark_stack_pos_, 0U);
687 if (kCountTasks) {
688 ++mark_sweep_->work_chunks_deleted_;
689 }
690 }
691
692 MarkSweep* const mark_sweep_;
693 ThreadPool* const thread_pool_;
694 // Thread local mark stack for this task.
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800695 StackReference<Object> mark_stack_[kMaxSize];
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700696 // Mark stack position.
697 size_t mark_stack_pos_;
698
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800699 ALWAYS_INLINE void MarkStackPush(Object* obj) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700700 if (UNLIKELY(mark_stack_pos_ == kMaxSize)) {
701 // Mark stack overflow, give 1/2 the stack to the thread pool as a new work task.
702 mark_stack_pos_ /= 2;
703 auto* task = new MarkStackTask(thread_pool_, mark_sweep_, kMaxSize - mark_stack_pos_,
704 mark_stack_ + mark_stack_pos_);
705 thread_pool_->AddTask(Thread::Current(), task);
706 }
707 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700708 DCHECK_LT(mark_stack_pos_, kMaxSize);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800709 mark_stack_[mark_stack_pos_++].Assign(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700710 }
711
712 virtual void Finalize() {
713 delete this;
714 }
715
716 // Scans all of the objects
Mathieu Chartier407f7022014-02-18 14:37:05 -0800717 virtual void Run(Thread* self) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
718 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700719 UNUSED(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700720 ScanObjectParallelVisitor visitor(this);
721 // TODO: Tune this.
722 static const size_t kFifoSize = 4;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700723 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700724 for (;;) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700725 Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700726 if (kUseMarkStackPrefetch) {
727 while (mark_stack_pos_ != 0 && prefetch_fifo.size() < kFifoSize) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800728 Object* const mark_stack_obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800729 DCHECK(mark_stack_obj != nullptr);
730 __builtin_prefetch(mark_stack_obj);
731 prefetch_fifo.push_back(mark_stack_obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700732 }
733 if (UNLIKELY(prefetch_fifo.empty())) {
734 break;
735 }
736 obj = prefetch_fifo.front();
737 prefetch_fifo.pop_front();
738 } else {
739 if (UNLIKELY(mark_stack_pos_ == 0)) {
740 break;
741 }
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800742 obj = mark_stack_[--mark_stack_pos_].AsMirrorPtr();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700743 }
Mathieu Chartier11409ae2013-09-23 11:49:36 -0700744 DCHECK(obj != nullptr);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700745 visitor(obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700746 }
747 }
748};
749
750class CardScanTask : public MarkStackTask<false> {
751 public:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700752 CardScanTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
753 accounting::ContinuousSpaceBitmap* bitmap,
Ian Rogers13735952014-10-08 12:43:28 -0700754 uint8_t* begin, uint8_t* end, uint8_t minimum_age, size_t mark_stack_size,
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800755 StackReference<Object>* mark_stack_obj, bool clear_card)
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700756 : MarkStackTask<false>(thread_pool, mark_sweep, mark_stack_size, mark_stack_obj),
757 bitmap_(bitmap),
758 begin_(begin),
759 end_(end),
Lei Li727b2942015-01-15 11:26:34 +0800760 minimum_age_(minimum_age), clear_card_(clear_card) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700761 }
762
763 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700764 accounting::ContinuousSpaceBitmap* const bitmap_;
Ian Rogers13735952014-10-08 12:43:28 -0700765 uint8_t* const begin_;
766 uint8_t* const end_;
767 const uint8_t minimum_age_;
Lei Li727b2942015-01-15 11:26:34 +0800768 const bool clear_card_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700769
770 virtual void Finalize() {
771 delete this;
772 }
773
774 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
775 ScanObjectParallelVisitor visitor(this);
776 accounting::CardTable* card_table = mark_sweep_->GetHeap()->GetCardTable();
Lei Li727b2942015-01-15 11:26:34 +0800777 size_t cards_scanned = clear_card_ ?
778 card_table->Scan<true>(bitmap_, begin_, end_, visitor, minimum_age_) :
779 card_table->Scan<false>(bitmap_, begin_, end_, visitor, minimum_age_);
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700780 VLOG(heap) << "Parallel scanning cards " << reinterpret_cast<void*>(begin_) << " - "
781 << reinterpret_cast<void*>(end_) << " = " << cards_scanned;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700782 // Finish by emptying our local mark stack.
783 MarkStackTask::Run(self);
784 }
785};
786
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700787size_t MarkSweep::GetThreadCount(bool paused) const {
788 if (heap_->GetThreadPool() == nullptr || !heap_->CareAboutPauseTimes()) {
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700789 return 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700790 }
Mathieu Chartier10d68862015-04-15 14:21:33 -0700791 return (paused ? heap_->GetParallelGCThreadCount() : heap_->GetConcGCThreadCount()) + 1;
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700792}
793
Ian Rogers13735952014-10-08 12:43:28 -0700794void MarkSweep::ScanGrayObjects(bool paused, uint8_t minimum_age) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700795 accounting::CardTable* card_table = GetHeap()->GetCardTable();
796 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700797 size_t thread_count = GetThreadCount(paused);
798 // The parallel version with only one thread is faster for card scanning, TODO: fix.
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700799 if (kParallelCardScan && thread_count > 1) {
Mathieu Chartier720ef762013-08-17 14:46:54 -0700800 Thread* self = Thread::Current();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700801 // Can't have a different split for each space since multiple spaces can have their cards being
802 // scanned at the same time.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700803 TimingLogger::ScopedTiming t(paused ? "(Paused)ScanGrayObjects" : __FUNCTION__,
804 GetTimings());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700805 // Try to take some of the mark stack since we can pass this off to the worker tasks.
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800806 StackReference<Object>* mark_stack_begin = mark_stack_->Begin();
807 StackReference<Object>* mark_stack_end = mark_stack_->End();
Mathieu Chartier720ef762013-08-17 14:46:54 -0700808 const size_t mark_stack_size = mark_stack_end - mark_stack_begin;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700809 // Estimated number of work tasks we will create.
810 const size_t mark_stack_tasks = GetHeap()->GetContinuousSpaces().size() * thread_count;
811 DCHECK_NE(mark_stack_tasks, 0U);
812 const size_t mark_stack_delta = std::min(CardScanTask::kMaxSize / 2,
813 mark_stack_size / mark_stack_tasks + 1);
814 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700815 if (space->GetMarkBitmap() == nullptr) {
816 continue;
817 }
Ian Rogers13735952014-10-08 12:43:28 -0700818 uint8_t* card_begin = space->Begin();
819 uint8_t* card_end = space->End();
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800820 // Align up the end address. For example, the image space's end
821 // may not be card-size-aligned.
822 card_end = AlignUp(card_end, accounting::CardTable::kCardSize);
823 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_begin));
824 DCHECK(IsAligned<accounting::CardTable::kCardSize>(card_end));
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700825 // Calculate how many bytes of heap we will scan,
826 const size_t address_range = card_end - card_begin;
827 // Calculate how much address range each task gets.
828 const size_t card_delta = RoundUp(address_range / thread_count + 1,
829 accounting::CardTable::kCardSize);
Lei Li727b2942015-01-15 11:26:34 +0800830 // If paused and the space is neither zygote nor image space, we could clear the dirty
831 // cards to avoid accumulating them to increase card scanning load in the following GC
832 // cycles. We need to keep dirty cards of image space and zygote space in order to track
833 // references to the other spaces.
834 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700835 // Create the worker tasks for this space.
836 while (card_begin != card_end) {
837 // Add a range of cards.
838 size_t addr_remaining = card_end - card_begin;
839 size_t card_increment = std::min(card_delta, addr_remaining);
840 // Take from the back of the mark stack.
841 size_t mark_stack_remaining = mark_stack_end - mark_stack_begin;
842 size_t mark_stack_increment = std::min(mark_stack_delta, mark_stack_remaining);
843 mark_stack_end -= mark_stack_increment;
844 mark_stack_->PopBackCount(static_cast<int32_t>(mark_stack_increment));
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700845 DCHECK_EQ(mark_stack_end, mark_stack_->End());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700846 // Add the new task to the thread pool.
847 auto* task = new CardScanTask(thread_pool, this, space->GetMarkBitmap(), card_begin,
848 card_begin + card_increment, minimum_age,
Lei Li727b2942015-01-15 11:26:34 +0800849 mark_stack_increment, mark_stack_end, clear_card);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700850 thread_pool->AddTask(self, task);
851 card_begin += card_increment;
852 }
853 }
Mathieu Chartier0f72e412013-09-06 16:40:01 -0700854
Hiroshi Yamauchi0941b042013-11-05 11:34:03 -0800855 // Note: the card scan below may dirty new cards (and scan them)
856 // as a side effect when a Reference object is encountered and
857 // queued during the marking. See b/11465268.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700858 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700859 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700860 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700861 thread_pool->StopWorkers(self);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700862 } else {
863 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864 if (space->GetMarkBitmap() != nullptr) {
865 // Image spaces are handled properly since live == marked for them.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700866 const char* name = nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700867 switch (space->GetGcRetentionPolicy()) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700868 case space::kGcRetentionPolicyNeverCollect:
869 name = paused ? "(Paused)ScanGrayImageSpaceObjects" : "ScanGrayImageSpaceObjects";
870 break;
871 case space::kGcRetentionPolicyFullCollect:
872 name = paused ? "(Paused)ScanGrayZygoteSpaceObjects" : "ScanGrayZygoteSpaceObjects";
873 break;
874 case space::kGcRetentionPolicyAlwaysCollect:
875 name = paused ? "(Paused)ScanGrayAllocSpaceObjects" : "ScanGrayAllocSpaceObjects";
876 break;
877 default:
878 LOG(FATAL) << "Unreachable";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700879 UNREACHABLE();
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700880 }
881 TimingLogger::ScopedTiming t(name, GetTimings());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700882 ScanObjectVisitor visitor(this);
Lei Li727b2942015-01-15 11:26:34 +0800883 bool clear_card = paused && !space->IsZygoteSpace() && !space->IsImageSpace();
884 if (clear_card) {
885 card_table->Scan<true>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor,
886 minimum_age);
887 } else {
888 card_table->Scan<false>(space->GetMarkBitmap(), space->Begin(), space->End(), visitor,
889 minimum_age);
890 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700892 }
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700893 }
894}
895
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700896class RecursiveMarkTask : public MarkStackTask<false> {
897 public:
898 RecursiveMarkTask(ThreadPool* thread_pool, MarkSweep* mark_sweep,
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700899 accounting::ContinuousSpaceBitmap* bitmap, uintptr_t begin, uintptr_t end)
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700900 : MarkStackTask<false>(thread_pool, mark_sweep, 0, nullptr), bitmap_(bitmap), begin_(begin),
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700901 end_(end) {
902 }
903
904 protected:
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700905 accounting::ContinuousSpaceBitmap* const bitmap_;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700906 const uintptr_t begin_;
907 const uintptr_t end_;
908
909 virtual void Finalize() {
910 delete this;
911 }
912
913 // Scans all of the objects
914 virtual void Run(Thread* self) NO_THREAD_SAFETY_ANALYSIS {
915 ScanObjectParallelVisitor visitor(this);
916 bitmap_->VisitMarkedRange(begin_, end_, visitor);
917 // Finish by emptying our local mark stack.
918 MarkStackTask::Run(self);
919 }
920};
921
Carl Shapiro58551df2011-07-24 03:09:51 -0700922// Populates the mark stack based on the set of marked objects and
923// recursively marks until the mark stack is emptied.
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800924void MarkSweep::RecursiveMark() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700925 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800926 // RecursiveMark will build the lists of known instances of the Reference classes. See
927 // DelayReferenceReferent for details.
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700928 if (kUseRecursiveMark) {
929 const bool partial = GetGcType() == kGcTypePartial;
930 ScanObjectVisitor scan_visitor(this);
931 auto* self = Thread::Current();
932 ThreadPool* thread_pool = heap_->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700933 size_t thread_count = GetThreadCount(false);
934 const bool parallel = kParallelRecursiveMark && thread_count > 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700935 mark_stack_->Reset();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700936 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Ian Rogers1d54e732013-05-02 21:10:01 -0700937 if ((space->GetGcRetentionPolicy() == space::kGcRetentionPolicyAlwaysCollect) ||
938 (!partial && space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect)) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700939 current_space_bitmap_ = space->GetMarkBitmap();
940 if (current_space_bitmap_ == nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700941 continue;
Mathieu Chartier2b82db42012-11-14 17:29:05 -0800942 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700943 if (parallel) {
944 // We will use the mark stack the future.
945 // CHECK(mark_stack_->IsEmpty());
946 // This function does not handle heap end increasing, so we must use the space end.
947 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
948 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Ian Rogers3e5cf302014-05-20 16:40:37 -0700949 atomic_finger_.StoreRelaxed(AtomicInteger::MaxValue());
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700950
951 // Create a few worker tasks.
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700952 const size_t n = thread_count * 2;
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700953 while (begin != end) {
954 uintptr_t start = begin;
955 uintptr_t delta = (end - begin) / n;
956 delta = RoundUp(delta, KB);
957 if (delta < 16 * KB) delta = end - begin;
958 begin += delta;
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700959 auto* task = new RecursiveMarkTask(thread_pool, this, current_space_bitmap_, start,
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700960 begin);
961 thread_pool->AddTask(self, task);
962 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700963 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700964 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -0700965 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700966 thread_pool->StopWorkers(self);
967 } else {
968 // This function does not handle heap end increasing, so we must use the space end.
969 uintptr_t begin = reinterpret_cast<uintptr_t>(space->Begin());
970 uintptr_t end = reinterpret_cast<uintptr_t>(space->End());
Mathieu Chartier0e54cd02014-03-20 12:41:23 -0700971 current_space_bitmap_->VisitMarkedRange(begin, end, scan_visitor);
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700972 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700973 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700974 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700975 }
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700976 ProcessMarkStack(false);
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700977}
978
Mathieu Chartier83c8ee02014-01-28 14:50:23 -0800979mirror::Object* MarkSweep::IsMarkedCallback(mirror::Object* object, void* arg) {
Mathieu Chartier5712d5d2013-09-18 17:59:36 -0700980 if (reinterpret_cast<MarkSweep*>(arg)->IsMarked(object)) {
Mathieu Chartier6aa3df92013-09-17 15:17:28 -0700981 return object;
982 }
983 return nullptr;
Mathieu Chartier357e9be2012-08-01 11:00:14 -0700984}
985
Ian Rogers13735952014-10-08 12:43:28 -0700986void MarkSweep::RecursiveMarkDirtyObjects(bool paused, uint8_t minimum_age) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -0700987 ScanGrayObjects(paused, minimum_age);
988 ProcessMarkStack(paused);
Mathieu Chartier262e5ff2012-06-01 17:35:38 -0700989}
990
Carl Shapiro58551df2011-07-24 03:09:51 -0700991void MarkSweep::ReMarkRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700992 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier893263b2014-03-04 11:07:42 -0800993 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700994 Runtime::Current()->VisitRoots(this, static_cast<VisitRootFlags>(
995 kVisitRootFlagNewRoots | kVisitRootFlagStopLoggingNewRoots | kVisitRootFlagClearRootLog));
Mathieu Chartier7bf9f192014-04-04 11:09:41 -0700996 if (kVerifyRootsMarked) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800997 TimingLogger::ScopedTiming t2("(Paused)VerifyRoots", GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700998 VerifyRootMarkedVisitor visitor(this);
999 Runtime::Current()->VisitRoots(&visitor);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001000 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001001}
1002
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001003void MarkSweep::SweepSystemWeaks(Thread* self) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001004 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001005 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001006 Runtime::Current()->SweepSystemWeaks(IsMarkedCallback, this);
Carl Shapiro58551df2011-07-24 03:09:51 -07001007}
1008
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001009mirror::Object* MarkSweep::VerifySystemWeakIsLiveCallback(Object* obj, void* arg) {
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001010 reinterpret_cast<MarkSweep*>(arg)->VerifyIsLive(obj);
1011 // We don't actually want to sweep the object, so lets return "marked"
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001012 return obj;
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001013}
1014
1015void MarkSweep::VerifyIsLive(const Object* obj) {
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001016 if (!heap_->GetLiveBitmap()->Test(obj)) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001017 // TODO: Consider live stack? Has this code bitrotted?
1018 CHECK(!heap_->allocation_stack_->Contains(obj))
1019 << "Found dead object " << obj << "\n" << heap_->DumpSpaces();
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001020 }
1021}
1022
1023void MarkSweep::VerifySystemWeaks() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001024 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier6aa3df92013-09-17 15:17:28 -07001025 // Verify system weaks, uses a special object visitor which returns the input object.
1026 Runtime::Current()->SweepSystemWeaks(VerifySystemWeakIsLiveCallback, this);
Mathieu Chartierc7b83a02012-09-11 18:07:39 -07001027}
1028
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001029class CheckpointMarkThreadRoots : public Closure, public RootVisitor {
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001030 public:
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001031 explicit CheckpointMarkThreadRoots(MarkSweep* mark_sweep,
1032 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint)
1033 : mark_sweep_(mark_sweep),
1034 revoke_ros_alloc_thread_local_buffers_at_checkpoint_(
1035 revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
1036 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001037
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001038 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
1039 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1040 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1041 for (size_t i = 0; i < count; ++i) {
1042 mark_sweep_->MarkObjectNonNullParallel(*roots[i]);
1043 }
1044 }
1045
1046 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1047 const RootInfo& info ATTRIBUTE_UNUSED)
1048 OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1049 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1050 for (size_t i = 0; i < count; ++i) {
1051 mark_sweep_->MarkObjectNonNullParallel(roots[i]->AsMirrorPtr());
1052 }
1053 }
1054
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001055 virtual void Run(Thread* thread) OVERRIDE NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier3f966702013-09-04 16:50:05 -07001056 ATRACE_BEGIN("Marking thread roots");
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001057 // Note: self is not necessarily equal to thread since thread may be suspended.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001058 Thread* const self = Thread::Current();
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001059 CHECK(thread == self || thread->IsSuspended() || thread->GetState() == kWaitingPerformingGc)
1060 << thread->GetState() << " thread " << thread << " self " << self;
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001061 thread->VisitRoots(this);
Mathieu Chartier3f966702013-09-04 16:50:05 -07001062 ATRACE_END();
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001063 if (revoke_ros_alloc_thread_local_buffers_at_checkpoint_) {
1064 ATRACE_BEGIN("RevokeRosAllocThreadLocalBuffers");
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001065 mark_sweep_->GetHeap()->RevokeRosAllocThreadLocalBuffers(thread);
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001066 ATRACE_END();
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001067 }
Lei Lidd9943d2015-02-02 14:24:44 +08001068 // If thread is a running mutator, then act on behalf of the garbage collector.
1069 // See the code in ThreadList::RunCheckpoint.
1070 if (thread->GetState() == kRunnable) {
1071 mark_sweep_->GetBarrier().Pass(self);
1072 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001073 }
1074
1075 private:
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001076 MarkSweep* const mark_sweep_;
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001077 const bool revoke_ros_alloc_thread_local_buffers_at_checkpoint_;
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001078};
1079
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001080void MarkSweep::MarkRootsCheckpoint(Thread* self,
1081 bool revoke_ros_alloc_thread_local_buffers_at_checkpoint) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001082 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001083 CheckpointMarkThreadRoots check_point(this, revoke_ros_alloc_thread_local_buffers_at_checkpoint);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001084 ThreadList* thread_list = Runtime::Current()->GetThreadList();
Ian Rogers1d54e732013-05-02 21:10:01 -07001085 // Request the check point is run on all threads returning a count of the threads that must
1086 // run through the barrier including self.
1087 size_t barrier_count = thread_list->RunCheckpoint(&check_point);
1088 // Release locks then wait for all mutator threads to pass the barrier.
Lei Lidd9943d2015-02-02 14:24:44 +08001089 // If there are no threads to wait which implys that all the checkpoint functions are finished,
1090 // then no need to release locks.
1091 if (barrier_count == 0) {
1092 return;
1093 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001094 Locks::heap_bitmap_lock_->ExclusiveUnlock(self);
1095 Locks::mutator_lock_->SharedUnlock(self);
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001096 {
1097 ScopedThreadStateChange tsc(self, kWaitingForCheckPointsToRun);
1098 gc_barrier_->Increment(self, barrier_count);
1099 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001100 Locks::mutator_lock_->SharedLock(self);
1101 Locks::heap_bitmap_lock_->ExclusiveLock(self);
Mathieu Chartier858f1c52012-10-17 17:45:55 -07001102}
1103
Ian Rogers1d54e732013-05-02 21:10:01 -07001104void MarkSweep::SweepArray(accounting::ObjectStack* allocations, bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001105 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001106 Thread* self = Thread::Current();
Hiroshi Yamauchibbdc5bc2014-05-28 14:04:59 -07001107 mirror::Object** chunk_free_buffer = reinterpret_cast<mirror::Object**>(
1108 sweep_array_free_buffer_mem_map_->BaseBegin());
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001109 size_t chunk_free_pos = 0;
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001110 ObjectBytePair freed;
1111 ObjectBytePair freed_los;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001112 // How many objects are left in the array, modified after each space is swept.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001113 StackReference<Object>* objects = allocations->Begin();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001114 size_t count = allocations->Size();
1115 // Change the order to ensure that the non-moving space last swept as an optimization.
1116 std::vector<space::ContinuousSpace*> sweep_spaces;
1117 space::ContinuousSpace* non_moving_space = nullptr;
1118 for (space::ContinuousSpace* space : heap_->GetContinuousSpaces()) {
Mathieu Chartier8d562102014-03-12 17:42:10 -07001119 if (space->IsAllocSpace() && !immune_region_.ContainsSpace(space) &&
1120 space->GetLiveBitmap() != nullptr) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001121 if (space == heap_->GetNonMovingSpace()) {
1122 non_moving_space = space;
1123 } else {
1124 sweep_spaces.push_back(space);
1125 }
1126 }
1127 }
1128 // Unlikely to sweep a significant amount of non_movable objects, so we do these after the after
1129 // the other alloc spaces as an optimization.
1130 if (non_moving_space != nullptr) {
1131 sweep_spaces.push_back(non_moving_space);
1132 }
1133 // Start by sweeping the continuous spaces.
1134 for (space::ContinuousSpace* space : sweep_spaces) {
1135 space::AllocSpace* alloc_space = space->AsAllocSpace();
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001136 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1137 accounting::ContinuousSpaceBitmap* mark_bitmap = space->GetMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001138 if (swap_bitmaps) {
1139 std::swap(live_bitmap, mark_bitmap);
1140 }
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001141 StackReference<Object>* out = objects;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001142 for (size_t i = 0; i < count; ++i) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001143 Object* const obj = objects[i].AsMirrorPtr();
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001144 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1145 continue;
1146 }
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001147 if (space->HasAddress(obj)) {
1148 // This object is in the space, remove it from the array and add it to the sweep buffer
1149 // if needed.
1150 if (!mark_bitmap->Test(obj)) {
1151 if (chunk_free_pos >= kSweepArrayChunkFreeSize) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001152 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001153 freed.objects += chunk_free_pos;
1154 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001155 chunk_free_pos = 0;
1156 }
1157 chunk_free_buffer[chunk_free_pos++] = obj;
1158 }
1159 } else {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001160 (out++)->Assign(obj);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001161 }
1162 }
1163 if (chunk_free_pos > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001164 TimingLogger::ScopedTiming t2("FreeList", GetTimings());
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001165 freed.objects += chunk_free_pos;
1166 freed.bytes += alloc_space->FreeList(self, chunk_free_pos, chunk_free_buffer);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -08001167 chunk_free_pos = 0;
1168 }
1169 // All of the references which space contained are no longer in the allocation stack, update
1170 // the count.
1171 count = out - objects;
1172 }
1173 // Handle the large object space.
1174 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001175 if (large_object_space != nullptr) {
1176 accounting::LargeObjectBitmap* large_live_objects = large_object_space->GetLiveBitmap();
1177 accounting::LargeObjectBitmap* large_mark_objects = large_object_space->GetMarkBitmap();
1178 if (swap_bitmaps) {
1179 std::swap(large_live_objects, large_mark_objects);
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -08001180 }
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001181 for (size_t i = 0; i < count; ++i) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001182 Object* const obj = objects[i].AsMirrorPtr();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001183 // Handle large objects.
1184 if (kUseThreadLocalAllocationStack && obj == nullptr) {
1185 continue;
1186 }
1187 if (!large_mark_objects->Test(obj)) {
1188 ++freed_los.objects;
1189 freed_los.bytes += large_object_space->Free(self, obj);
1190 }
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001191 }
1192 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001193 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001194 TimingLogger::ScopedTiming t2("RecordFree", GetTimings());
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001195 RecordFree(freed);
1196 RecordFreeLOS(freed_los);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001197 t2.NewTiming("ResetStack");
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001198 allocations->Reset();
1199 }
Ian Rogersc5f17732014-06-05 20:48:42 -07001200 sweep_array_free_buffer_mem_map_->MadviseDontNeedAndZero();
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001201}
1202
Ian Rogers1d54e732013-05-02 21:10:01 -07001203void MarkSweep::Sweep(bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001204 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier0f7bf6a2014-03-28 10:05:39 -07001205 // Ensure that nobody inserted items in the live stack after we swapped the stacks.
1206 CHECK_GE(live_stack_freeze_size_, GetHeap()->GetLiveStack()->Size());
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001207 {
1208 TimingLogger::ScopedTiming t2("MarkAllocStackAsLive", GetTimings());
1209 // Mark everything allocated since the last as GC live so that we can sweep concurrently,
1210 // knowing that new allocations won't be marked as live.
1211 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
1212 heap_->MarkAllocStackAsLive(live_stack);
1213 live_stack->Reset();
1214 DCHECK(mark_stack_->IsEmpty());
1215 }
Mathieu Chartier02e25112013-08-14 16:14:24 -07001216 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -08001217 if (space->IsContinuousMemMapAllocSpace()) {
1218 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001219 TimingLogger::ScopedTiming split(
Mathieu Chartier10fb83a2014-06-15 15:15:43 -07001220 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepMallocSpace", GetTimings());
1221 RecordFree(alloc_space->Sweep(swap_bitmaps));
Carl Shapiro58551df2011-07-24 03:09:51 -07001222 }
1223 }
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001224 SweepLargeObjects(swap_bitmaps);
Carl Shapiro58551df2011-07-24 03:09:51 -07001225}
1226
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001227void MarkSweep::SweepLargeObjects(bool swap_bitmaps) {
Mathieu Chartier2dbe6272014-09-16 10:43:23 -07001228 space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
1229 if (los != nullptr) {
1230 TimingLogger::ScopedTiming split(__FUNCTION__, GetTimings());
1231 RecordFreeLOS(los->Sweep(swap_bitmaps));
1232 }
Mathieu Chartiere0f0cb32012-08-28 11:26:00 -07001233}
1234
Mathieu Chartier407f7022014-02-18 14:37:05 -08001235// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
1236// marked, put it on the appropriate list in the heap for later processing.
1237void MarkSweep::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref) {
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001238 if (kCountJavaLangRefs) {
1239 ++reference_count_;
1240 }
Mathieu Chartier308351a2014-06-15 12:39:02 -07001241 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, ref, &HeapReferenceMarkedCallback,
1242 this);
Carl Shapiro69759ea2011-07-21 18:13:35 -07001243}
1244
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001245class MarkObjectVisitor {
1246 public:
Mathieu Chartier407f7022014-02-18 14:37:05 -08001247 explicit MarkObjectVisitor(MarkSweep* const mark_sweep) ALWAYS_INLINE : mark_sweep_(mark_sweep) {
1248 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001249
Mathieu Chartier407f7022014-02-18 14:37:05 -08001250 void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const
1251 ALWAYS_INLINE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1252 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001253 if (kCheckLocks) {
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001254 Locks::mutator_lock_->AssertSharedHeld(Thread::Current());
1255 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
1256 }
Hiroshi Yamauchieb2baaf2015-05-13 21:14:22 -07001257 mark_sweep_->MarkObject(obj->GetFieldObject<mirror::Object>(offset), obj, offset);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001258 }
1259
1260 private:
1261 MarkSweep* const mark_sweep_;
1262};
1263
Carl Shapiro69759ea2011-07-21 18:13:35 -07001264// Scans an object reference. Determines the type of the reference
1265// and dispatches to a specialized scanning routine.
Mathieu Chartier590fee92013-09-13 13:46:47 -07001266void MarkSweep::ScanObject(Object* obj) {
Mathieu Chartier407f7022014-02-18 14:37:05 -08001267 MarkObjectVisitor mark_visitor(this);
1268 DelayReferenceReferentVisitor ref_visitor(this);
1269 ScanObjectVisit(obj, mark_visitor, ref_visitor);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001270}
1271
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -07001272void MarkSweep::ProcessMarkStackCallback(void* arg) {
1273 reinterpret_cast<MarkSweep*>(arg)->ProcessMarkStack(false);
Mathieu Chartier3bb57c72014-02-18 11:38:45 -08001274}
1275
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001276void MarkSweep::ProcessMarkStackParallel(size_t thread_count) {
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001277 Thread* self = Thread::Current();
1278 ThreadPool* thread_pool = GetHeap()->GetThreadPool();
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001279 const size_t chunk_size = std::min(mark_stack_->Size() / thread_count + 1,
1280 static_cast<size_t>(MarkStackTask<false>::kMaxSize));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001281 CHECK_GT(chunk_size, 0U);
1282 // Split the current mark stack up into work tasks.
Mathieu Chartiercb535da2015-01-23 13:50:03 -08001283 for (auto* it = mark_stack_->Begin(), *end = mark_stack_->End(); it < end; ) {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001284 const size_t delta = std::min(static_cast<size_t>(end - it), chunk_size);
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001285 thread_pool->AddTask(self, new MarkStackTask<false>(thread_pool, this, delta, it));
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001286 it += delta;
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001287 }
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001288 thread_pool->SetMaxActiveWorkers(thread_count - 1);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001289 thread_pool->StartWorkers(self);
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001290 thread_pool->Wait(self, true, true);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001291 thread_pool->StopWorkers(self);
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001292 mark_stack_->Reset();
Ian Rogers3e5cf302014-05-20 16:40:37 -07001293 CHECK_EQ(work_chunks_created_.LoadSequentiallyConsistent(),
1294 work_chunks_deleted_.LoadSequentiallyConsistent())
1295 << " some of the work chunks were leaked";
Carl Shapiro69759ea2011-07-21 18:13:35 -07001296}
1297
Ian Rogers5d76c432011-10-31 21:42:49 -07001298// Scan anything that's on the mark stack.
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001299void MarkSweep::ProcessMarkStack(bool paused) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001300 TimingLogger::ScopedTiming t(paused ? "(Paused)ProcessMarkStack" : __FUNCTION__, GetTimings());
Mathieu Chartier2775ee42013-08-20 17:43:47 -07001301 size_t thread_count = GetThreadCount(paused);
1302 if (kParallelProcessMarkStack && thread_count > 1 &&
1303 mark_stack_->Size() >= kMinimumParallelMarkStackSize) {
1304 ProcessMarkStackParallel(thread_count);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001305 } else {
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001306 // TODO: Tune this.
1307 static const size_t kFifoSize = 4;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001308 BoundedFifoPowerOfTwo<Object*, kFifoSize> prefetch_fifo;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001309 for (;;) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001310 Object* obj = nullptr;
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001311 if (kUseMarkStackPrefetch) {
1312 while (!mark_stack_->IsEmpty() && prefetch_fifo.size() < kFifoSize) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001313 Object* mark_stack_obj = mark_stack_->PopBack();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001314 DCHECK(mark_stack_obj != nullptr);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001315 __builtin_prefetch(mark_stack_obj);
1316 prefetch_fifo.push_back(mark_stack_obj);
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001317 }
1318 if (prefetch_fifo.empty()) {
1319 break;
1320 }
1321 obj = prefetch_fifo.front();
1322 prefetch_fifo.pop_front();
1323 } else {
1324 if (mark_stack_->IsEmpty()) {
1325 break;
1326 }
1327 obj = mark_stack_->PopBack();
1328 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001329 DCHECK(obj != nullptr);
Mathieu Chartierd8195f12012-10-05 12:21:28 -07001330 ScanObject(obj);
Mathieu Chartier357e9be2012-08-01 11:00:14 -07001331 }
1332 }
Carl Shapiro69759ea2011-07-21 18:13:35 -07001333}
1334
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001335inline bool MarkSweep::IsMarked(const Object* object) const {
Mathieu Chartier8d562102014-03-12 17:42:10 -07001336 if (immune_region_.ContainsObject(object)) {
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001337 return true;
1338 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001339 if (current_space_bitmap_->HasAddress(object)) {
1340 return current_space_bitmap_->Test(object);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001341 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001342 return mark_bitmap_->Test(object);
Mathieu Chartier7469ebf2012-09-24 16:28:36 -07001343}
1344
Mathieu Chartier2b82db42012-11-14 17:29:05 -08001345void MarkSweep::FinishPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001346 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001347 if (kCountScannedTypes) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001348 VLOG(gc) << "MarkSweep scanned classes=" << class_count_.LoadRelaxed()
1349 << " arrays=" << array_count_.LoadRelaxed() << " other=" << other_count_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001350 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001351 if (kCountTasks) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001352 VLOG(gc) << "Total number of work chunks allocated: " << work_chunks_created_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001353 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001354 if (kMeasureOverhead) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001355 VLOG(gc) << "Overhead time " << PrettyDuration(overhead_time_.LoadRelaxed());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001356 }
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001357 if (kProfileLargeObjects) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001358 VLOG(gc) << "Large objects tested " << large_object_test_.LoadRelaxed()
1359 << " marked " << large_object_mark_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001360 }
Mathieu Chartierd22d5482012-11-06 17:14:12 -08001361 if (kCountJavaLangRefs) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001362 VLOG(gc) << "References scanned " << reference_count_.LoadRelaxed();
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001363 }
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001364 if (kCountMarkedObjects) {
Ian Rogers3e5cf302014-05-20 16:40:37 -07001365 VLOG(gc) << "Marked: null=" << mark_null_count_.LoadRelaxed()
1366 << " immune=" << mark_immune_count_.LoadRelaxed()
1367 << " fastpath=" << mark_fastpath_count_.LoadRelaxed()
1368 << " slowpath=" << mark_slowpath_count_.LoadRelaxed();
Mathieu Chartier0e54cd02014-03-20 12:41:23 -07001369 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001370 CHECK(mark_stack_->IsEmpty()); // Ensure that the mark stack is empty.
Mathieu Chartier5301cd22012-05-31 12:11:36 -07001371 mark_stack_->Reset();
Mathieu Chartier4aeec172014-03-27 16:09:46 -07001372 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1373 heap_->ClearMarkedObjects();
Carl Shapiro69759ea2011-07-21 18:13:35 -07001374}
1375
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001376void MarkSweep::RevokeAllThreadLocalBuffers() {
1377 if (kRevokeRosAllocThreadLocalBuffersAtCheckpoint && IsConcurrent()) {
1378 // If concurrent, rosalloc thread-local buffers are revoked at the
1379 // thread checkpoint. Bump pointer space thread-local buffers must
1380 // not be in use.
1381 GetHeap()->AssertAllBumpPointerSpaceThreadLocalBuffersAreRevoked();
1382 } else {
Mathieu Chartierf5997b42014-06-20 10:37:54 -07001383 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001384 GetHeap()->RevokeAllThreadLocalBuffers();
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -07001385 }
1386}
1387
Ian Rogers1d54e732013-05-02 21:10:01 -07001388} // namespace collector
1389} // namespace gc
Carl Shapiro69759ea2011-07-21 18:13:35 -07001390} // namespace art