1 /*
  2  * Copyright (c) 1998, 2024, 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/log.hpp"
 27 #include "memory/resourceArea.hpp"
 28 #include "runtime/interfaceSupport.inline.hpp"
 29 #include "runtime/javaThread.inline.hpp"
 30 #include "runtime/mutex.hpp"
 31 #include "runtime/os.inline.hpp"
 32 #include "runtime/osThread.hpp"
 33 #include "runtime/safepointMechanism.inline.hpp"
 34 #include "runtime/semaphore.inline.hpp"
 35 #include "runtime/threadCrashProtection.hpp"
 36 #include "utilities/events.hpp"
 37 #include "utilities/macros.hpp"
 38 
 39 class InFlightMutexRelease {
 40  private:
 41   Mutex* _in_flight_mutex;
 42  public:
 43   InFlightMutexRelease(Mutex* in_flight_mutex) : _in_flight_mutex(in_flight_mutex) {
 44     assert(in_flight_mutex != nullptr, "must be");
 45   }
 46   void operator()(JavaThread* current) {
 47     _in_flight_mutex->release_for_safepoint();
 48     _in_flight_mutex = nullptr;
 49   }
 50   bool not_released() { return _in_flight_mutex != nullptr; }
 51 };
 52 
 53 #ifdef ASSERT
 54 void Mutex::check_block_state(Thread* thread) {
 55   if (!_allow_vm_block && thread->is_VM_thread()) {
 56     // JavaThreads are checked to make sure that they do not hold _allow_vm_block locks during operations
 57     // that could safepoint.  Make sure the vm thread never uses locks with _allow_vm_block == false.
 58     fatal("VM thread could block on lock that may be held by a JavaThread during safepoint: %s", name());
 59   }
 60 
 61   assert(!ThreadCrashProtection::is_crash_protected(thread),
 62          "locking not allowed when crash protection is set");
 63 }
 64 
 65 void Mutex::check_safepoint_state(Thread* thread) {
 66   check_block_state(thread);
 67 
 68   // If the lock acquisition checks for safepoint, verify that the lock was created with rank that
 69   // has safepoint checks. Technically this doesn't affect NonJavaThreads since they won't actually
 70   // check for safepoint, but let's make the rule unconditional unless there's a good reason not to.
 71   assert(_rank > nosafepoint,
 72          "This lock should not be taken with a safepoint check: %s", name());
 73 
 74   if (thread->is_active_Java_thread()) {
 75     // Also check NoSafepointVerifier, and thread state is _thread_in_vm
 76     JavaThread::cast(thread)->check_for_valid_safepoint_state();
 77   }
 78 }
 79 
 80 void Mutex::check_no_safepoint_state(Thread* thread) {
 81   check_block_state(thread);
 82   assert(!thread->is_active_Java_thread() || _rank <= nosafepoint,
 83          "This lock should always have a safepoint check for Java threads: %s",
 84          name());
 85 }
 86 #endif // ASSERT
 87 
 88 void Mutex::lock_contended(Thread* self) {
 89   DEBUG_ONLY(int retry_cnt = 0;)
 90   bool is_active_Java_thread = self->is_active_Java_thread();
 91   do {
 92     #ifdef ASSERT
 93     if (retry_cnt++ > 3) {
 94       log_trace(vmmutex)("JavaThread " INTPTR_FORMAT " on %d attempt trying to acquire vmmutex %s", p2i(self), retry_cnt, _name);
 95     }
 96     #endif // ASSERT
 97 
 98     // Is it a JavaThread participating in the safepoint protocol.
 99     if (is_active_Java_thread) {
100       InFlightMutexRelease ifmr(this);
101       assert(rank() > Mutex::nosafepoint, "Potential deadlock with nosafepoint or lesser rank mutex");
102       {
103         ThreadBlockInVMPreprocess<InFlightMutexRelease> tbivmdc(JavaThread::cast(self), ifmr);
104         _lock.lock();
105       }
106       if (ifmr.not_released()) {
107         // Not unlocked by ~ThreadBlockInVMPreprocess
108         break;
109       }
110     } else {
111       _lock.lock();
112       break;
113     }
114   } while (!_lock.try_lock());
115 }
116 
117 void Mutex::lock(Thread* self) {
118   assert(owner() != self, "invariant");
119 
120   check_safepoint_state(self);
121   check_rank(self);
122 
123   if (!_lock.try_lock()) {
124     // The lock is contended, use contended slow-path function to lock
125     lock_contended(self);
126   }
127 
128   assert_owner(nullptr);
129   set_owner(self);
130 }
131 
132 void Mutex::lock() {
133   lock(Thread::current());
134 }
135 
136 // Lock without safepoint check - a degenerate variant of lock() for use by
137 // JavaThreads when it is known to be safe to not check for a safepoint when
138 // acquiring this lock. If the thread blocks acquiring the lock it is not
139 // safepoint-safe and so will prevent a safepoint from being reached. If used
140 // in the wrong way this can lead to a deadlock with the safepoint code.
141 
142 void Mutex::lock_without_safepoint_check(Thread * self) {
143   assert(owner() != self, "invariant");
144 
145   check_no_safepoint_state(self);
146   check_rank(self);
147 
148   _lock.lock();
149   assert_owner(nullptr);
150   set_owner(self);
151 }
152 
153 void Mutex::lock_without_safepoint_check() {
154   lock_without_safepoint_check(Thread::current());
155 }
156 
157 
158 // Returns true if thread succeeds in grabbing the lock, otherwise false.
159 bool Mutex::try_lock_inner(bool do_rank_checks) {
160   Thread * const self = Thread::current();
161   // Checking the owner hides the potential difference in recursive locking behaviour
162   // on some platforms.
163   if (owner() == self) {
164     return false;
165   }
166 
167   if (do_rank_checks) {
168     check_rank(self);
169   }
170   // Some safepoint checking locks use try_lock, so cannot check
171   // safepoint state, but can check blocking state.
172   check_block_state(self);
173 
174   if (_lock.try_lock()) {
175     assert_owner(nullptr);
176     set_owner(self);
177     return true;
178   }
179   return false;
180 }
181 
182 bool Mutex::try_lock() {
183   return try_lock_inner(true /* do_rank_checks */);
184 }
185 
186 bool Mutex::try_lock_without_rank_check() {
187   bool res = try_lock_inner(false /* do_rank_checks */);
188   DEBUG_ONLY(if (res) _skip_rank_check = true;)
189   return res;
190 }
191 
192 void Mutex::release_for_safepoint() {
193   assert_owner(nullptr);
194   _lock.unlock();
195 }
196 
197 void Mutex::unlock() {
198   DEBUG_ONLY(assert_owner(Thread::current()));
199   set_owner(nullptr);
200   _lock.unlock();
201 }
202 
203 void Monitor::notify() {
204   DEBUG_ONLY(assert_owner(Thread::current()));
205   _lock.notify();
206 }
207 
208 void Monitor::notify_all() {
209   DEBUG_ONLY(assert_owner(Thread::current()));
210   _lock.notify_all();
211 }
212 
213 // timeout is in milliseconds - with zero meaning never timeout
214 bool Monitor::wait_without_safepoint_check(uint64_t timeout) {
215   Thread* const self = Thread::current();
216 
217   assert_owner(self);
218   check_rank(self);
219 
220   // conceptually set the owner to null in anticipation of
221   // abdicating the lock in wait
222   set_owner(nullptr);
223 
224   // Check safepoint state after resetting owner and possible NSV.
225   check_no_safepoint_state(self);
226 
227   int wait_status = _lock.wait(timeout);
228   set_owner(self);
229   return wait_status != 0;          // return true IFF timeout
230 }
231 
232 // timeout is in milliseconds - with zero meaning never timeout
233 bool Monitor::wait(uint64_t timeout) {
234   JavaThread* const self = JavaThread::current();
235   // Safepoint checking logically implies an active JavaThread.
236   assert(self->is_active_Java_thread(), "invariant");
237 
238   assert_owner(self);
239   check_rank(self);
240 
241   // conceptually set the owner to null in anticipation of
242   // abdicating the lock in wait
243   set_owner(nullptr);
244 
245   // Check safepoint state after resetting owner and possible NSV.
246   check_safepoint_state(self);
247 
248   int wait_status;
249   InFlightMutexRelease ifmr(this);
250 
251   {
252     ThreadBlockInVMPreprocess<InFlightMutexRelease> tbivmdc(self, ifmr);
253     OSThreadWaitState osts(self->osthread(), false /* not Object.wait() */);
254 
255     wait_status = _lock.wait(timeout);
256   }
257 
258   if (ifmr.not_released()) {
259     // Not unlocked by ~ThreadBlockInVMPreprocess
260     assert_owner(nullptr);
261     // Conceptually reestablish ownership of the lock.
262     set_owner(self);
263   } else {
264     lock(self);
265   }
266 
267   return wait_status != 0;          // return true IFF timeout
268 }
269 
270 static const int MAX_NUM_MUTEX = 1204;
271 static Mutex* _internal_mutex_arr[MAX_NUM_MUTEX];
272 Mutex** Mutex::_mutex_array = _internal_mutex_arr;
273 int Mutex::_num_mutex = 0;
274 
275 void Mutex::add_mutex(Mutex* var) {
276   assert(Mutex::_num_mutex < MAX_NUM_MUTEX, "increase MAX_NUM_MUTEX");
277   Mutex::_mutex_array[_num_mutex++] = var;
278 }
279 
280 Mutex::~Mutex() {
281   assert_owner(nullptr);
282   os::free(const_cast<char*>(_name));
283 }
284 
285 Mutex::Mutex(Rank rank, const char * name, bool allow_vm_block) : _owner(nullptr) {
286   assert(os::mutex_init_done(), "Too early!");
287   assert(name != nullptr, "Mutex requires a name");
288   _name = os::strdup(name, mtInternal);
289 #ifdef ASSERT
290   _allow_vm_block  = allow_vm_block;
291   _rank            = rank;
292   _skip_rank_check = false;
293 
294   assert(_rank >= static_cast<Rank>(0) && _rank <= safepoint, "Bad lock rank %s: %s", rank_name(), name);
295 
296   // The allow_vm_block also includes allowing other non-Java threads to block or
297   // allowing Java threads to block in native.
298   assert(_rank > nosafepoint || _allow_vm_block,
299          "Locks that don't check for safepoint should always allow the vm to block: %s", name);
300 #endif
301 }
302 
303 bool Mutex::owned_by_self() const {
304   return owner() == Thread::current();
305 }
306 
307 void Mutex::print_on_error(outputStream* st) const {
308   st->print("[" PTR_FORMAT, p2i(this));
309   st->print("] %s", _name);
310   st->print(" - owner thread: " PTR_FORMAT, p2i(owner()));
311 }
312 
313 // ----------------------------------------------------------------------------------
314 // Non-product code
315 //
316 #ifdef ASSERT
317 static Mutex::Rank _ranks[] = { Mutex::event, Mutex::service, Mutex::stackwatermark, Mutex::tty, Mutex::oopstorage,
318                                 Mutex::nosafepoint, Mutex::safepoint };
319 
320 static const char* _rank_names[] = { "event", "service", "stackwatermark", "tty", "oopstorage",
321                                      "nosafepoint", "safepoint" };
322 
323 static const int _num_ranks = 7;
324 
325 static const char* rank_name_internal(Mutex::Rank r) {
326   // Find closest rank and print out the name
327   stringStream st;
328   for (int i = 0; i < _num_ranks; i++) {
329     if (r == _ranks[i]) {
330       return _rank_names[i];
331     } else if (r  > _ranks[i] && (i < _num_ranks-1 && r < _ranks[i+1])) {
332       int delta = static_cast<int>(_ranks[i+1]) - static_cast<int>(r);
333       st.print("%s-%d", _rank_names[i+1], delta);
334       return st.as_string();
335     }
336   }
337   return "fail";
338 }
339 
340 const char* Mutex::rank_name() const {
341   return rank_name_internal(_rank);
342 }
343 
344 
345 void Mutex::assert_no_overlap(Rank orig, Rank adjusted, int adjust) {
346   int i = 0;
347   while (_ranks[i] < orig) i++;
348   // underflow is caught in constructor
349   if (i != 0 && adjusted > event && adjusted <= _ranks[i-1]) {
350     ResourceMark rm;
351     assert(adjusted > _ranks[i-1],
352            "Rank %s-%d overlaps with %s",
353            rank_name_internal(orig), adjust, rank_name_internal(adjusted));
354   }
355 }
356 #endif // ASSERT
357 
358 #ifndef PRODUCT
359 void Mutex::print_on(outputStream* st) const {
360   st->print("Mutex: [" PTR_FORMAT "] %s - owner: " PTR_FORMAT,
361             p2i(this), _name, p2i(owner()));
362   if (_allow_vm_block) {
363     st->print("%s", " allow_vm_block");
364   }
365   DEBUG_ONLY(st->print(" %s", rank_name()));
366   st->cr();
367 }
368 
369 void Mutex::print() const {
370   print_on(::tty);
371 }
372 #endif // PRODUCT
373 
374 #ifdef ASSERT
375 void Mutex::assert_owner(Thread * expected) {
376   const char* msg = "invalid owner";
377   if (expected == nullptr) {
378     msg = "should be un-owned";
379   }
380   else if (expected == Thread::current()) {
381     msg = "should be owned by current thread";
382   }
383   assert(owner() == expected,
384          "%s: owner=" INTPTR_FORMAT ", should be=" INTPTR_FORMAT,
385          msg, p2i(owner()), p2i(expected));
386 }
387 
388 Mutex* Mutex::get_least_ranked_lock(Mutex* locks) {
389   Mutex *res, *tmp;
390   for (res = tmp = locks; tmp != nullptr; tmp = tmp->next()) {
391     if (tmp->rank() < res->rank()) {
392       res = tmp;
393     }
394   }
395   return res;
396 }
397 
398 Mutex* Mutex::get_least_ranked_lock_besides_this(Mutex* locks) {
399   Mutex *res, *tmp;
400   for (res = nullptr, tmp = locks; tmp != nullptr; tmp = tmp->next()) {
401     if (tmp != this && (res == nullptr || tmp->rank() < res->rank())) {
402       res = tmp;
403     }
404   }
405   assert(res != this, "invariant");
406   return res;
407 }
408 
409 // Tests for rank violations that might indicate exposure to deadlock.
410 void Mutex::check_rank(Thread* thread) {
411   Mutex* locks_owned = thread->owned_locks();
412 
413   // We expect the locks already acquired to be in increasing rank order,
414   // modulo locks acquired in try_lock_without_rank_check()
415   for (Mutex* tmp = locks_owned; tmp != nullptr; tmp = tmp->next()) {
416     if (tmp->next() != nullptr) {
417       assert(tmp->rank() < tmp->next()->rank()
418              || tmp->skip_rank_check(), "mutex rank anomaly?");
419     }
420   }
421 
422   if (owned_by_self()) {
423     // wait() case
424     Mutex* least = get_least_ranked_lock_besides_this(locks_owned);
425     // For JavaThreads, we enforce not holding locks of rank nosafepoint or lower while waiting
426     // because the held lock has a NoSafepointVerifier so waiting on a lower ranked lock will not be
427     // able to check for safepoints first with a TBIVM.
428     // For all threads, we enforce not holding the tty lock or below, since this could block progress also.
429     // Also "this" should be the monitor with lowest rank owned by this thread.
430     if (least != nullptr && ((least->rank() <= Mutex::nosafepoint && thread->is_Java_thread()) ||
431                            least->rank() <= Mutex::tty ||
432                            least->rank() <= this->rank())) {
433       ResourceMark rm(thread);
434       assert(false, "Attempting to wait on monitor %s/%s while holding lock %s/%s -- "
435              "possible deadlock. %s", name(), rank_name(), least->name(), least->rank_name(),
436              least->rank() <= this->rank() ?
437               "Should wait on the least ranked monitor from all owned locks." :
438              thread->is_Java_thread() ?
439               "Should not block(wait) while holding a lock of rank nosafepoint or below." :
440               "Should not block(wait) while holding a lock of rank tty or below.");
441     }
442   } else {
443     // lock()/lock_without_safepoint_check()/try_lock() case
444     Mutex* least = get_least_ranked_lock(locks_owned);
445     // Deadlock prevention rules require us to acquire Mutexes only in
446     // a global total order. For example, if m1 is the lowest ranked mutex
447     // that the thread holds and m2 is the mutex the thread is trying
448     // to acquire, then deadlock prevention rules require that the rank
449     // of m2 be less than the rank of m1. This prevents circular waits.
450     if (least != nullptr && least->rank() <= this->rank()) {
451       ResourceMark rm(thread);
452       if (least->rank() > Mutex::tty) {
453         // Printing owned locks acquires tty lock. If the least rank was below or equal
454         // tty, then deadlock detection code would circle back here, until we run
455         // out of stack and crash hard. Print locks only when it is safe.
456         thread->print_owned_locks();
457       }
458       assert(false, "Attempting to acquire lock %s/%s out of order with lock %s/%s -- "
459              "possible deadlock", this->name(), this->rank_name(), least->name(), least->rank_name());
460     }
461   }
462 }
463 
464 // Called immediately after lock acquisition or release as a diagnostic
465 // to track the lock-set of the thread.
466 // Rather like an EventListener for _owner (:>).
467 
468 void Mutex::set_owner_implementation(Thread *new_owner) {
469   // This function is solely responsible for maintaining
470   // and checking the invariant that threads and locks
471   // are in a 1/N relation, with some some locks unowned.
472   // It uses the Mutex::_owner, Mutex::_next, and
473   // Thread::_owned_locks fields, and no other function
474   // changes those fields.
475   // It is illegal to set the mutex from one non-null
476   // owner to another--it must be owned by null as an
477   // intermediate state.
478 
479   if (new_owner != nullptr) {
480     // the thread is acquiring this lock
481 
482     assert(new_owner == Thread::current(), "Should I be doing this?");
483     assert(owner() == nullptr, "setting the owner thread of an already owned mutex");
484     raw_set_owner(new_owner); // set the owner
485 
486     // link "this" into the owned locks list
487     this->_next = new_owner->_owned_locks;
488     new_owner->_owned_locks = this;
489 
490     // NSV implied with locking allow_vm_block flag.
491     // The tty_lock is special because it is released for the safepoint by
492     // the safepoint mechanism.
493     if (new_owner->is_Java_thread() && _allow_vm_block && this != tty_lock) {
494       JavaThread::cast(new_owner)->inc_no_safepoint_count();
495     }
496 
497   } else {
498     // the thread is releasing this lock
499 
500     Thread* old_owner = owner();
501     _last_owner = old_owner;
502     _skip_rank_check = false;
503 
504     assert(old_owner != nullptr, "removing the owner thread of an unowned mutex");
505     assert(old_owner == Thread::current(), "removing the owner thread of an unowned mutex");
506 
507     raw_set_owner(nullptr); // set the owner
508 
509     Mutex* locks = old_owner->owned_locks();
510 
511     // remove "this" from the owned locks list
512 
513     Mutex* prev = nullptr;
514     bool found = false;
515     for (; locks != nullptr; prev = locks, locks = locks->next()) {
516       if (locks == this) {
517         found = true;
518         break;
519       }
520     }
521     assert(found, "Removing a lock not owned");
522     if (prev == nullptr) {
523       old_owner->_owned_locks = _next;
524     } else {
525       prev->_next = _next;
526     }
527     _next = nullptr;
528 
529     // ~NSV implied with locking allow_vm_block flag.
530     if (old_owner->is_Java_thread() && _allow_vm_block && this != tty_lock) {
531       JavaThread::cast(old_owner)->dec_no_safepoint_count();
532     }
533   }
534 }
535 #endif // ASSERT
536 
537 // Print all mutexes/monitors that are currently owned by a thread; called
538 // by fatal error handler.
539 void Mutex::print_owned_locks_on_error(outputStream* st) {
540   st->print("VM Mutex/Monitor currently owned by a thread: ");
541   bool none = true;
542   for (int i = 0; i < _num_mutex; i++) {
543     // see if it has an owner
544     if (_mutex_array[i]->owner() != nullptr) {
545       if (none) {
546         // print format used by Mutex::print_on_error()
547         st->print_cr(" ([mutex/lock_event])");
548         none = false;
549       }
550       _mutex_array[i]->print_on_error(st);
551       st->cr();
552     }
553   }
554   if (none) st->print_cr("None");
555 }
556 
557 void Mutex::print_lock_ranks(outputStream* st) {
558   st->print_cr("VM Mutex/Monitor ranks: ");
559 
560 #ifdef ASSERT
561   // Be extra defensive and figure out the bounds on
562   // ranks right here. This also saves a bit of time
563   // in the #ranks*#mutexes loop below.
564   int min_rank = INT_MAX;
565   int max_rank = INT_MIN;
566   for (int i = 0; i < _num_mutex; i++) {
567     Mutex* m = _mutex_array[i];
568     int r = (int) m->rank();
569     if (min_rank > r) min_rank = r;
570     if (max_rank < r) max_rank = r;
571   }
572 
573   // Print the listings rank by rank
574   for (int r = min_rank; r <= max_rank; r++) {
575     bool first = true;
576     for (int i = 0; i < _num_mutex; i++) {
577       Mutex* m = _mutex_array[i];
578       if (r != (int) m->rank()) continue;
579 
580       if (first) {
581         st->cr();
582         st->print_cr("Rank \"%s\":", m->rank_name());
583         first = false;
584       }
585       st->print_cr("  %s", m->name());
586     }
587   }
588 #else
589   st->print_cr("  Only known in debug builds.");
590 #endif // ASSERT
591 }
592 
593 RecursiveMutex::RecursiveMutex() : _sem(1), _owner(nullptr), _recursions(0) {}
594 
595 void RecursiveMutex::lock(Thread* current) {
596   assert(current == Thread::current(), "must be current thread");
597   if (current == _owner) {
598     _recursions++;
599   } else {
600     // can be called by jvmti by VMThread.
601     if (current->is_Java_thread()) {
602       _sem.wait_with_safepoint_check(JavaThread::cast(current));
603     } else {
604       _sem.wait();
605     }
606     _recursions++;
607     assert(_recursions == 1, "should be");
608     _owner = current;
609   }
610 }
611 
612 void RecursiveMutex::unlock(Thread* current) {
613   assert(current == Thread::current(), "must be current thread");
614   assert(current == _owner, "must be owner");
615   _recursions--;
616   if (_recursions == 0) {
617     _owner = nullptr;
618     _sem.signal();
619   }
620 }