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 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 OrderAccess::load_acquire(&_armed) != 0; 208 } 209 210 void VMOperationTimeoutTask::arm() { 211 _arm_time = os::javaTimeMillis(); 212 OrderAccess::release_store_fence(&_armed, 1); 213 } 214 215 void VMOperationTimeoutTask::disarm() { 216 OrderAccess::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 if (AsyncDeflateIdleMonitors && log_is_enabled(Info, monitorinflation)) { 315 // AsyncDeflateIdleMonitors does a special deflation at the final 316 // safepoint in order to reduce the in-use monitor population that 317 // is reported by ObjectSynchronizer::log_in_use_monitor_details() 318 // at VM exit. 319 ObjectSynchronizer::set_is_special_deflation_requested(true); 320 } 321 322 // 4526887 let VM thread exit at Safepoint 323 _cur_vm_operation = &halt_op; 324 SafepointSynchronize::begin(); 325 326 if (VerifyBeforeExit) { 327 HandleMark hm(VMThread::vm_thread()); 328 // Among other things, this ensures that Eden top is correct. 329 Universe::heap()->prepare_for_verify(); 330 // Silent verification so as not to pollute normal output, 331 // unless we really asked for it. 332 Universe::verify(); 333 } 334 335 CompileBroker::set_should_block(); 336 337 // wait for threads (compiler threads or daemon threads) in the 338 // _thread_in_native state to block. 339 VM_Exit::wait_for_threads_in_native_to_block(); 340 341 // signal other threads that VM process is gone 342 { 343 // Note: we must have the _no_safepoint_check_flag. Mutex::lock() allows 344 // VM thread to enter any lock at Safepoint as long as its _owner is NULL. 345 // If that happens after _terminate_lock->wait() has unset _owner 346 // but before it actually drops the lock and waits, the notification below 347 // may get lost and we will have a hang. To avoid this, we need to use 348 // Mutex::lock_without_safepoint_check(). 349 MonitorLocker ml(_terminate_lock, Mutex::_no_safepoint_check_flag); 350 _terminated = true; 351 ml.notify(); 352 } 353 354 // We are now racing with the VM termination being carried out in 355 // another thread, so we don't "delete this". Numerous threads don't 356 // get deleted when the VM terminates 357 358 } 359 360 361 // Notify the VMThread that the last non-daemon JavaThread has terminated, 362 // and wait until operation is performed. 363 void VMThread::wait_for_vm_thread_exit() { 364 assert(Thread::current()->is_Java_thread(), "Should be a JavaThread"); 365 assert(((JavaThread*)Thread::current())->is_terminated(), "Should be terminated"); 366 { MutexLocker mu(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 367 _should_terminate = true; 368 VMOperationQueue_lock->notify(); 369 } 370 371 // Note: VM thread leaves at Safepoint. We are not stopped by Safepoint 372 // because this thread has been removed from the threads list. But anything 373 // that could get blocked by Safepoint should not be used after this point, 374 // otherwise we will hang, since there is no one can end the safepoint. 375 376 // Wait until VM thread is terminated 377 // Note: it should be OK to use Terminator_lock here. But this is called 378 // at a very delicate time (VM shutdown) and we are operating in non- VM 379 // thread at Safepoint. It's safer to not share lock with other threads. 380 { MonitorLocker ml(_terminate_lock, Mutex::_no_safepoint_check_flag); 381 while(!VMThread::is_terminated()) { 382 ml.wait(); 383 } 384 } 385 } 386 387 static void post_vm_operation_event(EventExecuteVMOperation* event, VM_Operation* op) { 388 assert(event != NULL, "invariant"); 389 assert(event->should_commit(), "invariant"); 390 assert(op != NULL, "invariant"); 391 const bool is_concurrent = op->evaluate_concurrently(); 392 const bool evaluate_at_safepoint = op->evaluate_at_safepoint(); 393 event->set_operation(op->type()); 394 event->set_safepoint(evaluate_at_safepoint); 395 event->set_blocking(!is_concurrent); 396 // Only write caller thread information for non-concurrent vm operations. 397 // For concurrent vm operations, the thread id is set to 0 indicating thread is unknown. 398 // This is because the caller thread could have exited already. 399 event->set_caller(is_concurrent ? 0 : JFR_THREAD_ID(op->calling_thread())); 400 event->set_safepointId(evaluate_at_safepoint ? SafepointSynchronize::safepoint_id() : 0); 401 event->commit(); 402 } 403 404 void VMThread::evaluate_operation(VM_Operation* op) { 405 ResourceMark rm; 406 407 { 408 PerfTraceTime vm_op_timer(perf_accumulated_vm_operation_time()); 409 HOTSPOT_VMOPS_BEGIN( 410 (char *) op->name(), strlen(op->name()), 411 op->evaluation_mode()); 412 413 EventExecuteVMOperation event; 414 op->evaluate(); 415 if (event.should_commit()) { 416 post_vm_operation_event(&event, op); 417 } 418 419 HOTSPOT_VMOPS_END( 420 (char *) op->name(), strlen(op->name()), 421 op->evaluation_mode()); 422 } 423 424 // Last access of info in _cur_vm_operation! 425 bool c_heap_allocated = op->is_cheap_allocated(); 426 427 // Mark as completed 428 if (!op->evaluate_concurrently()) { 429 op->calling_thread()->increment_vm_operation_completed_count(); 430 } 431 // It is unsafe to access the _cur_vm_operation after the 'increment_vm_operation_completed_count' call, 432 // since if it is stack allocated the calling thread might have deallocated 433 if (c_heap_allocated) { 434 delete _cur_vm_operation; 435 } 436 } 437 438 static VM_None safepointALot_op("SafepointALot"); 439 static VM_Cleanup cleanup_op; 440 441 class HandshakeALotTC : public ThreadClosure { 442 public: 443 virtual void do_thread(Thread* thread) { 444 #ifdef ASSERT 445 assert(thread->is_Java_thread(), "must be"); 446 JavaThread* jt = (JavaThread*)thread; 447 jt->verify_states_for_handshake(); 448 #endif 449 } 450 }; 451 452 VM_Operation* VMThread::no_op_safepoint() { 453 // Check for handshakes first since we may need to return a VMop. 454 if (HandshakeALot) { 455 HandshakeALotTC haltc; 456 Handshake::execute(&haltc); 457 } 458 // Check for a cleanup before SafepointALot to keep stats correct. 459 long interval_ms = SafepointTracing::time_since_last_safepoint_ms(); 460 bool max_time_exceeded = GuaranteedSafepointInterval != 0 && 461 (interval_ms >= GuaranteedSafepointInterval); 462 if (max_time_exceeded && SafepointSynchronize::is_cleanup_needed()) { 463 return &cleanup_op; 464 } 465 if (SafepointALot) { 466 return &safepointALot_op; 467 } 468 // Nothing to be done. 469 return NULL; 470 } 471 472 void VMThread::loop() { 473 assert(_cur_vm_operation == NULL, "no current one should be executing"); 474 475 SafepointSynchronize::init(_vm_thread); 476 477 while(true) { 478 VM_Operation* safepoint_ops = NULL; 479 // 480 // Wait for VM operation 481 // 482 // use no_safepoint_check to get lock without attempting to "sneak" 483 { MonitorLocker mu_queue(VMOperationQueue_lock, 484 Mutex::_no_safepoint_check_flag); 485 486 // Look for new operation 487 assert(_cur_vm_operation == NULL, "no current one should be executing"); 488 _cur_vm_operation = _vm_queue->remove_next(); 489 490 // Stall time tracking code 491 if (PrintVMQWaitTime && _cur_vm_operation != NULL && 492 !_cur_vm_operation->evaluate_concurrently()) { 493 long stall = os::javaTimeMillis() - _cur_vm_operation->timestamp(); 494 if (stall > 0) 495 tty->print_cr("%s stall: %ld", _cur_vm_operation->name(), stall); 496 } 497 498 while (!should_terminate() && _cur_vm_operation == NULL) { 499 // wait with a timeout to guarantee safepoints at regular intervals 500 bool timedout = 501 mu_queue.wait(GuaranteedSafepointInterval); 502 503 // Support for self destruction 504 if ((SelfDestructTimer != 0) && !VMError::is_error_reported() && 505 (os::elapsedTime() > (double)SelfDestructTimer * 60.0)) { 506 tty->print_cr("VM self-destructed"); 507 exit(-1); 508 } 509 510 if (timedout) { 511 // Have to unlock VMOperationQueue_lock just in case no_op_safepoint() 512 // has to do a handshake. 513 MutexUnlocker mul(VMOperationQueue_lock, Mutex::_no_safepoint_check_flag); 514 if ((_cur_vm_operation = VMThread::no_op_safepoint()) != NULL) { 515 // Force a safepoint since we have not had one for at least 516 // 'GuaranteedSafepointInterval' milliseconds and we need to clean 517 // something. This will run all the clean-up processing that needs 518 // to be done at a safepoint. 519 SafepointSynchronize::begin(); 520 #ifdef ASSERT 521 if (GCALotAtAllSafepoints) InterfaceSupport::check_gc_alot(); 522 #endif 523 SafepointSynchronize::end(); 524 _cur_vm_operation = NULL; 525 } 526 } 527 _cur_vm_operation = _vm_queue->remove_next(); 528 529 // If we are at a safepoint we will evaluate all the operations that 530 // follow that also require a safepoint 531 if (_cur_vm_operation != NULL && 532 _cur_vm_operation->evaluate_at_safepoint()) { 533 safepoint_ops = _vm_queue->drain_at_safepoint_priority(); 534 } 535 } 536 537 if (should_terminate()) break; 538 } // Release mu_queue_lock 539 540 // 541 // Execute VM operation 542 // 543 { HandleMark hm(VMThread::vm_thread()); 544 545 EventMark em("Executing VM operation: %s", vm_operation()->name()); 546 assert(_cur_vm_operation != NULL, "we should have found an operation to execute"); 547 548 // If we are at a safepoint we will evaluate all the operations that 549 // follow that also require a safepoint 550 if (_cur_vm_operation->evaluate_at_safepoint()) { 551 log_debug(vmthread)("Evaluating safepoint VM operation: %s", _cur_vm_operation->name()); 552 553 _vm_queue->set_drain_list(safepoint_ops); // ensure ops can be scanned 554 555 SafepointSynchronize::begin(); 556 557 if (_timeout_task != NULL) { 558 _timeout_task->arm(); 559 } 560 561 evaluate_operation(_cur_vm_operation); 562 // now process all queued safepoint ops, iteratively draining 563 // the queue until there are none left 564 do { 565 _cur_vm_operation = safepoint_ops; 566 if (_cur_vm_operation != NULL) { 567 do { 568 log_debug(vmthread)("Evaluating coalesced safepoint VM operation: %s", _cur_vm_operation->name()); 569 // evaluate_operation deletes the op object so we have 570 // to grab the next op now 571 VM_Operation* next = _cur_vm_operation->next(); 572 _vm_queue->set_drain_list(next); 573 evaluate_operation(_cur_vm_operation); 574 _cur_vm_operation = next; 575 _coalesced_count++; 576 } while (_cur_vm_operation != NULL); 577 } 578 // There is a chance that a thread enqueued a safepoint op 579 // since we released the op-queue lock and initiated the safepoint. 580 // So we drain the queue again if there is anything there, as an 581 // optimization to try and reduce the number of safepoints. 582 // As the safepoint synchronizes us with JavaThreads we will see 583 // any enqueue made by a JavaThread, but the peek will not 584 // necessarily detect a concurrent enqueue by a GC thread, but 585 // that simply means the op will wait for the next major cycle of the 586 // VMThread - just as it would if the GC thread lost the race for 587 // the lock. 588 if (_vm_queue->peek_at_safepoint_priority()) { 589 // must hold lock while draining queue 590 MutexLocker mu_queue(VMOperationQueue_lock, 591 Mutex::_no_safepoint_check_flag); 592 safepoint_ops = _vm_queue->drain_at_safepoint_priority(); 593 } else { 594 safepoint_ops = NULL; 595 } 596 } while(safepoint_ops != NULL); 597 598 _vm_queue->set_drain_list(NULL); 599 600 if (_timeout_task != NULL) { 601 _timeout_task->disarm(); 602 } 603 604 // Complete safepoint synchronization 605 SafepointSynchronize::end(); 606 607 } else { // not a safepoint operation 608 log_debug(vmthread)("Evaluating non-safepoint VM operation: %s", _cur_vm_operation->name()); 609 if (TraceLongCompiles) { 610 elapsedTimer t; 611 t.start(); 612 evaluate_operation(_cur_vm_operation); 613 t.stop(); 614 double secs = t.seconds(); 615 if (secs * 1e3 > LongCompileThreshold) { 616 // XXX - _cur_vm_operation should not be accessed after 617 // the completed count has been incremented; the waiting 618 // thread may have already freed this memory. 619 tty->print_cr("vm %s: %3.7f secs]", _cur_vm_operation->name(), secs); 620 } 621 } else { 622 evaluate_operation(_cur_vm_operation); 623 } 624 625 _cur_vm_operation = NULL; 626 } 627 } 628 629 // 630 // Notify (potential) waiting Java thread(s) 631 { MutexLocker mu(VMOperationRequest_lock, Mutex::_no_safepoint_check_flag); 632 VMOperationRequest_lock->notify_all(); 633 } 634 635 // We want to make sure that we get to a safepoint regularly 636 // even when executing VMops that don't require safepoints. 637 if ((_cur_vm_operation = VMThread::no_op_safepoint()) != NULL) { 638 HandleMark hm(VMThread::vm_thread()); 639 SafepointSynchronize::begin(); 640 SafepointSynchronize::end(); 641 _cur_vm_operation = NULL; 642 } 643 } 644 } 645 646 // A SkipGCALot object is used to elide the usual effect of gc-a-lot 647 // over a section of execution by a thread. Currently, it's used only to 648 // prevent re-entrant calls to GC. 649 class SkipGCALot : public StackObj { 650 private: 651 bool _saved; 652 Thread* _t; 653 654 public: 655 #ifdef ASSERT 656 SkipGCALot(Thread* t) : _t(t) { 657 _saved = _t->skip_gcalot(); 658 _t->set_skip_gcalot(true); 659 } 660 661 ~SkipGCALot() { 662 assert(_t->skip_gcalot(), "Save-restore protocol invariant"); 663 _t->set_skip_gcalot(_saved); 664 } 665 #else 666 SkipGCALot(Thread* t) { } 667 ~SkipGCALot() { } 668 #endif 669 }; 670 671 void VMThread::execute(VM_Operation* op) { 672 Thread* t = Thread::current(); 673 674 if (!t->is_VM_thread()) { 675 SkipGCALot sgcalot(t); // avoid re-entrant attempts to gc-a-lot 676 // JavaThread or WatcherThread 677 bool concurrent = op->evaluate_concurrently(); 678 // only blocking VM operations need to verify the caller's safepoint state: 679 if (!concurrent) { 680 t->check_for_valid_safepoint_state(true); 681 } 682 683 // New request from Java thread, evaluate prologue 684 if (!op->doit_prologue()) { 685 return; // op was cancelled 686 } 687 688 // Setup VM_operations for execution 689 op->set_calling_thread(t); 690 691 // It does not make sense to execute the epilogue, if the VM operation object is getting 692 // deallocated by the VM thread. 693 bool execute_epilog = !op->is_cheap_allocated(); 694 assert(!concurrent || op->is_cheap_allocated(), "concurrent => cheap_allocated"); 695 696 // Get ticket number for non-concurrent VM operations 697 int ticket = 0; 698 if (!concurrent) { 699 ticket = t->vm_operation_ticket(); 700 } 701 702 // Add VM operation to list of waiting threads. We are guaranteed not to block while holding the 703 // VMOperationQueue_lock, so we can block without a safepoint check. This allows vm operation requests 704 // to be queued up during a safepoint synchronization. 705 { 706 VMOperationQueue_lock->lock_without_safepoint_check(); 707 log_debug(vmthread)("Adding VM operation: %s", op->name()); 708 _vm_queue->add(op); 709 op->set_timestamp(os::javaTimeMillis()); 710 VMOperationQueue_lock->notify(); 711 VMOperationQueue_lock->unlock(); 712 } 713 714 if (!concurrent) { 715 // Wait for completion of request (non-concurrent) 716 // Note: only a JavaThread triggers the safepoint check when locking 717 MonitorLocker ml(VMOperationRequest_lock, 718 t->is_Java_thread() ? Mutex::_safepoint_check_flag : Mutex::_no_safepoint_check_flag); 719 while(t->vm_operation_completed_count() < ticket) { 720 ml.wait(); 721 } 722 } 723 724 if (execute_epilog) { 725 op->doit_epilogue(); 726 } 727 } else { 728 // invoked by VM thread; usually nested VM operation 729 assert(t->is_VM_thread(), "must be a VM thread"); 730 VM_Operation* prev_vm_operation = vm_operation(); 731 if (prev_vm_operation != NULL) { 732 // Check the VM operation allows nested VM operation. This normally not the case, e.g., the compiler 733 // does not allow nested scavenges or compiles. 734 if (!prev_vm_operation->allow_nested_vm_operations()) { 735 fatal("Nested VM operation %s requested by operation %s", 736 op->name(), vm_operation()->name()); 737 } 738 op->set_calling_thread(prev_vm_operation->calling_thread()); 739 } 740 741 EventMark em("Executing %s VM operation: %s", prev_vm_operation ? "nested" : "", op->name()); 742 743 // Release all internal handles after operation is evaluated 744 HandleMark hm(t); 745 _cur_vm_operation = op; 746 747 if (op->evaluate_at_safepoint() && !SafepointSynchronize::is_at_safepoint()) { 748 SafepointSynchronize::begin(); 749 op->evaluate(); 750 SafepointSynchronize::end(); 751 } else { 752 op->evaluate(); 753 } 754 755 // Free memory if needed 756 if (op->is_cheap_allocated()) delete op; 757 758 _cur_vm_operation = prev_vm_operation; 759 } 760 } 761 762 763 void VMThread::oops_do(OopClosure* f, CodeBlobClosure* cf) { 764 Thread::oops_do(f, cf); 765 _vm_queue->oops_do(f); 766 } 767 768 //------------------------------------------------------------------------------------------------------------------ 769 #ifndef PRODUCT 770 771 void VMOperationQueue::verify_queue(int prio) { 772 // Check that list is correctly linked 773 int length = _queue_length[prio]; 774 VM_Operation *cur = _queue[prio]; 775 int i; 776 777 // Check forward links 778 for(i = 0; i < length; i++) { 779 cur = cur->next(); 780 assert(cur != _queue[prio], "list to short (forward)"); 781 } 782 assert(cur->next() == _queue[prio], "list to long (forward)"); 783 784 // Check backwards links 785 cur = _queue[prio]; 786 for(i = 0; i < length; i++) { 787 cur = cur->prev(); 788 assert(cur != _queue[prio], "list to short (backwards)"); 789 } 790 assert(cur->prev() == _queue[prio], "list to long (backwards)"); 791 } 792 793 #endif 794 795 void VMThread::verify() { 796 oops_do(&VerifyOopClosure::verify_oop, NULL); 797 }