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