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