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