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