referenceProcessor.cpp 52.5 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
19 20 21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
22 23 24
 *
 */

25 26 27
#include "precompiled.hpp"
#include "classfile/javaClasses.hpp"
#include "classfile/systemDictionary.hpp"
S
sla 已提交
28 29
#include "gc_implementation/shared/gcTimer.hpp"
#include "gc_implementation/shared/gcTraceTime.hpp"
30 31 32 33 34 35 36
#include "gc_interface/collectedHeap.hpp"
#include "gc_interface/collectedHeap.inline.hpp"
#include "memory/referencePolicy.hpp"
#include "memory/referenceProcessor.hpp"
#include "oops/oop.inline.hpp"
#include "runtime/java.hpp"
#include "runtime/jniHandles.hpp"
D
duke 已提交
37

38 39
PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC

40 41
ReferencePolicy* ReferenceProcessor::_always_clear_soft_ref_policy = NULL;
ReferencePolicy* ReferenceProcessor::_default_soft_ref_policy      = NULL;
42
bool             ReferenceProcessor::_pending_list_uses_discovered_field = false;
43
jlong            ReferenceProcessor::_soft_ref_timestamp_clock = 0;
44

D
duke 已提交
45 46 47 48 49
void referenceProcessor_init() {
  ReferenceProcessor::init_statics();
}

void ReferenceProcessor::init_statics() {
50 51 52
  // We need a monotonically non-deccreasing time in ms but
  // os::javaTimeMillis() does not guarantee monotonicity.
  jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
53 54 55 56 57

  // Initialize the soft ref timestamp clock.
  _soft_ref_timestamp_clock = now;
  // Also update the soft ref clock in j.l.r.SoftReference
  java_lang_ref_SoftReference::set_clock(_soft_ref_timestamp_clock);
D
duke 已提交
58

59 60 61 62 63 64
  _always_clear_soft_ref_policy = new AlwaysClearPolicy();
  _default_soft_ref_policy      = new COMPILER2_PRESENT(LRUMaxHeapPolicy())
                                      NOT_COMPILER2(LRUCurrentHeapPolicy());
  if (_always_clear_soft_ref_policy == NULL || _default_soft_ref_policy == NULL) {
    vm_exit_during_initialization("Could not allocate reference policy object");
  }
D
duke 已提交
65 66 67
  guarantee(RefDiscoveryPolicy == ReferenceBasedDiscovery ||
            RefDiscoveryPolicy == ReferentBasedDiscovery,
            "Unrecongnized RefDiscoveryPolicy");
68
  _pending_list_uses_discovered_field = JDK_Version::current().pending_list_uses_discovered_field();
D
duke 已提交
69 70
}

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
void ReferenceProcessor::enable_discovery(bool verify_disabled, bool check_no_refs) {
#ifdef ASSERT
  // Verify that we're not currently discovering refs
  assert(!verify_disabled || !_discovering_refs, "nested call?");

  if (check_no_refs) {
    // Verify that the discovered lists are empty
    verify_no_references_recorded();
  }
#endif // ASSERT

  // Someone could have modified the value of the static
  // field in the j.l.r.SoftReference class that holds the
  // soft reference timestamp clock using reflection or
  // Unsafe between GCs. Unconditionally update the static
  // field in ReferenceProcessor here so that we use the new
  // value during reference discovery.

  _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();
  _discovering_refs = true;
}

D
duke 已提交
93
ReferenceProcessor::ReferenceProcessor(MemRegion span,
94
                                       bool      mt_processing,
95
                                       uint      mt_processing_degree,
96
                                       bool      mt_discovery,
97
                                       uint      mt_discovery_degree,
98
                                       bool      atomic_discovery,
99
                                       BoolObjectClosure* is_alive_non_header)  :
D
duke 已提交
100 101
  _discovering_refs(false),
  _enqueuing_is_done(false),
102
  _is_alive_non_header(is_alive_non_header),
D
duke 已提交
103 104 105 106 107 108
  _processing_is_mt(mt_processing),
  _next_id(0)
{
  _span = span;
  _discovery_is_atomic = atomic_discovery;
  _discovery_is_mt     = mt_discovery;
109
  _num_q               = MAX2(1U, mt_processing_degree);
110
  _max_num_q           = MAX2(_num_q, mt_discovery_degree);
111
  _discovered_refs     = NEW_C_HEAP_ARRAY(DiscoveredList,
Z
zgu 已提交
112 113
            _max_num_q * number_of_subclasses_of_ref(), mtGC);

114
  if (_discovered_refs == NULL) {
D
duke 已提交
115 116
    vm_exit_during_initialization("Could not allocated RefProc Array");
  }
117
  _discoveredSoftRefs    = &_discovered_refs[0];
118 119 120
  _discoveredWeakRefs    = &_discoveredSoftRefs[_max_num_q];
  _discoveredFinalRefs   = &_discoveredWeakRefs[_max_num_q];
  _discoveredPhantomRefs = &_discoveredFinalRefs[_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 125
    _discovered_refs[i].set_head(NULL);
    _discovered_refs[i].set_length(0);
D
duke 已提交
126
  }
127

128
  setup_policy(false /* default soft ref policy */);
D
duke 已提交
129 130 131 132 133
}

#ifndef PRODUCT
void ReferenceProcessor::verify_no_references_recorded() {
  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(),
D
duke 已提交
136 137 138 139 140 141
              "Found non-empty discovered list");
  }
}
#endif

void 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
    }
D
duke 已提交
148 149 150
  }
}

151
void ReferenceProcessor::update_soft_ref_master_clock() {
D
duke 已提交
152 153
  // Update (advance) the soft ref master clock field. This must be done
  // after processing the soft ref list.
154 155 156 157

  // We need a monotonically non-deccreasing time in ms but
  // os::javaTimeMillis() does not guarantee monotonicity.
  jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
158 159 160
  jlong soft_ref_clock = java_lang_ref_SoftReference::clock();
  assert(soft_ref_clock == _soft_ref_timestamp_clock, "soft ref clocks out of sync");

D
duke 已提交
161
  NOT_PRODUCT(
162 163 164
  if (now < _soft_ref_timestamp_clock) {
    warning("time warp: "INT64_FORMAT" to "INT64_FORMAT,
            _soft_ref_timestamp_clock, now);
D
duke 已提交
165 166
  }
  )
167 168 169 170 171
  // The values of now and _soft_ref_timestamp_clock are set using
  // javaTimeNanos(), which is guaranteed to be monotonically
  // non-decreasing provided the underlying platform provides such
  // a time source (and it is bug free).
  // In product mode, however, protect ourselves from non-monotonicty.
172 173
  if (now > _soft_ref_timestamp_clock) {
    _soft_ref_timestamp_clock = now;
D
duke 已提交
174 175 176 177 178 179
    java_lang_ref_SoftReference::set_clock(now);
  }
  // Else leave clock stalled at its old value until time progresses
  // past clock value.
}

S
sla 已提交
180 181 182 183 184 185 186 187 188
size_t ReferenceProcessor::total_count(DiscoveredList lists[]) {
  size_t total = 0;
  for (uint i = 0; i < _max_num_q; ++i) {
    total += lists[i].length();
  }
  return total;
}

ReferenceProcessorStats ReferenceProcessor::process_discovered_references(
D
duke 已提交
189 190 191
  BoolObjectClosure*           is_alive,
  OopClosure*                  keep_alive,
  VoidClosure*                 complete_gc,
S
sla 已提交
192 193
  AbstractRefProcTaskExecutor* task_executor,
  GCTimer*                     gc_timer) {
D
duke 已提交
194 195 196 197 198 199
  NOT_PRODUCT(verify_ok_to_handle_reflists());

  assert(!enqueuing_is_done(), "If here enqueuing should not be complete");
  // Stop treating discovered references specially.
  disable_discovery();

200 201 202 203 204 205 206 207 208 209
  // If discovery was concurrent, someone could have modified
  // the value of the static field in the j.l.r.SoftReference
  // class that holds the soft reference timestamp clock using
  // reflection or Unsafe between when discovery was enabled and
  // now. Unconditionally update the static field in ReferenceProcessor
  // here so that we use the new value during processing of the
  // discovered soft refs.

  _soft_ref_timestamp_clock = java_lang_ref_SoftReference::clock();

D
duke 已提交
210
  bool trace_time = PrintGCDetails && PrintReferenceGC;
S
sla 已提交
211

D
duke 已提交
212
  // Soft references
S
sla 已提交
213
  size_t soft_count = 0;
D
duke 已提交
214
  {
S
sla 已提交
215 216 217 218
    GCTraceTime tt("SoftReference", trace_time, false, gc_timer);
    soft_count =
      process_discovered_reflist(_discoveredSoftRefs, _current_soft_ref_policy, true,
                                 is_alive, keep_alive, complete_gc, task_executor);
D
duke 已提交
219 220 221 222 223
  }

  update_soft_ref_master_clock();

  // Weak references
S
sla 已提交
224
  size_t weak_count = 0;
D
duke 已提交
225
  {
S
sla 已提交
226 227 228 229
    GCTraceTime tt("WeakReference", trace_time, false, gc_timer);
    weak_count =
      process_discovered_reflist(_discoveredWeakRefs, NULL, true,
                                 is_alive, keep_alive, complete_gc, task_executor);
D
duke 已提交
230 231 232
  }

  // Final references
S
sla 已提交
233
  size_t final_count = 0;
D
duke 已提交
234
  {
S
sla 已提交
235 236 237 238
    GCTraceTime tt("FinalReference", trace_time, false, gc_timer);
    final_count =
      process_discovered_reflist(_discoveredFinalRefs, NULL, false,
                                 is_alive, keep_alive, complete_gc, task_executor);
D
duke 已提交
239 240 241
  }

  // Phantom references
S
sla 已提交
242
  size_t phantom_count = 0;
D
duke 已提交
243
  {
S
sla 已提交
244 245 246 247
    GCTraceTime tt("PhantomReference", trace_time, false, gc_timer);
    phantom_count =
      process_discovered_reflist(_discoveredPhantomRefs, NULL, false,
                                 is_alive, keep_alive, complete_gc, task_executor);
D
duke 已提交
248 249 250 251 252 253 254 255
  }

  // Weak global JNI references. It would make more sense (semantically) to
  // traverse these simultaneously with the regular weak references above, but
  // that is not how the JDK1.2 specification is. See #4126360. Native code can
  // thus use JNI weak references to circumvent the phantom references and
  // resurrect a "post-mortem" object.
  {
S
sla 已提交
256
    GCTraceTime tt("JNI Weak Reference", trace_time, false, gc_timer);
D
duke 已提交
257 258 259 260 261
    if (task_executor != NULL) {
      task_executor->set_single_threaded_mode();
    }
    process_phaseJNI(is_alive, keep_alive, complete_gc);
  }
S
sla 已提交
262 263

  return ReferenceProcessorStats(soft_count, weak_count, final_count, phantom_count);
D
duke 已提交
264 265 266 267
}

#ifndef PRODUCT
// Calculate the number of jni handles.
268
uint ReferenceProcessor::count_jni_refs() {
D
duke 已提交
269 270
  class AlwaysAliveClosure: public BoolObjectClosure {
  public:
271
    virtual bool do_object_b(oop obj) { return true; }
D
duke 已提交
272 273 274 275 276 277 278
  };

  class CountHandleClosure: public OopClosure {
  private:
    int _count;
  public:
    CountHandleClosure(): _count(0) {}
279 280
    void do_oop(oop* unused)       { _count++; }
    void do_oop(narrowOop* unused) { ShouldNotReachHere(); }
D
duke 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
    int count() { return _count; }
  };
  CountHandleClosure global_handle_count;
  AlwaysAliveClosure always_alive;
  JNIHandles::weak_oops_do(&always_alive, &global_handle_count);
  return global_handle_count.count();
}
#endif

void ReferenceProcessor::process_phaseJNI(BoolObjectClosure* is_alive,
                                          OopClosure*        keep_alive,
                                          VoidClosure*       complete_gc) {
#ifndef PRODUCT
  if (PrintGCDetails && PrintReferenceGC) {
    unsigned int count = count_jni_refs();
    gclog_or_tty->print(", %u refs", count);
  }
#endif
  JNIHandles::weak_oops_do(is_alive, keep_alive);
  complete_gc->do_void();
}

303 304

template <class T>
305 306
bool enqueue_discovered_ref_helper(ReferenceProcessor* ref,
                                   AbstractRefProcTaskExecutor* task_executor) {
307

D
duke 已提交
308
  // Remember old value of pending references list
309 310
  T* pending_list_addr = (T*)java_lang_ref_Reference::pending_list_addr();
  T old_pending_list_value = *pending_list_addr;
D
duke 已提交
311 312 313

  // Enqueue references that are not made active again, and
  // clear the decks for the next collection (cycle).
314
  ref->enqueue_discovered_reflists((HeapWord*)pending_list_addr, task_executor);
315 316 317
  // Do the post-barrier on pending_list_addr missed in
  // enqueue_discovered_reflist.
  oopDesc::bs()->write_ref_field(pending_list_addr, oopDesc::load_decode_heap_oop(pending_list_addr));
D
duke 已提交
318 319

  // Stop treating discovered references specially.
320
  ref->disable_discovery();
D
duke 已提交
321 322 323 324 325

  // Return true if new pending references were added
  return old_pending_list_value != *pending_list_addr;
}

326 327 328 329 330 331 332 333 334
bool ReferenceProcessor::enqueue_discovered_references(AbstractRefProcTaskExecutor* task_executor) {
  NOT_PRODUCT(verify_ok_to_handle_reflists());
  if (UseCompressedOops) {
    return enqueue_discovered_ref_helper<narrowOop>(this, task_executor);
  } else {
    return enqueue_discovered_ref_helper<oop>(this, task_executor);
  }
}

D
duke 已提交
335
void ReferenceProcessor::enqueue_discovered_reflist(DiscoveredList& refs_list,
336
                                                    HeapWord* pending_list_addr) {
D
duke 已提交
337
  // Given a list of refs linked through the "discovered" field
338 339 340
  // (java.lang.ref.Reference.discovered), self-loop their "next" field
  // thus distinguishing them from active References, then
  // prepend them to the pending list.
341 342 343 344 345 346 347 348 349
  //
  // The Java threads will see the Reference objects linked together through
  // the discovered field. Instead of trying to do the write barrier updates
  // in all places in the reference processor where we manipulate the discovered
  // field we make sure to do the barrier here where we anyway iterate through
  // all linked Reference objects. Note that it is important to not dirty any
  // cards during reference processing since this will cause card table
  // verification to fail for G1.
  //
350 351 352
  // BKWRD COMPATIBILITY NOTE: For older JDKs (prior to the fix for 4956777),
  // the "next" field is used to chain the pending list, not the discovered
  // field.
D
duke 已提交
353 354 355 356
  if (TraceReferenceGC && PrintGCDetails) {
    gclog_or_tty->print_cr("ReferenceProcessor::enqueue_discovered_reflist list "
                           INTPTR_FORMAT, (address)refs_list.head());
  }
357 358

  oop obj = NULL;
359
  oop next_d = refs_list.head();
360
  if (pending_list_uses_discovered_field()) { // New behavior
361 362 363 364 365 366 367 368
    // Walk down the list, self-looping the next field
    // so that the References are not considered active.
    while (obj != next_d) {
      obj = next_d;
      assert(obj->is_instanceRef(), "should be reference object");
      next_d = java_lang_ref_Reference::discovered(obj);
      if (TraceReferenceGC && PrintGCDetails) {
        gclog_or_tty->print_cr("        obj " INTPTR_FORMAT "/next_d " INTPTR_FORMAT,
369
                               (void *)obj, (void *)next_d);
370 371 372 373
      }
      assert(java_lang_ref_Reference::next(obj) == NULL,
             "Reference not active; should not be discovered");
      // Self-loop next, so as to make Ref not active.
374
      java_lang_ref_Reference::set_next_raw(obj, obj);
375 376 377 378 379
      if (next_d != obj) {
        oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), next_d);
      } else {
        // This is the last object.
        // Swap refs_list into pending_list_addr and
380 381
        // set obj's discovered to what we read from pending_list_addr.
        oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr);
382
        // Need post-barrier on pending_list_addr. See enqueue_discovered_ref_helper() above.
383 384
        java_lang_ref_Reference::set_discovered_raw(obj, old); // old may be NULL
        oopDesc::bs()->write_ref_field(java_lang_ref_Reference::discovered_addr(obj), old);
385
      }
D
duke 已提交
386
    }
387 388 389 390 391 392 393 394 395
  } else { // Old behaviour
    // Walk down the list, copying the discovered field into
    // the next field and clearing the discovered field.
    while (obj != next_d) {
      obj = next_d;
      assert(obj->is_instanceRef(), "should be reference object");
      next_d = java_lang_ref_Reference::discovered(obj);
      if (TraceReferenceGC && PrintGCDetails) {
        gclog_or_tty->print_cr("        obj " INTPTR_FORMAT "/next_d " INTPTR_FORMAT,
396
                               (void *)obj, (void *)next_d);
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
      }
      assert(java_lang_ref_Reference::next(obj) == NULL,
             "The reference should not be enqueued");
      if (next_d == obj) {  // obj is last
        // Swap refs_list into pendling_list_addr and
        // set obj's next to what we read from pending_list_addr.
        oop old = oopDesc::atomic_exchange_oop(refs_list.head(), pending_list_addr);
        // Need oop_check on pending_list_addr above;
        // see special oop-check code at the end of
        // enqueue_discovered_reflists() further below.
        if (old == NULL) {
          // obj should be made to point to itself, since
          // pending list was empty.
          java_lang_ref_Reference::set_next(obj, obj);
        } else {
          java_lang_ref_Reference::set_next(obj, old);
        }
D
duke 已提交
414
      } else {
415
        java_lang_ref_Reference::set_next(obj, next_d);
D
duke 已提交
416
      }
417
      java_lang_ref_Reference::set_discovered(obj, (oop) NULL);
D
duke 已提交
418 419 420 421 422 423 424 425 426
    }
  }
}

// Parallel enqueue task
class RefProcEnqueueTask: public AbstractRefProcTaskExecutor::EnqueueTask {
public:
  RefProcEnqueueTask(ReferenceProcessor& ref_processor,
                     DiscoveredList      discovered_refs[],
427
                     HeapWord*           pending_list_addr,
D
duke 已提交
428 429
                     int                 n_queues)
    : EnqueueTask(ref_processor, discovered_refs,
430
                  pending_list_addr, n_queues)
D
duke 已提交
431 432
  { }

433
  virtual void work(unsigned int work_id) {
434
    assert(work_id < (unsigned int)_ref_processor.max_num_q(), "Index out-of-bounds");
D
duke 已提交
435 436
    // Simplest first cut: static partitioning.
    int index = work_id;
437 438 439
    // The increment on "index" must correspond to the maximum number of queues
    // (n_queues) with which that ReferenceProcessor was created.  That
    // is because of the "clever" way the discovered references lists were
440 441
    // allocated and are indexed into.
    assert(_n_queues == (int) _ref_processor.max_num_q(), "Different number not expected");
442
    for (int j = 0;
443
         j < ReferenceProcessor::number_of_subclasses_of_ref();
444
         j++, index += _n_queues) {
D
duke 已提交
445 446
      _ref_processor.enqueue_discovered_reflist(
        _refs_lists[index], _pending_list_addr);
447
      _refs_lists[index].set_head(NULL);
D
duke 已提交
448 449 450 451 452 453
      _refs_lists[index].set_length(0);
    }
  }
};

// Enqueue references that are not made active again
454
void ReferenceProcessor::enqueue_discovered_reflists(HeapWord* pending_list_addr,
D
duke 已提交
455 456 457
  AbstractRefProcTaskExecutor* task_executor) {
  if (_processing_is_mt && task_executor != NULL) {
    // Parallel code
458
    RefProcEnqueueTask tsk(*this, _discovered_refs,
459
                           pending_list_addr, _max_num_q);
D
duke 已提交
460 461 462
    task_executor->execute(tsk);
  } else {
    // Serial code: call the parent class's implementation
463
    for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
464 465 466
      enqueue_discovered_reflist(_discovered_refs[i], pending_list_addr);
      _discovered_refs[i].set_head(NULL);
      _discovered_refs[i].set_length(0);
D
duke 已提交
467 468 469 470
    }
  }
}

471
void DiscoveredListIterator::load_ptrs(DEBUG_ONLY(bool allow_null_referent)) {
D
duke 已提交
472
  _discovered_addr = java_lang_ref_Reference::discovered_addr(_ref);
473 474
  oop discovered = java_lang_ref_Reference::discovered(_ref);
  assert(_discovered_addr && discovered->is_oop_or_null(),
D
duke 已提交
475
         "discovered field is bad");
476
  _next = discovered;
D
duke 已提交
477
  _referent_addr = java_lang_ref_Reference::referent_addr(_ref);
478
  _referent = java_lang_ref_Reference::referent(_ref);
D
duke 已提交
479 480 481 482 483 484 485 486
  assert(Universe::heap()->is_in_reserved_or_null(_referent),
         "Wrong oop found in java.lang.Reference object");
  assert(allow_null_referent ?
             _referent->is_oop_or_null()
           : _referent->is_oop(),
         "bad referent");
}

487
void DiscoveredListIterator::remove() {
D
duke 已提交
488
  assert(_ref->is_oop(), "Dropping a bad reference");
489
  oop_store_raw(_discovered_addr, NULL);
490

491
  // First _prev_next ref actually points into DiscoveredList (gross).
492 493 494 495 496 497 498 499 500
  oop new_next;
  if (_next == _ref) {
    // At the end of the list, we should make _prev point to itself.
    // If _ref is the first ref, then _prev_next will be in the DiscoveredList,
    // and _prev will be NULL.
    new_next = _prev;
  } else {
    new_next = _next;
  }
501 502 503 504
  // Remove Reference object from discovered list. Note that G1 does not need a
  // pre-barrier here because we know the Reference has already been found/marked,
  // that's how it ended up in the discovered list in the first place.
  oop_store_raw(_prev_next, new_next);
D
duke 已提交
505
  NOT_PRODUCT(_removed++);
506
  _refs_list.dec_length(1);
D
duke 已提交
507 508
}

509 510
// Make the Reference object active again.
void DiscoveredListIterator::make_active() {
511 512 513
  // The pre barrier for G1 is probably just needed for the old
  // reference processing behavior. Should we guard this with
  // ReferenceProcessor::pending_list_uses_discovered_field() ?
514 515 516
  if (UseG1GC) {
    HeapWord* next_addr = java_lang_ref_Reference::next_addr(_ref);
    if (UseCompressedOops) {
517
      oopDesc::bs()->write_ref_field_pre((narrowOop*)next_addr, NULL);
518
    } else {
519
      oopDesc::bs()->write_ref_field_pre((oop*)next_addr, NULL);
520
    }
521
  }
522
  java_lang_ref_Reference::set_next_raw(_ref, NULL);
523 524 525 526
}

void DiscoveredListIterator::clear_referent() {
  oop_store_raw(_referent_addr, NULL);
D
duke 已提交
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
}

// NOTE: process_phase*() are largely similar, and at a high level
// merely iterate over the extant list applying a predicate to
// each of its elements and possibly removing that element from the
// list and applying some further closures to that element.
// We should consider the possibility of replacing these
// process_phase*() methods by abstracting them into
// a single general iterator invocation that receives appropriate
// closures that accomplish this work.

// (SoftReferences only) Traverse the list and remove any SoftReferences whose
// referents are not alive, but that should be kept alive for policy reasons.
// Keep alive the transitive closure of all such referents.
void
542
ReferenceProcessor::process_phase1(DiscoveredList&    refs_list,
D
duke 已提交
543 544 545 546 547
                                   ReferencePolicy*   policy,
                                   BoolObjectClosure* is_alive,
                                   OopClosure*        keep_alive,
                                   VoidClosure*       complete_gc) {
  assert(policy != NULL, "Must have a non-NULL policy");
548
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
549 550 551 552
  // Decide which softly reachable refs should be kept alive.
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(!discovery_is_atomic() /* allow_null_referent */));
    bool referent_is_dead = (iter.referent() != NULL) && !iter.is_referent_alive();
553 554
    if (referent_is_dead &&
        !policy->should_clear_reference(iter.obj(), _soft_ref_timestamp_clock)) {
D
duke 已提交
555 556
      if (TraceReferenceGC) {
        gclog_or_tty->print_cr("Dropping reference (" INTPTR_FORMAT ": %s"  ") by policy",
557
                               (void *)iter.obj(), iter.obj()->klass()->internal_name());
D
duke 已提交
558
      }
559 560
      // Remove Reference object from list
      iter.remove();
D
duke 已提交
561 562 563 564
      // Make the Reference object active again
      iter.make_active();
      // keep the referent around
      iter.make_referent_alive();
565
      iter.move_to_next();
D
duke 已提交
566 567 568 569 570 571 572 573
    } else {
      iter.next();
    }
  }
  // Close the reachable set
  complete_gc->do_void();
  NOT_PRODUCT(
    if (PrintGCDetails && TraceReferenceGC) {
574
      gclog_or_tty->print_cr(" Dropped %d dead Refs out of %d "
575
        "discovered Refs by policy, from list " INTPTR_FORMAT,
576
        iter.removed(), iter.processed(), (address)refs_list.head());
D
duke 已提交
577 578 579 580 581 582 583
    }
  )
}

// Traverse the list and remove any Refs that are not active, or
// whose referents are either alive or NULL.
void
584
ReferenceProcessor::pp2_work(DiscoveredList&    refs_list,
D
duke 已提交
585
                             BoolObjectClosure* is_alive,
586
                             OopClosure*        keep_alive) {
D
duke 已提交
587
  assert(discovery_is_atomic(), "Error");
588
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
589 590
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
591 592
    DEBUG_ONLY(oop next = java_lang_ref_Reference::next(iter.obj());)
    assert(next == NULL, "Should not discover inactive Reference");
D
duke 已提交
593 594 595
    if (iter.is_referent_alive()) {
      if (TraceReferenceGC) {
        gclog_or_tty->print_cr("Dropping strongly reachable reference (" INTPTR_FORMAT ": %s)",
596
                               (void *)iter.obj(), iter.obj()->klass()->internal_name());
D
duke 已提交
597 598
      }
      // The referent is reachable after all.
599 600
      // Remove Reference object from list.
      iter.remove();
D
duke 已提交
601 602 603 604
      // Update the referent pointer as necessary: Note that this
      // should not entail any recursive marking because the
      // referent must already have been traversed.
      iter.make_referent_alive();
605
      iter.move_to_next();
D
duke 已提交
606 607 608 609 610
    } else {
      iter.next();
    }
  }
  NOT_PRODUCT(
611
    if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
612 613 614
      gclog_or_tty->print_cr(" Dropped %d active Refs out of %d "
        "Refs in discovered list " INTPTR_FORMAT,
        iter.removed(), iter.processed(), (address)refs_list.head());
D
duke 已提交
615 616 617 618 619
    }
  )
}

void
620 621 622 623
ReferenceProcessor::pp2_work_concurrent_discovery(DiscoveredList&    refs_list,
                                                  BoolObjectClosure* is_alive,
                                                  OopClosure*        keep_alive,
                                                  VoidClosure*       complete_gc) {
D
duke 已提交
624
  assert(!discovery_is_atomic(), "Error");
625
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
626 627
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
628 629
    HeapWord* next_addr = java_lang_ref_Reference::next_addr(iter.obj());
    oop next = java_lang_ref_Reference::next(iter.obj());
D
duke 已提交
630
    if ((iter.referent() == NULL || iter.is_referent_alive() ||
631 632
         next != NULL)) {
      assert(next->is_oop_or_null(), "bad next field");
D
duke 已提交
633 634 635 636
      // Remove Reference object from list
      iter.remove();
      // Trace the cohorts
      iter.make_referent_alive();
637 638 639 640 641
      if (UseCompressedOops) {
        keep_alive->do_oop((narrowOop*)next_addr);
      } else {
        keep_alive->do_oop((oop*)next_addr);
      }
642
      iter.move_to_next();
D
duke 已提交
643 644 645 646 647 648 649
    } else {
      iter.next();
    }
  }
  // Now close the newly reachable set
  complete_gc->do_void();
  NOT_PRODUCT(
650
    if (PrintGCDetails && TraceReferenceGC && (iter.processed() > 0)) {
651 652 653
      gclog_or_tty->print_cr(" Dropped %d active Refs out of %d "
        "Refs in discovered list " INTPTR_FORMAT,
        iter.removed(), iter.processed(), (address)refs_list.head());
D
duke 已提交
654 655 656 657 658
    }
  )
}

// Traverse the list and process the referents, by either
659
// clearing them or keeping them (and their reachable
D
duke 已提交
660 661
// closure) alive.
void
662
ReferenceProcessor::process_phase3(DiscoveredList&    refs_list,
D
duke 已提交
663 664 665 666
                                   bool               clear_referent,
                                   BoolObjectClosure* is_alive,
                                   OopClosure*        keep_alive,
                                   VoidClosure*       complete_gc) {
667
  ResourceMark rm;
668
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
669 670 671 672 673 674 675 676 677 678 679 680 681
  while (iter.has_next()) {
    iter.update_discovered();
    iter.load_ptrs(DEBUG_ONLY(false /* allow_null_referent */));
    if (clear_referent) {
      // NULL out referent pointer
      iter.clear_referent();
    } else {
      // keep the referent around
      iter.make_referent_alive();
    }
    if (TraceReferenceGC) {
      gclog_or_tty->print_cr("Adding %sreference (" INTPTR_FORMAT ": %s) as pending",
                             clear_referent ? "cleared " : "",
682
                             (void *)iter.obj(), iter.obj()->klass()->internal_name());
D
duke 已提交
683 684 685 686
    }
    assert(iter.obj()->is_oop(UseConcMarkSweepGC), "Adding a bad reference");
    iter.next();
  }
687
  // Remember to update the next pointer of the last ref.
D
duke 已提交
688 689 690 691 692 693
  iter.update_discovered();
  // Close the reachable set
  complete_gc->do_void();
}

void
694 695 696 697 698 699
ReferenceProcessor::clear_discovered_references(DiscoveredList& refs_list) {
  oop obj = NULL;
  oop next = refs_list.head();
  while (next != obj) {
    obj = next;
    next = java_lang_ref_Reference::discovered(obj);
700 701
    java_lang_ref_Reference::set_discovered_raw(obj, NULL);
  }
702
  refs_list.set_head(NULL);
703
  refs_list.set_length(0);
D
duke 已提交
704 705
}

706 707 708 709 710
void
ReferenceProcessor::abandon_partial_discovered_list(DiscoveredList& refs_list) {
  clear_discovered_references(refs_list);
}

711 712
void ReferenceProcessor::abandon_partial_discovery() {
  // loop over the lists
713
  for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
714
    if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
715
      gclog_or_tty->print_cr("\nAbandoning %s discovered list", list_name(i));
716
    }
717
    abandon_partial_discovered_list(_discovered_refs[i]);
D
duke 已提交
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
  }
}

class RefProcPhase1Task: public AbstractRefProcTaskExecutor::ProcessTask {
public:
  RefProcPhase1Task(ReferenceProcessor& ref_processor,
                    DiscoveredList      refs_lists[],
                    ReferencePolicy*    policy,
                    bool                marks_oops_alive)
    : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
      _policy(policy)
  { }
  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
                    OopClosure& keep_alive,
                    VoidClosure& complete_gc)
  {
734 735 736
    Thread* thr = Thread::current();
    int refs_list_index = ((WorkerThread*)thr)->id();
    _ref_processor.process_phase1(_refs_lists[refs_list_index], _policy,
D
duke 已提交
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771
                                  &is_alive, &keep_alive, &complete_gc);
  }
private:
  ReferencePolicy* _policy;
};

class RefProcPhase2Task: public AbstractRefProcTaskExecutor::ProcessTask {
public:
  RefProcPhase2Task(ReferenceProcessor& ref_processor,
                    DiscoveredList      refs_lists[],
                    bool                marks_oops_alive)
    : ProcessTask(ref_processor, refs_lists, marks_oops_alive)
  { }
  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
                    OopClosure& keep_alive,
                    VoidClosure& complete_gc)
  {
    _ref_processor.process_phase2(_refs_lists[i],
                                  &is_alive, &keep_alive, &complete_gc);
  }
};

class RefProcPhase3Task: public AbstractRefProcTaskExecutor::ProcessTask {
public:
  RefProcPhase3Task(ReferenceProcessor& ref_processor,
                    DiscoveredList      refs_lists[],
                    bool                clear_referent,
                    bool                marks_oops_alive)
    : ProcessTask(ref_processor, refs_lists, marks_oops_alive),
      _clear_referent(clear_referent)
  { }
  virtual void work(unsigned int i, BoolObjectClosure& is_alive,
                    OopClosure& keep_alive,
                    VoidClosure& complete_gc)
  {
772 773 774 775 776
    // Don't use "refs_list_index" calculated in this way because
    // balance_queues() has moved the Ref's into the first n queues.
    // Thread* thr = Thread::current();
    // int refs_list_index = ((WorkerThread*)thr)->id();
    // _ref_processor.process_phase3(_refs_lists[refs_list_index], _clear_referent,
D
duke 已提交
777 778 779 780 781 782 783 784
    _ref_processor.process_phase3(_refs_lists[i], _clear_referent,
                                  &is_alive, &keep_alive, &complete_gc);
  }
private:
  bool _clear_referent;
};

// Balances reference queues.
785 786 787
// Move entries from all queues[0, 1, ..., _max_num_q-1] to
// queues[0, 1, ..., _num_q-1] because only the first _num_q
// corresponding to the active workers will be processed.
D
duke 已提交
788 789 790 791
void ReferenceProcessor::balance_queues(DiscoveredList ref_lists[])
{
  // calculate total length
  size_t total_refs = 0;
792 793 794 795
  if (TraceReferenceGC && PrintGCDetails) {
    gclog_or_tty->print_cr("\nBalance ref_lists ");
  }

796
  for (uint i = 0; i < _max_num_q; ++i) {
D
duke 已提交
797
    total_refs += ref_lists[i].length();
798 799 800 801 802 803
    if (TraceReferenceGC && PrintGCDetails) {
      gclog_or_tty->print("%d ", ref_lists[i].length());
    }
  }
  if (TraceReferenceGC && PrintGCDetails) {
    gclog_or_tty->print_cr(" = %d", total_refs);
D
duke 已提交
804 805
  }
  size_t avg_refs = total_refs / _num_q + 1;
806 807
  uint to_idx = 0;
  for (uint from_idx = 0; from_idx < _max_num_q; from_idx++) {
808 809 810 811 812 813
    bool move_all = false;
    if (from_idx >= _num_q) {
      move_all = ref_lists[from_idx].length() > 0;
    }
    while ((ref_lists[from_idx].length() > avg_refs) ||
           move_all) {
D
duke 已提交
814 815 816
      assert(to_idx < _num_q, "Sanity Check!");
      if (ref_lists[to_idx].length() < avg_refs) {
        // move superfluous refs
817 818 819 820 821 822 823 824 825
        size_t refs_to_move;
        // Move all the Ref's if the from queue will not be processed.
        if (move_all) {
          refs_to_move = MIN2(ref_lists[from_idx].length(),
                              avg_refs - ref_lists[to_idx].length());
        } else {
          refs_to_move = MIN2(ref_lists[from_idx].length() - avg_refs,
                              avg_refs - ref_lists[to_idx].length());
        }
826 827 828

        assert(refs_to_move > 0, "otherwise the code below will fail");

D
duke 已提交
829 830 831 832 833 834
        oop move_head = ref_lists[from_idx].head();
        oop move_tail = move_head;
        oop new_head  = move_head;
        // find an element to split the list on
        for (size_t j = 0; j < refs_to_move; ++j) {
          move_tail = new_head;
835
          new_head = java_lang_ref_Reference::discovered(new_head);
D
duke 已提交
836
        }
837 838 839 840

        // Add the chain to the to list.
        if (ref_lists[to_idx].head() == NULL) {
          // to list is empty. Make a loop at the end.
841
          java_lang_ref_Reference::set_discovered_raw(move_tail, move_tail);
842
        } else {
843
          java_lang_ref_Reference::set_discovered_raw(move_tail, ref_lists[to_idx].head());
844
        }
D
duke 已提交
845
        ref_lists[to_idx].set_head(move_head);
846
        ref_lists[to_idx].inc_length(refs_to_move);
847 848 849 850 851 852 853 854

        // Remove the chain from the from list.
        if (move_tail == new_head) {
          // We found the end of the from list.
          ref_lists[from_idx].set_head(NULL);
        } else {
          ref_lists[from_idx].set_head(new_head);
        }
855
        ref_lists[from_idx].dec_length(refs_to_move);
856 857 858
        if (ref_lists[from_idx].length() == 0) {
          break;
        }
D
duke 已提交
859
      } else {
860
        to_idx = (to_idx + 1) % _num_q;
D
duke 已提交
861 862 863
      }
    }
  }
864 865
#ifdef ASSERT
  size_t balanced_total_refs = 0;
866
  for (uint i = 0; i < _max_num_q; ++i) {
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
    balanced_total_refs += ref_lists[i].length();
    if (TraceReferenceGC && PrintGCDetails) {
      gclog_or_tty->print("%d ", ref_lists[i].length());
    }
  }
  if (TraceReferenceGC && PrintGCDetails) {
    gclog_or_tty->print_cr(" = %d", balanced_total_refs);
    gclog_or_tty->flush();
  }
  assert(total_refs == balanced_total_refs, "Balancing was incomplete");
#endif
}

void ReferenceProcessor::balance_all_queues() {
  balance_queues(_discoveredSoftRefs);
  balance_queues(_discoveredWeakRefs);
  balance_queues(_discoveredFinalRefs);
  balance_queues(_discoveredPhantomRefs);
D
duke 已提交
885 886
}

S
sla 已提交
887
size_t
D
duke 已提交
888 889 890 891 892 893 894 895 896
ReferenceProcessor::process_discovered_reflist(
  DiscoveredList               refs_lists[],
  ReferencePolicy*             policy,
  bool                         clear_referent,
  BoolObjectClosure*           is_alive,
  OopClosure*                  keep_alive,
  VoidClosure*                 complete_gc,
  AbstractRefProcTaskExecutor* task_executor)
{
897 898 899 900 901 902 903 904 905 906 907
  bool mt_processing = task_executor != NULL && _processing_is_mt;
  // If discovery used MT and a dynamic number of GC threads, then
  // the queues must be balanced for correctness if fewer than the
  // maximum number of queues were used.  The number of queue used
  // during discovery may be different than the number to be used
  // for processing so don't depend of _num_q < _max_num_q as part
  // of the test.
  bool must_balance = _discovery_is_mt;

  if ((mt_processing && ParallelRefProcBalancingEnabled) ||
      must_balance) {
D
duke 已提交
908 909
    balance_queues(refs_lists);
  }
S
sla 已提交
910 911 912

  size_t total_list_count = total_count(refs_lists);

D
duke 已提交
913
  if (PrintReferenceGC && PrintGCDetails) {
S
sla 已提交
914
    gclog_or_tty->print(", %u refs", total_list_count);
D
duke 已提交
915 916 917 918 919 920 921 922
  }

  // Phase 1 (soft refs only):
  // . Traverse the list and remove any SoftReferences whose
  //   referents are not alive, but that should be kept alive for
  //   policy reasons. Keep alive the transitive closure of all
  //   such referents.
  if (policy != NULL) {
923
    if (mt_processing) {
D
duke 已提交
924 925 926
      RefProcPhase1Task phase1(*this, refs_lists, policy, true /*marks_oops_alive*/);
      task_executor->execute(phase1);
    } else {
927
      for (uint i = 0; i < _max_num_q; i++) {
D
duke 已提交
928 929 930 931 932 933 934 935 936 937 938
        process_phase1(refs_lists[i], policy,
                       is_alive, keep_alive, complete_gc);
      }
    }
  } else { // policy == NULL
    assert(refs_lists != _discoveredSoftRefs,
           "Policy must be specified for soft references.");
  }

  // Phase 2:
  // . Traverse the list and remove any refs whose referents are alive.
939
  if (mt_processing) {
D
duke 已提交
940 941 942
    RefProcPhase2Task phase2(*this, refs_lists, !discovery_is_atomic() /*marks_oops_alive*/);
    task_executor->execute(phase2);
  } else {
943
    for (uint i = 0; i < _max_num_q; i++) {
D
duke 已提交
944 945 946 947 948 949
      process_phase2(refs_lists[i], is_alive, keep_alive, complete_gc);
    }
  }

  // Phase 3:
  // . Traverse the list and process referents as appropriate.
950
  if (mt_processing) {
D
duke 已提交
951 952 953
    RefProcPhase3Task phase3(*this, refs_lists, clear_referent, true /*marks_oops_alive*/);
    task_executor->execute(phase3);
  } else {
954
    for (uint i = 0; i < _max_num_q; i++) {
D
duke 已提交
955 956 957 958
      process_phase3(refs_lists[i], clear_referent,
                     is_alive, keep_alive, complete_gc);
    }
  }
S
sla 已提交
959 960

  return total_list_count;
D
duke 已提交
961 962 963 964
}

void ReferenceProcessor::clean_up_discovered_references() {
  // loop over the lists
965
  for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
966
    if (TraceReferenceGC && PrintGCDetails && ((i % _max_num_q) == 0)) {
D
duke 已提交
967 968 969 970
      gclog_or_tty->print_cr(
        "\nScrubbing %s discovered list of Null referents",
        list_name(i));
    }
971
    clean_up_discovered_reflist(_discovered_refs[i]);
D
duke 已提交
972 973 974 975 976
  }
}

void ReferenceProcessor::clean_up_discovered_reflist(DiscoveredList& refs_list) {
  assert(!discovery_is_atomic(), "Else why call this method?");
977
  DiscoveredListIterator iter(refs_list, NULL, NULL);
D
duke 已提交
978 979
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
980 981
    oop next = java_lang_ref_Reference::next(iter.obj());
    assert(next->is_oop_or_null(), "bad next field");
D
duke 已提交
982 983
    // If referent has been cleared or Reference is not active,
    // drop it.
984
    if (iter.referent() == NULL || next != NULL) {
D
duke 已提交
985 986 987 988 989
      debug_only(
        if (PrintGCDetails && TraceReferenceGC) {
          gclog_or_tty->print_cr("clean_up_discovered_list: Dropping Reference: "
            INTPTR_FORMAT " with next field: " INTPTR_FORMAT
            " and referent: " INTPTR_FORMAT,
990
            (void *)iter.obj(), (void *)next, (void *)iter.referent());
D
duke 已提交
991 992 993 994
        }
      )
      // Remove Reference object from list
      iter.remove();
995
      iter.move_to_next();
D
duke 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    } else {
      iter.next();
    }
  }
  NOT_PRODUCT(
    if (PrintGCDetails && TraceReferenceGC) {
      gclog_or_tty->print(
        " Removed %d Refs with NULL referents out of %d discovered Refs",
        iter.removed(), iter.processed());
    }
  )
}

inline DiscoveredList* ReferenceProcessor::get_discovered_list(ReferenceType rt) {
1010
  uint id = 0;
D
duke 已提交
1011 1012 1013 1014 1015
  // Determine the queue index to use for this object.
  if (_discovery_is_mt) {
    // During a multi-threaded discovery phase,
    // each thread saves to its "own" list.
    Thread* thr = Thread::current();
1016
    id = thr->as_Worker_thread()->id();
D
duke 已提交
1017 1018 1019 1020 1021 1022 1023
  } else {
    // single-threaded discovery, we save in round-robin
    // fashion to each of the lists.
    if (_processing_is_mt) {
      id = next_id();
    }
  }
1024
  assert(0 <= id && id < _max_num_q, "Id is out-of-bounds (call Freud?)");
D
duke 已提交
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

  // Get the discovered queue to which we will add
  DiscoveredList* list = NULL;
  switch (rt) {
    case REF_OTHER:
      // Unknown reference type, no special treatment
      break;
    case REF_SOFT:
      list = &_discoveredSoftRefs[id];
      break;
    case REF_WEAK:
      list = &_discoveredWeakRefs[id];
      break;
    case REF_FINAL:
      list = &_discoveredFinalRefs[id];
      break;
    case REF_PHANTOM:
      list = &_discoveredPhantomRefs[id];
      break;
    case REF_NONE:
1045
      // we should not reach here if we are an InstanceRefKlass
D
duke 已提交
1046 1047 1048
    default:
      ShouldNotReachHere();
  }
1049
  if (TraceReferenceGC && PrintGCDetails) {
1050
    gclog_or_tty->print_cr("Thread %d gets list " INTPTR_FORMAT, id, list);
1051
  }
D
duke 已提交
1052 1053 1054
  return list;
}

1055 1056 1057 1058
inline void
ReferenceProcessor::add_to_discovered_list_mt(DiscoveredList& refs_list,
                                              oop             obj,
                                              HeapWord*       discovered_addr) {
D
duke 已提交
1059 1060 1061
  assert(_discovery_is_mt, "!_discovery_is_mt should have been handled by caller");
  // First we must make sure this object is only enqueued once. CAS in a non null
  // discovered_addr.
1062
  oop current_head = refs_list.head();
1063 1064
  // The last ref must have its discovered field pointing to itself.
  oop next_discovered = (current_head != NULL) ? current_head : obj;
1065

1066
  oop retest = oopDesc::atomic_compare_exchange_oop(next_discovered, discovered_addr,
1067
                                                    NULL);
D
duke 已提交
1068 1069
  if (retest == NULL) {
    // This thread just won the right to enqueue the object.
1070
    // We have separate lists for enqueueing, so no synchronization
D
duke 已提交
1071
    // is necessary.
1072
    refs_list.set_head(obj);
1073
    refs_list.inc_length(1);
1074 1075

    if (TraceReferenceGC) {
1076
      gclog_or_tty->print_cr("Discovered reference (mt) (" INTPTR_FORMAT ": %s)",
1077
                             (void *)obj, obj->klass()->internal_name());
1078
    }
D
duke 已提交
1079 1080 1081 1082
  } else {
    // If retest was non NULL, another thread beat us to it:
    // The reference has already been discovered...
    if (TraceReferenceGC) {
1083
      gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)",
1084
                             (void *)obj, obj->klass()->internal_name());
D
duke 已提交
1085 1086 1087 1088
    }
  }
}

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
#ifndef PRODUCT
// Non-atomic (i.e. concurrent) discovery might allow us
// to observe j.l.References with NULL referents, being those
// cleared concurrently by mutators during (or after) discovery.
void ReferenceProcessor::verify_referent(oop obj) {
  bool da = discovery_is_atomic();
  oop referent = java_lang_ref_Reference::referent(obj);
  assert(da ? referent->is_oop() : referent->is_oop_or_null(),
         err_msg("Bad referent " INTPTR_FORMAT " found in Reference "
                 INTPTR_FORMAT " during %satomic discovery ",
1099
                 (void *)referent, (void *)obj, da ? "" : "non-"));
1100 1101 1102
}
#endif

D
duke 已提交
1103 1104 1105 1106 1107
// We mention two of several possible choices here:
// #0: if the reference object is not in the "originating generation"
//     (or part of the heap being collected, indicated by our "span"
//     we don't treat it specially (i.e. we scan it as we would
//     a normal oop, treating its references as strong references).
1108
//     This means that references can't be discovered unless their
D
duke 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
//     referent is also in the same span. This is the simplest,
//     most "local" and most conservative approach, albeit one
//     that may cause weak references to be enqueued least promptly.
//     We call this choice the "ReferenceBasedDiscovery" policy.
// #1: the reference object may be in any generation (span), but if
//     the referent is in the generation (span) being currently collected
//     then we can discover the reference object, provided
//     the object has not already been discovered by
//     a different concurrently running collector (as may be the
//     case, for instance, if the reference object is in CMS and
//     the referent in DefNewGeneration), and provided the processing
//     of this reference object by the current collector will
//     appear atomic to every other collector in the system.
//     (Thus, for instance, a concurrent collector may not
//     discover references in other generations even if the
//     referent is in its own generation). This policy may,
//     in certain cases, enqueue references somewhat sooner than
//     might Policy #0 above, but at marginally increased cost
//     and complexity in processing these references.
//     We call this choice the "RefeferentBasedDiscovery" policy.
bool ReferenceProcessor::discover_reference(oop obj, ReferenceType rt) {
1130
  // Make sure we are discovering refs (rather than processing discovered refs).
D
duke 已提交
1131 1132 1133
  if (!_discovering_refs || !RegisterReferences) {
    return false;
  }
1134
  // We only discover active references.
1135
  oop next = java_lang_ref_Reference::next(obj);
1136
  if (next != NULL) {   // Ref is no longer active
D
duke 已提交
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
    return false;
  }

  HeapWord* obj_addr = (HeapWord*)obj;
  if (RefDiscoveryPolicy == ReferenceBasedDiscovery &&
      !_span.contains(obj_addr)) {
    // Reference is not in the originating generation;
    // don't treat it specially (i.e. we want to scan it as a normal
    // object with strong references).
    return false;
  }

1149 1150
  // We only discover references whose referents are not (yet)
  // known to be strongly reachable.
D
duke 已提交
1151
  if (is_alive_non_header() != NULL) {
1152 1153
    verify_referent(obj);
    if (is_alive_non_header()->do_object_b(java_lang_ref_Reference::referent(obj))) {
D
duke 已提交
1154 1155 1156
      return false;  // referent is reachable
    }
  }
1157 1158 1159 1160 1161 1162 1163 1164
  if (rt == REF_SOFT) {
    // For soft refs we can decide now if these are not
    // current candidates for clearing, in which case we
    // can mark through them now, rather than delaying that
    // to the reference-processing phase. Since all current
    // time-stamp policies advance the soft-ref clock only
    // at a major collection cycle, this is always currently
    // accurate.
1165
    if (!_current_soft_ref_policy->should_clear_reference(obj, _soft_ref_timestamp_clock)) {
1166 1167 1168
      return false;
    }
  }
D
duke 已提交
1169

1170 1171
  ResourceMark rm;      // Needed for tracing.

1172 1173
  HeapWord* const discovered_addr = java_lang_ref_Reference::discovered_addr(obj);
  const oop  discovered = java_lang_ref_Reference::discovered(obj);
1174 1175
  assert(discovered->is_oop_or_null(), "bad discovered field");
  if (discovered != NULL) {
D
duke 已提交
1176 1177
    // The reference has already been discovered...
    if (TraceReferenceGC) {
1178
      gclog_or_tty->print_cr("Already discovered reference (" INTPTR_FORMAT ": %s)",
1179
                             (void *)obj, obj->klass()->internal_name());
D
duke 已提交
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
    }
    if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
      // assumes that an object is not processed twice;
      // if it's been already discovered it must be on another
      // generation's discovered list; so we won't discover it.
      return false;
    } else {
      assert(RefDiscoveryPolicy == ReferenceBasedDiscovery,
             "Unrecognized policy");
      // Check assumption that an object is not potentially
      // discovered twice except by concurrent collectors that potentially
      // trace the same Reference object twice.
1192 1193
      assert(UseConcMarkSweepGC || UseG1GC,
             "Only possible with a concurrent marking collector");
D
duke 已提交
1194 1195 1196 1197 1198
      return true;
    }
  }

  if (RefDiscoveryPolicy == ReferentBasedDiscovery) {
1199
    verify_referent(obj);
1200 1201 1202
    // Discover if and only if EITHER:
    // .. reference is in our span, OR
    // .. we are an atomic collector and referent is in our span
D
duke 已提交
1203
    if (_span.contains(obj_addr) ||
1204 1205
        (discovery_is_atomic() &&
         _span.contains(java_lang_ref_Reference::referent(obj)))) {
D
duke 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
      // should_enqueue = true;
    } else {
      return false;
    }
  } else {
    assert(RefDiscoveryPolicy == ReferenceBasedDiscovery &&
           _span.contains(obj_addr), "code inconsistency");
  }

  // Get the right type of discovered queue head.
  DiscoveredList* list = get_discovered_list(rt);
  if (list == NULL) {
    return false;   // nothing special needs to be done
  }

  if (_discovery_is_mt) {
    add_to_discovered_list_mt(*list, obj, discovered_addr);
  } else {
1224 1225
    // We do a raw store here: the field will be visited later when processing
    // the discovered references.
1226
    oop current_head = list->head();
1227 1228 1229
    // The last ref must have its discovered field pointing to itself.
    oop next_discovered = (current_head != NULL) ? current_head : obj;

1230
    assert(discovered == NULL, "control point invariant");
1231
    oop_store_raw(discovered_addr, next_discovered);
D
duke 已提交
1232
    list->set_head(obj);
1233
    list->inc_length(1);
D
duke 已提交
1234

1235
    if (TraceReferenceGC) {
1236
      gclog_or_tty->print_cr("Discovered reference (" INTPTR_FORMAT ": %s)",
1237
                                (void *)obj, obj->klass()->internal_name());
D
duke 已提交
1238 1239
    }
  }
1240
  assert(obj->is_oop(), "Discovered a bad reference");
1241
  verify_referent(obj);
D
duke 已提交
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
  return true;
}

// Preclean the discovered references by removing those
// whose referents are alive, and by marking from those that
// are not active. These lists can be handled here
// in any order and, indeed, concurrently.
void ReferenceProcessor::preclean_discovered_references(
  BoolObjectClosure* is_alive,
  OopClosure* keep_alive,
  VoidClosure* complete_gc,
S
sla 已提交
1253 1254
  YieldClosure* yield,
  GCTimer* gc_timer) {
D
duke 已提交
1255 1256 1257 1258 1259

  NOT_PRODUCT(verify_ok_to_handle_reflists());

  // Soft references
  {
S
sla 已提交
1260 1261
    GCTraceTime tt("Preclean SoftReferences", PrintGCDetails && PrintReferenceGC,
              false, gc_timer);
1262
    for (uint i = 0; i < _max_num_q; i++) {
1263 1264 1265
      if (yield->should_return()) {
        return;
      }
D
duke 已提交
1266 1267 1268 1269 1270 1271 1272
      preclean_discovered_reflist(_discoveredSoftRefs[i], is_alive,
                                  keep_alive, complete_gc, yield);
    }
  }

  // Weak references
  {
S
sla 已提交
1273 1274
    GCTraceTime tt("Preclean WeakReferences", PrintGCDetails && PrintReferenceGC,
              false, gc_timer);
1275
    for (uint i = 0; i < _max_num_q; i++) {
1276 1277 1278
      if (yield->should_return()) {
        return;
      }
D
duke 已提交
1279 1280 1281 1282 1283 1284 1285
      preclean_discovered_reflist(_discoveredWeakRefs[i], is_alive,
                                  keep_alive, complete_gc, yield);
    }
  }

  // Final references
  {
S
sla 已提交
1286 1287
    GCTraceTime tt("Preclean FinalReferences", PrintGCDetails && PrintReferenceGC,
              false, gc_timer);
1288
    for (uint i = 0; i < _max_num_q; i++) {
1289 1290 1291
      if (yield->should_return()) {
        return;
      }
D
duke 已提交
1292 1293 1294 1295 1296 1297 1298
      preclean_discovered_reflist(_discoveredFinalRefs[i], is_alive,
                                  keep_alive, complete_gc, yield);
    }
  }

  // Phantom references
  {
S
sla 已提交
1299 1300
    GCTraceTime tt("Preclean PhantomReferences", PrintGCDetails && PrintReferenceGC,
              false, gc_timer);
1301
    for (uint i = 0; i < _max_num_q; i++) {
1302 1303 1304
      if (yield->should_return()) {
        return;
      }
D
duke 已提交
1305 1306 1307 1308 1309 1310 1311 1312
      preclean_discovered_reflist(_discoveredPhantomRefs[i], is_alive,
                                  keep_alive, complete_gc, yield);
    }
  }
}

// Walk the given discovered ref list, and remove all reference objects
// whose referents are still alive, whose referents are NULL or which
1313 1314 1315 1316 1317 1318
// are not active (have a non-NULL next field). NOTE: When we are
// thus precleaning the ref lists (which happens single-threaded today),
// we do not disable refs discovery to honour the correct semantics of
// java.lang.Reference. As a result, we need to be careful below
// that ref removal steps interleave safely with ref discovery steps
// (in this thread).
1319 1320 1321 1322 1323 1324
void
ReferenceProcessor::preclean_discovered_reflist(DiscoveredList&    refs_list,
                                                BoolObjectClosure* is_alive,
                                                OopClosure*        keep_alive,
                                                VoidClosure*       complete_gc,
                                                YieldClosure*      yield) {
1325
  DiscoveredListIterator iter(refs_list, keep_alive, is_alive);
D
duke 已提交
1326 1327
  while (iter.has_next()) {
    iter.load_ptrs(DEBUG_ONLY(true /* allow_null_referent */));
1328 1329
    oop obj = iter.obj();
    oop next = java_lang_ref_Reference::next(obj);
D
duke 已提交
1330
    if (iter.referent() == NULL || iter.is_referent_alive() ||
1331
        next != NULL) {
D
duke 已提交
1332 1333 1334 1335
      // The referent has been cleared, or is alive, or the Reference is not
      // active; we need to trace and mark its cohort.
      if (TraceReferenceGC) {
        gclog_or_tty->print_cr("Precleaning Reference (" INTPTR_FORMAT ": %s)",
1336
                               (void *)iter.obj(), iter.obj()->klass()->internal_name());
D
duke 已提交
1337 1338 1339 1340 1341
      }
      // Remove Reference object from list
      iter.remove();
      // Keep alive its cohort.
      iter.make_referent_alive();
1342 1343 1344 1345 1346 1347 1348
      if (UseCompressedOops) {
        narrowOop* next_addr = (narrowOop*)java_lang_ref_Reference::next_addr(obj);
        keep_alive->do_oop(next_addr);
      } else {
        oop* next_addr = (oop*)java_lang_ref_Reference::next_addr(obj);
        keep_alive->do_oop(next_addr);
      }
1349
      iter.move_to_next();
D
duke 已提交
1350 1351 1352 1353 1354 1355 1356 1357
    } else {
      iter.next();
    }
  }
  // Close the reachable set
  complete_gc->do_void();

  NOT_PRODUCT(
1358
    if (PrintGCDetails && PrintReferenceGC && (iter.processed() > 0)) {
1359 1360 1361
      gclog_or_tty->print_cr(" Dropped %d Refs out of %d "
        "Refs in discovered list " INTPTR_FORMAT,
        iter.removed(), iter.processed(), (address)refs_list.head());
D
duke 已提交
1362 1363 1364 1365
    }
  )
}

1366
const char* ReferenceProcessor::list_name(uint i) {
1367 1368 1369
   assert(i >= 0 && i <= _max_num_q * number_of_subclasses_of_ref(),
          "Out of bounds index");

1370
   int j = i / _max_num_q;
D
duke 已提交
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
   switch (j) {
     case 0: return "SoftRef";
     case 1: return "WeakRef";
     case 2: return "FinalRef";
     case 3: return "PhantomRef";
   }
   ShouldNotReachHere();
   return NULL;
}

#ifndef PRODUCT
void ReferenceProcessor::verify_ok_to_handle_reflists() {
  // empty for now
}
#endif

#ifndef PRODUCT
void ReferenceProcessor::clear_discovered_references() {
  guarantee(!_discovering_refs, "Discovering refs?");
1390
  for (uint i = 0; i < _max_num_q * number_of_subclasses_of_ref(); i++) {
1391
    clear_discovered_references(_discovered_refs[i]);
D
duke 已提交
1392 1393
  }
}
1394

D
duke 已提交
1395
#endif // PRODUCT