1 /*
   2  * Copyright (c) 2001, 2018, 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.inline.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.inline.hpp"
  34 #include "logging/log.hpp"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "oops/access.inline.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "runtime/java.hpp"
  40 
  41 ReferencePolicy* ReferenceProcessor::_always_clear_soft_ref_policy = NULL;
  42 ReferencePolicy* ReferenceProcessor::_default_soft_ref_policy      = NULL;
  43 jlong            ReferenceProcessor::_soft_ref_timestamp_clock = 0;
  44 
  45 void referenceProcessor_init() {
  46   ReferenceProcessor::init_statics();
  47 }
  48 
  49 void ReferenceProcessor::init_statics() {
  50   // We need a monotonically non-decreasing time in ms but
  51   // os::javaTimeMillis() does not guarantee monotonicity.
  52   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
  53 
  54   // Initialize the soft ref timestamp clock.
  55   _soft_ref_timestamp_clock = now;
  56   // Also update the soft ref clock in j.l.r.SoftReference
  57   java_lang_ref_SoftReference::set_clock(_soft_ref_timestamp_clock);
  58 
  59   _always_clear_soft_ref_policy = new AlwaysClearPolicy();
  60   if (is_server_compilation_mode_vm()) {
  61     _default_soft_ref_policy = new LRUMaxHeapPolicy();
  62   } else {
  63     _default_soft_ref_policy = new LRUCurrentHeapPolicy();
  64   }
  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             "Unrecognized RefDiscoveryPolicy");
  71 }
  72 
  73 void ReferenceProcessor::enable_discovery(bool check_no_refs) {
  74 #ifdef ASSERT
  75   // Verify that we're not currently discovering refs
  76   assert(!_discovering_refs, "nested call?");
  77 
  78   if (check_no_refs) {
  79     // Verify that the discovered lists are empty
  80     verify_no_references_recorded();
  81   }
  82 #endif // ASSERT
  83 
  84   // Someone could have modified the value of the static
  85   // field in the j.l.r.SoftReference class that holds the
  86   // soft reference timestamp clock using reflection or
  87   // Unsafe between GCs. Unconditionally update the static
  88   // field in ReferenceProcessor here so that we use the new
  89   // value during reference discovery.
  90 
  91   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
  92   _discovering_refs = true;
  93 }
  94 
  95 ReferenceProcessor::ReferenceProcessor(BoolObjectClosure* is_subject_to_discovery,
  96                                        bool      mt_processing,
  97                                        uint      mt_processing_degree,
  98                                        bool      mt_discovery,
  99                                        uint      mt_discovery_degree,
 100                                        bool      atomic_discovery,
 101                                        BoolObjectClosure* is_alive_non_header)  :
 102   _is_subject_to_discovery(is_subject_to_discovery),
 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   assert(is_subject_to_discovery != NULL, "must be set");
 110 
 111   _discovery_is_atomic = atomic_discovery;
 112   _discovery_is_mt     = mt_discovery;
 113   _num_queues          = MAX2(1U, mt_processing_degree);
 114   _max_num_queues      = MAX2(_num_queues, mt_discovery_degree);
 115   _discovered_refs     = NEW_C_HEAP_ARRAY(DiscoveredList,
 116             _max_num_queues * number_of_subclasses_of_ref(), mtGC);
 117 
 118   if (_discovered_refs == NULL) {
 119     vm_exit_during_initialization("Could not allocated RefProc Array");
 120   }
 121   _discoveredSoftRefs    = &_discovered_refs[0];
 122   _discoveredWeakRefs    = &_discoveredSoftRefs[_max_num_queues];
 123   _discoveredFinalRefs   = &_discoveredWeakRefs[_max_num_queues];
 124   _discoveredPhantomRefs = &_discoveredFinalRefs[_max_num_queues];
 125 
 126   // Initialize all entries to NULL
 127   for (uint i = 0; i < _max_num_queues * 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 SpanReferenceProcessor::SpanReferenceProcessor(MemRegion span,
 136                                                          bool      mt_processing,
 137                                                          uint      mt_processing_degree,
 138                                                          bool      mt_discovery,
 139                                                          uint      mt_discovery_degree,
 140                                                          bool      atomic_discovery,
 141                                                          BoolObjectClosure* is_alive_non_header)  :
 142   ReferenceProcessor(&_span_based_discoverer,
 143                      mt_processing,
 144                      mt_processing_degree,
 145                      mt_discovery,
 146                      mt_discovery_degree,
 147                      atomic_discovery,
 148                      is_alive_non_header),
 149   _span_based_discoverer(span) {
 150 
 151 }
 152 
 153 #ifndef PRODUCT
 154 void ReferenceProcessor::verify_no_references_recorded() {
 155   guarantee(!_discovering_refs, "Discovering refs?");
 156   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
 157     guarantee(_discovered_refs[i].is_empty(),
 158               "Found non-empty discovered list at %u", i);
 159   }
 160 }
 161 #endif
 162 
 163 void ReferenceProcessor::weak_oops_do(OopClosure* f) {
 164   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
 165     if (UseCompressedOops) {
 166       f->do_oop((narrowOop*)_discovered_refs[i].adr_head());
 167     } else {
 168       f->do_oop((oop*)_discovered_refs[i].adr_head());
 169     }
 170   }
 171 }
 172 
 173 void ReferenceProcessor::update_soft_ref_master_clock() {
 174   // Update (advance) the soft ref master clock field. This must be done
 175   // after processing the soft ref list.
 176 
 177   // We need a monotonically non-decreasing time in ms but
 178   // os::javaTimeMillis() does not guarantee monotonicity.
 179   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
 180   jlong soft_ref_clock = java_lang_ref_SoftReference::clock();
 181   assert(soft_ref_clock == _soft_ref_timestamp_clock, "soft ref clocks out of sync");
 182 
 183   NOT_PRODUCT(
 184   if (now < _soft_ref_timestamp_clock) {
 185     log_warning(gc)("time warp: " JLONG_FORMAT " to " JLONG_FORMAT,
 186                     _soft_ref_timestamp_clock, now);
 187   }
 188   )
 189   // The values of now and _soft_ref_timestamp_clock are set using
 190   // javaTimeNanos(), which is guaranteed to be monotonically
 191   // non-decreasing provided the underlying platform provides such
 192   // a time source (and it is bug free).
 193   // In product mode, however, protect ourselves from non-monotonicity.
 194   if (now > _soft_ref_timestamp_clock) {
 195     _soft_ref_timestamp_clock = now;
 196     java_lang_ref_SoftReference::set_clock(now);
 197   }
 198   // Else leave clock stalled at its old value until time progresses
 199   // past clock value.
 200 }
 201 
 202 size_t ReferenceProcessor::total_count(DiscoveredList lists[]) const {
 203   size_t total = 0;
 204   for (uint i = 0; i < _max_num_queues; ++i) {
 205     total += lists[i].length();
 206   }
 207   return total;
 208 }
 209 
 210 ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
 211   BoolObjectClosure*            is_alive,
 212   OopClosure*                   keep_alive,
 213   VoidClosure*                  complete_gc,
 214   AbstractRefProcTaskExecutor*  task_executor,
 215   ReferenceProcessorPhaseTimes* phase_times) {
 216 
 217   double start_time = os::elapsedTime();
 218 
 219   assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
 220   // Stop treating discovered references specially.
 221   disable_discovery();
 222 
 223   // If discovery was concurrent, someone could have modified
 224   // the value of the static field in the j.l.r.SoftReference
 225   // class that holds the soft reference timestamp clock using
 226   // reflection or Unsafe between when discovery was enabled and
 227   // now. Unconditionally update the static field in ReferenceProcessor
 228   // here so that we use the new value during processing of the
 229   // discovered soft refs.
 230 
 231   _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
 232 
 233   ReferenceProcessorStats stats(total_count(_discoveredSoftRefs),
 234                                 total_count(_discoveredWeakRefs),
 235                                 total_count(_discoveredFinalRefs),
 236                                 total_count(_discoveredPhantomRefs));
 237 
 238   // Soft references
 239   {
 240     RefProcPhaseTimesTracker tt(REF_SOFT, phase_times, this);
 241     process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
 242                                is_alive, keep_alive, complete_gc, task_executor, phase_times);
 243   }
 244 
 245   update_soft_ref_master_clock();
 246 
 247   // Weak references
 248   {
 249     RefProcPhaseTimesTracker tt(REF_WEAK, phase_times, this);
 250     process_discovered_reflist(_discoveredWeakRefs, NULL, true,
 251                                is_alive, keep_alive, complete_gc, task_executor, phase_times);
 252   }
 253 
 254   // Final references
 255   {
 256     RefProcPhaseTimesTracker tt(REF_FINAL, phase_times, this);
 257     process_discovered_reflist(_discoveredFinalRefs, NULL, false,
 258                                is_alive, keep_alive, complete_gc, task_executor, phase_times);
 259   }
 260 
 261   // Phantom references
 262   {
 263     RefProcPhaseTimesTracker tt(REF_PHANTOM, phase_times, this);
 264     process_discovered_reflist(_discoveredPhantomRefs, NULL, true,
 265                                is_alive, keep_alive, complete_gc, task_executor, phase_times);
 266   }
 267 
 268   if (task_executor != NULL) {
 269     // Record the work done by the parallel workers.
 270     task_executor->set_single_threaded_mode();
 271   }
 272 
 273   phase_times->set_total_time_ms((os::elapsedTime() - start_time) * 1000);
 274 
 275   return stats;
 276 }
 277 
 278 void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
 279   _current_discovered_addr = java_lang_ref_Reference::discovered_addr_raw(_current_discovered);
 280   oop discovered = java_lang_ref_Reference::discovered(_current_discovered);
 281   assert(_current_discovered_addr && oopDesc::is_oop_or_null(discovered),
 282          "Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered));
 283   _next_discovered = discovered;
 284 
 285   _referent_addr = java_lang_ref_Reference::referent_addr_raw(_current_discovered);
 286   _referent = java_lang_ref_Reference::referent(_current_discovered);
 287   assert(Universe::heap()->is_in_reserved_or_null(_referent),
 288          "Wrong oop found in java.lang.Reference object");
 289   assert(allow_null_referent ?
 290              oopDesc::is_oop_or_null(_referent)
 291            : oopDesc::is_oop(_referent),
 292          "Expected an oop%s for referent field at " PTR_FORMAT,
 293          (allow_null_referent ? " or NULL" : ""),
 294          p2i(_referent));
 295 }
 296 
 297 void DiscoveredListIterator::remove() {
 298   assert(oopDesc::is_oop(_current_discovered), "Dropping a bad reference");
 299   RawAccess<>::oop_store(_current_discovered_addr, oop(NULL));
 300 
 301   // First _prev_next ref actually points into DiscoveredList (gross).
 302   oop new_next;
 303   if (_next_discovered == _current_discovered) {
 304     // At the end of the list, we should make _prev point to itself.
 305     // If _ref is the first ref, then _prev_next will be in the DiscoveredList,
 306     // and _prev will be NULL.
 307     new_next = _prev_discovered;
 308   } else {
 309     new_next = _next_discovered;
 310   }
 311   // Remove Reference object from discovered list. Note that G1 does not need a
 312   // pre-barrier here because we know the Reference has already been found/marked,
 313   // that's how it ended up in the discovered list in the first place.
 314   RawAccess<>::oop_store(_prev_discovered_addr, new_next);
 315   NOT_PRODUCT(_removed++);
 316   _refs_list.dec_length(1);
 317 }
 318 
 319 void DiscoveredListIterator::clear_referent() {
 320   RawAccess<>::oop_store(_referent_addr, oop(NULL));
 321 }
 322 
 323 void DiscoveredListIterator::enqueue() {
 324   // Self-loop next, so as to make Ref not active.
 325   java_lang_ref_Reference::set_next_raw(_current_discovered, _current_discovered);
 326 
 327   HeapAccess<AS_NO_KEEPALIVE>::oop_store_at(_current_discovered,
 328                                             java_lang_ref_Reference::discovered_offset,
 329                                             _next_discovered);
 330 }
 331 
 332 void DiscoveredListIterator::complete_enqeue() {
 333   if (_prev_discovered != NULL) {
 334     // This is the last object.
 335     // Swap refs_list into pending list and set obj's
 336     // discovered to what we read from the pending list.
 337     oop old = Universe::swap_reference_pending_list(_refs_list.head());
 338     HeapAccess<AS_NO_KEEPALIVE>::oop_store_at(_prev_discovered, java_lang_ref_Reference::discovered_offset, old);
 339   }
 340 }
 341 
 342 // NOTE: process_phase*() are largely similar, and at a high level
 343 // merely iterate over the extant list applying a predicate to
 344 // each of its elements and possibly removing that element from the
 345 // list and applying some further closures to that element.
 346 // We should consider the possibility of replacing these
 347 // process_phase*() methods by abstracting them into
 348 // a single general iterator invocation that receives appropriate
 349 // closures that accomplish this work.
 350 
 351 // (SoftReferences only) Traverse the list and remove any SoftReferences whose
 352 // referents are not alive, but that should be kept alive for policy reasons.
 353 // Keep alive the transitive closure of all such referents.
 354 void
 355 ReferenceProcessor::process_phase1(DiscoveredList&    refs_list,
 356                                    ReferencePolicy*   policy,
 357                                    BoolObjectClosure* is_alive,
 358                                    OopClosure*        keep_alive,
 359                                    VoidClosure*       complete_gc) {
 360   assert(policy != NULL, "Must have a non-NULL policy");
 361   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 362   // Decide which softly reachable refs should be kept alive.
 363   while (iter.has_next()) {
 364     iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
 365     bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
 366     if (referent_is_dead &&
 367         !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
 368       log_develop_trace(gc, ref)("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
 369                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
 370       // Remove Reference object from list
 371       iter.remove();
 372       // keep the referent around
 373       iter.make_referent_alive();
 374       iter.move_to_next();
 375     } else {
 376       iter.next();
 377     }
 378   }
 379   // Close the reachable set
 380   complete_gc->do_void();
 381   log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " dead Refs out of " SIZE_FORMAT " discovered Refs by policy, from list " INTPTR_FORMAT,
 382                              iter.removed(), iter.processed(), p2i(&refs_list));
 383 }
 384 
 385 void ReferenceProcessor::process_phase2(DiscoveredList&    refs_list,
 386                                         BoolObjectClosure* is_alive,
 387                                         OopClosure*        keep_alive,
 388                                         VoidClosure*       complete_gc) {
 389   if (discovery_is_atomic()) {
 390     // complete_gc is ignored in this case for this phase
 391     pp2_work(refs_list, is_alive, keep_alive);
 392   } else {
 393     assert(complete_gc != NULL, "Error");
 394     pp2_work_concurrent_discovery(refs_list, is_alive,
 395                                   keep_alive, complete_gc);
 396   }
 397 }
 398 // Traverse the list and remove any Refs that are not active, or
 399 // whose referents are either alive or NULL.
 400 void
 401 ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
 402                              BoolObjectClosure* is_alive,
 403                              OopClosure*        keep_alive) {
 404   assert(discovery_is_atomic(), "Error");
 405   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 406   while (iter.has_next()) {
 407     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 408     DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
 409     assert(next == NULL, "Should not discover inactive Reference");
 410     if (iter.is_referent_alive()) {
 411       log_develop_trace(gc, ref)("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
 412                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
 413       // The referent is reachable after all.
 414       // Remove Reference object from list.
 415       iter.remove();
 416       // Update the referent pointer as necessary: Note that this
 417       // should not entail any recursive marking because the
 418       // referent must already have been traversed.
 419       iter.make_referent_alive();
 420       iter.move_to_next();
 421     } else {
 422       iter.next();
 423     }
 424   }
 425   NOT_PRODUCT(
 426     if (iter.processed() > 0) {
 427       log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
 428         " Refs in discovered list " INTPTR_FORMAT,
 429         iter.removed(), iter.processed(), p2i(&refs_list));
 430     }
 431   )
 432 }
 433 
 434 void
 435 ReferenceProcessor::pp2_work_concurrent_discovery(DiscoveredList&    refs_list,
 436                                                   BoolObjectClosure* is_alive,
 437                                                   OopClosure*        keep_alive,
 438                                                   VoidClosure*       complete_gc) {
 439   assert(!discovery_is_atomic(), "Error");
 440   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 441   while (iter.has_next()) {
 442     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
 443     HeapWord* next_addr = java_lang_ref_Reference::next_addr_raw(iter.obj());
 444     oop next = java_lang_ref_Reference::next(iter.obj());
 445     if ((iter.referent() == NULL || iter.is_referent_alive() ||
 446          next != NULL)) {
 447       assert(oopDesc::is_oop_or_null(next), "Expected an oop or NULL for next field at " PTR_FORMAT, p2i(next));
 448       // Remove Reference object from list
 449       iter.remove();
 450       // Trace the cohorts
 451       iter.make_referent_alive();
 452       if (UseCompressedOops) {
 453         keep_alive->do_oop((narrowOop*)next_addr);
 454       } else {
 455         keep_alive->do_oop((oop*)next_addr);
 456       }
 457       iter.move_to_next();
 458     } else {
 459       iter.next();
 460     }
 461   }
 462   // Now close the newly reachable set
 463   complete_gc->do_void();
 464   NOT_PRODUCT(
 465     if (iter.processed() > 0) {
 466       log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " active Refs out of " SIZE_FORMAT
 467         " Refs in discovered list " INTPTR_FORMAT,
 468         iter.removed(), iter.processed(), p2i(&refs_list));
 469     }
 470   )
 471 }
 472 
 473 void ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
 474                                         bool               clear_referent,
 475                                         BoolObjectClosure* is_alive,
 476                                         OopClosure*        keep_alive,
 477                                         VoidClosure*       complete_gc) {
 478   ResourceMark rm;
 479   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
 480   while (iter.has_next()) {
 481     iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
 482     if (clear_referent) {
 483       // NULL out referent pointer
 484       iter.clear_referent();
 485     } else {
 486       // keep the referent around
 487       iter.make_referent_alive();
 488     }
 489     iter.enqueue();
 490     log_develop_trace(gc, ref)("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
 491                                clear_referent ? "cleared " : "", p2i(iter.obj()), iter.obj()->klass()->internal_name());
 492     assert(oopDesc::is_oop(iter.obj(), UseConcMarkSweepGC), "Adding a bad reference");
 493     iter.next();
 494   }
 495   iter.complete_enqeue();
 496   // Close the reachable set
 497   complete_gc->do_void();
 498   // Clear the list.
 499   refs_list.set_head(NULL);
 500   refs_list.set_length(0);
 501 }
 502 
 503 void
 504 ReferenceProcessor::clear_discovered_references(DiscoveredList& refs_list) {
 505   oop obj = NULL;
 506   oop next = refs_list.head();
 507   while (next != obj) {
 508     obj = next;
 509     next = java_lang_ref_Reference::discovered(obj);
 510     java_lang_ref_Reference::set_discovered_raw(obj, NULL);
 511   }
 512   refs_list.set_head(NULL);
 513   refs_list.set_length(0);
 514 }
 515 
 516 void ReferenceProcessor::abandon_partial_discovery() {
 517   // loop over the lists
 518   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
 519     if ((i % _max_num_queues) == 0) {
 520       log_develop_trace(gc, ref)("Abandoning %s discovered list", list_name(i));
 521     }
 522     clear_discovered_references(_discovered_refs[i]);
 523   }
 524 }
 525 
 526 size_t ReferenceProcessor::total_reference_count(ReferenceType type) const {
 527   DiscoveredList* list = NULL;
 528 
 529   switch (type) {
 530     case REF_SOFT:
 531       list = _discoveredSoftRefs;
 532       break;
 533     case REF_WEAK:
 534       list = _discoveredWeakRefs;
 535       break;
 536     case REF_FINAL:
 537       list = _discoveredFinalRefs;
 538       break;
 539     case REF_PHANTOM:
 540       list = _discoveredPhantomRefs;
 541       break;
 542     case REF_OTHER:
 543     case REF_NONE:
 544     default:
 545       ShouldNotReachHere();
 546   }
 547   return total_count(list);
 548 }
 549 
 550 class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
 551 public:
 552   RefProcPhase1Task(ReferenceProcessor&           ref_processor,
 553                     DiscoveredList                refs_lists[],
 554                     ReferencePolicy*              policy,
 555                     bool                          marks_oops_alive,
 556                     ReferenceProcessorPhaseTimes* phase_times)
 557     : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times),
 558       _policy(policy)
 559   { }
 560   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 561                     OopClosure& keep_alive,
 562                     VoidClosure& complete_gc)
 563   {
 564     RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase1, _phase_times, i);
 565 
 566     _ref_processor.process_phase1(_refs_lists[i], _policy,
 567                                   &is_alive, &keep_alive, &complete_gc);
 568   }
 569 private:
 570   ReferencePolicy* _policy;
 571 };
 572 
 573 class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
 574 public:
 575   RefProcPhase2Task(ReferenceProcessor&           ref_processor,
 576                     DiscoveredList                refs_lists[],
 577                     bool                          marks_oops_alive,
 578                     ReferenceProcessorPhaseTimes* phase_times)
 579     : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times)
 580   { }
 581   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 582                     OopClosure& keep_alive,
 583                     VoidClosure& complete_gc)
 584   {
 585     RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase2, _phase_times, i);
 586 
 587     _ref_processor.process_phase2(_refs_lists[i],
 588                                   &is_alive, &keep_alive, &complete_gc);
 589   }
 590 };
 591 
 592 class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
 593 public:
 594   RefProcPhase3Task(ReferenceProcessor&           ref_processor,
 595                     DiscoveredList                refs_lists[],
 596                     bool                         clear_referent,
 597                     bool                          marks_oops_alive,
 598                     ReferenceProcessorPhaseTimes* phase_times)
 599     : ProcessTask(ref_processor, refs_lists, marks_oops_alive, phase_times),
 600       _clear_referent(clear_referent)
 601   { }
 602   virtual void work(unsigned int i, BoolObjectClosure& is_alive,
 603                     OopClosure& keep_alive,
 604                     VoidClosure& complete_gc)
 605   {
 606     RefProcWorkerTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase3, _phase_times, i);
 607 
 608     _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
 609                                   &is_alive, &keep_alive, &complete_gc);
 610   }
 611 private:
 612   bool _clear_referent;
 613 };
 614 
 615 void ReferenceProcessor::log_reflist(const char* prefix, DiscoveredList list[], uint num_active_queues) {
 616   LogTarget(Trace, gc, ref) lt;
 617 
 618   if (!lt.is_enabled()) {
 619     return;
 620   }
 621 
 622   size_t total = 0;
 623 
 624   LogStream ls(lt);
 625   ls.print("%s", prefix);
 626   for (uint i = 0; i < num_active_queues; i++) {
 627     ls.print(SIZE_FORMAT " ", list[i].length());
 628     total += list[i].length();
 629   }
 630   ls.print_cr("(" SIZE_FORMAT ")", total);
 631 }
 632 
 633 #ifndef PRODUCT
 634 void ReferenceProcessor::log_reflist_counts(DiscoveredList ref_lists[], uint num_active_queues) {
 635   if (!log_is_enabled(Trace, gc, ref)) {
 636     return;
 637   }
 638 
 639   log_reflist("", ref_lists, num_active_queues);
 640 #ifdef ASSERT
 641   for (uint i = num_active_queues; i < _max_num_queues; i++) {
 642     assert(ref_lists[i].length() == 0, SIZE_FORMAT " unexpected References in %u",
 643            ref_lists[i].length(), i);
 644   }
 645 #endif
 646 }
 647 #endif
 648 
 649 void ReferenceProcessor::set_active_mt_degree(uint v) {
 650   _num_queues = v;
 651   _next_id = 0;
 652 }
 653 
 654 // Balances reference queues.
 655 // Move entries from all queues[0, 1, ..., _max_num_q-1] to
 656 // queues[0, 1, ..., _num_q-1] because only the first _num_q
 657 // corresponding to the active workers will be processed.
 658 void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[])
 659 {
 660   // calculate total length
 661   size_t total_refs = 0;
 662   log_develop_trace(gc, ref)("Balance ref_lists ");
 663 
 664   log_reflist_counts(ref_lists, _max_num_queues);
 665 
 666   for (uint i = 0; i < _max_num_queues; ++i) {
 667     total_refs += ref_lists[i].length();
 668   }
 669   size_t avg_refs = total_refs / _num_queues + 1;
 670   uint to_idx = 0;
 671   for (uint from_idx = 0; from_idx < _max_num_queues; from_idx++) {
 672     bool move_all = false;
 673     if (from_idx >= _num_queues) {
 674       move_all = ref_lists[from_idx].length() > 0;
 675     }
 676     while ((ref_lists[from_idx].length() > avg_refs) ||
 677            move_all) {
 678       assert(to_idx < _num_queues, "Sanity Check!");
 679       if (ref_lists[to_idx].length() < avg_refs) {
 680         // move superfluous refs
 681         size_t refs_to_move;
 682         // Move all the Ref's if the from queue will not be processed.
 683         if (move_all) {
 684           refs_to_move = MIN2(ref_lists[from_idx].length(),
 685                               avg_refs - ref_lists[to_idx].length());
 686         } else {
 687           refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs,
 688                               avg_refs - ref_lists[to_idx].length());
 689         }
 690 
 691         assert(refs_to_move > 0, "otherwise the code below will fail");
 692 
 693         oop move_head = ref_lists[from_idx].head();
 694         oop move_tail = move_head;
 695         oop new_head  = move_head;
 696         // find an element to split the list on
 697         for (size_t j = 0; j < refs_to_move; ++j) {
 698           move_tail = new_head;
 699           new_head = java_lang_ref_Reference::discovered(new_head);
 700         }
 701 
 702         // Add the chain to the to list.
 703         if (ref_lists[to_idx].head() == NULL) {
 704           // to list is empty. Make a loop at the end.
 705           java_lang_ref_Reference::set_discovered_raw(move_tail, move_tail);
 706         } else {
 707           java_lang_ref_Reference::set_discovered_raw(move_tail, ref_lists[to_idx].head());
 708         }
 709         ref_lists[to_idx].set_head(move_head);
 710         ref_lists[to_idx].inc_length(refs_to_move);
 711 
 712         // Remove the chain from the from list.
 713         if (move_tail == new_head) {
 714           // We found the end of the from list.
 715           ref_lists[from_idx].set_head(NULL);
 716         } else {
 717           ref_lists[from_idx].set_head(new_head);
 718         }
 719         ref_lists[from_idx].dec_length(refs_to_move);
 720         if (ref_lists[from_idx].length() == 0) {
 721           break;
 722         }
 723       } else {
 724         to_idx = (to_idx + 1) % _num_queues;
 725       }
 726     }
 727   }
 728 #ifdef ASSERT
 729   log_reflist_counts(ref_lists, _num_queues);
 730   size_t balanced_total_refs = 0;
 731   for (uint i = 0; i < _num_queues; ++i) {
 732     balanced_total_refs += ref_lists[i].length();
 733   }
 734   assert(total_refs == balanced_total_refs, "Balancing was incomplete");
 735 #endif
 736 }
 737 
 738 void ReferenceProcessor::process_discovered_reflist(
 739   DiscoveredList                refs_lists[],
 740   ReferencePolicy*              policy,
 741   bool                          clear_referent,
 742   BoolObjectClosure*            is_alive,
 743   OopClosure*                   keep_alive,
 744   VoidClosure*                  complete_gc,
 745   AbstractRefProcTaskExecutor*  task_executor,
 746   ReferenceProcessorPhaseTimes* phase_times)
 747 {
 748   bool mt_processing = task_executor != NULL && _processing_is_mt;
 749 
 750   phase_times->set_processing_is_mt(mt_processing);
 751 
 752   if (mt_processing && ParallelRefProcBalancingEnabled) {
 753     RefProcBalanceQueuesTimeTracker tt(phase_times);
 754     balance_queues(refs_lists);
 755   }
 756 
 757   // Phase 1 (soft refs only):
 758   // . Traverse the list and remove any SoftReferences whose
 759   //   referents are not alive, but that should be kept alive for
 760   //   policy reasons. Keep alive the transitive closure of all
 761   //   such referents.
 762   if (policy != NULL) {
 763     RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase1, phase_times);
 764 
 765     if (mt_processing) {
 766       RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/, phase_times);
 767       task_executor->execute(phase1);
 768     } else {
 769       for (uint i = 0; i < _max_num_queues; i++) {
 770         process_phase1(refs_lists[i], policy,
 771                        is_alive, keep_alive, complete_gc);
 772       }
 773     }
 774   } else { // policy == NULL
 775     assert(refs_lists != _discoveredSoftRefs,
 776            "Policy must be specified for soft references.");
 777   }
 778 
 779   // Phase 2:
 780   // . Traverse the list and remove any refs whose referents are alive.
 781   {
 782     RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase2, phase_times);
 783 
 784     if (mt_processing) {
 785       RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/, phase_times);
 786       task_executor->execute(phase2);
 787     } else {
 788       for (uint i = 0; i < _max_num_queues; i++) {
 789         process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
 790       }
 791     }
 792   }
 793 
 794   // Phase 3:
 795   // . Traverse the list and process referents as appropriate.
 796   {
 797     RefProcParPhaseTimeTracker tt(ReferenceProcessorPhaseTimes::RefPhase3, phase_times);
 798 
 799     if (mt_processing) {
 800       RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/, phase_times);
 801       task_executor->execute(phase3);
 802     } else {
 803       for (uint i = 0; i < _max_num_queues; i++) {
 804         process_phase3(refs_lists[i], clear_referent,
 805                        is_alive, keep_alive, complete_gc);
 806       }
 807     }
 808   }
 809 }
 810 
 811 inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
 812   uint id = 0;
 813   // Determine the queue index to use for this object.
 814   if (_discovery_is_mt) {
 815     // During a multi-threaded discovery phase,
 816     // each thread saves to its "own" list.
 817     Thread* thr = Thread::current();
 818     id = thr->as_Worker_thread()->id();
 819   } else {
 820     // single-threaded discovery, we save in round-robin
 821     // fashion to each of the lists.
 822     if (_processing_is_mt) {
 823       id = next_id();
 824     }
 825   }
 826   assert(id < _max_num_queues, "Id is out-of-bounds id %u and max id %u)", id, _max_num_queues);
 827 
 828   // Get the discovered queue to which we will add
 829   DiscoveredList* list = NULL;
 830   switch (rt) {
 831     case REF_OTHER:
 832       // Unknown reference type, no special treatment
 833       break;
 834     case REF_SOFT:
 835       list = &_discoveredSoftRefs[id];
 836       break;
 837     case REF_WEAK:
 838       list = &_discoveredWeakRefs[id];
 839       break;
 840     case REF_FINAL:
 841       list = &_discoveredFinalRefs[id];
 842       break;
 843     case REF_PHANTOM:
 844       list = &_discoveredPhantomRefs[id];
 845       break;
 846     case REF_NONE:
 847       // we should not reach here if we are an InstanceRefKlass
 848     default:
 849       ShouldNotReachHere();
 850   }
 851   log_develop_trace(gc, ref)("Thread %d gets list " INTPTR_FORMAT, id, p2i(list));
 852   return list;
 853 }
 854 
 855 inline void
 856 ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list,
 857                                               oop             obj,
 858                                               HeapWord*       discovered_addr) {
 859   assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller");
 860   // First we must make sure this object is only enqueued once. CAS in a non null
 861   // discovered_addr.
 862   oop current_head = refs_list.head();
 863   // The last ref must have its discovered field pointing to itself.
 864   oop next_discovered = (current_head != NULL) ? current_head : obj;
 865 
 866   oop retest = RawAccess<>::oop_atomic_cmpxchg(next_discovered, discovered_addr, oop(NULL));
 867 
 868   if (retest == NULL) {
 869     // This thread just won the right to enqueue the object.
 870     // We have separate lists for enqueueing, so no synchronization
 871     // is necessary.
 872     refs_list.set_head(obj);
 873     refs_list.inc_length(1);
 874 
 875     log_develop_trace(gc, ref)("Discovered reference (mt) (" INTPTR_FORMAT ": %s)",
 876                                p2i(obj), obj->klass()->internal_name());
 877   } else {
 878     // If retest was non NULL, another thread beat us to it:
 879     // The reference has already been discovered...
 880     log_develop_trace(gc, ref)("Already discovered reference (" INTPTR_FORMAT ": %s)",
 881                                p2i(obj), obj->klass()->internal_name());
 882   }
 883 }
 884 
 885 #ifndef PRODUCT
 886 // Non-atomic (i.e. concurrent) discovery might allow us
 887 // to observe j.l.References with NULL referents, being those
 888 // cleared concurrently by mutators during (or after) discovery.
 889 void ReferenceProcessor::verify_referent(oop obj) {
 890   bool da = discovery_is_atomic();
 891   oop referent = java_lang_ref_Reference::referent(obj);
 892   assert(da ? oopDesc::is_oop(referent) : oopDesc::is_oop_or_null(referent),
 893          "Bad referent " INTPTR_FORMAT " found in Reference "
 894          INTPTR_FORMAT " during %satomic discovery ",
 895          p2i(referent), p2i(obj), da ? "" : "non-");
 896 }
 897 #endif
 898 
 899 template <class T>
 900 bool ReferenceProcessor::is_subject_to_discovery(T const obj) const {
 901   return _is_subject_to_discovery->do_object_b(obj);
 902 }
 903 
 904 // We mention two of several possible choices here:
 905 // #0: if the reference object is not in the "originating generation"
 906 //     (or part of the heap being collected, indicated by our "span"
 907 //     we don't treat it specially (i.e. we scan it as we would
 908 //     a normal oop, treating its references as strong references).
 909 //     This means that references can't be discovered unless their
 910 //     referent is also in the same span. This is the simplest,
 911 //     most "local" and most conservative approach, albeit one
 912 //     that may cause weak references to be enqueued least promptly.
 913 //     We call this choice the "ReferenceBasedDiscovery" policy.
 914 // #1: the reference object may be in any generation (span), but if
 915 //     the referent is in the generation (span) being currently collected
 916 //     then we can discover the reference object, provided
 917 //     the object has not already been discovered by
 918 //     a different concurrently running collector (as may be the
 919 //     case, for instance, if the reference object is in CMS and
 920 //     the referent in DefNewGeneration), and provided the processing
 921 //     of this reference object by the current collector will
 922 //     appear atomic to every other collector in the system.
 923 //     (Thus, for instance, a concurrent collector may not
 924 //     discover references in other generations even if the
 925 //     referent is in its own generation). This policy may,
 926 //     in certain cases, enqueue references somewhat sooner than
 927 //     might Policy #0 above, but at marginally increased cost
 928 //     and complexity in processing these references.
 929 //     We call this choice the "RefeferentBasedDiscovery" policy.
 930 bool ReferenceProcessor::discover_reference(oop obj, ReferenceType rt) {
 931   // Make sure we are discovering refs (rather than processing discovered refs).
 932   if (!_discovering_refs || !RegisterReferences) {
 933     return false;
 934   }
 935   // We only discover active references.
 936   oop next = java_lang_ref_Reference::next(obj);
 937   if (next != NULL) {   // Ref is no longer active
 938     return false;
 939   }
 940 
 941   if (RefDiscoveryPolicy == ReferenceBasedDiscovery &&
 942       !is_subject_to_discovery(obj)) {
 943     // Reference is not in the originating generation;
 944     // don't treat it specially (i.e. we want to scan it as a normal
 945     // object with strong references).
 946     return false;
 947   }
 948 
 949   // We only discover references whose referents are not (yet)
 950   // known to be strongly reachable.
 951   if (is_alive_non_header() != NULL) {
 952     verify_referent(obj);
 953     if (is_alive_non_header()->do_object_b(java_lang_ref_Reference::referent(obj))) {
 954       return false;  // referent is reachable
 955     }
 956   }
 957   if (rt == REF_SOFT) {
 958     // For soft refs we can decide now if these are not
 959     // current candidates for clearing, in which case we
 960     // can mark through them now, rather than delaying that
 961     // to the reference-processing phase. Since all current
 962     // time-stamp policies advance the soft-ref clock only
 963     // at a full collection cycle, this is always currently
 964     // accurate.
 965     if (!_current_soft_ref_policy->should_clear_reference(obj, _soft_ref_timestamp_clock)) {
 966       return false;
 967     }
 968   }
 969 
 970   ResourceMark rm;      // Needed for tracing.
 971 
 972   HeapWord* const discovered_addr = java_lang_ref_Reference::discovered_addr_raw(obj);
 973   const oop  discovered = java_lang_ref_Reference::discovered(obj);
 974   assert(oopDesc::is_oop_or_null(discovered), "Expected an oop or NULL for discovered field at " PTR_FORMAT, p2i(discovered));
 975   if (discovered != NULL) {
 976     // The reference has already been discovered...
 977     log_develop_trace(gc, ref)("Already discovered reference (" INTPTR_FORMAT ": %s)",
 978                                p2i(obj), obj->klass()->internal_name());
 979     if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
 980       // assumes that an object is not processed twice;
 981       // if it's been already discovered it must be on another
 982       // generation's discovered list; so we won't discover it.
 983       return false;
 984     } else {
 985       assert(RefDiscoveryPolicy == ReferenceBasedDiscovery,
 986              "Unrecognized policy");
 987       // Check assumption that an object is not potentially
 988       // discovered twice except by concurrent collectors that potentially
 989       // trace the same Reference object twice.
 990       assert(UseConcMarkSweepGC || UseG1GC,
 991              "Only possible with a concurrent marking collector");
 992       return true;
 993     }
 994   }
 995 
 996   if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
 997     verify_referent(obj);
 998     // Discover if and only if EITHER:
 999     // .. reference is in our span, OR
1000     // .. we are an atomic collector and referent is in our span
1001     if (is_subject_to_discovery(obj) ||
1002         (discovery_is_atomic() &&
1003          is_subject_to_discovery(java_lang_ref_Reference::referent(obj)))) {
1004     } else {
1005       return false;
1006     }
1007   } else {
1008     assert(RefDiscoveryPolicy == ReferenceBasedDiscovery &&
1009            is_subject_to_discovery(obj), "code inconsistency");
1010   }
1011 
1012   // Get the right type of discovered queue head.
1013   DiscoveredList* list = get_discovered_list(rt);
1014   if (list == NULL) {
1015     return false;   // nothing special needs to be done
1016   }
1017 
1018   if (_discovery_is_mt) {
1019     add_to_discovered_list_mt(*list, obj, discovered_addr);
1020   } else {
1021     // We do a raw store here: the field will be visited later when processing
1022     // the discovered references.
1023     oop current_head = list->head();
1024     // The last ref must have its discovered field pointing to itself.
1025     oop next_discovered = (current_head != NULL) ? current_head : obj;
1026 
1027     assert(discovered == NULL, "control point invariant");
1028     RawAccess<>::oop_store(discovered_addr, next_discovered);
1029     list->set_head(obj);
1030     list->inc_length(1);
1031 
1032     log_develop_trace(gc, ref)("Discovered reference (" INTPTR_FORMAT ": %s)", p2i(obj), obj->klass()->internal_name());
1033   }
1034   assert(oopDesc::is_oop(obj), "Discovered a bad reference");
1035   verify_referent(obj);
1036   return true;
1037 }
1038 
1039 bool ReferenceProcessor::has_discovered_references() {
1040   for (uint i = 0; i < _max_num_queues * number_of_subclasses_of_ref(); i++) {
1041     if (!_discovered_refs[i].is_empty()) {
1042       return true;
1043     }
1044   }
1045   return false;
1046 }
1047 
1048 void ReferenceProcessor::preclean_discovered_references(BoolObjectClosure* is_alive,
1049                                                         OopClosure* keep_alive,
1050                                                         VoidClosure* complete_gc,
1051                                                         YieldClosure* yield,
1052                                                         GCTimer* gc_timer) {
1053   // These lists can be handled here in any order and, indeed, concurrently.
1054     
1055   // Soft references
1056   {
1057     GCTraceTime(Debug, gc, ref) tm("Preclean SoftReferences", gc_timer);
1058     log_reflist("SoftRef before: ", _discoveredSoftRefs, _max_num_queues);
1059     for (uint i = 0; i < _max_num_queues; i++) {
1060       if (yield->should_return()) {
1061         return;
1062       }        
1063       if (preclean_discovered_reflist(_discoveredSoftRefs[i], is_alive,
1064                                       keep_alive, complete_gc, yield)) {
1065         log_reflist("SoftRef abort: ", _discoveredSoftRefs, _max_num_queues);
1066         return;
1067       }
1068     }
1069     log_reflist("SoftRef after: ", _discoveredSoftRefs, _max_num_queues);
1070   }
1071 
1072   // Weak references
1073   {
1074     GCTraceTime(Debug, gc, ref) tm("Preclean WeakReferences", gc_timer);
1075     log_reflist("WeakRef before: ", _discoveredWeakRefs, _max_num_queues);
1076     for (uint i = 0; i < _max_num_queues; i++) {
1077       if (yield->should_return()) {
1078         return;
1079       }
1080       if (preclean_discovered_reflist(_discoveredWeakRefs[i], is_alive,
1081                                       keep_alive, complete_gc, yield)) {
1082         log_reflist("WeakRef abort: ", _discoveredWeakRefs, _max_num_queues);
1083         return;
1084       }
1085     }
1086     log_reflist("WeakRef after: ", _discoveredWeakRefs, _max_num_queues);
1087   }
1088 
1089   // Final references
1090   {
1091     GCTraceTime(Debug, gc, ref) tm("Preclean FinalReferences", gc_timer);
1092     log_reflist("FinalRef before: ", _discoveredFinalRefs, _max_num_queues);
1093     for (uint i = 0; i < _max_num_queues; i++) {
1094       if (yield->should_return()) {
1095         return;
1096       }
1097       if (preclean_discovered_reflist(_discoveredFinalRefs[i], is_alive,
1098                                       keep_alive, complete_gc, yield)) {
1099         log_reflist("FinalRef abort: ", _discoveredFinalRefs, _max_num_queues);
1100         return;
1101       }
1102     }
1103     log_reflist("FinalRef after: ", _discoveredFinalRefs, _max_num_queues);
1104   }
1105 
1106   // Phantom references
1107   {
1108     GCTraceTime(Debug, gc, ref) tm("Preclean PhantomReferences", gc_timer);
1109     log_reflist("PhantomRef before: ", _discoveredPhantomRefs, _max_num_queues);
1110     for (uint i = 0; i < _max_num_queues; i++) {
1111       if (yield->should_return()) {
1112         return;
1113       }
1114       if (preclean_discovered_reflist(_discoveredPhantomRefs[i], is_alive,
1115                                       keep_alive, complete_gc, yield)) {
1116         log_reflist("PhantomRef abort: ", _discoveredPhantomRefs, _max_num_queues);
1117         return;
1118       }
1119     }
1120     log_reflist("PhantomRef after: ", _discoveredPhantomRefs, _max_num_queues);
1121   }
1122 }
1123 
1124 // Walk the given discovered ref list, and remove all reference objects
1125 // whose referents are still alive, whose referents are NULL or which
1126 // are not active (have a non-NULL next field). NOTE: When we are
1127 // thus precleaning the ref lists (which happens single-threaded today),
1128 // we do not disable refs discovery to honor the correct semantics of
1129 // java.lang.Reference. As a result, we need to be careful below
1130 // that ref removal steps interleave safely with ref discovery steps
1131 // (in this thread).
1132 bool ReferenceProcessor::preclean_discovered_reflist(DiscoveredList&    refs_list,
1133                                                      BoolObjectClosure* is_alive,
1134                                                      OopClosure*        keep_alive,
1135                                                      VoidClosure*       complete_gc,
1136                                                      YieldClosure*      yield) {
1137   DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
1138   while (iter.has_next()) {
1139     if (yield->should_return_fine_grain()) {
1140       return true;
1141     }
1142     iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
1143     oop obj = iter.obj();
1144     oop next = java_lang_ref_Reference::next(obj);
1145     if (iter.referent() == NULL || iter.is_referent_alive() || next != NULL) {
1146       // The referent has been cleared, or is alive, or the Reference is not
1147       // active; we need to trace and mark its cohort.
1148       log_develop_trace(gc, ref)("Precleaning Reference (" INTPTR_FORMAT ": %s)",
1149                                  p2i(iter.obj()), iter.obj()->klass()->internal_name());
1150       // Remove Reference object from list
1151       iter.remove();
1152       // Keep alive its cohort.
1153       iter.make_referent_alive();
1154       if (UseCompressedOops) {
1155         narrowOop* next_addr = (narrowOop*)java_lang_ref_Reference::next_addr_raw(obj);
1156         keep_alive->do_oop(next_addr);
1157       } else {
1158         oop* next_addr = (oop*)java_lang_ref_Reference::next_addr_raw(obj);
1159         keep_alive->do_oop(next_addr);
1160       }
1161       iter.move_to_next();
1162     } else {
1163       iter.next();
1164     }
1165   }
1166   // Close the reachable set
1167   complete_gc->do_void();
1168 
1169   NOT_PRODUCT(
1170     if (iter.processed() > 0) {
1171       log_develop_trace(gc, ref)(" Dropped " SIZE_FORMAT " Refs out of " SIZE_FORMAT " Refs in discovered list " INTPTR_FORMAT,
1172         iter.removed(), iter.processed(), p2i(&refs_list));
1173     }
1174   )
1175   return false;
1176 }
1177 
1178 const char* ReferenceProcessor::list_name(uint i) {
1179    assert(i <= _max_num_queues * number_of_subclasses_of_ref(),
1180           "Out of bounds index");
1181 
1182    int j = i / _max_num_queues;
1183    switch (j) {
1184      case 0: return "SoftRef";
1185      case 1: return "WeakRef";
1186      case 2: return "FinalRef";
1187      case 3: return "PhantomRef";
1188    }
1189    ShouldNotReachHere();
1190    return NULL;
1191 }