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 36 void Mutex::check_block_state(Thread* thread) { 37 if (!_allow_vm_block && thread->is_VM_thread()) { 38 // JavaThreads are checked to make sure that they do not hold _allow_vm_block locks during operations 39 // that could safepoint. Make sure the vm thread never uses locks with _allow_vm_block == false. 40 fatal("VM thread could block on lock that may be held by a JavaThread during safepoint: %s", name()); 41 } 42 43 assert(!os::ThreadCrashProtection::is_crash_protected(thread), 44 "locking not allowed when crash protection is set"); 45 } 46 47 void Mutex::check_safepoint_state(Thread* thread) { 48 check_block_state(thread); 49 50 // If the JavaThread checks for safepoint, verify that the lock wasn't created with safepoint_check_never. 51 if (thread->is_active_Java_thread()) { 52 assert(_safepoint_check_required != _safepoint_check_never, 53 "This lock should %s have a safepoint check for Java threads: %s", 54 _safepoint_check_required ? "always" : "never", name()); 55 56 // Also check NoSafepointVerifier, and thread state is _thread_in_vm 57 thread->check_for_valid_safepoint_state(); 58 } else { 59 // If initialized with safepoint_check_never, a NonJavaThread should never ask to safepoint check either. 60 assert(_safepoint_check_required != _safepoint_check_never, 61 "NonJavaThread should not check for safepoint"); 62 } 63 } 64 65 void Mutex::check_no_safepoint_state(Thread* thread) { 66 check_block_state(thread); 67 assert(!thread->is_active_Java_thread() || _safepoint_check_required != _safepoint_check_always, 68 "This lock should %s have a safepoint check for Java threads: %s", 69 _safepoint_check_required ? "always" : "never", name()); 70 } 71 #endif // ASSERT 72 73 void Mutex::lock_contended(Thread* self) { 74 Mutex *in_flight_mutex = NULL; 75 DEBUG_ONLY(int retry_cnt = 0;) 76 bool is_active_Java_thread = self->is_active_Java_thread(); 77 do { 78 #ifdef ASSERT 79 if (retry_cnt++ > 3) { 80 log_trace(vmmutex)("JavaThread " INTPTR_FORMAT " on %d attempt trying to acquire vmmutex %s", p2i(self), retry_cnt, _name); 81 } 82 #endif // ASSERT 83 84 // Is it a JavaThread participating in the safepoint protocol. 85 if (is_active_Java_thread) { 86 assert(rank() > Mutex::special, "Potential deadlock with special or lesser rank mutex"); 87 { ThreadBlockInVMWithDeadlockCheck tbivmdc((JavaThread *) self, &in_flight_mutex); 88 in_flight_mutex = this; // save for ~ThreadBlockInVMWithDeadlockCheck 89 _lock.lock(); 90 } 91 if (in_flight_mutex != NULL) { 92 // Not unlocked by ~ThreadBlockInVMWithDeadlockCheck 93 break; 94 } 95 } else { 96 _lock.lock(); 97 break; 98 } 99 } while (!_lock.try_lock()); 100 } 101 102 void Mutex::lock(Thread* self) { 103 check_safepoint_state(self); 104 105 assert(_owner != self, "invariant"); 106 107 if (!_lock.try_lock()) { 108 // The lock is contended, use contended slow-path function to lock 109 lock_contended(self); 110 } 111 112 assert_owner(NULL); 113 set_owner(self); 114 } 115 116 void Mutex::lock() { 117 lock(Thread::current()); 118 } 119 120 // Lock without safepoint check - a degenerate variant of lock() for use by 121 // JavaThreads when it is known to be safe to not check for a safepoint when 122 // acquiring this lock. If the thread blocks acquiring the lock it is not 123 // safepoint-safe and so will prevent a safepoint from being reached. If used 124 // in the wrong way this can lead to a deadlock with the safepoint code. 125 126 void Mutex::lock_without_safepoint_check(Thread * self) { 127 check_no_safepoint_state(self); 128 assert(_owner != self, "invariant"); 129 _lock.lock(); 130 assert_owner(NULL); 131 set_owner(self); 132 } 133 134 void Mutex::lock_without_safepoint_check() { 135 lock_without_safepoint_check(Thread::current()); 136 } 137 138 139 // Returns true if thread succeeds in grabbing the lock, otherwise false. 140 141 bool Mutex::try_lock() { 142 Thread * const self = Thread::current(); 143 // Some safepoint_check_always locks use try_lock, so cannot check 144 // safepoint state, but can check blocking state. 145 check_block_state(self); 146 if (_lock.try_lock()) { 147 assert_owner(NULL); 148 set_owner(self); 149 return true; 150 } 151 return false; 152 } 153 154 void Mutex::release_for_safepoint() { 155 assert_owner(NULL); 156 _lock.unlock(); 157 } 158 159 void Mutex::unlock() { 160 DEBUG_ONLY(assert_owner(Thread::current())); 161 set_owner(NULL); 162 _lock.unlock(); 163 } 164 165 void Monitor::notify() { 166 DEBUG_ONLY(assert_owner(Thread::current())); 167 _lock.notify(); 168 } 169 170 void Monitor::notify_all() { 171 DEBUG_ONLY(assert_owner(Thread::current())); 172 _lock.notify_all(); 173 } 174 175 #ifdef ASSERT 176 void Monitor::assert_wait_lock_state(Thread* self) { 177 Mutex* least = get_least_ranked_lock_besides_this(self->owned_locks()); 178 assert(least != this, "Specification of get_least_... call above"); 179 if (least != NULL && least->rank() <= special) { 180 ::tty->print("Attempting to wait on monitor %s/%d while holding" 181 " lock %s/%d -- possible deadlock", 182 name(), rank(), least->name(), least->rank()); 183 assert(false, "Shouldn't block(wait) while holding a lock of rank special"); 184 } 185 } 186 #endif // ASSERT 187 188 bool Monitor::wait_without_safepoint_check(long timeout) { 189 Thread* const self = Thread::current(); 190 191 // timeout is in milliseconds - with zero meaning never timeout 192 assert(timeout >= 0, "negative timeout"); 193 194 assert_owner(self); 195 assert_wait_lock_state(self); 196 197 // conceptually set the owner to NULL in anticipation of 198 // abdicating the lock in wait 199 set_owner(NULL); 200 // Check safepoint state after resetting owner and possible NSV. 201 check_no_safepoint_state(self); 202 203 int wait_status = _lock.wait(timeout); 204 set_owner(self); 205 return wait_status != 0; // return true IFF timeout 206 } 207 208 bool Monitor::wait(long timeout, bool as_suspend_equivalent) { 209 Thread* const self = Thread::current(); 210 211 // timeout is in milliseconds - with zero meaning never timeout 212 assert(timeout >= 0, "negative timeout"); 213 214 assert_owner(self); 215 216 // Safepoint checking logically implies an active JavaThread. 217 guarantee(self->is_active_Java_thread(), "invariant"); 218 assert_wait_lock_state(self); 219 220 int wait_status; 221 // conceptually set the owner to NULL in anticipation of 222 // abdicating the lock in wait 223 set_owner(NULL); 224 // Check safepoint state after resetting owner and possible NSV. 225 check_safepoint_state(self); 226 JavaThread *jt = (JavaThread *)self; 227 Mutex* in_flight_mutex = NULL; 228 229 { 230 ThreadBlockInVMWithDeadlockCheck tbivmdc(jt, &in_flight_mutex); 231 OSThreadWaitState osts(self->osthread(), false /* not Object.wait() */); 232 if (as_suspend_equivalent) { 233 jt->set_suspend_equivalent(); 234 // cleared by handle_special_suspend_equivalent_condition() or 235 // java_suspend_self() 236 } 237 238 wait_status = _lock.wait(timeout); 239 in_flight_mutex = this; // save for ~ThreadBlockInVMWithDeadlockCheck 240 241 // were we externally suspended while we were waiting? 242 if (as_suspend_equivalent && jt->handle_special_suspend_equivalent_condition()) { 243 // Our event wait has finished and we own the lock, but 244 // while we were waiting another thread suspended us. We don't 245 // want to hold the lock while suspended because that 246 // would surprise the thread that suspended us. 247 _lock.unlock(); 248 jt->java_suspend_self(); 249 _lock.lock(); 250 } 251 } 252 253 if (in_flight_mutex != NULL) { 254 // Not unlocked by ~ThreadBlockInVMWithDeadlockCheck 255 assert_owner(NULL); 256 // Conceptually reestablish ownership of the lock. 257 set_owner(self); 258 } else { 259 lock(self); 260 } 261 262 return wait_status != 0; // return true IFF timeout 263 } 264 265 Mutex::~Mutex() { 266 assert_owner(NULL); 267 } 268 269 // Only Threads_lock, Heap_lock and SR_lock may be safepoint_check_sometimes. 270 bool is_sometimes_ok(const char* name) { 271 return (strcmp(name, "Threads_lock") == 0 || strcmp(name, "Heap_lock") == 0 || strcmp(name, "SR_lock") == 0); 272 } 273 274 Mutex::Mutex(int Rank, const char * name, bool allow_vm_block, 275 SafepointCheckRequired safepoint_check_required) : _owner(NULL) { 276 assert(os::mutex_init_done(), "Too early!"); 277 if (name == NULL) { 278 strcpy(_name, "UNKNOWN"); 279 } else { 280 strncpy(_name, name, MUTEX_NAME_LEN - 1); 281 _name[MUTEX_NAME_LEN - 1] = '\0'; 282 } 283 #ifdef ASSERT 284 _allow_vm_block = allow_vm_block; 285 _rank = Rank; 286 _safepoint_check_required = safepoint_check_required; 287 288 assert(_safepoint_check_required != _safepoint_check_sometimes || is_sometimes_ok(name), 289 "Lock has _safepoint_check_sometimes %s", name); 290 291 assert(_rank > special || _safepoint_check_required == _safepoint_check_never, 292 "Special locks or below should never safepoint"); 293 #endif 294 } 295 296 Monitor::Monitor(int Rank, const char * name, bool allow_vm_block, 297 SafepointCheckRequired safepoint_check_required) : 298 Mutex(Rank, name, allow_vm_block, safepoint_check_required) {} 299 300 bool Mutex::owned_by_self() const { 301 return _owner == Thread::current(); 302 } 303 304 void Mutex::print_on_error(outputStream* st) const { 305 st->print("[" PTR_FORMAT, p2i(this)); 306 st->print("] %s", _name); 307 st->print(" - owner thread: " PTR_FORMAT, p2i(_owner)); 308 } 309 310 // ---------------------------------------------------------------------------------- 311 // Non-product code 312 313 #ifndef PRODUCT 314 const char* print_safepoint_check(Mutex::SafepointCheckRequired safepoint_check) { 315 switch (safepoint_check) { 316 case Mutex::_safepoint_check_never: return "safepoint_check_never"; 317 case Mutex::_safepoint_check_sometimes: return "safepoint_check_sometimes"; 318 case Mutex::_safepoint_check_always: return "safepoint_check_always"; 319 default: return ""; 320 } 321 } 322 323 void Mutex::print_on(outputStream* st) const { 324 st->print("Mutex: [" PTR_FORMAT "] %s - owner: " PTR_FORMAT, 325 p2i(this), _name, p2i(_owner)); 326 if (_allow_vm_block) { 327 st->print("%s", " allow_vm_block"); 328 } 329 st->print(" %s", print_safepoint_check(_safepoint_check_required)); 330 st->cr(); 331 } 332 #endif 333 334 #ifdef ASSERT 335 void Mutex::assert_owner(Thread * expected) { 336 const char* msg = "invalid owner"; 337 if (expected == NULL) { 338 msg = "should be un-owned"; 339 } 340 else if (expected == Thread::current()) { 341 msg = "should be owned by current thread"; 342 } 343 assert(_owner == expected, 344 "%s: owner=" INTPTR_FORMAT ", should be=" INTPTR_FORMAT, 345 msg, p2i(_owner), p2i(expected)); 346 } 347 348 Mutex* Mutex::get_least_ranked_lock(Mutex* locks) { 349 Mutex *res, *tmp; 350 for (res = tmp = locks; tmp != NULL; tmp = tmp->next()) { 351 if (tmp->rank() < res->rank()) { 352 res = tmp; 353 } 354 } 355 if (!SafepointSynchronize::is_at_safepoint()) { 356 // In this case, we expect the held locks to be 357 // in increasing rank order (modulo any native ranks) 358 for (tmp = locks; tmp != NULL; tmp = tmp->next()) { 359 if (tmp->next() != NULL) { 360 assert(tmp->rank() == Mutex::native || 361 tmp->rank() <= tmp->next()->rank(), "mutex rank anomaly?"); 362 } 363 } 364 } 365 return res; 366 } 367 368 Mutex* Mutex::get_least_ranked_lock_besides_this(Mutex* locks) { 369 Mutex *res, *tmp; 370 for (res = NULL, tmp = locks; tmp != NULL; tmp = tmp->next()) { 371 if (tmp != this && (res == NULL || tmp->rank() < res->rank())) { 372 res = tmp; 373 } 374 } 375 if (!SafepointSynchronize::is_at_safepoint()) { 376 // In this case, we expect the held locks to be 377 // in increasing rank order (modulo any native ranks) 378 for (tmp = locks; tmp != NULL; tmp = tmp->next()) { 379 if (tmp->next() != NULL) { 380 assert(tmp->rank() == Mutex::native || 381 tmp->rank() <= tmp->next()->rank(), "mutex rank anomaly?"); 382 } 383 } 384 } 385 return res; 386 } 387 388 bool Mutex::contains(Mutex* locks, Mutex* lock) { 389 for (; locks != NULL; locks = locks->next()) { 390 if (locks == lock) { 391 return true; 392 } 393 } 394 return false; 395 } 396 397 // NSV implied with locking allow_vm_block or !safepoint_check locks. 398 void Mutex::no_safepoint_verifier(Thread* thread, bool enable) { 399 // The tty_lock is special because it is released for the safepoint by 400 // the safepoint mechanism. 401 if (this == tty_lock) { 402 return; 403 } 404 405 if (_allow_vm_block) { 406 if (enable) { 407 thread->_no_safepoint_count++; 408 } else { 409 thread->_no_safepoint_count--; 410 } 411 } 412 } 413 414 // Called immediately after lock acquisition or release as a diagnostic 415 // to track the lock-set of the thread and test for rank violations that 416 // might indicate exposure to deadlock. 417 // Rather like an EventListener for _owner (:>). 418 419 void Mutex::set_owner_implementation(Thread *new_owner) { 420 // This function is solely responsible for maintaining 421 // and checking the invariant that threads and locks 422 // are in a 1/N relation, with some some locks unowned. 423 // It uses the Mutex::_owner, Mutex::_next, and 424 // Thread::_owned_locks fields, and no other function 425 // changes those fields. 426 // It is illegal to set the mutex from one non-NULL 427 // owner to another--it must be owned by NULL as an 428 // intermediate state. 429 430 if (new_owner != NULL) { 431 // the thread is acquiring this lock 432 433 assert(new_owner == Thread::current(), "Should I be doing this?"); 434 assert(_owner == NULL, "setting the owner thread of an already owned mutex"); 435 _owner = new_owner; // set the owner 436 437 // link "this" into the owned locks list 438 439 Mutex* locks = get_least_ranked_lock(new_owner->owned_locks()); 440 // Mutex::set_owner_implementation is a friend of Thread 441 442 assert(this->rank() >= 0, "bad lock rank"); 443 444 // Deadlock avoidance rules require us to acquire Mutexes only in 445 // a global total order. For example 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 avoidance rules require that the rank 448 // of m2 be less than the rank of m1. 449 // The rank Mutex::native is an exception in that it is not subject 450 // to the verification rules. 451 if (this->rank() != Mutex::native && 452 this->rank() != Mutex::suspend_resume && 453 locks != NULL && locks->rank() <= this->rank() && 454 !SafepointSynchronize::is_at_safepoint()) { 455 new_owner->print_owned_locks(); 456 fatal("acquiring lock %s/%d out of order with lock %s/%d -- " 457 "possible deadlock", this->name(), this->rank(), 458 locks->name(), locks->rank()); 459 } 460 461 this->_next = new_owner->_owned_locks; 462 new_owner->_owned_locks = this; 463 464 // NSV implied with locking allow_vm_block flag. 465 no_safepoint_verifier(new_owner, true); 466 467 } else { 468 // the thread is releasing this lock 469 470 Thread* old_owner = _owner; 471 _last_owner = old_owner; 472 473 assert(old_owner != NULL, "removing the owner thread of an unowned mutex"); 474 assert(old_owner == Thread::current(), "removing the owner thread of an unowned mutex"); 475 476 _owner = NULL; // set the owner 477 478 Mutex* locks = old_owner->owned_locks(); 479 480 // remove "this" from the owned locks list 481 482 Mutex* prev = NULL; 483 bool found = false; 484 for (; locks != NULL; prev = locks, locks = locks->next()) { 485 if (locks == this) { 486 found = true; 487 break; 488 } 489 } 490 assert(found, "Removing a lock not owned"); 491 if (prev == NULL) { 492 old_owner->_owned_locks = _next; 493 } else { 494 prev->_next = _next; 495 } 496 _next = NULL; 497 498 // ~NSV implied with locking allow_vm_block flag. 499 no_safepoint_verifier(old_owner, false); 500 } 501 } 502 #endif // ASSERT