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