referenceProcessor.cpp 54.0 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27 28 29 30 31 32 33 34
#include "precompiled.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/systemDictionary.hpp"
#include "gc_interface/collectedHeap.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "memory/referencePolicy.hpp"
#include "memory/referenceProcessor.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/jniHandles.hpp"
D
duke 已提交
35

36 37 38 39 40
ReferencePolicy* ReferenceProcessor::_always_clear_soft_ref_policy = NULL;
ReferencePolicy* ReferenceProcessor::_default_soft_ref_policy      = NULL;
oop              ReferenceProcessor::_sentinelRef = NULL;
const int        subclasses_of_ref                = REF_PHANTOM - REF_OTHER;

D
duke 已提交
41 42 43
// List of discovered references.
class DiscoveredList {
public:
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  DiscoveredList() : _len(0), _compressed_head(0), _oop_head(NULL) { }
  oop head() const     {
     return UseCompressedOops ?  oopDesc::decode_heap_oop_not_null(_compressed_head) :
                                _oop_head;
  }
  HeapWord* adr_head() {
    return UseCompressedOops ? (HeapWord*)&_compressed_head :
                               (HeapWord*)&_oop_head;
  }
  void   set_head(oop o) {
    if (UseCompressedOops) {
      // Must compress the head ptr.
      _compressed_head = oopDesc::encode_heap_oop_not_null(o);
    } else {
      _oop_head = o;
    }
  }
  bool   empty() const          { return head() == ReferenceProcessor::sentinel_ref(); }
D
duke 已提交
62
  size_t length()               { return _len; }
63 64 65
  void   set_length(size_t len) { _len = len;  }
  void   inc_length(size_t inc) { _len += inc; assert(_len > 0, "Error"); }
  void   dec_length(size_t dec) { _len -= dec; }
D
duke 已提交
66
private:
67 68 69 70
  // Set value depending on UseCompressedOops. This could be a template class
  // but then we have to fix all the instantiations and declarations that use this class.
  oop       _oop_head;
  narrowOop _compressed_head;
D
duke 已提交
71 72 73 74 75 76 77 78
  size_t _len;
};

void referenceProcessor_init() {
  ReferenceProcessor::init_statics();
}

void ReferenceProcessor::init_statics() {
79
  assert(_sentinelRef == NULL, "should be initialized precisely once");
D
duke 已提交
80 81
  EXCEPTION_MARK;
  _sentinelRef = instanceKlass::cast(
82
                    SystemDictionary::Reference_klass())->
83
                      allocate_permanent_instance(THREAD);
D
duke 已提交
84 85 86 87 88 89 90 91 92 93

  // Initialize the master soft ref clock.
  java_lang_ref_SoftReference::set_clock(os::javaTimeMillis());

  if (HAS_PENDING_EXCEPTION) {
      Handle ex(THREAD, PENDING_EXCEPTION);
      vm_exit_during_initialization(ex);
  }
  assert(_sentinelRef != NULL && _sentinelRef->is_oop(),
         "Just constructed it!");
94 95 96 97 98 99
  _always_clear_soft_ref_policy = new AlwaysClearPolicy();
  _default_soft_ref_policy      = new COMPILER2_PRESENT(LRUMaxHeapPolicy())
                                      NOT_COMPILER2(LRUCurrentHeapPolicy());
  if (_always_clear_soft_ref_policy == NULL || _default_soft_ref_policy == NULL) {
    vm_exit_during_initialization("Could not allocate reference policy object");
  }
D
duke 已提交
100 101 102 103 104 105
  guarantee(RefDiscoveryPolicy == ReferenceBasedDiscovery ||
            RefDiscoveryPolicy == ReferentBasedDiscovery,
            "Unrecongnized RefDiscoveryPolicy");
}

ReferenceProcessor::ReferenceProcessor(MemRegion span,
106
                                       bool      mt_processing,
107 108 109 110 111
                                       int       mt_processing_degree,
                                       bool      mt_discovery,
                                       int       mt_discovery_degree,
                                       bool      atomic_discovery,
                                       BoolObjectClosure* is_alive_non_header,
112
                                       bool      discovered_list_needs_barrier)  :
D
duke 已提交
113 114
  _discovering_refs(false),
  _enqueuing_is_done(false),
115
  _is_alive_non_header(is_alive_non_header),
116 117
  _discovered_list_needs_barrier(discovered_list_needs_barrier),
  _bs(NULL),
D
duke 已提交
118 119 120 121 122 123
  _processing_is_mt(mt_processing),
  _next_id(0)
{
  _span = span;
  _discovery_is_atomic = atomic_discovery;
  _discovery_is_mt     = mt_discovery;
124 125
  _num_q               = MAX2(1, mt_processing_degree);
  _max_num_q           = MAX2(_num_q, mt_discovery_degree);
126
  _discoveredSoftRefs  = NEW_C_HEAP_ARRAY(DiscoveredList, _max_num_q * subclasses_of_ref);
D
duke 已提交
127 128 129
  if (_discoveredSoftRefs == NULL) {
    vm_exit_during_initialization("Could not allocated RefProc Array");
  }
130 131 132
  _discoveredWeakRefs    = &_discoveredSoftRefs[_max_num_q];
  _discoveredFinalRefs   = &_discoveredWeakRefs[_max_num_q];
  _discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_q];
133
  assert(sentinel_ref() != NULL, "_sentinelRef is NULL");
D
duke 已提交
134
  // Initialized all entries to _sentinelRef
135
  for (int i = 0; i < _max_num_q * subclasses_of_ref; i++) {
136
        _discoveredSoftRefs[i].set_head(sentinel_ref());
D
duke 已提交
137 138
    _discoveredSoftRefs[i].set_length(0);
  }
139 140 141 142
  // If we do barreirs, cache a copy of the barrier set.
  if (discovered_list_needs_barrier) {
    _bs = Universe::heap()->barrier_set();
  }
143
  setup_policy(false /* default soft ref policy */);
D
duke 已提交
144 145 146 147 148
}

#ifndef PRODUCT
void ReferenceProcessor::verify_no_references_recorded() {
  guarantee(!_discovering_refs, "Discovering refs?");
149
  for (int i = 0; i < _max_num_q * subclasses_of_ref; i++) {
D
duke 已提交
150 151 152 153 154 155 156
    guarantee(_discoveredSoftRefs[i].empty(),
              "Found non-empty discovered list");
  }
}
#endif

void ReferenceProcessor::weak_oops_do(OopClosure* f) {
157 158 159 160 161
  // Should this instead be
  // for (int i = 0; i < subclasses_of_ref; i++_ {
  //   for (int j = 0; j < _num_q; j++) {
  //     int index = i * _max_num_q + j;
  for (int i = 0; i < _max_num_q * subclasses_of_ref; i++) {
162 163 164 165 166
    if (UseCompressedOops) {
      f->do_oop((narrowOop*)_discoveredSoftRefs[i].adr_head());
    } else {
      f->do_oop((oop*)_discoveredSoftRefs[i].adr_head());
    }
D
duke 已提交
167 168 169 170
  }
}

void ReferenceProcessor::oops_do(OopClosure* f) {
171
  f->do_oop(adr_sentinel_ref());
D
duke 已提交
172 173
}

174
void ReferenceProcessor::update_soft_ref_master_clock() {
D
duke 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
  // Update (advance) the soft ref master clock field. This must be done
  // after processing the soft ref list.
  jlong now = os::javaTimeMillis();
  jlong clock = java_lang_ref_SoftReference::clock();
  NOT_PRODUCT(
  if (now < clock) {
    warning("time warp: %d to %d", clock, now);
  }
  )
  // In product mode, protect ourselves from system time being adjusted
  // externally and going backward; see note in the implementation of
  // GenCollectedHeap::time_since_last_gc() for the right way to fix
  // this uniformly throughout the VM; see bug-id 4741166. XXX
  if (now > clock) {
    java_lang_ref_SoftReference::set_clock(now);
  }
  // Else leave clock stalled at its old value until time progresses
  // past clock value.
}

195
void ReferenceProcessor::process_discovered_references(
D
duke 已提交
196 197 198 199 200 201 202 203 204 205 206 207 208 209
  BoolObjectClosure*           is_alive,
  OopClosure*                  keep_alive,
  VoidClosure*                 complete_gc,
  AbstractRefProcTaskExecutor* task_executor) {
  NOT_PRODUCT(verify_ok_to_handle_reflists());

  assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
  // Stop treating discovered references specially.
  disable_discovery();

  bool trace_time = PrintGCDetails && PrintReferenceGC;
  // Soft references
  {
    TraceTime tt("SoftReference", trace_time, false, gclog_or_tty);
210
    process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
D
duke 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
                               is_alive, keep_alive, complete_gc, task_executor);
  }

  update_soft_ref_master_clock();

  // Weak references
  {
    TraceTime tt("WeakReference", trace_time, false, gclog_or_tty);
    process_discovered_reflist(_discoveredWeakRefs, NULL, true,
                               is_alive, keep_alive, complete_gc, task_executor);
  }

  // Final references
  {
    TraceTime tt("FinalReference", trace_time, false, gclog_or_tty);
    process_discovered_reflist(_discoveredFinalRefs, NULL, false,
                               is_alive, keep_alive, complete_gc, task_executor);
  }

  // Phantom references
  {
    TraceTime tt("PhantomReference", trace_time, false, gclog_or_tty);
    process_discovered_reflist(_discoveredPhantomRefs, NULL, false,
                               is_alive, keep_alive, complete_gc, task_executor);
  }

  // Weak global JNI references. It would make more sense (semantically) to
  // traverse these simultaneously with the regular weak references above, but
  // that is not how the JDK1.2 specification is. See #4126360. Native code can
  // thus use JNI weak references to circumvent the phantom references and
  // resurrect a "post-mortem" object.
  {
    TraceTime tt("JNI Weak Reference", trace_time, false, gclog_or_tty);
    if (task_executor != NULL) {
      task_executor->set_single_threaded_mode();
    }
    process_phaseJNI(is_alive, keep_alive, complete_gc);
  }
}

#ifndef PRODUCT
// Calculate the number of jni handles.
253
uint ReferenceProcessor::count_jni_refs() {
D
duke 已提交
254 255
  class AlwaysAliveClosure: public BoolObjectClosure {
  public:
256 257
    virtual bool do_object_b(oop obj) { return true; }
    virtual void do_object(oop obj) { assert(false, "Don't call"); }
D
duke 已提交
258 259 260 261 262 263 264
  };

  class CountHandleClosure: public OopClosure {
  private:
    int _count;
  public:
    CountHandleClosure(): _count(0) {}
265 266
    void do_oop(oop* unused)       { _count++; }
    void do_oop(narrowOop* unused) { ShouldNotReachHere(); }
D
duke 已提交
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    int count() { return _count; }
  };
  CountHandleClosure global_handle_count;
  AlwaysAliveClosure always_alive;
  JNIHandles::weak_oops_do(&always_alive, &global_handle_count);
  return global_handle_count.count();
}
#endif

void ReferenceProcessor::process_phaseJNI(BoolObjectClosure* is_alive,
                                          OopClosure*        keep_alive,
                                          VoidClosure*       complete_gc) {
#ifndef PRODUCT
  if (PrintGCDetails && PrintReferenceGC) {
    unsigned int count = count_jni_refs();
    gclog_or_tty->print(", %u refs", count);
  }
#endif
  JNIHandles::weak_oops_do(is_alive, keep_alive);
  // Finally remember to keep sentinel around
287
  keep_alive->do_oop(adr_sentinel_ref());
D
duke 已提交
288 289 290
  complete_gc->do_void();
}

291 292

template <class T>
293 294
bool enqueue_discovered_ref_helper(ReferenceProcessor* ref,
                                   AbstractRefProcTaskExecutor* task_executor) {
295

D
duke 已提交
296
  // Remember old value of pending references list
297 298
  T* pending_list_addr = (T*)java_lang_ref_Reference::pending_list_addr();
  T old_pending_list_value = *pending_list_addr;
D
duke 已提交
299 300 301

  // Enqueue references that are not made active again, and
  // clear the decks for the next collection (cycle).
302
  ref->enqueue_discovered_reflists((HeapWord*)pending_list_addr, task_executor);
D
duke 已提交
303 304 305 306 307 308
  // Do the oop-check on pending_list_addr missed in
  // enqueue_discovered_reflist. We should probably
  // do a raw oop_check so that future such idempotent
  // oop_stores relying on the oop-check side-effect
  // may be elided automatically and safely without
  // affecting correctness.
309
  oop_store(pending_list_addr, oopDesc::load_decode_heap_oop(pending_list_addr));
D
duke 已提交
310 311

  // Stop treating discovered references specially.
312
  ref->disable_discovery();
D
duke 已提交
313 314 315 316 317

  // Return true if new pending references were added
  return old_pending_list_value != *pending_list_addr;
}

318 319 320 321 322 323 324 325 326
bool ReferenceProcessor::enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor) {
  NOT_PRODUCT(verify_ok_to_handle_reflists());
  if (UseCompressedOops) {
    return enqueue_discovered_ref_helper<narrowOop>(this, task_executor);
  } else {
    return enqueue_discovered_ref_helper<oop>(this, task_executor);
  }
}

D
duke 已提交
327
void ReferenceProcessor::enqueue_discovered_reflist(DiscoveredList& refs_list,
328
                                                    HeapWord* pending_list_addr) {
D
duke 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341
  // Given a list of refs linked through the "discovered" field
  // (java.lang.ref.Reference.discovered) chain them through the
  // "next" field (java.lang.ref.Reference.next) and prepend
  // to the pending list.
  if (TraceReferenceGC && PrintGCDetails) {
    gclog_or_tty->print_cr("ReferenceProcessor::enqueue_discovered_reflist list "
                           INTPTR_FORMAT, (address)refs_list.head());
  }
  oop obj = refs_list.head();
  // Walk down the list, copying the discovered field into
  // the next field and clearing it (except for the last
  // non-sentinel object which is treated specially to avoid
  // confusion with an active reference).
342
  while (obj != sentinel_ref()) {
D
duke 已提交
343 344 345
    assert(obj->is_instanceRef(), "should be reference object");
    oop next = java_lang_ref_Reference::discovered(obj);
    if (TraceReferenceGC && PrintGCDetails) {
346 347
      gclog_or_tty->print_cr("        obj " INTPTR_FORMAT "/next " INTPTR_FORMAT,
                             obj, next);
D
duke 已提交
348
    }
349 350 351
    assert(java_lang_ref_Reference::next(obj) == NULL,
           "The reference should not be enqueued");
    if (next == sentinel_ref()) {  // obj is last
D
duke 已提交
352 353
      // Swap refs_list into pendling_list_addr and
      // set obj's next to what we read from pending_list_addr.
354
      oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr);
D
duke 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
      // Need oop_check on pending_list_addr above;
      // see special oop-check code at the end of
      // enqueue_discovered_reflists() further below.
      if (old == NULL) {
        // obj should be made to point to itself, since
        // pending list was empty.
        java_lang_ref_Reference::set_next(obj, obj);
      } else {
        java_lang_ref_Reference::set_next(obj, old);
      }
    } else {
      java_lang_ref_Reference::set_next(obj, next);
    }
    java_lang_ref_Reference::set_discovered(obj, (oop) NULL);
    obj = next;
  }
}

// Parallel enqueue task
class RefProcEnqueueTask: public AbstractRefProcTaskExecutor::EnqueueTask {
public:
  RefProcEnqueueTask(ReferenceProcessor& ref_processor,
                     DiscoveredList      discovered_refs[],
378
                     HeapWord*           pending_list_addr,
D
duke 已提交
379 380 381 382 383 384
                     oop                 sentinel_ref,
                     int                 n_queues)
    : EnqueueTask(ref_processor, discovered_refs,
                  pending_list_addr, sentinel_ref, n_queues)
  { }

385
  virtual void work(unsigned int work_id) {
386
    assert(work_id < (unsigned int)_ref_processor.max_num_q(), "Index out-of-bounds");
D
duke 已提交
387 388
    // Simplest first cut: static partitioning.
    int index = work_id;
389 390 391
    // The increment on "index" must correspond to the maximum number of queues
    // (n_queues) with which that ReferenceProcessor was created.  That
    // is because of the "clever" way the discovered references lists were
392 393
    // allocated and are indexed into.
    assert(_n_queues == (int) _ref_processor.max_num_q(), "Different number not expected");
394 395 396
    for (int j = 0;
         j < subclasses_of_ref;
         j++, index += _n_queues) {
D
duke 已提交
397 398 399 400 401 402 403 404 405
      _ref_processor.enqueue_discovered_reflist(
        _refs_lists[index], _pending_list_addr);
      _refs_lists[index].set_head(_sentinel_ref);
      _refs_lists[index].set_length(0);
    }
  }
};

// Enqueue references that are not made active again
406
void ReferenceProcessor::enqueue_discovered_reflists(HeapWord* pending_list_addr,
D
duke 已提交
407 408 409 410
  AbstractRefProcTaskExecutor* task_executor) {
  if (_processing_is_mt && task_executor != NULL) {
    // Parallel code
    RefProcEnqueueTask tsk(*this, _discoveredSoftRefs,
411
                           pending_list_addr, sentinel_ref(), _max_num_q);
D
duke 已提交
412 413 414
    task_executor->execute(tsk);
  } else {
    // Serial code: call the parent class's implementation
415
    for (int i = 0; i < _max_num_q * subclasses_of_ref; i++) {
D
duke 已提交
416
      enqueue_discovered_reflist(_discoveredSoftRefs[i], pending_list_addr);
417
      _discoveredSoftRefs[i].set_head(sentinel_ref());
D
duke 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430
      _discoveredSoftRefs[i].set_length(0);
    }
  }
}

// Iterator for the list of discovered references.
class DiscoveredListIterator {
public:
  inline DiscoveredListIterator(DiscoveredList&    refs_list,
                                OopClosure*        keep_alive,
                                BoolObjectClosure* is_alive);

  // End Of List.
431
  inline bool has_next() const { return _next != ReferenceProcessor::sentinel_ref(); }
D
duke 已提交
432 433

  // Get oop to the Reference object.
434
  inline oop obj() const { return _ref; }
D
duke 已提交
435 436

  // Get oop to the referent object.
437
  inline oop referent() const { return _referent; }
D
duke 已提交
438 439 440 441 442 443 444 445

  // Returns true if referent is alive.
  inline bool is_referent_alive() const;

  // Loads data for the current reference.
  // The "allow_null_referent" argument tells us to allow for the possibility
  // of a NULL referent in the discovered Reference object. This typically
  // happens in the case of concurrent collectors that may have done the
446
  // discovery concurrently, or interleaved, with mutator execution.
D
duke 已提交
447 448 449 450 451
  inline void load_ptrs(DEBUG_ONLY(bool allow_null_referent));

  // Move to the next discovered reference.
  inline void next();

452
  // Remove the current reference from the list
D
duke 已提交
453 454 455 456 457 458
  inline void remove();

  // Make the Reference object active again.
  inline void make_active() { java_lang_ref_Reference::set_next(_ref, NULL); }

  // Make the referent alive.
459 460 461 462 463 464 465
  inline void make_referent_alive() {
    if (UseCompressedOops) {
      _keep_alive->do_oop((narrowOop*)_referent_addr);
    } else {
      _keep_alive->do_oop((oop*)_referent_addr);
    }
  }
D
duke 已提交
466 467

  // Update the discovered field.
468 469 470 471 472 473 474 475
  inline void update_discovered() {
    // First _prev_next ref actually points into DiscoveredList (gross).
    if (UseCompressedOops) {
      _keep_alive->do_oop((narrowOop*)_prev_next);
    } else {
      _keep_alive->do_oop((oop*)_prev_next);
    }
  }
D
duke 已提交
476 477

  // NULL out referent pointer.
478
  inline void clear_referent() { oop_store_raw(_referent_addr, NULL); }
D
duke 已提交
479 480 481 482 483 484 485 486 487 488 489

  // Statistics
  NOT_PRODUCT(
  inline size_t processed() const { return _processed; }
  inline size_t removed() const   { return _removed; }
  )

  inline void move_to_next();

private:
  DiscoveredList&    _refs_list;
490
  HeapWord*          _prev_next;
D
duke 已提交
491
  oop                _ref;
492
  HeapWord*          _discovered_addr;
D
duke 已提交
493
  oop                _next;
494
  HeapWord*          _referent_addr;
D
duke 已提交
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
  oop                _referent;
  OopClosure*        _keep_alive;
  BoolObjectClosure* _is_alive;
  DEBUG_ONLY(
  oop                _first_seen; // cyclic linked list check
  )
  NOT_PRODUCT(
  size_t             _processed;
  size_t             _removed;
  )
};

inline DiscoveredListIterator::DiscoveredListIterator(DiscoveredList&    refs_list,
                                                      OopClosure*        keep_alive,
                                                      BoolObjectClosure* is_alive)
  : _refs_list(refs_list),
511
    _prev_next(refs_list.adr_head()),
D
duke 已提交
512 513 514 515 516 517 518 519 520 521 522 523 524
    _ref(refs_list.head()),
#ifdef ASSERT
    _first_seen(refs_list.head()),
#endif
#ifndef PRODUCT
    _processed(0),
    _removed(0),
#endif
    _next(refs_list.head()),
    _keep_alive(keep_alive),
    _is_alive(is_alive)
{ }

525
inline bool DiscoveredListIterator::is_referent_alive() const {
D
duke 已提交
526 527 528
  return _is_alive->do_object_b(_referent);
}

529
inline void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
D
duke 已提交
530
  _discovered_addr = java_lang_ref_Reference::discovered_addr(_ref);
531 532
  oop discovered = java_lang_ref_Reference::discovered(_ref);
  assert(_discovered_addr && discovered->is_oop_or_null(),
D
duke 已提交
533
         "discovered field is bad");
534
  _next = discovered;
D
duke 已提交
535
  _referent_addr = java_lang_ref_Reference::referent_addr(_ref);
536
  _referent = java_lang_ref_Reference::referent(_ref);
D
duke 已提交
537 538 539 540 541 542 543 544
  assert(Universe::heap()->is_in_reserved_or_null(_referent),
         "Wrong oop found in java.lang.Reference object");
  assert(allow_null_referent ?
             _referent->is_oop_or_null()
           : _referent->is_oop(),
         "bad referent");
}

545
inline void DiscoveredListIterator::next() {
D
duke 已提交
546 547 548 549
  _prev_next = _discovered_addr;
  move_to_next();
}

550
inline void DiscoveredListIterator::remove() {
D
duke 已提交
551
  assert(_ref->is_oop(), "Dropping a bad reference");
552 553 554 555 556 557 558 559 560
  oop_store_raw(_discovered_addr, NULL);
  // First _prev_next ref actually points into DiscoveredList (gross).
  if (UseCompressedOops) {
    // Remove Reference object from list.
    oopDesc::encode_store_heap_oop_not_null((narrowOop*)_prev_next, _next);
  } else {
    // Remove Reference object from list.
    oopDesc::store_heap_oop((oop*)_prev_next, _next);
  }
D
duke 已提交
561
  NOT_PRODUCT(_removed++);
562
  _refs_list.dec_length(1);
D
duke 已提交
563 564
}

565
inline void DiscoveredListIterator::move_to_next() {
D
duke 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
  _ref = _next;
  assert(_ref != _first_seen, "cyclic ref_list found");
  NOT_PRODUCT(_processed++);
}

// NOTE: process_phase*() are largely similar, and at a high level
// merely iterate over the extant list applying a predicate to
// each of its elements and possibly removing that element from the
// list and applying some further closures to that element.
// We should consider the possibility of replacing these
// process_phase*() methods by abstracting them into
// a single general iterator invocation that receives appropriate
// closures that accomplish this work.

// (SoftReferences only) Traverse the list and remove any SoftReferences whose
// referents are not alive, but that should be kept alive for policy reasons.
// Keep alive the transitive closure of all such referents.
void
584
ReferenceProcessor::process_phase1(DiscoveredList&    refs_list,
D
duke 已提交
585 586 587 588 589
                                   ReferencePolicy*   policy,
                                   BoolObjectClosure* is_alive,
                                   OopClosure*        keep_alive,
                                   VoidClosure*       complete_gc) {
  assert(policy != NULL, "Must have a non-NULL policy");
590
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
591 592 593 594 595 596 597
  // Decide which softly reachable refs should be kept alive.
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
    bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
    if (referent_is_dead && !policy->should_clear_reference(iter.obj())) {
      if (TraceReferenceGC) {
        gclog_or_tty->print_cr("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
598
                               iter.obj(), iter.obj()->blueprint()->internal_name());
D
duke 已提交
599
      }
600 601
      // Remove Reference object from list
      iter.remove();
D
duke 已提交
602 603 604 605
      // Make the Reference object active again
      iter.make_active();
      // keep the referent around
      iter.make_referent_alive();
606
      iter.move_to_next();
D
duke 已提交
607 608 609 610 611 612 613 614
    } else {
      iter.next();
    }
  }
  // Close the reachable set
  complete_gc->do_void();
  NOT_PRODUCT(
    if (PrintGCDetails && TraceReferenceGC) {
615 616 617
      gclog_or_tty->print_cr(" Dropped %d dead Refs out of %d "
        "discovered Refs by policy  list " INTPTR_FORMAT,
        iter.removed(), iter.processed(), (address)refs_list.head());
D
duke 已提交
618 619 620 621 622 623 624
    }
  )
}

// Traverse the list and remove any Refs that are not active, or
// whose referents are either alive or NULL.
void
625
ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
D
duke 已提交
626
                             BoolObjectClosure* is_alive,
627
                             OopClosure*        keep_alive) {
D
duke 已提交
628
  assert(discovery_is_atomic(), "Error");
629
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
630 631
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
632 633
    DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
    assert(next == NULL, "Should not discover inactive Reference");
D
duke 已提交
634 635 636
    if (iter.is_referent_alive()) {
      if (TraceReferenceGC) {
        gclog_or_tty->print_cr("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
637
                               iter.obj(), iter.obj()->blueprint()->internal_name());
D
duke 已提交
638 639
      }
      // The referent is reachable after all.
640 641
      // Remove Reference object from list.
      iter.remove();
D
duke 已提交
642 643 644 645
      // Update the referent pointer as necessary: Note that this
      // should not entail any recursive marking because the
      // referent must already have been traversed.
      iter.make_referent_alive();
646
      iter.move_to_next();
D
duke 已提交
647 648 649 650 651
    } else {
      iter.next();
    }
  }
  NOT_PRODUCT(
652
    if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
653 654 655
      gclog_or_tty->print_cr(" Dropped %d active Refs out of %d "
        "Refs in discovered list " INTPTR_FORMAT,
        iter.removed(), iter.processed(), (address)refs_list.head());
D
duke 已提交
656 657 658 659 660
    }
  )
}

void
661 662 663 664
ReferenceProcessor::pp2_work_concurrent_discovery(DiscoveredList&    refs_list,
                                                  BoolObjectClosure* is_alive,
                                                  OopClosure*        keep_alive,
                                                  VoidClosure*       complete_gc) {
D
duke 已提交
665
  assert(!discovery_is_atomic(), "Error");
666
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
667 668
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
669 670
    HeapWord* next_addr = java_lang_ref_Reference::next_addr(iter.obj());
    oop next = java_lang_ref_Reference::next(iter.obj());
D
duke 已提交
671
    if ((iter.referent() == NULL || iter.is_referent_alive() ||
672 673
         next != NULL)) {
      assert(next->is_oop_or_null(), "bad next field");
D
duke 已提交
674 675 676 677
      // Remove Reference object from list
      iter.remove();
      // Trace the cohorts
      iter.make_referent_alive();
678 679 680 681 682
      if (UseCompressedOops) {
        keep_alive->do_oop((narrowOop*)next_addr);
      } else {
        keep_alive->do_oop((oop*)next_addr);
      }
683
      iter.move_to_next();
D
duke 已提交
684 685 686 687 688 689 690
    } else {
      iter.next();
    }
  }
  // Now close the newly reachable set
  complete_gc->do_void();
  NOT_PRODUCT(
691
    if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
692 693 694
      gclog_or_tty->print_cr(" Dropped %d active Refs out of %d "
        "Refs in discovered list " INTPTR_FORMAT,
        iter.removed(), iter.processed(), (address)refs_list.head());
D
duke 已提交
695 696 697 698 699
    }
  )
}

// Traverse the list and process the referents, by either
700
// clearing them or keeping them (and their reachable
D
duke 已提交
701 702
// closure) alive.
void
703
ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
D
duke 已提交
704 705 706 707
                                   bool               clear_referent,
                                   BoolObjectClosure* is_alive,
                                   OopClosure*        keep_alive,
                                   VoidClosure*       complete_gc) {
708
  ResourceMark rm;
709
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
710 711 712 713 714 715 716 717 718 719 720 721 722
  while (iter.has_next()) {
    iter.update_discovered();
    iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
    if (clear_referent) {
      // NULL out referent pointer
      iter.clear_referent();
    } else {
      // keep the referent around
      iter.make_referent_alive();
    }
    if (TraceReferenceGC) {
      gclog_or_tty->print_cr("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
                             clear_referent ? "cleared " : "",
723
                             iter.obj(), iter.obj()->blueprint()->internal_name());
D
duke 已提交
724 725 726 727 728 729 730 731 732 733 734
    }
    assert(iter.obj()->is_oop(UseConcMarkSweepGC), "Adding a bad reference");
    iter.next();
  }
  // Remember to keep sentinel pointer around
  iter.update_discovered();
  // Close the reachable set
  complete_gc->do_void();
}

void
735 736 737 738 739 740 741 742 743
ReferenceProcessor::abandon_partial_discovered_list(DiscoveredList& refs_list) {
  oop obj = refs_list.head();
  while (obj != sentinel_ref()) {
    oop discovered = java_lang_ref_Reference::discovered(obj);
    java_lang_ref_Reference::set_discovered_raw(obj, NULL);
    obj = discovered;
  }
  refs_list.set_head(sentinel_ref());
  refs_list.set_length(0);
D
duke 已提交
744 745
}

746 747
void ReferenceProcessor::abandon_partial_discovery() {
  // loop over the lists
748 749
  for (int i = 0; i < _max_num_q * subclasses_of_ref; i++) {
    if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
750 751
      gclog_or_tty->print_cr("\nAbandoning %s discovered list",
                             list_name(i));
752 753
    }
    abandon_partial_discovered_list(_discoveredSoftRefs[i]);
D
duke 已提交
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
  }
}

class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
public:
  RefProcPhase1Task(ReferenceProcessor& ref_processor,
                    DiscoveredList      refs_lists[],
                    ReferencePolicy*    policy,
                    bool                marks_oops_alive)
    : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
      _policy(policy)
  { }
  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
                    OopClosure& keep_alive,
                    VoidClosure& complete_gc)
  {
770 771 772
    Thread* thr = Thread::current();
    int refs_list_index = ((WorkerThread*)thr)->id();
    _ref_processor.process_phase1(_refs_lists[refs_list_index], _policy,
D
duke 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807
                                  &is_alive, &keep_alive, &complete_gc);
  }
private:
  ReferencePolicy* _policy;
};

class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
public:
  RefProcPhase2Task(ReferenceProcessor& ref_processor,
                    DiscoveredList      refs_lists[],
                    bool                marks_oops_alive)
    : ProcessTask(ref_processor, refs_lists, marks_oops_alive)
  { }
  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
                    OopClosure& keep_alive,
                    VoidClosure& complete_gc)
  {
    _ref_processor.process_phase2(_refs_lists[i],
                                  &is_alive, &keep_alive, &complete_gc);
  }
};

class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
public:
  RefProcPhase3Task(ReferenceProcessor& ref_processor,
                    DiscoveredList      refs_lists[],
                    bool                clear_referent,
                    bool                marks_oops_alive)
    : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
      _clear_referent(clear_referent)
  { }
  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
                    OopClosure& keep_alive,
                    VoidClosure& complete_gc)
  {
808 809 810 811 812
    // Don't use "refs_list_index" calculated in this way because
    // balance_queues() has moved the Ref's into the first n queues.
    // Thread* thr = Thread::current();
    // int refs_list_index = ((WorkerThread*)thr)->id();
    // _ref_processor.process_phase3(_refs_lists[refs_list_index], _clear_referent,
D
duke 已提交
813 814 815 816 817 818 819 820
    _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
                                  &is_alive, &keep_alive, &complete_gc);
  }
private:
  bool _clear_referent;
};

// Balances reference queues.
821 822 823
// Move entries from all queues[0, 1, ..., _max_num_q-1] to
// queues[0, 1, ..., _num_q-1] because only the first _num_q
// corresponding to the active workers will be processed.
D
duke 已提交
824 825 826 827
void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[])
{
  // calculate total length
  size_t total_refs = 0;
828 829 830 831 832
  if (TraceReferenceGC && PrintGCDetails) {
    gclog_or_tty->print_cr("\nBalance ref_lists ");
  }

  for (int i = 0; i < _max_num_q; ++i) {
D
duke 已提交
833
    total_refs += ref_lists[i].length();
834 835 836 837 838 839
    if (TraceReferenceGC && PrintGCDetails) {
      gclog_or_tty->print("%d ", ref_lists[i].length());
    }
  }
  if (TraceReferenceGC && PrintGCDetails) {
    gclog_or_tty->print_cr(" = %d", total_refs);
D
duke 已提交
840 841 842
  }
  size_t avg_refs = total_refs / _num_q + 1;
  int to_idx = 0;
843 844 845 846 847 848 849
  for (int from_idx = 0; from_idx < _max_num_q; from_idx++) {
    bool move_all = false;
    if (from_idx >= _num_q) {
      move_all = ref_lists[from_idx].length() > 0;
    }
    while ((ref_lists[from_idx].length() > avg_refs) ||
           move_all) {
D
duke 已提交
850 851 852
      assert(to_idx < _num_q, "Sanity Check!");
      if (ref_lists[to_idx].length() < avg_refs) {
        // move superfluous refs
853 854 855 856 857 858 859 860 861
        size_t refs_to_move;
        // Move all the Ref's if the from queue will not be processed.
        if (move_all) {
          refs_to_move = MIN2(ref_lists[from_idx].length(),
                              avg_refs - ref_lists[to_idx].length());
        } else {
          refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs,
                              avg_refs - ref_lists[to_idx].length());
        }
D
duke 已提交
862 863 864 865 866 867
        oop move_head = ref_lists[from_idx].head();
        oop move_tail = move_head;
        oop new_head  = move_head;
        // find an element to split the list on
        for (size_t j = 0; j < refs_to_move; ++j) {
          move_tail = new_head;
868
          new_head = java_lang_ref_Reference::discovered(new_head);
D
duke 已提交
869 870 871
        }
        java_lang_ref_Reference::set_discovered(move_tail, ref_lists[to_idx].head());
        ref_lists[to_idx].set_head(move_head);
872
        ref_lists[to_idx].inc_length(refs_to_move);
D
duke 已提交
873
        ref_lists[from_idx].set_head(new_head);
874
        ref_lists[from_idx].dec_length(refs_to_move);
875 876 877
        if (ref_lists[from_idx].length() == 0) {
          break;
        }
D
duke 已提交
878
      } else {
879
        to_idx = (to_idx + 1) % _num_q;
D
duke 已提交
880 881 882
      }
    }
  }
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
#ifdef ASSERT
  size_t balanced_total_refs = 0;
  for (int i = 0; i < _max_num_q; ++i) {
    balanced_total_refs += ref_lists[i].length();
    if (TraceReferenceGC && PrintGCDetails) {
      gclog_or_tty->print("%d ", ref_lists[i].length());
    }
  }
  if (TraceReferenceGC && PrintGCDetails) {
    gclog_or_tty->print_cr(" = %d", balanced_total_refs);
    gclog_or_tty->flush();
  }
  assert(total_refs == balanced_total_refs, "Balancing was incomplete");
#endif
}

void ReferenceProcessor::balance_all_queues() {
  balance_queues(_discoveredSoftRefs);
  balance_queues(_discoveredWeakRefs);
  balance_queues(_discoveredFinalRefs);
  balance_queues(_discoveredPhantomRefs);
D
duke 已提交
904 905 906 907 908 909 910 911 912 913 914 915
}

void
ReferenceProcessor::process_discovered_reflist(
  DiscoveredList               refs_lists[],
  ReferencePolicy*             policy,
  bool                         clear_referent,
  BoolObjectClosure*           is_alive,
  OopClosure*                  keep_alive,
  VoidClosure*                 complete_gc,
  AbstractRefProcTaskExecutor* task_executor)
{
916 917 918 919 920 921 922 923 924 925 926
  bool mt_processing = task_executor != NULL && _processing_is_mt;
  // If discovery used MT and a dynamic number of GC threads, then
  // the queues must be balanced for correctness if fewer than the
  // maximum number of queues were used.  The number of queue used
  // during discovery may be different than the number to be used
  // for processing so don't depend of _num_q < _max_num_q as part
  // of the test.
  bool must_balance = _discovery_is_mt;

  if ((mt_processing && ParallelRefProcBalancingEnabled) ||
      must_balance) {
D
duke 已提交
927 928 929 930
    balance_queues(refs_lists);
  }
  if (PrintReferenceGC && PrintGCDetails) {
    size_t total = 0;
931
    for (int i = 0; i < _max_num_q; ++i) {
D
duke 已提交
932 933 934 935 936 937 938 939 940 941 942
      total += refs_lists[i].length();
    }
    gclog_or_tty->print(", %u refs", total);
  }

  // Phase 1 (soft refs only):
  // . Traverse the list and remove any SoftReferences whose
  //   referents are not alive, but that should be kept alive for
  //   policy reasons. Keep alive the transitive closure of all
  //   such referents.
  if (policy != NULL) {
943
    if (mt_processing) {
D
duke 已提交
944 945 946
      RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/);
      task_executor->execute(phase1);
    } else {
947
      for (int i = 0; i < _max_num_q; i++) {
D
duke 已提交
948 949 950 951 952 953 954 955 956 957 958
        process_phase1(refs_lists[i], policy,
                       is_alive, keep_alive, complete_gc);
      }
    }
  } else { // policy == NULL
    assert(refs_lists != _discoveredSoftRefs,
           "Policy must be specified for soft references.");
  }

  // Phase 2:
  // . Traverse the list and remove any refs whose referents are alive.
959
  if (mt_processing) {
D
duke 已提交
960 961 962
    RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/);
    task_executor->execute(phase2);
  } else {
963
    for (int i = 0; i < _max_num_q; i++) {
D
duke 已提交
964 965 966 967 968 969
      process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
    }
  }

  // Phase 3:
  // . Traverse the list and process referents as appropriate.
970
  if (mt_processing) {
D
duke 已提交
971 972 973
    RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/);
    task_executor->execute(phase3);
  } else {
974
    for (int i = 0; i < _max_num_q; i++) {
D
duke 已提交
975 976 977 978 979 980 981 982
      process_phase3(refs_lists[i], clear_referent,
                     is_alive, keep_alive, complete_gc);
    }
  }
}

void ReferenceProcessor::clean_up_discovered_references() {
  // loop over the lists
983 984 985 986 987
  // Should this instead be
  // for (int i = 0; i < subclasses_of_ref; i++_ {
  //   for (int j = 0; j < _num_q; j++) {
  //     int index = i * _max_num_q + j;
  for (int i = 0; i < _max_num_q * subclasses_of_ref; i++) {
988
    if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
D
duke 已提交
989 990 991 992 993 994 995 996 997 998 999 1000 1001
      gclog_or_tty->print_cr(
        "\nScrubbing %s discovered list of Null referents",
        list_name(i));
    }
    clean_up_discovered_reflist(_discoveredSoftRefs[i]);
  }
}

void ReferenceProcessor::clean_up_discovered_reflist(DiscoveredList& refs_list) {
  assert(!discovery_is_atomic(), "Else why call this method?");
  DiscoveredListIterator iter(refs_list, NULL, NULL);
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
1002 1003
    oop next = java_lang_ref_Reference::next(iter.obj());
    assert(next->is_oop_or_null(), "bad next field");
D
duke 已提交
1004 1005
    // If referent has been cleared or Reference is not active,
    // drop it.
1006
    if (iter.referent() == NULL || next != NULL) {
D
duke 已提交
1007 1008 1009 1010 1011
      debug_only(
        if (PrintGCDetails && TraceReferenceGC) {
          gclog_or_tty->print_cr("clean_up_discovered_list: Dropping Reference: "
            INTPTR_FORMAT " with next field: " INTPTR_FORMAT
            " and referent: " INTPTR_FORMAT,
1012
            iter.obj(), next, iter.referent());
D
duke 已提交
1013 1014 1015 1016
        }
      )
      // Remove Reference object from list
      iter.remove();
1017
      iter.move_to_next();
D
duke 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    } else {
      iter.next();
    }
  }
  NOT_PRODUCT(
    if (PrintGCDetails && TraceReferenceGC) {
      gclog_or_tty->print(
        " Removed %d Refs with NULL referents out of %d discovered Refs",
        iter.removed(), iter.processed());
    }
  )
}

inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
  int id = 0;
  // Determine the queue index to use for this object.
  if (_discovery_is_mt) {
    // During a multi-threaded discovery phase,
    // each thread saves to its "own" list.
    Thread* thr = Thread::current();
1038
    id = thr->as_Worker_thread()->id();
D
duke 已提交
1039 1040 1041 1042 1043 1044 1045
  } else {
    // single-threaded discovery, we save in round-robin
    // fashion to each of the lists.
    if (_processing_is_mt) {
      id = next_id();
    }
  }
1046
  assert(0 <= id && id < _max_num_q, "Id is out-of-bounds (call Freud?)");
D
duke 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070

  // Get the discovered queue to which we will add
  DiscoveredList* list = NULL;
  switch (rt) {
    case REF_OTHER:
      // Unknown reference type, no special treatment
      break;
    case REF_SOFT:
      list = &_discoveredSoftRefs[id];
      break;
    case REF_WEAK:
      list = &_discoveredWeakRefs[id];
      break;
    case REF_FINAL:
      list = &_discoveredFinalRefs[id];
      break;
    case REF_PHANTOM:
      list = &_discoveredPhantomRefs[id];
      break;
    case REF_NONE:
      // we should not reach here if we are an instanceRefKlass
    default:
      ShouldNotReachHere();
  }
1071
  if (TraceReferenceGC && PrintGCDetails) {
1072
    gclog_or_tty->print_cr("Thread %d gets list " INTPTR_FORMAT, id, list);
1073
  }
D
duke 已提交
1074 1075 1076
  return list;
}

1077 1078 1079 1080
inline void
ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list,
                                              oop             obj,
                                              HeapWord*       discovered_addr) {
D
duke 已提交
1081 1082 1083
  assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller");
  // First we must make sure this object is only enqueued once. CAS in a non null
  // discovered_addr.
1084 1085
  oop current_head = refs_list.head();

1086
  // Note: In the case of G1, this specific pre-barrier is strictly
1087
  // not necessary because the only case we are interested in
1088 1089 1090 1091
  // here is when *discovered_addr is NULL (see the CAS further below),
  // so this will expand to nothing. As a result, we have manually
  // elided this out for G1, but left in the test for some future
  // collector that might have need for a pre-barrier here.
1092
  if (_discovered_list_needs_barrier && !UseG1GC) {
1093 1094 1095 1096 1097 1098
    if (UseCompressedOops) {
      _bs->write_ref_field_pre((narrowOop*)discovered_addr, current_head);
    } else {
      _bs->write_ref_field_pre((oop*)discovered_addr, current_head);
    }
    guarantee(false, "Need to check non-G1 collector");
1099 1100
  }
  oop retest = oopDesc::atomic_compare_exchange_oop(current_head, discovered_addr,
1101
                                                    NULL);
D
duke 已提交
1102 1103 1104 1105
  if (retest == NULL) {
    // This thread just won the right to enqueue the object.
    // We have separate lists for enqueueing so no synchronization
    // is necessary.
1106
    refs_list.set_head(obj);
1107
    refs_list.inc_length(1);
1108
    if (_discovered_list_needs_barrier) {
1109
      _bs->write_ref_field((void*)discovered_addr, current_head);
1110
    }
1111 1112 1113 1114 1115

    if (TraceReferenceGC) {
      gclog_or_tty->print_cr("Enqueued reference (mt) (" INTPTR_FORMAT ": %s)",
                             obj, obj->blueprint()->internal_name());
    }
D
duke 已提交
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
  } else {
    // If retest was non NULL, another thread beat us to it:
    // The reference has already been discovered...
    if (TraceReferenceGC) {
      gclog_or_tty->print_cr("Already enqueued reference (" INTPTR_FORMAT ": %s)",
                             obj, obj->blueprint()->internal_name());
    }
  }
}

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
#ifndef PRODUCT
// Non-atomic (i.e. concurrent) discovery might allow us
// to observe j.l.References with NULL referents, being those
// cleared concurrently by mutators during (or after) discovery.
void ReferenceProcessor::verify_referent(oop obj) {
  bool da = discovery_is_atomic();
  oop referent = java_lang_ref_Reference::referent(obj);
  assert(da ? referent->is_oop() : referent->is_oop_or_null(),
         err_msg("Bad referent " INTPTR_FORMAT " found in Reference "
                 INTPTR_FORMAT " during %satomic discovery ",
                 (intptr_t)referent, (intptr_t)obj, da ? "" : "non-"));
}
#endif

D
duke 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
// We mention two of several possible choices here:
// #0: if the reference object is not in the "originating generation"
//     (or part of the heap being collected, indicated by our "span"
//     we don't treat it specially (i.e. we scan it as we would
//     a normal oop, treating its references as strong references).
//     This means that references can't be enqueued unless their
//     referent is also in the same span. This is the simplest,
//     most "local" and most conservative approach, albeit one
//     that may cause weak references to be enqueued least promptly.
//     We call this choice the "ReferenceBasedDiscovery" policy.
// #1: the reference object may be in any generation (span), but if
//     the referent is in the generation (span) being currently collected
//     then we can discover the reference object, provided
//     the object has not already been discovered by
//     a different concurrently running collector (as may be the
//     case, for instance, if the reference object is in CMS and
//     the referent in DefNewGeneration), and provided the processing
//     of this reference object by the current collector will
//     appear atomic to every other collector in the system.
//     (Thus, for instance, a concurrent collector may not
//     discover references in other generations even if the
//     referent is in its own generation). This policy may,
//     in certain cases, enqueue references somewhat sooner than
//     might Policy #0 above, but at marginally increased cost
//     and complexity in processing these references.
//     We call this choice the "RefeferentBasedDiscovery" policy.
bool ReferenceProcessor::discover_reference(oop obj, ReferenceType rt) {
  // We enqueue references only if we are discovering refs
  // (rather than processing discovered refs).
  if (!_discovering_refs || !RegisterReferences) {
    return false;
  }
  // We only enqueue active references.
1173 1174
  oop next = java_lang_ref_Reference::next(obj);
  if (next != NULL) {
D
duke 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    return false;
  }

  HeapWord* obj_addr = (HeapWord*)obj;
  if (RefDiscoveryPolicy == ReferenceBasedDiscovery &&
      !_span.contains(obj_addr)) {
    // Reference is not in the originating generation;
    // don't treat it specially (i.e. we want to scan it as a normal
    // object with strong references).
    return false;
  }

  // We only enqueue references whose referents are not (yet) strongly
  // reachable.
  if (is_alive_non_header() != NULL) {
1190 1191
    verify_referent(obj);
    if (is_alive_non_header()->do_object_b(java_lang_ref_Reference::referent(obj))) {
D
duke 已提交
1192 1193 1194
      return false;  // referent is reachable
    }
  }
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
  if (rt == REF_SOFT) {
    // For soft refs we can decide now if these are not
    // current candidates for clearing, in which case we
    // can mark through them now, rather than delaying that
    // to the reference-processing phase. Since all current
    // time-stamp policies advance the soft-ref clock only
    // at a major collection cycle, this is always currently
    // accurate.
    if (!_current_soft_ref_policy->should_clear_reference(obj)) {
      return false;
    }
  }
D
duke 已提交
1207

1208 1209
  HeapWord* const discovered_addr = java_lang_ref_Reference::discovered_addr(obj);
  const oop  discovered = java_lang_ref_Reference::discovered(obj);
1210 1211
  assert(discovered->is_oop_or_null(), "bad discovered field");
  if (discovered != NULL) {
D
duke 已提交
1212 1213 1214
    // The reference has already been discovered...
    if (TraceReferenceGC) {
      gclog_or_tty->print_cr("Already enqueued reference (" INTPTR_FORMAT ": %s)",
1215
                             obj, obj->blueprint()->internal_name());
D
duke 已提交
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    }
    if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
      // assumes that an object is not processed twice;
      // if it's been already discovered it must be on another
      // generation's discovered list; so we won't discover it.
      return false;
    } else {
      assert(RefDiscoveryPolicy == ReferenceBasedDiscovery,
             "Unrecognized policy");
      // Check assumption that an object is not potentially
      // discovered twice except by concurrent collectors that potentially
      // trace the same Reference object twice.
1228 1229
      assert(UseConcMarkSweepGC || UseG1GC,
             "Only possible with a concurrent marking collector");
D
duke 已提交
1230 1231 1232 1233 1234
      return true;
    }
  }

  if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
1235
    verify_referent(obj);
D
duke 已提交
1236 1237 1238 1239
    // enqueue if and only if either:
    // reference is in our span or
    // we are an atomic collector and referent is in our span
    if (_span.contains(obj_addr) ||
1240 1241
        (discovery_is_atomic() &&
         _span.contains(java_lang_ref_Reference::referent(obj)))) {
D
duke 已提交
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
      // should_enqueue = true;
    } else {
      return false;
    }
  } else {
    assert(RefDiscoveryPolicy == ReferenceBasedDiscovery &&
           _span.contains(obj_addr), "code inconsistency");
  }

  // Get the right type of discovered queue head.
  DiscoveredList* list = get_discovered_list(rt);
  if (list == NULL) {
    return false;   // nothing special needs to be done
  }

  if (_discovery_is_mt) {
    add_to_discovered_list_mt(*list, obj, discovered_addr);
  } else {
1260 1261 1262 1263 1264 1265 1266 1267 1268
    // If "_discovered_list_needs_barrier", we do write barriers when
    // updating the discovered reference list.  Otherwise, we do a raw store
    // here: the field will be visited later when processing the discovered
    // references.
    oop current_head = list->head();
    // As in the case further above, since we are over-writing a NULL
    // pre-value, we can safely elide the pre-barrier here for the case of G1.
    assert(discovered == NULL, "control point invariant");
    if (_discovered_list_needs_barrier && !UseG1GC) { // safe to elide for G1
1269 1270 1271 1272 1273 1274
      if (UseCompressedOops) {
        _bs->write_ref_field_pre((narrowOop*)discovered_addr, current_head);
      } else {
        _bs->write_ref_field_pre((oop*)discovered_addr, current_head);
      }
      guarantee(false, "Need to check non-G1 collector");
1275 1276 1277
    }
    oop_store_raw(discovered_addr, current_head);
    if (_discovered_list_needs_barrier) {
1278
      _bs->write_ref_field((void*)discovered_addr, current_head);
1279
    }
D
duke 已提交
1280
    list->set_head(obj);
1281
    list->inc_length(1);
D
duke 已提交
1282

1283
    if (TraceReferenceGC) {
D
duke 已提交
1284
      gclog_or_tty->print_cr("Enqueued reference (" INTPTR_FORMAT ": %s)",
1285
                                obj, obj->blueprint()->internal_name());
D
duke 已提交
1286 1287 1288
    }
  }
  assert(obj->is_oop(), "Enqueued a bad reference");
1289
  verify_referent(obj);
D
duke 已提交
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
  return true;
}

// Preclean the discovered references by removing those
// whose referents are alive, and by marking from those that
// are not active. These lists can be handled here
// in any order and, indeed, concurrently.
void ReferenceProcessor::preclean_discovered_references(
  BoolObjectClosure* is_alive,
  OopClosure* keep_alive,
  VoidClosure* complete_gc,
1301 1302
  YieldClosure* yield,
  bool should_unload_classes) {
D
duke 已提交
1303 1304 1305

  NOT_PRODUCT(verify_ok_to_handle_reflists());

1306 1307
#ifdef ASSERT
  bool must_remember_klasses = ClassUnloading && !UseConcMarkSweepGC ||
1308 1309 1310
                               CMSClassUnloadingEnabled && UseConcMarkSweepGC ||
                               ExplicitGCInvokesConcurrentAndUnloadsClasses &&
                                 UseConcMarkSweepGC && should_unload_classes;
1311 1312
  RememberKlassesChecker mx(must_remember_klasses);
#endif
D
duke 已提交
1313 1314 1315 1316
  // Soft references
  {
    TraceTime tt("Preclean SoftReferences", PrintGCDetails && PrintReferenceGC,
              false, gclog_or_tty);
1317
    for (int i = 0; i < _max_num_q; i++) {
1318 1319 1320
      if (yield->should_return()) {
        return;
      }
D
duke 已提交
1321 1322 1323 1324 1325 1326 1327 1328 1329
      preclean_discovered_reflist(_discoveredSoftRefs[i], is_alive,
                                  keep_alive, complete_gc, yield);
    }
  }

  // Weak references
  {
    TraceTime tt("Preclean WeakReferences", PrintGCDetails && PrintReferenceGC,
              false, gclog_or_tty);
1330
    for (int i = 0; i < _max_num_q; i++) {
1331 1332 1333
      if (yield->should_return()) {
        return;
      }
D
duke 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342
      preclean_discovered_reflist(_discoveredWeakRefs[i], is_alive,
                                  keep_alive, complete_gc, yield);
    }
  }

  // Final references
  {
    TraceTime tt("Preclean FinalReferences", PrintGCDetails && PrintReferenceGC,
              false, gclog_or_tty);
1343
    for (int i = 0; i < _max_num_q; i++) {
1344 1345 1346
      if (yield->should_return()) {
        return;
      }
D
duke 已提交
1347 1348 1349 1350 1351 1352 1353 1354 1355
      preclean_discovered_reflist(_discoveredFinalRefs[i], is_alive,
                                  keep_alive, complete_gc, yield);
    }
  }

  // Phantom references
  {
    TraceTime tt("Preclean PhantomReferences", PrintGCDetails && PrintReferenceGC,
              false, gclog_or_tty);
1356
    for (int i = 0; i < _max_num_q; i++) {
1357 1358 1359
      if (yield->should_return()) {
        return;
      }
D
duke 已提交
1360 1361 1362 1363 1364 1365 1366 1367
      preclean_discovered_reflist(_discoveredPhantomRefs[i], is_alive,
                                  keep_alive, complete_gc, yield);
    }
  }
}

// Walk the given discovered ref list, and remove all reference objects
// whose referents are still alive, whose referents are NULL or which
1368 1369 1370 1371 1372 1373
// are not active (have a non-NULL next field). NOTE: When we are
// thus precleaning the ref lists (which happens single-threaded today),
// we do not disable refs discovery to honour the correct semantics of
// java.lang.Reference. As a result, we need to be careful below
// that ref removal steps interleave safely with ref discovery steps
// (in this thread).
1374 1375 1376 1377 1378 1379
void
ReferenceProcessor::preclean_discovered_reflist(DiscoveredList&    refs_list,
                                                BoolObjectClosure* is_alive,
                                                OopClosure*        keep_alive,
                                                VoidClosure*       complete_gc,
                                                YieldClosure*      yield) {
D
duke 已提交
1380 1381 1382
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
1383 1384
    oop obj = iter.obj();
    oop next = java_lang_ref_Reference::next(obj);
D
duke 已提交
1385
    if (iter.referent() == NULL || iter.is_referent_alive() ||
1386
        next != NULL) {
D
duke 已提交
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396
      // The referent has been cleared, or is alive, or the Reference is not
      // active; we need to trace and mark its cohort.
      if (TraceReferenceGC) {
        gclog_or_tty->print_cr("Precleaning Reference (" INTPTR_FORMAT ": %s)",
                               iter.obj(), iter.obj()->blueprint()->internal_name());
      }
      // Remove Reference object from list
      iter.remove();
      // Keep alive its cohort.
      iter.make_referent_alive();
1397 1398 1399 1400 1401 1402 1403
      if (UseCompressedOops) {
        narrowOop* next_addr = (narrowOop*)java_lang_ref_Reference::next_addr(obj);
        keep_alive->do_oop(next_addr);
      } else {
        oop* next_addr = (oop*)java_lang_ref_Reference::next_addr(obj);
        keep_alive->do_oop(next_addr);
      }
1404
      iter.move_to_next();
D
duke 已提交
1405 1406 1407 1408 1409 1410 1411 1412
    } else {
      iter.next();
    }
  }
  // Close the reachable set
  complete_gc->do_void();

  NOT_PRODUCT(
1413
    if (PrintGCDetails && PrintReferenceGC && (iter.processed() > 0)) {
1414 1415 1416
      gclog_or_tty->print_cr(" Dropped %d Refs out of %d "
        "Refs in discovered list " INTPTR_FORMAT,
        iter.removed(), iter.processed(), (address)refs_list.head());
D
duke 已提交
1417 1418 1419 1420 1421
    }
  )
}

const char* ReferenceProcessor::list_name(int i) {
1422 1423
   assert(i >= 0 && i <= _max_num_q * subclasses_of_ref, "Out of bounds index");
   int j = i / _max_num_q;
D
duke 已提交
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
   switch (j) {
     case 0: return "SoftRef";
     case 1: return "WeakRef";
     case 2: return "FinalRef";
     case 3: return "PhantomRef";
   }
   ShouldNotReachHere();
   return NULL;
}

#ifndef PRODUCT
void ReferenceProcessor::verify_ok_to_handle_reflists() {
  // empty for now
}
#endif

void ReferenceProcessor::verify() {
1441
  guarantee(sentinel_ref() != NULL && sentinel_ref()->is_oop(), "Lost _sentinelRef");
D
duke 已提交
1442 1443 1444 1445 1446
}

#ifndef PRODUCT
void ReferenceProcessor::clear_discovered_references() {
  guarantee(!_discovering_refs, "Discovering refs?");
1447
  for (int i = 0; i < _max_num_q * subclasses_of_ref; i++) {
D
duke 已提交
1448
    oop obj = _discoveredSoftRefs[i].head();
1449
    while (obj != sentinel_ref()) {
D
duke 已提交
1450 1451 1452 1453
      oop next = java_lang_ref_Reference::discovered(obj);
      java_lang_ref_Reference::set_discovered(obj, (oop) NULL);
      obj = next;
    }
1454
    _discoveredSoftRefs[i].set_head(sentinel_ref());
D
duke 已提交
1455 1456 1457 1458
    _discoveredSoftRefs[i].set_length(0);
  }
}
#endif // PRODUCT