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 HandshakeALotClosure : public HandshakeClosure { 434 public: 435 HandshakeALotClosure() : HandshakeClosure("HandshakeALot") {} 436 void do_thread(Thread* thread) { 437 #ifdef ASSERT 438 assert(thread->is_Java_thread(), "must be"); 439 JavaThread* jt = (JavaThread*)thread; 440 jt->verify_states_for_handshake(); 441 #endif 442 } 443 }; 444 445 VM_Operation* VMThread::no_op_safepoint() { 446 // Check for handshakes first since we may need to return a VMop. 447 if (HandshakeALot) { 448 HandshakeALotClosure hal_cl; 449 Handshake::execute(&hal_cl); 450 } 451 // Check for a cleanup before SafepointALot to keep stats correct. 452 long interval_ms = SafepointTracing::time_since_last_safepoint_ms(); 453 bool max_time_exceeded = GuaranteedSafepointInterval != 0 && 454 (interval_ms >= GuaranteedSafepointInterval); 455 if (max_time_exceeded && SafepointSynchronize::is_cleanup_needed()) { 456 return &cleanup_op; 457 } 458 if (SafepointALot) { 459 return &safepointALot_op; 460 } 461 // Nothing to be done. 462 return NULL; 463 } 464 465 void VMThread::loop() { 466 assert(_cur_vm_operation == NULL, "no current one should be executing"); 467 468 SafepointSynchronize::init(_vm_thread); 469 470 while(true) { 471 VM_Operation* safepoint_ops = NULL; 472 // 473 // Wait for VM operation 474 // 475 // use no_safepoint_check to get lock without attempting to "sneak" 476 { MonitorLocker mu_queue(VMOperationQueue_lock, 477 Mutex::_no_safepoint_check_flag); 478 479 // Look for new operation 480 assert(_cur_vm_operation == NULL, "no current one should be executing"); 481 _cur_vm_operation = _vm_queue->remove_next(); 482 483 // Stall time tracking code 484 if (PrintVMQWaitTime && _cur_vm_operation != NULL && 485 !_cur_vm_operation->evaluate_concurrently()) { 486 long stall = os::javaTimeMillis() - _cur_vm_operation->timestamp(); 487 if (stall > 0) 488 tty->print_cr("%s stall: %ld", _cur_vm_operation->name(), stall); 489 } 490 491 while (!should_terminate() && _cur_vm_operation == NULL) { 492 // wait with a timeout to guarantee safepoints at regular intervals 493 bool timedout = 494 mu_queue.wait(GuaranteedSafepointInterval); 495 496 // Support for self destruction 497 if ((SelfDestructTimer != 0) && !VMError::is_error_reported() && 498 (os::elapsedTime() > (double)SelfDestructTimer * 60.0)) { 499 tty->print_cr("VM self-destructed"); 500 exit(-1); 501 } 502 503 if (timedout) { 504 // Have to unlock VMOperationQueue_lock just in case no_op_safepoint() 505 // has to do a handshake. 506 MutexUnlocker mul(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 507 if ((_cur_vm_operation = VMThread::no_op_safepoint()) != NULL) { 508 // Force a safepoint since we have not had one for at least 509 // 'GuaranteedSafepointInterval' milliseconds and we need to clean 510 // something. This will run all the clean-up processing that needs 511 // to be done at a safepoint. 512 SafepointSynchronize::begin(); 513 #ifdef ASSERT 514 if (GCALotAtAllSafepoints) InterfaceSupport::check_gc_alot(); 515 #endif 516 SafepointSynchronize::end(); 517 _cur_vm_operation = NULL; 518 } 519 } 520 _cur_vm_operation = _vm_queue->remove_next(); 521 522 // If we are at a safepoint we will evaluate all the operations that 523 // follow that also require a safepoint 524 if (_cur_vm_operation != NULL && 525 _cur_vm_operation->evaluate_at_safepoint()) { 526 safepoint_ops = _vm_queue->drain_at_safepoint_priority(); 527 } 528 } 529 530 if (should_terminate()) break; 531 } // Release mu_queue_lock 532 533 // 534 // Execute VM operation 535 // 536 { HandleMark hm(VMThread::vm_thread()); 537 538 EventMark em("Executing VM operation: %s", vm_operation()->name()); 539 assert(_cur_vm_operation != NULL, "we should have found an operation to execute"); 540 541 // If we are at a safepoint we will evaluate all the operations that 542 // follow that also require a safepoint 543 if (_cur_vm_operation->evaluate_at_safepoint()) { 544 log_debug(vmthread)("Evaluating safepoint VM operation: %s", _cur_vm_operation->name()); 545 546 _vm_queue->set_drain_list(safepoint_ops); // ensure ops can be scanned 547 548 SafepointSynchronize::begin(); 549 550 if (_timeout_task != NULL) { 551 _timeout_task->arm(); 552 } 553 554 evaluate_operation(_cur_vm_operation); 555 // now process all queued safepoint ops, iteratively draining 556 // the queue until there are none left 557 do { 558 _cur_vm_operation = safepoint_ops; 559 if (_cur_vm_operation != NULL) { 560 do { 561 EventMark em("Executing coalesced safepoint VM operation: %s", _cur_vm_operation->name()); 562 log_debug(vmthread)("Evaluating coalesced safepoint VM operation: %s", _cur_vm_operation->name()); 563 // evaluate_operation deletes the op object so we have 564 // to grab the next op now 565 VM_Operation* next = _cur_vm_operation->next(); 566 _vm_queue->set_drain_list(next); 567 evaluate_operation(_cur_vm_operation); 568 _cur_vm_operation = next; 569 _coalesced_count++; 570 } while (_cur_vm_operation != NULL); 571 } 572 // There is a chance that a thread enqueued a safepoint op 573 // since we released the op-queue lock and initiated the safepoint. 574 // So we drain the queue again if there is anything there, as an 575 // optimization to try and reduce the number of safepoints. 576 // As the safepoint synchronizes us with JavaThreads we will see 577 // any enqueue made by a JavaThread, but the peek will not 578 // necessarily detect a concurrent enqueue by a GC thread, but 579 // that simply means the op will wait for the next major cycle of the 580 // VMThread - just as it would if the GC thread lost the race for 581 // the lock. 582 if (_vm_queue->peek_at_safepoint_priority()) { 583 // must hold lock while draining queue 584 MutexLocker mu_queue(VMOperationQueue_lock, 585 Mutex::_no_safepoint_check_flag); 586 safepoint_ops = _vm_queue->drain_at_safepoint_priority(); 587 } else { 588 safepoint_ops = NULL; 589 } 590 } while(safepoint_ops != NULL); 591 592 _vm_queue->set_drain_list(NULL); 593 594 if (_timeout_task != NULL) { 595 _timeout_task->disarm(); 596 } 597 598 // Complete safepoint synchronization 599 SafepointSynchronize::end(); 600 601 } else { // not a safepoint operation 602 log_debug(vmthread)("Evaluating non-safepoint VM operation: %s", _cur_vm_operation->name()); 603 if (TraceLongCompiles) { 604 elapsedTimer t; 605 t.start(); 606 evaluate_operation(_cur_vm_operation); 607 t.stop(); 608 double secs = t.seconds(); 609 if (secs * 1e3 > LongCompileThreshold) { 610 // XXX - _cur_vm_operation should not be accessed after 611 // the completed count has been incremented; the waiting 612 // thread may have already freed this memory. 613 tty->print_cr("vm %s: %3.7f secs]", _cur_vm_operation->name(), secs); 614 } 615 } else { 616 evaluate_operation(_cur_vm_operation); 617 } 618 619 _cur_vm_operation = NULL; 620 } 621 } 622 623 // 624 // Notify (potential) waiting Java thread(s) 625 { MonitorLocker mu(VMOperationRequest_lock, Mutex::_no_safepoint_check_flag); 626 mu.notify_all(); 627 } 628 629 // We want to make sure that we get to a safepoint regularly 630 // even when executing VMops that don't require safepoints. 631 if ((_cur_vm_operation = VMThread::no_op_safepoint()) != NULL) { 632 HandleMark hm(VMThread::vm_thread()); 633 SafepointSynchronize::begin(); 634 SafepointSynchronize::end(); 635 _cur_vm_operation = NULL; 636 } 637 } 638 } 639 640 // A SkipGCALot object is used to elide the usual effect of gc-a-lot 641 // over a section of execution by a thread. Currently, it's used only to 642 // prevent re-entrant calls to GC. 643 class SkipGCALot : public StackObj { 644 private: 645 bool _saved; 646 Thread* _t; 647 648 public: 649 #ifdef ASSERT 650 SkipGCALot(Thread* t) : _t(t) { 651 _saved = _t->skip_gcalot(); 652 _t->set_skip_gcalot(true); 653 } 654 655 ~SkipGCALot() { 656 assert(_t->skip_gcalot(), "Save-restore protocol invariant"); 657 _t->set_skip_gcalot(_saved); 658 } 659 #else 660 SkipGCALot(Thread* t) { } 661 ~SkipGCALot() { } 662 #endif 663 }; 664 665 void VMThread::execute(VM_Operation* op) { 666 Thread* t = Thread::current(); 667 668 if (!t->is_VM_thread()) { 669 SkipGCALot sgcalot(t); // avoid re-entrant attempts to gc-a-lot 670 // JavaThread or WatcherThread 671 bool concurrent = op->evaluate_concurrently(); 672 // only blocking VM operations need to verify the caller's safepoint state: 673 if (!concurrent) { 674 t->check_for_valid_safepoint_state(); 675 } 676 677 // New request from Java thread, evaluate prologue 678 if (!op->doit_prologue()) { 679 return; // op was cancelled 680 } 681 682 // Setup VM_operations for execution 683 op->set_calling_thread(t); 684 685 // It does not make sense to execute the epilogue, if the VM operation object is getting 686 // deallocated by the VM thread. 687 bool execute_epilog = !op->is_cheap_allocated(); 688 assert(!concurrent || op->is_cheap_allocated(), "concurrent => cheap_allocated"); 689 690 // Get ticket number for non-concurrent VM operations 691 int ticket = 0; 692 if (!concurrent) { 693 ticket = t->vm_operation_ticket(); 694 } 695 696 // Add VM operation to list of waiting threads. We are guaranteed not to block while holding the 697 // VMOperationQueue_lock, so we can block without a safepoint check. This allows vm operation requests 698 // to be queued up during a safepoint synchronization. 699 { 700 MonitorLocker ml(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 701 log_debug(vmthread)("Adding VM operation: %s", op->name()); 702 _vm_queue->add(op); 703 op->set_timestamp(os::javaTimeMillis()); 704 ml.notify(); 705 } 706 707 if (!concurrent) { 708 // Wait for completion of request (non-concurrent) 709 // Note: only a JavaThread triggers the safepoint check when locking 710 MonitorLocker ml(VMOperationRequest_lock, 711 t->is_Java_thread() ? Mutex::_safepoint_check_flag : Mutex::_no_safepoint_check_flag); 712 while(t->vm_operation_completed_count() < ticket) { 713 ml.wait(); 714 } 715 } 716 717 if (execute_epilog) { 718 op->doit_epilogue(); 719 } 720 } else { 721 // invoked by VM thread; usually nested VM operation 722 assert(t->is_VM_thread(), "must be a VM thread"); 723 VM_Operation* prev_vm_operation = vm_operation(); 724 if (prev_vm_operation != NULL) { 725 // Check the VM operation allows nested VM operation. This normally not the case, e.g., the compiler 726 // does not allow nested scavenges or compiles. 727 if (!prev_vm_operation->allow_nested_vm_operations()) { 728 fatal("Nested VM operation %s requested by operation %s", 729 op->name(), vm_operation()->name()); 730 } 731 op->set_calling_thread(prev_vm_operation->calling_thread()); 732 } 733 734 EventMark em("Executing %s VM operation: %s", prev_vm_operation ? "nested" : "", op->name()); 735 736 // Release all internal handles after operation is evaluated 737 HandleMark hm(t); 738 _cur_vm_operation = op; 739 740 if (op->evaluate_at_safepoint() && !SafepointSynchronize::is_at_safepoint()) { 741 SafepointSynchronize::begin(); 742 op->evaluate(); 743 SafepointSynchronize::end(); 744 } else { 745 op->evaluate(); 746 } 747 748 // Free memory if needed 749 if (op->is_cheap_allocated()) delete op; 750 751 _cur_vm_operation = prev_vm_operation; 752 } 753 } 754 755 756 void VMThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 757 Thread::oops_do(f, cf); 758 _vm_queue->oops_do(f); 759 } 760 761 //------------------------------------------------------------------------------------------------------------------ 762 #ifndef PRODUCT 763 764 void VMOperationQueue::verify_queue(int prio) { 765 // Check that list is correctly linked 766 int length = _queue_length[prio]; 767 VM_Operation *cur = _queue[prio]; 768 int i; 769 770 // Check forward links 771 for(i = 0; i < length; i++) { 772 cur = cur->next(); 773 assert(cur != _queue[prio], "list to short (forward)"); 774 } 775 assert(cur->next() == _queue[prio], "list to long (forward)"); 776 777 // Check backwards links 778 cur = _queue[prio]; 779 for(i = 0; i < length; i++) { 780 cur = cur->prev(); 781 assert(cur != _queue[prio], "list to short (backwards)"); 782 } 783 assert(cur->prev() == _queue[prio], "list to long (backwards)"); 784 } 785 786 #endif 787 788 void VMThread::verify() { 789 oops_do(&VerifyOopClosure::verify_oop, NULL); 790 }