• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 #include "reference_queue.h"
18 
19 #include "accounting/card_table-inl.h"
20 #include "base/mutex.h"
21 #include "collector/concurrent_copying.h"
22 #include "heap.h"
23 #include "mirror/class-inl.h"
24 #include "mirror/object-inl.h"
25 #include "mirror/reference-inl.h"
26 #include "object_callbacks.h"
27 
28 namespace art {
29 namespace gc {
30 
ReferenceQueue(Mutex * lock)31 ReferenceQueue::ReferenceQueue(Mutex* lock) : lock_(lock), list_(nullptr) {
32 }
33 
AtomicEnqueueIfNotEnqueued(Thread * self,ObjPtr<mirror::Reference> ref)34 void ReferenceQueue::AtomicEnqueueIfNotEnqueued(Thread* self, ObjPtr<mirror::Reference> ref) {
35   DCHECK(ref != nullptr);
36   MutexLock mu(self, *lock_);
37   if (ref->IsUnprocessed()) {
38     EnqueueReference(ref);
39   }
40 }
41 
EnqueueReference(ObjPtr<mirror::Reference> ref)42 void ReferenceQueue::EnqueueReference(ObjPtr<mirror::Reference> ref) {
43   DCHECK(ref != nullptr);
44   CHECK(ref->IsUnprocessed());
45   if (IsEmpty()) {
46     // 1 element cyclic queue, ie: Reference ref = ..; ref.pendingNext = ref;
47     list_ = ref.Ptr();
48   } else {
49     // The list is owned by the GC, everything that has been inserted must already be at least
50     // gray.
51     ObjPtr<mirror::Reference> head = list_->GetPendingNext<kWithoutReadBarrier>();
52     DCHECK(head != nullptr);
53     ref->SetPendingNext(head);
54   }
55   // Add the reference in the middle to preserve the cycle.
56   list_->SetPendingNext(ref);
57 }
58 
DequeuePendingReference()59 ObjPtr<mirror::Reference> ReferenceQueue::DequeuePendingReference() {
60   DCHECK(!IsEmpty());
61   ObjPtr<mirror::Reference> ref = list_->GetPendingNext<kWithoutReadBarrier>();
62   DCHECK(ref != nullptr);
63   // Note: the following code is thread-safe because it is only called from ProcessReferences which
64   // is single threaded.
65   if (list_ == ref) {
66     list_ = nullptr;
67   } else {
68     ObjPtr<mirror::Reference> next = ref->GetPendingNext<kWithoutReadBarrier>();
69     list_->SetPendingNext(next);
70   }
71   ref->SetPendingNext(nullptr);
72   return ref;
73 }
74 
75 // This must be called whenever DequeuePendingReference is called.
DisableReadBarrierForReference(ObjPtr<mirror::Reference> ref)76 void ReferenceQueue::DisableReadBarrierForReference(ObjPtr<mirror::Reference> ref) {
77   Heap* heap = Runtime::Current()->GetHeap();
78   if (kUseBakerReadBarrier && heap->CurrentCollectorType() == kCollectorTypeCC &&
79       heap->ConcurrentCopyingCollector()->IsActive()) {
80     // Change the gray ptr we left in ConcurrentCopying::ProcessMarkStackRef() to non-gray.
81     // We check IsActive() above because we don't want to do this when the zygote compaction
82     // collector (SemiSpace) is running.
83     CHECK(ref != nullptr);
84     collector::ConcurrentCopying* concurrent_copying = heap->ConcurrentCopyingCollector();
85     uint32_t rb_state = ref->GetReadBarrierState();
86     if (rb_state == ReadBarrier::GrayState()) {
87       ref->AtomicSetReadBarrierState(ReadBarrier::GrayState(), ReadBarrier::NonGrayState());
88       CHECK_EQ(ref->GetReadBarrierState(), ReadBarrier::NonGrayState());
89     } else {
90       // In ConcurrentCopying::ProcessMarkStackRef() we may leave a non-gray reference in the queue
91       // and find it here, which is OK.
92       CHECK_EQ(rb_state, ReadBarrier::NonGrayState()) << "ref=" << ref << " rb_state=" << rb_state;
93       ObjPtr<mirror::Object> referent = ref->GetReferent<kWithoutReadBarrier>();
94       // The referent could be null if it's cleared by a mutator (Reference.clear()).
95       if (referent != nullptr) {
96         CHECK(concurrent_copying->IsInToSpace(referent.Ptr()))
97             << "ref=" << ref << " rb_state=" << ref->GetReadBarrierState()
98             << " referent=" << referent;
99       }
100     }
101   }
102 }
103 
Dump(std::ostream & os) const104 void ReferenceQueue::Dump(std::ostream& os) const {
105   ObjPtr<mirror::Reference> cur = list_;
106   os << "Reference starting at list_=" << list_ << "\n";
107   if (cur == nullptr) {
108     return;
109   }
110   do {
111     ObjPtr<mirror::Reference> pending_next = cur->GetPendingNext();
112     os << "Reference= " << cur << " PendingNext=" << pending_next;
113     if (cur->IsFinalizerReferenceInstance()) {
114       os << " Zombie=" << cur->AsFinalizerReference()->GetZombie();
115     }
116     os << "\n";
117     cur = pending_next;
118   } while (cur != list_);
119 }
120 
GetLength() const121 size_t ReferenceQueue::GetLength() const {
122   size_t count = 0;
123   ObjPtr<mirror::Reference> cur = list_;
124   if (cur != nullptr) {
125     do {
126       ++count;
127       cur = cur->GetPendingNext();
128     } while (cur != list_);
129   }
130   return count;
131 }
132 
ClearWhiteReferences(ReferenceQueue * cleared_references,collector::GarbageCollector * collector,bool report_cleared)133 void ReferenceQueue::ClearWhiteReferences(ReferenceQueue* cleared_references,
134                                           collector::GarbageCollector* collector,
135                                           bool report_cleared) {
136   while (!IsEmpty()) {
137     ObjPtr<mirror::Reference> ref = DequeuePendingReference();
138     mirror::HeapReference<mirror::Object>* referent_addr = ref->GetReferentReferenceAddr();
139     // do_atomic_update is false because this happens during the reference processing phase where
140     // Reference.clear() would block.
141     if (!collector->IsNullOrMarkedHeapReference(referent_addr, /*do_atomic_update=*/false)) {
142       // Referent is white, clear it.
143       if (Runtime::Current()->IsActiveTransaction()) {
144         ref->ClearReferent<true>();
145       } else {
146         ref->ClearReferent<false>();
147       }
148       cleared_references->EnqueueReference(ref);
149       if (report_cleared) {
150         static bool already_reported = false;
151         if (!already_reported) {
152           // TODO: Maybe do this only if the queue is non-null?
153           LOG(WARNING)
154               << "Cleared Reference was only reachable from finalizer (only reported once)";
155           already_reported = true;
156         }
157       }
158     }
159     // Delay disabling the read barrier until here so that the ClearReferent call above in
160     // transaction mode will trigger the read barrier.
161     DisableReadBarrierForReference(ref);
162   }
163 }
164 
EnqueueFinalizerReferences(ReferenceQueue * cleared_references,collector::GarbageCollector * collector)165 FinalizerStats ReferenceQueue::EnqueueFinalizerReferences(ReferenceQueue* cleared_references,
166                                                 collector::GarbageCollector* collector) {
167   uint32_t num_refs(0), num_enqueued(0);
168   while (!IsEmpty()) {
169     ObjPtr<mirror::FinalizerReference> ref = DequeuePendingReference()->AsFinalizerReference();
170     ++num_refs;
171     mirror::HeapReference<mirror::Object>* referent_addr = ref->GetReferentReferenceAddr();
172     // do_atomic_update is false because this happens during the reference processing phase where
173     // Reference.clear() would block.
174     if (!collector->IsNullOrMarkedHeapReference(referent_addr, /*do_atomic_update=*/false)) {
175       ObjPtr<mirror::Object> forward_address = collector->MarkObject(referent_addr->AsMirrorPtr());
176       // Move the updated referent to the zombie field.
177       if (Runtime::Current()->IsActiveTransaction()) {
178         ref->SetZombie<true>(forward_address);
179         ref->ClearReferent<true>();
180       } else {
181         ref->SetZombie<false>(forward_address);
182         ref->ClearReferent<false>();
183       }
184       cleared_references->EnqueueReference(ref);
185       ++num_enqueued;
186     }
187     // Delay disabling the read barrier until here so that the ClearReferent call above in
188     // transaction mode will trigger the read barrier.
189     DisableReadBarrierForReference(ref->AsReference());
190   }
191   return FinalizerStats(num_refs, num_enqueued);
192 }
193 
ForwardSoftReferences(MarkObjectVisitor * visitor)194 uint32_t ReferenceQueue::ForwardSoftReferences(MarkObjectVisitor* visitor) {
195   uint32_t num_refs(0);
196   Thread* self = Thread::Current();
197   static constexpr int SR_BUF_SIZE = 32;
198   ObjPtr<mirror::Reference> buf[SR_BUF_SIZE];
199   int n_entries;
200   bool empty;
201   do {
202     {
203       // Acquire lock only a few times and hold it as briefly as possible.
204       MutexLock mu(self, *lock_);
205       empty = IsEmpty();
206       for (n_entries = 0; n_entries < SR_BUF_SIZE && !empty; ++n_entries) {
207         // Dequeuing the Reference here means it could possibly be enqueued again during this GC.
208         // That's unlikely and benign.
209         buf[n_entries] = DequeuePendingReference();
210         empty = IsEmpty();
211       }
212     }
213     for (int i = 0; i < n_entries; ++i) {
214       mirror::HeapReference<mirror::Object>* referent_addr = buf[i]->GetReferentReferenceAddr();
215       if (referent_addr->AsMirrorPtr() != nullptr) {
216         visitor->MarkHeapReference(referent_addr, /*do_atomic_update=*/ true);
217         ++num_refs;
218       }
219       DisableReadBarrierForReference(buf[i]->AsReference());
220     }
221   } while (!empty);
222   return num_refs;
223 }
224 
UpdateRoots(IsMarkedVisitor * visitor)225 void ReferenceQueue::UpdateRoots(IsMarkedVisitor* visitor) {
226   if (list_ != nullptr) {
227     list_ = down_cast<mirror::Reference*>(visitor->IsMarked(list_));
228   }
229 }
230 
231 }  // namespace gc
232 }  // namespace art
233