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 "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/thread.inline.hpp" 45 #include "runtime/vmThread.hpp" 46 #include "runtime/vmOperations.hpp" 47 #include "services/runtimeService.hpp" 48 #include "utilities/dtrace.hpp" 49 #include "utilities/events.hpp" 50 #include "utilities/vmError.hpp" 51 #include "utilities/xmlstream.hpp" 52 53 VMOperationQueue::VMOperationQueue() { 54 // The queue is a circular doubled-linked list, which always contains 55 // one element (i.e., one element means empty). 56 for(int i = 0; i < nof_priorities; i++) { 57 _queue_length[i] = 0; 58 _queue_counter = 0; 59 _queue[i] = new VM_None("QueueHead"); 60 _queue[i]->set_next(_queue[i]); 61 _queue[i]->set_prev(_queue[i]); 62 } 63 _drain_list = NULL; 64 } 65 66 67 bool VMOperationQueue::queue_empty(int prio) { 68 // It is empty if there is exactly one element 69 bool empty = (_queue[prio] == _queue[prio]->next()); 70 assert( (_queue_length[prio] == 0 && empty) || 71 (_queue_length[prio] > 0 && !empty), "sanity check"); 72 return _queue_length[prio] == 0; 73 } 74 75 // Inserts an element to the right of the q element 76 void VMOperationQueue::insert(VM_Operation* q, VM_Operation* n) { 77 assert(q->next()->prev() == q && q->prev()->next() == q, "sanity check"); 78 n->set_prev(q); 79 n->set_next(q->next()); 80 q->next()->set_prev(n); 81 q->set_next(n); 82 } 83 84 void VMOperationQueue::queue_add_front(int prio, VM_Operation *op) { 85 _queue_length[prio]++; 86 insert(_queue[prio]->next(), op); 87 } 88 89 void VMOperationQueue::queue_add_back(int prio, VM_Operation *op) { 90 _queue_length[prio]++; 91 insert(_queue[prio]->prev(), op); 92 } 93 94 95 void VMOperationQueue::unlink(VM_Operation* q) { 96 assert(q->next()->prev() == q && q->prev()->next() == q, "sanity check"); 97 q->prev()->set_next(q->next()); 98 q->next()->set_prev(q->prev()); 99 } 100 101 VM_Operation* VMOperationQueue::queue_remove_front(int prio) { 102 if (queue_empty(prio)) return NULL; 103 assert(_queue_length[prio] >= 0, "sanity check"); 104 _queue_length[prio]--; 105 VM_Operation* r = _queue[prio]->next(); 106 assert(r != _queue[prio], "cannot remove base element"); 107 unlink(r); 108 return r; 109 } 110 111 VM_Operation* VMOperationQueue::queue_drain(int prio) { 112 if (queue_empty(prio)) return NULL; 113 DEBUG_ONLY(int length = _queue_length[prio];); 114 assert(length >= 0, "sanity check"); 115 _queue_length[prio] = 0; 116 VM_Operation* r = _queue[prio]->next(); 117 assert(r != _queue[prio], "cannot remove base element"); 118 // remove links to base element from head and tail 119 r->set_prev(NULL); 120 _queue[prio]->prev()->set_next(NULL); 121 // restore queue to empty state 122 _queue[prio]->set_next(_queue[prio]); 123 _queue[prio]->set_prev(_queue[prio]); 124 assert(queue_empty(prio), "drain corrupted queue"); 125 #ifdef ASSERT 126 int len = 0; 127 VM_Operation* cur; 128 for(cur = r; cur != NULL; cur=cur->next()) len++; 129 assert(len == length, "drain lost some ops"); 130 #endif 131 return r; 132 } 133 134 void VMOperationQueue::queue_oops_do(int queue, OopClosure* f) { 135 VM_Operation* cur = _queue[queue]; 136 cur = cur->next(); 137 while (cur != _queue[queue]) { 138 cur->oops_do(f); 139 cur = cur->next(); 140 } 141 } 142 143 void VMOperationQueue::drain_list_oops_do(OopClosure* f) { 144 VM_Operation* cur = _drain_list; 145 while (cur != NULL) { 146 cur->oops_do(f); 147 cur = cur->next(); 148 } 149 } 150 151 //----------------------------------------------------------------- 152 // High-level interface 153 void VMOperationQueue::add(VM_Operation *op) { 154 155 HOTSPOT_VMOPS_REQUEST( 156 (char *) op->name(), strlen(op->name()), 157 op->evaluation_mode()); 158 159 // Encapsulates VM queue policy. Currently, that 160 // only involves putting them on the right list 161 queue_add_back(op->evaluate_at_safepoint() ? SafepointPriority : MediumPriority, op); 162 } 163 164 VM_Operation* VMOperationQueue::remove_next() { 165 // Assuming VMOperation queue is two-level priority queue. If there are 166 // more than two priorities, we need a different scheduling algorithm. 167 assert(SafepointPriority == 0 && MediumPriority == 1 && nof_priorities == 2, 168 "current algorithm does not work"); 169 170 // simple counter based scheduling to prevent starvation of lower priority 171 // queue. -- see 4390175 172 int high_prio, low_prio; 173 if (_queue_counter++ < 10) { 174 high_prio = SafepointPriority; 175 low_prio = MediumPriority; 176 } else { 177 _queue_counter = 0; 178 high_prio = MediumPriority; 179 low_prio = SafepointPriority; 180 } 181 182 return queue_remove_front(queue_empty(high_prio) ? low_prio : high_prio); 183 } 184 185 void VMOperationQueue::oops_do(OopClosure* f) { 186 for(int i = 0; i < nof_priorities; i++) { 187 queue_oops_do(i, f); 188 } 189 drain_list_oops_do(f); 190 } 191 192 //------------------------------------------------------------------------------------------------------------------ 193 // Timeout machinery 194 195 void VMOperationTimeoutTask::task() { 196 assert(AbortVMOnVMOperationTimeout, "only if enabled"); 197 if (is_armed()) { 198 jlong delay = (os::javaTimeMillis() - _arm_time); 199 if (delay > AbortVMOnVMOperationTimeoutDelay) { 200 fatal("VM operation took too long: " JLONG_FORMAT " ms (timeout: " INTX_FORMAT " ms)", 201 delay, AbortVMOnVMOperationTimeoutDelay); 202 } 203 } 204 } 205 206 bool VMOperationTimeoutTask::is_armed() { 207 return Atomic::load_acquire(&_armed) != 0; 208 } 209 210 void VMOperationTimeoutTask::arm() { 211 _arm_time = os::javaTimeMillis(); 212 Atomic::release_store_fence(&_armed, 1); 213 } 214 215 void VMOperationTimeoutTask::disarm() { 216 Atomic::release_store_fence(&_armed, 0); 217 } 218 219 //------------------------------------------------------------------------------------------------------------------ 220 // Implementation of VMThread stuff 221 222 bool VMThread::_should_terminate = false; 223 bool VMThread::_terminated = false; 224 Monitor* VMThread::_terminate_lock = NULL; 225 VMThread* VMThread::_vm_thread = NULL; 226 VM_Operation* VMThread::_cur_vm_operation = NULL; 227 VMOperationQueue* VMThread::_vm_queue = NULL; 228 PerfCounter* VMThread::_perf_accumulated_vm_operation_time = NULL; 229 uint64_t VMThread::_coalesced_count = 0; 230 VMOperationTimeoutTask* VMThread::_timeout_task = NULL; 231 232 233 void VMThread::create() { 234 assert(vm_thread() == NULL, "we can only allocate one VMThread"); 235 _vm_thread = new VMThread(); 236 237 if (AbortVMOnVMOperationTimeout) { 238 // Make sure we call the timeout task frequently enough, but not too frequent. 239 // Try to make the interval 10% of the timeout delay, so that we miss the timeout 240 // by those 10% at max. Periodic task also expects it to fit min/max intervals. 241 size_t interval = (size_t)AbortVMOnVMOperationTimeoutDelay / 10; 242 interval = interval / PeriodicTask::interval_gran * PeriodicTask::interval_gran; 243 interval = MAX2<size_t>(interval, PeriodicTask::min_interval); 244 interval = MIN2<size_t>(interval, PeriodicTask::max_interval); 245 246 _timeout_task = new VMOperationTimeoutTask(interval); 247 _timeout_task->enroll(); 248 } else { 249 assert(_timeout_task == NULL, "sanity"); 250 } 251 252 // Create VM operation queue 253 _vm_queue = new VMOperationQueue(); 254 guarantee(_vm_queue != NULL, "just checking"); 255 256 _terminate_lock = new Monitor(Mutex::safepoint, "VMThread::_terminate_lock", true, 257 Monitor::_safepoint_check_never); 258 259 if (UsePerfData) { 260 // jvmstat performance counters 261 Thread* THREAD = Thread::current(); 262 _perf_accumulated_vm_operation_time = 263 PerfDataManager::create_counter(SUN_THREADS, "vmOperationTime", 264 PerfData::U_Ticks, CHECK); 265 } 266 } 267 268 VMThread::VMThread() : NamedThread() { 269 set_name("VM Thread"); 270 } 271 272 void VMThread::destroy() { 273 _vm_thread = NULL; // VM thread is gone 274 } 275 276 static VM_None halt_op("Halt"); 277 278 void VMThread::run() { 279 assert(this == vm_thread(), "check"); 280 281 // Notify_lock wait checks on active_handles() to rewait in 282 // case of spurious wakeup, it should wait on the last 283 // value set prior to the notify 284 this->set_active_handles(JNIHandleBlock::allocate_block()); 285 286 { 287 MutexLocker ml(Notify_lock); 288 Notify_lock->notify(); 289 } 290 // Notify_lock is destroyed by Threads::create_vm() 291 292 int prio = (VMThreadPriority == -1) 293 ? os::java_to_os_priority[NearMaxPriority] 294 : VMThreadPriority; 295 // Note that I cannot call os::set_priority because it expects Java 296 // priorities and I am *explicitly* using OS priorities so that it's 297 // possible to set the VM thread priority higher than any Java thread. 298 os::set_native_priority( this, prio ); 299 300 // Wait for VM_Operations until termination 301 this->loop(); 302 303 // Note the intention to exit before safepointing. 304 // 6295565 This has the effect of waiting for any large tty 305 // outputs to finish. 306 if (xtty != NULL) { 307 ttyLocker ttyl; 308 xtty->begin_elem("destroy_vm"); 309 xtty->stamp(); 310 xtty->end_elem(); 311 assert(should_terminate(), "termination flag must be set"); 312 } 313 314 // 4526887 let VM thread exit at Safepoint 315 _cur_vm_operation = &halt_op; 316 SafepointSynchronize::begin(); 317 318 if (VerifyBeforeExit) { 319 HandleMark hm(VMThread::vm_thread()); 320 // Among other things, this ensures that Eden top is correct. 321 Universe::heap()->prepare_for_verify(); 322 // Silent verification so as not to pollute normal output, 323 // unless we really asked for it. 324 Universe::verify(); 325 } 326 327 CompileBroker::set_should_block(); 328 329 // wait for threads (compiler threads or daemon threads) in the 330 // _thread_in_native state to block. 331 VM_Exit::wait_for_threads_in_native_to_block(); 332 333 // signal other threads that VM process is gone 334 { 335 // Note: we must have the _no_safepoint_check_flag. Mutex::lock() allows 336 // VM thread to enter any lock at Safepoint as long as its _owner is NULL. 337 // If that happens after _terminate_lock->wait() has unset _owner 338 // but before it actually drops the lock and waits, the notification below 339 // may get lost and we will have a hang. To avoid this, we need to use 340 // Mutex::lock_without_safepoint_check(). 341 MonitorLocker ml(_terminate_lock, Mutex::_no_safepoint_check_flag); 342 _terminated = true; 343 ml.notify(); 344 } 345 346 // We are now racing with the VM termination being carried out in 347 // another thread, so we don't "delete this". Numerous threads don't 348 // get deleted when the VM terminates 349 350 } 351 352 353 // Notify the VMThread that the last non-daemon JavaThread has terminated, 354 // and wait until operation is performed. 355 void VMThread::wait_for_vm_thread_exit() { 356 assert(Thread::current()->is_Java_thread(), "Should be a JavaThread"); 357 assert(((JavaThread*)Thread::current())->is_terminated(), "Should be terminated"); 358 { MonitorLocker mu(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 359 _should_terminate = true; 360 mu.notify(); 361 } 362 363 // Note: VM thread leaves at Safepoint. We are not stopped by Safepoint 364 // because this thread has been removed from the threads list. But anything 365 // that could get blocked by Safepoint should not be used after this point, 366 // otherwise we will hang, since there is no one can end the safepoint. 367 368 // Wait until VM thread is terminated 369 // Note: it should be OK to use Terminator_lock here. But this is called 370 // at a very delicate time (VM shutdown) and we are operating in non- VM 371 // thread at Safepoint. It's safer to not share lock with other threads. 372 { MonitorLocker ml(_terminate_lock, Mutex::_no_safepoint_check_flag); 373 while(!VMThread::is_terminated()) { 374 ml.wait(); 375 } 376 } 377 } 378 379 static void post_vm_operation_event(EventExecuteVMOperation* event, VM_Operation* op) { 380 assert(event != NULL, "invariant"); 381 assert(event->should_commit(), "invariant"); 382 assert(op != NULL, "invariant"); 383 const bool is_concurrent = op->evaluate_concurrently(); 384 const bool evaluate_at_safepoint = op->evaluate_at_safepoint(); 385 event->set_operation(op->type()); 386 event->set_safepoint(evaluate_at_safepoint); 387 event->set_blocking(!is_concurrent); 388 // Only write caller thread information for non-concurrent vm operations. 389 // For concurrent vm operations, the thread id is set to 0 indicating thread is unknown. 390 // This is because the caller thread could have exited already. 391 event->set_caller(is_concurrent ? 0 : JFR_THREAD_ID(op->calling_thread())); 392 event->set_safepointId(evaluate_at_safepoint ? SafepointSynchronize::safepoint_id() : 0); 393 event->commit(); 394 } 395 396 void VMThread::evaluate_operation(VM_Operation* op) { 397 ResourceMark rm; 398 399 { 400 PerfTraceTime vm_op_timer(perf_accumulated_vm_operation_time()); 401 HOTSPOT_VMOPS_BEGIN( 402 (char *) op->name(), strlen(op->name()), 403 op->evaluation_mode()); 404 405 EventExecuteVMOperation event; 406 op->evaluate(); 407 if (event.should_commit()) { 408 post_vm_operation_event(&event, op); 409 } 410 411 HOTSPOT_VMOPS_END( 412 (char *) op->name(), strlen(op->name()), 413 op->evaluation_mode()); 414 } 415 416 // Last access of info in _cur_vm_operation! 417 bool c_heap_allocated = op->is_cheap_allocated(); 418 419 // Mark as completed 420 if (!op->evaluate_concurrently()) { 421 op->calling_thread()->increment_vm_operation_completed_count(); 422 } 423 // It is unsafe to access the _cur_vm_operation after the 'increment_vm_operation_completed_count' call, 424 // since if it is stack allocated the calling thread might have deallocated 425 if (c_heap_allocated) { 426 delete _cur_vm_operation; 427 } 428 } 429 430 static VM_None safepointALot_op("SafepointALot"); 431 static VM_Cleanup cleanup_op; 432 433 class HandshakeALotTC : public ThreadClosure { 434 public: 435 virtual void do_thread(Thread* thread) { 436 #ifdef ASSERT 437 assert(thread->is_Java_thread(), "must be"); 438 JavaThread* jt = (JavaThread*)thread; 439 jt->verify_states_for_handshake(); 440 #endif 441 } 442 }; 443 444 VM_Operation* VMThread::no_op_safepoint() { 445 // Check for handshakes first since we may need to return a VMop. 446 if (HandshakeALot) { 447 HandshakeALotTC haltc; 448 Handshake::execute(&haltc); 449 } 450 // Check for a cleanup before SafepointALot to keep stats correct. 451 long interval_ms = SafepointTracing::time_since_last_safepoint_ms(); 452 bool max_time_exceeded = GuaranteedSafepointInterval != 0 && 453 (interval_ms >= GuaranteedSafepointInterval); 454 if (max_time_exceeded && SafepointSynchronize::is_cleanup_needed()) { 455 return &cleanup_op; 456 } 457 if (SafepointALot) { 458 return &safepointALot_op; 459 } 460 // Nothing to be done. 461 return NULL; 462 } 463 464 void VMThread::loop() { 465 assert(_cur_vm_operation == NULL, "no current one should be executing"); 466 467 SafepointSynchronize::init(_vm_thread); 468 469 while(true) { 470 VM_Operation* safepoint_ops = NULL; 471 // 472 // Wait for VM operation 473 // 474 // use no_safepoint_check to get lock without attempting to "sneak" 475 { MonitorLocker mu_queue(VMOperationQueue_lock, 476 Mutex::_no_safepoint_check_flag); 477 478 // Look for new operation 479 assert(_cur_vm_operation == NULL, "no current one should be executing"); 480 _cur_vm_operation = _vm_queue->remove_next(); 481 482 // Stall time tracking code 483 if (PrintVMQWaitTime && _cur_vm_operation != NULL && 484 !_cur_vm_operation->evaluate_concurrently()) { 485 long stall = os::javaTimeMillis() - _cur_vm_operation->timestamp(); 486 if (stall > 0) 487 tty->print_cr("%s stall: %ld", _cur_vm_operation->name(), stall); 488 } 489 490 while (!should_terminate() && _cur_vm_operation == NULL) { 491 // wait with a timeout to guarantee safepoints at regular intervals 492 bool timedout = 493 mu_queue.wait(GuaranteedSafepointInterval); 494 495 // Support for self destruction 496 if ((SelfDestructTimer != 0) && !VMError::is_error_reported() && 497 (os::elapsedTime() > (double)SelfDestructTimer * 60.0)) { 498 tty->print_cr("VM self-destructed"); 499 exit(-1); 500 } 501 502 if (timedout) { 503 // Have to unlock VMOperationQueue_lock just in case no_op_safepoint() 504 // has to do a handshake. 505 MutexUnlocker mul(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 506 if ((_cur_vm_operation = VMThread::no_op_safepoint()) != NULL) { 507 // Force a safepoint since we have not had one for at least 508 // 'GuaranteedSafepointInterval' milliseconds and we need to clean 509 // something. This will run all the clean-up processing that needs 510 // to be done at a safepoint. 511 SafepointSynchronize::begin(); 512 #ifdef ASSERT 513 if (GCALotAtAllSafepoints) InterfaceSupport::check_gc_alot(); 514 #endif 515 SafepointSynchronize::end(); 516 _cur_vm_operation = NULL; 517 } 518 } 519 _cur_vm_operation = _vm_queue->remove_next(); 520 521 // If we are at a safepoint we will evaluate all the operations that 522 // follow that also require a safepoint 523 if (_cur_vm_operation != NULL && 524 _cur_vm_operation->evaluate_at_safepoint()) { 525 safepoint_ops = _vm_queue->drain_at_safepoint_priority(); 526 } 527 } 528 529 if (should_terminate()) break; 530 } // Release mu_queue_lock 531 532 // 533 // Execute VM operation 534 // 535 { HandleMark hm(VMThread::vm_thread()); 536 537 EventMark em("Executing VM operation: %s", vm_operation()->name()); 538 assert(_cur_vm_operation != NULL, "we should have found an operation to execute"); 539 540 // If we are at a safepoint we will evaluate all the operations that 541 // follow that also require a safepoint 542 if (_cur_vm_operation->evaluate_at_safepoint()) { 543 log_debug(vmthread)("Evaluating safepoint VM operation: %s", _cur_vm_operation->name()); 544 545 _vm_queue->set_drain_list(safepoint_ops); // ensure ops can be scanned 546 547 SafepointSynchronize::begin(); 548 549 if (_timeout_task != NULL) { 550 _timeout_task->arm(); 551 } 552 553 evaluate_operation(_cur_vm_operation); 554 // now process all queued safepoint ops, iteratively draining 555 // the queue until there are none left 556 do { 557 _cur_vm_operation = safepoint_ops; 558 if (_cur_vm_operation != NULL) { 559 do { 560 EventMark em("Executing coalesced safepoint VM operation: %s", _cur_vm_operation->name()); 561 log_debug(vmthread)("Evaluating coalesced safepoint VM operation: %s", _cur_vm_operation->name()); 562 // evaluate_operation deletes the op object so we have 563 // to grab the next op now 564 VM_Operation* next = _cur_vm_operation->next(); 565 _vm_queue->set_drain_list(next); 566 evaluate_operation(_cur_vm_operation); 567 _cur_vm_operation = next; 568 _coalesced_count++; 569 } while (_cur_vm_operation != NULL); 570 } 571 // There is a chance that a thread enqueued a safepoint op 572 // since we released the op-queue lock and initiated the safepoint. 573 // So we drain the queue again if there is anything there, as an 574 // optimization to try and reduce the number of safepoints. 575 // As the safepoint synchronizes us with JavaThreads we will see 576 // any enqueue made by a JavaThread, but the peek will not 577 // necessarily detect a concurrent enqueue by a GC thread, but 578 // that simply means the op will wait for the next major cycle of the 579 // VMThread - just as it would if the GC thread lost the race for 580 // the lock. 581 if (_vm_queue->peek_at_safepoint_priority()) { 582 // must hold lock while draining queue 583 MutexLocker mu_queue(VMOperationQueue_lock, 584 Mutex::_no_safepoint_check_flag); 585 safepoint_ops = _vm_queue->drain_at_safepoint_priority(); 586 } else { 587 safepoint_ops = NULL; 588 } 589 } while(safepoint_ops != NULL); 590 591 _vm_queue->set_drain_list(NULL); 592 593 if (_timeout_task != NULL) { 594 _timeout_task->disarm(); 595 } 596 597 // Complete safepoint synchronization 598 SafepointSynchronize::end(); 599 600 } else { // not a safepoint operation 601 log_debug(vmthread)("Evaluating non-safepoint VM operation: %s", _cur_vm_operation->name()); 602 if (TraceLongCompiles) { 603 elapsedTimer t; 604 t.start(); 605 evaluate_operation(_cur_vm_operation); 606 t.stop(); 607 double secs = t.seconds(); 608 if (secs * 1e3 > LongCompileThreshold) { 609 // XXX - _cur_vm_operation should not be accessed after 610 // the completed count has been incremented; the waiting 611 // thread may have already freed this memory. 612 tty->print_cr("vm %s: %3.7f secs]", _cur_vm_operation->name(), secs); 613 } 614 } else { 615 evaluate_operation(_cur_vm_operation); 616 } 617 618 _cur_vm_operation = NULL; 619 } 620 } 621 622 // 623 // Notify (potential) waiting Java thread(s) 624 { MonitorLocker mu(VMOperationRequest_lock, Mutex::_no_safepoint_check_flag); 625 mu.notify_all(); 626 } 627 628 // We want to make sure that we get to a safepoint regularly 629 // even when executing VMops that don't require safepoints. 630 if ((_cur_vm_operation = VMThread::no_op_safepoint()) != NULL) { 631 HandleMark hm(VMThread::vm_thread()); 632 SafepointSynchronize::begin(); 633 SafepointSynchronize::end(); 634 _cur_vm_operation = NULL; 635 } 636 } 637 } 638 639 // A SkipGCALot object is used to elide the usual effect of gc-a-lot 640 // over a section of execution by a thread. Currently, it's used only to 641 // prevent re-entrant calls to GC. 642 class SkipGCALot : public StackObj { 643 private: 644 bool _saved; 645 Thread* _t; 646 647 public: 648 #ifdef ASSERT 649 SkipGCALot(Thread* t) : _t(t) { 650 _saved = _t->skip_gcalot(); 651 _t->set_skip_gcalot(true); 652 } 653 654 ~SkipGCALot() { 655 assert(_t->skip_gcalot(), "Save-restore protocol invariant"); 656 _t->set_skip_gcalot(_saved); 657 } 658 #else 659 SkipGCALot(Thread* t) { } 660 ~SkipGCALot() { } 661 #endif 662 }; 663 664 void VMThread::execute(VM_Operation* op) { 665 Thread* t = Thread::current(); 666 667 if (!t->is_VM_thread()) { 668 SkipGCALot sgcalot(t); // avoid re-entrant attempts to gc-a-lot 669 // JavaThread or WatcherThread 670 bool concurrent = op->evaluate_concurrently(); 671 // only blocking VM operations need to verify the caller's safepoint state: 672 if (!concurrent) { 673 t->check_for_valid_safepoint_state(); 674 } 675 676 // New request from Java thread, evaluate prologue 677 if (!op->doit_prologue()) { 678 return; // op was cancelled 679 } 680 681 // Setup VM_operations for execution 682 op->set_calling_thread(t); 683 684 // It does not make sense to execute the epilogue, if the VM operation object is getting 685 // deallocated by the VM thread. 686 bool execute_epilog = !op->is_cheap_allocated(); 687 assert(!concurrent || op->is_cheap_allocated(), "concurrent => cheap_allocated"); 688 689 // Get ticket number for non-concurrent VM operations 690 int ticket = 0; 691 if (!concurrent) { 692 ticket = t->vm_operation_ticket(); 693 } 694 695 // Add VM operation to list of waiting threads. We are guaranteed not to block while holding the 696 // VMOperationQueue_lock, so we can block without a safepoint check. This allows vm operation requests 697 // to be queued up during a safepoint synchronization. 698 { 699 MonitorLocker ml(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 700 log_debug(vmthread)("Adding VM operation: %s", op->name()); 701 _vm_queue->add(op); 702 op->set_timestamp(os::javaTimeMillis()); 703 ml.notify(); 704 } 705 706 if (!concurrent) { 707 // Wait for completion of request (non-concurrent) 708 // Note: only a JavaThread triggers the safepoint check when locking 709 MonitorLocker ml(VMOperationRequest_lock, 710 t->is_Java_thread() ? Mutex::_safepoint_check_flag : Mutex::_no_safepoint_check_flag); 711 while(t->vm_operation_completed_count() < ticket) { 712 ml.wait(); 713 } 714 } 715 716 if (execute_epilog) { 717 op->doit_epilogue(); 718 } 719 } else { 720 // invoked by VM thread; usually nested VM operation 721 assert(t->is_VM_thread(), "must be a VM thread"); 722 VM_Operation* prev_vm_operation = vm_operation(); 723 if (prev_vm_operation != NULL) { 724 // Check the VM operation allows nested VM operation. This normally not the case, e.g., the compiler 725 // does not allow nested scavenges or compiles. 726 if (!prev_vm_operation->allow_nested_vm_operations()) { 727 fatal("Nested VM operation %s requested by operation %s", 728 op->name(), vm_operation()->name()); 729 } 730 op->set_calling_thread(prev_vm_operation->calling_thread()); 731 } 732 733 EventMark em("Executing %s VM operation: %s", prev_vm_operation ? "nested" : "", op->name()); 734 735 // Release all internal handles after operation is evaluated 736 HandleMark hm(t); 737 _cur_vm_operation = op; 738 739 if (op->evaluate_at_safepoint() && !SafepointSynchronize::is_at_safepoint()) { 740 SafepointSynchronize::begin(); 741 op->evaluate(); 742 SafepointSynchronize::end(); 743 } else { 744 op->evaluate(); 745 } 746 747 // Free memory if needed 748 if (op->is_cheap_allocated()) delete op; 749 750 _cur_vm_operation = prev_vm_operation; 751 } 752 } 753 754 755 void VMThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 756 Thread::oops_do(f, cf); 757 _vm_queue->oops_do(f); 758 } 759 760 //------------------------------------------------------------------------------------------------------------------ 761 #ifndef PRODUCT 762 763 void VMOperationQueue::verify_queue(int prio) { 764 // Check that list is correctly linked 765 int length = _queue_length[prio]; 766 VM_Operation *cur = _queue[prio]; 767 int i; 768 769 // Check forward links 770 for(i = 0; i < length; i++) { 771 cur = cur->next(); 772 assert(cur != _queue[prio], "list to short (forward)"); 773 } 774 assert(cur->next() == _queue[prio], "list to long (forward)"); 775 776 // Check backwards links 777 cur = _queue[prio]; 778 for(i = 0; i < length; i++) { 779 cur = cur->prev(); 780 assert(cur != _queue[prio], "list to short (backwards)"); 781 } 782 assert(cur->prev() == _queue[prio], "list to long (backwards)"); 783 } 784 785 #endif 786 787 void VMThread::verify() { 788 oops_do(&VerifyOopClosure::verify_oop, NULL); 789 }