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