1 /* 2 * Copyright (c) 1998, 2020, 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 "compiler/compileBroker.hpp" 27 #include "gc/shared/collectedHeap.hpp" 28 #include "jfr/jfrEvents.hpp" 29 #include "jfr/support/jfrThreadId.hpp" 30 #include "logging/log.hpp" 31 #include "logging/logStream.hpp" 32 #include "logging/logConfiguration.hpp" 33 #include "memory/resourceArea.hpp" 34 #include "memory/universe.hpp" 35 #include "oops/method.hpp" 36 #include "oops/oop.inline.hpp" 37 #include "oops/verifyOopClosure.hpp" 38 #include "runtime/atomic.hpp" 39 #include "runtime/handles.inline.hpp" 40 #include "runtime/interfaceSupport.inline.hpp" 41 #include "runtime/mutexLocker.hpp" 42 #include "runtime/os.hpp" 43 #include "runtime/safepoint.hpp" 44 #include "runtime/synchronizer.hpp" 45 #include "runtime/thread.inline.hpp" 46 #include "runtime/vmThread.hpp" 47 #include "runtime/vmOperations.hpp" 48 #include "services/runtimeService.hpp" 49 #include "utilities/dtrace.hpp" 50 #include "utilities/events.hpp" 51 #include "utilities/vmError.hpp" 52 #include "utilities/xmlstream.hpp" 53 54 VM_QueueHead VMOperationQueue::_queue_head[VMOperationQueue::nof_priorities]; 55 56 VMOperationQueue::VMOperationQueue() { 57 // The queue is a circular doubled-linked list, which always contains 58 // one element (i.e., one element means empty). 59 for(int i = 0; i < nof_priorities; i++) { 60 _queue_length[i] = 0; 61 _queue_counter = 0; 62 _queue[i] = &_queue_head[i]; 63 _queue[i]->set_next(_queue[i]); 64 _queue[i]->set_prev(_queue[i]); 65 } 66 } 67 68 69 bool VMOperationQueue::queue_empty(int prio) { 70 // It is empty if there is exactly one element 71 bool empty = (_queue[prio] == _queue[prio]->next()); 72 assert( (_queue_length[prio] == 0 && empty) || 73 (_queue_length[prio] > 0 && !empty), "sanity check"); 74 return _queue_length[prio] == 0; 75 } 76 77 // Inserts an element to the right of the q element 78 void VMOperationQueue::insert(VM_Operation* q, VM_Operation* n) { 79 assert(q->next()->prev() == q && q->prev()->next() == q, "sanity check"); 80 n->set_prev(q); 81 n->set_next(q->next()); 82 q->next()->set_prev(n); 83 q->set_next(n); 84 } 85 86 void VMOperationQueue::queue_add(int prio, VM_Operation *op) { 87 _queue_length[prio]++; 88 insert(_queue[prio]->prev(), op); 89 } 90 91 92 void VMOperationQueue::unlink(VM_Operation* q) { 93 assert(q->next()->prev() == q && q->prev()->next() == q, "sanity check"); 94 q->prev()->set_next(q->next()); 95 q->next()->set_prev(q->prev()); 96 } 97 98 VM_Operation* VMOperationQueue::queue_remove_front(int prio) { 99 if (queue_empty(prio)) return NULL; 100 assert(_queue_length[prio] >= 0, "sanity check"); 101 _queue_length[prio]--; 102 VM_Operation* r = _queue[prio]->next(); 103 assert(r != _queue[prio], "cannot remove base element"); 104 unlink(r); 105 return r; 106 } 107 108 //----------------------------------------------------------------- 109 // High-level interface 110 void VMOperationQueue::add(VM_Operation *op) { 111 112 HOTSPOT_VMOPS_REQUEST( 113 (char *) op->name(), strlen(op->name()), 114 op->evaluate_at_safepoint() ? 0 : 1); 115 116 // Encapsulates VM queue policy. Currently, that 117 // only involves putting them on the right list 118 queue_add(op->evaluate_at_safepoint() ? SafepointPriority : MediumPriority, op); 119 } 120 121 VM_Operation* VMOperationQueue::remove_next() { 122 // Assuming VMOperation queue is two-level priority queue. If there are 123 // more than two priorities, we need a different scheduling algorithm. 124 assert(SafepointPriority == 0 && MediumPriority == 1 && nof_priorities == 2, 125 "current algorithm does not work"); 126 127 // simple counter based scheduling to prevent starvation of lower priority 128 // queue. -- see 4390175 129 int high_prio, low_prio; 130 if (_queue_counter++ < 10) { 131 high_prio = SafepointPriority; 132 low_prio = MediumPriority; 133 } else { 134 _queue_counter = 0; 135 high_prio = MediumPriority; 136 low_prio = SafepointPriority; 137 } 138 139 return queue_remove_front(queue_empty(high_prio) ? low_prio : high_prio); 140 } 141 142 //------------------------------------------------------------------------------------------------------------------ 143 // Timeout machinery 144 145 void VMOperationTimeoutTask::task() { 146 assert(AbortVMOnVMOperationTimeout, "only if enabled"); 147 if (is_armed()) { 148 jlong delay = nanos_to_millis(os::javaTimeNanos() - _arm_time); 149 if (delay > AbortVMOnVMOperationTimeoutDelay) { 150 fatal("VM operation took too long: " JLONG_FORMAT " ms (timeout: " INTX_FORMAT " ms)", 151 delay, AbortVMOnVMOperationTimeoutDelay); 152 } 153 } 154 } 155 156 bool VMOperationTimeoutTask::is_armed() { 157 return Atomic::load_acquire(&_armed) != 0; 158 } 159 160 void VMOperationTimeoutTask::arm() { 161 _arm_time = os::javaTimeNanos(); 162 Atomic::release_store_fence(&_armed, 1); 163 } 164 165 void VMOperationTimeoutTask::disarm() { 166 Atomic::release_store_fence(&_armed, 0); 167 } 168 169 //------------------------------------------------------------------------------------------------------------------ 170 // Implementation of VMThread stuff 171 172 bool VMThread::_should_terminate = false; 173 bool VMThread::_terminated = false; 174 Monitor* VMThread::_terminate_lock = NULL; 175 VMThread* VMThread::_vm_thread = NULL; 176 VM_Operation* VMThread::_cur_vm_operation = NULL; 177 VMOperationQueue* VMThread::_vm_queue = NULL; 178 PerfCounter* VMThread::_perf_accumulated_vm_operation_time = NULL; 179 VMOperationTimeoutTask* VMThread::_timeout_task = NULL; 180 181 182 void VMThread::create() { 183 assert(vm_thread() == NULL, "we can only allocate one VMThread"); 184 _vm_thread = new VMThread(); 185 186 if (AbortVMOnVMOperationTimeout) { 187 // Make sure we call the timeout task frequently enough, but not too frequent. 188 // Try to make the interval 10% of the timeout delay, so that we miss the timeout 189 // by those 10% at max. Periodic task also expects it to fit min/max intervals. 190 size_t interval = (size_t)AbortVMOnVMOperationTimeoutDelay / 10; 191 interval = interval / PeriodicTask::interval_gran * PeriodicTask::interval_gran; 192 interval = MAX2<size_t>(interval, PeriodicTask::min_interval); 193 interval = MIN2<size_t>(interval, PeriodicTask::max_interval); 194 195 _timeout_task = new VMOperationTimeoutTask(interval); 196 _timeout_task->enroll(); 197 } else { 198 assert(_timeout_task == NULL, "sanity"); 199 } 200 201 // Create VM operation queue 202 _vm_queue = new VMOperationQueue(); 203 guarantee(_vm_queue != NULL, "just checking"); 204 205 _terminate_lock = new Monitor(Mutex::safepoint, "VMThread::_terminate_lock", true, 206 Monitor::_safepoint_check_never); 207 208 if (UsePerfData) { 209 // jvmstat performance counters 210 Thread* THREAD = Thread::current(); 211 _perf_accumulated_vm_operation_time = 212 PerfDataManager::create_counter(SUN_THREADS, "vmOperationTime", 213 PerfData::U_Ticks, CHECK); 214 } 215 } 216 217 VMThread::VMThread() : NamedThread() { 218 set_name("VM Thread"); 219 } 220 221 void VMThread::destroy() { 222 _vm_thread = NULL; // VM thread is gone 223 } 224 225 static VM_None halt_op("Halt"); 226 227 void VMThread::run() { 228 assert(this == vm_thread(), "check"); 229 230 // Notify_lock wait checks on active_handles() to rewait in 231 // case of spurious wakeup, it should wait on the last 232 // value set prior to the notify 233 this->set_active_handles(JNIHandleBlock::allocate_block()); 234 235 { 236 MutexLocker ml(Notify_lock); 237 Notify_lock->notify(); 238 } 239 // Notify_lock is destroyed by Threads::create_vm() 240 241 int prio = (VMThreadPriority == -1) 242 ? os::java_to_os_priority[NearMaxPriority] 243 : VMThreadPriority; 244 // Note that I cannot call os::set_priority because it expects Java 245 // priorities and I am *explicitly* using OS priorities so that it's 246 // possible to set the VM thread priority higher than any Java thread. 247 os::set_native_priority( this, prio ); 248 249 // Wait for VM_Operations until termination 250 this->loop(); 251 252 // Note the intention to exit before safepointing. 253 // 6295565 This has the effect of waiting for any large tty 254 // outputs to finish. 255 if (xtty != NULL) { 256 ttyLocker ttyl; 257 xtty->begin_elem("destroy_vm"); 258 xtty->stamp(); 259 xtty->end_elem(); 260 assert(should_terminate(), "termination flag must be set"); 261 } 262 263 if (log_is_enabled(Info, monitorinflation)) { 264 // Do a deflation in order to reduce the in-use monitor population 265 // that is reported by ObjectSynchronizer::log_in_use_monitor_details() 266 // at VM exit. 267 ObjectSynchronizer::request_deflate_idle_monitors(); 268 } 269 270 // 4526887 let VM thread exit at Safepoint 271 _cur_vm_operation = &halt_op; 272 SafepointSynchronize::begin(); 273 274 if (VerifyBeforeExit) { 275 HandleMark hm(VMThread::vm_thread()); 276 // Among other things, this ensures that Eden top is correct. 277 Universe::heap()->prepare_for_verify(); 278 // Silent verification so as not to pollute normal output, 279 // unless we really asked for it. 280 Universe::verify(); 281 } 282 283 CompileBroker::set_should_block(); 284 285 // wait for threads (compiler threads or daemon threads) in the 286 // _thread_in_native state to block. 287 VM_Exit::wait_for_threads_in_native_to_block(); 288 289 // signal other threads that VM process is gone 290 { 291 // Note: we must have the _no_safepoint_check_flag. Mutex::lock() allows 292 // VM thread to enter any lock at Safepoint as long as its _owner is NULL. 293 // If that happens after _terminate_lock->wait() has unset _owner 294 // but before it actually drops the lock and waits, the notification below 295 // may get lost and we will have a hang. To avoid this, we need to use 296 // Mutex::lock_without_safepoint_check(). 297 MonitorLocker ml(_terminate_lock, Mutex::_no_safepoint_check_flag); 298 _terminated = true; 299 ml.notify(); 300 } 301 302 // We are now racing with the VM termination being carried out in 303 // another thread, so we don't "delete this". Numerous threads don't 304 // get deleted when the VM terminates 305 306 } 307 308 309 // Notify the VMThread that the last non-daemon JavaThread has terminated, 310 // and wait until operation is performed. 311 void VMThread::wait_for_vm_thread_exit() { 312 assert(Thread::current()->is_Java_thread(), "Should be a JavaThread"); 313 assert(((JavaThread*)Thread::current())->is_terminated(), "Should be terminated"); 314 { MonitorLocker mu(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 315 _should_terminate = true; 316 mu.notify(); 317 } 318 319 // Note: VM thread leaves at Safepoint. We are not stopped by Safepoint 320 // because this thread has been removed from the threads list. But anything 321 // that could get blocked by Safepoint should not be used after this point, 322 // otherwise we will hang, since there is no one can end the safepoint. 323 324 // Wait until VM thread is terminated 325 // Note: it should be OK to use Terminator_lock here. But this is called 326 // at a very delicate time (VM shutdown) and we are operating in non- VM 327 // thread at Safepoint. It's safer to not share lock with other threads. 328 { MonitorLocker ml(_terminate_lock, Mutex::_no_safepoint_check_flag); 329 while(!VMThread::is_terminated()) { 330 ml.wait(); 331 } 332 } 333 } 334 335 static void post_vm_operation_event(EventExecuteVMOperation* event, VM_Operation* op) { 336 assert(event != NULL, "invariant"); 337 assert(event->should_commit(), "invariant"); 338 assert(op != NULL, "invariant"); 339 const bool evaluate_at_safepoint = op->evaluate_at_safepoint(); 340 event->set_operation(op->type()); 341 event->set_safepoint(evaluate_at_safepoint); 342 event->set_blocking(true); 343 event->set_caller(JFR_THREAD_ID(op->calling_thread())); 344 event->set_safepointId(evaluate_at_safepoint ? SafepointSynchronize::safepoint_id() : 0); 345 event->commit(); 346 } 347 348 void VMThread::evaluate_operation(VM_Operation* op) { 349 ResourceMark rm; 350 351 { 352 PerfTraceTime vm_op_timer(perf_accumulated_vm_operation_time()); 353 HOTSPOT_VMOPS_BEGIN( 354 (char *) op->name(), strlen(op->name()), 355 op->evaluate_at_safepoint() ? 0 : 1); 356 357 EventExecuteVMOperation event; 358 op->evaluate(); 359 if (event.should_commit()) { 360 post_vm_operation_event(&event, op); 361 } 362 363 HOTSPOT_VMOPS_END( 364 (char *) op->name(), strlen(op->name()), 365 op->evaluate_at_safepoint() ? 0 : 1); 366 } 367 368 // Mark as completed 369 op->calling_thread()->increment_vm_operation_completed_count(); 370 } 371 372 static VM_None safepointALot_op("SafepointALot"); 373 static VM_Cleanup cleanup_op; 374 375 class HandshakeALotClosure : public HandshakeClosure { 376 public: 377 HandshakeALotClosure() : HandshakeClosure("HandshakeALot") {} 378 void do_thread(Thread* thread) { 379 #ifdef ASSERT 380 assert(thread->is_Java_thread(), "must be"); 381 JavaThread* jt = (JavaThread*)thread; 382 jt->verify_states_for_handshake(); 383 #endif 384 } 385 }; 386 387 VM_Operation* VMThread::no_op_safepoint() { 388 // Check for handshakes first since we may need to return a VMop. 389 if (HandshakeALot) { 390 HandshakeALotClosure hal_cl; 391 Handshake::execute(&hal_cl); 392 } 393 // Check for a cleanup before SafepointALot to keep stats correct. 394 long interval_ms = SafepointTracing::time_since_last_safepoint_ms(); 395 bool max_time_exceeded = GuaranteedSafepointInterval != 0 && 396 (interval_ms >= GuaranteedSafepointInterval); 397 if (max_time_exceeded && SafepointSynchronize::is_cleanup_needed()) { 398 return &cleanup_op; 399 } 400 if (SafepointALot) { 401 return &safepointALot_op; 402 } 403 // Nothing to be done. 404 return NULL; 405 } 406 407 void VMThread::loop() { 408 assert(_cur_vm_operation == NULL, "no current one should be executing"); 409 410 SafepointSynchronize::init(_vm_thread); 411 412 while(true) { 413 // 414 // Wait for VM operation 415 // 416 // use no_safepoint_check to get lock without attempting to "sneak" 417 { MonitorLocker mu_queue(VMOperationQueue_lock, 418 Mutex::_no_safepoint_check_flag); 419 420 // Look for new operation 421 assert(_cur_vm_operation == NULL, "no current one should be executing"); 422 _cur_vm_operation = _vm_queue->remove_next(); 423 424 while (!should_terminate() && _cur_vm_operation == NULL) { 425 // wait with a timeout to guarantee safepoints at regular intervals 426 // (if there is cleanup work to do) 427 (void)mu_queue.wait(GuaranteedSafepointInterval); 428 429 // Support for self destruction 430 if ((SelfDestructTimer != 0) && !VMError::is_error_reported() && 431 (os::elapsedTime() > (double)SelfDestructTimer * 60.0)) { 432 tty->print_cr("VM self-destructed"); 433 exit(-1); 434 } 435 436 // If the queue contains a safepoint VM op, 437 // clean up will be done so we can skip this part. 438 if (!_vm_queue->peek_at_safepoint_priority()) { 439 440 // Have to unlock VMOperationQueue_lock just in case no_op_safepoint() 441 // has to do a handshake when HandshakeALot is enabled. 442 MutexUnlocker mul(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 443 if ((_cur_vm_operation = VMThread::no_op_safepoint()) != NULL) { 444 // Force a safepoint since we have not had one for at least 445 // 'GuaranteedSafepointInterval' milliseconds and we need to clean 446 // something. This will run all the clean-up processing that needs 447 // to be done at a safepoint. 448 SafepointSynchronize::begin(); 449 #ifdef ASSERT 450 if (GCALotAtAllSafepoints) InterfaceSupport::check_gc_alot(); 451 #endif 452 SafepointSynchronize::end(); 453 _cur_vm_operation = NULL; 454 } 455 } 456 _cur_vm_operation = _vm_queue->remove_next(); 457 } 458 459 if (should_terminate()) break; 460 } // Release mu_queue_lock 461 462 // 463 // Execute VM operation 464 // 465 { HandleMark hm(VMThread::vm_thread()); 466 467 EventMark em("Executing VM operation: %s", vm_operation()->name()); 468 assert(_cur_vm_operation != NULL, "we should have found an operation to execute"); 469 470 // If we are at a safepoint we will evaluate all the operations that 471 // follow that also require a safepoint 472 if (_cur_vm_operation->evaluate_at_safepoint()) { 473 log_debug(vmthread)("Evaluating safepoint VM operation: %s", _cur_vm_operation->name()); 474 475 SafepointSynchronize::begin(); 476 477 if (_timeout_task != NULL) { 478 _timeout_task->arm(); 479 } 480 481 evaluate_operation(_cur_vm_operation); 482 _cur_vm_operation = NULL; 483 484 if (_timeout_task != NULL) { 485 _timeout_task->disarm(); 486 } 487 488 // Complete safepoint synchronization 489 SafepointSynchronize::end(); 490 491 } else { // not a safepoint operation 492 log_debug(vmthread)("Evaluating non-safepoint VM operation: %s", _cur_vm_operation->name()); 493 if (TraceLongCompiles) { 494 elapsedTimer t; 495 t.start(); 496 evaluate_operation(_cur_vm_operation); 497 t.stop(); 498 double secs = t.seconds(); 499 if (secs * 1e3 > LongCompileThreshold) { 500 // XXX - _cur_vm_operation should not be accessed after 501 // the completed count has been incremented; the waiting 502 // thread may have already freed this memory. 503 tty->print_cr("vm %s: %3.7f secs]", _cur_vm_operation->name(), secs); 504 } 505 } else { 506 evaluate_operation(_cur_vm_operation); 507 } 508 509 _cur_vm_operation = NULL; 510 } 511 } 512 513 // 514 // Notify (potential) waiting Java thread(s) 515 { MonitorLocker mu(VMOperationRequest_lock, Mutex::_no_safepoint_check_flag); 516 mu.notify_all(); 517 } 518 } 519 } 520 521 // A SkipGCALot object is used to elide the usual effect of gc-a-lot 522 // over a section of execution by a thread. Currently, it's used only to 523 // prevent re-entrant calls to GC. 524 class SkipGCALot : public StackObj { 525 private: 526 bool _saved; 527 Thread* _t; 528 529 public: 530 #ifdef ASSERT 531 SkipGCALot(Thread* t) : _t(t) { 532 _saved = _t->skip_gcalot(); 533 _t->set_skip_gcalot(true); 534 } 535 536 ~SkipGCALot() { 537 assert(_t->skip_gcalot(), "Save-restore protocol invariant"); 538 _t->set_skip_gcalot(_saved); 539 } 540 #else 541 SkipGCALot(Thread* t) { } 542 ~SkipGCALot() { } 543 #endif 544 }; 545 546 void VMThread::execute(VM_Operation* op) { 547 Thread* t = Thread::current(); 548 549 if (!t->is_VM_thread()) { 550 SkipGCALot sgcalot(t); // avoid re-entrant attempts to gc-a-lot 551 // JavaThread or WatcherThread 552 t->check_for_valid_safepoint_state(); 553 554 // New request from Java thread, evaluate prologue 555 if (!op->doit_prologue()) { 556 return; // op was cancelled 557 } 558 559 // Setup VM_operations for execution 560 op->set_calling_thread(t); 561 562 // Get ticket number for the VM operation 563 int ticket = t->vm_operation_ticket(); 564 565 // Add VM operation to list of waiting threads. We are guaranteed not to block while holding the 566 // VMOperationQueue_lock, so we can block without a safepoint check. This allows vm operation requests 567 // to be queued up during a safepoint synchronization. 568 { 569 MonitorLocker ml(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 570 log_debug(vmthread)("Adding VM operation: %s", op->name()); 571 _vm_queue->add(op); 572 ml.notify(); 573 } 574 { 575 // Wait for completion of request 576 // Note: only a JavaThread triggers the safepoint check when locking 577 MonitorLocker ml(VMOperationRequest_lock, 578 t->is_Java_thread() ? Mutex::_safepoint_check_flag : Mutex::_no_safepoint_check_flag); 579 while(t->vm_operation_completed_count() < ticket) { 580 ml.wait(); 581 } 582 } 583 op->doit_epilogue(); 584 } else { 585 // invoked by VM thread; usually nested VM operation 586 assert(t->is_VM_thread(), "must be a VM thread"); 587 VM_Operation* prev_vm_operation = vm_operation(); 588 if (prev_vm_operation != NULL) { 589 // Check the VM operation allows nested VM operation. This normally not the case, e.g., the compiler 590 // does not allow nested scavenges or compiles. 591 if (!prev_vm_operation->allow_nested_vm_operations()) { 592 fatal("Nested VM operation %s requested by operation %s", 593 op->name(), vm_operation()->name()); 594 } 595 op->set_calling_thread(prev_vm_operation->calling_thread()); 596 } 597 598 EventMark em("Executing %s VM operation: %s", prev_vm_operation ? "nested" : "", op->name()); 599 600 // Release all internal handles after operation is evaluated 601 HandleMark hm(t); 602 _cur_vm_operation = op; 603 604 if (op->evaluate_at_safepoint() && !SafepointSynchronize::is_at_safepoint()) { 605 SafepointSynchronize::begin(); 606 op->evaluate(); 607 SafepointSynchronize::end(); 608 } else { 609 op->evaluate(); 610 } 611 612 _cur_vm_operation = prev_vm_operation; 613 } 614 } 615 616 void VMThread::verify() { 617 oops_do(&VerifyOopClosure::verify_oop, NULL); 618 }