1 /*
   2  * Copyright (c) 2017, 2019, 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 "logging/logStream.hpp"
  27 #include "memory/allocation.inline.hpp"
  28 #include "runtime/jniHandles.inline.hpp"
  29 #include "runtime/thread.inline.hpp"
  30 #include "runtime/threadSMR.inline.hpp"
  31 #include "runtime/vmOperations.hpp"
  32 #include "services/threadService.hpp"
  33 #include "utilities/copy.hpp"
  34 #include "utilities/globalDefinitions.hpp"
  35 #include "utilities/ostream.hpp"
  36 #include "utilities/resourceHash.hpp"
  37 #include "utilities/vmError.hpp"
  38 
  39 // The '_cnt', '_max' and '_times" fields are enabled via
  40 // -XX:+EnableThreadSMRStatistics:
  41 
  42 // # of parallel threads in _delete_lock->wait().
  43 // Impl note: Hard to imagine > 64K waiting threads so this could be 16-bit,
  44 // but there is no nice 16-bit _FORMAT support.
  45 uint                  ThreadsSMRSupport::_delete_lock_wait_cnt = 0;
  46 
  47 // Max # of parallel threads in _delete_lock->wait().
  48 // Impl note: See _delete_lock_wait_cnt note.
  49 uint                  ThreadsSMRSupport::_delete_lock_wait_max = 0;
  50 
  51 // Flag to indicate when an _delete_lock->notify() is needed.
  52 // Impl note: See _delete_lock_wait_cnt note.
  53 volatile uint         ThreadsSMRSupport::_delete_notify = 0;
  54 
  55 // # of threads deleted over VM lifetime.
  56 // Impl note: Atomically incremented over VM lifetime so use unsigned for more
  57 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
  58 // isn't available everywhere (or is it?).
  59 volatile uint         ThreadsSMRSupport::_deleted_thread_cnt = 0;
  60 
  61 // Max time in millis to delete a thread.
  62 // Impl note: 16-bit might be too small on an overloaded machine. Use
  63 // unsigned since this is a time value. Set via Atomic::cmpxchg() in a
  64 // loop for correctness.
  65 volatile uint         ThreadsSMRSupport::_deleted_thread_time_max = 0;
  66 
  67 // Cumulative time in millis to delete threads.
  68 // Impl note: Atomically added to over VM lifetime so use unsigned for more
  69 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
  70 // isn't available everywhere (or is it?).
  71 volatile uint         ThreadsSMRSupport::_deleted_thread_times = 0;
  72 
  73 // The bootstrap list is empty and cannot be freed.
  74 ThreadsList ThreadsSMRSupport::_bootstrap_list = ThreadsList(0);
  75 
  76 // This is the VM's current "threads list" and it contains all of
  77 // the JavaThreads the VM considers to be alive at this moment in
  78 // time. The other ThreadsList objects in the VM contain past
  79 // snapshots of the "threads list". _java_thread_list is initially
  80 // set to _bootstrap_list so that we can detect when we have a very
  81 // early use of a ThreadsListHandle.
  82 ThreadsList* volatile ThreadsSMRSupport::_java_thread_list = &_bootstrap_list;
  83 
  84 // # of ThreadsLists allocated over VM lifetime.
  85 // Impl note: We allocate a new ThreadsList for every thread create and
  86 // every thread delete so we need a bigger type than the
  87 // _deleted_thread_cnt field.
  88 uint64_t              ThreadsSMRSupport::_java_thread_list_alloc_cnt = 1;
  89 
  90 // # of ThreadsLists freed over VM lifetime.
  91 // Impl note: See _java_thread_list_alloc_cnt note.
  92 uint64_t              ThreadsSMRSupport::_java_thread_list_free_cnt = 0;
  93 
  94 // Max size ThreadsList allocated.
  95 // Impl note: Max # of threads alive at one time should fit in unsigned 32-bit.
  96 uint                  ThreadsSMRSupport::_java_thread_list_max = 0;
  97 
  98 // Max # of nested ThreadsLists for a thread.
  99 // Impl note: Hard to imagine > 64K nested ThreadsLists so this could be
 100 // 16-bit, but there is no nice 16-bit _FORMAT support.
 101 uint                  ThreadsSMRSupport::_nested_thread_list_max = 0;
 102 
 103 // # of ThreadsListHandles deleted over VM lifetime.
 104 // Impl note: Atomically incremented over VM lifetime so use unsigned for
 105 // more range. There will be fewer ThreadsListHandles than threads so
 106 // unsigned 32-bit should be fine.
 107 volatile uint         ThreadsSMRSupport::_tlh_cnt = 0;
 108 
 109 // Max time in millis to delete a ThreadsListHandle.
 110 // Impl note: 16-bit might be too small on an overloaded machine. Use
 111 // unsigned since this is a time value. Set via Atomic::cmpxchg() in a
 112 // loop for correctness.
 113 volatile uint         ThreadsSMRSupport::_tlh_time_max = 0;
 114 
 115 // Cumulative time in millis to delete ThreadsListHandles.
 116 // Impl note: Atomically added to over VM lifetime so use unsigned for more
 117 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
 118 // isn't available everywhere (or is it?).
 119 volatile uint         ThreadsSMRSupport::_tlh_times = 0;
 120 
 121 ThreadsList*          ThreadsSMRSupport::_to_delete_list = NULL;
 122 
 123 // # of parallel ThreadsLists on the to-delete list.
 124 // Impl note: Hard to imagine > 64K ThreadsLists needing to be deleted so
 125 // this could be 16-bit, but there is no nice 16-bit _FORMAT support.
 126 uint                  ThreadsSMRSupport::_to_delete_list_cnt = 0;
 127 
 128 // Max # of parallel ThreadsLists on the to-delete list.
 129 // Impl note: See _to_delete_list_cnt note.
 130 uint                  ThreadsSMRSupport::_to_delete_list_max = 0;
 131 
 132 
 133 // 'inline' functions first so the definitions are before first use:
 134 
 135 inline void ThreadsSMRSupport::add_deleted_thread_times(uint add_value) {
 136   Atomic::add(add_value, &_deleted_thread_times);
 137 }
 138 
 139 inline void ThreadsSMRSupport::inc_deleted_thread_cnt() {
 140   Atomic::inc(&_deleted_thread_cnt);
 141 }
 142 
 143 inline void ThreadsSMRSupport::inc_java_thread_list_alloc_cnt() {
 144   _java_thread_list_alloc_cnt++;
 145 }
 146 
 147 inline bool ThreadsSMRSupport::is_bootstrap_list(ThreadsList* list) {
 148   return list == &_bootstrap_list;
 149 }
 150 
 151 inline void ThreadsSMRSupport::update_deleted_thread_time_max(uint new_value) {
 152   while (true) {
 153     uint cur_value = _deleted_thread_time_max;
 154     if (new_value <= cur_value) {
 155       // No need to update max value so we're done.
 156       break;
 157     }
 158     if (Atomic::cmpxchg(new_value, &_deleted_thread_time_max, cur_value) == cur_value) {
 159       // Updated max value so we're done. Otherwise try it all again.
 160       break;
 161     }
 162   }
 163 }
 164 
 165 inline void ThreadsSMRSupport::update_java_thread_list_max(uint new_value) {
 166   if (new_value > _java_thread_list_max) {
 167     _java_thread_list_max = new_value;
 168   }
 169 }
 170 
 171 inline ThreadsList* ThreadsSMRSupport::xchg_java_thread_list(ThreadsList* new_list) {
 172   return (ThreadsList*)Atomic::xchg(new_list, &_java_thread_list);
 173 }
 174 
 175 // Hash table of pointers found by a scan. Used for collecting hazard
 176 // pointers (ThreadsList references). Also used for collecting JavaThreads
 177 // that are indirectly referenced by hazard ptrs. An instance of this
 178 // class only contains one type of pointer.
 179 //
 180 class ThreadScanHashtable : public CHeapObj<mtThread> {
 181  private:
 182   static bool ptr_equals(void * const& s1, void * const& s2) {
 183     return s1 == s2;
 184   }
 185 
 186   static unsigned int ptr_hash(void * const& s1) {
 187     // 2654435761 = 2^32 * Phi (golden ratio)
 188     return (unsigned int)(((uint32_t)(uintptr_t)s1) * 2654435761u);
 189   }
 190 
 191   int _table_size;
 192   // ResourceHashtable SIZE is specified at compile time so our
 193   // dynamic _table_size is unused for now; 1031 is the first prime
 194   // after 1024.
 195   typedef ResourceHashtable<void *, int, &ThreadScanHashtable::ptr_hash,
 196                             &ThreadScanHashtable::ptr_equals, 1031,
 197                             ResourceObj::C_HEAP, mtThread> PtrTable;
 198   PtrTable * _ptrs;
 199 
 200  public:
 201   // ResourceHashtable is passed to various functions and populated in
 202   // different places so we allocate it using C_HEAP to make it immune
 203   // from any ResourceMarks that happen to be in the code paths.
 204   ThreadScanHashtable(int table_size) : _table_size(table_size), _ptrs(new (ResourceObj::C_HEAP, mtThread) PtrTable()) {}
 205 
 206   ~ThreadScanHashtable() { delete _ptrs; }
 207 
 208   bool has_entry(void *pointer) {
 209     int *val_ptr = _ptrs->get(pointer);
 210     return val_ptr != NULL && *val_ptr == 1;
 211   }
 212 
 213   void add_entry(void *pointer) {
 214     _ptrs->put(pointer, 1);
 215   }
 216 };
 217 
 218 // Closure to gather JavaThreads indirectly referenced by hazard ptrs
 219 // (ThreadsList references) into a hash table. This closure handles part 2
 220 // of the dance - adding all the JavaThreads referenced by the hazard
 221 // pointer (ThreadsList reference) to the hash table.
 222 //
 223 class AddThreadHazardPointerThreadClosure : public ThreadClosure {
 224  private:
 225   ThreadScanHashtable *_table;
 226 
 227  public:
 228   AddThreadHazardPointerThreadClosure(ThreadScanHashtable *table) : _table(table) {}
 229 
 230   virtual void do_thread(Thread *thread) {
 231     if (!_table->has_entry((void*)thread)) {
 232       // The same JavaThread might be on more than one ThreadsList or
 233       // more than one thread might be using the same ThreadsList. In
 234       // either case, we only need a single entry for a JavaThread.
 235       _table->add_entry((void*)thread);
 236     }
 237   }
 238 };
 239 
 240 // Closure to gather JavaThreads indirectly referenced by hazard ptrs
 241 // (ThreadsList references) into a hash table. This closure handles part 1
 242 // of the dance - hazard ptr chain walking and dispatch to another
 243 // closure.
 244 //
 245 class ScanHazardPtrGatherProtectedThreadsClosure : public ThreadClosure {
 246  private:
 247   ThreadScanHashtable *_table;
 248  public:
 249   ScanHazardPtrGatherProtectedThreadsClosure(ThreadScanHashtable *table) : _table(table) {}
 250 
 251   virtual void do_thread(Thread *thread) {
 252     assert_locked_or_safepoint(Threads_lock);
 253 
 254     if (thread == NULL) return;
 255 
 256     // This code races with ThreadsSMRSupport::acquire_stable_list() which
 257     // is lock-free so we have to handle some special situations.
 258     //
 259     ThreadsList *current_list = NULL;
 260     while (true) {
 261       current_list = thread->get_threads_hazard_ptr();
 262       // No hazard ptr so nothing more to do.
 263       if (current_list == NULL) {
 264         return;
 265       }
 266 
 267       // If the hazard ptr is verified as stable (since it is not tagged),
 268       // then it is safe to use.
 269       if (!Thread::is_hazard_ptr_tagged(current_list)) break;
 270 
 271       // The hazard ptr is tagged as not yet verified as being stable
 272       // so we are racing with acquire_stable_list(). This exchange
 273       // attempts to invalidate the hazard ptr. If we win the race,
 274       // then we can ignore this unstable hazard ptr and the other
 275       // thread will retry the attempt to publish a stable hazard ptr.
 276       // If we lose the race, then we retry our attempt to look at the
 277       // hazard ptr.
 278       if (thread->cmpxchg_threads_hazard_ptr(NULL, current_list) == current_list) return;
 279     }
 280 
 281     // The current JavaThread has a hazard ptr (ThreadsList reference)
 282     // which might be _java_thread_list or it might be an older
 283     // ThreadsList that has been removed but not freed. In either case,
 284     // the hazard ptr is protecting all the JavaThreads on that
 285     // ThreadsList.
 286     AddThreadHazardPointerThreadClosure add_cl(_table);
 287     current_list->threads_do(&add_cl);
 288   }
 289 };
 290 
 291 // Closure to gather hazard ptrs (ThreadsList references) into a hash table.
 292 //
 293 class ScanHazardPtrGatherThreadsListClosure : public ThreadClosure {
 294  private:
 295   ThreadScanHashtable *_table;
 296  public:
 297   ScanHazardPtrGatherThreadsListClosure(ThreadScanHashtable *table) : _table(table) {}
 298 
 299   virtual void do_thread(Thread* thread) {
 300     assert_locked_or_safepoint(Threads_lock);
 301 
 302     if (thread == NULL) return;
 303     ThreadsList *threads = thread->get_threads_hazard_ptr();
 304     if (threads == NULL) {
 305       return;
 306     }
 307     // In this closure we always ignore the tag that might mark this
 308     // hazard ptr as not yet verified. If we happen to catch an
 309     // unverified hazard ptr that is subsequently discarded (not
 310     // published), then the only side effect is that we might keep a
 311     // to-be-deleted ThreadsList alive a little longer.
 312     threads = Thread::untag_hazard_ptr(threads);
 313     if (!_table->has_entry((void*)threads)) {
 314       _table->add_entry((void*)threads);
 315     }
 316   }
 317 };
 318 
 319 // Closure to print JavaThreads that have a hazard ptr (ThreadsList
 320 // reference) that contains an indirect reference to a specific JavaThread.
 321 //
 322 class ScanHazardPtrPrintMatchingThreadsClosure : public ThreadClosure {
 323  private:
 324   JavaThread *_thread;
 325  public:
 326   ScanHazardPtrPrintMatchingThreadsClosure(JavaThread *thread) : _thread(thread) {}
 327 
 328   virtual void do_thread(Thread *thread) {
 329     assert_locked_or_safepoint(Threads_lock);
 330 
 331     if (thread == NULL) return;
 332     ThreadsList *current_list = thread->get_threads_hazard_ptr();
 333     if (current_list == NULL) {
 334       return;
 335     }
 336     // If the hazard ptr is unverified, then ignore it.
 337     if (Thread::is_hazard_ptr_tagged(current_list)) return;
 338 
 339     // The current JavaThread has a hazard ptr (ThreadsList reference)
 340     // which might be _java_thread_list or it might be an older
 341     // ThreadsList that has been removed but not freed. In either case,
 342     // the hazard ptr is protecting all the JavaThreads on that
 343     // ThreadsList, but we only care about matching a specific JavaThread.
 344     JavaThreadIterator jti(current_list);
 345     for (JavaThread *p = jti.first(); p != NULL; p = jti.next()) {
 346       if (p == _thread) {
 347         log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: thread1=" INTPTR_FORMAT " has a hazard pointer for thread2=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread), p2i(_thread));
 348         break;
 349       }
 350     }
 351   }
 352 };
 353 
 354 // Closure to determine if the specified JavaThread is found by
 355 // threads_do().
 356 //
 357 class VerifyHazardPtrThreadClosure : public ThreadClosure {
 358  private:
 359   bool _found;
 360   Thread *_self;
 361 
 362  public:
 363   VerifyHazardPtrThreadClosure(Thread *self) : _found(false), _self(self) {}
 364 
 365   bool found() const { return _found; }
 366 
 367   virtual void do_thread(Thread *thread) {
 368     if (thread == _self) {
 369       _found = true;
 370     }
 371   }
 372 };
 373 
 374 
 375 // Acquire a stable ThreadsList.
 376 //
 377 void SafeThreadsListPtr::acquire_stable_list() {
 378   assert(_thread != NULL, "sanity check");
 379   _needs_release = true;
 380   _previous = _thread->_threads_list_ptr;
 381   _thread->_threads_list_ptr = this;
 382 
 383   if (_thread->get_threads_hazard_ptr() == NULL) {
 384     // The typical case is first.
 385     acquire_stable_list_fast_path();
 386     return;
 387   }
 388 
 389   // The nested case is rare.
 390   acquire_stable_list_nested_path();
 391 }
 392 
 393 // Fast path way to acquire a stable ThreadsList.
 394 //
 395 void SafeThreadsListPtr::acquire_stable_list_fast_path() {
 396   assert(_thread != NULL, "sanity check");
 397   assert(_thread->get_threads_hazard_ptr() == NULL, "sanity check");
 398 
 399   ThreadsList* threads;
 400 
 401   // Stable recording of a hazard ptr for SMR. This code does not use
 402   // locks so its use of the _smr_java_thread_list & _threads_hazard_ptr
 403   // fields is racy relative to code that uses those fields with locks.
 404   // OrderAccess and Atomic functions are used to deal with those races.
 405   //
 406   while (true) {
 407     threads = ThreadsSMRSupport::get_java_thread_list();
 408 
 409     // Publish a tagged hazard ptr to denote that the hazard ptr is not
 410     // yet verified as being stable. Due to the fence after the hazard
 411     // ptr write, it will be sequentially consistent w.r.t. the
 412     // sequentially consistent writes of the ThreadsList, even on
 413     // non-multiple copy atomic machines where stores can be observed
 414     // in different order from different observer threads.
 415     ThreadsList* unverified_threads = Thread::tag_hazard_ptr(threads);
 416     _thread->set_threads_hazard_ptr(unverified_threads);
 417 
 418     // If _smr_java_thread_list has changed, we have lost a race with
 419     // Threads::add() or Threads::remove() and have to try again.
 420     if (ThreadsSMRSupport::get_java_thread_list() != threads) {
 421       continue;
 422     }
 423 
 424     // We try to remove the tag which will verify the hazard ptr as
 425     // being stable. This exchange can race with a scanning thread
 426     // which might invalidate the tagged hazard ptr to keep it from
 427     // being followed to access JavaThread ptrs. If we lose the race,
 428     // we simply retry. If we win the race, then the stable hazard
 429     // ptr is officially published.
 430     if (_thread->cmpxchg_threads_hazard_ptr(threads, unverified_threads) == unverified_threads) {
 431       break;
 432     }
 433   }
 434 
 435   // A stable hazard ptr has been published letting other threads know
 436   // that the ThreadsList and the JavaThreads reachable from this list
 437   // are protected and hence they should not be deleted until everyone
 438   // agrees it is safe to do so.
 439 
 440   _list = threads;
 441 
 442   verify_hazard_ptr_scanned();
 443 }
 444 
 445 // Acquire a nested stable ThreadsList; this is rare so it uses
 446 // reference counting.
 447 //
 448 void SafeThreadsListPtr::acquire_stable_list_nested_path() {
 449   assert(_thread != NULL, "sanity check");
 450   assert(_thread->get_threads_hazard_ptr() != NULL,
 451          "cannot have a NULL regular hazard ptr when acquiring a nested hazard ptr");
 452 
 453   // The thread already has a hazard ptr (ThreadsList ref) so we need
 454   // to create a nested ThreadsListHandle with the current ThreadsList
 455   // since it might be different than our current hazard ptr. To remedy
 456   // the situation, the ThreadsList pointed to by the pre-existing
 457   // stable hazard ptr is reference counted before the hazard ptr may
 458   // be released and moved to a new ThreadsList. The old ThreadsList
 459   // is remembered in the ThreadsListHandle.
 460 
 461   ThreadsList* current_list = _previous->_list;
 462   if (EnableThreadSMRStatistics) {
 463     _thread->inc_nested_threads_hazard_ptr_cnt();
 464   }
 465   current_list->inc_nested_handle_cnt();
 466   _previous->_has_ref_count = true;  // promote SafeThreadsListPtr to be reference counted
 467   _thread->_threads_hazard_ptr = NULL;  // clear the hazard ptr so we can go through the fast path below
 468 
 469   if (EnableThreadSMRStatistics && _thread->nested_threads_hazard_ptr_cnt() > ThreadsSMRSupport::_nested_thread_list_max) {
 470     ThreadsSMRSupport::_nested_thread_list_max = _thread->nested_threads_hazard_ptr_cnt();
 471   }
 472 
 473   acquire_stable_list_fast_path();
 474 
 475   verify_hazard_ptr_scanned();
 476 
 477   log_debug(thread, smr)("tid=" UINTX_FORMAT ": SafeThreadsListPtr::acquire_stable_list: add nested list pointer to ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(_list));
 478 }
 479 
 480 // Release a stable ThreadsList.
 481 //
 482 void SafeThreadsListPtr::release_stable_list() {
 483   assert(_thread != NULL, "sanity check");
 484   assert(_thread->_threads_list_ptr == this, "sanity check");
 485   _thread->_threads_list_ptr = _previous;
 486 
 487   if (_has_ref_count) {
 488     // If a SafeThreadsListPtr has been promoted to use reference counting
 489     // due to nesting of ThreadsListHandles, then the reference count must be
 490     // decremented, at which point it may be freed. The forgotten value of
 491     // the list no longer matters at this point and should already be NULL.
 492     assert(_thread->get_threads_hazard_ptr() == NULL, "sanity check");
 493     if (EnableThreadSMRStatistics) {
 494       _thread->dec_nested_threads_hazard_ptr_cnt();
 495     }
 496     _list->dec_nested_handle_cnt();
 497 
 498     log_debug(thread, smr)("tid=" UINTX_FORMAT ": SafeThreadsListPtr::release_stable_list: delete nested list pointer to ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(_list));
 499   } else {
 500     // The normal case: a leaf ThreadsListHandle. This merely requires setting
 501     // the thread hazard ptr back to NULL.
 502     assert(_thread->get_threads_hazard_ptr() != NULL, "sanity check");
 503     _thread->set_threads_hazard_ptr(NULL);
 504   }
 505 
 506   // After releasing the hazard ptr, other threads may go ahead and
 507   // free up some memory temporarily used by a ThreadsList snapshot.
 508 
 509   // We use double-check locking to reduce traffic on the system
 510   // wide Thread-SMR delete_lock.
 511   if (ThreadsSMRSupport::delete_notify()) {
 512     // An exiting thread might be waiting in smr_delete(); we need to
 513     // check with delete_lock to be sure.
 514     ThreadsSMRSupport::release_stable_list_wake_up(_has_ref_count);
 515   }
 516 }
 517 
 518 // Verify that the stable hazard ptr used to safely keep threads
 519 // alive is scanned by threads_do() which is a key piece of honoring
 520 // the Thread-SMR protocol.
 521 void SafeThreadsListPtr::verify_hazard_ptr_scanned() {
 522 #ifdef ASSERT
 523   assert(_list != NULL, "_list must not be NULL");
 524 
 525   if (ThreadsSMRSupport::is_bootstrap_list(_list)) {
 526     // We are early in VM bootstrapping so nothing to do here.
 527     return;
 528   }
 529 
 530   // The closure will attempt to verify that the calling thread can
 531   // be found by threads_do() on the specified ThreadsList. If it
 532   // is successful, then the specified ThreadsList was acquired as
 533   // a stable hazard ptr by the calling thread in a way that honored
 534   // the Thread-SMR protocol.
 535   //
 536   // If the calling thread cannot be found by threads_do() and if
 537   // it is not the shutdown thread, then the calling thread is not
 538   // honoring the Thread-SMR ptotocol. This means that the specified
 539   // ThreadsList is not a stable hazard ptr and can be freed by
 540   // another thread from the to-be-deleted list at any time.
 541   //
 542   // Note: The shutdown thread has removed itself from the Threads
 543   // list and is safe to have a waiver from this check because
 544   // VM_Exit::_shutdown_thread is not set until after the VMThread
 545   // has started the final safepoint which holds the Threads_lock
 546   // for the remainder of the VM's life.
 547   //
 548   VerifyHazardPtrThreadClosure cl(_thread);
 549   ThreadsSMRSupport::threads_do(&cl, _list);
 550 
 551   // If the calling thread is not honoring the Thread-SMR protocol,
 552   // then we will either crash in threads_do() above because 'threads'
 553   // was freed by another thread or we will fail the assert() below.
 554   // In either case, we won't get past this point with a badly placed
 555   // ThreadsListHandle.
 556 
 557   assert(cl.found() || _thread == VM_Exit::shutdown_thread(), "Acquired a ThreadsList snapshot from a thread not recognized by the Thread-SMR protocol.");
 558 #endif
 559 }
 560 
 561 // 'entries + 1' so we always have at least one entry.
 562 ThreadsList::ThreadsList(int entries) :
 563   _length(entries),
 564   _next_list(NULL),
 565   _threads(NEW_C_HEAP_ARRAY(JavaThread*, entries + 1, mtThread)),
 566   _nested_handle_cnt(0)
 567 {
 568   *(JavaThread**)(_threads + entries) = NULL;  // Make sure the extra entry is NULL.
 569 }
 570 
 571 ThreadsList::~ThreadsList() {
 572   FREE_C_HEAP_ARRAY(JavaThread*, _threads);
 573 }
 574 
 575 // Add a JavaThread to a ThreadsList. The returned ThreadsList is a
 576 // new copy of the specified ThreadsList with the specified JavaThread
 577 // appended to the end.
 578 ThreadsList *ThreadsList::add_thread(ThreadsList *list, JavaThread *java_thread) {
 579   const uint index = list->_length;
 580   const uint new_length = index + 1;
 581   const uint head_length = index;
 582   ThreadsList *const new_list = new ThreadsList(new_length);
 583 
 584   if (head_length > 0) {
 585     Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
 586   }
 587   *(JavaThread**)(new_list->_threads + index) = java_thread;
 588 
 589   return new_list;
 590 }
 591 
 592 void ThreadsList::dec_nested_handle_cnt() {
 593   // The decrement only needs to be MO_ACQ_REL since the reference
 594   // counter is volatile (and the hazard ptr is already NULL).
 595   Atomic::dec(&_nested_handle_cnt);



 596 }
 597 
 598 int ThreadsList::find_index_of_JavaThread(JavaThread *target) {
 599   if (target == NULL) {
 600     return -1;
 601   }
 602   for (uint i = 0; i < length(); i++) {
 603     if (target == thread_at(i)) {
 604       return (int)i;
 605     }
 606   }
 607   return -1;
 608 }
 609 
 610 JavaThread* ThreadsList::find_JavaThread_from_java_tid(jlong java_tid) const {
 611   for (uint i = 0; i < length(); i++) {
 612     JavaThread* thread = thread_at(i);
 613     oop tobj = thread->threadObj();
 614     // Ignore the thread if it hasn't run yet, has exited
 615     // or is starting to exit.
 616     if (tobj != NULL && !thread->is_exiting() &&
 617         java_tid == java_lang_Thread::thread_id(tobj)) {
 618       // found a match
 619       return thread;
 620     }
 621   }
 622   return NULL;
 623 }
 624 
 625 void ThreadsList::inc_nested_handle_cnt() {
 626   // The increment needs to be MO_SEQ_CST so that the reference counter
 627   // update is seen before the subsequent hazard ptr update.
 628   Atomic::inc(&_nested_handle_cnt);










 629 }
 630 
 631 bool ThreadsList::includes(const JavaThread * const p) const {
 632   if (p == NULL) {
 633     return false;
 634   }
 635   for (uint i = 0; i < length(); i++) {
 636     if (thread_at(i) == p) {
 637       return true;
 638     }
 639   }
 640   return false;
 641 }
 642 
 643 // Remove a JavaThread from a ThreadsList. The returned ThreadsList is a
 644 // new copy of the specified ThreadsList with the specified JavaThread
 645 // removed.
 646 ThreadsList *ThreadsList::remove_thread(ThreadsList* list, JavaThread* java_thread) {
 647   assert(list->_length > 0, "sanity");
 648 
 649   uint i = (uint)list->find_index_of_JavaThread(java_thread);
 650   assert(i < list->_length, "did not find JavaThread on the list");
 651   const uint index = i;
 652   const uint new_length = list->_length - 1;
 653   const uint head_length = index;
 654   const uint tail_length = (new_length >= index) ? (new_length - index) : 0;
 655   ThreadsList *const new_list = new ThreadsList(new_length);
 656 
 657   if (head_length > 0) {
 658     Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
 659   }
 660   if (tail_length > 0) {
 661     Copy::disjoint_words((HeapWord*)list->_threads + index + 1, (HeapWord*)new_list->_threads + index, tail_length);
 662   }
 663 
 664   return new_list;
 665 }
 666 
 667 ThreadsListHandle::ThreadsListHandle(Thread *self) : _list_ptr(self, /* acquire */ true) {
 668   assert(self == Thread::current(), "sanity check");
 669   if (EnableThreadSMRStatistics) {
 670     _timer.start();
 671   }
 672 }
 673 
 674 ThreadsListHandle::~ThreadsListHandle() {
 675   if (EnableThreadSMRStatistics) {
 676     _timer.stop();
 677     uint millis = (uint)_timer.milliseconds();
 678     ThreadsSMRSupport::update_tlh_stats(millis);
 679   }
 680 }
 681 
 682 // Convert an internal thread reference to a JavaThread found on the
 683 // associated ThreadsList. This ThreadsListHandle "protects" the
 684 // returned JavaThread *.
 685 //
 686 // If thread_oop_p is not NULL, then the caller wants to use the oop
 687 // after this call so the oop is returned. On success, *jt_pp is set
 688 // to the converted JavaThread * and true is returned. On error,
 689 // returns false.
 690 //
 691 bool ThreadsListHandle::cv_internal_thread_to_JavaThread(jobject jthread,
 692                                                          JavaThread ** jt_pp,
 693                                                          oop * thread_oop_p) {
 694   assert(this->list() != NULL, "must have a ThreadsList");
 695   assert(jt_pp != NULL, "must have a return JavaThread pointer");
 696   // thread_oop_p is optional so no assert()
 697 
 698   // The JVM_* interfaces don't allow a NULL thread parameter; JVM/TI
 699   // allows a NULL thread parameter to signify "current thread" which
 700   // allows us to avoid calling cv_external_thread_to_JavaThread().
 701   // The JVM_* interfaces have no such leeway.
 702 
 703   oop thread_oop = JNIHandles::resolve_non_null(jthread);
 704   // Looks like an oop at this point.
 705   if (thread_oop_p != NULL) {
 706     // Return the oop to the caller; the caller may still want
 707     // the oop even if this function returns false.
 708     *thread_oop_p = thread_oop;
 709   }
 710 
 711   JavaThread *java_thread = java_lang_Thread::thread(thread_oop);
 712   if (java_thread == NULL) {
 713     // The java.lang.Thread does not contain a JavaThread * so it has
 714     // not yet run or it has died.
 715     return false;
 716   }
 717   // Looks like a live JavaThread at this point.
 718 
 719   if (java_thread != JavaThread::current()) {
 720     // jthread is not for the current JavaThread so have to verify
 721     // the JavaThread * against the ThreadsList.
 722     if (EnableThreadSMRExtraValidityChecks && !includes(java_thread)) {
 723       // Not on the JavaThreads list so it is not alive.
 724       return false;
 725     }
 726   }
 727 
 728   // Return a live JavaThread that is "protected" by the
 729   // ThreadsListHandle in the caller.
 730   *jt_pp = java_thread;
 731   return true;
 732 }
 733 
 734 void ThreadsSMRSupport::add_thread(JavaThread *thread){
 735   ThreadsList *new_list = ThreadsList::add_thread(get_java_thread_list(), thread);
 736   if (EnableThreadSMRStatistics) {
 737     inc_java_thread_list_alloc_cnt();
 738     update_java_thread_list_max(new_list->length());
 739   }
 740   // Initial _java_thread_list will not generate a "Threads::add" mesg.
 741   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::add: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
 742 
 743   ThreadsList *old_list = xchg_java_thread_list(new_list);
 744   free_list(old_list);
 745 }
 746 
 747 // set_delete_notify() and clear_delete_notify() are called
 748 // under the protection of the delete_lock, but we also use an
 749 // Atomic operation to ensure the memory update is seen earlier than
 750 // when the delete_lock is dropped.
 751 //
 752 void ThreadsSMRSupport::clear_delete_notify() {
 753   Atomic::dec(&_delete_notify);
 754 }
 755 
 756 bool ThreadsSMRSupport::delete_notify() {
 757   // Use load_acquire() in order to see any updates to _delete_notify
 758   // earlier than when delete_lock is grabbed.
 759   return (OrderAccess::load_acquire(&_delete_notify) != 0);
 760 }
 761 
 762 // Safely free a ThreadsList after a Threads::add() or Threads::remove().
 763 // The specified ThreadsList may not get deleted during this call if it
 764 // is still in-use (referenced by a hazard ptr). Other ThreadsLists
 765 // in the chain may get deleted by this call if they are no longer in-use.
 766 void ThreadsSMRSupport::free_list(ThreadsList* threads) {
 767   assert_locked_or_safepoint(Threads_lock);
 768 
 769   if (is_bootstrap_list(threads)) {
 770     // The bootstrap list cannot be freed and is empty so
 771     // it does not need to be scanned. Nothing to do here.
 772     log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::free_list: bootstrap ThreadsList=" INTPTR_FORMAT " is no longer in use.", os::current_thread_id(), p2i(threads));
 773     return;
 774   }
 775 
 776   threads->set_next_list(_to_delete_list);
 777   _to_delete_list = threads;
 778   if (EnableThreadSMRStatistics) {
 779     _to_delete_list_cnt++;
 780     if (_to_delete_list_cnt > _to_delete_list_max) {
 781       _to_delete_list_max = _to_delete_list_cnt;
 782     }
 783   }
 784 
 785   // Hash table size should be first power of two higher than twice the length of the ThreadsList
 786   int hash_table_size = MIN2((int)get_java_thread_list()->length(), 32) << 1;
 787   hash_table_size--;
 788   hash_table_size |= hash_table_size >> 1;
 789   hash_table_size |= hash_table_size >> 2;
 790   hash_table_size |= hash_table_size >> 4;
 791   hash_table_size |= hash_table_size >> 8;
 792   hash_table_size |= hash_table_size >> 16;
 793   hash_table_size++;
 794 
 795   // Gather a hash table of the current hazard ptrs:
 796   ThreadScanHashtable *scan_table = new ThreadScanHashtable(hash_table_size);
 797   ScanHazardPtrGatherThreadsListClosure scan_cl(scan_table);
 798   threads_do(&scan_cl);
 799   OrderAccess::acquire(); // Must order reads of hazard ptr before reads of
 800                           // nested reference counters
 801 
 802   // Walk through the linked list of pending freeable ThreadsLists
 803   // and free the ones that are not referenced from hazard ptrs.
 804   ThreadsList* current = _to_delete_list;
 805   ThreadsList* prev = NULL;
 806   ThreadsList* next = NULL;
 807   bool threads_is_freed = false;
 808   while (current != NULL) {
 809     next = current->next_list();
 810     if (!scan_table->has_entry((void*)current) && current->_nested_handle_cnt == 0) {
 811       // This ThreadsList is not referenced by a hazard ptr.
 812       if (prev != NULL) {
 813         prev->set_next_list(next);
 814       }
 815       if (_to_delete_list == current) {
 816         _to_delete_list = next;
 817       }
 818 
 819       log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::free_list: threads=" INTPTR_FORMAT " is freed.", os::current_thread_id(), p2i(current));
 820       if (current == threads) threads_is_freed = true;
 821       delete current;
 822       if (EnableThreadSMRStatistics) {
 823         _java_thread_list_free_cnt++;
 824         _to_delete_list_cnt--;
 825       }
 826     } else {
 827       prev = current;
 828     }
 829     current = next;
 830   }
 831 
 832   if (!threads_is_freed) {
 833     // Only report "is not freed" on the original call to
 834     // free_list() for this ThreadsList.
 835     log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::free_list: threads=" INTPTR_FORMAT " is not freed.", os::current_thread_id(), p2i(threads));
 836   }
 837 
 838   delete scan_table;
 839 }
 840 
 841 // Return true if the specified JavaThread is protected by a hazard
 842 // pointer (ThreadsList reference). Otherwise, returns false.
 843 //
 844 bool ThreadsSMRSupport::is_a_protected_JavaThread(JavaThread *thread) {
 845   assert_locked_or_safepoint(Threads_lock);
 846 
 847   // Hash table size should be first power of two higher than twice
 848   // the length of the Threads list.
 849   int hash_table_size = MIN2((int)get_java_thread_list()->length(), 32) << 1;
 850   hash_table_size--;
 851   hash_table_size |= hash_table_size >> 1;
 852   hash_table_size |= hash_table_size >> 2;
 853   hash_table_size |= hash_table_size >> 4;
 854   hash_table_size |= hash_table_size >> 8;
 855   hash_table_size |= hash_table_size >> 16;
 856   hash_table_size++;
 857 
 858   // Gather a hash table of the JavaThreads indirectly referenced by
 859   // hazard ptrs.
 860   ThreadScanHashtable *scan_table = new ThreadScanHashtable(hash_table_size);
 861   ScanHazardPtrGatherProtectedThreadsClosure scan_cl(scan_table);
 862   threads_do(&scan_cl);
 863   OrderAccess::acquire(); // Must order reads of hazard ptr before reads of
 864                           // nested reference counters
 865 
 866   // Walk through the linked list of pending freeable ThreadsLists
 867   // and include the ones that are currently in use by a nested
 868   // ThreadsListHandle in the search set.
 869   ThreadsList* current = _to_delete_list;
 870   while (current != NULL) {
 871     if (current->_nested_handle_cnt != 0) {
 872       // 'current' is in use by a nested ThreadsListHandle so the hazard
 873       // ptr is protecting all the JavaThreads on that ThreadsList.
 874       AddThreadHazardPointerThreadClosure add_cl(scan_table);
 875       current->threads_do(&add_cl);
 876     }
 877     current = current->next_list();
 878   }
 879 
 880   bool thread_is_protected = false;
 881   if (scan_table->has_entry((void*)thread)) {
 882     thread_is_protected = true;
 883   }
 884   delete scan_table;
 885   return thread_is_protected;
 886 }
 887 
 888 // Wake up portion of the release stable ThreadsList protocol;
 889 // uses the delete_lock().
 890 //
 891 void ThreadsSMRSupport::release_stable_list_wake_up(bool is_nested) {
 892   const char* log_str = is_nested ? "nested hazard ptr" : "regular hazard ptr";
 893 
 894   // Note: delete_lock is held in smr_delete() for the entire
 895   // hazard ptr search so that we do not lose this notify() if
 896   // the exiting thread has to wait. That code path also holds
 897   // Threads_lock (which was grabbed before delete_lock) so that
 898   // threads_do() can be called. This means the system can't start a
 899   // safepoint which means this thread can't take too long to get to
 900   // a safepoint because of being blocked on delete_lock.
 901   //
 902   MonitorLocker ml(ThreadsSMRSupport::delete_lock(), Monitor::_no_safepoint_check_flag);
 903   if (ThreadsSMRSupport::delete_notify()) {
 904     // Notify any exiting JavaThreads that are waiting in smr_delete()
 905     // that we've released a ThreadsList.
 906     ml.notify_all();
 907     log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::release_stable_list notified %s", os::current_thread_id(), log_str);
 908   }
 909 }
 910 
 911 void ThreadsSMRSupport::remove_thread(JavaThread *thread) {
 912   ThreadsList *new_list = ThreadsList::remove_thread(ThreadsSMRSupport::get_java_thread_list(), thread);
 913   if (EnableThreadSMRStatistics) {
 914     ThreadsSMRSupport::inc_java_thread_list_alloc_cnt();
 915     // This list is smaller so no need to check for a "longest" update.
 916   }
 917 
 918   // Final _java_thread_list will not generate a "Threads::remove" mesg.
 919   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::remove: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
 920 
 921   ThreadsList *old_list = ThreadsSMRSupport::xchg_java_thread_list(new_list);
 922   ThreadsSMRSupport::free_list(old_list);
 923 }
 924 
 925 // See note for clear_delete_notify().
 926 //
 927 void ThreadsSMRSupport::set_delete_notify() {
 928   Atomic::inc(&_delete_notify);
 929 }
 930 
 931 // Safely delete a JavaThread when it is no longer in use by a
 932 // ThreadsListHandle.
 933 //
 934 void ThreadsSMRSupport::smr_delete(JavaThread *thread) {
 935   assert(!Threads_lock->owned_by_self(), "sanity");
 936 
 937   bool has_logged_once = false;
 938   elapsedTimer timer;
 939   if (EnableThreadSMRStatistics) {
 940     timer.start();
 941   }
 942 
 943   while (true) {
 944     {
 945       // No safepoint check because this JavaThread is not on the
 946       // Threads list.
 947       MutexLocker ml(Threads_lock, Mutex::_no_safepoint_check_flag);
 948       // Cannot use a MonitorLocker helper here because we have
 949       // to drop the Threads_lock first if we wait.
 950       ThreadsSMRSupport::delete_lock()->lock_without_safepoint_check();
 951       // Set the delete_notify flag after we grab delete_lock
 952       // and before we scan hazard ptrs because we're doing
 953       // double-check locking in release_stable_list().
 954       ThreadsSMRSupport::set_delete_notify();
 955 
 956       if (!is_a_protected_JavaThread(thread)) {
 957         // This is the common case.
 958         ThreadsSMRSupport::clear_delete_notify();
 959         ThreadsSMRSupport::delete_lock()->unlock();
 960         break;
 961       }
 962       if (!has_logged_once) {
 963         has_logged_once = true;
 964         log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: thread=" INTPTR_FORMAT " is not deleted.", os::current_thread_id(), p2i(thread));
 965         if (log_is_enabled(Debug, os, thread)) {
 966           ScanHazardPtrPrintMatchingThreadsClosure scan_cl(thread);
 967           threads_do(&scan_cl);
 968           ThreadsList* current = _to_delete_list;
 969           while (current != NULL) {
 970             if (current->_nested_handle_cnt != 0 && current->includes(thread)) {
 971               log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: found nested hazard pointer to thread=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread));
 972             }
 973             current = current->next_list();
 974           }
 975         }
 976       }
 977     } // We have to drop the Threads_lock to wait or delete the thread
 978 
 979     if (EnableThreadSMRStatistics) {
 980       _delete_lock_wait_cnt++;
 981       if (_delete_lock_wait_cnt > _delete_lock_wait_max) {
 982         _delete_lock_wait_max = _delete_lock_wait_cnt;
 983       }
 984     }
 985     // Wait for a release_stable_list() call before we check again. No
 986     // safepoint check, no timeout, and not as suspend equivalent flag
 987     // because this JavaThread is not on the Threads list.
 988     ThreadsSMRSupport::delete_lock()->wait_without_safepoint_check();

 989     if (EnableThreadSMRStatistics) {
 990       _delete_lock_wait_cnt--;
 991     }
 992 
 993     ThreadsSMRSupport::clear_delete_notify();
 994     ThreadsSMRSupport::delete_lock()->unlock();
 995     // Retry the whole scenario.
 996   }
 997 
 998   delete thread;
 999   if (EnableThreadSMRStatistics) {
1000     timer.stop();
1001     uint millis = (uint)timer.milliseconds();
1002     ThreadsSMRSupport::inc_deleted_thread_cnt();
1003     ThreadsSMRSupport::add_deleted_thread_times(millis);
1004     ThreadsSMRSupport::update_deleted_thread_time_max(millis);
1005   }
1006 
1007   log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: thread=" INTPTR_FORMAT " is deleted.", os::current_thread_id(), p2i(thread));
1008 }
1009 
1010 // Apply the closure to all threads in the system, with a snapshot of
1011 // all JavaThreads provided by the list parameter.
1012 void ThreadsSMRSupport::threads_do(ThreadClosure *tc, ThreadsList *list) {
1013   list->threads_do(tc);
1014   Threads::non_java_threads_do(tc);
1015 }
1016 
1017 // Apply the closure to all threads in the system.
1018 void ThreadsSMRSupport::threads_do(ThreadClosure *tc) {
1019   threads_do(tc, _java_thread_list);
1020 }
1021 
1022 
1023 // Debug, logging, and printing stuff at the end:
1024 
1025 // Print SMR info for a SafeThreadsListPtr to a given output stream.
1026 void SafeThreadsListPtr::print_on(outputStream* st) {
1027   if (this == _thread->_threads_list_ptr) {
1028     // The top level hazard ptr.
1029     st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(_list));
1030   } else {
1031     // Nested hazard ptrs.
1032     st->print(", _nested_threads_hazard_ptr=" INTPTR_FORMAT, p2i(_list));
1033   }
1034 }
1035 
1036 // Log Threads class SMR info.
1037 void ThreadsSMRSupport::log_statistics() {
1038   LogTarget(Info, thread, smr) log;
1039   if (log.is_enabled()) {
1040     LogStream out(log);
1041     print_info_on(&out);
1042   }
1043 }
1044 
1045 // Print SMR info for a thread to a given output stream.
1046 void ThreadsSMRSupport::print_info_on(const Thread* thread, outputStream* st) {
1047   if (thread->_threads_hazard_ptr != NULL) {
1048     st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(thread->_threads_hazard_ptr));
1049   }
1050   if (EnableThreadSMRStatistics && thread->_threads_list_ptr != NULL) {
1051     // The count is only interesting if we have a _threads_list_ptr.
1052     st->print(", _nested_threads_hazard_ptr_cnt=%u", thread->_nested_threads_hazard_ptr_cnt);
1053   }
1054   if (SafepointSynchronize::is_at_safepoint() || Thread::current() == thread) {
1055     // It is only safe to walk the list if we're at a safepoint or the
1056     // calling thread is walking its own list.
1057     SafeThreadsListPtr* current = thread->_threads_list_ptr;
1058     if (current != NULL) {
1059       // Skip the top nesting level as it is always printed above.
1060       current = current->previous();
1061     }
1062     while (current != NULL) {
1063       current->print_on(st);
1064       current = current->previous();
1065     }
1066   }
1067 }
1068 
1069 // Print Threads class SMR info.
1070 void ThreadsSMRSupport::print_info_on(outputStream* st) {
1071   // Only grab the Threads_lock if we don't already own it and if we
1072   // are not reporting an error.
1073   // Note: Not grabbing the Threads_lock during error reporting is
1074   // dangerous because the data structures we want to print can be
1075   // freed concurrently. However, grabbing the Threads_lock during
1076   // error reporting can be equally dangerous since this thread might
1077   // block during error reporting or a nested error could leave the
1078   // Threads_lock held. The classic no win scenario.
1079   //
1080   MutexLocker ml((Threads_lock->owned_by_self() || VMError::is_error_reported()) ? NULL : Threads_lock);
1081 
1082   st->print_cr("Threads class SMR info:");
1083   st->print_cr("_java_thread_list=" INTPTR_FORMAT ", length=%u, "
1084                "elements={", p2i(_java_thread_list),
1085                _java_thread_list->length());
1086   print_info_elements_on(st, _java_thread_list);
1087   st->print_cr("}");
1088   if (_to_delete_list != NULL) {
1089     st->print_cr("_to_delete_list=" INTPTR_FORMAT ", length=%u, "
1090                  "elements={", p2i(_to_delete_list),
1091                  _to_delete_list->length());
1092     print_info_elements_on(st, _to_delete_list);
1093     st->print_cr("}");
1094     for (ThreadsList *t_list = _to_delete_list->next_list();
1095          t_list != NULL; t_list = t_list->next_list()) {
1096       st->print("next-> " INTPTR_FORMAT ", length=%u, "
1097                 "elements={", p2i(t_list), t_list->length());
1098       print_info_elements_on(st, t_list);
1099       st->print_cr("}");
1100     }
1101   }
1102   if (!EnableThreadSMRStatistics) {
1103     return;
1104   }
1105   st->print_cr("_java_thread_list_alloc_cnt=" UINT64_FORMAT ", "
1106                "_java_thread_list_free_cnt=" UINT64_FORMAT ", "
1107                "_java_thread_list_max=%u, "
1108                "_nested_thread_list_max=%u",
1109                _java_thread_list_alloc_cnt,
1110                _java_thread_list_free_cnt,
1111                _java_thread_list_max,
1112                _nested_thread_list_max);
1113   if (_tlh_cnt > 0) {
1114     st->print_cr("_tlh_cnt=%u"
1115                  ", _tlh_times=%u"
1116                  ", avg_tlh_time=%0.2f"
1117                  ", _tlh_time_max=%u",
1118                  _tlh_cnt, _tlh_times,
1119                  ((double) _tlh_times / _tlh_cnt),
1120                  _tlh_time_max);
1121   }
1122   if (_deleted_thread_cnt > 0) {
1123     st->print_cr("_deleted_thread_cnt=%u"
1124                  ", _deleted_thread_times=%u"
1125                  ", avg_deleted_thread_time=%0.2f"
1126                  ", _deleted_thread_time_max=%u",
1127                  _deleted_thread_cnt, _deleted_thread_times,
1128                  ((double) _deleted_thread_times / _deleted_thread_cnt),
1129                  _deleted_thread_time_max);
1130   }
1131   st->print_cr("_delete_lock_wait_cnt=%u, _delete_lock_wait_max=%u",
1132                _delete_lock_wait_cnt, _delete_lock_wait_max);
1133   st->print_cr("_to_delete_list_cnt=%u, _to_delete_list_max=%u",
1134                _to_delete_list_cnt, _to_delete_list_max);
1135 }
1136 
1137 // Print ThreadsList elements (4 per line).
1138 void ThreadsSMRSupport::print_info_elements_on(outputStream* st, ThreadsList* t_list) {
1139   uint cnt = 0;
1140   JavaThreadIterator jti(t_list);
1141   for (JavaThread *jt = jti.first(); jt != NULL; jt = jti.next()) {
1142     st->print(INTPTR_FORMAT, p2i(jt));
1143     if (cnt < t_list->length() - 1) {
1144       // Separate with comma or comma-space except for the last one.
1145       if (((cnt + 1) % 4) == 0) {
1146         // Four INTPTR_FORMAT fit on an 80 column line so end the
1147         // current line with just a comma.
1148         st->print_cr(",");
1149       } else {
1150         // Not the last one on the current line so use comma-space:
1151         st->print(", ");
1152       }
1153     } else {
1154       // Last one so just end the current line.
1155       st->cr();
1156     }
1157     cnt++;
1158   }
1159 }
--- EOF ---