1 /*
2  * Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "logging/log.hpp"
27 #include "runtime/interfaceSupport.inline.hpp"
28 #include "runtime/mutex.hpp"
29 #include "runtime/osThread.hpp"
30 #include "runtime/safepointMechanism.inline.hpp"
31 #include "runtime/thread.inline.hpp"
32 #include "utilities/events.hpp"
33 #include "utilities/macros.hpp"
34 
35 #ifdef ASSERT
check_safepoint_state(Thread * thread,bool do_safepoint_check)36 void Monitor::check_safepoint_state(Thread* thread, bool do_safepoint_check) {
37   // If the JavaThread checks for safepoint, verify that the lock wasn't created with safepoint_check_never.
38   SafepointCheckRequired not_allowed = do_safepoint_check ?  Monitor::_safepoint_check_never :
39                                                              Monitor::_safepoint_check_always;
40   assert(!thread->is_Java_thread() || _safepoint_check_required != not_allowed,
41          "This lock should %s have a safepoint check for Java threads: %s",
42          _safepoint_check_required ? "always" : "never", name());
43 }
44 #endif // ASSERT
45 
lock(Thread * self)46 void Monitor::lock(Thread * self) {
47   check_safepoint_state(self, true);
48 
49 #ifdef CHECK_UNHANDLED_OOPS
50   // Clear unhandled oops in JavaThreads so we get a crash right away.
51   if (self->is_Java_thread()) {
52     self->clear_unhandled_oops();
53   }
54 #endif // CHECK_UNHANDLED_OOPS
55 
56   DEBUG_ONLY(check_prelock_state(self, StrictSafepointChecks));
57   assert(_owner != self, "invariant");
58 
59   Monitor* in_flight_monitor = NULL;
60   DEBUG_ONLY(int retry_cnt = 0;)
61   while (!_lock.try_lock()) {
62     // The lock is contended
63 
64   #ifdef ASSERT
65     check_block_state(self);
66     if (retry_cnt++ > 3) {
67       log_trace(vmmonitor)("JavaThread " INTPTR_FORMAT " on %d attempt trying to acquire vmmonitor %s", p2i(self), retry_cnt, _name);
68     }
69   #endif // ASSERT
70 
71     if (self->is_Java_thread()) {
72       assert(rank() > Mutex::special, "Potential deadlock with special or lesser rank mutex");
73       { ThreadBlockInVMWithDeadlockCheck tbivmdc((JavaThread *) self, &in_flight_monitor);
74         in_flight_monitor = this;  // save for ~ThreadBlockInVMWithDeadlockCheck
75         _lock.lock();
76       }
77       if (in_flight_monitor != NULL) {
78         // Not unlocked by ~ThreadBlockInVMWithDeadlockCheck
79         break;
80       }
81     } else {
82       _lock.lock();
83       break;
84     }
85   }
86 
87   assert_owner(NULL);
88   set_owner(self);
89 }
90 
lock()91 void Monitor::lock() {
92   this->lock(Thread::current());
93 }
94 
95 // Lock without safepoint check - a degenerate variant of lock() for use by
96 // JavaThreads when it is known to be safe to not check for a safepoint when
97 // acquiring this lock. If the thread blocks acquiring the lock it is not
98 // safepoint-safe and so will prevent a safepoint from being reached. If used
99 // in the wrong way this can lead to a deadlock with the safepoint code.
100 
lock_without_safepoint_check(Thread * self)101 void Monitor::lock_without_safepoint_check(Thread * self) {
102   check_safepoint_state(self, false);
103   assert(_owner != self, "invariant");
104   _lock.lock();
105   assert_owner(NULL);
106   set_owner(self);
107 }
108 
lock_without_safepoint_check()109 void Monitor::lock_without_safepoint_check() {
110   lock_without_safepoint_check(Thread::current());
111 }
112 
113 
114 // Returns true if thread succeeds in grabbing the lock, otherwise false.
115 
try_lock()116 bool Monitor::try_lock() {
117   Thread * const self = Thread::current();
118   DEBUG_ONLY(check_prelock_state(self, false);)
119 
120   if (_lock.try_lock()) {
121     assert_owner(NULL);
122     set_owner(self);
123     return true;
124   }
125   return false;
126 }
127 
release_for_safepoint()128 void Monitor::release_for_safepoint() {
129   assert_owner(NULL);
130   _lock.unlock();
131 }
132 
unlock()133 void Monitor::unlock() {
134   assert_owner(Thread::current());
135   set_owner(NULL);
136   _lock.unlock();
137 }
138 
notify()139 void Monitor::notify() {
140   assert_owner(Thread::current());
141   _lock.notify();
142 }
143 
notify_all()144 void Monitor::notify_all() {
145   assert_owner(Thread::current());
146   _lock.notify_all();
147 }
148 
149 #ifdef ASSERT
assert_wait_lock_state(Thread * self)150 void Monitor::assert_wait_lock_state(Thread* self) {
151   Monitor* least = get_least_ranked_lock_besides_this(self->owned_locks());
152   assert(least != this, "Specification of get_least_... call above");
153   if (least != NULL && least->rank() <= special) {
154     ::tty->print("Attempting to wait on monitor %s/%d while holding"
155                " lock %s/%d -- possible deadlock",
156                name(), rank(), least->name(), least->rank());
157     assert(false, "Shouldn't block(wait) while holding a lock of rank special");
158   }
159 }
160 #endif // ASSERT
161 
wait_without_safepoint_check(long timeout)162 bool Monitor::wait_without_safepoint_check(long timeout) {
163   Thread* const self = Thread::current();
164   check_safepoint_state(self, false);
165 
166   // timeout is in milliseconds - with zero meaning never timeout
167   assert(timeout >= 0, "negative timeout");
168 
169   assert_owner(self);
170   assert_wait_lock_state(self);
171 
172   // conceptually set the owner to NULL in anticipation of
173   // abdicating the lock in wait
174   set_owner(NULL);
175   int wait_status = _lock.wait(timeout);
176   set_owner(self);
177   return wait_status != 0;          // return true IFF timeout
178 }
179 
wait(long timeout,bool as_suspend_equivalent)180 bool Monitor::wait(long timeout, bool as_suspend_equivalent) {
181   Thread* const self = Thread::current();
182   check_safepoint_state(self, true);
183 
184   // timeout is in milliseconds - with zero meaning never timeout
185   assert(timeout >= 0, "negative timeout");
186 
187   assert_owner(self);
188 
189   // Safepoint checking logically implies java_thread
190   guarantee(self->is_Java_thread(), "invariant");
191   assert_wait_lock_state(self);
192 
193 #ifdef CHECK_UNHANDLED_OOPS
194   // Clear unhandled oops in JavaThreads so we get a crash right away.
195   self->clear_unhandled_oops();
196 #endif // CHECK_UNHANDLED_OOPS
197 
198   int wait_status;
199   // conceptually set the owner to NULL in anticipation of
200   // abdicating the lock in wait
201   set_owner(NULL);
202   JavaThread *jt = (JavaThread *)self;
203   Monitor* in_flight_monitor = NULL;
204 
205   {
206     ThreadBlockInVMWithDeadlockCheck tbivmdc(jt, &in_flight_monitor);
207     OSThreadWaitState osts(self->osthread(), false /* not Object.wait() */);
208     if (as_suspend_equivalent) {
209       jt->set_suspend_equivalent();
210       // cleared by handle_special_suspend_equivalent_condition() or
211       // java_suspend_self()
212     }
213 
214     wait_status = _lock.wait(timeout);
215     in_flight_monitor = this;  // save for ~ThreadBlockInVMWithDeadlockCheck
216 
217     // were we externally suspended while we were waiting?
218     if (as_suspend_equivalent && jt->handle_special_suspend_equivalent_condition()) {
219       // Our event wait has finished and we own the lock, but
220       // while we were waiting another thread suspended us. We don't
221       // want to hold the lock while suspended because that
222       // would surprise the thread that suspended us.
223       _lock.unlock();
224       jt->java_suspend_self();
225       _lock.lock();
226     }
227   }
228 
229   if (in_flight_monitor != NULL) {
230     // Not unlocked by ~ThreadBlockInVMWithDeadlockCheck
231     assert_owner(NULL);
232     // Conceptually reestablish ownership of the lock.
233     set_owner(self);
234   } else {
235     lock(self);
236   }
237 
238   return wait_status != 0;          // return true IFF timeout
239 }
240 
241 
242 // Temporary JVM_RawMonitor* support.
243 // Yet another degenerate version of Monitor::lock() or lock_without_safepoint_check()
244 // jvm_raw_lock() and _unlock() can be called by non-Java threads via JVM_RawMonitorEnter.
245 // There's no expectation that JVM_RawMonitors will interoperate properly with the native
246 // Mutex-Monitor constructs.  We happen to implement JVM_RawMonitors in terms of
247 // native Mutex-Monitors simply as a matter of convenience.
248 
jvm_raw_lock()249 void Monitor::jvm_raw_lock() {
250   _lock.lock();
251   assert_owner(NULL);
252 }
253 
jvm_raw_unlock()254 void Monitor::jvm_raw_unlock() {
255   assert_owner(NULL);
256   _lock.unlock();
257 }
258 
~Monitor()259 Monitor::~Monitor() {
260   assert_owner(NULL);
261 }
262 
ClearMonitor(Monitor * m,const char * name)263 void Monitor::ClearMonitor(Monitor * m, const char *name) {
264   m->_owner             = NULL;
265   if (name == NULL) {
266     strcpy(m->_name, "UNKNOWN");
267   } else {
268     strncpy(m->_name, name, MONITOR_NAME_LEN - 1);
269     m->_name[MONITOR_NAME_LEN - 1] = '\0';
270   }
271 }
272 
Monitor()273 Monitor::Monitor() {
274   assert(os::mutex_init_done(), "Too early!");
275   ClearMonitor(this);
276 }
277 
278 
279 // Only Threads_lock, Heap_lock and SR_lock may be safepoint_check_sometimes.
is_sometimes_ok(const char * name)280 bool is_sometimes_ok(const char* name) {
281   return (strcmp(name, "Threads_lock") == 0 || strcmp(name, "Heap_lock") == 0 || strcmp(name, "SR_lock") == 0);
282 }
283 
Monitor(int Rank,const char * name,bool allow_vm_block,SafepointCheckRequired safepoint_check_required)284 Monitor::Monitor(int Rank, const char * name, bool allow_vm_block,
285                  SafepointCheckRequired safepoint_check_required) {
286   assert(os::mutex_init_done(), "Too early!");
287   ClearMonitor(this, name);
288 #ifdef ASSERT
289   _allow_vm_block  = allow_vm_block;
290   _rank            = Rank;
291   NOT_PRODUCT(_safepoint_check_required = safepoint_check_required;)
292 
293   assert(_safepoint_check_required != Monitor::_safepoint_check_sometimes || is_sometimes_ok(name),
294          "Lock has _safepoint_check_sometimes %s", name);
295 #endif
296 }
297 
Mutex(int Rank,const char * name,bool allow_vm_block,SafepointCheckRequired safepoint_check_required)298 Mutex::Mutex(int Rank, const char * name, bool allow_vm_block,
299              SafepointCheckRequired safepoint_check_required) {
300   ClearMonitor((Monitor *) this, name);
301 #ifdef ASSERT
302   _allow_vm_block   = allow_vm_block;
303   _rank             = Rank;
304   NOT_PRODUCT(_safepoint_check_required = safepoint_check_required;)
305 
306   assert(_safepoint_check_required != Monitor::_safepoint_check_sometimes || is_sometimes_ok(name),
307          "Lock has _safepoint_check_sometimes %s", name);
308 #endif
309 }
310 
owned_by_self() const311 bool Monitor::owned_by_self() const {
312   return _owner == Thread::current();
313 }
314 
print_on_error(outputStream * st) const315 void Monitor::print_on_error(outputStream* st) const {
316   st->print("[" PTR_FORMAT, p2i(this));
317   st->print("] %s", _name);
318   st->print(" - owner thread: " PTR_FORMAT, p2i(_owner));
319 }
320 
321 // ----------------------------------------------------------------------------------
322 // Non-product code
323 
324 #ifndef PRODUCT
print_on(outputStream * st) const325 void Monitor::print_on(outputStream* st) const {
326   st->print_cr("Mutex: [" PTR_FORMAT "] %s - owner: " PTR_FORMAT,
327                p2i(this), _name, p2i(_owner));
328 }
329 #endif
330 
331 #ifndef PRODUCT
332 #ifdef ASSERT
333 
assert_owner(Thread * expected)334 void Monitor::assert_owner(Thread * expected) {
335   const char* msg = "invalid owner";
336   if (expected == NULL) {
337     msg = "should be un-owned";
338   }
339   else if (expected == Thread::current()) {
340     msg = "should be owned by current thread";
341   }
342   assert(_owner == expected,
343          "%s: owner=" INTPTR_FORMAT ", should be=" INTPTR_FORMAT,
344          msg, p2i(_owner), p2i(expected));
345 }
346 
get_least_ranked_lock(Monitor * locks)347 Monitor * Monitor::get_least_ranked_lock(Monitor * locks) {
348   Monitor *res, *tmp;
349   for (res = tmp = locks; tmp != NULL; tmp = tmp->next()) {
350     if (tmp->rank() < res->rank()) {
351       res = tmp;
352     }
353   }
354   if (!SafepointSynchronize::is_at_safepoint()) {
355     // In this case, we expect the held locks to be
356     // in increasing rank order (modulo any native ranks)
357     for (tmp = locks; tmp != NULL; tmp = tmp->next()) {
358       if (tmp->next() != NULL) {
359         assert(tmp->rank() == Mutex::native ||
360                tmp->rank() <= tmp->next()->rank(), "mutex rank anomaly?");
361       }
362     }
363   }
364   return res;
365 }
366 
get_least_ranked_lock_besides_this(Monitor * locks)367 Monitor* Monitor::get_least_ranked_lock_besides_this(Monitor* locks) {
368   Monitor *res, *tmp;
369   for (res = NULL, tmp = locks; tmp != NULL; tmp = tmp->next()) {
370     if (tmp != this && (res == NULL || tmp->rank() < res->rank())) {
371       res = tmp;
372     }
373   }
374   if (!SafepointSynchronize::is_at_safepoint()) {
375     // In this case, we expect the held locks to be
376     // in increasing rank order (modulo any native ranks)
377     for (tmp = locks; tmp != NULL; tmp = tmp->next()) {
378       if (tmp->next() != NULL) {
379         assert(tmp->rank() == Mutex::native ||
380                tmp->rank() <= tmp->next()->rank(), "mutex rank anomaly?");
381       }
382     }
383   }
384   return res;
385 }
386 
387 
contains(Monitor * locks,Monitor * lock)388 bool Monitor::contains(Monitor* locks, Monitor * lock) {
389   for (; locks != NULL; locks = locks->next()) {
390     if (locks == lock) {
391       return true;
392     }
393   }
394   return false;
395 }
396 #endif
397 
398 // Called immediately after lock acquisition or release as a diagnostic
399 // to track the lock-set of the thread and test for rank violations that
400 // might indicate exposure to deadlock.
401 // Rather like an EventListener for _owner (:>).
402 
set_owner_implementation(Thread * new_owner)403 void Monitor::set_owner_implementation(Thread *new_owner) {
404   // This function is solely responsible for maintaining
405   // and checking the invariant that threads and locks
406   // are in a 1/N relation, with some some locks unowned.
407   // It uses the Mutex::_owner, Mutex::_next, and
408   // Thread::_owned_locks fields, and no other function
409   // changes those fields.
410   // It is illegal to set the mutex from one non-NULL
411   // owner to another--it must be owned by NULL as an
412   // intermediate state.
413 
414   if (new_owner != NULL) {
415     // the thread is acquiring this lock
416 
417     assert(new_owner == Thread::current(), "Should I be doing this?");
418     assert(_owner == NULL, "setting the owner thread of an already owned mutex");
419     _owner = new_owner; // set the owner
420 
421     // link "this" into the owned locks list
422 
423 #ifdef ASSERT  // Thread::_owned_locks is under the same ifdef
424     Monitor* locks = get_least_ranked_lock(new_owner->owned_locks());
425     // Mutex::set_owner_implementation is a friend of Thread
426 
427     assert(this->rank() >= 0, "bad lock rank");
428 
429     // Deadlock avoidance rules require us to acquire Mutexes only in
430     // a global total order. For example m1 is the lowest ranked mutex
431     // that the thread holds and m2 is the mutex the thread is trying
432     // to acquire, then deadlock avoidance rules require that the rank
433     // of m2 be less than the rank of m1.
434     // The rank Mutex::native  is an exception in that it is not subject
435     // to the verification rules.
436     if (this->rank() != Mutex::native &&
437         this->rank() != Mutex::suspend_resume &&
438         locks != NULL && locks->rank() <= this->rank() &&
439         !SafepointSynchronize::is_at_safepoint()) {
440       new_owner->print_owned_locks();
441       fatal("acquiring lock %s/%d out of order with lock %s/%d -- "
442             "possible deadlock", this->name(), this->rank(),
443             locks->name(), locks->rank());
444     }
445 
446     this->_next = new_owner->_owned_locks;
447     new_owner->_owned_locks = this;
448 #endif
449 
450   } else {
451     // the thread is releasing this lock
452 
453     Thread* old_owner = _owner;
454     DEBUG_ONLY(_last_owner = old_owner;)
455 
456     assert(old_owner != NULL, "removing the owner thread of an unowned mutex");
457     assert(old_owner == Thread::current(), "removing the owner thread of an unowned mutex");
458 
459     _owner = NULL; // set the owner
460 
461 #ifdef ASSERT
462     Monitor *locks = old_owner->owned_locks();
463 
464     // remove "this" from the owned locks list
465 
466     Monitor *prev = NULL;
467     bool found = false;
468     for (; locks != NULL; prev = locks, locks = locks->next()) {
469       if (locks == this) {
470         found = true;
471         break;
472       }
473     }
474     assert(found, "Removing a lock not owned");
475     if (prev == NULL) {
476       old_owner->_owned_locks = _next;
477     } else {
478       prev->_next = _next;
479     }
480     _next = NULL;
481 #endif
482   }
483 }
484 
485 
486 // Factored out common sanity checks for locking mutex'es. Used by lock() and try_lock()
check_prelock_state(Thread * thread,bool safepoint_check)487 void Monitor::check_prelock_state(Thread *thread, bool safepoint_check) {
488   if (safepoint_check) {
489     assert((!thread->is_Java_thread() || ((JavaThread *)thread)->thread_state() == _thread_in_vm)
490            || rank() == Mutex::special, "wrong thread state for using locks");
491     if (thread->is_VM_thread() && !allow_vm_block()) {
492       fatal("VM thread using lock %s (not allowed to block on)", name());
493     }
494     DEBUG_ONLY(if (rank() != Mutex::special) \
495                thread->check_for_valid_safepoint_state(false);)
496   }
497   assert(!os::ThreadCrashProtection::is_crash_protected(thread),
498          "locking not allowed when crash protection is set");
499 }
500 
check_block_state(Thread * thread)501 void Monitor::check_block_state(Thread *thread) {
502   if (!_allow_vm_block && thread->is_VM_thread()) {
503     warning("VM thread blocked on lock");
504     print();
505     BREAKPOINT;
506   }
507   assert(_owner != thread, "deadlock: blocking on monitor owned by current thread");
508 }
509 
510 #endif // PRODUCT
511