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