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