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