1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "mod_union_table.h"
18
19#include <memory>
20
21#include "base/stl_util.h"
22#include "bitmap-inl.h"
23#include "card_table-inl.h"
24#include "heap_bitmap.h"
25#include "gc/accounting/space_bitmap-inl.h"
26#include "gc/collector/mark_sweep.h"
27#include "gc/collector/mark_sweep-inl.h"
28#include "gc/heap.h"
29#include "gc/space/space.h"
30#include "gc/space/image_space.h"
31#include "mirror/object-inl.h"
32#include "mirror/class-inl.h"
33#include "mirror/object_array-inl.h"
34#include "space_bitmap-inl.h"
35#include "thread.h"
36
37using ::art::mirror::Object;
38
39namespace art {
40namespace gc {
41namespace accounting {
42
43class ModUnionAddToCardSetVisitor {
44 public:
45  explicit ModUnionAddToCardSetVisitor(ModUnionTable::CardSet* const cleared_cards)
46      : cleared_cards_(cleared_cards) {
47  }
48
49  inline void operator()(uint8_t* card, uint8_t expected_value,
50                         uint8_t new_value ATTRIBUTE_UNUSED) const {
51    if (expected_value == CardTable::kCardDirty) {
52      cleared_cards_->insert(card);
53    }
54  }
55
56 private:
57  ModUnionTable::CardSet* const cleared_cards_;
58};
59
60class ModUnionAddToCardBitmapVisitor {
61 public:
62  explicit ModUnionAddToCardBitmapVisitor(ModUnionTable::CardBitmap* bitmap,
63                                          CardTable* card_table)
64      : bitmap_(bitmap), card_table_(card_table) {
65  }
66
67  inline void operator()(uint8_t* card, uint8_t expected_value,
68                         uint8_t new_value ATTRIBUTE_UNUSED) const {
69    if (expected_value == CardTable::kCardDirty) {
70      // We want the address the card represents, not the address of the card.
71      bitmap_->Set(reinterpret_cast<uintptr_t>(card_table_->AddrFromCard(card)));
72    }
73  }
74
75 private:
76  ModUnionTable::CardBitmap* const bitmap_;
77  CardTable* const card_table_;
78};
79
80class ModUnionAddToCardVectorVisitor {
81 public:
82  explicit ModUnionAddToCardVectorVisitor(std::vector<uint8_t*>* cleared_cards)
83      : cleared_cards_(cleared_cards) {
84  }
85
86  void operator()(uint8_t* card, uint8_t expected_card, uint8_t new_card ATTRIBUTE_UNUSED) const {
87    if (expected_card == CardTable::kCardDirty) {
88      cleared_cards_->push_back(card);
89    }
90  }
91
92 private:
93  std::vector<uint8_t*>* const cleared_cards_;
94};
95
96class ModUnionUpdateObjectReferencesVisitor {
97 public:
98  ModUnionUpdateObjectReferencesVisitor(MarkHeapReferenceCallback* callback, void* arg,
99                                        space::ContinuousSpace* from_space,
100                                        space::ContinuousSpace* immune_space,
101                                        bool* contains_reference_to_other_space)
102    : callback_(callback), arg_(arg), from_space_(from_space), immune_space_(immune_space),
103      contains_reference_to_other_space_(contains_reference_to_other_space) {
104  }
105
106  // Extra parameters are required since we use this same visitor signature for checking objects.
107  void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
108      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
109    // Only add the reference if it is non null and fits our criteria.
110    mirror::HeapReference<Object>* const obj_ptr = obj->GetFieldObjectReferenceAddr(offset);
111    mirror::Object* ref = obj_ptr->AsMirrorPtr();
112    if (ref != nullptr && !from_space_->HasAddress(ref) && !immune_space_->HasAddress(ref)) {
113      *contains_reference_to_other_space_ = true;
114      callback_(obj_ptr, arg_);
115    }
116  }
117
118 private:
119  MarkHeapReferenceCallback* const callback_;
120  void* const arg_;
121  // Space which we are scanning
122  space::ContinuousSpace* const from_space_;
123  space::ContinuousSpace* const immune_space_;
124  // Set if we have any references to another space.
125  bool* const contains_reference_to_other_space_;
126};
127
128class ModUnionScanImageRootVisitor {
129 public:
130  // Immune space is any other space which we don't care about references to. Currently this is
131  // the image space in the case of the zygote mod union table.
132  ModUnionScanImageRootVisitor(MarkHeapReferenceCallback* callback, void* arg,
133                               space::ContinuousSpace* from_space,
134                               space::ContinuousSpace* immune_space,
135                               bool* contains_reference_to_other_space)
136      : callback_(callback), arg_(arg), from_space_(from_space), immune_space_(immune_space),
137        contains_reference_to_other_space_(contains_reference_to_other_space) {}
138
139  void operator()(Object* root) const
140      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
141      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
142    DCHECK(root != nullptr);
143    ModUnionUpdateObjectReferencesVisitor ref_visitor(callback_, arg_, from_space_, immune_space_,
144                                                      contains_reference_to_other_space_);
145    root->VisitReferences<kMovingClasses>(ref_visitor, VoidFunctor());
146  }
147
148 private:
149  MarkHeapReferenceCallback* const callback_;
150  void* const arg_;
151  // Space which we are scanning
152  space::ContinuousSpace* const from_space_;
153  space::ContinuousSpace* const immune_space_;
154  // Set if we have any references to another space.
155  bool* const contains_reference_to_other_space_;
156};
157
158void ModUnionTableReferenceCache::ClearCards() {
159  CardTable* card_table = GetHeap()->GetCardTable();
160  ModUnionAddToCardSetVisitor visitor(&cleared_cards_);
161  // Clear dirty cards in the this space and update the corresponding mod-union bits.
162  card_table->ModifyCardsAtomic(space_->Begin(), space_->End(), AgeCardVisitor(), visitor);
163}
164
165class AddToReferenceArrayVisitor {
166 public:
167  explicit AddToReferenceArrayVisitor(ModUnionTableReferenceCache* mod_union_table,
168                                      std::vector<mirror::HeapReference<Object>*>* references)
169    : mod_union_table_(mod_union_table), references_(references) {
170  }
171
172  // Extra parameters are required since we use this same visitor signature for checking objects.
173  void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
174      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
175    mirror::HeapReference<Object>* ref_ptr = obj->GetFieldObjectReferenceAddr(offset);
176    mirror::Object* ref = ref_ptr->AsMirrorPtr();
177    // Only add the reference if it is non null and fits our criteria.
178    if (ref != nullptr && mod_union_table_->ShouldAddReference(ref)) {
179      // Push the adddress of the reference.
180      references_->push_back(ref_ptr);
181    }
182  }
183
184 private:
185  ModUnionTableReferenceCache* const mod_union_table_;
186  std::vector<mirror::HeapReference<Object>*>* const references_;
187};
188
189class ModUnionReferenceVisitor {
190 public:
191  explicit ModUnionReferenceVisitor(ModUnionTableReferenceCache* const mod_union_table,
192                                    std::vector<mirror::HeapReference<Object>*>* references)
193    : mod_union_table_(mod_union_table),
194      references_(references) {
195  }
196
197  void operator()(Object* obj) const
198      SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
199    // We don't have an early exit since we use the visitor pattern, an early
200    // exit should significantly speed this up.
201    AddToReferenceArrayVisitor visitor(mod_union_table_, references_);
202    obj->VisitReferences<kMovingClasses>(visitor, VoidFunctor());
203  }
204 private:
205  ModUnionTableReferenceCache* const mod_union_table_;
206  std::vector<mirror::HeapReference<Object>*>* const references_;
207};
208
209class CheckReferenceVisitor {
210 public:
211  explicit CheckReferenceVisitor(ModUnionTableReferenceCache* mod_union_table,
212                                 const std::set<const Object*>& references)
213    : mod_union_table_(mod_union_table),
214      references_(references) {
215  }
216
217  // Extra parameters are required since we use this same visitor signature for checking objects.
218  void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
219      SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_, Locks::mutator_lock_) {
220    mirror::Object* ref = obj->GetFieldObject<mirror::Object>(offset);
221    if (ref != nullptr && mod_union_table_->ShouldAddReference(ref) &&
222        references_.find(ref) == references_.end()) {
223      Heap* heap = mod_union_table_->GetHeap();
224      space::ContinuousSpace* from_space = heap->FindContinuousSpaceFromObject(obj, false);
225      space::ContinuousSpace* to_space = heap->FindContinuousSpaceFromObject(ref, false);
226      LOG(INFO) << "Object " << reinterpret_cast<const void*>(obj) << "(" << PrettyTypeOf(obj)
227          << ")" << "References " << reinterpret_cast<const void*>(ref) << "(" << PrettyTypeOf(ref)
228          << ") without being in mod-union table";
229      LOG(INFO) << "FromSpace " << from_space->GetName() << " type "
230          << from_space->GetGcRetentionPolicy();
231      LOG(INFO) << "ToSpace " << to_space->GetName() << " type "
232          << to_space->GetGcRetentionPolicy();
233      heap->DumpSpaces(LOG(INFO));
234      LOG(FATAL) << "FATAL ERROR";
235    }
236  }
237
238 private:
239  ModUnionTableReferenceCache* const mod_union_table_;
240  const std::set<const Object*>& references_;
241};
242
243class ModUnionCheckReferences {
244 public:
245  explicit ModUnionCheckReferences(ModUnionTableReferenceCache* mod_union_table,
246                                   const std::set<const Object*>& references)
247      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_)
248      : mod_union_table_(mod_union_table), references_(references) {
249  }
250
251  void operator()(Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
252    Locks::heap_bitmap_lock_->AssertSharedHeld(Thread::Current());
253    CheckReferenceVisitor visitor(mod_union_table_, references_);
254    obj->VisitReferences<kMovingClasses>(visitor, VoidFunctor());
255  }
256
257 private:
258  ModUnionTableReferenceCache* const mod_union_table_;
259  const std::set<const Object*>& references_;
260};
261
262void ModUnionTableReferenceCache::Verify() {
263  // Start by checking that everything in the mod union table is marked.
264  for (const auto& ref_pair : references_) {
265    for (mirror::HeapReference<Object>* ref : ref_pair.second) {
266      CHECK(heap_->IsLiveObjectLocked(ref->AsMirrorPtr()));
267    }
268  }
269
270  // Check the references of each clean card which is also in the mod union table.
271  CardTable* card_table = heap_->GetCardTable();
272  ContinuousSpaceBitmap* live_bitmap = space_->GetLiveBitmap();
273  for (const auto& ref_pair : references_) {
274    const uint8_t* card = ref_pair.first;
275    if (*card == CardTable::kCardClean) {
276      std::set<const Object*> reference_set;
277      for (mirror::HeapReference<Object>* obj_ptr : ref_pair.second) {
278        reference_set.insert(obj_ptr->AsMirrorPtr());
279      }
280      ModUnionCheckReferences visitor(this, reference_set);
281      uintptr_t start = reinterpret_cast<uintptr_t>(card_table->AddrFromCard(card));
282      live_bitmap->VisitMarkedRange(start, start + CardTable::kCardSize, visitor);
283    }
284  }
285}
286
287void ModUnionTableReferenceCache::Dump(std::ostream& os) {
288  CardTable* card_table = heap_->GetCardTable();
289  os << "ModUnionTable cleared cards: [";
290  for (uint8_t* card_addr : cleared_cards_) {
291    uintptr_t start = reinterpret_cast<uintptr_t>(card_table->AddrFromCard(card_addr));
292    uintptr_t end = start + CardTable::kCardSize;
293    os << reinterpret_cast<void*>(start) << "-" << reinterpret_cast<void*>(end) << ",";
294  }
295  os << "]\nModUnionTable references: [";
296  for (const auto& ref_pair : references_) {
297    const uint8_t* card_addr = ref_pair.first;
298    uintptr_t start = reinterpret_cast<uintptr_t>(card_table->AddrFromCard(card_addr));
299    uintptr_t end = start + CardTable::kCardSize;
300    os << reinterpret_cast<void*>(start) << "-" << reinterpret_cast<void*>(end) << "->{";
301    for (mirror::HeapReference<Object>* ref : ref_pair.second) {
302      os << reinterpret_cast<const void*>(ref->AsMirrorPtr()) << ",";
303    }
304    os << "},";
305  }
306}
307
308void ModUnionTableReferenceCache::UpdateAndMarkReferences(MarkHeapReferenceCallback* callback,
309                                                          void* arg) {
310  CardTable* card_table = heap_->GetCardTable();
311
312  std::vector<mirror::HeapReference<Object>*> cards_references;
313  ModUnionReferenceVisitor add_visitor(this, &cards_references);
314
315  for (const auto& card : cleared_cards_) {
316    // Clear and re-compute alloc space references associated with this card.
317    cards_references.clear();
318    uintptr_t start = reinterpret_cast<uintptr_t>(card_table->AddrFromCard(card));
319    uintptr_t end = start + CardTable::kCardSize;
320    auto* space = heap_->FindContinuousSpaceFromObject(reinterpret_cast<Object*>(start), false);
321    DCHECK(space != nullptr);
322    ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
323    live_bitmap->VisitMarkedRange(start, end, add_visitor);
324
325    // Update the corresponding references for the card.
326    auto found = references_.find(card);
327    if (found == references_.end()) {
328      if (cards_references.empty()) {
329        // No reason to add empty array.
330        continue;
331      }
332      references_.Put(card, cards_references);
333    } else {
334      found->second = cards_references;
335    }
336  }
337  cleared_cards_.clear();
338  size_t count = 0;
339  for (const auto& ref : references_) {
340    for (mirror::HeapReference<Object>* obj_ptr : ref.second) {
341      callback(obj_ptr, arg);
342    }
343    count += ref.second.size();
344  }
345  if (VLOG_IS_ON(heap)) {
346    VLOG(gc) << "Marked " << count << " references in mod union table";
347  }
348}
349
350ModUnionTableCardCache::ModUnionTableCardCache(const std::string& name, Heap* heap,
351                                               space::ContinuousSpace* space)
352    : ModUnionTable(name, heap, space) {
353  // Normally here we could use End() instead of Limit(), but for testing we may want to have a
354  // mod-union table for a space which can still grow.
355  if (!space->IsImageSpace()) {
356    CHECK_ALIGNED(reinterpret_cast<uintptr_t>(space->Limit()), CardTable::kCardSize);
357  }
358  card_bitmap_.reset(CardBitmap::Create(
359      "mod union bitmap", reinterpret_cast<uintptr_t>(space->Begin()),
360      RoundUp(reinterpret_cast<uintptr_t>(space->Limit()), CardTable::kCardSize)));
361}
362
363class CardBitVisitor {
364 public:
365  CardBitVisitor(MarkHeapReferenceCallback* callback, void* arg, space::ContinuousSpace* space,
366                 space::ContinuousSpace* immune_space, ModUnionTable::CardBitmap* card_bitmap)
367      : callback_(callback), arg_(arg), space_(space), immune_space_(immune_space),
368        bitmap_(space->GetLiveBitmap()), card_bitmap_(card_bitmap) {
369    DCHECK(immune_space_ != nullptr);
370  }
371
372  void operator()(size_t bit_index) const {
373    const uintptr_t start = card_bitmap_->AddrFromBitIndex(bit_index);
374    DCHECK(space_->HasAddress(reinterpret_cast<mirror::Object*>(start)))
375        << start << " " << *space_;
376    bool reference_to_other_space = false;
377    ModUnionScanImageRootVisitor scan_visitor(callback_, arg_, space_, immune_space_,
378                                              &reference_to_other_space);
379    bitmap_->VisitMarkedRange(start, start + CardTable::kCardSize, scan_visitor);
380    if (!reference_to_other_space) {
381      // No non null reference to another space, clear the bit.
382      card_bitmap_->ClearBit(bit_index);
383    }
384  }
385
386 private:
387  MarkHeapReferenceCallback* const callback_;
388  void* const arg_;
389  space::ContinuousSpace* const space_;
390  space::ContinuousSpace* const immune_space_;
391  ContinuousSpaceBitmap* const bitmap_;
392  ModUnionTable::CardBitmap* const card_bitmap_;
393};
394
395void ModUnionTableCardCache::ClearCards() {
396  CardTable* const card_table = GetHeap()->GetCardTable();
397  ModUnionAddToCardBitmapVisitor visitor(card_bitmap_.get(), card_table);
398  // Clear dirty cards in the this space and update the corresponding mod-union bits.
399  card_table->ModifyCardsAtomic(space_->Begin(), space_->End(), AgeCardVisitor(), visitor);
400}
401
402// Mark all references to the alloc space(s).
403void ModUnionTableCardCache::UpdateAndMarkReferences(MarkHeapReferenceCallback* callback,
404                                                     void* arg) {
405  auto* image_space = heap_->GetImageSpace();
406  // If we don't have an image space, just pass in space_ as the immune space. Pass in the same
407  // space_ instead of image_space to avoid a null check in ModUnionUpdateObjectReferencesVisitor.
408  CardBitVisitor visitor(callback, arg, space_, image_space != nullptr ? image_space : space_,
409      card_bitmap_.get());
410  card_bitmap_->VisitSetBits(
411      0, RoundUp(space_->Size(), CardTable::kCardSize) / CardTable::kCardSize, visitor);
412}
413
414void ModUnionTableCardCache::Dump(std::ostream& os) {
415  os << "ModUnionTable dirty cards: [";
416  // TODO: Find cleaner way of doing this.
417  for (uint8_t* addr = space_->Begin(); addr < AlignUp(space_->End(), CardTable::kCardSize);
418      addr += CardTable::kCardSize) {
419    if (card_bitmap_->Test(reinterpret_cast<uintptr_t>(addr))) {
420      os << reinterpret_cast<void*>(addr) << "-"
421         << reinterpret_cast<void*>(addr + CardTable::kCardSize) << "\n";
422    }
423  }
424  os << "]";
425}
426
427void ModUnionTableCardCache::SetCards() {
428  // Only clean up to the end since there cannot be any objects past the End() of the space.
429  for (uint8_t* addr = space_->Begin(); addr < AlignUp(space_->End(), CardTable::kCardSize);
430       addr += CardTable::kCardSize) {
431    card_bitmap_->Set(reinterpret_cast<uintptr_t>(addr));
432  }
433}
434
435bool ModUnionTableCardCache::ContainsCardFor(uintptr_t addr) {
436  return card_bitmap_->Test(addr);
437}
438
439void ModUnionTableReferenceCache::SetCards() {
440  for (uint8_t* addr = space_->Begin(); addr < AlignUp(space_->End(), CardTable::kCardSize);
441       addr += CardTable::kCardSize) {
442    cleared_cards_.insert(heap_->GetCardTable()->CardFromAddr(reinterpret_cast<void*>(addr)));
443  }
444}
445
446bool ModUnionTableReferenceCache::ContainsCardFor(uintptr_t addr) {
447  auto* card_ptr = heap_->GetCardTable()->CardFromAddr(reinterpret_cast<void*>(addr));
448  return cleared_cards_.find(card_ptr) != cleared_cards_.end() ||
449      references_.find(card_ptr) != references_.end();
450}
451
452}  // namespace accounting
453}  // namespace gc
454}  // namespace art
455