blob: 2cb17671e5211842856e0f699de4c4866acf0ac2 [file] [log] [blame]
Mathieu Chartier590fee92013-09-13 13:46:47 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -070017#include "semi_space-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070018
Ian Rogersc7dd2952014-10-21 23:31:19 -070019#include <climits>
Mathieu Chartier590fee92013-09-13 13:46:47 -070020#include <functional>
21#include <numeric>
Ian Rogersc7dd2952014-10-21 23:31:19 -070022#include <sstream>
Mathieu Chartier590fee92013-09-13 13:46:47 -070023#include <vector>
24
25#include "base/logging.h"
26#include "base/macros.h"
27#include "base/mutex-inl.h"
28#include "base/timing_logger.h"
Mathieu Chartier4aeec172014-03-27 16:09:46 -070029#include "gc/accounting/heap_bitmap-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070030#include "gc/accounting/mod_union_table.h"
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -080031#include "gc/accounting/remembered_set.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070032#include "gc/accounting/space_bitmap-inl.h"
33#include "gc/heap.h"
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -070034#include "gc/reference_processor.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070035#include "gc/space/bump_pointer_space.h"
36#include "gc/space/bump_pointer_space-inl.h"
37#include "gc/space/image_space.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
40#include "indirect_reference_table.h"
41#include "intern_table.h"
42#include "jni_internal.h"
43#include "mark_sweep-inl.h"
44#include "monitor.h"
Mathieu Chartier8fa2dad2014-03-13 12:22:56 -070045#include "mirror/reference-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070046#include "mirror/object-inl.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070047#include "runtime.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070048#include "thread-inl.h"
49#include "thread_list.h"
Mathieu Chartier590fee92013-09-13 13:46:47 -070050
Mathieu Chartier590fee92013-09-13 13:46:47 -070051using ::art::mirror::Object;
52
53namespace art {
54namespace gc {
55namespace collector {
56
57static constexpr bool kProtectFromSpace = true;
Mathieu Chartier15d34022014-02-26 17:16:38 -080058static constexpr bool kStoreStackTraces = false;
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -070059static constexpr size_t kBytesPromotedThreshold = 4 * MB;
Hiroshi Yamauchi24faeb22014-05-07 13:12:43 -070060static constexpr size_t kLargeObjectBytesAllocatedThreshold = 16 * MB;
Mathieu Chartier590fee92013-09-13 13:46:47 -070061
Mathieu Chartier590fee92013-09-13 13:46:47 -070062void SemiSpace::BindBitmaps() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -070063 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiera1602f22014-01-13 17:19:19 -080064 WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -070065 // Mark all of the spaces we never collect as immune.
66 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -070067 if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect ||
68 space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -080069 immune_spaces_.AddSpace(space);
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -070070 } else if (space->GetLiveBitmap() != nullptr) {
Mathieu Chartier763a31e2015-11-16 16:05:55 -080071 // TODO: We can probably also add this space to the immune region.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -070072 if (space == to_space_ || collect_from_space_only_) {
73 if (collect_from_space_only_) {
Mathieu Chartierb363f662014-07-16 13:28:58 -070074 // Bind the bitmaps of the main free list space and the non-moving space we are doing a
75 // bump pointer space only collection.
76 CHECK(space == GetHeap()->GetPrimaryFreeListSpace() ||
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -070077 space == GetHeap()->GetNonMovingSpace());
78 }
79 CHECK(space->IsContinuousMemMapAllocSpace());
80 space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -080081 }
Mathieu Chartier590fee92013-09-13 13:46:47 -070082 }
83 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -070084 if (collect_from_space_only_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -080085 // We won't collect the large object space if a bump pointer space only collection.
86 is_large_object_space_immune_ = true;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -080087 }
Mathieu Chartier590fee92013-09-13 13:46:47 -070088}
89
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -080090SemiSpace::SemiSpace(Heap* heap, bool generational, const std::string& name_prefix)
Mathieu Chartier590fee92013-09-13 13:46:47 -070091 : GarbageCollector(heap,
92 name_prefix + (name_prefix.empty() ? "" : " ") + "marksweep + semispace"),
Sebastien Hertzaa50d3a2015-08-25 15:25:41 +020093 mark_stack_(nullptr),
94 is_large_object_space_immune_(false),
Mathieu Chartier590fee92013-09-13 13:46:47 -070095 to_space_(nullptr),
Sebastien Hertzaa50d3a2015-08-25 15:25:41 +020096 to_space_live_bitmap_(nullptr),
Mathieu Chartier590fee92013-09-13 13:46:47 -070097 from_space_(nullptr),
Sebastien Hertzaa50d3a2015-08-25 15:25:41 +020098 mark_bitmap_(nullptr),
99 self_(nullptr),
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800100 generational_(generational),
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800101 last_gc_to_space_end_(nullptr),
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800102 bytes_promoted_(0),
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700103 bytes_promoted_since_last_whole_heap_collection_(0),
Hiroshi Yamauchi24faeb22014-05-07 13:12:43 -0700104 large_object_bytes_allocated_at_last_whole_heap_collection_(0),
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700105 collect_from_space_only_(generational),
Sebastien Hertzaa50d3a2015-08-25 15:25:41 +0200106 promo_dest_space_(nullptr),
107 fallback_space_(nullptr),
108 bytes_moved_(0U),
109 objects_moved_(0U),
110 saved_bytes_(0U),
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700111 collector_name_(name_),
112 swap_semi_spaces_(true) {
113}
114
115void SemiSpace::RunPhases() {
116 Thread* self = Thread::Current();
117 InitializePhase();
118 // Semi-space collector is special since it is sometimes called with the mutators suspended
119 // during the zygote creation and collector transitions. If we already exclusively hold the
120 // mutator lock, then we can't lock it again since it will cause a deadlock.
121 if (Locks::mutator_lock_->IsExclusiveHeld(self)) {
122 GetHeap()->PreGcVerificationPaused(this);
123 GetHeap()->PrePauseRosAllocVerification(this);
124 MarkingPhase();
125 ReclaimPhase();
126 GetHeap()->PostGcVerificationPaused(this);
127 } else {
128 Locks::mutator_lock_->AssertNotHeld(self);
129 {
130 ScopedPause pause(this);
131 GetHeap()->PreGcVerificationPaused(this);
132 GetHeap()->PrePauseRosAllocVerification(this);
133 MarkingPhase();
134 }
135 {
136 ReaderMutexLock mu(self, *Locks::mutator_lock_);
137 ReclaimPhase();
138 }
139 GetHeap()->PostGcVerification(this);
140 }
141 FinishPhase();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700142}
143
144void SemiSpace::InitializePhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700145 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700146 mark_stack_ = heap_->GetMarkStack();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700147 DCHECK(mark_stack_ != nullptr);
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800148 immune_spaces_.Reset();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800149 is_large_object_space_immune_ = false;
Mathieu Chartierad35d902014-02-11 16:20:42 -0800150 saved_bytes_ = 0;
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700151 bytes_moved_ = 0;
152 objects_moved_ = 0;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700153 self_ = Thread::Current();
Mathieu Chartier31f44142014-04-08 14:40:03 -0700154 CHECK(from_space_->CanMoveObjects()) << "Attempting to move from " << *from_space_;
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800155 // Set the initial bitmap.
156 to_space_live_bitmap_ = to_space_->GetLiveBitmap();
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700157 {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700158 // TODO: I don't think we should need heap bitmap lock to Get the mark bitmap.
Mathieu Chartierbbd695c2014-04-16 09:48:48 -0700159 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
160 mark_bitmap_ = heap_->GetMarkBitmap();
161 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700162 if (generational_) {
163 promo_dest_space_ = GetHeap()->GetPrimaryFreeListSpace();
164 }
165 fallback_space_ = GetHeap()->GetNonMovingSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700166}
167
168void SemiSpace::ProcessReferences(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700169 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier78f7b4c2014-05-06 10:57:27 -0700170 GetHeap()->GetReferenceProcessor()->ProcessReferences(
Mathieu Chartier97509952015-07-13 14:35:43 -0700171 false, GetTimings(), GetCurrentIteration()->GetClearSoftReferences(), this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700172}
173
174void SemiSpace::MarkingPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700175 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700176 CHECK(Locks::mutator_lock_->IsExclusiveHeld(self_));
Mathieu Chartier15d34022014-02-26 17:16:38 -0800177 if (kStoreStackTraces) {
178 Locks::mutator_lock_->AssertExclusiveHeld(self_);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700179 // Store the stack traces into the runtime fault string in case we Get a heap corruption
Mathieu Chartier15d34022014-02-26 17:16:38 -0800180 // related crash later.
181 ThreadState old_state = self_->SetStateUnsafe(kRunnable);
182 std::ostringstream oss;
183 Runtime* runtime = Runtime::Current();
184 runtime->GetThreadList()->DumpForSigQuit(oss);
185 runtime->GetThreadList()->DumpNativeStacks(oss);
186 runtime->SetFaultMessage(oss.str());
187 CHECK_EQ(self_->SetStateUnsafe(old_state), kRunnable);
188 }
Mathieu Chartier0651d412014-04-29 14:37:57 -0700189 // Revoke the thread local buffers since the GC may allocate into a RosAllocSpace and this helps
190 // to prevent fragmentation.
191 RevokeAllThreadLocalBuffers();
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800192 if (generational_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700193 if (GetCurrentIteration()->GetGcCause() == kGcCauseExplicit ||
194 GetCurrentIteration()->GetGcCause() == kGcCauseForNativeAlloc ||
195 GetCurrentIteration()->GetClearSoftReferences()) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800196 // If an explicit, native allocation-triggered, or last attempt
Hiroshi Yamauchi24faeb22014-05-07 13:12:43 -0700197 // collection, collect the whole heap.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700198 collect_from_space_only_ = false;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800199 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700200 if (!collect_from_space_only_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800201 VLOG(heap) << "Whole heap collection";
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700202 name_ = collector_name_ + " whole";
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800203 } else {
204 VLOG(heap) << "Bump pointer space only collection";
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700205 name_ = collector_name_ + " bps";
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800206 }
207 }
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700208
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700209 if (!collect_from_space_only_) {
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700210 // If non-generational, always clear soft references.
211 // If generational, clear soft references if a whole heap collection.
212 GetCurrentIteration()->SetClearSoftReferences(true);
Hiroshi Yamauchidf386c52014-04-08 16:21:52 -0700213 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800214 Locks::mutator_lock_->AssertExclusiveHeld(self_);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800215 if (generational_) {
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800216 // If last_gc_to_space_end_ is out of the bounds of the from-space
217 // (the to-space from last GC), then point it to the beginning of
218 // the from-space. For example, the very first GC or the
219 // pre-zygote compaction.
220 if (!from_space_->HasAddress(reinterpret_cast<mirror::Object*>(last_gc_to_space_end_))) {
221 last_gc_to_space_end_ = from_space_->Begin();
222 }
223 // Reset this before the marking starts below.
224 bytes_promoted_ = 0;
225 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700226 // Assume the cleared space is already empty.
227 BindBitmaps();
228 // Process dirty cards and add dirty cards to mod-union tables.
Lei Li4add3b42015-01-15 11:55:26 +0800229 heap_->ProcessCards(GetTimings(), kUseRememberedSet && generational_, false, true);
Roland Levillain91d65e02016-01-19 15:59:16 +0000230 // Clear the whole card table since we cannot get any additional dirty cards during the
Mathieu Chartierc528dba2013-11-26 12:00:11 -0800231 // paused GC. This saves memory but only works for pause the world collectors.
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700232 t.NewTiming("ClearCardTable");
Mathieu Chartierc528dba2013-11-26 12:00:11 -0800233 heap_->GetCardTable()->ClearCardTable();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700234 // Need to do this before the checkpoint since we don't want any threads to add references to
235 // the live stack during the recursive mark.
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800236 if (kUseThreadLocalAllocationStack) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800237 TimingLogger::ScopedTiming t2("RevokeAllThreadLocalAllocationStacks", GetTimings());
Hiroshi Yamauchif5b0e202014-02-11 17:02:22 -0800238 heap_->RevokeAllThreadLocalAllocationStacks(self_);
239 }
Mathieu Chartiera4f6af92015-08-11 17:35:25 -0700240 heap_->SwapStacks();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700241 {
242 WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
243 MarkRoots();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700244 // Recursively mark remaining objects.
245 MarkReachableObjects();
246 }
247 ProcessReferences(self_);
248 {
249 ReaderMutexLock mu(self_, *Locks::heap_bitmap_lock_);
250 SweepSystemWeaks();
251 }
Mathieu Chartier951ec2c2015-09-22 08:50:05 -0700252 Runtime::Current()->GetClassLinker()->CleanupClassLoaders();
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700253 // Revoke buffers before measuring how many objects were moved since the TLABs need to be revoked
254 // before they are properly counted.
255 RevokeAllThreadLocalBuffers();
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700256 GetHeap()->RecordFreeRevoke(); // this is for the non-moving rosalloc space used by GSS.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700257 // Record freed memory.
Mathieu Chartiere76e70f2014-05-02 16:35:37 -0700258 const int64_t from_bytes = from_space_->GetBytesAllocated();
259 const int64_t to_bytes = bytes_moved_;
260 const uint64_t from_objects = from_space_->GetObjectsAllocated();
261 const uint64_t to_objects = objects_moved_;
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700262 CHECK_LE(to_objects, from_objects);
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700263 // Note: Freed bytes can be negative if we copy form a compacted space to a free-list backed
264 // space.
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700265 RecordFree(ObjectBytePair(from_objects - to_objects, from_bytes - to_bytes));
Hiroshi Yamauchi312baf12015-01-12 12:11:05 -0800266 // Clear and protect the from space.
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700267 from_space_->Clear();
Hiroshi Yamauchi34cf8322016-09-06 12:24:52 -0700268 // b/31172841. Temporarily disable the from-space protection with host debug build
269 // due to some protection issue in the build server.
270 if (kProtectFromSpace && !(kIsDebugBuild && !kIsTargetBuild)) {
271 if (!from_space_->IsRosAllocSpace()) {
272 // Protect with PROT_NONE.
273 VLOG(heap) << "Protecting from_space_ : " << *from_space_;
274 from_space_->GetMemMap()->Protect(PROT_NONE);
275 } else {
276 // If RosAllocSpace, we'll leave it as PROT_READ here so the
277 // rosaloc verification can read the metadata magic number and
278 // protect it with PROT_NONE later in FinishPhase().
279 VLOG(heap) << "Protecting from_space_ with PROT_READ : " << *from_space_;
280 from_space_->GetMemMap()->Protect(PROT_READ);
281 }
Hiroshi Yamauchi312baf12015-01-12 12:11:05 -0800282 }
Mathieu Chartier6f365cc2014-04-23 12:42:27 -0700283 heap_->PreSweepingGcVerification(this);
Mathieu Chartier4240c512014-05-27 10:10:11 -0700284 if (swap_semi_spaces_) {
285 heap_->SwapSemiSpaces();
286 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700287}
288
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800289// Used to verify that there's no references to the from-space.
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700290class SemiSpace::VerifyNoFromSpaceReferencesVisitor {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800291 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700292 explicit VerifyNoFromSpaceReferencesVisitor(space::ContinuousMemMapAllocSpace* from_space)
293 : from_space_(from_space) {}
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800294
Mathieu Chartier407f7022014-02-18 14:37:05 -0800295 void operator()(Object* obj, MemberOffset offset, bool /* is_static */) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700296 REQUIRES_SHARED(Locks::mutator_lock_) ALWAYS_INLINE {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700297 mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800298 if (from_space_->HasAddress(ref)) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700299 LOG(FATAL) << ref << " found in from space";
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800300 }
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800301 }
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700302
303 // TODO: Remove NO_THREAD_SAFETY_ANALYSIS when clang better understands visitors.
304 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
305 NO_THREAD_SAFETY_ANALYSIS {
306 if (!root->IsNull()) {
307 VisitRoot(root);
308 }
309 }
310
311 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
312 NO_THREAD_SAFETY_ANALYSIS {
313 if (kIsDebugBuild) {
314 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
315 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
316 }
317 CHECK(!from_space_->HasAddress(root->AsMirrorPtr()));
318 }
319
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800320 private:
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700321 space::ContinuousMemMapAllocSpace* const from_space_;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800322};
323
324void SemiSpace::VerifyNoFromSpaceReferences(Object* obj) {
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800325 DCHECK(!from_space_->HasAddress(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700326 VerifyNoFromSpaceReferencesVisitor visitor(from_space_);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700327 obj->VisitReferences(visitor, VoidFunctor());
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800328}
329
Mathieu Chartier590fee92013-09-13 13:46:47 -0700330void SemiSpace::MarkReachableObjects() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700331 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
332 {
333 TimingLogger::ScopedTiming t2("MarkStackAsLive", GetTimings());
334 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
335 heap_->MarkAllocStackAsLive(live_stack);
336 live_stack->Reset();
337 }
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800338 for (auto& space : heap_->GetContinuousSpaces()) {
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700339 // If the space is immune then we need to mark the references to other spaces.
340 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
341 if (table != nullptr) {
342 // TODO: Improve naming.
343 TimingLogger::ScopedTiming t2(
344 space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
345 "UpdateAndMarkImageModUnionTable",
346 GetTimings());
Mathieu Chartier97509952015-07-13 14:35:43 -0700347 table->UpdateAndMarkReferences(this);
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700348 DCHECK(GetHeap()->FindRememberedSetFromSpace(space) == nullptr);
Mathieu Chartier95bbf622015-12-16 15:56:15 -0800349 } else if ((space->IsImageSpace() || collect_from_space_only_) &&
350 space->GetLiveBitmap() != nullptr) {
351 // If the space has no mod union table (the non-moving space, app image spaces, main spaces
352 // when the bump pointer space only collection is enabled,) then we need to scan its live
353 // bitmap or dirty cards as roots (including the objects on the live stack which have just
354 // marked in the live bitmap above in MarkAllocStackAsLive().)
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700355 accounting::RememberedSet* rem_set = GetHeap()->FindRememberedSetFromSpace(space);
Mathieu Chartier95bbf622015-12-16 15:56:15 -0800356 if (!space->IsImageSpace()) {
357 DCHECK(space == heap_->GetNonMovingSpace() || space == heap_->GetPrimaryFreeListSpace())
358 << "Space " << space->GetName() << " "
359 << "generational_=" << generational_ << " "
360 << "collect_from_space_only_=" << collect_from_space_only_;
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800361 // App images currently do not have remembered sets.
Mathieu Chartier95bbf622015-12-16 15:56:15 -0800362 DCHECK_EQ(kUseRememberedSet, rem_set != nullptr);
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800363 } else {
364 DCHECK(rem_set == nullptr);
365 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700366 if (rem_set != nullptr) {
367 TimingLogger::ScopedTiming t2("UpdateAndMarkRememberedSet", GetTimings());
Mathieu Chartier97509952015-07-13 14:35:43 -0700368 rem_set->UpdateAndMarkReferences(from_space_, this);
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800369 } else {
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700370 TimingLogger::ScopedTiming t2("VisitLiveBits", GetTimings());
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700371 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800372 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
373 reinterpret_cast<uintptr_t>(space->End()),
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700374 [this](mirror::Object* obj)
375 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
376 ScanObject(obj);
377 });
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800378 }
Mathieu Chartier95bbf622015-12-16 15:56:15 -0800379 if (kIsDebugBuild) {
380 // Verify that there are no from-space references that
381 // remain in the space, that is, the remembered set (and the
382 // card table) didn't miss any from-space references in the
383 // space.
384 accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
Mathieu Chartier95bbf622015-12-16 15:56:15 -0800385 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
386 reinterpret_cast<uintptr_t>(space->End()),
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700387 [this](Object* obj)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700388 REQUIRES_SHARED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700389 DCHECK(obj != nullptr);
390 VerifyNoFromSpaceReferences(obj);
391 });
Mathieu Chartier95bbf622015-12-16 15:56:15 -0800392 }
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800393 }
394 }
395
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700396 CHECK_EQ(is_large_object_space_immune_, collect_from_space_only_);
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700397 space::LargeObjectSpace* los = GetHeap()->GetLargeObjectsSpace();
398 if (is_large_object_space_immune_ && los != nullptr) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800399 TimingLogger::ScopedTiming t2("VisitLargeObjects", GetTimings());
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700400 DCHECK(collect_from_space_only_);
Hiroshi Yamauchiba5870d2014-01-29 15:31:03 -0800401 // Delay copying the live set to the marked set until here from
402 // BindBitmaps() as the large objects on the allocation stack may
403 // be newly added to the live set above in MarkAllocStackAsLive().
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700404 los->CopyLiveToMarked();
Hiroshi Yamauchiba5870d2014-01-29 15:31:03 -0800405
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800406 // When the large object space is immune, we need to scan the
407 // large object space as roots as they contain references to their
408 // classes (primitive array classes) that could move though they
409 // don't contain any other references.
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700410 accounting::LargeObjectBitmap* large_live_bitmap = los->GetLiveBitmap();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700411 large_live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(los->Begin()),
412 reinterpret_cast<uintptr_t>(los->End()),
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700413 [this](mirror::Object* obj)
414 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
415 ScanObject(obj);
416 });
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800417 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700418 // Recursively process the mark stack.
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800419 ProcessMarkStack();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700420}
421
422void SemiSpace::ReclaimPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700423 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
424 WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
425 // Reclaim unmarked objects.
426 Sweep(false);
427 // Swap the live and mark bitmaps for each space which we modified space. This is an
428 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
429 // bitmaps.
430 SwapBitmaps();
431 // Unbind the live and mark bitmaps.
432 GetHeap()->UnBindBitmaps();
Mathieu Chartierad35d902014-02-11 16:20:42 -0800433 if (saved_bytes_ > 0) {
434 VLOG(heap) << "Avoided dirtying " << PrettySize(saved_bytes_);
435 }
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800436 if (generational_) {
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800437 // Record the end (top) of the to space so we can distinguish
438 // between objects that were allocated since the last GC and the
439 // older objects.
440 last_gc_to_space_end_ = to_space_->End();
441 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700442}
443
444void SemiSpace::ResizeMarkStack(size_t new_size) {
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800445 std::vector<StackReference<Object>> temp(mark_stack_->Begin(), mark_stack_->End());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700446 CHECK_LE(mark_stack_->Size(), new_size);
447 mark_stack_->Resize(new_size);
Mathieu Chartiercb535da2015-01-23 13:50:03 -0800448 for (auto& obj : temp) {
449 mark_stack_->PushBack(obj.AsMirrorPtr());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700450 }
451}
452
453inline void SemiSpace::MarkStackPush(Object* obj) {
454 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
455 ResizeMarkStack(mark_stack_->Capacity() * 2);
456 }
457 // The object must be pushed on to the mark stack.
458 mark_stack_->PushBack(obj);
459}
460
Mathieu Chartierad35d902014-02-11 16:20:42 -0800461static inline size_t CopyAvoidingDirtyingPages(void* dest, const void* src, size_t size) {
462 if (LIKELY(size <= static_cast<size_t>(kPageSize))) {
463 // We will dirty the current page and somewhere in the middle of the next page. This means
464 // that the next object copied will also dirty that page.
465 // TODO: Worth considering the last object copied? We may end up dirtying one page which is
466 // not necessary per GC.
467 memcpy(dest, src, size);
468 return 0;
469 }
470 size_t saved_bytes = 0;
Ian Rogers13735952014-10-08 12:43:28 -0700471 uint8_t* byte_dest = reinterpret_cast<uint8_t*>(dest);
Mathieu Chartierad35d902014-02-11 16:20:42 -0800472 if (kIsDebugBuild) {
473 for (size_t i = 0; i < size; ++i) {
474 CHECK_EQ(byte_dest[i], 0U);
475 }
476 }
477 // Process the start of the page. The page must already be dirty, don't bother with checking.
Ian Rogers13735952014-10-08 12:43:28 -0700478 const uint8_t* byte_src = reinterpret_cast<const uint8_t*>(src);
479 const uint8_t* limit = byte_src + size;
Mathieu Chartierad35d902014-02-11 16:20:42 -0800480 size_t page_remain = AlignUp(byte_dest, kPageSize) - byte_dest;
481 // Copy the bytes until the start of the next page.
482 memcpy(dest, src, page_remain);
483 byte_src += page_remain;
484 byte_dest += page_remain;
Mathieu Chartier407f7022014-02-18 14:37:05 -0800485 DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(byte_dest), kPageSize);
486 DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(byte_dest), sizeof(uintptr_t));
487 DCHECK_ALIGNED(reinterpret_cast<uintptr_t>(byte_src), sizeof(uintptr_t));
Mathieu Chartierad35d902014-02-11 16:20:42 -0800488 while (byte_src + kPageSize < limit) {
489 bool all_zero = true;
490 uintptr_t* word_dest = reinterpret_cast<uintptr_t*>(byte_dest);
491 const uintptr_t* word_src = reinterpret_cast<const uintptr_t*>(byte_src);
492 for (size_t i = 0; i < kPageSize / sizeof(*word_src); ++i) {
493 // Assumes the destination of the copy is all zeros.
494 if (word_src[i] != 0) {
495 all_zero = false;
496 word_dest[i] = word_src[i];
497 }
498 }
499 if (all_zero) {
500 // Avoided copying into the page since it was all zeros.
501 saved_bytes += kPageSize;
502 }
503 byte_src += kPageSize;
504 byte_dest += kPageSize;
505 }
506 // Handle the part of the page at the end.
507 memcpy(byte_dest, byte_src, limit - byte_src);
508 return saved_bytes;
509}
510
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800511mirror::Object* SemiSpace::MarkNonForwardedObject(mirror::Object* obj) {
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700512 const size_t object_size = obj->SizeOf();
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700513 size_t bytes_allocated, dummy;
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800514 mirror::Object* forward_address = nullptr;
Ian Rogers13735952014-10-08 12:43:28 -0700515 if (generational_ && reinterpret_cast<uint8_t*>(obj) < last_gc_to_space_end_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800516 // If it's allocated before the last GC (older), move
517 // (pseudo-promote) it to the main free list space (as sort
518 // of an old generation.)
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700519 forward_address = promo_dest_space_->AllocThreadUnsafe(self_, object_size, &bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700520 nullptr, &dummy);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700521 if (UNLIKELY(forward_address == nullptr)) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800522 // If out of space, fall back to the to-space.
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700523 forward_address = to_space_->AllocThreadUnsafe(self_, object_size, &bytes_allocated, nullptr,
524 &dummy);
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700525 // No logic for marking the bitmap, so it must be null.
Mathieu Chartierb363f662014-07-16 13:28:58 -0700526 DCHECK(to_space_live_bitmap_ == nullptr);
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800527 } else {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700528 bytes_promoted_ += bytes_allocated;
Hiroshi Yamauchi38e68e92014-03-07 13:59:08 -0800529 // Dirty the card at the destionation as it may contain
530 // references (including the class pointer) to the bump pointer
531 // space.
532 GetHeap()->WriteBarrierEveryFieldOf(forward_address);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800533 // Handle the bitmaps marking.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700534 accounting::ContinuousSpaceBitmap* live_bitmap = promo_dest_space_->GetLiveBitmap();
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800535 DCHECK(live_bitmap != nullptr);
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700536 accounting::ContinuousSpaceBitmap* mark_bitmap = promo_dest_space_->GetMarkBitmap();
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800537 DCHECK(mark_bitmap != nullptr);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800538 DCHECK(!live_bitmap->Test(forward_address));
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700539 if (collect_from_space_only_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800540 // If collecting the bump pointer spaces only, live_bitmap == mark_bitmap.
541 DCHECK_EQ(live_bitmap, mark_bitmap);
542
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800543 // If a bump pointer space only collection, delay the live
544 // bitmap marking of the promoted object until it's popped off
545 // the mark stack (ProcessMarkStack()). The rationale: we may
546 // be in the middle of scanning the objects in the promo
547 // destination space for
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800548 // non-moving-space-to-bump-pointer-space references by
549 // iterating over the marked bits of the live bitmap
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800550 // (MarkReachableObjects()). If we don't delay it (and instead
551 // mark the promoted object here), the above promo destination
552 // space scan could encounter the just-promoted object and
553 // forward the references in the promoted object's fields even
554 // through it is pushed onto the mark stack. If this happens,
555 // the promoted object would be in an inconsistent state, that
556 // is, it's on the mark stack (gray) but its fields are
557 // already forwarded (black), which would cause a
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800558 // DCHECK(!to_space_->HasAddress(obj)) failure below.
559 } else {
560 // Mark forward_address on the live bit map.
561 live_bitmap->Set(forward_address);
562 // Mark forward_address on the mark bit map.
563 DCHECK(!mark_bitmap->Test(forward_address));
564 mark_bitmap->Set(forward_address);
565 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800566 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800567 } else {
568 // If it's allocated after the last GC (younger), copy it to the to-space.
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700569 forward_address = to_space_->AllocThreadUnsafe(self_, object_size, &bytes_allocated, nullptr,
570 &dummy);
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700571 if (forward_address != nullptr && to_space_live_bitmap_ != nullptr) {
572 to_space_live_bitmap_->Set(forward_address);
573 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800574 }
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700575 // If it's still null, attempt to use the fallback space.
576 if (UNLIKELY(forward_address == nullptr)) {
577 forward_address = fallback_space_->AllocThreadUnsafe(self_, object_size, &bytes_allocated,
Hiroshi Yamauchi4460a842015-03-09 11:57:48 -0700578 nullptr, &dummy);
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700579 CHECK(forward_address != nullptr) << "Out of memory in the to-space and fallback space.";
580 accounting::ContinuousSpaceBitmap* bitmap = fallback_space_->GetLiveBitmap();
581 if (bitmap != nullptr) {
582 bitmap->Set(forward_address);
583 }
584 }
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700585 ++objects_moved_;
586 bytes_moved_ += bytes_allocated;
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800587 // Copy over the object and add it to the mark stack since we still need to update its
588 // references.
Mathieu Chartierad35d902014-02-11 16:20:42 -0800589 saved_bytes_ +=
590 CopyAvoidingDirtyingPages(reinterpret_cast<void*>(forward_address), obj, object_size);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700591 if (kUseBakerOrBrooksReadBarrier) {
592 obj->AssertReadBarrierPointer();
593 if (kUseBrooksReadBarrier) {
594 DCHECK_EQ(forward_address->GetReadBarrierPointer(), obj);
595 forward_address->SetReadBarrierPointer(forward_address);
596 }
597 forward_address->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800598 }
Mathieu Chartier5dc08a62014-01-10 10:10:23 -0800599 DCHECK(to_space_->HasAddress(forward_address) ||
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700600 fallback_space_->HasAddress(forward_address) ||
601 (generational_ && promo_dest_space_->HasAddress(forward_address)))
602 << forward_address << "\n" << GetHeap()->DumpSpaces();
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800603 return forward_address;
604}
605
Mathieu Chartier97509952015-07-13 14:35:43 -0700606mirror::Object* SemiSpace::MarkObject(mirror::Object* root) {
Mathieu Chartier3b05e9b2014-03-25 09:29:43 -0700607 auto ref = StackReference<mirror::Object>::FromMirrorPtr(root);
Mathieu Chartier9a9aee62016-03-04 10:30:39 -0800608 MarkObjectIfNotInToSpace(&ref);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800609 return ref.AsMirrorPtr();
610}
611
Mathieu Chartier97509952015-07-13 14:35:43 -0700612void SemiSpace::MarkHeapReference(mirror::HeapReference<mirror::Object>* obj_ptr) {
613 MarkObject(obj_ptr);
Hiroshi Yamauchi4db74492014-04-22 17:10:48 -0700614}
615
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700616void SemiSpace::VisitRoots(mirror::Object*** roots, size_t count,
617 const RootInfo& info ATTRIBUTE_UNUSED) {
618 for (size_t i = 0; i < count; ++i) {
619 auto* root = roots[i];
620 auto ref = StackReference<mirror::Object>::FromMirrorPtr(*root);
Mathieu Chartierb18e8272015-08-14 10:37:28 -0700621 // The root can be in the to-space since we may visit the declaring class of an ArtMethod
622 // multiple times if it is on the call stack.
623 MarkObjectIfNotInToSpace(&ref);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700624 if (*root != ref.AsMirrorPtr()) {
625 *root = ref.AsMirrorPtr();
626 }
627 }
628}
629
630void SemiSpace::VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
631 const RootInfo& info ATTRIBUTE_UNUSED) {
632 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierb18e8272015-08-14 10:37:28 -0700633 MarkObjectIfNotInToSpace(roots[i]);
Mathieu Chartier407f7022014-02-18 14:37:05 -0800634 }
Mathieu Chartier815873e2014-02-13 18:02:13 -0800635}
636
Mathieu Chartier590fee92013-09-13 13:46:47 -0700637// Marks all objects in the root set.
638void SemiSpace::MarkRoots() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700639 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700640 Runtime::Current()->VisitRoots(this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700641}
642
Mathieu Chartier590fee92013-09-13 13:46:47 -0700643void SemiSpace::SweepSystemWeaks() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700644 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier97509952015-07-13 14:35:43 -0700645 Runtime::Current()->SweepSystemWeaks(this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700646}
647
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800648bool SemiSpace::ShouldSweepSpace(space::ContinuousSpace* space) const {
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700649 return space != from_space_ && space != to_space_;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700650}
651
652void SemiSpace::Sweep(bool swap_bitmaps) {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700653 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700654 DCHECK(mark_stack_->IsEmpty());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700655 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800656 if (space->IsContinuousMemMapAllocSpace()) {
657 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
658 if (!ShouldSweepSpace(alloc_space)) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800659 continue;
660 }
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700661 TimingLogger::ScopedTiming split(
Mathieu Chartier10fb83a2014-06-15 15:15:43 -0700662 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", GetTimings());
663 RecordFree(alloc_space->Sweep(swap_bitmaps));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700664 }
665 }
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800666 if (!is_large_object_space_immune_) {
667 SweepLargeObjects(swap_bitmaps);
668 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700669}
670
671void SemiSpace::SweepLargeObjects(bool swap_bitmaps) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800672 DCHECK(!is_large_object_space_immune_);
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700673 space::LargeObjectSpace* los = heap_->GetLargeObjectsSpace();
674 if (los != nullptr) {
675 TimingLogger::ScopedTiming split("SweepLargeObjects", GetTimings());
676 RecordFreeLOS(los->Sweep(swap_bitmaps));
677 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700678}
679
680// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
681// marked, put it on the appropriate list in the heap for later processing.
Mathieu Chartier31e88222016-10-14 18:43:19 -0700682void SemiSpace::DelayReferenceReferent(ObjPtr<mirror::Class> klass,
683 ObjPtr<mirror::Reference> reference) {
Mathieu Chartier97509952015-07-13 14:35:43 -0700684 heap_->GetReferenceProcessor()->DelayReferenceReferent(klass, reference, this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700685}
686
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700687class SemiSpace::MarkObjectVisitor {
Ian Rogers719d1a32014-03-06 12:13:39 -0800688 public:
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700689 explicit MarkObjectVisitor(SemiSpace* collector) : collector_(collector) {}
Ian Rogers719d1a32014-03-06 12:13:39 -0800690
Mathieu Chartier31e88222016-10-14 18:43:19 -0700691 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool /* is_static */) const ALWAYS_INLINE
Mathieu Chartier90443472015-07-16 20:32:27 -0700692 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier580a8df2014-03-26 15:15:57 -0700693 // Object was already verified when we scanned it.
694 collector_->MarkObject(obj->GetFieldObjectReferenceAddr<kVerifyNone>(offset));
Ian Rogers719d1a32014-03-06 12:13:39 -0800695 }
Mathieu Chartier407f7022014-02-18 14:37:05 -0800696
Mathieu Chartier31e88222016-10-14 18:43:19 -0700697 void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700698 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier407f7022014-02-18 14:37:05 -0800699 collector_->DelayReferenceReferent(klass, ref);
700 }
701
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700702 // TODO: Remove NO_THREAD_SAFETY_ANALYSIS when clang better understands visitors.
703 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
704 NO_THREAD_SAFETY_ANALYSIS {
705 if (!root->IsNull()) {
706 VisitRoot(root);
707 }
708 }
709
710 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
711 NO_THREAD_SAFETY_ANALYSIS {
712 if (kIsDebugBuild) {
713 Locks::mutator_lock_->AssertExclusiveHeld(Thread::Current());
714 Locks::heap_bitmap_lock_->AssertExclusiveHeld(Thread::Current());
715 }
Mathieu Chartierc6211062015-07-24 16:05:55 -0700716 // We may visit the same root multiple times, so avoid marking things in the to-space since
717 // this is not handled by the GC.
718 collector_->MarkObjectIfNotInToSpace(root);
Mathieu Chartierda7c6502015-07-23 16:01:26 -0700719 }
720
Ian Rogers719d1a32014-03-06 12:13:39 -0800721 private:
Mathieu Chartier407f7022014-02-18 14:37:05 -0800722 SemiSpace* const collector_;
Ian Rogers719d1a32014-03-06 12:13:39 -0800723};
724
725// Visit all of the references of an object and update.
726void SemiSpace::ScanObject(Object* obj) {
Ian Rogers719d1a32014-03-06 12:13:39 -0800727 DCHECK(!from_space_->HasAddress(obj)) << "Scanning object " << obj << " in from space";
Mathieu Chartiera07f5592016-06-16 11:44:28 -0700728 MarkObjectVisitor visitor(this);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700729 obj->VisitReferences(visitor, visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700730}
731
732// Scan anything that's on the mark stack.
Mathieu Chartier3bb57c72014-02-18 11:38:45 -0800733void SemiSpace::ProcessMarkStack() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700734 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700735 accounting::ContinuousSpaceBitmap* live_bitmap = nullptr;
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700736 if (collect_from_space_only_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800737 // If a bump pointer space only collection (and the promotion is
738 // enabled,) we delay the live-bitmap marking of promoted objects
739 // from MarkObject() until this function.
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700740 live_bitmap = promo_dest_space_->GetLiveBitmap();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800741 DCHECK(live_bitmap != nullptr);
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700742 accounting::ContinuousSpaceBitmap* mark_bitmap = promo_dest_space_->GetMarkBitmap();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800743 DCHECK(mark_bitmap != nullptr);
744 DCHECK_EQ(live_bitmap, mark_bitmap);
745 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700746 while (!mark_stack_->IsEmpty()) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800747 Object* obj = mark_stack_->PopBack();
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700748 if (collect_from_space_only_ && promo_dest_space_->HasAddress(obj)) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800749 // obj has just been promoted. Mark the live bitmap for it,
750 // which is delayed from MarkObject().
751 DCHECK(!live_bitmap->Test(obj));
752 live_bitmap->Set(obj);
753 }
754 ScanObject(obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700755 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700756}
757
Mathieu Chartier97509952015-07-13 14:35:43 -0700758mirror::Object* SemiSpace::IsMarked(mirror::Object* obj) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700759 // All immune objects are assumed marked.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700760 if (from_space_->HasAddress(obj)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700761 // Returns either the forwarding address or null.
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700762 return GetForwardingAddressInFromSpace(obj);
Mathieu Chartier763a31e2015-11-16 16:05:55 -0800763 } else if (collect_from_space_only_ ||
764 immune_spaces_.IsInImmuneRegion(obj) ||
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700765 to_space_->HasAddress(obj)) {
766 return obj; // Already forwarded, must be marked.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700767 }
Mathieu Chartier52e4b432014-06-10 11:22:31 -0700768 return mark_bitmap_->Test(obj) ? obj : nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700769}
770
Mathieu Chartier97509952015-07-13 14:35:43 -0700771bool SemiSpace::IsMarkedHeapReference(mirror::HeapReference<mirror::Object>* object) {
772 mirror::Object* obj = object->AsMirrorPtr();
773 mirror::Object* new_obj = IsMarked(obj);
774 if (new_obj == nullptr) {
775 return false;
776 }
777 if (new_obj != obj) {
778 // Write barrier is not necessary since it still points to the same object, just at a different
779 // address.
780 object->Assign(new_obj);
781 }
782 return true;
783}
784
Mathieu Chartier590fee92013-09-13 13:46:47 -0700785void SemiSpace::SetToSpace(space::ContinuousMemMapAllocSpace* to_space) {
786 DCHECK(to_space != nullptr);
787 to_space_ = to_space;
788}
789
790void SemiSpace::SetFromSpace(space::ContinuousMemMapAllocSpace* from_space) {
791 DCHECK(from_space != nullptr);
792 from_space_ = from_space;
793}
794
795void SemiSpace::FinishPhase() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700796 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Hiroshi Yamauchi34cf8322016-09-06 12:24:52 -0700797 // b/31172841. Temporarily disable the from-space protection with host debug build
798 // due to some protection issue in the build server.
799 if (kProtectFromSpace && !(kIsDebugBuild && !kIsTargetBuild)) {
800 if (from_space_->IsRosAllocSpace()) {
801 VLOG(heap) << "Protecting from_space_ with PROT_NONE : " << *from_space_;
802 from_space_->GetMemMap()->Protect(PROT_NONE);
803 }
Hiroshi Yamauchia233e032015-01-09 17:48:00 -0800804 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700805 // Null the "to" and "from" spaces since compacting from one to the other isn't valid until
806 // further action is done by the heap.
807 to_space_ = nullptr;
808 from_space_ = nullptr;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700809 CHECK(mark_stack_->IsEmpty());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700810 mark_stack_->Reset();
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700811 space::LargeObjectSpace* los = GetHeap()->GetLargeObjectsSpace();
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800812 if (generational_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800813 // Decide whether to do a whole heap collection or a bump pointer
814 // only space collection at the next collection by updating
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700815 // collect_from_space_only_.
816 if (collect_from_space_only_) {
817 // Disable collect_from_space_only_ if the bytes promoted since the
Hiroshi Yamauchi24faeb22014-05-07 13:12:43 -0700818 // last whole heap collection or the large object bytes
819 // allocated exceeds a threshold.
820 bytes_promoted_since_last_whole_heap_collection_ += bytes_promoted_;
821 bool bytes_promoted_threshold_exceeded =
822 bytes_promoted_since_last_whole_heap_collection_ >= kBytesPromotedThreshold;
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700823 uint64_t current_los_bytes_allocated = los != nullptr ? los->GetBytesAllocated() : 0U;
Hiroshi Yamauchi24faeb22014-05-07 13:12:43 -0700824 uint64_t last_los_bytes_allocated =
825 large_object_bytes_allocated_at_last_whole_heap_collection_;
826 bool large_object_bytes_threshold_exceeded =
827 current_los_bytes_allocated >=
828 last_los_bytes_allocated + kLargeObjectBytesAllocatedThreshold;
829 if (bytes_promoted_threshold_exceeded || large_object_bytes_threshold_exceeded) {
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700830 collect_from_space_only_ = false;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800831 }
832 } else {
Hiroshi Yamauchi24faeb22014-05-07 13:12:43 -0700833 // Reset the counters.
834 bytes_promoted_since_last_whole_heap_collection_ = bytes_promoted_;
835 large_object_bytes_allocated_at_last_whole_heap_collection_ =
Mathieu Chartier2dbe6272014-09-16 10:43:23 -0700836 los != nullptr ? los->GetBytesAllocated() : 0U;
Mathieu Chartier4c13a3f2014-07-14 14:57:16 -0700837 collect_from_space_only_ = true;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800838 }
839 }
Mathieu Chartier4aeec172014-03-27 16:09:46 -0700840 // Clear all of the spaces' mark bitmaps.
841 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
842 heap_->ClearMarkedObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700843}
844
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -0700845void SemiSpace::RevokeAllThreadLocalBuffers() {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700846 TimingLogger::ScopedTiming t(__FUNCTION__, GetTimings());
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -0700847 GetHeap()->RevokeAllThreadLocalBuffers();
Hiroshi Yamauchic93c5302014-03-20 16:15:37 -0700848}
849
Mathieu Chartier590fee92013-09-13 13:46:47 -0700850} // namespace collector
851} // namespace gc
852} // namespace art