blob: 99c726d216f663fd0f7b601f4f9428059b454b1f [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 Chartier590fee92013-09-13 13:46:47 -070017#include "semi_space.h"
18
19#include <functional>
20#include <numeric>
21#include <climits>
22#include <vector>
23
24#include "base/logging.h"
25#include "base/macros.h"
26#include "base/mutex-inl.h"
27#include "base/timing_logger.h"
28#include "gc/accounting/heap_bitmap.h"
29#include "gc/accounting/mod_union_table.h"
30#include "gc/accounting/space_bitmap-inl.h"
31#include "gc/heap.h"
32#include "gc/space/bump_pointer_space.h"
33#include "gc/space/bump_pointer_space-inl.h"
34#include "gc/space/image_space.h"
35#include "gc/space/large_object_space.h"
36#include "gc/space/space-inl.h"
37#include "indirect_reference_table.h"
38#include "intern_table.h"
39#include "jni_internal.h"
40#include "mark_sweep-inl.h"
41#include "monitor.h"
42#include "mirror/art_field.h"
43#include "mirror/art_field-inl.h"
44#include "mirror/class-inl.h"
45#include "mirror/class_loader.h"
46#include "mirror/dex_cache.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array.h"
49#include "mirror/object_array-inl.h"
50#include "runtime.h"
51#include "semi_space-inl.h"
52#include "thread-inl.h"
53#include "thread_list.h"
54#include "verifier/method_verifier.h"
55
56using ::art::mirror::Class;
57using ::art::mirror::Object;
58
59namespace art {
60namespace gc {
61namespace collector {
62
63static constexpr bool kProtectFromSpace = true;
64static constexpr bool kResetFromSpace = true;
65
66// TODO: Unduplicate logic.
67void SemiSpace::ImmuneSpace(space::ContinuousSpace* space) {
68 // Bind live to mark bitmap if necessary.
69 if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
70 BindLiveToMarkBitmap(space);
71 }
72 // Add the space to the immune region.
73 if (immune_begin_ == nullptr) {
74 DCHECK(immune_end_ == nullptr);
75 immune_begin_ = reinterpret_cast<Object*>(space->Begin());
76 immune_end_ = reinterpret_cast<Object*>(space->End());
77 } else {
78 const space::ContinuousSpace* prev_space = nullptr;
79 // Find out if the previous space is immune.
80 for (space::ContinuousSpace* cur_space : GetHeap()->GetContinuousSpaces()) {
81 if (cur_space == space) {
82 break;
83 }
84 prev_space = cur_space;
85 }
86 // If previous space was immune, then extend the immune region. Relies on continuous spaces
87 // being sorted by Heap::AddContinuousSpace.
88 if (prev_space != nullptr && IsImmuneSpace(prev_space)) {
89 immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -080090 // Use Limit() instead of End() because otherwise if the
91 // generational mode is enabled, the alloc space might expand
92 // due to promotion and the sense of immunity may change in the
93 // middle of a GC.
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -080094 immune_end_ = std::max(reinterpret_cast<Object*>(space->Limit()), immune_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -070095 }
96 }
97}
98
99void SemiSpace::BindBitmaps() {
100 timings_.StartSplit("BindBitmaps");
101 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
102 // Mark all of the spaces we never collect as immune.
103 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800104 if (space->GetLiveBitmap() != nullptr) {
105 if (space == to_space_) {
106 BindLiveToMarkBitmap(to_space_);
107 } else if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800108 || space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect
109 // Add the main free list space and the non-moving
110 // space to the immune space if a bump pointer space
111 // only collection.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800112 || (generational_ && !whole_heap_collection_ &&
113 (space == GetHeap()->GetNonMovingSpace() ||
114 space == GetHeap()->GetPrimaryFreeListSpace()))) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800115 ImmuneSpace(space);
116 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700117 }
118 }
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800119 if (generational_ && !whole_heap_collection_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800120 // We won't collect the large object space if a bump pointer space only collection.
121 is_large_object_space_immune_ = true;
122 GetHeap()->GetLargeObjectsSpace()->CopyLiveToMarked();
123 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700124 timings_.EndSplit();
125}
126
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800127SemiSpace::SemiSpace(Heap* heap, bool generational, const std::string& name_prefix)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700128 : GarbageCollector(heap,
129 name_prefix + (name_prefix.empty() ? "" : " ") + "marksweep + semispace"),
130 mark_stack_(nullptr),
131 immune_begin_(nullptr),
132 immune_end_(nullptr),
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800133 is_large_object_space_immune_(false),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700134 to_space_(nullptr),
135 from_space_(nullptr),
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800136 self_(nullptr),
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800137 generational_(generational),
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800138 last_gc_to_space_end_(nullptr),
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800139 bytes_promoted_(0),
140 whole_heap_collection_(true),
141 whole_heap_collection_interval_counter_(0) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700142}
143
144void SemiSpace::InitializePhase() {
145 timings_.Reset();
Ian Rogers5fe9af72013-11-14 00:17:20 -0800146 TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700147 mark_stack_ = heap_->mark_stack_.get();
148 DCHECK(mark_stack_ != nullptr);
149 immune_begin_ = nullptr;
150 immune_end_ = nullptr;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800151 is_large_object_space_immune_ = false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700152 self_ = Thread::Current();
153 // Do any pre GC verification.
154 timings_.NewSplit("PreGcVerification");
155 heap_->PreGcVerification(this);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800156 // Set the initial bitmap.
157 to_space_live_bitmap_ = to_space_->GetLiveBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700158}
159
160void SemiSpace::ProcessReferences(Thread* self) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800161 TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700162 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800163 GetHeap()->ProcessReferences(timings_, clear_soft_references_, &MarkedForwardingAddressCallback,
164 &RecursiveMarkObjectCallback, this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700165}
166
167void SemiSpace::MarkingPhase() {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800168 if (generational_) {
169 if (gc_cause_ == kGcCauseExplicit || gc_cause_ == kGcCauseForNativeAlloc ||
170 clear_soft_references_) {
171 // If an explicit, native allocation-triggered, or last attempt
172 // collection, collect the whole heap (and reset the interval
173 // counter to be consistent.)
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800174 whole_heap_collection_ = true;
175 whole_heap_collection_interval_counter_ = 0;
176 }
177 if (whole_heap_collection_) {
178 VLOG(heap) << "Whole heap collection";
179 } else {
180 VLOG(heap) << "Bump pointer space only collection";
181 }
182 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700183 Thread* self = Thread::Current();
184 Locks::mutator_lock_->AssertExclusiveHeld(self);
Ian Rogers5fe9af72013-11-14 00:17:20 -0800185 TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700186 // Need to do this with mutators paused so that somebody doesn't accidentally allocate into the
187 // wrong space.
188 heap_->SwapSemiSpaces();
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800189 if (generational_) {
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800190 // If last_gc_to_space_end_ is out of the bounds of the from-space
191 // (the to-space from last GC), then point it to the beginning of
192 // the from-space. For example, the very first GC or the
193 // pre-zygote compaction.
194 if (!from_space_->HasAddress(reinterpret_cast<mirror::Object*>(last_gc_to_space_end_))) {
195 last_gc_to_space_end_ = from_space_->Begin();
196 }
197 // Reset this before the marking starts below.
198 bytes_promoted_ = 0;
199 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700200 // Assume the cleared space is already empty.
201 BindBitmaps();
202 // Process dirty cards and add dirty cards to mod-union tables.
203 heap_->ProcessCards(timings_);
Mathieu Chartierc528dba2013-11-26 12:00:11 -0800204 // Clear the whole card table since we can not get any additional dirty cards during the
205 // paused GC. This saves memory but only works for pause the world collectors.
206 timings_.NewSplit("ClearCardTable");
207 heap_->GetCardTable()->ClearCardTable();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700208 // Need to do this before the checkpoint since we don't want any threads to add references to
209 // the live stack during the recursive mark.
210 timings_.NewSplit("SwapStacks");
211 heap_->SwapStacks();
212 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
213 MarkRoots();
214 // Mark roots of immune spaces.
215 UpdateAndMarkModUnion();
216 // Recursively mark remaining objects.
217 MarkReachableObjects();
218}
219
220bool SemiSpace::IsImmuneSpace(const space::ContinuousSpace* space) const {
221 return
222 immune_begin_ <= reinterpret_cast<Object*>(space->Begin()) &&
223 immune_end_ >= reinterpret_cast<Object*>(space->End());
224}
225
226void SemiSpace::UpdateAndMarkModUnion() {
227 for (auto& space : heap_->GetContinuousSpaces()) {
228 // If the space is immune then we need to mark the references to other spaces.
229 if (IsImmuneSpace(space)) {
230 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800231 if (table != nullptr) {
232 // TODO: Improve naming.
233 TimingLogger::ScopedSplit split(
234 space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
235 "UpdateAndMarkImageModUnionTable",
236 &timings_);
237 table->UpdateAndMarkReferences(MarkRootCallback, this);
238 } else {
239 // If a bump pointer space only collection, the non-moving
240 // space is added to the immune space. But the non-moving
241 // space doesn't have a mod union table. Instead, its live
242 // bitmap will be scanned later in MarkReachableObjects().
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800243 DCHECK(generational_ && !whole_heap_collection_ &&
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800244 (space == heap_->GetNonMovingSpace() || space == heap_->GetPrimaryFreeListSpace()));
245 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700246 }
247 }
248}
249
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800250class SemiSpaceScanObjectVisitor {
251 public:
252 explicit SemiSpaceScanObjectVisitor(SemiSpace* ss) : semi_space_(ss) {}
253 void operator()(Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
254 // TODO: fix NO_THREAD_SAFETY_ANALYSIS. ScanObject() requires an
255 // exclusive lock on the mutator lock, but
256 // SpaceBitmap::VisitMarkedRange() only requires the shared lock.
257 DCHECK(obj != nullptr);
258 semi_space_->ScanObject(obj);
259 }
260 private:
261 SemiSpace* semi_space_;
262};
263
Mathieu Chartier590fee92013-09-13 13:46:47 -0700264void SemiSpace::MarkReachableObjects() {
265 timings_.StartSplit("MarkStackAsLive");
266 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
267 heap_->MarkAllocStackAsLive(live_stack);
268 live_stack->Reset();
269 timings_.EndSplit();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800270
271 for (auto& space : heap_->GetContinuousSpaces()) {
272 // If the space is immune and has no mod union table (the
273 // non-moving space when the bump pointer space only collection is
274 // enabled,) then we need to scan its live bitmap as roots
275 // (including the objects on the live stack which have just marked
276 // in the live bitmap above in MarkAllocStackAsLive().)
277 if (IsImmuneSpace(space) && heap_->FindModUnionTableFromSpace(space) == nullptr) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800278 DCHECK(generational_ && !whole_heap_collection_ &&
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800279 (space == GetHeap()->GetNonMovingSpace() || space == GetHeap()->GetPrimaryFreeListSpace()));
280 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
281 SemiSpaceScanObjectVisitor visitor(this);
282 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
283 reinterpret_cast<uintptr_t>(space->End()),
284 visitor);
285 }
286 }
287
288 if (is_large_object_space_immune_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800289 DCHECK(generational_ && !whole_heap_collection_);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800290 // When the large object space is immune, we need to scan the
291 // large object space as roots as they contain references to their
292 // classes (primitive array classes) that could move though they
293 // don't contain any other references.
294 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
295 accounting::ObjectSet* large_live_objects = large_object_space->GetLiveObjects();
296 SemiSpaceScanObjectVisitor visitor(this);
297 for (const Object* obj : large_live_objects->GetObjects()) {
298 visitor(const_cast<Object*>(obj));
299 }
300 }
301
Mathieu Chartier590fee92013-09-13 13:46:47 -0700302 // Recursively process the mark stack.
303 ProcessMarkStack(true);
304}
305
306void SemiSpace::ReclaimPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800307 TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700308 Thread* self = Thread::Current();
309 ProcessReferences(self);
310 {
311 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
312 SweepSystemWeaks();
313 }
314 // Record freed memory.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800315 uint64_t from_bytes = from_space_->GetBytesAllocated();
316 uint64_t to_bytes = to_space_->GetBytesAllocated();
317 uint64_t from_objects = from_space_->GetObjectsAllocated();
318 uint64_t to_objects = to_space_->GetObjectsAllocated();
319 CHECK_LE(to_objects, from_objects);
320 int64_t freed_bytes = from_bytes - to_bytes;
321 int64_t freed_objects = from_objects - to_objects;
Ian Rogersb122a4b2013-11-19 18:00:50 -0800322 freed_bytes_.FetchAndAdd(freed_bytes);
323 freed_objects_.FetchAndAdd(freed_objects);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800324 // Note: Freed bytes can be negative if we copy form a compacted space to a free-list backed
325 // space.
326 heap_->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700327 timings_.StartSplit("PreSweepingGcVerification");
328 heap_->PreSweepingGcVerification(this);
329 timings_.EndSplit();
330
331 {
332 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
333 // Reclaim unmarked objects.
334 Sweep(false);
335 // Swap the live and mark bitmaps for each space which we modified space. This is an
336 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
337 // bitmaps.
338 timings_.StartSplit("SwapBitmaps");
339 SwapBitmaps();
340 timings_.EndSplit();
341 // Unbind the live and mark bitmaps.
342 UnBindBitmaps();
343 }
344 // Release the memory used by the from space.
345 if (kResetFromSpace) {
346 // Clearing from space.
347 from_space_->Clear();
348 }
349 // Protect the from space.
350 VLOG(heap)
351 << "mprotect region " << reinterpret_cast<void*>(from_space_->Begin()) << " - "
352 << reinterpret_cast<void*>(from_space_->Limit());
353 if (kProtectFromSpace) {
354 mprotect(from_space_->Begin(), from_space_->Capacity(), PROT_NONE);
355 } else {
356 mprotect(from_space_->Begin(), from_space_->Capacity(), PROT_READ);
357 }
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800358
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800359 if (generational_) {
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800360 // Record the end (top) of the to space so we can distinguish
361 // between objects that were allocated since the last GC and the
362 // older objects.
363 last_gc_to_space_end_ = to_space_->End();
364 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700365}
366
367void SemiSpace::ResizeMarkStack(size_t new_size) {
368 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
369 CHECK_LE(mark_stack_->Size(), new_size);
370 mark_stack_->Resize(new_size);
371 for (const auto& obj : temp) {
372 mark_stack_->PushBack(obj);
373 }
374}
375
376inline void SemiSpace::MarkStackPush(Object* obj) {
377 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
378 ResizeMarkStack(mark_stack_->Capacity() * 2);
379 }
380 // The object must be pushed on to the mark stack.
381 mark_stack_->PushBack(obj);
382}
383
384// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
385bool SemiSpace::MarkLargeObject(const Object* obj) {
386 // TODO: support >1 discontinuous space.
387 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800388 DCHECK(large_object_space->Contains(obj));
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -0800389 accounting::ObjectSet* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700390 if (UNLIKELY(!large_objects->Test(obj))) {
391 large_objects->Set(obj);
392 return true;
393 }
394 return false;
395}
396
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800397mirror::Object* SemiSpace::MarkNonForwardedObject(mirror::Object* obj) {
398 size_t object_size = obj->SizeOf();
Mathieu Chartier5dc08a62014-01-10 10:10:23 -0800399 size_t bytes_allocated;
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800400 mirror::Object* forward_address = nullptr;
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800401 if (generational_ && reinterpret_cast<byte*>(obj) < last_gc_to_space_end_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800402 // If it's allocated before the last GC (older), move
403 // (pseudo-promote) it to the main free list space (as sort
404 // of an old generation.)
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800405 size_t bytes_promoted;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800406 space::MallocSpace* promo_dest_space = GetHeap()->GetPrimaryFreeListSpace();
407 forward_address = promo_dest_space->Alloc(self_, object_size, &bytes_promoted);
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800408 if (forward_address == nullptr) {
409 // If out of space, fall back to the to-space.
410 forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated);
411 } else {
412 GetHeap()->num_bytes_allocated_.FetchAndAdd(bytes_promoted);
413 bytes_promoted_ += bytes_promoted;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800414 // Handle the bitmaps marking.
415 accounting::SpaceBitmap* live_bitmap = promo_dest_space->GetLiveBitmap();
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800416 DCHECK(live_bitmap != nullptr);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800417 accounting::SpaceBitmap* mark_bitmap = promo_dest_space->GetMarkBitmap();
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800418 DCHECK(mark_bitmap != nullptr);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800419 DCHECK(!live_bitmap->Test(forward_address));
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800420 if (!whole_heap_collection_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800421 // If collecting the bump pointer spaces only, live_bitmap == mark_bitmap.
422 DCHECK_EQ(live_bitmap, mark_bitmap);
423
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800424 // If a bump pointer space only collection, delay the live
425 // bitmap marking of the promoted object until it's popped off
426 // the mark stack (ProcessMarkStack()). The rationale: we may
427 // be in the middle of scanning the objects in the promo
428 // destination space for
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800429 // non-moving-space-to-bump-pointer-space references by
430 // iterating over the marked bits of the live bitmap
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800431 // (MarkReachableObjects()). If we don't delay it (and instead
432 // mark the promoted object here), the above promo destination
433 // space scan could encounter the just-promoted object and
434 // forward the references in the promoted object's fields even
435 // through it is pushed onto the mark stack. If this happens,
436 // the promoted object would be in an inconsistent state, that
437 // is, it's on the mark stack (gray) but its fields are
438 // already forwarded (black), which would cause a
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800439 // DCHECK(!to_space_->HasAddress(obj)) failure below.
440 } else {
441 // Mark forward_address on the live bit map.
442 live_bitmap->Set(forward_address);
443 // Mark forward_address on the mark bit map.
444 DCHECK(!mark_bitmap->Test(forward_address));
445 mark_bitmap->Set(forward_address);
446 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800447 }
448 DCHECK(forward_address != nullptr);
449 } else {
450 // If it's allocated after the last GC (younger), copy it to the to-space.
451 forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated);
452 }
453 // Copy over the object and add it to the mark stack since we still need to update its
454 // references.
455 memcpy(reinterpret_cast<void*>(forward_address), obj, object_size);
456 if (to_space_live_bitmap_ != nullptr) {
457 to_space_live_bitmap_->Set(forward_address);
458 }
Mathieu Chartier5dc08a62014-01-10 10:10:23 -0800459 DCHECK(to_space_->HasAddress(forward_address) ||
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800460 (generational_ && GetHeap()->GetPrimaryFreeListSpace()->HasAddress(forward_address)));
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800461 return forward_address;
462}
463
Mathieu Chartier590fee92013-09-13 13:46:47 -0700464// Used to mark and copy objects. Any newly-marked objects who are in the from space get moved to
465// the to-space and have their forward address updated. Objects which have been newly marked are
466// pushed on the mark stack.
467Object* SemiSpace::MarkObject(Object* obj) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800468 Object* forward_address = obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700469 if (obj != nullptr && !IsImmune(obj)) {
470 if (from_space_->HasAddress(obj)) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800471 forward_address = GetForwardingAddressInFromSpace(obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700472 // If the object has already been moved, return the new forward address.
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800473 if (forward_address == nullptr) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800474 forward_address = MarkNonForwardedObject(obj);
475 DCHECK(forward_address != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700476 // Make sure to only update the forwarding address AFTER you copy the object so that the
477 // monitor word doesn't get stomped over.
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800478 obj->SetLockWord(LockWord::FromForwardingAddress(
479 reinterpret_cast<size_t>(forward_address)));
480 // Push the object onto the mark stack for later processing.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700481 MarkStackPush(forward_address);
482 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700483 // TODO: Do we need this if in the else statement?
484 } else {
485 accounting::SpaceBitmap* object_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
486 if (LIKELY(object_bitmap != nullptr)) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800487 if (generational_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800488 // If a bump pointer space only collection, we should not
489 // reach here as we don't/won't mark the objects in the
490 // non-moving space (except for the promoted objects.) Note
491 // the non-moving space is added to the immune space.
492 DCHECK(whole_heap_collection_);
493 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700494 // This object was not previously marked.
495 if (!object_bitmap->Test(obj)) {
496 object_bitmap->Set(obj);
497 MarkStackPush(obj);
498 }
499 } else {
500 DCHECK(!to_space_->HasAddress(obj)) << "Marking object in to_space_";
501 if (MarkLargeObject(obj)) {
502 MarkStackPush(obj);
503 }
504 }
505 }
506 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800507 return forward_address;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700508}
509
Mathieu Chartier39e32612013-11-12 16:28:05 -0800510Object* SemiSpace::RecursiveMarkObjectCallback(Object* root, void* arg) {
511 DCHECK(root != nullptr);
512 DCHECK(arg != nullptr);
513 SemiSpace* semi_space = reinterpret_cast<SemiSpace*>(arg);
514 mirror::Object* ret = semi_space->MarkObject(root);
515 semi_space->ProcessMarkStack(true);
516 return ret;
517}
518
Mathieu Chartier590fee92013-09-13 13:46:47 -0700519Object* SemiSpace::MarkRootCallback(Object* root, void* arg) {
520 DCHECK(root != nullptr);
521 DCHECK(arg != nullptr);
522 return reinterpret_cast<SemiSpace*>(arg)->MarkObject(root);
523}
524
525// Marks all objects in the root set.
526void SemiSpace::MarkRoots() {
527 timings_.StartSplit("MarkRoots");
528 // TODO: Visit up image roots as well?
529 Runtime::Current()->VisitRoots(MarkRootCallback, this, false, true);
530 timings_.EndSplit();
531}
532
533void SemiSpace::BindLiveToMarkBitmap(space::ContinuousSpace* space) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700534 CHECK(space->IsMallocSpace());
535 space::MallocSpace* alloc_space = space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700536 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
537 accounting::SpaceBitmap* mark_bitmap = alloc_space->BindLiveToMarkBitmap();
538 GetHeap()->GetMarkBitmap()->ReplaceBitmap(mark_bitmap, live_bitmap);
539}
540
Mathieu Chartier39e32612013-11-12 16:28:05 -0800541mirror::Object* SemiSpace::MarkedForwardingAddressCallback(Object* object, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700542 return reinterpret_cast<SemiSpace*>(arg)->GetMarkedForwardAddress(object);
543}
544
545void SemiSpace::SweepSystemWeaks() {
546 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800547 Runtime::Current()->SweepSystemWeaks(MarkedForwardingAddressCallback, this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700548 timings_.EndSplit();
549}
550
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800551bool SemiSpace::ShouldSweepSpace(space::MallocSpace* space) const {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800552 return space != from_space_ && space != to_space_ && !IsImmuneSpace(space);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700553}
554
555void SemiSpace::Sweep(bool swap_bitmaps) {
556 DCHECK(mark_stack_->IsEmpty());
Ian Rogers5fe9af72013-11-14 00:17:20 -0800557 TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700558 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800559 if (space->IsMallocSpace()) {
Mathieu Chartierec050072014-01-07 16:00:07 -0800560 space::MallocSpace* malloc_space = space->AsMallocSpace();
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800561 if (!ShouldSweepSpace(malloc_space)) {
562 continue;
563 }
Mathieu Chartierec050072014-01-07 16:00:07 -0800564 TimingLogger::ScopedSplit split(
565 malloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", &timings_);
566 size_t freed_objects = 0;
567 size_t freed_bytes = 0;
568 malloc_space->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
569 heap_->RecordFree(freed_objects, freed_bytes);
570 freed_objects_.FetchAndAdd(freed_objects);
571 freed_bytes_.FetchAndAdd(freed_bytes);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700572 }
573 }
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800574 if (!is_large_object_space_immune_) {
575 SweepLargeObjects(swap_bitmaps);
576 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700577}
578
579void SemiSpace::SweepLargeObjects(bool swap_bitmaps) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800580 DCHECK(!is_large_object_space_immune_);
Ian Rogers5fe9af72013-11-14 00:17:20 -0800581 TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700582 size_t freed_objects = 0;
583 size_t freed_bytes = 0;
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -0800584 GetHeap()->GetLargeObjectsSpace()->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800585 freed_large_objects_.FetchAndAdd(freed_objects);
586 freed_large_object_bytes_.FetchAndAdd(freed_bytes);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700587 GetHeap()->RecordFree(freed_objects, freed_bytes);
588}
589
590// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
591// marked, put it on the appropriate list in the heap for later processing.
592void SemiSpace::DelayReferenceReferent(mirror::Class* klass, Object* obj) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800593 heap_->DelayReferenceReferent(klass, obj, MarkedForwardingAddressCallback, this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700594}
595
596// Visit all of the references of an object and update.
597void SemiSpace::ScanObject(Object* obj) {
598 DCHECK(obj != NULL);
599 DCHECK(!from_space_->HasAddress(obj)) << "Scanning object " << obj << " in from space";
600 MarkSweep::VisitObjectReferences(obj, [this](Object* obj, Object* ref, const MemberOffset& offset,
Bernhard Rosenkränzer46053622013-12-12 02:15:52 +0100601 bool /* is_static */) ALWAYS_INLINE_LAMBDA NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700602 mirror::Object* new_address = MarkObject(ref);
603 if (new_address != ref) {
604 DCHECK(new_address != nullptr);
Mathieu Chartierc528dba2013-11-26 12:00:11 -0800605 // Don't need to mark the card since we updating the object address and not changing the
606 // actual objects its pointing to. Using SetFieldPtr is better in this case since it does not
607 // dirty cards and use additional memory.
608 obj->SetFieldPtr(offset, new_address, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700609 }
610 }, kMovingClasses);
611 mirror::Class* klass = obj->GetClass();
612 if (UNLIKELY(klass->IsReferenceClass())) {
613 DelayReferenceReferent(klass, obj);
614 }
615}
616
617// Scan anything that's on the mark stack.
618void SemiSpace::ProcessMarkStack(bool paused) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800619 space::MallocSpace* promo_dest_space = NULL;
620 accounting::SpaceBitmap* live_bitmap = NULL;
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800621 if (generational_ && !whole_heap_collection_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800622 // If a bump pointer space only collection (and the promotion is
623 // enabled,) we delay the live-bitmap marking of promoted objects
624 // from MarkObject() until this function.
625 promo_dest_space = GetHeap()->GetPrimaryFreeListSpace();
626 live_bitmap = promo_dest_space->GetLiveBitmap();
627 DCHECK(live_bitmap != nullptr);
628 accounting::SpaceBitmap* mark_bitmap = promo_dest_space->GetMarkBitmap();
629 DCHECK(mark_bitmap != nullptr);
630 DCHECK_EQ(live_bitmap, mark_bitmap);
631 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700632 timings_.StartSplit(paused ? "(paused)ProcessMarkStack" : "ProcessMarkStack");
633 while (!mark_stack_->IsEmpty()) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800634 Object* obj = mark_stack_->PopBack();
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800635 if (generational_ && !whole_heap_collection_ && promo_dest_space->HasAddress(obj)) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800636 // obj has just been promoted. Mark the live bitmap for it,
637 // which is delayed from MarkObject().
638 DCHECK(!live_bitmap->Test(obj));
639 live_bitmap->Set(obj);
640 }
641 ScanObject(obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700642 }
643 timings_.EndSplit();
644}
645
Mathieu Chartier590fee92013-09-13 13:46:47 -0700646inline Object* SemiSpace::GetMarkedForwardAddress(mirror::Object* obj) const
647 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
648 // All immune objects are assumed marked.
649 if (IsImmune(obj)) {
650 return obj;
651 }
652 if (from_space_->HasAddress(obj)) {
653 mirror::Object* forwarding_address = GetForwardingAddressInFromSpace(const_cast<Object*>(obj));
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800654 return forwarding_address; // Returns either the forwarding address or nullptr.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700655 } else if (to_space_->HasAddress(obj)) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800656 // Should be unlikely.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700657 // Already forwarded, must be marked.
658 return obj;
659 }
660 return heap_->GetMarkBitmap()->Test(obj) ? obj : nullptr;
661}
662
Mathieu Chartier590fee92013-09-13 13:46:47 -0700663void SemiSpace::UnBindBitmaps() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800664 TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700665 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Hiroshi Yamauchicf58d4a2013-09-26 14:21:22 -0700666 if (space->IsMallocSpace()) {
667 space::MallocSpace* alloc_space = space->AsMallocSpace();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700668 if (alloc_space->HasBoundBitmaps()) {
669 alloc_space->UnBindBitmaps();
670 heap_->GetMarkBitmap()->ReplaceBitmap(alloc_space->GetLiveBitmap(),
671 alloc_space->GetMarkBitmap());
672 }
673 }
674 }
675}
676
677void SemiSpace::SetToSpace(space::ContinuousMemMapAllocSpace* to_space) {
678 DCHECK(to_space != nullptr);
679 to_space_ = to_space;
680}
681
682void SemiSpace::SetFromSpace(space::ContinuousMemMapAllocSpace* from_space) {
683 DCHECK(from_space != nullptr);
684 from_space_ = from_space;
685}
686
687void SemiSpace::FinishPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800688 TimingLogger::ScopedSplit split("FinishPhase", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700689 // Can't enqueue references if we hold the mutator lock.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700690 Heap* heap = GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700691 timings_.NewSplit("PostGcVerification");
692 heap->PostGcVerification(this);
693
694 // Null the "to" and "from" spaces since compacting from one to the other isn't valid until
695 // further action is done by the heap.
696 to_space_ = nullptr;
697 from_space_ = nullptr;
698
699 // Update the cumulative statistics
Mathieu Chartier590fee92013-09-13 13:46:47 -0700700 total_freed_objects_ += GetFreedObjects() + GetFreedLargeObjects();
701 total_freed_bytes_ += GetFreedBytes() + GetFreedLargeObjectBytes();
702
703 // Ensure that the mark stack is empty.
704 CHECK(mark_stack_->IsEmpty());
705
706 // Update the cumulative loggers.
707 cumulative_timings_.Start();
708 cumulative_timings_.AddLogger(timings_);
709 cumulative_timings_.End();
710
711 // Clear all of the spaces' mark bitmaps.
712 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
713 accounting::SpaceBitmap* bitmap = space->GetMarkBitmap();
714 if (bitmap != nullptr &&
715 space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
716 bitmap->Clear();
717 }
718 }
719 mark_stack_->Reset();
720
721 // Reset the marked large objects.
722 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
723 large_objects->GetMarkObjects()->Clear();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800724
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800725 if (generational_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800726 // Decide whether to do a whole heap collection or a bump pointer
727 // only space collection at the next collection by updating
728 // whole_heap_collection. Enable whole_heap_collection once every
729 // kDefaultWholeHeapCollectionInterval collections.
730 if (!whole_heap_collection_) {
731 --whole_heap_collection_interval_counter_;
732 DCHECK_GE(whole_heap_collection_interval_counter_, 0);
733 if (whole_heap_collection_interval_counter_ == 0) {
734 whole_heap_collection_ = true;
735 }
736 } else {
737 DCHECK_EQ(whole_heap_collection_interval_counter_, 0);
738 whole_heap_collection_interval_counter_ = kDefaultWholeHeapCollectionInterval;
739 whole_heap_collection_ = false;
740 }
741 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700742}
743
744} // namespace collector
745} // namespace gc
746} // namespace art