reference_processor.cc 12.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "reference_processor.h"

19
#include "base/time_utils.h"
20
#include "collector/garbage_collector.h"
21
#include "mirror/class-inl.h"
22 23
#include "mirror/object-inl.h"
#include "mirror/reference-inl.h"
24
#include "reference_processor-inl.h"
25 26 27
#include "reflection.h"
#include "ScopedLocalRef.h"
#include "scoped_thread_state_change.h"
Mathieu Chartier's avatar
Mathieu Chartier committed
28
#include "task_processor.h"
29
#include "utils.h"
30 31 32 33 34
#include "well_known_classes.h"

namespace art {
namespace gc {

Mathieu Chartier's avatar
Mathieu Chartier committed
35 36
static constexpr bool kAsyncReferenceQueueAdd = false;

37
ReferenceProcessor::ReferenceProcessor()
38
    : collector_(nullptr),
39 40 41 42 43 44 45
      preserving_references_(false),
      condition_("reference processor condition", *Locks::reference_processor_lock_) ,
      soft_reference_queue_(Locks::reference_queue_soft_references_lock_),
      weak_reference_queue_(Locks::reference_queue_weak_references_lock_),
      finalizer_reference_queue_(Locks::reference_queue_finalizer_references_lock_),
      phantom_reference_queue_(Locks::reference_queue_phantom_references_lock_),
      cleared_references_(Locks::reference_queue_cleared_references_lock_) {
46 47 48
}

void ReferenceProcessor::EnableSlowPath() {
49
  mirror::Reference::GetJavaLangRefReference()->SetSlowPath(true);
50 51 52
}

void ReferenceProcessor::DisableSlowPath(Thread* self) {
53
  mirror::Reference::GetJavaLangRefReference()->SetSlowPath(false);
54 55 56
  condition_.Broadcast(self);
}

57 58 59 60 61 62
void ReferenceProcessor::BroadcastForSlowPath(Thread* self) {
  CHECK(kUseReadBarrier);
  MutexLock mu(self, *Locks::reference_processor_lock_);
  condition_.Broadcast(self);
}

63
mirror::Object* ReferenceProcessor::GetReferent(Thread* self, mirror::Reference* reference) {
64 65 66 67 68 69 70 71 72 73
  if (!kUseReadBarrier || self->GetWeakRefAccessEnabled()) {
    // Under read barrier / concurrent copying collector, it's not safe to call GetReferent() when
    // weak ref access is disabled as the call includes a read barrier which may push a ref onto the
    // mark stack and interfere with termination of marking.
    mirror::Object* const referent = reference->GetReferent();
    // If the referent is null then it is already cleared, we can just return null since there is no
    // scenario where it becomes non-null during the reference processing phase.
    if (UNLIKELY(!SlowPathEnabled()) || referent == nullptr) {
      return referent;
    }
74
  }
75
  MutexLock mu(self, *Locks::reference_processor_lock_);
76 77
  while ((!kUseReadBarrier && SlowPathEnabled()) ||
         (kUseReadBarrier && !self->GetWeakRefAccessEnabled())) {
78 79 80 81 82
    mirror::HeapReference<mirror::Object>* const referent_addr =
        reference->GetReferentReferenceAddr();
    // If the referent became cleared, return it. Don't need barrier since thread roots can't get
    // updated until after we leave the function due to holding the mutator lock.
    if (referent_addr->AsMirrorPtr() == nullptr) {
83 84
      return nullptr;
    }
85
    // Try to see if the referent is already marked by using the is_marked_callback. We can return
86
    // it to the mutator as long as the GC is not preserving references.
87
    if (LIKELY(collector_ != nullptr)) {
88
      // If it's null it means not marked, but it could become marked if the referent is reachable
89
      // by finalizer referents. So we cannot return in this case and must block. Otherwise, we
90 91 92 93
      // can return it to the mutator as long as the GC is not preserving references, in which
      // case only black nodes can be safely returned. If the GC is preserving references, the
      // mutator could take a white field from a grey or white node and move it somewhere else
      // in the heap causing corruption since this field would get swept.
94
      if (collector_->IsMarkedHeapReference(referent_addr)) {
95
        if (!preserving_references_ ||
96
           (LIKELY(!reference->IsFinalizerReferenceInstance()) && reference->IsUnprocessed())) {
97
          return referent_addr->AsMirrorPtr();
98
        }
99 100
      }
    }
101
    condition_.WaitHoldingLocks(self);
102 103 104 105 106
  }
  return reference->GetReferent();
}

void ReferenceProcessor::StartPreservingReferences(Thread* self) {
107
  MutexLock mu(self, *Locks::reference_processor_lock_);
108 109 110 111
  preserving_references_ = true;
}

void ReferenceProcessor::StopPreservingReferences(Thread* self) {
112
  MutexLock mu(self, *Locks::reference_processor_lock_);
113 114 115 116 117 118 119 120
  preserving_references_ = false;
  // We are done preserving references, some people who are blocked may see a marked referent.
  condition_.Broadcast(self);
}

// Process reference class instances and schedule finalizations.
void ReferenceProcessor::ProcessReferences(bool concurrent, TimingLogger* timings,
                                           bool clear_soft_references,
121
                                           collector::GarbageCollector* collector) {
122
  TimingLogger::ScopedTiming t(concurrent ? __FUNCTION__ : "(Paused)ProcessReferences", timings);
123 124
  Thread* self = Thread::Current();
  {
125
    MutexLock mu(self, *Locks::reference_processor_lock_);
126
    collector_ = collector;
127 128 129 130 131 132
    if (!kUseReadBarrier) {
      CHECK_EQ(SlowPathEnabled(), concurrent) << "Slow path must be enabled iff concurrent";
    } else {
      // Weak ref access is enabled at Zygote compaction by SemiSpace (concurrent == false).
      CHECK_EQ(!self->GetWeakRefAccessEnabled(), concurrent);
    }
133 134 135
  }
  // Unless required to clear soft references with white references, preserve some white referents.
  if (!clear_soft_references) {
136
    TimingLogger::ScopedTiming split(concurrent ? "ForwardSoftReferences" :
137
        "(Paused)ForwardSoftReferences", timings);
138 139 140
    if (concurrent) {
      StartPreservingReferences(self);
    }
Mathieu Chartier's avatar
Mathieu Chartier committed
141 142
    // TODO: Add smarter logic for preserving soft references. The behavior should be a conditional
    // mark if the SoftReference is supposed to be preserved.
143 144
    soft_reference_queue_.ForwardSoftReferences(collector);
    collector->ProcessMarkStack();
145 146 147 148 149
    if (concurrent) {
      StopPreservingReferences(self);
    }
  }
  // Clear all remaining soft and weak references with white referents.
150 151
  soft_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
  weak_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
152
  {
Andreas Gampe's avatar
Andreas Gampe committed
153
    TimingLogger::ScopedTiming t2(concurrent ? "EnqueueFinalizerReferences" :
154 155 156 157 158
        "(Paused)EnqueueFinalizerReferences", timings);
    if (concurrent) {
      StartPreservingReferences(self);
    }
    // Preserve all white objects with finalize methods and schedule them for finalization.
159 160
    finalizer_reference_queue_.EnqueueFinalizerReferences(&cleared_references_, collector);
    collector->ProcessMarkStack();
161 162 163 164 165
    if (concurrent) {
      StopPreservingReferences(self);
    }
  }
  // Clear all finalizer referent reachable soft and weak references with white referents.
166 167
  soft_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
  weak_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
168
  // Clear all phantom references with white referents.
169
  phantom_reference_queue_.ClearWhiteReferences(&cleared_references_, collector);
170 171 172 173 174
  // At this point all reference queues other than the cleared references should be empty.
  DCHECK(soft_reference_queue_.IsEmpty());
  DCHECK(weak_reference_queue_.IsEmpty());
  DCHECK(finalizer_reference_queue_.IsEmpty());
  DCHECK(phantom_reference_queue_.IsEmpty());
175
  {
176
    MutexLock mu(self, *Locks::reference_processor_lock_);
177 178 179 180
    // Need to always do this since the next GC may be concurrent. Doing this for only concurrent
    // could result in a stale is_marked_callback_ being called before the reference processing
    // starts since there is a small window of time where slow_path_enabled_ is enabled but the
    // callback isn't yet set.
181 182 183 184
    collector_ = nullptr;
    if (!kUseReadBarrier && concurrent) {
      // Done processing, disable the slow path and broadcast to the waiters.
      DisableSlowPath(self);
185
    }
186 187 188 189 190 191
  }
}

// Process the "referent" field in a java.lang.ref.Reference.  If the referent has not yet been
// marked, put it on the appropriate list in the heap for later processing.
void ReferenceProcessor::DelayReferenceReferent(mirror::Class* klass, mirror::Reference* ref,
192
                                                collector::GarbageCollector* collector) {
193
  // klass can be the class of the old object if the visitor already updated the class of ref.
194
  DCHECK(klass != nullptr);
195
  DCHECK(klass->IsTypeOfReferenceClass());
196
  mirror::HeapReference<mirror::Object>* referent = ref->GetReferentReferenceAddr();
197
  if (referent->AsMirrorPtr() != nullptr && !collector->IsMarkedHeapReference(referent)) {
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    Thread* self = Thread::Current();
    // TODO: Remove these locks, and use atomic stacks for storing references?
    // We need to check that the references haven't already been enqueued since we can end up
    // scanning the same reference multiple times due to dirty cards.
    if (klass->IsSoftReferenceClass()) {
      soft_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
    } else if (klass->IsWeakReferenceClass()) {
      weak_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
    } else if (klass->IsFinalizerReferenceClass()) {
      finalizer_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
    } else if (klass->IsPhantomReferenceClass()) {
      phantom_reference_queue_.AtomicEnqueueIfNotEnqueued(self, ref);
    } else {
      LOG(FATAL) << "Invalid reference type " << PrettyClass(klass) << " " << std::hex
                 << klass->GetAccessFlags();
213 214 215 216
    }
  }
}

217 218
void ReferenceProcessor::UpdateRoots(IsMarkedVisitor* visitor) {
  cleared_references_.UpdateRoots(visitor);
Mathieu Chartier's avatar
Mathieu Chartier committed
219 220
}

Mathieu Chartier's avatar
Mathieu Chartier committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
class ClearedReferenceTask : public HeapTask {
 public:
  explicit ClearedReferenceTask(jobject cleared_references)
      : HeapTask(NanoTime()), cleared_references_(cleared_references) {
  }
  virtual void Run(Thread* thread) {
    ScopedObjectAccess soa(thread);
    jvalue args[1];
    args[0].l = cleared_references_;
    InvokeWithJValues(soa, nullptr, WellKnownClasses::java_lang_ref_ReferenceQueue_add, args);
    soa.Env()->DeleteGlobalRef(cleared_references_);
  }

 private:
  const jobject cleared_references_;
};

238
void ReferenceProcessor::EnqueueClearedReferences(Thread* self) {
239
  Locks::mutator_lock_->AssertNotHeld(self);
Mathieu Chartier's avatar
Mathieu Chartier committed
240
  // When a runtime isn't started there are no reference queues to care about so ignore.
241 242
  if (!cleared_references_.IsEmpty()) {
    if (LIKELY(Runtime::Current()->IsStarted())) {
Mathieu Chartier's avatar
Mathieu Chartier committed
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
      jobject cleared_references;
      {
        ReaderMutexLock mu(self, *Locks::mutator_lock_);
        cleared_references = self->GetJniEnv()->vm->AddGlobalRef(
            self, cleared_references_.GetList());
      }
      if (kAsyncReferenceQueueAdd) {
        // TODO: This can cause RunFinalization to terminate before newly freed objects are
        // finalized since they may not be enqueued by the time RunFinalization starts.
        Runtime::Current()->GetHeap()->GetTaskProcessor()->AddTask(
            self, new ClearedReferenceTask(cleared_references));
      } else {
        ClearedReferenceTask task(cleared_references);
        task.Run(self);
      }
258 259 260 261 262
    }
    cleared_references_.Clear();
  }
}

263 264 265 266
bool ReferenceProcessor::MakeCircularListIfUnenqueued(mirror::FinalizerReference* reference) {
  Thread* self = Thread::Current();
  MutexLock mu(self, *Locks::reference_processor_lock_);
  // Wait untul we are done processing reference.
267 268
  while ((!kUseReadBarrier && SlowPathEnabled()) ||
         (kUseReadBarrier && !self->GetWeakRefAccessEnabled())) {
269
    condition_.WaitHoldingLocks(self);
270 271 272 273 274 275 276 277
  }
  // At this point, since the sentinel of the reference is live, it is guaranteed to not be
  // enqueued if we just finished processing references. Otherwise, we may be doing the main GC
  // phase. Since we are holding the reference processor lock, it guarantees that reference
  // processing can't begin. The GC could have just enqueued the reference one one of the internal
  // GC queues, but since we hold the lock finalizer_reference_queue_ lock it also prevents this
  // race.
  MutexLock mu2(self, *Locks::reference_queue_finalizer_references_lock_);
278
  if (reference->IsUnprocessed()) {
279
    CHECK(reference->IsFinalizerReferenceInstance());
280
    reference->SetPendingNext(reference);
281 282 283 284 285
    return true;
  }
  return false;
}

286 287
}  // namespace gc
}  // namespace art