1 /*
2  * Copyright (c) 2017, 2021, 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/atomic.hpp"
29 #include "runtime/jniHandles.inline.hpp"
30 #include "runtime/orderAccess.hpp"
31 #include "runtime/sharedRuntime.hpp"
32 #include "runtime/thread.inline.hpp"
33 #include "runtime/threadSMR.inline.hpp"
34 #include "runtime/vmOperations.hpp"
35 #include "services/threadIdTable.hpp"
36 #include "services/threadService.hpp"
37 #include "utilities/copy.hpp"
38 #include "utilities/globalDefinitions.hpp"
39 #include "utilities/ostream.hpp"
40 #include "utilities/powerOfTwo.hpp"
41 #include "utilities/resourceHash.hpp"
42 #include "utilities/vmError.hpp"
43 
44 // The '_cnt', '_max' and '_times" fields are enabled via
45 // -XX:+EnableThreadSMRStatistics:
46 
47 // # of parallel threads in _delete_lock->wait().
48 // Impl note: Hard to imagine > 64K waiting threads so this could be 16-bit,
49 // but there is no nice 16-bit _FORMAT support.
50 uint                  ThreadsSMRSupport::_delete_lock_wait_cnt = 0;
51 
52 // Max # of parallel threads in _delete_lock->wait().
53 // Impl note: See _delete_lock_wait_cnt note.
54 uint                  ThreadsSMRSupport::_delete_lock_wait_max = 0;
55 
56 // Flag to indicate when an _delete_lock->notify() is needed.
57 // Impl note: See _delete_lock_wait_cnt note.
58 volatile uint         ThreadsSMRSupport::_delete_notify = 0;
59 
60 // # of threads deleted over VM lifetime.
61 // Impl note: Atomically incremented over VM lifetime so use unsigned for more
62 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
63 // isn't available everywhere (or is it?).
64 volatile uint         ThreadsSMRSupport::_deleted_thread_cnt = 0;
65 
66 // Max time in millis to delete a thread.
67 // Impl note: 16-bit might be too small on an overloaded machine. Use
68 // unsigned since this is a time value. Set via Atomic::cmpxchg() in a
69 // loop for correctness.
70 volatile uint         ThreadsSMRSupport::_deleted_thread_time_max = 0;
71 
72 // Cumulative time in millis to delete threads.
73 // Impl note: Atomically added to over VM lifetime so use unsigned for more
74 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
75 // isn't available everywhere (or is it?).
76 volatile uint         ThreadsSMRSupport::_deleted_thread_times = 0;
77 
78 // The bootstrap list is empty and cannot be freed.
79 ThreadsList ThreadsSMRSupport::_bootstrap_list{0};
80 
81 // This is the VM's current "threads list" and it contains all of
82 // the JavaThreads the VM considers to be alive at this moment in
83 // time. The other ThreadsList objects in the VM contain past
84 // snapshots of the "threads list". _java_thread_list is initially
85 // set to _bootstrap_list so that we can detect when we have a very
86 // early use of a ThreadsListHandle.
87 ThreadsList* volatile ThreadsSMRSupport::_java_thread_list = &_bootstrap_list;
88 
89 // # of ThreadsLists allocated over VM lifetime.
90 // Impl note: We allocate a new ThreadsList for every thread create and
91 // every thread delete so we need a bigger type than the
92 // _deleted_thread_cnt field.
93 uint64_t              ThreadsSMRSupport::_java_thread_list_alloc_cnt = 1;
94 
95 // # of ThreadsLists freed over VM lifetime.
96 // Impl note: See _java_thread_list_alloc_cnt note.
97 uint64_t              ThreadsSMRSupport::_java_thread_list_free_cnt = 0;
98 
99 // Max size ThreadsList allocated.
100 // Impl note: Max # of threads alive at one time should fit in unsigned 32-bit.
101 uint                  ThreadsSMRSupport::_java_thread_list_max = 0;
102 
103 // Max # of nested ThreadsLists for a thread.
104 // Impl note: Hard to imagine > 64K nested ThreadsLists so this could be
105 // 16-bit, but there is no nice 16-bit _FORMAT support.
106 uint                  ThreadsSMRSupport::_nested_thread_list_max = 0;
107 
108 // # of ThreadsListHandles deleted over VM lifetime.
109 // Impl note: Atomically incremented over VM lifetime so use unsigned for
110 // more range. There will be fewer ThreadsListHandles than threads so
111 // unsigned 32-bit should be fine.
112 volatile uint         ThreadsSMRSupport::_tlh_cnt = 0;
113 
114 // Max time in millis to delete a ThreadsListHandle.
115 // Impl note: 16-bit might be too small on an overloaded machine. Use
116 // unsigned since this is a time value. Set via Atomic::cmpxchg() in a
117 // loop for correctness.
118 volatile uint         ThreadsSMRSupport::_tlh_time_max = 0;
119 
120 // Cumulative time in millis to delete ThreadsListHandles.
121 // Impl note: Atomically added to over VM lifetime so use unsigned for more
122 // range. Unsigned 64-bit would be more future proof, but 64-bit atomic inc
123 // isn't available everywhere (or is it?).
124 volatile uint         ThreadsSMRSupport::_tlh_times = 0;
125 
126 ThreadsList*          ThreadsSMRSupport::_to_delete_list = NULL;
127 
128 // # of parallel ThreadsLists on the to-delete list.
129 // Impl note: Hard to imagine > 64K ThreadsLists needing to be deleted so
130 // this could be 16-bit, but there is no nice 16-bit _FORMAT support.
131 uint                  ThreadsSMRSupport::_to_delete_list_cnt = 0;
132 
133 // Max # of parallel ThreadsLists on the to-delete list.
134 // Impl note: See _to_delete_list_cnt note.
135 uint                  ThreadsSMRSupport::_to_delete_list_max = 0;
136 
137 // 'inline' functions first so the definitions are before first use:
138 
add_deleted_thread_times(uint add_value)139 inline void ThreadsSMRSupport::add_deleted_thread_times(uint add_value) {
140   Atomic::add(&_deleted_thread_times, add_value);
141 }
142 
inc_deleted_thread_cnt()143 inline void ThreadsSMRSupport::inc_deleted_thread_cnt() {
144   Atomic::inc(&_deleted_thread_cnt);
145 }
146 
inc_java_thread_list_alloc_cnt()147 inline void ThreadsSMRSupport::inc_java_thread_list_alloc_cnt() {
148   _java_thread_list_alloc_cnt++;
149 }
150 
is_bootstrap_list(ThreadsList * list)151 inline bool ThreadsSMRSupport::is_bootstrap_list(ThreadsList* list) {
152   return list == &_bootstrap_list;
153 }
154 
update_deleted_thread_time_max(uint new_value)155 inline void ThreadsSMRSupport::update_deleted_thread_time_max(uint new_value) {
156   while (true) {
157     uint cur_value = _deleted_thread_time_max;
158     if (new_value <= cur_value) {
159       // No need to update max value so we're done.
160       break;
161     }
162     if (Atomic::cmpxchg(&_deleted_thread_time_max, cur_value, new_value) == cur_value) {
163       // Updated max value so we're done. Otherwise try it all again.
164       break;
165     }
166   }
167 }
168 
update_java_thread_list_max(uint new_value)169 inline void ThreadsSMRSupport::update_java_thread_list_max(uint new_value) {
170   if (new_value > _java_thread_list_max) {
171     _java_thread_list_max = new_value;
172   }
173 }
174 
xchg_java_thread_list(ThreadsList * new_list)175 inline ThreadsList* ThreadsSMRSupport::xchg_java_thread_list(ThreadsList* new_list) {
176   return (ThreadsList*)Atomic::xchg(&_java_thread_list, new_list);
177 }
178 
179 // Hash table of pointers found by a scan. Used for collecting hazard
180 // pointers (ThreadsList references). Also used for collecting JavaThreads
181 // that are indirectly referenced by hazard ptrs. An instance of this
182 // class only contains one type of pointer.
183 //
184 class ThreadScanHashtable : public CHeapObj<mtThread> {
185  private:
ptr_equals(void * const & s1,void * const & s2)186   static bool ptr_equals(void * const& s1, void * const& s2) {
187     return s1 == s2;
188   }
189 
ptr_hash(void * const & s1)190   static unsigned int ptr_hash(void * const& s1) {
191     // 2654435761 = 2^32 * Phi (golden ratio)
192     return (unsigned int)(((uint32_t)(uintptr_t)s1) * 2654435761u);
193   }
194 
195   // ResourceHashtable SIZE is specified at compile time so we
196   // use 1031 which is the first prime after 1024.
197   typedef ResourceHashtable<void *, int, &ThreadScanHashtable::ptr_hash,
198                             &ThreadScanHashtable::ptr_equals, 1031,
199                             ResourceObj::C_HEAP, mtThread> PtrTable;
200   PtrTable * _ptrs;
201 
202  public:
203   // ResourceHashtable is passed to various functions and populated in
204   // different places so we allocate it using C_HEAP to make it immune
205   // from any ResourceMarks that happen to be in the code paths.
ThreadScanHashtable()206   ThreadScanHashtable() : _ptrs(new (ResourceObj::C_HEAP, mtThread) PtrTable()) {}
207 
~ThreadScanHashtable()208   ~ThreadScanHashtable() { delete _ptrs; }
209 
has_entry(void * pointer)210   bool has_entry(void *pointer) {
211     int *val_ptr = _ptrs->get(pointer);
212     return val_ptr != NULL && *val_ptr == 1;
213   }
214 
add_entry(void * pointer)215   void add_entry(void *pointer) {
216     _ptrs->put(pointer, 1);
217   }
218 };
219 
220 // Closure to gather JavaThreads indirectly referenced by hazard ptrs
221 // (ThreadsList references) into a hash table. This closure handles part 2
222 // of the dance - adding all the JavaThreads referenced by the hazard
223 // pointer (ThreadsList reference) to the hash table.
224 //
225 class AddThreadHazardPointerThreadClosure : public ThreadClosure {
226  private:
227   ThreadScanHashtable *_table;
228 
229  public:
AddThreadHazardPointerThreadClosure(ThreadScanHashtable * table)230   AddThreadHazardPointerThreadClosure(ThreadScanHashtable *table) : _table(table) {}
231 
do_thread(Thread * thread)232   virtual void do_thread(Thread *thread) {
233     if (!_table->has_entry((void*)thread)) {
234       // The same JavaThread might be on more than one ThreadsList or
235       // more than one thread might be using the same ThreadsList. In
236       // either case, we only need a single entry for a JavaThread.
237       _table->add_entry((void*)thread);
238     }
239   }
240 };
241 
242 // Closure to gather JavaThreads indirectly referenced by hazard ptrs
243 // (ThreadsList references) into a hash table. This closure handles part 1
244 // of the dance - hazard ptr chain walking and dispatch to another
245 // closure.
246 //
247 class ScanHazardPtrGatherProtectedThreadsClosure : public ThreadClosure {
248  private:
249   ThreadScanHashtable *_table;
250  public:
ScanHazardPtrGatherProtectedThreadsClosure(ThreadScanHashtable * table)251   ScanHazardPtrGatherProtectedThreadsClosure(ThreadScanHashtable *table) : _table(table) {}
252 
do_thread(Thread * thread)253   virtual void do_thread(Thread *thread) {
254     assert_locked_or_safepoint(Threads_lock);
255 
256     if (thread == NULL) return;
257 
258     // This code races with ThreadsSMRSupport::acquire_stable_list() which
259     // is lock-free so we have to handle some special situations.
260     //
261     ThreadsList *current_list = NULL;
262     while (true) {
263       current_list = thread->get_threads_hazard_ptr();
264       // No hazard ptr so nothing more to do.
265       if (current_list == NULL) {
266         return;
267       }
268 
269       // If the hazard ptr is verified as stable (since it is not tagged),
270       // then it is safe to use.
271       if (!Thread::is_hazard_ptr_tagged(current_list)) break;
272 
273       // The hazard ptr is tagged as not yet verified as being stable
274       // so we are racing with acquire_stable_list(). This exchange
275       // attempts to invalidate the hazard ptr. If we win the race,
276       // then we can ignore this unstable hazard ptr and the other
277       // thread will retry the attempt to publish a stable hazard ptr.
278       // If we lose the race, then we retry our attempt to look at the
279       // hazard ptr.
280       if (thread->cmpxchg_threads_hazard_ptr(NULL, current_list) == current_list) return;
281     }
282 
283     assert(ThreadsList::is_valid(current_list), "current_list="
284            INTPTR_FORMAT " is not valid!", p2i(current_list));
285 
286     // The current JavaThread has a hazard ptr (ThreadsList reference)
287     // which might be _java_thread_list or it might be an older
288     // ThreadsList that has been removed but not freed. In either case,
289     // the hazard ptr is protecting all the JavaThreads on that
290     // ThreadsList.
291     AddThreadHazardPointerThreadClosure add_cl(_table);
292     current_list->threads_do(&add_cl);
293   }
294 };
295 
296 // Closure to gather hazard ptrs (ThreadsList references) into a hash table.
297 //
298 // Since this closure gathers hazard ptrs that may be tagged, this hash
299 // table of hazard ptrs should only be used for value comparison and not
300 // traversal of the ThreadsList.
301 //
302 class ScanHazardPtrGatherThreadsListClosure : public ThreadClosure {
303  private:
304   ThreadScanHashtable *_table;
305  public:
ScanHazardPtrGatherThreadsListClosure(ThreadScanHashtable * table)306   ScanHazardPtrGatherThreadsListClosure(ThreadScanHashtable *table) : _table(table) {}
307 
do_thread(Thread * thread)308   virtual void do_thread(Thread* thread) {
309     assert_locked_or_safepoint(Threads_lock);
310 
311     if (thread == NULL) return;
312     ThreadsList *hazard_ptr = thread->get_threads_hazard_ptr();
313     if (hazard_ptr == NULL) return;
314 #ifdef ASSERT
315     if (!Thread::is_hazard_ptr_tagged(hazard_ptr)) {
316       // We only validate hazard_ptrs that are not tagged since a tagged
317       // hazard ptr can be deleted at any time.
318       assert(ThreadsList::is_valid(hazard_ptr), "hazard_ptr=" INTPTR_FORMAT
319              " for thread=" INTPTR_FORMAT " is not valid!", p2i(hazard_ptr),
320              p2i(thread));
321     }
322 #endif
323     // In this closure we always ignore the tag that might mark this
324     // hazard ptr as not yet verified. If we happen to catch an
325     // unverified hazard ptr that is subsequently discarded (not
326     // published), then the only side effect is that we might keep a
327     // to-be-deleted ThreadsList alive a little longer.
328     hazard_ptr = Thread::untag_hazard_ptr(hazard_ptr);
329     if (!_table->has_entry((void*)hazard_ptr)) {
330       _table->add_entry((void*)hazard_ptr);
331     }
332   }
333 };
334 
335 // Closure to print JavaThreads that have a hazard ptr (ThreadsList
336 // reference) that contains an indirect reference to a specific JavaThread.
337 //
338 class ScanHazardPtrPrintMatchingThreadsClosure : public ThreadClosure {
339  private:
340   JavaThread *_thread;
341  public:
ScanHazardPtrPrintMatchingThreadsClosure(JavaThread * thread)342   ScanHazardPtrPrintMatchingThreadsClosure(JavaThread *thread) : _thread(thread) {}
343 
do_thread(Thread * thread)344   virtual void do_thread(Thread *thread) {
345     assert_locked_or_safepoint(Threads_lock);
346 
347     if (thread == NULL) return;
348     ThreadsList *current_list = thread->get_threads_hazard_ptr();
349     if (current_list == NULL) {
350       return;
351     }
352     // If the hazard ptr is unverified, then ignore it.
353     if (Thread::is_hazard_ptr_tagged(current_list)) return;
354 
355     // The current JavaThread has a hazard ptr (ThreadsList reference)
356     // which might be _java_thread_list or it might be an older
357     // ThreadsList that has been removed but not freed. In either case,
358     // the hazard ptr is protecting all the JavaThreads on that
359     // ThreadsList, but we only care about matching a specific JavaThread.
360     JavaThreadIterator jti(current_list);
361     for (JavaThread *p = jti.first(); p != NULL; p = jti.next()) {
362       if (p == _thread) {
363         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));
364         break;
365       }
366     }
367   }
368 };
369 
370 // Closure to validate hazard ptrs.
371 //
372 class ValidateHazardPtrsClosure : public ThreadClosure {
373  public:
ValidateHazardPtrsClosure()374   ValidateHazardPtrsClosure() {};
375 
do_thread(Thread * thread)376   virtual void do_thread(Thread* thread) {
377     assert_locked_or_safepoint(Threads_lock);
378 
379     if (thread == NULL) return;
380     ThreadsList *hazard_ptr = thread->get_threads_hazard_ptr();
381     if (hazard_ptr == NULL) return;
382     // If the hazard ptr is unverified, then ignore it since it could
383     // be deleted at any time now.
384     if (Thread::is_hazard_ptr_tagged(hazard_ptr)) return;
385     assert(ThreadsList::is_valid(hazard_ptr), "hazard_ptr=" INTPTR_FORMAT
386            " for thread=" INTPTR_FORMAT " is not valid!", p2i(hazard_ptr),
387            p2i(thread));
388   }
389 };
390 
391 // Closure to determine if the specified JavaThread is found by
392 // threads_do().
393 //
394 class VerifyHazardPtrThreadClosure : public ThreadClosure {
395  private:
396   bool _found;
397   Thread *_self;
398 
399  public:
VerifyHazardPtrThreadClosure(Thread * self)400   VerifyHazardPtrThreadClosure(Thread *self) : _found(false), _self(self) {}
401 
found() const402   bool found() const { return _found; }
403 
do_thread(Thread * thread)404   virtual void do_thread(Thread *thread) {
405     if (thread == _self) {
406       _found = true;
407     }
408   }
409 };
410 
411 
412 // Acquire a stable ThreadsList.
413 //
acquire_stable_list()414 void SafeThreadsListPtr::acquire_stable_list() {
415   assert(_thread != NULL, "sanity check");
416   _needs_release = true;
417   _previous = _thread->_threads_list_ptr;
418   _thread->_threads_list_ptr = this;
419 
420   if (_thread->get_threads_hazard_ptr() == NULL && _previous == NULL) {
421     // The typical case is first.
422     acquire_stable_list_fast_path();
423     return;
424   }
425 
426   // The nested case is rare.
427   acquire_stable_list_nested_path();
428 }
429 
430 // Fast path way to acquire a stable ThreadsList.
431 //
acquire_stable_list_fast_path()432 void SafeThreadsListPtr::acquire_stable_list_fast_path() {
433   assert(_thread != NULL, "sanity check");
434   assert(_thread->get_threads_hazard_ptr() == NULL, "sanity check");
435 
436   ThreadsList* threads;
437 
438   // Stable recording of a hazard ptr for SMR. This code does not use
439   // locks so its use of the _java_thread_list & _threads_hazard_ptr
440   // fields is racy relative to code that uses those fields with locks.
441   // OrderAccess and Atomic functions are used to deal with those races.
442   //
443   while (true) {
444     threads = ThreadsSMRSupport::get_java_thread_list();
445 
446     // Publish a tagged hazard ptr to denote that the hazard ptr is not
447     // yet verified as being stable. Due to the fence after the hazard
448     // ptr write, it will be sequentially consistent w.r.t. the
449     // sequentially consistent writes of the ThreadsList, even on
450     // non-multiple copy atomic machines where stores can be observed
451     // in different order from different observer threads.
452     ThreadsList* unverified_threads = Thread::tag_hazard_ptr(threads);
453     _thread->set_threads_hazard_ptr(unverified_threads);
454 
455     // If _java_thread_list has changed, we have lost a race with
456     // Threads::add() or Threads::remove() and have to try again.
457     if (ThreadsSMRSupport::get_java_thread_list() != threads) {
458       continue;
459     }
460 
461     // We try to remove the tag which will verify the hazard ptr as
462     // being stable. This exchange can race with a scanning thread
463     // which might invalidate the tagged hazard ptr to keep it from
464     // being followed to access JavaThread ptrs. If we lose the race,
465     // we simply retry. If we win the race, then the stable hazard
466     // ptr is officially published.
467     if (_thread->cmpxchg_threads_hazard_ptr(threads, unverified_threads) == unverified_threads) {
468       break;
469     }
470   }
471 
472   // A stable hazard ptr has been published letting other threads know
473   // that the ThreadsList and the JavaThreads reachable from this list
474   // are protected and hence they should not be deleted until everyone
475   // agrees it is safe to do so.
476 
477   _list = threads;
478 
479   verify_hazard_ptr_scanned();
480 }
481 
482 // Acquire a nested stable ThreadsList; this is rare so it uses
483 // reference counting.
484 //
acquire_stable_list_nested_path()485 void SafeThreadsListPtr::acquire_stable_list_nested_path() {
486   assert(_thread != NULL, "sanity check");
487 
488   // The thread already has a hazard ptr (ThreadsList ref) so we need
489   // to create a nested ThreadsListHandle with the current ThreadsList
490   // since it might be different than our current hazard ptr. To remedy
491   // the situation, the ThreadsList pointed to by the pre-existing
492   // stable hazard ptr is reference counted before the hazard ptr may
493   // be released and moved to a new ThreadsList. The old ThreadsList
494   // is remembered in the ThreadsListHandle.
495 
496   ThreadsList* current_list = _previous->_list;
497   if (EnableThreadSMRStatistics) {
498     _thread->inc_nested_threads_hazard_ptr_cnt();
499   }
500   if (!_previous->_has_ref_count) {
501     // Promote the thread's current SafeThreadsListPtr to be reference counted.
502     current_list->inc_nested_handle_cnt();
503     _previous->_has_ref_count = true;
504   }
505   // Clear the hazard ptr so we can go through the fast path below and
506   // acquire a nested stable ThreadsList.
507   _thread->set_threads_hazard_ptr(NULL);
508 
509   if (EnableThreadSMRStatistics && _thread->nested_threads_hazard_ptr_cnt() > ThreadsSMRSupport::_nested_thread_list_max) {
510     ThreadsSMRSupport::_nested_thread_list_max = _thread->nested_threads_hazard_ptr_cnt();
511   }
512 
513   acquire_stable_list_fast_path();
514 
515   verify_hazard_ptr_scanned();
516 
517   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));
518 }
519 
520 // Release a stable ThreadsList.
521 //
release_stable_list()522 void SafeThreadsListPtr::release_stable_list() {
523   assert(_thread != NULL, "sanity check");
524   assert(_thread->_threads_list_ptr == this, "sanity check");
525   _thread->_threads_list_ptr = _previous;
526 
527   // We're releasing either a leaf or nested ThreadsListHandle. In either
528   // case, we set this thread's hazard ptr back to NULL and we do it before
529   // _nested_handle_cnt is decremented below.
530   _thread->set_threads_hazard_ptr(NULL);
531   if (_previous != NULL) {
532     // The ThreadsListHandle being released is a nested ThreadsListHandle.
533     if (EnableThreadSMRStatistics) {
534       _thread->dec_nested_threads_hazard_ptr_cnt();
535     }
536     // The previous ThreadsList is stable because the _nested_handle_cnt is
537     // > 0, but we cannot safely make it this thread's hazard ptr again.
538     // The protocol for installing and verifying a ThreadsList as a
539     // thread's hazard ptr is handled by acquire_stable_list_fast_path().
540     // And that protocol cannot be properly done with a ThreadsList that
541     // might not be the current system ThreadsList.
542     assert(_previous->_list->_nested_handle_cnt > 0, "must be > zero");
543   }
544   if (_has_ref_count) {
545     // This thread created a nested ThreadsListHandle after the current
546     // ThreadsListHandle so we had to protect this ThreadsList with a
547     // ref count. We no longer need that protection.
548     _list->dec_nested_handle_cnt();
549 
550     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));
551   }
552 
553   // After releasing the hazard ptr, other threads may go ahead and
554   // free up some memory temporarily used by a ThreadsList snapshot.
555 
556   // We use double-check locking to reduce traffic on the system
557   // wide Thread-SMR delete_lock.
558   if (ThreadsSMRSupport::delete_notify()) {
559     // An exiting thread might be waiting in smr_delete(); we need to
560     // check with delete_lock to be sure.
561     ThreadsSMRSupport::release_stable_list_wake_up(_has_ref_count);
562     assert(_previous == NULL || ThreadsList::is_valid(_previous->_list),
563            "_previous->_list=" INTPTR_FORMAT
564            " is not valid after calling release_stable_list_wake_up!",
565            p2i(_previous->_list));
566   }
567 }
568 
569 // Verify that the stable hazard ptr used to safely keep threads
570 // alive is scanned by threads_do() which is a key piece of honoring
571 // the Thread-SMR protocol.
verify_hazard_ptr_scanned()572 void SafeThreadsListPtr::verify_hazard_ptr_scanned() {
573 #ifdef ASSERT
574   assert(_list != NULL, "_list must not be NULL");
575 
576   if (ThreadsSMRSupport::is_bootstrap_list(_list)) {
577     // We are early in VM bootstrapping so nothing to do here.
578     return;
579   }
580 
581   if ( _thread == VM_Exit::shutdown_thread()) {
582     // The shutdown thread has removed itself from the Threads
583     // list and is safe to have a waiver from this check because
584     // VM_Exit::_shutdown_thread is not set until after the VMThread
585     // has started the final safepoint which holds the Threads_lock
586     // for the remainder of the VM's life.
587     return;
588   }
589 
590   if (VMError::is_error_reported_in_current_thread()) {
591     // If there is an error reported by this thread it may use ThreadsList even
592     // if it's unsafe.
593     return;
594   }
595 
596   // The closure will attempt to verify that the calling thread can
597   // be found by threads_do() on the specified ThreadsList. If it
598   // is successful, then the specified ThreadsList was acquired as
599   // a stable hazard ptr by the calling thread in a way that honored
600   // the Thread-SMR protocol.
601   //
602   // If the calling thread cannot be found by threads_do() and if
603   // it is not the shutdown thread, then the calling thread is not
604   // honoring the Thread-SMR ptotocol. This means that the specified
605   // ThreadsList is not a stable hazard ptr and can be freed by
606   // another thread from the to-be-deleted list at any time.
607   //
608   VerifyHazardPtrThreadClosure cl(_thread);
609   ThreadsSMRSupport::threads_do(&cl, _list);
610 
611   // If the calling thread is not honoring the Thread-SMR protocol,
612   // then we will either crash in threads_do() above because 'threads'
613   // was freed by another thread or we will fail the assert() below.
614   // In either case, we won't get past this point with a badly placed
615   // ThreadsListHandle.
616 
617   assert(cl.found(), "Acquired a ThreadsList snapshot from a thread not recognized by the Thread-SMR protocol.");
618 #endif
619 }
620 
621 // Shared singleton data for all ThreadsList(0) instances.
622 // Used by _bootstrap_list to avoid static init time heap allocation.
623 // No real entries, just the final NULL terminator.
624 static JavaThread* const empty_threads_list_data[1] = {};
625 
626 // Result has 'entries + 1' elements, with the last being the NULL terminator.
make_threads_list_data(int entries)627 static JavaThread* const* make_threads_list_data(int entries) {
628   if (entries == 0) {
629     return empty_threads_list_data;
630   }
631   JavaThread** data = NEW_C_HEAP_ARRAY(JavaThread*, entries + 1, mtThread);
632   data[entries] = NULL;         // Make sure the final entry is NULL.
633   return data;
634 }
635 
ThreadsList(int entries)636 ThreadsList::ThreadsList(int entries) :
637   _magic(THREADS_LIST_MAGIC),
638   _length(entries),
639   _next_list(NULL),
640   _threads(make_threads_list_data(entries)),
641   _nested_handle_cnt(0)
642 {}
643 
~ThreadsList()644 ThreadsList::~ThreadsList() {
645   if (_threads != empty_threads_list_data) {
646     FREE_C_HEAP_ARRAY(JavaThread*, _threads);
647   }
648   _magic = 0xDEADBEEF;
649 }
650 
651 // Add a JavaThread to a ThreadsList. The returned ThreadsList is a
652 // new copy of the specified ThreadsList with the specified JavaThread
653 // appended to the end.
add_thread(ThreadsList * list,JavaThread * java_thread)654 ThreadsList *ThreadsList::add_thread(ThreadsList *list, JavaThread *java_thread) {
655   const uint index = list->_length;
656   const uint new_length = index + 1;
657   const uint head_length = index;
658   ThreadsList *const new_list = new ThreadsList(new_length);
659 
660   if (head_length > 0) {
661     Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
662   }
663   *(JavaThread**)(new_list->_threads + index) = java_thread;
664 
665   return new_list;
666 }
667 
dec_nested_handle_cnt()668 void ThreadsList::dec_nested_handle_cnt() {
669   Atomic::dec(&_nested_handle_cnt);
670 }
671 
find_index_of_JavaThread(JavaThread * target)672 int ThreadsList::find_index_of_JavaThread(JavaThread *target) {
673   if (target == NULL) {
674     return -1;
675   }
676   for (uint i = 0; i < length(); i++) {
677     if (target == thread_at(i)) {
678       return (int)i;
679     }
680   }
681   return -1;
682 }
683 
find_JavaThread_from_java_tid(jlong java_tid) const684 JavaThread* ThreadsList::find_JavaThread_from_java_tid(jlong java_tid) const {
685   ThreadIdTable::lazy_initialize(this);
686   JavaThread* thread = ThreadIdTable::find_thread_by_tid(java_tid);
687   if (thread == NULL) {
688     // If the thread is not found in the table find it
689     // with a linear search and add to the table.
690     for (uint i = 0; i < length(); i++) {
691       thread = thread_at(i);
692       oop tobj = thread->threadObj();
693       // Ignore the thread if it hasn't run yet, has exited
694       // or is starting to exit.
695       if (tobj != NULL && java_tid == java_lang_Thread::thread_id(tobj)) {
696         MutexLocker ml(Threads_lock);
697         // Must be inside the lock to ensure that we don't add a thread to the table
698         // that has just passed the removal point in ThreadsSMRSupport::remove_thread()
699         if (!thread->is_exiting()) {
700           ThreadIdTable::add_thread(java_tid, thread);
701           return thread;
702         }
703       }
704     }
705   } else if (!thread->is_exiting()) {
706     return thread;
707   }
708   return NULL;
709 }
710 
inc_nested_handle_cnt()711 void ThreadsList::inc_nested_handle_cnt() {
712   Atomic::inc(&_nested_handle_cnt);
713 }
714 
includes(const JavaThread * const p) const715 bool ThreadsList::includes(const JavaThread * const p) const {
716   if (p == NULL) {
717     return false;
718   }
719   for (uint i = 0; i < length(); i++) {
720     if (thread_at(i) == p) {
721       return true;
722     }
723   }
724   return false;
725 }
726 
727 // Remove a JavaThread from a ThreadsList. The returned ThreadsList is a
728 // new copy of the specified ThreadsList with the specified JavaThread
729 // removed.
remove_thread(ThreadsList * list,JavaThread * java_thread)730 ThreadsList *ThreadsList::remove_thread(ThreadsList* list, JavaThread* java_thread) {
731   assert(list->_length > 0, "sanity");
732 
733   uint i = (uint)list->find_index_of_JavaThread(java_thread);
734   assert(i < list->_length, "did not find JavaThread on the list");
735   const uint index = i;
736   const uint new_length = list->_length - 1;
737   const uint head_length = index;
738   const uint tail_length = (new_length >= index) ? (new_length - index) : 0;
739   ThreadsList *const new_list = new ThreadsList(new_length);
740 
741   if (head_length > 0) {
742     Copy::disjoint_words((HeapWord*)list->_threads, (HeapWord*)new_list->_threads, head_length);
743   }
744   if (tail_length > 0) {
745     Copy::disjoint_words((HeapWord*)list->_threads + index + 1, (HeapWord*)new_list->_threads + index, tail_length);
746   }
747 
748   return new_list;
749 }
750 
ThreadsListHandle(Thread * self)751 ThreadsListHandle::ThreadsListHandle(Thread *self) : _list_ptr(self, /* acquire */ true) {
752   assert(self == Thread::current(), "sanity check");
753   if (EnableThreadSMRStatistics) {
754     _timer.start();
755   }
756 }
757 
~ThreadsListHandle()758 ThreadsListHandle::~ThreadsListHandle() {
759   if (EnableThreadSMRStatistics) {
760     _timer.stop();
761     uint millis = (uint)_timer.milliseconds();
762     ThreadsSMRSupport::update_tlh_stats(millis);
763   }
764 }
765 
766 // Convert an internal thread reference to a JavaThread found on the
767 // associated ThreadsList. This ThreadsListHandle "protects" the
768 // returned JavaThread *.
769 //
770 // If thread_oop_p is not NULL, then the caller wants to use the oop
771 // after this call so the oop is returned. On success, *jt_pp is set
772 // to the converted JavaThread * and true is returned. On error,
773 // returns false.
774 //
cv_internal_thread_to_JavaThread(jobject jthread,JavaThread ** jt_pp,oop * thread_oop_p)775 bool ThreadsListHandle::cv_internal_thread_to_JavaThread(jobject jthread,
776                                                          JavaThread ** jt_pp,
777                                                          oop * thread_oop_p) {
778   assert(this->list() != NULL, "must have a ThreadsList");
779   assert(jt_pp != NULL, "must have a return JavaThread pointer");
780   // thread_oop_p is optional so no assert()
781 
782   // The JVM_* interfaces don't allow a NULL thread parameter; JVM/TI
783   // allows a NULL thread parameter to signify "current thread" which
784   // allows us to avoid calling cv_external_thread_to_JavaThread().
785   // The JVM_* interfaces have no such leeway.
786 
787   oop thread_oop = JNIHandles::resolve_non_null(jthread);
788   // Looks like an oop at this point.
789   if (thread_oop_p != NULL) {
790     // Return the oop to the caller; the caller may still want
791     // the oop even if this function returns false.
792     *thread_oop_p = thread_oop;
793   }
794 
795   JavaThread *java_thread = java_lang_Thread::thread(thread_oop);
796   if (java_thread == NULL) {
797     // The java.lang.Thread does not contain a JavaThread * so it has
798     // not yet run or it has died.
799     return false;
800   }
801   // Looks like a live JavaThread at this point.
802 
803   if (java_thread != JavaThread::current()) {
804     // jthread is not for the current JavaThread so have to verify
805     // the JavaThread * against the ThreadsList.
806     if (EnableThreadSMRExtraValidityChecks && !includes(java_thread)) {
807       // Not on the JavaThreads list so it is not alive.
808       return false;
809     }
810   }
811 
812   // Return a live JavaThread that is "protected" by the
813   // ThreadsListHandle in the caller.
814   *jt_pp = java_thread;
815   return true;
816 }
817 
add_thread(JavaThread * thread)818 void ThreadsSMRSupport::add_thread(JavaThread *thread){
819   ThreadsList *new_list = ThreadsList::add_thread(get_java_thread_list(), thread);
820   if (EnableThreadSMRStatistics) {
821     inc_java_thread_list_alloc_cnt();
822     update_java_thread_list_max(new_list->length());
823   }
824   // Initial _java_thread_list will not generate a "Threads::add" mesg.
825   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::add: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
826 
827   ThreadsList *old_list = xchg_java_thread_list(new_list);
828   free_list(old_list);
829   if (ThreadIdTable::is_initialized()) {
830     jlong tid = SharedRuntime::get_java_tid(thread);
831     ThreadIdTable::add_thread(tid, thread);
832   }
833 }
834 
835 // set_delete_notify() and clear_delete_notify() are called
836 // under the protection of the delete_lock, but we also use an
837 // Atomic operation to ensure the memory update is seen earlier than
838 // when the delete_lock is dropped.
839 //
clear_delete_notify()840 void ThreadsSMRSupport::clear_delete_notify() {
841   Atomic::dec(&_delete_notify);
842 }
843 
delete_notify()844 bool ThreadsSMRSupport::delete_notify() {
845   // Use load_acquire() in order to see any updates to _delete_notify
846   // earlier than when delete_lock is grabbed.
847   return (Atomic::load_acquire(&_delete_notify) != 0);
848 }
849 
850 // Safely free a ThreadsList after a Threads::add() or Threads::remove().
851 // The specified ThreadsList may not get deleted during this call if it
852 // is still in-use (referenced by a hazard ptr). Other ThreadsLists
853 // in the chain may get deleted by this call if they are no longer in-use.
free_list(ThreadsList * threads)854 void ThreadsSMRSupport::free_list(ThreadsList* threads) {
855   assert_locked_or_safepoint(Threads_lock);
856 
857   if (is_bootstrap_list(threads)) {
858     // The bootstrap list cannot be freed and is empty so
859     // it does not need to be scanned. Nothing to do here.
860     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));
861     return;
862   }
863 
864   threads->set_next_list(_to_delete_list);
865   _to_delete_list = threads;
866   if (EnableThreadSMRStatistics) {
867     _to_delete_list_cnt++;
868     if (_to_delete_list_cnt > _to_delete_list_max) {
869       _to_delete_list_max = _to_delete_list_cnt;
870     }
871   }
872 
873   // Gather a hash table of the current hazard ptrs:
874   ThreadScanHashtable *scan_table = new ThreadScanHashtable();
875   ScanHazardPtrGatherThreadsListClosure scan_cl(scan_table);
876   threads_do(&scan_cl);
877   OrderAccess::acquire(); // Must order reads of hazard ptr before reads of
878                           // nested reference counters
879 
880   // Walk through the linked list of pending freeable ThreadsLists
881   // and free the ones that are not referenced from hazard ptrs.
882   ThreadsList* current = _to_delete_list;
883   ThreadsList* prev = NULL;
884   ThreadsList* next = NULL;
885   bool threads_is_freed = false;
886   while (current != NULL) {
887     next = current->next_list();
888     if (!scan_table->has_entry((void*)current) && current->_nested_handle_cnt == 0) {
889       // This ThreadsList is not referenced by a hazard ptr.
890       if (prev != NULL) {
891         prev->set_next_list(next);
892       }
893       if (_to_delete_list == current) {
894         _to_delete_list = next;
895       }
896 
897       log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::free_list: threads=" INTPTR_FORMAT " is freed.", os::current_thread_id(), p2i(current));
898       if (current == threads) threads_is_freed = true;
899       delete current;
900       if (EnableThreadSMRStatistics) {
901         _java_thread_list_free_cnt++;
902         _to_delete_list_cnt--;
903       }
904     } else {
905       prev = current;
906     }
907     current = next;
908   }
909 
910   if (!threads_is_freed) {
911     // Only report "is not freed" on the original call to
912     // free_list() for this ThreadsList.
913     log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::free_list: threads=" INTPTR_FORMAT " is not freed.", os::current_thread_id(), p2i(threads));
914   }
915 
916   ValidateHazardPtrsClosure validate_cl;
917   threads_do(&validate_cl);
918 
919   delete scan_table;
920 }
921 
922 // Return true if the specified JavaThread is protected by a hazard
923 // pointer (ThreadsList reference). Otherwise, returns false.
924 //
is_a_protected_JavaThread(JavaThread * thread)925 bool ThreadsSMRSupport::is_a_protected_JavaThread(JavaThread *thread) {
926   assert_locked_or_safepoint(Threads_lock);
927 
928   // Gather a hash table of the JavaThreads indirectly referenced by
929   // hazard ptrs.
930   ThreadScanHashtable *scan_table = new ThreadScanHashtable();
931   ScanHazardPtrGatherProtectedThreadsClosure scan_cl(scan_table);
932   threads_do(&scan_cl);
933   OrderAccess::acquire(); // Must order reads of hazard ptr before reads of
934                           // nested reference counters
935 
936   // Walk through the linked list of pending freeable ThreadsLists
937   // and include the ones that are currently in use by a nested
938   // ThreadsListHandle in the search set.
939   ThreadsList* current = _to_delete_list;
940   while (current != NULL) {
941     if (current->_nested_handle_cnt != 0) {
942       // 'current' is in use by a nested ThreadsListHandle so the hazard
943       // ptr is protecting all the JavaThreads on that ThreadsList.
944       AddThreadHazardPointerThreadClosure add_cl(scan_table);
945       current->threads_do(&add_cl);
946     }
947     current = current->next_list();
948   }
949 
950   bool thread_is_protected = false;
951   if (scan_table->has_entry((void*)thread)) {
952     thread_is_protected = true;
953   }
954   delete scan_table;
955   return thread_is_protected;
956 }
957 
958 // Wake up portion of the release stable ThreadsList protocol;
959 // uses the delete_lock().
960 //
release_stable_list_wake_up(bool is_nested)961 void ThreadsSMRSupport::release_stable_list_wake_up(bool is_nested) {
962   const char* log_str = is_nested ? "nested hazard ptr" : "regular hazard ptr";
963 
964   // Note: delete_lock is held in smr_delete() for the entire
965   // hazard ptr search so that we do not lose this notify() if
966   // the exiting thread has to wait. That code path also holds
967   // Threads_lock (which was grabbed before delete_lock) so that
968   // threads_do() can be called. This means the system can't start a
969   // safepoint which means this thread can't take too long to get to
970   // a safepoint because of being blocked on delete_lock.
971   //
972   MonitorLocker ml(ThreadsSMRSupport::delete_lock(), Monitor::_no_safepoint_check_flag);
973   if (ThreadsSMRSupport::delete_notify()) {
974     // Notify any exiting JavaThreads that are waiting in smr_delete()
975     // that we've released a ThreadsList.
976     ml.notify_all();
977     log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::release_stable_list notified %s", os::current_thread_id(), log_str);
978   }
979 }
980 
remove_thread(JavaThread * thread)981 void ThreadsSMRSupport::remove_thread(JavaThread *thread) {
982 
983   if (ThreadIdTable::is_initialized()) {
984     jlong tid = SharedRuntime::get_java_tid(thread);
985     ThreadIdTable::remove_thread(tid);
986   }
987 
988   ThreadsList *new_list = ThreadsList::remove_thread(ThreadsSMRSupport::get_java_thread_list(), thread);
989   if (EnableThreadSMRStatistics) {
990     ThreadsSMRSupport::inc_java_thread_list_alloc_cnt();
991     // This list is smaller so no need to check for a "longest" update.
992   }
993 
994   // Final _java_thread_list will not generate a "Threads::remove" mesg.
995   log_debug(thread, smr)("tid=" UINTX_FORMAT ": Threads::remove: new ThreadsList=" INTPTR_FORMAT, os::current_thread_id(), p2i(new_list));
996 
997   ThreadsList *old_list = ThreadsSMRSupport::xchg_java_thread_list(new_list);
998   ThreadsSMRSupport::free_list(old_list);
999 }
1000 
1001 // See note for clear_delete_notify().
1002 //
set_delete_notify()1003 void ThreadsSMRSupport::set_delete_notify() {
1004   Atomic::inc(&_delete_notify);
1005 }
1006 
1007 // Safely delete a JavaThread when it is no longer in use by a
1008 // ThreadsListHandle.
1009 //
smr_delete(JavaThread * thread)1010 void ThreadsSMRSupport::smr_delete(JavaThread *thread) {
1011   elapsedTimer timer;
1012   if (EnableThreadSMRStatistics) {
1013     timer.start();
1014   }
1015 
1016   wait_until_not_protected(thread);
1017 
1018   delete thread;
1019   if (EnableThreadSMRStatistics) {
1020     timer.stop();
1021     uint millis = (uint)timer.milliseconds();
1022     ThreadsSMRSupport::inc_deleted_thread_cnt();
1023     ThreadsSMRSupport::add_deleted_thread_times(millis);
1024     ThreadsSMRSupport::update_deleted_thread_time_max(millis);
1025   }
1026 
1027   log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::smr_delete: thread=" INTPTR_FORMAT " is deleted.", os::current_thread_id(), p2i(thread));
1028 }
1029 
wait_until_not_protected(JavaThread * thread)1030 void ThreadsSMRSupport::wait_until_not_protected(JavaThread *thread) {
1031   assert(!Threads_lock->owned_by_self(), "sanity");
1032 
1033   bool has_logged_once = false;
1034 
1035   while (true) {
1036     {
1037       // Will not make a safepoint check because this JavaThread
1038       // is not on the current ThreadsList.
1039       MutexLocker ml(Threads_lock);
1040       // Cannot use a MonitorLocker helper here because we have
1041       // to drop the Threads_lock first if we wait.
1042       ThreadsSMRSupport::delete_lock()->lock_without_safepoint_check();
1043       // Set the delete_notify flag after we grab delete_lock
1044       // and before we scan hazard ptrs because we're doing
1045       // double-check locking in release_stable_list().
1046       ThreadsSMRSupport::set_delete_notify();
1047 
1048       if (!is_a_protected_JavaThread(thread)) {
1049         // This is the common case.
1050         ThreadsSMRSupport::clear_delete_notify();
1051         ThreadsSMRSupport::delete_lock()->unlock();
1052         break;
1053       }
1054       if (!has_logged_once) {
1055         has_logged_once = true;
1056         log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::wait_until_not_protected: thread=" INTPTR_FORMAT " is not deleted.", os::current_thread_id(), p2i(thread));
1057         if (log_is_enabled(Debug, os, thread)) {
1058           ScanHazardPtrPrintMatchingThreadsClosure scan_cl(thread);
1059           threads_do(&scan_cl);
1060           ThreadsList* current = _to_delete_list;
1061           while (current != NULL) {
1062             if (current->_nested_handle_cnt != 0 && current->includes(thread)) {
1063               log_debug(thread, smr)("tid=" UINTX_FORMAT ": ThreadsSMRSupport::wait_until_not_protected: found nested hazard pointer to thread=" INTPTR_FORMAT, os::current_thread_id(), p2i(thread));
1064             }
1065             current = current->next_list();
1066           }
1067         }
1068       }
1069     } // We have to drop the Threads_lock to wait or delete the thread
1070 
1071     if (EnableThreadSMRStatistics) {
1072       _delete_lock_wait_cnt++;
1073       if (_delete_lock_wait_cnt > _delete_lock_wait_max) {
1074         _delete_lock_wait_max = _delete_lock_wait_cnt;
1075       }
1076     }
1077     // Wait for a release_stable_list() call before we check again. No
1078     // safepoint check, no timeout, and not as suspend equivalent flag
1079     // because this JavaThread is not on the Threads list.
1080     ThreadsSMRSupport::delete_lock()->wait_without_safepoint_check();
1081     if (EnableThreadSMRStatistics) {
1082       _delete_lock_wait_cnt--;
1083     }
1084 
1085     ThreadsSMRSupport::clear_delete_notify();
1086     ThreadsSMRSupport::delete_lock()->unlock();
1087     // Retry the whole scenario.
1088   }
1089 }
1090 
1091 // Apply the closure to all threads in the system, with a snapshot of
1092 // all JavaThreads provided by the list parameter.
threads_do(ThreadClosure * tc,ThreadsList * list)1093 void ThreadsSMRSupport::threads_do(ThreadClosure *tc, ThreadsList *list) {
1094   list->threads_do(tc);
1095   Threads::non_java_threads_do(tc);
1096 }
1097 
1098 // Apply the closure to all threads in the system.
threads_do(ThreadClosure * tc)1099 void ThreadsSMRSupport::threads_do(ThreadClosure *tc) {
1100   threads_do(tc, _java_thread_list);
1101 }
1102 
1103 
1104 // Debug, logging, and printing stuff at the end:
1105 
1106 // Print SMR info for a SafeThreadsListPtr to a given output stream.
print_on(outputStream * st)1107 void SafeThreadsListPtr::print_on(outputStream* st) {
1108   if (this == _thread->_threads_list_ptr) {
1109     // The top level hazard ptr.
1110     st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(_list));
1111   } else {
1112     // Nested hazard ptrs.
1113     st->print(", _nested_threads_hazard_ptr=" INTPTR_FORMAT, p2i(_list));
1114   }
1115 }
1116 
1117 // Log Threads class SMR info.
log_statistics()1118 void ThreadsSMRSupport::log_statistics() {
1119   LogTarget(Info, thread, smr) log;
1120   if (log.is_enabled()) {
1121     LogStream out(log);
1122     print_info_on(&out);
1123   }
1124 }
1125 
1126 // Print SMR info for a thread to a given output stream.
print_info_on(const Thread * thread,outputStream * st)1127 void ThreadsSMRSupport::print_info_on(const Thread* thread, outputStream* st) {
1128   ThreadsList* hazard_ptr = thread->get_threads_hazard_ptr();
1129   if (hazard_ptr != NULL) {
1130     st->print(" _threads_hazard_ptr=" INTPTR_FORMAT, p2i(hazard_ptr));
1131   }
1132   if (EnableThreadSMRStatistics && thread->_threads_list_ptr != NULL) {
1133     // The count is only interesting if we have a _threads_list_ptr.
1134     st->print(", _nested_threads_hazard_ptr_cnt=%u", thread->_nested_threads_hazard_ptr_cnt);
1135   }
1136   if (SafepointSynchronize::is_at_safepoint() || Thread::current() == thread) {
1137     // It is only safe to walk the list if we're at a safepoint or the
1138     // calling thread is walking its own list.
1139     SafeThreadsListPtr* current = thread->_threads_list_ptr;
1140     if (current != NULL) {
1141       // Skip the top nesting level as it is always printed above.
1142       current = current->previous();
1143     }
1144     while (current != NULL) {
1145       current->print_on(st);
1146       current = current->previous();
1147     }
1148   }
1149 }
1150 
1151 // Print Threads class SMR info.
print_info_on(outputStream * st)1152 void ThreadsSMRSupport::print_info_on(outputStream* st) {
1153   bool needs_unlock = false;
1154   if (Threads_lock->try_lock_without_rank_check()) {
1155     // We were able to grab the Threads_lock which makes things safe for
1156     // this call, but if we are error reporting, then a nested error
1157     // could happen with the Threads_lock held.
1158     needs_unlock = true;
1159   }
1160 
1161   ThreadsList* saved_threads_list = NULL;
1162   {
1163     ThreadsListHandle tlh;  // make the current ThreadsList safe for reporting
1164     saved_threads_list = tlh.list();  // save for later comparison
1165 
1166     st->print_cr("Threads class SMR info:");
1167     st->print_cr("_java_thread_list=" INTPTR_FORMAT ", length=%u, elements={",
1168                  p2i(saved_threads_list), saved_threads_list->length());
1169     print_info_elements_on(st, saved_threads_list);
1170     st->print_cr("}");
1171   }
1172 
1173   if (_to_delete_list != NULL) {
1174     if (Threads_lock->owned_by_self()) {
1175       // Only safe if we have the Threads_lock.
1176       st->print_cr("_to_delete_list=" INTPTR_FORMAT ", length=%u, elements={",
1177                    p2i(_to_delete_list), _to_delete_list->length());
1178       print_info_elements_on(st, _to_delete_list);
1179       st->print_cr("}");
1180       for (ThreadsList *t_list = _to_delete_list->next_list();
1181            t_list != NULL; t_list = t_list->next_list()) {
1182         st->print("next-> " INTPTR_FORMAT ", length=%u, elements={",
1183                   p2i(t_list), t_list->length());
1184         print_info_elements_on(st, t_list);
1185         st->print_cr("}");
1186       }
1187     } else {
1188       st->print_cr("_to_delete_list=" INTPTR_FORMAT, p2i(_to_delete_list));
1189       st->print_cr("Skipping _to_delete_list fields and contents for safety.");
1190     }
1191   }
1192   if (EnableThreadSMRStatistics) {
1193     st->print_cr("_java_thread_list_alloc_cnt=" UINT64_FORMAT ", "
1194                  "_java_thread_list_free_cnt=" UINT64_FORMAT ", "
1195                  "_java_thread_list_max=%u, "
1196                  "_nested_thread_list_max=%u",
1197                  _java_thread_list_alloc_cnt,
1198                  _java_thread_list_free_cnt,
1199                  _java_thread_list_max,
1200                  _nested_thread_list_max);
1201     if (_tlh_cnt > 0) {
1202       st->print_cr("_tlh_cnt=%u"
1203                    ", _tlh_times=%u"
1204                    ", avg_tlh_time=%0.2f"
1205                    ", _tlh_time_max=%u",
1206                    _tlh_cnt, _tlh_times,
1207                    ((double) _tlh_times / _tlh_cnt),
1208                    _tlh_time_max);
1209     }
1210     if (_deleted_thread_cnt > 0) {
1211       st->print_cr("_deleted_thread_cnt=%u"
1212                    ", _deleted_thread_times=%u"
1213                    ", avg_deleted_thread_time=%0.2f"
1214                    ", _deleted_thread_time_max=%u",
1215                    _deleted_thread_cnt, _deleted_thread_times,
1216                    ((double) _deleted_thread_times / _deleted_thread_cnt),
1217                    _deleted_thread_time_max);
1218     }
1219     st->print_cr("_delete_lock_wait_cnt=%u, _delete_lock_wait_max=%u",
1220                  _delete_lock_wait_cnt, _delete_lock_wait_max);
1221     st->print_cr("_to_delete_list_cnt=%u, _to_delete_list_max=%u",
1222                  _to_delete_list_cnt, _to_delete_list_max);
1223   }
1224   if (needs_unlock) {
1225     Threads_lock->unlock();
1226   } else {
1227     if (_java_thread_list != saved_threads_list) {
1228       st->print_cr("The _java_thread_list has changed from " INTPTR_FORMAT
1229                    " to " INTPTR_FORMAT
1230                    " so some of the above information may be stale.",
1231                    p2i(saved_threads_list), p2i(_java_thread_list));
1232     }
1233   }
1234 }
1235 
1236 // Print ThreadsList elements (4 per line).
print_info_elements_on(outputStream * st,ThreadsList * t_list)1237 void ThreadsSMRSupport::print_info_elements_on(outputStream* st, ThreadsList* t_list) {
1238   uint cnt = 0;
1239   JavaThreadIterator jti(t_list);
1240   for (JavaThread *jt = jti.first(); jt != NULL; jt = jti.next()) {
1241     st->print(INTPTR_FORMAT, p2i(jt));
1242     if (cnt < t_list->length() - 1) {
1243       // Separate with comma or comma-space except for the last one.
1244       if (((cnt + 1) % 4) == 0) {
1245         // Four INTPTR_FORMAT fit on an 80 column line so end the
1246         // current line with just a comma.
1247         st->print_cr(",");
1248       } else {
1249         // Not the last one on the current line so use comma-space:
1250         st->print(", ");
1251       }
1252     } else {
1253       // Last one so just end the current line.
1254       st->cr();
1255     }
1256     cnt++;
1257   }
1258 }
1259