1 /*
   2  * Copyright (c) 2003, 2016, 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 "prims/jvmtiRawMonitor.hpp"
  27 #include "runtime/atomic.hpp"
  28 #include "runtime/interfaceSupport.hpp"
  29 #include "runtime/orderAccess.inline.hpp"
  30 #include "runtime/thread.inline.hpp"
  31 
  32 GrowableArray<JvmtiRawMonitor*> *JvmtiPendingMonitors::_monitors = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<JvmtiRawMonitor*>(1,true);
  33 
  34 void JvmtiPendingMonitors::transition_raw_monitors() {
  35   assert((Threads::number_of_threads()==1),
  36          "Java thread has not created yet or more than one java thread \
  37 is running. Raw monitor transition will not work");
  38   JavaThread *current_java_thread = JavaThread::current();
  39   assert(current_java_thread->thread_state() == _thread_in_vm, "Must be in vm");
  40   {
  41     ThreadBlockInVM __tbivm(current_java_thread);
  42     for(int i=0; i< count(); i++) {
  43       JvmtiRawMonitor *rmonitor = monitors()->at(i);
  44       int r = rmonitor->raw_enter(current_java_thread);
  45       assert(r == ObjectMonitor::OM_OK, "raw_enter should have worked");
  46     }
  47   }
  48   // pending monitors are converted to real monitor so delete them all.
  49   dispose();
  50 }
  51 
  52 //
  53 // class JvmtiRawMonitor
  54 //
  55 
  56 JvmtiRawMonitor::JvmtiRawMonitor(const char *name) {
  57 #ifdef ASSERT
  58   _name = strcpy(NEW_C_HEAP_ARRAY(char, strlen(name) + 1, mtInternal), name);
  59 #else
  60   _name = NULL;
  61 #endif
  62   _magic = JVMTI_RM_MAGIC;
  63 }
  64 
  65 JvmtiRawMonitor::~JvmtiRawMonitor() {
  66 #ifdef ASSERT
  67   FreeHeap(_name);
  68 #endif
  69   _magic = 0;
  70 }
  71 
  72 
  73 bool
  74 JvmtiRawMonitor::is_valid() {
  75   int value = 0;
  76 
  77   // This object might not be a JvmtiRawMonitor so we can't assume
  78   // the _magic field is properly aligned. Get the value in a safe
  79   // way and then check against JVMTI_RM_MAGIC.
  80 
  81   switch (sizeof(_magic)) {
  82   case 2:
  83     value = Bytes::get_native_u2((address)&_magic);
  84     break;
  85 
  86   case 4:
  87     value = Bytes::get_native_u4((address)&_magic);
  88     break;
  89 
  90   case 8:
  91     value = Bytes::get_native_u8((address)&_magic);
  92     break;
  93 
  94   default:
  95     guarantee(false, "_magic field is an unexpected size");
  96   }
  97 
  98   return value == JVMTI_RM_MAGIC;
  99 }
 100 
 101 // -------------------------------------------------------------------------
 102 // The raw monitor subsystem is entirely distinct from normal
 103 // java-synchronization or jni-synchronization.  raw monitors are not
 104 // associated with objects.  They can be implemented in any manner
 105 // that makes sense.  The original implementors decided to piggy-back
 106 // the raw-monitor implementation on the existing Java objectMonitor mechanism.
 107 // This flaw needs to fixed.  We should reimplement raw monitors as sui-generis.
 108 // Specifically, we should not implement raw monitors via java monitors.
 109 // Time permitting, we should disentangle and deconvolve the two implementations
 110 // and move the resulting raw monitor implementation over to the JVMTI directories.
 111 // Ideally, the raw monitor implementation would be built on top of
 112 // park-unpark and nothing else.
 113 //
 114 // raw monitors are used mainly by JVMTI
 115 // The raw monitor implementation borrows the ObjectMonitor structure,
 116 // but the operators are degenerate and extremely simple.
 117 //
 118 // Mixed use of a single objectMonitor instance -- as both a raw monitor
 119 // and a normal java monitor -- is not permissible.
 120 //
 121 // Note that we use the single RawMonitor_lock to protect queue operations for
 122 // _all_ raw monitors.  This is a scalability impediment, but since raw monitor usage
 123 // is deprecated and rare, this is not of concern.  The RawMonitor_lock can not
 124 // be held indefinitely.  The critical sections must be short and bounded.
 125 //
 126 // -------------------------------------------------------------------------
 127 
 128 int JvmtiRawMonitor::SimpleEnter (Thread * Self) {
 129   for (;;) {
 130     if (Atomic::cmpxchg(Self, &_owner, (void*)NULL) == NULL) {
 131        return OS_OK ;
 132     }
 133 
 134     ObjectWaiter Node (Self) ;
 135     Self->_ParkEvent->reset() ;     // strictly optional
 136     Node.TState = ObjectWaiter::TS_ENTER ;
 137 
 138     RawMonitor_lock->lock_without_safepoint_check() ;
 139     Node._next  = _EntryList ;
 140     _EntryList  = &Node ;
 141     OrderAccess::fence() ;
 142     if (_owner == NULL && Atomic::cmpxchg(Self, &_owner, (void*)NULL) == NULL) {
 143         _EntryList = Node._next ;
 144         RawMonitor_lock->unlock() ;
 145         return OS_OK ;
 146     }
 147     RawMonitor_lock->unlock() ;
 148     while (Node.TState == ObjectWaiter::TS_ENTER) {
 149        Self->_ParkEvent->park() ;
 150     }
 151   }
 152 }
 153 
 154 int JvmtiRawMonitor::SimpleExit (Thread * Self) {
 155   guarantee (_owner == Self, "invariant") ;
 156   OrderAccess::release_store(&_owner, (void*)NULL) ;
 157   OrderAccess::fence() ;
 158   if (_EntryList == NULL) return OS_OK ;
 159   ObjectWaiter * w ;
 160 
 161   RawMonitor_lock->lock_without_safepoint_check() ;
 162   w = _EntryList ;
 163   if (w != NULL) {
 164       _EntryList = w->_next ;
 165   }
 166   RawMonitor_lock->unlock() ;
 167   if (w != NULL) {
 168       guarantee (w ->TState == ObjectWaiter::TS_ENTER, "invariant") ;
 169       ParkEvent * ev = w->_event ;
 170       w->TState = ObjectWaiter::TS_RUN ;
 171       OrderAccess::fence() ;
 172       ev->unpark() ;
 173   }
 174   return OS_OK ;
 175 }
 176 
 177 int JvmtiRawMonitor::SimpleWait (Thread * Self, jlong millis) {
 178   guarantee (_owner == Self  , "invariant") ;
 179   guarantee (_recursions == 0, "invariant") ;
 180 
 181   ObjectWaiter Node (Self) ;
 182   Node._notified = 0 ;
 183   Node.TState    = ObjectWaiter::TS_WAIT ;
 184 
 185   RawMonitor_lock->lock_without_safepoint_check() ;
 186   Node._next     = _WaitSet ;
 187   _WaitSet       = &Node ;
 188   RawMonitor_lock->unlock() ;
 189 
 190   SimpleExit (Self) ;
 191   guarantee (_owner != Self, "invariant") ;
 192 
 193   int ret = OS_OK ;
 194   if (millis <= 0) {
 195     Self->_ParkEvent->park();
 196   } else {
 197     ret = Self->_ParkEvent->park(millis);
 198   }
 199 
 200   // If thread still resides on the waitset then unlink it.
 201   // Double-checked locking -- the usage is safe in this context
 202   // as we TState is volatile and the lock-unlock operators are
 203   // serializing (barrier-equivalent).
 204 
 205   if (Node.TState == ObjectWaiter::TS_WAIT) {
 206     RawMonitor_lock->lock_without_safepoint_check() ;
 207     if (Node.TState == ObjectWaiter::TS_WAIT) {
 208       // Simple O(n) unlink, but performance isn't critical here.
 209       ObjectWaiter * p ;
 210       ObjectWaiter * q = NULL ;
 211       for (p = _WaitSet ; p != &Node; p = p->_next) {
 212          q = p ;
 213       }
 214       guarantee (p == &Node, "invariant") ;
 215       if (q == NULL) {
 216         guarantee (p == _WaitSet, "invariant") ;
 217         _WaitSet = p->_next ;
 218       } else {
 219         guarantee (p == q->_next, "invariant") ;
 220         q->_next = p->_next ;
 221       }
 222       Node.TState = ObjectWaiter::TS_RUN ;
 223     }
 224     RawMonitor_lock->unlock() ;
 225   }
 226 
 227   guarantee (Node.TState == ObjectWaiter::TS_RUN, "invariant") ;
 228   SimpleEnter (Self) ;
 229 
 230   guarantee (_owner == Self, "invariant") ;
 231   guarantee (_recursions == 0, "invariant") ;
 232   return ret ;
 233 }
 234 
 235 int JvmtiRawMonitor::SimpleNotify (Thread * Self, bool All) {
 236   guarantee (_owner == Self, "invariant") ;
 237   if (_WaitSet == NULL) return OS_OK ;
 238 
 239   // We have two options:
 240   // A. Transfer the threads from the WaitSet to the EntryList
 241   // B. Remove the thread from the WaitSet and unpark() it.
 242   //
 243   // We use (B), which is crude and results in lots of futile
 244   // context switching.  In particular (B) induces lots of contention.
 245 
 246   ParkEvent * ev = NULL ;       // consider using a small auto array ...
 247   RawMonitor_lock->lock_without_safepoint_check() ;
 248   for (;;) {
 249       ObjectWaiter * w = _WaitSet ;
 250       if (w == NULL) break ;
 251       _WaitSet = w->_next ;
 252       if (ev != NULL) { ev->unpark(); ev = NULL; }
 253       ev = w->_event ;
 254       OrderAccess::loadstore() ;
 255       w->TState = ObjectWaiter::TS_RUN ;
 256       OrderAccess::storeload();
 257       if (!All) break ;
 258   }
 259   RawMonitor_lock->unlock() ;
 260   if (ev != NULL) ev->unpark();
 261   return OS_OK ;
 262 }
 263 
 264 // Any JavaThread will enter here with state _thread_blocked
 265 int JvmtiRawMonitor::raw_enter(TRAPS) {
 266   TEVENT (raw_enter) ;
 267   void * Contended ;
 268 
 269   // don't enter raw monitor if thread is being externally suspended, it will
 270   // surprise the suspender if a "suspended" thread can still enter monitor
 271   JavaThread * jt = (JavaThread *)THREAD;
 272   if (THREAD->is_Java_thread()) {
 273     jt->SR_lock()->lock_without_safepoint_check();
 274     while (jt->is_external_suspend()) {
 275       jt->SR_lock()->unlock();
 276       jt->java_suspend_self();
 277       jt->SR_lock()->lock_without_safepoint_check();
 278     }
 279     // guarded by SR_lock to avoid racing with new external suspend requests.
 280     Contended = Atomic::cmpxchg(THREAD, &_owner, (void*)NULL);
 281     jt->SR_lock()->unlock();
 282   } else {
 283     Contended = Atomic::cmpxchg(THREAD, &_owner, (void*)NULL);
 284   }
 285 
 286   if (Contended == THREAD) {
 287      _recursions ++ ;
 288      return OM_OK ;
 289   }
 290 
 291   if (Contended == NULL) {
 292      guarantee (_owner == THREAD, "invariant") ;
 293      guarantee (_recursions == 0, "invariant") ;
 294      return OM_OK ;
 295   }
 296 
 297   THREAD->set_current_pending_monitor(this);
 298 
 299   if (!THREAD->is_Java_thread()) {
 300      // No other non-Java threads besides VM thread would acquire
 301      // a raw monitor.
 302      assert(THREAD->is_VM_thread(), "must be VM thread");
 303      SimpleEnter (THREAD) ;
 304    } else {
 305      guarantee (jt->thread_state() == _thread_blocked, "invariant") ;
 306      for (;;) {
 307        jt->set_suspend_equivalent();
 308        // cleared by handle_special_suspend_equivalent_condition() or
 309        // java_suspend_self()
 310        SimpleEnter (THREAD) ;
 311 
 312        // were we externally suspended while we were waiting?
 313        if (!jt->handle_special_suspend_equivalent_condition()) break ;
 314 
 315        // This thread was externally suspended
 316        //
 317        // This logic isn't needed for JVMTI raw monitors,
 318        // but doesn't hurt just in case the suspend rules change. This
 319            // logic is needed for the JvmtiRawMonitor.wait() reentry phase.
 320            // We have reentered the contended monitor, but while we were
 321            // waiting another thread suspended us. We don't want to reenter
 322            // the monitor while suspended because that would surprise the
 323            // thread that suspended us.
 324            //
 325            // Drop the lock -
 326        SimpleExit (THREAD) ;
 327 
 328            jt->java_suspend_self();
 329          }
 330 
 331      assert(_owner == THREAD, "Fatal error with monitor owner!");
 332      assert(_recursions == 0, "Fatal error with monitor recursions!");
 333   }
 334 
 335   THREAD->set_current_pending_monitor(NULL);
 336   guarantee (_recursions == 0, "invariant") ;
 337   return OM_OK;
 338 }
 339 
 340 // Used mainly for JVMTI raw monitor implementation
 341 // Also used for JvmtiRawMonitor::wait().
 342 int JvmtiRawMonitor::raw_exit(TRAPS) {
 343   TEVENT (raw_exit) ;
 344   if (THREAD != _owner) {
 345     return OM_ILLEGAL_MONITOR_STATE;
 346   }
 347   if (_recursions > 0) {
 348     --_recursions ;
 349     return OM_OK ;
 350   }
 351 
 352   void * List = _EntryList ;
 353   SimpleExit (THREAD) ;
 354 
 355   return OM_OK;
 356 }
 357 
 358 // Used for JVMTI raw monitor implementation.
 359 // All JavaThreads will enter here with state _thread_blocked
 360 
 361 int JvmtiRawMonitor::raw_wait(jlong millis, bool interruptible, TRAPS) {
 362   TEVENT (raw_wait) ;
 363   if (THREAD != _owner) {
 364     return OM_ILLEGAL_MONITOR_STATE;
 365   }
 366 
 367   // To avoid spurious wakeups we reset the parkevent -- This is strictly optional.
 368   // The caller must be able to tolerate spurious returns from raw_wait().
 369   THREAD->_ParkEvent->reset() ;
 370   OrderAccess::fence() ;
 371 
 372   // check interrupt event
 373   if (interruptible && Thread::is_interrupted(THREAD, true)) {
 374     return OM_INTERRUPTED;
 375   }
 376 
 377   intptr_t save = _recursions ;
 378   _recursions = 0 ;
 379   _waiters ++ ;
 380   if (THREAD->is_Java_thread()) {
 381     guarantee (((JavaThread *) THREAD)->thread_state() == _thread_blocked, "invariant") ;
 382     ((JavaThread *)THREAD)->set_suspend_equivalent();
 383   }
 384   int rv = SimpleWait (THREAD, millis) ;
 385   _recursions = save ;
 386   _waiters -- ;
 387 
 388   guarantee (THREAD == _owner, "invariant") ;
 389   if (THREAD->is_Java_thread()) {
 390      JavaThread * jSelf = (JavaThread *) THREAD ;
 391      for (;;) {
 392         if (!jSelf->handle_special_suspend_equivalent_condition()) break ;
 393         SimpleExit (THREAD) ;
 394         jSelf->java_suspend_self();
 395         SimpleEnter (THREAD) ;
 396         jSelf->set_suspend_equivalent() ;
 397      }
 398   }
 399   guarantee (THREAD == _owner, "invariant") ;
 400 
 401   if (interruptible && Thread::is_interrupted(THREAD, true)) {
 402     return OM_INTERRUPTED;
 403   }
 404   return OM_OK ;
 405 }
 406 
 407 int JvmtiRawMonitor::raw_notify(TRAPS) {
 408   TEVENT (raw_notify) ;
 409   if (THREAD != _owner) {
 410     return OM_ILLEGAL_MONITOR_STATE;
 411   }
 412   SimpleNotify (THREAD, false) ;
 413   return OM_OK;
 414 }
 415 
 416 int JvmtiRawMonitor::raw_notifyAll(TRAPS) {
 417   TEVENT (raw_notifyAll) ;
 418   if (THREAD != _owner) {
 419     return OM_ILLEGAL_MONITOR_STATE;
 420   }
 421   SimpleNotify (THREAD, true) ;
 422   return OM_OK;
 423 }
 424