1 /*
  2  * Copyright (c) 2003, 2021, 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 "memory/allocation.inline.hpp"
 27 #include "prims/jvmtiRawMonitor.hpp"
 28 #include "runtime/atomic.hpp"
 29 #include "runtime/interfaceSupport.inline.hpp"
 30 #include "runtime/orderAccess.hpp"
 31 #include "runtime/thread.inline.hpp"
 32 
 33 JvmtiRawMonitor::QNode::QNode(Thread* thread) : _next(NULL), _prev(NULL),
 34                                                 _event(thread->_ParkEvent),
 35                                                 _notified(0), _t_state(TS_RUN) {
 36 }
 37 
 38 GrowableArray<JvmtiRawMonitor*>* JvmtiPendingMonitors::_monitors =
 39   new (ResourceObj::C_HEAP, mtServiceability) GrowableArray<JvmtiRawMonitor*>(1, mtServiceability);
 40 
 41 void JvmtiPendingMonitors::transition_raw_monitors() {
 42   assert((Threads::number_of_threads()==1),
 43          "Java thread has not been created yet or more than one java thread "
 44          "is running. Raw monitor transition will not work");
 45   JavaThread* current_java_thread = JavaThread::current();
 46   {
 47     ThreadToNativeFromVM ttnfvm(current_java_thread);
 48     for (int i = 0; i < count(); i++) {
 49       JvmtiRawMonitor* rmonitor = monitors()->at(i);
 50       rmonitor->raw_enter(current_java_thread);
 51     }
 52   }
 53   // pending monitors are converted to real monitor so delete them all.
 54   dispose();
 55 }
 56 
 57 //
 58 // class JvmtiRawMonitor
 59 //
 60 
 61 JvmtiRawMonitor::JvmtiRawMonitor(const char* name) : _owner(NULL),
 62                                                      _recursions(0),
 63                                                      _entry_list(NULL),
 64                                                      _wait_set(NULL),
 65                                                      _magic(JVMTI_RM_MAGIC),
 66                                                      _name(NULL) {
 67 #ifdef ASSERT
 68   _name = strcpy(NEW_C_HEAP_ARRAY(char, strlen(name) + 1, mtInternal), name);
 69 #endif
 70 }
 71 
 72 JvmtiRawMonitor::~JvmtiRawMonitor() {
 73 #ifdef ASSERT
 74   FreeHeap(_name);
 75 #endif
 76   _magic = 0;
 77 }
 78 
 79 
 80 bool
 81 JvmtiRawMonitor::is_valid() {
 82   int value = 0;
 83 
 84   // This object might not be a JvmtiRawMonitor so we can't assume
 85   // the _magic field is properly aligned. Get the value in a safe
 86   // way and then check against JVMTI_RM_MAGIC.
 87 
 88   switch (sizeof(_magic)) {
 89   case 2:
 90     value = Bytes::get_native_u2((address)&_magic);
 91     break;
 92 
 93   case 4:
 94     value = Bytes::get_native_u4((address)&_magic);
 95     break;
 96 
 97   case 8:
 98     value = Bytes::get_native_u8((address)&_magic);
 99     break;
100 
101   default:
102     guarantee(false, "_magic field is an unexpected size");
103   }
104 
105   return value == JVMTI_RM_MAGIC;
106 }
107 
108 // -------------------------------------------------------------------------
109 // The JVMTI raw monitor subsystem is entirely distinct from normal
110 // java-synchronization or jni-synchronization.  JVMTI raw monitors are not
111 // associated with objects.  They can be implemented in any manner
112 // that makes sense.  The original implementors decided to piggy-back
113 // the raw-monitor implementation on the existing Java ObjectMonitor mechanism.
114 // Now we just use a simplified form of that ObjectMonitor code.
115 //
116 // Note that we use the single RawMonitor_lock to protect queue operations for
117 // _all_ raw monitors.  This is a scalability impediment, but since raw monitor usage
118 // is fairly rare, this is not of concern.  The RawMonitor_lock can not
119 // be held indefinitely.  The critical sections must be short and bounded.
120 //
121 // -------------------------------------------------------------------------
122 
123 void JvmtiRawMonitor::simple_enter(Thread* self) {
124   for (;;) {
125     if (Atomic::replace_if_null(&_owner, self)) {
126       if (self->is_Java_thread()) {
127         Continuation::pin(JavaThread::cast(self));
128       }
129       return;
130     }
131 
132     QNode node(self);
133     self->_ParkEvent->reset();     // strictly optional
134     node._t_state = QNode::TS_ENTER;
135 
136     RawMonitor_lock->lock_without_safepoint_check();
137     node._next = _entry_list;
138     _entry_list = &node;
139     OrderAccess::fence();
140     if (_owner == NULL && Atomic::replace_if_null(&_owner, self)) {
141       _entry_list = node._next;
142       RawMonitor_lock->unlock();
143       if (self->is_Java_thread()) {
144         Continuation::pin(JavaThread::cast(self));
145       }
146       return;
147     }
148     RawMonitor_lock->unlock();
149     while (node._t_state == QNode::TS_ENTER) {
150       self->_ParkEvent->park();
151     }
152   }
153 }
154 
155 void JvmtiRawMonitor::simple_exit(Thread* self) {
156   guarantee(_owner == self, "invariant");
157   Atomic::release_store(&_owner, (Thread*)NULL);
158   OrderAccess::fence();
159   if (self->is_Java_thread()) {
160     Continuation::unpin(JavaThread::cast(self));
161   }
162   if (_entry_list == NULL) {
163     return;
164   }
165 
166   RawMonitor_lock->lock_without_safepoint_check();
167   QNode* w = _entry_list;
168   if (w != NULL) {
169     _entry_list = w->_next;
170   }
171   RawMonitor_lock->unlock();
172   if (w != NULL) {
173     guarantee(w ->_t_state == QNode::TS_ENTER, "invariant");
174     // Once we set _t_state to TS_RUN the waiting thread can complete
175     // simple_enter and 'w' is pointing into random stack space. So we have
176     // to ensure we extract the ParkEvent (which is in type-stable memory)
177     // before we set the state, and then don't access 'w'.
178     ParkEvent* ev = w->_event;
179     OrderAccess::loadstore();
180     w->_t_state = QNode::TS_RUN;
181     OrderAccess::fence();
182     ev->unpark();
183   }
184   return;
185 }
186 
187 inline void JvmtiRawMonitor::enqueue_waiter(QNode& node) {
188   node._notified = 0;
189   node._t_state = QNode::TS_WAIT;
190   RawMonitor_lock->lock_without_safepoint_check();
191   node._next = _wait_set;
192   _wait_set = &node;
193   RawMonitor_lock->unlock();
194 }
195 
196 inline void JvmtiRawMonitor::dequeue_waiter(QNode& node) {
197   // If thread still resides on the waitset then unlink it.
198   // Double-checked locking -- the usage is safe in this context
199   // as _t_state is volatile and the lock-unlock operators are
200   // serializing (barrier-equivalent).
201 
202   if (node._t_state == QNode::TS_WAIT) {
203     RawMonitor_lock->lock_without_safepoint_check();
204     if (node._t_state == QNode::TS_WAIT) {
205       // Simple O(n) unlink, but performance isn't critical here.
206       QNode* p;
207       QNode* q = NULL;
208       for (p = _wait_set; p != &node; p = p->_next) {
209         q = p;
210       }
211       guarantee(p == &node, "invariant");
212       if (q == NULL) {
213         guarantee (p == _wait_set, "invariant");
214         _wait_set = p->_next;
215       } else {
216         guarantee(p == q->_next, "invariant");
217         q->_next = p->_next;
218       }
219       node._t_state = QNode::TS_RUN;
220     }
221     RawMonitor_lock->unlock();
222   }
223 
224   guarantee(node._t_state == QNode::TS_RUN, "invariant");
225 }
226 
227 // simple_wait is not quite so simple as we have to deal with the interaction
228 // with the Thread interrupt state, which resides in the java.lang.Thread object.
229 // That state must only be accessed while _thread_in_vm and requires proper thread-state
230 // transitions.
231 // Returns M_OK usually, but M_INTERRUPTED if the thread is a JavaThread and was
232 // interrupted.
233 // Note:
234 //  - simple_wait never reenters the monitor.
235 //  - A JavaThread must be in native.
236 int JvmtiRawMonitor::simple_wait(Thread* self, jlong millis) {
237   guarantee(_owner == self  , "invariant");
238   guarantee(_recursions == 0, "invariant");
239 
240   QNode node(self);
241   enqueue_waiter(node);
242 
243   simple_exit(self);
244   guarantee(_owner != self, "invariant");
245 
246   int ret = M_OK;
247   if (self->is_Java_thread()) {
248     JavaThread* jt = JavaThread::cast(self);
249     guarantee(jt->thread_state() == _thread_in_native, "invariant");
250     {
251       // This transition must be after we exited the monitor.
252       ThreadInVMfromNative tivmfn(jt);
253       if (jt->is_interrupted(true)) {
254         ret = M_INTERRUPTED;
255       } else {
256         ThreadBlockInVM tbivm(jt);
257         if (millis <= 0) {
258           self->_ParkEvent->park();
259         } else {
260           self->_ParkEvent->park(millis);
261         }
262         // Return to VM before post-check of interrupt state
263       }
264       if (jt->is_interrupted(true)) {
265         ret = M_INTERRUPTED;
266       }
267     }
268   } else {
269     if (millis <= 0) {
270       self->_ParkEvent->park();
271     } else {
272       self->_ParkEvent->park(millis);
273     }
274   }
275 
276   dequeue_waiter(node);
277 
278   return ret;
279 }
280 
281 void JvmtiRawMonitor::simple_notify(Thread* self, bool all) {
282   guarantee(_owner == self, "invariant");
283   if (_wait_set == NULL) {
284     return;
285   }
286 
287   // We have two options:
288   // A. Transfer the threads from the _wait_set to the _entry_list
289   // B. Remove the thread from the _wait_set and unpark() it.
290   //
291   // We use (B), which is crude and results in lots of futile
292   // context switching.  In particular (B) induces lots of contention.
293 
294   ParkEvent* ev = NULL;       // consider using a small auto array ...
295   RawMonitor_lock->lock_without_safepoint_check();
296   for (;;) {
297     QNode* w = _wait_set;
298     if (w == NULL) break;
299     _wait_set = w->_next;
300     if (ev != NULL) {
301       ev->unpark();
302       ev = NULL;
303     }
304     ev = w->_event;
305     OrderAccess::loadstore();
306     w->_t_state = QNode::TS_RUN;
307     OrderAccess::storeload();
308     if (!all) {
309       break;
310     }
311   }
312   RawMonitor_lock->unlock();
313   if (ev != NULL) {
314     ev->unpark();
315   }
316   return;
317 }
318 
319 void JvmtiRawMonitor::ExitOnSuspend::operator()(JavaThread* current) {
320   // We must exit the monitor in case of a safepoint.
321   _rm->simple_exit(current);
322   _rm_exited = true;
323 }
324 
325 // JavaThreads will enter here with state _thread_in_native.
326 void JvmtiRawMonitor::raw_enter(Thread* self) {
327   // TODO Atomic::load on _owner field
328   if (_owner == self) {
329     _recursions++;
330     return;
331   }
332 
333   self->set_current_pending_raw_monitor(this);
334 
335   if (!self->is_Java_thread()) {
336     simple_enter(self);
337   } else {
338     JavaThread* jt = JavaThread::cast(self);
339     guarantee(jt->thread_state() == _thread_in_native, "invariant");
340     ThreadInVMfromNative tivmfn(jt);
341     for (;;) {
342       ExitOnSuspend eos(this);
343       {
344         ThreadBlockInVMPreprocess<ExitOnSuspend> tbivmp(jt, eos, true /* allow_suspend */);
345         simple_enter(jt);
346       }
347       if (!eos.monitor_exited()) {
348         break;
349       }
350     }
351   }
352 
353   self->set_current_pending_raw_monitor(NULL);
354 
355   guarantee(_owner == self, "invariant");
356   guarantee(_recursions == 0, "invariant");
357 }
358 
359 int JvmtiRawMonitor::raw_exit(Thread* self) {
360   if (self != _owner) {
361     return M_ILLEGAL_MONITOR_STATE;
362   }
363   if (_recursions > 0) {
364     _recursions--;
365   } else {
366     simple_exit(self);
367   }
368 
369   return M_OK;
370 }
371 
372 int JvmtiRawMonitor::raw_wait(jlong millis, Thread* self) {
373   if (self != _owner) {
374     return M_ILLEGAL_MONITOR_STATE;
375   }
376 
377   int ret = M_OK;
378 
379   // To avoid spurious wakeups we reset the parkevent. This is strictly optional.
380   // The caller must be able to tolerate spurious returns from raw_wait().
381   self->_ParkEvent->reset();
382   OrderAccess::fence();
383 
384   intptr_t save = _recursions;
385   _recursions = 0;
386   ret = simple_wait(self, millis);
387 
388   // Now we need to re-enter the monitor. For JavaThreads
389   // we need to manage suspend requests.
390   if (self->is_Java_thread()) { // JavaThread re-enter
391     JavaThread* jt = JavaThread::cast(self);
392     ThreadInVMfromNative tivmfn(jt);
393     for (;;) {
394       ExitOnSuspend eos(this);
395       {
396         ThreadBlockInVMPreprocess<ExitOnSuspend> tbivmp(jt, eos, true /* allow_suspend */);
397         simple_enter(jt);
398       }
399       if (!eos.monitor_exited()) {
400         break;
401       }
402     }
403     if (jt->is_interrupted(true)) {
404       ret = M_INTERRUPTED;
405     }
406   } else { // Non-JavaThread re-enter
407     assert(ret != M_INTERRUPTED, "Only JavaThreads can be interrupted");
408     simple_enter(self);
409   }
410 
411   _recursions = save;
412 
413   guarantee(self == _owner, "invariant");
414   return ret;
415 }
416 
417 int JvmtiRawMonitor::raw_notify(Thread* self) {
418   if (self != _owner) {
419     return M_ILLEGAL_MONITOR_STATE;
420   }
421   simple_notify(self, false);
422   return M_OK;
423 }
424 
425 int JvmtiRawMonitor::raw_notifyAll(Thread* self) {
426   if (self != _owner) {
427     return M_ILLEGAL_MONITOR_STATE;
428   }
429   simple_notify(self, true);
430   return M_OK;
431 }