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