1 /*
   2  * Copyright (c) 2001, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "gc_interface/collectedHeap.hpp"
  29 #include "gc_interface/collectedHeap.inline.hpp"
  30 #include "memory/referencePolicy.hpp"
  31 #include "memory/referenceProcessor.hpp"
  32 #include "oops/oop.inline.hpp"
  33 #include "runtime/java.hpp"
  34 #include "runtime/jniHandles.hpp"
  35 
  36 ReferencePolicy* ReferenceProcessor::_always_clear_soft_ref_policy = NULL;
  37 ReferencePolicy* ReferenceProcessor::_default_soft_ref_policy      = NULL;
  38 bool             ReferenceProcessor::_pending_list_uses_discovered_field = false;
  39 jlong            ReferenceProcessor::_soft_ref_timestamp_clock = 0;
  40 
  41 void referenceProcessor_init() {
  42   ReferenceProcessor::init_statics();
  43 }
  44 
  45 void ReferenceProcessor::init_statics() {
  46   // We need a montonically increasing time in ms but os::javaTimeMillis()
  47   // does not guarantee montonicity.
  48   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
  49 
  50   // Initialize the soft ref timestamp clock.
  51   _soft_ref_timestamp_clock = now;
  52   // Also update the soft ref clock in j.l.r.SoftReference
  53   java_lang_ref_SoftReference::set_clock(_soft_ref_timestamp_clock);
  54 
  55   _always_clear_soft_ref_policy = new AlwaysClearPolicy();
  56   _default_soft_ref_policy      = new COMPILER2_PRESENT(LRUMaxHeapPolicy())
  57                                       NOT_COMPILER2(LRUCurrentHeapPolicy());
  58   if (_always_clear_soft_ref_policy == NULL || _default_soft_ref_policy == NULL) {
  59     vm_exit_during_initialization("Could not allocate reference policy object");
  60   }
  61   guarantee(RefDiscoveryPolicy == ReferenceBasedDiscovery ||
  62             RefDiscoveryPolicy == ReferentBasedDiscovery,
  63             "Unrecongnized RefDiscoveryPolicy");
  64   _pending_list_uses_discovered_field = JDK_Version::current().pending_list_uses_discovered_field();
  65 }
  66 
  67 void ReferenceProcessor::enable_discovery(bool verify_disabled, bool check_no_refs) {
  68 #ifdef ASSERT
  69   // Verify that we're not currently discovering refs
  70   assert(!verify_disabled || !_discovering_refs, "nested call?");
  71 
  72   if (check_no_refs) {
  73     // Verify that the discovered lists are empty
  74     verify_no_references_recorded();
  75   }
  76 #endif // ASSERT
  77 
  78   // Someone could have modified the value of the static
  79   // field in the j.l.r.SoftReference class that holds the
  80   // soft reference timestamp clock using reflection or
  81   // Unsafe between GCs. Unconditionally update the static
  82   // field in ReferenceProcessor here so that we use the new
  83   // value during reference discovery.
  84 
  85   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
  86   _discovering_refs = true;
  87 }
  88 
  89 ReferenceProcessor::ReferenceProcessor(MemRegion span,
  90                                        bool      mt_processing,
  91                                        int       mt_processing_degree,
  92                                        bool      mt_discovery,
  93                                        int       mt_discovery_degree,
  94                                        bool      atomic_discovery,
  95                                        BoolObjectClosure* is_alive_non_header,
  96                                        bool      discovered_list_needs_barrier)  :
  97   _discovering_refs(false),
  98   _enqueuing_is_done(false),
  99   _is_alive_non_header(is_alive_non_header),
 100   _discovered_list_needs_barrier(discovered_list_needs_barrier),
 101   _bs(NULL),
 102   _processing_is_mt(mt_processing),
 103   _next_id(0)
 104 {
 105   _span = span;
 106   _discovery_is_atomic = atomic_discovery;
 107   _discovery_is_mt     = mt_discovery;
 108   _num_q               = MAX2(1, mt_processing_degree);
 109   _max_num_q           = MAX2(_num_q, mt_discovery_degree);
 110   _discovered_refs     = NEW_C_HEAP_ARRAY(DiscoveredList,
 111                                           _max_num_q * number_of_subclasses_of_ref());
 112   if (_discovered_refs == NULL) {
 113     vm_exit_during_initialization("Could not allocated RefProc Array");
 114   }
 115   _discoveredSoftRefs    = &_discovered_refs[0];
 116   _discoveredWeakRefs    = &_discoveredSoftRefs[_max_num_q];
 117   _discoveredFinalRefs   = &_discoveredWeakRefs[_max_num_q];
 118   _discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_q];
 119 
 120   // Initialize all entries to NULL
 121   for (int i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 122     _discovered_refs[i].set_head(NULL);
 123     _discovered_refs[i].set_length(0);
 124   }
 125 
 126   // If we do barriers, cache a copy of the barrier set.
 127   if (discovered_list_needs_barrier) {
 128     _bs = Universe::heap()->barrier_set();
 129   }
 130   setup_policy(false /* default soft ref policy */);
 131 }
 132 
 133 #ifndef PRODUCT
 134 void ReferenceProcessor::verify_no_references_recorded() {
 135   guarantee(!_discovering_refs, "Discovering refs?");
 136   for (int i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 137     guarantee(_discovered_refs[i].is_empty(),
 138               "Found non-empty discovered list");
 139   }
 140 }
 141 #endif
 142 
 143 void ReferenceProcessor::weak_oops_do(OopClosure* f) {
 144   for (int i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 145     if (UseCompressedOops) {
 146       f->do_oop((narrowOop*)_discovered_refs[i].adr_head());
 147     } else {
 148       f->do_oop((oop*)_discovered_refs[i].adr_head());
 149     }
 150   }
 151 }
 152 
 153 void ReferenceProcessor::update_soft_ref_master_clock() {
 154   // Update (advance) the soft ref master clock field. This must be done
 155   // after processing the soft ref list.
 156 
 157   // We need a montonically increasing time in ms but os::javaTimeMillis()
 158   // does not guarantee montonicity.
 159   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
 160   jlong soft_ref_clock = java_lang_ref_SoftReference::clock();
 161   assert(soft_ref_clock == _soft_ref_timestamp_clock, "soft ref clocks out of sync");
 162 
 163   NOT_PRODUCT(
 164   if (now < _soft_ref_timestamp_clock) {
 165     warning("time warp: "INT64_FORMAT" to "INT64_FORMAT,
 166             _soft_ref_timestamp_clock, now);
 167   }
 168   )
 169   // In product mode, protect ourselves from system time being adjusted
 170   // externally and going backward; see note in the implementation of
 171   // GenCollectedHeap::time_since_last_gc() for the right way to fix
 172   // this uniformly throughout the VM; see bug-id 4741166. XXX
 173   if (now > _soft_ref_timestamp_clock) {
 174     _soft_ref_timestamp_clock = now;
 175     java_lang_ref_SoftReference::set_clock(now);
 176   }
 177   // Else leave clock stalled at its old value until time progresses
 178   // past clock value.
 179 }
 180 
 181 void ReferenceProcessor::process_discovered_references(
 182   BoolObjectClosure*           is_alive,
 183   OopClosure*                  keep_alive,
 184   VoidClosure*                 complete_gc,
 185   AbstractRefProcTaskExecutor* task_executor) {
 186   NOT_PRODUCT(verify_ok_to_handle_reflists());
 187 
 188   assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
 189   // Stop treating discovered references specially.
 190   disable_discovery();
 191 
 192   // If discovery was concurrent, someone could have modified
 193   // the value of the static field in the j.l.r.SoftReference
 194   // class that holds the soft reference timestamp clock using
 195   // reflection or Unsafe between when discovery was enabled and
 196   // now. Unconditionally update the static field in ReferenceProcessor
 197   // here so that we use the new value during processing of the
 198   // discovered soft refs.
 199 
 200   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
 201 
 202   bool trace_time = PrintGCDetails && PrintReferenceGC;
 203   // Soft references
 204   {
 205     TraceTime tt("SoftReference", trace_time, false, gclog_or_tty);
 206     process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
 207                                is_alive, keep_alive, complete_gc, task_executor);
 208   }
 209 
 210   update_soft_ref_master_clock();
 211 
 212   // Weak references
 213   {
 214     TraceTime tt("WeakReference", trace_time, false, gclog_or_tty);
 215     process_discovered_reflist(_discoveredWeakRefs, NULL, true,
 216                                is_alive, keep_alive, complete_gc, task_executor);
 217   }
 218 
 219   // Final references
 220   {
 221     TraceTime tt("FinalReference", trace_time, false, gclog_or_tty);
 222     process_discovered_reflist(_discoveredFinalRefs, NULL, false,
 223                                is_alive, keep_alive, complete_gc, task_executor);
 224   }
 225 
 226   // Phantom references
 227   {
 228     TraceTime tt("PhantomReference", trace_time, false, gclog_or_tty);
 229     process_discovered_reflist(_discoveredPhantomRefs, NULL, false,
 230                                is_alive, keep_alive, complete_gc, task_executor);
 231   }
 232 
 233   // Weak global JNI references. It would make more sense (semantically) to
 234   // traverse these simultaneously with the regular weak references above, but
 235   // that is not how the JDK1.2 specification is. See #4126360. Native code can
 236   // thus use JNI weak references to circumvent the phantom references and
 237   // resurrect a "post-mortem" object.
 238   {
 239     TraceTime tt("JNI Weak Reference", trace_time, false, gclog_or_tty);
 240     if (task_executor != NULL) {
 241       task_executor->set_single_threaded_mode();
 242     }
 243     process_phaseJNI(is_alive, keep_alive, complete_gc);
 244   }
 245 }
 246 
 247 #ifndef PRODUCT
 248 // Calculate the number of jni handles.
 249 uint ReferenceProcessor::count_jni_refs() {
 250   class AlwaysAliveClosure: public BoolObjectClosure {
 251   public:
 252     virtual bool do_object_b(oop obj) { return true; }
 253     virtual void do_object(oop obj) { assert(false, "Don't call"); }
 254   };
 255 
 256   class CountHandleClosure: public OopClosure {
 257   private:
 258     int _count;
 259   public:
 260     CountHandleClosure(): _count(0) {}
 261     void do_oop(oop* unused)       { _count++; }
 262     void do_oop(narrowOop* unused) { ShouldNotReachHere(); }
 263     int count() { return _count; }
 264   };
 265   CountHandleClosure global_handle_count;
 266   AlwaysAliveClosure always_alive;
 267   JNIHandles::weak_oops_do(&always_alive, &global_handle_count);
 268   return global_handle_count.count();
 269 }
 270 #endif
 271 
 272 void ReferenceProcessor::process_phaseJNI(BoolObjectClosure* is_alive,
 273                                           OopClosure*        keep_alive,
 274                                           VoidClosure*       complete_gc) {
 275 #ifndef PRODUCT
 276   if (PrintGCDetails && PrintReferenceGC) {
 277     unsigned int count = count_jni_refs();
 278     gclog_or_tty->print(", %u refs", count);
 279   }
 280 #endif
 281   JNIHandles::weak_oops_do(is_alive, keep_alive);
 282   complete_gc->do_void();
 283 }
 284 
 285 
 286 template <class T>
 287 bool enqueue_discovered_ref_helper(ReferenceProcessor* ref,
 288                                    AbstractRefProcTaskExecutor* task_executor) {
 289 
 290   // Remember old value of pending references list
 291   T* pending_list_addr = (T*)java_lang_ref_Reference::pending_list_addr();
 292   T old_pending_list_value = *pending_list_addr;
 293 
 294   // Enqueue references that are not made active again, and
 295   // clear the decks for the next collection (cycle).
 296   ref->enqueue_discovered_reflists((HeapWord*)pending_list_addr, task_executor);
 297   // Do the oop-check on pending_list_addr missed in
 298   // enqueue_discovered_reflist. We should probably
 299   // do a raw oop_check so that future such idempotent
 300   // oop_stores relying on the oop-check side-effect
 301   // may be elided automatically and safely without
 302   // affecting correctness.
 303   oop_store(pending_list_addr, oopDesc::load_decode_heap_oop(pending_list_addr));
 304 
 305   // Stop treating discovered references specially.
 306   ref->disable_discovery();
 307 
 308   // Return true if new pending references were added
 309   return old_pending_list_value != *pending_list_addr;
 310 }
 311 
 312 bool ReferenceProcessor::enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor) {
 313   NOT_PRODUCT(verify_ok_to_handle_reflists());
 314   if (UseCompressedOops) {
 315     return enqueue_discovered_ref_helper<narrowOop>(this, task_executor);
 316   } else {
 317     return enqueue_discovered_ref_helper<oop>(this, task_executor);
 318   }
 319 }
 320 
 321 void ReferenceProcessor::enqueue_discovered_reflist(DiscoveredList& refs_list,
 322                                                     HeapWord* pending_list_addr) {
 323   // Given a list of refs linked through the "discovered" field
 324   // (java.lang.ref.Reference.discovered), self-loop their "next" field
 325   // thus distinguishing them from active References, then
 326   // prepend them to the pending list.
 327   // BKWRD COMPATIBILITY NOTE: For older JDKs (prior to the fix for 4956777),
 328   // the "next" field is used to chain the pending list, not the discovered
 329   // field.
 330 
 331   if (TraceReferenceGC && PrintGCDetails) {
 332     gclog_or_tty->print_cr("ReferenceProcessor::enqueue_discovered_reflist list "
 333                            INTPTR_FORMAT, (address)refs_list.head());
 334   }
 335 
 336   oop obj = NULL;
 337   oop next_d = refs_list.head();
 338   if (pending_list_uses_discovered_field()) { // New behaviour
 339     // Walk down the list, self-looping the next field
 340     // so that the References are not considered active.
 341     while (obj != next_d) {
 342       obj = next_d;
 343       assert(obj->is_instanceRef(), "should be reference object");
 344       next_d = java_lang_ref_Reference::discovered(obj);
 345       if (TraceReferenceGC && PrintGCDetails) {
 346         gclog_or_tty->print_cr("        obj " INTPTR_FORMAT "/next_d " INTPTR_FORMAT,
 347                                obj, next_d);
 348       }
 349       assert(java_lang_ref_Reference::next(obj) == NULL,
 350              "Reference not active; should not be discovered");
 351       // Self-loop next, so as to make Ref not active.
 352       java_lang_ref_Reference::set_next(obj, obj);
 353       if (next_d == obj) {  // obj is last
 354         // Swap refs_list into pendling_list_addr and
 355         // set obj's discovered to what we read from pending_list_addr.
 356         oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr);
 357         // Need oop_check on pending_list_addr above;
 358         // see special oop-check code at the end of
 359         // enqueue_discovered_reflists() further below.
 360         java_lang_ref_Reference::set_discovered(obj, old); // old may be NULL
 361       }
 362     }
 363   } else { // Old behaviour
 364     // Walk down the list, copying the discovered field into
 365     // the next field and clearing the discovered field.
 366     while (obj != next_d) {
 367       obj = next_d;
 368       assert(obj->is_instanceRef(), "should be reference object");
 369       next_d = java_lang_ref_Reference::discovered(obj);
 370       if (TraceReferenceGC && PrintGCDetails) {
 371         gclog_or_tty->print_cr("        obj " INTPTR_FORMAT "/next_d " INTPTR_FORMAT,
 372                                obj, next_d);
 373       }
 374       assert(java_lang_ref_Reference::next(obj) == NULL,
 375              "The reference should not be enqueued");
 376       if (next_d == obj) {  // obj is last
 377         // Swap refs_list into pendling_list_addr and
 378         // set obj's next to what we read from pending_list_addr.
 379         oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr);
 380         // Need oop_check on pending_list_addr above;
 381         // see special oop-check code at the end of
 382         // enqueue_discovered_reflists() further below.
 383         if (old == NULL) {
 384           // obj should be made to point to itself, since
 385           // pending list was empty.
 386           java_lang_ref_Reference::set_next(obj, obj);
 387         } else {
 388           java_lang_ref_Reference::set_next(obj, old);
 389         }
 390       } else {
 391         java_lang_ref_Reference::set_next(obj, next_d);
 392       }
 393       java_lang_ref_Reference::set_discovered(obj, (oop) NULL);
 394     }
 395   }
 396 }
 397 
 398 // Parallel enqueue task
 399 class RefProcEnqueueTask: public AbstractRefProcTaskExecutor::EnqueueTask {
 400 public:
 401   RefProcEnqueueTask(ReferenceProcessor& ref_processor,
 402                      DiscoveredList      discovered_refs[],
 403                      HeapWord*           pending_list_addr,
 404                      int                 n_queues)
 405     : EnqueueTask(ref_processor, discovered_refs,
 406                   pending_list_addr, n_queues)
 407   { }
 408 
 409   virtual void work(unsigned int work_id) {
 410     assert(work_id < (unsigned int)_ref_processor.max_num_q(), "Index out-of-bounds");
 411     // Simplest first cut: static partitioning.
 412     int index = work_id;
 413     // The increment on "index" must correspond to the maximum number of queues
 414     // (n_queues) with which that ReferenceProcessor was created.  That
 415     // is because of the "clever" way the discovered references lists were
 416     // allocated and are indexed into.
 417     assert(_n_queues == (int) _ref_processor.max_num_q(), "Different number not expected");
 418     for (int j = 0;
 419          j < ReferenceProcessor::number_of_subclasses_of_ref();
 420          j++, index += _n_queues) {
 421       _ref_processor.enqueue_discovered_reflist(
 422         _refs_lists[index], _pending_list_addr);
 423       _refs_lists[index].set_head(NULL);
 424       _refs_lists[index].set_length(0);
 425     }
 426   }
 427 };
 428 
 429 // Enqueue references that are not made active again
 430 void ReferenceProcessor::enqueue_discovered_reflists(HeapWord* pending_list_addr,
 431   AbstractRefProcTaskExecutor* task_executor) {
 432   if (_processing_is_mt && task_executor != NULL) {
 433     // Parallel code
 434     RefProcEnqueueTask tsk(*this, _discovered_refs,
 435                            pending_list_addr, _max_num_q);
 436     task_executor->execute(tsk);
 437   } else {
 438     // Serial code: call the parent class's implementation
 439     for (int i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 440       enqueue_discovered_reflist(_discovered_refs[i], pending_list_addr);
 441       _discovered_refs[i].set_head(NULL);
 442       _discovered_refs[i].set_length(0);
 443     }
 444   }
 445 }
 446 
 447 void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
 448   _discovered_addr = java_lang_ref_Reference::discovered_addr(_ref);
 449   oop discovered = java_lang_ref_Reference::discovered(_ref);
 450   assert(_discovered_addr && discovered->is_oop_or_null(),
 451          "discovered field is bad");
 452   _next = discovered;
 453   _referent_addr = java_lang_ref_Reference::referent_addr(_ref);
 454   _referent = java_lang_ref_Reference::referent(_ref);
 455   assert(Universe::heap()->is_in_reserved_or_null(_referent),
 456          "Wrong oop found in java.lang.Reference object");
 457   assert(allow_null_referent ?
 458              _referent->is_oop_or_null()
 459            : _referent->is_oop(),
 460          "bad referent");
 461 }
 462 
 463 void DiscoveredListIterator::remove() {
 464   assert(_ref->is_oop(), "Dropping a bad reference");
 465   oop_store_raw(_discovered_addr, NULL);
 466 
 467   // First _prev_next ref actually points into DiscoveredList (gross).
 468   oop new_next;
 469   if (_next == _ref) {
 470     // At the end of the list, we should make _prev point to itself.
 471     // If _ref is the first ref, then _prev_next will be in the DiscoveredList,
 472     // and _prev will be NULL.
 473     new_next = _prev;
 474   } else {
 475     new_next = _next;
 476   }
 477 
 478   if (UseCompressedOops) {
 479     // Remove Reference object from list.
 480     oopDesc::encode_store_heap_oop((narrowOop*)_prev_next, new_next);
 481   } else {
 482     // Remove Reference object from list.
 483     oopDesc::store_heap_oop((oop*)_prev_next, new_next);
 484   }
 485   NOT_PRODUCT(_removed++);
 486   _refs_list.dec_length(1);
 487 }
 488 
 489 // Make the Reference object active again.
 490 void DiscoveredListIterator::make_active() {
 491   // For G1 we don't want to use set_next - it
 492   // will dirty the card for the next field of
 493   // the reference object and will fail
 494   // CT verification.
 495   if (UseG1GC) {
 496     BarrierSet* bs = oopDesc::bs();
 497     HeapWord* next_addr = java_lang_ref_Reference::next_addr(_ref);
 498 
 499     if (UseCompressedOops) {
 500       bs->write_ref_field_pre((narrowOop*)next_addr, NULL);
 501     } else {
 502       bs->write_ref_field_pre((oop*)next_addr, NULL);
 503     }
 504     java_lang_ref_Reference::set_next_raw(_ref, NULL);
 505   } else {
 506     java_lang_ref_Reference::set_next(_ref, NULL);
 507   }
 508 }
 509 
 510 void DiscoveredListIterator::clear_referent() {
 511   oop_store_raw(_referent_addr, NULL);
 512 }
 513 
 514 // NOTE: process_phase*() are largely similar, and at a high level
 515 // merely iterate over the extant list applying a predicate to
 516 // each of its elements and possibly removing that element from the
 517 // list and applying some further closures to that element.
 518 // We should consider the possibility of replacing these
 519 // process_phase*() methods by abstracting them into
 520 // a single general iterator invocation that receives appropriate
 521 // closures that accomplish this work.
 522 
 523 // (SoftReferences only) Traverse the list and remove any SoftReferences whose
 524 // referents are not alive, but that should be kept alive for policy reasons.
 525 // Keep alive the transitive closure of all such referents.
 526 void
 527 ReferenceProcessor::process_phase1(DiscoveredList&    refs_list,
 528                                    ReferencePolicy*   policy,
 529                                    BoolObjectClosure* is_alive,
 530                                    OopClosure*        keep_alive,
 531                                    VoidClosure*       complete_gc) {
 532   assert(policy != NULL, "Must have a non-NULL policy");
 533   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 534   // Decide which softly reachable refs should be kept alive.
 535   while (iter.has_next()) {
 536     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
 537     bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
 538     if (referent_is_dead &&
 539         !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
 540       if (TraceReferenceGC) {
 541         gclog_or_tty->print_cr("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
 542                                iter.obj(), iter.obj()->blueprint()->internal_name());
 543       }
 544       // Remove Reference object from list
 545       iter.remove();
 546       // Make the Reference object active again
 547       iter.make_active();
 548       // keep the referent around
 549       iter.make_referent_alive();
 550       iter.move_to_next();
 551     } else {
 552       iter.next();
 553     }
 554   }
 555   // Close the reachable set
 556   complete_gc->do_void();
 557   NOT_PRODUCT(
 558     if (PrintGCDetails && TraceReferenceGC) {
 559       gclog_or_tty->print_cr(" Dropped %d dead Refs out of %d "
 560         "discovered Refs by policy, from list " INTPTR_FORMAT,
 561         iter.removed(), iter.processed(), (address)refs_list.head());
 562     }
 563   )
 564 }
 565 
 566 // Traverse the list and remove any Refs that are not active, or
 567 // whose referents are either alive or NULL.
 568 void
 569 ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
 570                              BoolObjectClosure* is_alive,
 571                              OopClosure*        keep_alive) {
 572   assert(discovery_is_atomic(), "Error");
 573   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 574   while (iter.has_next()) {
 575     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 576     DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
 577     assert(next == NULL, "Should not discover inactive Reference");
 578     if (iter.is_referent_alive()) {
 579       if (TraceReferenceGC) {
 580         gclog_or_tty->print_cr("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
 581                                iter.obj(), iter.obj()->blueprint()->internal_name());
 582       }
 583       // The referent is reachable after all.
 584       // Remove Reference object from list.
 585       iter.remove();
 586       // Update the referent pointer as necessary: Note that this
 587       // should not entail any recursive marking because the
 588       // referent must already have been traversed.
 589       iter.make_referent_alive();
 590       iter.move_to_next();
 591     } else {
 592       iter.next();
 593     }
 594   }
 595   NOT_PRODUCT(
 596     if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
 597       gclog_or_tty->print_cr(" Dropped %d active Refs out of %d "
 598         "Refs in discovered list " INTPTR_FORMAT,
 599         iter.removed(), iter.processed(), (address)refs_list.head());
 600     }
 601   )
 602 }
 603 
 604 void
 605 ReferenceProcessor::pp2_work_concurrent_discovery(DiscoveredList&    refs_list,
 606                                                   BoolObjectClosure* is_alive,
 607                                                   OopClosure*        keep_alive,
 608                                                   VoidClosure*       complete_gc) {
 609   assert(!discovery_is_atomic(), "Error");
 610   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 611   while (iter.has_next()) {
 612     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
 613     HeapWord* next_addr = java_lang_ref_Reference::next_addr(iter.obj());
 614     oop next = java_lang_ref_Reference::next(iter.obj());
 615     if ((iter.referent() == NULL || iter.is_referent_alive() ||
 616          next != NULL)) {
 617       assert(next->is_oop_or_null(), "bad next field");
 618       // Remove Reference object from list
 619       iter.remove();
 620       // Trace the cohorts
 621       iter.make_referent_alive();
 622       if (UseCompressedOops) {
 623         keep_alive->do_oop((narrowOop*)next_addr);
 624       } else {
 625         keep_alive->do_oop((oop*)next_addr);
 626       }
 627       iter.move_to_next();
 628     } else {
 629       iter.next();
 630     }
 631   }
 632   // Now close the newly reachable set
 633   complete_gc->do_void();
 634   NOT_PRODUCT(
 635     if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
 636       gclog_or_tty->print_cr(" Dropped %d active Refs out of %d "
 637         "Refs in discovered list " INTPTR_FORMAT,
 638         iter.removed(), iter.processed(), (address)refs_list.head());
 639     }
 640   )
 641 }
 642 
 643 // Traverse the list and process the referents, by either
 644 // clearing them or keeping them (and their reachable
 645 // closure) alive.
 646 void
 647 ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
 648                                    bool               clear_referent,
 649                                    BoolObjectClosure* is_alive,
 650                                    OopClosure*        keep_alive,
 651                                    VoidClosure*       complete_gc) {
 652   ResourceMark rm;
 653   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 654   while (iter.has_next()) {
 655     iter.update_discovered();
 656     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 657     if (clear_referent) {
 658       // NULL out referent pointer
 659       iter.clear_referent();
 660     } else {
 661       // keep the referent around
 662       iter.make_referent_alive();
 663     }
 664     if (TraceReferenceGC) {
 665       gclog_or_tty->print_cr("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
 666                              clear_referent ? "cleared " : "",
 667                              iter.obj(), iter.obj()->blueprint()->internal_name());
 668     }
 669     assert(iter.obj()->is_oop(UseConcMarkSweepGC), "Adding a bad reference");
 670     iter.next();
 671   }
 672   // Remember to update the next pointer of the last ref.
 673   iter.update_discovered();
 674   // Close the reachable set
 675   complete_gc->do_void();
 676 }
 677 
 678 void
 679 ReferenceProcessor::clear_discovered_references(DiscoveredList& refs_list) {
 680   oop obj = NULL;
 681   oop next = refs_list.head();
 682   while (next != obj) {
 683     obj = next;
 684     next = java_lang_ref_Reference::discovered(obj);
 685     java_lang_ref_Reference::set_discovered_raw(obj, NULL);
 686   }
 687   refs_list.set_head(NULL);
 688   refs_list.set_length(0);
 689 }
 690 
 691 void
 692 ReferenceProcessor::abandon_partial_discovered_list(DiscoveredList& refs_list) {
 693   clear_discovered_references(refs_list);
 694 }
 695 
 696 void ReferenceProcessor::abandon_partial_discovery() {
 697   // loop over the lists
 698   for (int i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 699     if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
 700       gclog_or_tty->print_cr("\nAbandoning %s discovered list", list_name(i));
 701     }
 702     abandon_partial_discovered_list(_discovered_refs[i]);
 703   }
 704 }
 705 
 706 class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
 707 public:
 708   RefProcPhase1Task(ReferenceProcessor& ref_processor,
 709                     DiscoveredList      refs_lists[],
 710                     ReferencePolicy*    policy,
 711                     bool                marks_oops_alive)
 712     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
 713       _policy(policy)
 714   { }
 715   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 716                     OopClosure& keep_alive,
 717                     VoidClosure& complete_gc)
 718   {
 719     Thread* thr = Thread::current();
 720     int refs_list_index = ((WorkerThread*)thr)->id();
 721     _ref_processor.process_phase1(_refs_lists[refs_list_index], _policy,
 722                                   &is_alive, &keep_alive, &complete_gc);
 723   }
 724 private:
 725   ReferencePolicy* _policy;
 726 };
 727 
 728 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
 729 public:
 730   RefProcPhase2Task(ReferenceProcessor& ref_processor,
 731                     DiscoveredList      refs_lists[],
 732                     bool                marks_oops_alive)
 733     : ProcessTask(ref_processor, refs_lists, marks_oops_alive)
 734   { }
 735   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 736                     OopClosure& keep_alive,
 737                     VoidClosure& complete_gc)
 738   {
 739     _ref_processor.process_phase2(_refs_lists[i],
 740                                   &is_alive, &keep_alive, &complete_gc);
 741   }
 742 };
 743 
 744 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
 745 public:
 746   RefProcPhase3Task(ReferenceProcessor& ref_processor,
 747                     DiscoveredList      refs_lists[],
 748                     bool                clear_referent,
 749                     bool                marks_oops_alive)
 750     : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
 751       _clear_referent(clear_referent)
 752   { }
 753   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 754                     OopClosure& keep_alive,
 755                     VoidClosure& complete_gc)
 756   {
 757     // Don't use "refs_list_index" calculated in this way because
 758     // balance_queues() has moved the Ref's into the first n queues.
 759     // Thread* thr = Thread::current();
 760     // int refs_list_index = ((WorkerThread*)thr)->id();
 761     // _ref_processor.process_phase3(_refs_lists[refs_list_index], _clear_referent,
 762     _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
 763                                   &is_alive, &keep_alive, &complete_gc);
 764   }
 765 private:
 766   bool _clear_referent;
 767 };
 768 
 769 void ReferenceProcessor::set_discovered(oop ref, oop value) {
 770   if (_discovered_list_needs_barrier) {
 771     java_lang_ref_Reference::set_discovered(ref, value);
 772   } else {
 773     java_lang_ref_Reference::set_discovered_raw(ref, value);
 774   }
 775 }
 776 
 777 // Balances reference queues.
 778 // Move entries from all queues[0, 1, ..., _max_num_q-1] to
 779 // queues[0, 1, ..., _num_q-1] because only the first _num_q
 780 // corresponding to the active workers will be processed.
 781 void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[])
 782 {
 783   // calculate total length
 784   size_t total_refs = 0;
 785   if (TraceReferenceGC && PrintGCDetails) {
 786     gclog_or_tty->print_cr("\nBalance ref_lists ");
 787   }
 788 
 789   for (int i = 0; i < _max_num_q; ++i) {
 790     total_refs += ref_lists[i].length();
 791     if (TraceReferenceGC && PrintGCDetails) {
 792       gclog_or_tty->print("%d ", ref_lists[i].length());
 793     }
 794   }
 795   if (TraceReferenceGC && PrintGCDetails) {
 796     gclog_or_tty->print_cr(" = %d", total_refs);
 797   }
 798   size_t avg_refs = total_refs / _num_q + 1;
 799   int to_idx = 0;
 800   for (int from_idx = 0; from_idx < _max_num_q; from_idx++) {
 801     bool move_all = false;
 802     if (from_idx >= _num_q) {
 803       move_all = ref_lists[from_idx].length() > 0;
 804     }
 805     while ((ref_lists[from_idx].length() > avg_refs) ||
 806            move_all) {
 807       assert(to_idx < _num_q, "Sanity Check!");
 808       if (ref_lists[to_idx].length() < avg_refs) {
 809         // move superfluous refs
 810         size_t refs_to_move;
 811         // Move all the Ref's if the from queue will not be processed.
 812         if (move_all) {
 813           refs_to_move = MIN2(ref_lists[from_idx].length(),
 814                               avg_refs - ref_lists[to_idx].length());
 815         } else {
 816           refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs,
 817                               avg_refs - ref_lists[to_idx].length());
 818         }
 819 
 820         assert(refs_to_move > 0, "otherwise the code below will fail");
 821 
 822         oop move_head = ref_lists[from_idx].head();
 823         oop move_tail = move_head;
 824         oop new_head  = move_head;
 825         // find an element to split the list on
 826         for (size_t j = 0; j < refs_to_move; ++j) {
 827           move_tail = new_head;
 828           new_head = java_lang_ref_Reference::discovered(new_head);
 829         }
 830 
 831         // Add the chain to the to list.
 832         if (ref_lists[to_idx].head() == NULL) {
 833           // to list is empty. Make a loop at the end.
 834           set_discovered(move_tail, move_tail);
 835         } else {
 836           set_discovered(move_tail, ref_lists[to_idx].head());
 837         }
 838         ref_lists[to_idx].set_head(move_head);
 839         ref_lists[to_idx].inc_length(refs_to_move);
 840 
 841         // Remove the chain from the from list.
 842         if (move_tail == new_head) {
 843           // We found the end of the from list.
 844           ref_lists[from_idx].set_head(NULL);
 845         } else {
 846           ref_lists[from_idx].set_head(new_head);
 847         }
 848         ref_lists[from_idx].dec_length(refs_to_move);
 849         if (ref_lists[from_idx].length() == 0) {
 850           break;
 851         }
 852       } else {
 853         to_idx = (to_idx + 1) % _num_q;
 854       }
 855     }
 856   }
 857 #ifdef ASSERT
 858   size_t balanced_total_refs = 0;
 859   for (int i = 0; i < _max_num_q; ++i) {
 860     balanced_total_refs += ref_lists[i].length();
 861     if (TraceReferenceGC && PrintGCDetails) {
 862       gclog_or_tty->print("%d ", ref_lists[i].length());
 863     }
 864   }
 865   if (TraceReferenceGC && PrintGCDetails) {
 866     gclog_or_tty->print_cr(" = %d", balanced_total_refs);
 867     gclog_or_tty->flush();
 868   }
 869   assert(total_refs == balanced_total_refs, "Balancing was incomplete");
 870 #endif
 871 }
 872 
 873 void ReferenceProcessor::balance_all_queues() {
 874   balance_queues(_discoveredSoftRefs);
 875   balance_queues(_discoveredWeakRefs);
 876   balance_queues(_discoveredFinalRefs);
 877   balance_queues(_discoveredPhantomRefs);
 878 }
 879 
 880 void
 881 ReferenceProcessor::process_discovered_reflist(
 882   DiscoveredList               refs_lists[],
 883   ReferencePolicy*             policy,
 884   bool                         clear_referent,
 885   BoolObjectClosure*           is_alive,
 886   OopClosure*                  keep_alive,
 887   VoidClosure*                 complete_gc,
 888   AbstractRefProcTaskExecutor* task_executor)
 889 {
 890   bool mt_processing = task_executor != NULL && _processing_is_mt;
 891   // If discovery used MT and a dynamic number of GC threads, then
 892   // the queues must be balanced for correctness if fewer than the
 893   // maximum number of queues were used.  The number of queue used
 894   // during discovery may be different than the number to be used
 895   // for processing so don't depend of _num_q < _max_num_q as part
 896   // of the test.
 897   bool must_balance = _discovery_is_mt;
 898 
 899   if ((mt_processing && ParallelRefProcBalancingEnabled) ||
 900       must_balance) {
 901     balance_queues(refs_lists);
 902   }
 903   if (PrintReferenceGC && PrintGCDetails) {
 904     size_t total = 0;
 905     for (int i = 0; i < _max_num_q; ++i) {
 906       total += refs_lists[i].length();
 907     }
 908     gclog_or_tty->print(", %u refs", total);
 909   }
 910 
 911   // Phase 1 (soft refs only):
 912   // . Traverse the list and remove any SoftReferences whose
 913   //   referents are not alive, but that should be kept alive for
 914   //   policy reasons. Keep alive the transitive closure of all
 915   //   such referents.
 916   if (policy != NULL) {
 917     if (mt_processing) {
 918       RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/);
 919       task_executor->execute(phase1);
 920     } else {
 921       for (int i = 0; i < _max_num_q; i++) {
 922         process_phase1(refs_lists[i], policy,
 923                        is_alive, keep_alive, complete_gc);
 924       }
 925     }
 926   } else { // policy == NULL
 927     assert(refs_lists != _discoveredSoftRefs,
 928            "Policy must be specified for soft references.");
 929   }
 930 
 931   // Phase 2:
 932   // . Traverse the list and remove any refs whose referents are alive.
 933   if (mt_processing) {
 934     RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/);
 935     task_executor->execute(phase2);
 936   } else {
 937     for (int i = 0; i < _max_num_q; i++) {
 938       process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
 939     }
 940   }
 941 
 942   // Phase 3:
 943   // . Traverse the list and process referents as appropriate.
 944   if (mt_processing) {
 945     RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/);
 946     task_executor->execute(phase3);
 947   } else {
 948     for (int i = 0; i < _max_num_q; i++) {
 949       process_phase3(refs_lists[i], clear_referent,
 950                      is_alive, keep_alive, complete_gc);
 951     }
 952   }
 953 }
 954 
 955 void ReferenceProcessor::clean_up_discovered_references() {
 956   // loop over the lists
 957   for (int i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
 958     if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
 959       gclog_or_tty->print_cr(
 960         "\nScrubbing %s discovered list of Null referents",
 961         list_name(i));
 962     }
 963     clean_up_discovered_reflist(_discovered_refs[i]);
 964   }
 965 }
 966 
 967 void ReferenceProcessor::clean_up_discovered_reflist(DiscoveredList& refs_list) {
 968   assert(!discovery_is_atomic(), "Else why call this method?");
 969   DiscoveredListIterator iter(refs_list, NULL, NULL);
 970   while (iter.has_next()) {
 971     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
 972     oop next = java_lang_ref_Reference::next(iter.obj());
 973     assert(next->is_oop_or_null(), "bad next field");
 974     // If referent has been cleared or Reference is not active,
 975     // drop it.
 976     if (iter.referent() == NULL || next != NULL) {
 977       debug_only(
 978         if (PrintGCDetails && TraceReferenceGC) {
 979           gclog_or_tty->print_cr("clean_up_discovered_list: Dropping Reference: "
 980             INTPTR_FORMAT " with next field: " INTPTR_FORMAT
 981             " and referent: " INTPTR_FORMAT,
 982             iter.obj(), next, iter.referent());
 983         }
 984       )
 985       // Remove Reference object from list
 986       iter.remove();
 987       iter.move_to_next();
 988     } else {
 989       iter.next();
 990     }
 991   }
 992   NOT_PRODUCT(
 993     if (PrintGCDetails && TraceReferenceGC) {
 994       gclog_or_tty->print(
 995         " Removed %d Refs with NULL referents out of %d discovered Refs",
 996         iter.removed(), iter.processed());
 997     }
 998   )
 999 }
1000 
1001 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
1002   int id = 0;
1003   // Determine the queue index to use for this object.
1004   if (_discovery_is_mt) {
1005     // During a multi-threaded discovery phase,
1006     // each thread saves to its "own" list.
1007     Thread* thr = Thread::current();
1008     id = thr->as_Worker_thread()->id();
1009   } else {
1010     // single-threaded discovery, we save in round-robin
1011     // fashion to each of the lists.
1012     if (_processing_is_mt) {
1013       id = next_id();
1014     }
1015   }
1016   assert(0 <= id && id < _max_num_q, "Id is out-of-bounds (call Freud?)");
1017 
1018   // Get the discovered queue to which we will add
1019   DiscoveredList* list = NULL;
1020   switch (rt) {
1021     case REF_OTHER:
1022       // Unknown reference type, no special treatment
1023       break;
1024     case REF_SOFT:
1025       list = &_discoveredSoftRefs[id];
1026       break;
1027     case REF_WEAK:
1028       list = &_discoveredWeakRefs[id];
1029       break;
1030     case REF_FINAL:
1031       list = &_discoveredFinalRefs[id];
1032       break;
1033     case REF_PHANTOM:
1034       list = &_discoveredPhantomRefs[id];
1035       break;
1036     case REF_NONE:
1037       // we should not reach here if we are an instanceRefKlass
1038     default:
1039       ShouldNotReachHere();
1040   }
1041   if (TraceReferenceGC && PrintGCDetails) {
1042     gclog_or_tty->print_cr("Thread %d gets list " INTPTR_FORMAT, id, list);
1043   }
1044   return list;
1045 }
1046 
1047 inline void
1048 ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list,
1049                                               oop             obj,
1050                                               HeapWord*       discovered_addr) {
1051   assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller");
1052   // First we must make sure this object is only enqueued once. CAS in a non null
1053   // discovered_addr.
1054   oop current_head = refs_list.head();
1055   // The last ref must have its discovered field pointing to itself.
1056   oop next_discovered = (current_head != NULL) ? current_head : obj;
1057 
1058   // Note: In the case of G1, this specific pre-barrier is strictly
1059   // not necessary because the only case we are interested in
1060   // here is when *discovered_addr is NULL (see the CAS further below),
1061   // so this will expand to nothing. As a result, we have manually
1062   // elided this out for G1, but left in the test for some future
1063   // collector that might have need for a pre-barrier here, e.g.:-
1064   // _bs->write_ref_field_pre((oop* or narrowOop*)discovered_addr, next_discovered);
1065   assert(!_discovered_list_needs_barrier || UseG1GC,
1066          "Need to check non-G1 collector: "
1067          "may need a pre-write-barrier for CAS from NULL below");
1068   oop retest = oopDesc::atomic_compare_exchange_oop(next_discovered, discovered_addr,
1069                                                     NULL);
1070   if (retest == NULL) {
1071     // This thread just won the right to enqueue the object.
1072     // We have separate lists for enqueueing, so no synchronization
1073     // is necessary.
1074     refs_list.set_head(obj);
1075     refs_list.inc_length(1);
1076     if (_discovered_list_needs_barrier) {
1077       _bs->write_ref_field((void*)discovered_addr, next_discovered);
1078     }
1079 
1080     if (TraceReferenceGC) {
1081       gclog_or_tty->print_cr("Discovered reference (mt) (" INTPTR_FORMAT ": %s)",
1082                              obj, obj->blueprint()->internal_name());
1083     }
1084   } else {
1085     // If retest was non NULL, another thread beat us to it:
1086     // The reference has already been discovered...
1087     if (TraceReferenceGC) {
1088       gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)",
1089                              obj, obj->blueprint()->internal_name());
1090     }
1091   }
1092 }
1093 
1094 #ifndef PRODUCT
1095 // Non-atomic (i.e. concurrent) discovery might allow us
1096 // to observe j.l.References with NULL referents, being those
1097 // cleared concurrently by mutators during (or after) discovery.
1098 void ReferenceProcessor::verify_referent(oop obj) {
1099   bool da = discovery_is_atomic();
1100   oop referent = java_lang_ref_Reference::referent(obj);
1101   assert(da ? referent->is_oop() : referent->is_oop_or_null(),
1102          err_msg("Bad referent " INTPTR_FORMAT " found in Reference "
1103                  INTPTR_FORMAT " during %satomic discovery ",
1104                  (intptr_t)referent, (intptr_t)obj, da ? "" : "non-"));
1105 }
1106 #endif
1107 
1108 // We mention two of several possible choices here:
1109 // #0: if the reference object is not in the "originating generation"
1110 //     (or part of the heap being collected, indicated by our "span"
1111 //     we don't treat it specially (i.e. we scan it as we would
1112 //     a normal oop, treating its references as strong references).
1113 //     This means that references can't be discovered unless their
1114 //     referent is also in the same span. This is the simplest,
1115 //     most "local" and most conservative approach, albeit one
1116 //     that may cause weak references to be enqueued least promptly.
1117 //     We call this choice the "ReferenceBasedDiscovery" policy.
1118 // #1: the reference object may be in any generation (span), but if
1119 //     the referent is in the generation (span) being currently collected
1120 //     then we can discover the reference object, provided
1121 //     the object has not already been discovered by
1122 //     a different concurrently running collector (as may be the
1123 //     case, for instance, if the reference object is in CMS and
1124 //     the referent in DefNewGeneration), and provided the processing
1125 //     of this reference object by the current collector will
1126 //     appear atomic to every other collector in the system.
1127 //     (Thus, for instance, a concurrent collector may not
1128 //     discover references in other generations even if the
1129 //     referent is in its own generation). This policy may,
1130 //     in certain cases, enqueue references somewhat sooner than
1131 //     might Policy #0 above, but at marginally increased cost
1132 //     and complexity in processing these references.
1133 //     We call this choice the "RefeferentBasedDiscovery" policy.
1134 bool ReferenceProcessor::discover_reference(oop obj, ReferenceType rt) {
1135   // Make sure we are discovering refs (rather than processing discovered refs).
1136   if (!_discovering_refs || !RegisterReferences) {
1137     return false;
1138   }
1139   // We only discover active references.
1140   oop next = java_lang_ref_Reference::next(obj);
1141   if (next != NULL) {   // Ref is no longer active
1142     return false;
1143   }
1144 
1145   HeapWord* obj_addr = (HeapWord*)obj;
1146   if (RefDiscoveryPolicy == ReferenceBasedDiscovery &&
1147       !_span.contains(obj_addr)) {
1148     // Reference is not in the originating generation;
1149     // don't treat it specially (i.e. we want to scan it as a normal
1150     // object with strong references).
1151     return false;
1152   }
1153 
1154   // We only discover references whose referents are not (yet)
1155   // known to be strongly reachable.
1156   if (is_alive_non_header() != NULL) {
1157     verify_referent(obj);
1158     if (is_alive_non_header()->do_object_b(java_lang_ref_Reference::referent(obj))) {
1159       return false;  // referent is reachable
1160     }
1161   }
1162   if (rt == REF_SOFT) {
1163     // For soft refs we can decide now if these are not
1164     // current candidates for clearing, in which case we
1165     // can mark through them now, rather than delaying that
1166     // to the reference-processing phase. Since all current
1167     // time-stamp policies advance the soft-ref clock only
1168     // at a major collection cycle, this is always currently
1169     // accurate.
1170     if (!_current_soft_ref_policy->should_clear_reference(obj, _soft_ref_timestamp_clock)) {
1171       return false;
1172     }
1173   }
1174 
1175   ResourceMark rm;      // Needed for tracing.
1176 
1177   HeapWord* const discovered_addr = java_lang_ref_Reference::discovered_addr(obj);
1178   const oop  discovered = java_lang_ref_Reference::discovered(obj);
1179   assert(discovered->is_oop_or_null(), "bad discovered field");
1180   if (discovered != NULL) {
1181     // The reference has already been discovered...
1182     if (TraceReferenceGC) {
1183       gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)",
1184                              obj, obj->blueprint()->internal_name());
1185     }
1186     if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
1187       // assumes that an object is not processed twice;
1188       // if it's been already discovered it must be on another
1189       // generation's discovered list; so we won't discover it.
1190       return false;
1191     } else {
1192       assert(RefDiscoveryPolicy == ReferenceBasedDiscovery,
1193              "Unrecognized policy");
1194       // Check assumption that an object is not potentially
1195       // discovered twice except by concurrent collectors that potentially
1196       // trace the same Reference object twice.
1197       assert(UseConcMarkSweepGC || UseG1GC,
1198              "Only possible with a concurrent marking collector");
1199       return true;
1200     }
1201   }
1202 
1203   if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
1204     verify_referent(obj);
1205     // Discover if and only if EITHER:
1206     // .. reference is in our span, OR
1207     // .. we are an atomic collector and referent is in our span
1208     if (_span.contains(obj_addr) ||
1209         (discovery_is_atomic() &&
1210          _span.contains(java_lang_ref_Reference::referent(obj)))) {
1211       // should_enqueue = true;
1212     } else {
1213       return false;
1214     }
1215   } else {
1216     assert(RefDiscoveryPolicy == ReferenceBasedDiscovery &&
1217            _span.contains(obj_addr), "code inconsistency");
1218   }
1219 
1220   // Get the right type of discovered queue head.
1221   DiscoveredList* list = get_discovered_list(rt);
1222   if (list == NULL) {
1223     return false;   // nothing special needs to be done
1224   }
1225 
1226   if (_discovery_is_mt) {
1227     add_to_discovered_list_mt(*list, obj, discovered_addr);
1228   } else {
1229     // If "_discovered_list_needs_barrier", we do write barriers when
1230     // updating the discovered reference list.  Otherwise, we do a raw store
1231     // here: the field will be visited later when processing the discovered
1232     // references.
1233     oop current_head = list->head();
1234     // The last ref must have its discovered field pointing to itself.
1235     oop next_discovered = (current_head != NULL) ? current_head : obj;
1236 
1237     // As in the case further above, since we are over-writing a NULL
1238     // pre-value, we can safely elide the pre-barrier here for the case of G1.
1239     // e.g.:- _bs->write_ref_field_pre((oop* or narrowOop*)discovered_addr, next_discovered);
1240     assert(discovered == NULL, "control point invariant");
1241     assert(!_discovered_list_needs_barrier || UseG1GC,
1242            "For non-G1 collector, may need a pre-write-barrier for CAS from NULL below");
1243     oop_store_raw(discovered_addr, next_discovered);
1244     if (_discovered_list_needs_barrier) {
1245       _bs->write_ref_field((void*)discovered_addr, next_discovered);
1246     }
1247     list->set_head(obj);
1248     list->inc_length(1);
1249 
1250     if (TraceReferenceGC) {
1251       gclog_or_tty->print_cr("Discovered reference (" INTPTR_FORMAT ": %s)",
1252                                 obj, obj->blueprint()->internal_name());
1253     }
1254   }
1255   assert(obj->is_oop(), "Discovered a bad reference");
1256   verify_referent(obj);
1257   return true;
1258 }
1259 
1260 // Preclean the discovered references by removing those
1261 // whose referents are alive, and by marking from those that
1262 // are not active. These lists can be handled here
1263 // in any order and, indeed, concurrently.
1264 void ReferenceProcessor::preclean_discovered_references(
1265   BoolObjectClosure* is_alive,
1266   OopClosure* keep_alive,
1267   VoidClosure* complete_gc,
1268   YieldClosure* yield,
1269   bool should_unload_classes) {
1270 
1271   NOT_PRODUCT(verify_ok_to_handle_reflists());
1272 
1273 #ifdef ASSERT
1274   bool must_remember_klasses = ClassUnloading && !UseConcMarkSweepGC ||
1275                                CMSClassUnloadingEnabled && UseConcMarkSweepGC ||
1276                                ExplicitGCInvokesConcurrentAndUnloadsClasses &&
1277                                  UseConcMarkSweepGC && should_unload_classes;
1278   RememberKlassesChecker mx(must_remember_klasses);
1279 #endif
1280   // Soft references
1281   {
1282     TraceTime tt("Preclean SoftReferences", PrintGCDetails && PrintReferenceGC,
1283               false, gclog_or_tty);
1284     for (int i = 0; i < _max_num_q; i++) {
1285       if (yield->should_return()) {
1286         return;
1287       }
1288       preclean_discovered_reflist(_discoveredSoftRefs[i], is_alive,
1289                                   keep_alive, complete_gc, yield);
1290     }
1291   }
1292 
1293   // Weak references
1294   {
1295     TraceTime tt("Preclean WeakReferences", PrintGCDetails && PrintReferenceGC,
1296               false, gclog_or_tty);
1297     for (int i = 0; i < _max_num_q; i++) {
1298       if (yield->should_return()) {
1299         return;
1300       }
1301       preclean_discovered_reflist(_discoveredWeakRefs[i], is_alive,
1302                                   keep_alive, complete_gc, yield);
1303     }
1304   }
1305 
1306   // Final references
1307   {
1308     TraceTime tt("Preclean FinalReferences", PrintGCDetails && PrintReferenceGC,
1309               false, gclog_or_tty);
1310     for (int i = 0; i < _max_num_q; i++) {
1311       if (yield->should_return()) {
1312         return;
1313       }
1314       preclean_discovered_reflist(_discoveredFinalRefs[i], is_alive,
1315                                   keep_alive, complete_gc, yield);
1316     }
1317   }
1318 
1319   // Phantom references
1320   {
1321     TraceTime tt("Preclean PhantomReferences", PrintGCDetails && PrintReferenceGC,
1322               false, gclog_or_tty);
1323     for (int i = 0; i < _max_num_q; i++) {
1324       if (yield->should_return()) {
1325         return;
1326       }
1327       preclean_discovered_reflist(_discoveredPhantomRefs[i], is_alive,
1328                                   keep_alive, complete_gc, yield);
1329     }
1330   }
1331 }
1332 
1333 // Walk the given discovered ref list, and remove all reference objects
1334 // whose referents are still alive, whose referents are NULL or which
1335 // are not active (have a non-NULL next field). NOTE: When we are
1336 // thus precleaning the ref lists (which happens single-threaded today),
1337 // we do not disable refs discovery to honour the correct semantics of
1338 // java.lang.Reference. As a result, we need to be careful below
1339 // that ref removal steps interleave safely with ref discovery steps
1340 // (in this thread).
1341 void
1342 ReferenceProcessor::preclean_discovered_reflist(DiscoveredList&    refs_list,
1343                                                 BoolObjectClosure* is_alive,
1344                                                 OopClosure*        keep_alive,
1345                                                 VoidClosure*       complete_gc,
1346                                                 YieldClosure*      yield) {
1347   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
1348   while (iter.has_next()) {
1349     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
1350     oop obj = iter.obj();
1351     oop next = java_lang_ref_Reference::next(obj);
1352     if (iter.referent() == NULL || iter.is_referent_alive() ||
1353         next != NULL) {
1354       // The referent has been cleared, or is alive, or the Reference is not
1355       // active; we need to trace and mark its cohort.
1356       if (TraceReferenceGC) {
1357         gclog_or_tty->print_cr("Precleaning Reference (" INTPTR_FORMAT ": %s)",
1358                                iter.obj(), iter.obj()->blueprint()->internal_name());
1359       }
1360       // Remove Reference object from list
1361       iter.remove();
1362       // Keep alive its cohort.
1363       iter.make_referent_alive();
1364       if (UseCompressedOops) {
1365         narrowOop* next_addr = (narrowOop*)java_lang_ref_Reference::next_addr(obj);
1366         keep_alive->do_oop(next_addr);
1367       } else {
1368         oop* next_addr = (oop*)java_lang_ref_Reference::next_addr(obj);
1369         keep_alive->do_oop(next_addr);
1370       }
1371       iter.move_to_next();
1372     } else {
1373       iter.next();
1374     }
1375   }
1376   // Close the reachable set
1377   complete_gc->do_void();
1378 
1379   NOT_PRODUCT(
1380     if (PrintGCDetails && PrintReferenceGC && (iter.processed() > 0)) {
1381       gclog_or_tty->print_cr(" Dropped %d Refs out of %d "
1382         "Refs in discovered list " INTPTR_FORMAT,
1383         iter.removed(), iter.processed(), (address)refs_list.head());
1384     }
1385   )
1386 }
1387 
1388 const char* ReferenceProcessor::list_name(int i) {
1389    assert(i >= 0 && i <= _max_num_q * number_of_subclasses_of_ref(),
1390           "Out of bounds index");
1391 
1392    int j = i / _max_num_q;
1393    switch (j) {
1394      case 0: return "SoftRef";
1395      case 1: return "WeakRef";
1396      case 2: return "FinalRef";
1397      case 3: return "PhantomRef";
1398    }
1399    ShouldNotReachHere();
1400    return NULL;
1401 }
1402 
1403 #ifndef PRODUCT
1404 void ReferenceProcessor::verify_ok_to_handle_reflists() {
1405   // empty for now
1406 }
1407 #endif
1408 
1409 #ifndef PRODUCT
1410 void ReferenceProcessor::clear_discovered_references() {
1411   guarantee(!_discovering_refs, "Discovering refs?");
1412   for (int i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
1413     clear_discovered_references(_discovered_refs[i]);
1414   }
1415 }
1416 
1417 #endif // PRODUCT